From andreas.lobinger at netsurf.de Thu Jul 14 08:16:22 2005 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Thu, 14 Jul 2005 14:16:22 +0200 Subject: Frankenstring In-Reply-To: References: Message-ID: Aloha, Thomas Lotze wrote: >>A string, and a pointer on that string. If you give up the boundary >>condition to tell backwards, you can start to eat up the string via f = >>f[p:]. There was a performance difference with that, in fact it was faster >>~4% on a python2.2. > When I tried it just now, it was the other way around. Eating up the > string was slower, which makes sense to me since it involves creating new > string objects all the time. I expected the f[p:] also to be slower, the 4% i only measured on one platform. Most propably the CG and memory management isn't the same. >>I dont't expect any iterator solution to be faster than that. > It's not so much an issue of iterators, but handling Python objects > for every char. Iterators would actually be quite helpful for searching: I > wonder why there doesn't seem to be an str.iterfind or str.itersplit > thing. And I wonder whether there shouldn't be str.findany and > str.iterfindany, which takes a sequence as an argument and returns the > next match on any element of it. There is a finditer in the re. I'm currently rewriting a few pattern matching things and find it quite valueable. >>> import re >>> pat = re.compile('[57]') >>> f = "754356184756046104564" >>> for a in pat.finditer(f): ... print a.start(),f[a.start()] ... 0 7 1 5 4 5 9 7 10 5 18 5 Wishing a happy day LOBI From simon.brunning at gmail.com Mon Jul 4 07:56:58 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Jul 2005 12:56:58 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file In-Reply-To: References: Message-ID: <8c7f10c6050704045673484357@mail.gmail.com> On 7/4/05, Guy Lateur wrote: > I've been writing some code to move some data into and out of Outlook (2003 > + Exchange 2003). I have some email .msg files on our file server, and I > can't seem to get them back into the Outlook object I need, ie a MailItem. > I've tried to use App.CopyFile() to (temporarily) put the file in an OL > folder. Problem is, however, this returns a DocumentItem and not a MailItem. > > Is there any way I could 'cast' this DItem into a MItem? Apparently, OL > treats it as any general document - which, btw, shows in the view, too; it > has another icon and you have to open it to view it). Or maybe there's > another way to open it; I really only need the object in memory. Any ideas? Well, I don't know anything about Outlook's COM interface, so I don't know if this will work, but you might try win32com.client.CastTo(). Something like: my_MItem = win32com.client.CastTo(my_DItem, 'MItem') -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From http Fri Jul 29 05:08:37 2005 From: http (Paul Rubin) Date: 29 Jul 2005 02:08:37 -0700 Subject: Advanced concurrancy References: Message-ID: <7xk6jagesq.fsf@ruckus.brouhaha.com> Peter Tillotson writes: > I have come across twisted and used in async code. What i'm really > looking for is something that provides concurrency based on CSP or pi > calculus. Or something that looks much more like Java's JSR 166 which > is now integrated in Tiger. Python doesn't have anything that fancy. You could look at: pyro.sf.net - Python remote objects using sockets poshmodule.sf.net - objects shared between processes using shared memory Queue module - synchronized queues for interthread communications in one process It would be nice if there were something like Queue that used MPI. Underneath there could be either sockets, shared memory, some special multiprocessor interconnect, or whatever. From luismgz at gmail.com Wed Jul 6 16:40:07 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 6 Jul 2005 13:40:07 -0700 Subject: I am a Java Programmer In-Reply-To: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> Message-ID: <1120682407.485534.318380@g43g2000cwa.googlegroups.com> I'm sorry for you, nobody deserves to program in Java ... I'm glad you decided to stand up for your human rights. Go learn python! From rebound1618 at yahoo.com Wed Jul 27 16:12:58 2005 From: rebound1618 at yahoo.com (Jerry He) Date: Wed, 27 Jul 2005 13:12:58 -0700 (PDT) Subject: Why Tcl/Tk? Message-ID: <20050727201258.25065.qmail@web51508.mail.yahoo.com> I'm a little curious, why does most scripting languges(i.e. python and ruby) use Tcl/Tk rather than wx or Fox as its standard GUI? Although I did notice that the Vpython IDE that uses Tkinker starts up a lot faster than the DrPython IDE that uses wxpython. But that makes no sense, Tk is based on Tcl, a scripting language, but wx is written in C++. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bronger at physik.rwth-aachen.de Sat Jul 30 10:35:09 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 30 Jul 2005 16:35:09 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: <871x5gs6oy.fsf@wilson.rwth-aachen.de> Hall?chen! Peter Decker writes: > On 7/30/05, Torsten Bronger wrote: > >> I've been having a closer look at wxPython which is not Pythonic >> at all and bad documented. Probably I'll use it nevertheless. >> PyGTK and PyQt may have their own advantages and disadvantages. >> >> However, in my opinion we don't need yet another binding so thin >> that C or C++ is shining through, but a modern replacement for >> Tkinter with its Pythonic way of thinking. > > I had the exact same impression when I started working with > wxPython: [...] I then discovered Dabo (http://dabodev.com), which > is a full application framework, but whose UI layer is a very > Pythonic wrapper around wxPython. I've created several apps now > using Dabo, even though I haven't even looked at the data > connectivity aspects of it; the UI code works fine without it. I'm aware of it (and there is Wax and maybe a third one). Actually it illustrates my point quite well: These projects are small and instable (Dabo has a developer basis of very few people, Wax has only one); they are even worse documented; they add another layer which slows down and requires the end-user to install another package; they force you to test even more GUI approaches. ==> They contribute heavily to Dark Cowherd's observation that "it is shambles". Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From phillip.watts at anvilcom.com Tue Jul 5 11:03:48 2005 From: phillip.watts at anvilcom.com (phil) Date: Tue, 05 Jul 2005 10:03:48 -0500 Subject: More On - deepcopy, Tkinter References: <42C9B738.7010604@anvilcom.com> Message-ID: <42CAA154.2080509@anvilcom.com> > The deepcopy protocol does allow you to specify how complicated objects > should be copied. Try defining __deepcopy__() in your objects to just copy > the reference to the Canvas object instead of the object itself. I can't figure out from the docs what __deepcopy__ is or how it works. I have about 25 classes of drawn objects. for instance class linefromslope creates an instance of class line. One of my "ugly solutions" involves a class prop: within each class, put properties like slope and midpoint within the self.prop instance and making a copy of that. Would __deepcopy__ facilitate this? Or am I assuming too much: is __deepcopy__ just a method I invent to do what I want? From kraus at hagen-partner.de Tue Jul 12 02:50:33 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue, 12 Jul 2005 08:50:33 +0200 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' In-Reply-To: References: Message-ID: Ric Da Force wrote: > Hi, > > I have a string such as 'C1, C2, C3'. Without assuming that each bit of > text is of fixed size, what is the easiest way to change this list so that > it reads: > 'C1, C2 and C3' regardless of the length of the string. > > Regards and sorry for the newbie question, > > Ric > > Use rfind and slicing: >>> x = "C1, C2, C3" >>> x[:x.rfind(',')]+' and'+x[x.rfind(',')+1:] 'C1, C2 and C3' HTH, Wolfram From programmer.py at gmail.com Tue Jul 19 15:24:57 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 19 Jul 2005 14:24:57 -0500 Subject: socket programming In-Reply-To: <20050719184205.GA24773@mail.smule.com> References: <20050719184205.GA24773@mail.smule.com> Message-ID: It sounds really strange to connect to a server "several hundred" times. If I had to guess, the server monitored all of the connects coming from your IP address and eventually stopped accepting ANY connections. jw On 7/19/05, Helge Aksdal wrote: > i've recently made my very first socket program in python, > however i've stumbled upon a problem. > > this program connects to a server serveral hundred time while it's > executed (it's not possible to let connection stay up, because the > server closes it), and after a time my program dies with the error: > "socket.error: (134, 'Transport endpoint is not connected')" > > if i then change to a console window, and telnet to this server it > sends me to another one. That's probably why my program dies, how > can i get my code to handle this? > > Trying xxx.xxx.xxx.xxx > telnet: connect to address xxx.xxx.xxx.xxx: Connection refused > Trying xxx.xxx.xxx.xxx > Connected to xxxxxx.xxxxx. > Escape character is '^]'. > > here is my current connection code: > > def connect(self, server, port): > self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.sock.setblocking(0) > self.sock.connect((server, port)) > (sread, swrite, serror) = select.select([], [self.sock], [], 10) > if swrite.count(self.sock) > 0: > i = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) > if 0 == i: > self.sock.setblocking(1) > > -- > Helge Aksdal > -- > http://mail.python.org/mailman/listinfo/python-list > From bill.mill at gmail.com Thu Jul 21 10:27:24 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu, 21 Jul 2005 10:27:24 -0400 Subject: is this pythonic? In-Reply-To: References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: <797fe3d4050721072775cff831@mail.gmail.com> On 7/21/05, Steven D'Aprano wrote: > On Wed, 20 Jul 2005 16:30:10 -0400, Bill Mill wrote: > > > On 7/20/05, Simon Brunning wrote: > >> On 7/20/05, Mage wrote: > >> > Or is there better way? > >> > > >> > for (i, url) in [(i,links[i]) for i in range(len(links))]: > >> > >> for i, url in enumerate(links): > >> > > > > +2 for creating seeing a need and crafting a reasonable solution, but > > -1 for not reading the section on builtins to see if it existed > > already. > > To see if *what* existed already? > > It is well and good to say RTFM, but there are 697 subsections to the > Python Library reference, and if you don't know what you are looking for, > and beginners rarely are, it isn't obvious which is the right section to > read. And the Library Reference isn't even "the" manual: there is also the > global module reference and language reference. > > If you already know what you are looking for, reading the manual is great > advice. Browsing the manual looking for interesting tidbits can even be > fun for a certain mindset. But if you don't know enough to know what to > look for, where in the 2000-odd sections of the Python references will > you find it? > I said the *builtins* section. I think you learn pretty quick that figuring out what functions are builtins is pretty important in every language. There's a fair number of people out there giving the advice to read chapter 2 of the library reference cover-to-cover for a good starter on python. Furthermore, I wasn't being hard on the guy, he still added up to +1. Lighten up, I was joking. > > > > (As for its pythonicity, I would have recommended isolating it into a > > function and making it a generator: > > It is easy to take this to extremes. It isn't necessary to isolate > everything into its own object, or class, or module. Too much > encapsulation is just as bad as too little. > agreed; his listcomp just looks awkward inside the for loop statement; if it were my code, I would put it into a function. He asked if his code was pythonic, and I think the (non-extreme) pythonic thing to do would be to put his listcomp into a function. > > > def my_enumerate(enumerable): > > i = 0 > > for elt in enumerable: > > yield (i, elt) > > i += 1 > > > > for i, url in my_enumerate(links): > > > > but it's not too bad as it is. Also, my function is completely > > untested - it's close to right though.) > > What is the advantage of your function my_enumerate over the Python > built-in enumerate? > > absolutely none; I just was saying how I would encapsulate it into a function. Peace Bill Mill bill.mill at gmail.com From __peter__ at web.de Sun Jul 3 04:42:08 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 03 Jul 2005 10:42:08 +0200 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> Message-ID: Steven D'Aprano wrote: > How do you replace: > > reduce(lambda x,y: x*y-1/y, sequence) > > with sum? missing = object() def my_reduce(f, items, first=missing): class adder: def __init__(self, value): self.value = value def __add__(self, other): return adder(f(self.value, other)) if first is missing: items = iter(items) try: first = items.next() except StopIteration: raise TypeError return sum(items, adder(first)).value if __name__ == "__main__": sequence = map(float, range(10)) r = reduce(lambda x, y: x*y-1/y, sequence) s = my_reduce(lambda x, y: x*y-1/y, sequence) assert r == s :-) Peter From steve at REMOVEMEcyber.com.au Thu Jul 7 04:24:58 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 07 Jul 2005 18:24:58 +1000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> Message-ID: <42CCE6DA.5020402@REMOVEMEcyber.com.au> Ron Adam wrote: > Why would you want to use None as an integer value? > > If a value isn't established yet, then do you need the name defined? > Wouldn't it be better to wait until you need the name then give it a value? Er, maybe I'm misunderstanding something here, but surely the most obvious case is for default and special function arguments: def count_records(record_obj, start=0, end=None): if end == None: end = len(record_obj) if start == None: # this is not the default! # start at the current position start = record_obj.current n = 0 for rec in record_obj.data[start:end]: if not rec.isblank(): n += 1 return n which you call with: # current position to end count_records(myRecords, None) # start to end count_records(myRecords) # start to current position count_records(myRecords, end=myRecords.current) -- Steven. From dan at cardinalproperty.com Wed Jul 27 16:22:22 2005 From: dan at cardinalproperty.com (dan at cardinalproperty.com) Date: Wed, 27 Jul 2005 16:22:22 -0400 Subject: MESSAGE NOT DELIVERED: Returned mail: Data format error In-Reply-To: <200507272022.j6RKMK6X022605@host.secure-domain.com> References: <200507272022.j6RKMK6X022605@host.secure-domain.com> Message-ID: <200507272022.j6RKMM4S022723@host.secure-domain.com> Your message could not be delivered. The User is out of space. Please try to send your message again at a later time. From grig.gheorghiu at gmail.com Tue Jul 26 13:50:17 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 26 Jul 2005 10:50:17 -0700 Subject: Using win32com for web automation In-Reply-To: <1122399814.174328.63980@g43g2000cwa.googlegroups.com> References: <1122399814.174328.63980@g43g2000cwa.googlegroups.com> Message-ID: <1122400217.789941.245640@g47g2000cwa.googlegroups.com> For Javascript automation, I recommend Selenium (). Grig From phr at localhost.localdomain Tue Jul 19 09:23:54 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Tue, 19 Jul 2005 13:23:54 GMT Subject: How to send a query to the browser from time to time? References: Message-ID: Admin writes: > If there were a way to have the server-side application send new > messages to the browser this would be awesome because it would save > dramatically on bandwidth. The application would consume bandwidth > only when there are new messages. There would be no communication > client-server until people write a new message. > > Do you know if it's possible? Some people have done stuff like that with multipart mime encodings and chunked transfers. I've looked into it but I'm not sure of the exact mechanism any more. It's kind of messy. The other usual way is to open a tcp connection from a java applet. I don't like that since it means you need java in your browser. There's a chat app called arsc that you might look at: http://manuel.kiessling.net/projects/software/arsc/ Warning, last time I looked at it, it had some security bugs. From jwaixs at gmail.com Sun Jul 3 12:01:01 2005 From: jwaixs at gmail.com (jwaixs) Date: 3 Jul 2005 09:01:01 -0700 Subject: website catcher In-Reply-To: <3iq8juFmr22qU1@uni-berlin.de> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> <3iq5e7Fmn8drU1@uni-berlin.de> <1120396132.606888.322880@g14g2000cwa.googlegroups.com> <3iq8juFmr22qU1@uni-berlin.de> Message-ID: <1120403696.212030.120390@g43g2000cwa.googlegroups.com> Well, thank you for your advice. So I have a couple of solutions, but it can't become a server at its own so this means I will deal with files. Thank you for your advice, I'll first make it work... than the server. Noud Aldenhoven From steve at REMOVETHIScyber.com.au Sat Jul 30 12:25:54 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 02:25:54 +1000 Subject: Comparison of functions References: Message-ID: On Sat, 30 Jul 2005 13:30:20 +0000, Adriano Varoli Piazza wrote: > But tell me, how do you think sort works if not with <, >, ==, <= and >= > ? I'm really interested. How do you sort words in a dictionary? Why does five come before four when the number five is larger than the number four? Why does hundred come before ten? What does it mean to say that elephant is less than mouse? When you can answer those questions, you will be enlightened. -- Steven. From kay.schluehr at gmx.net Sat Jul 9 04:14:54 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 Jul 2005 01:14:54 -0700 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120834070.272672.143850@f14g2000cwb.googlegroups.com> <87br5d2n0a.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: <1120896894.392801.5800@z14g2000cwz.googlegroups.com> Kirk Job Sluder schrieb: > "Kay Schluehr" writes: > > > This might be a great self experience for some "great hackers" but just > > annoying for others who used to work with modular standard librarys and > > think that the border of the language and an application should be > > somehow fixed to enable those. > > In what way do lisp macros prevent the creation of modular libraries? > Common Lisp does does have mechanisms for library namespaces, and in > practice a macro contained within a library is not that much different > from a function contained in a library or a class contained in a > library. Macros just provide another mechanism for creating useful > domain-specific abstractions. To be honest I don't understand what a "domain-specific abstraction" could be? What is the benefit of abstractions if they are not abstracting from particular domain specific stuff? > The primary advantage to macros is that > you can create abstractions with functionality that is not easily > described as either a function or a class definition. As long as macros are used to create new language features such as an object system like CLOS this technique may be perfectly justified for language developers ( ! ) but I still consider it as a bad idea to muddle the language development and the application development, that seems to be the favourite programming style of Paul Graham. On the other hand thinking about language development as a certain application domain I find nothing wrong with the idea that it once reaches somehow a state of a mature product that should not be altered in arbitrary manner for the sake of a large user community. Kay From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 20 10:30:41 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 20 Jul 2005 15:30:41 +0100 Subject: How to kill easygui dialog? In-Reply-To: <1121868204.552155.171690@g49g2000cwa.googlegroups.com> References: <1121800637.589080.210700@g47g2000cwa.googlegroups.com> <1e44d$42dd9a21$d1b7122a$29240@PRIMUS.CA> <1121868204.552155.171690@g49g2000cwa.googlegroups.com> Message-ID: utabintarbo at gmail.com wrote: > William, > > Thanks for the reply. No flames, but I am running on both Linux and > Windows, so I need a x-platform solution. I thought I had it with > easygui... > > Must try some other ideas.... > Can you post an example... the following works for me... >>> import easygui >>> while 1: ... rv = easygui.enterbox() ... if rv: ... print "Done" ... break ... ... Done From eurleif at ecritters.biz Wed Jul 6 00:00:19 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 06 Jul 2005 04:00:19 GMT Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? In-Reply-To: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: markturansky at gmail.com wrote: > I'd like to dynamically find and invoke a method in a Python CGI. getattr(self, methodName)() But make sure to validate user input first, of course. From usenet at zabiello.com Mon Jul 18 08:41:08 2005 From: usenet at zabiello.com (JZ) Date: Mon, 18 Jul 2005 14:41:08 +0200 Subject: What is your favorite Python web framework? References: <1121685852.674382.216790@g14g2000cwa.googlegroups.com> <1myz92llzdq71.qz6wr10keyp8.dlg@40tude.net> Message-ID: <1187fag8wp9vx$.cxafx7ybf8i1.dlg@40tude.net> Dnia Mon, 18 Jul 2005 09:26:10 -0300, Admin napisa?(a): > On Mon, 18 Jul 2005 08:45:22 -0300, JZ wrote: > >> Much more stable and much faster is e.g. Mygty (http://myghty.org) It is >> about 2x faster then CherryPy. Also faster than CherryPy is Webware and >> SkunkWeb. I did not check how fast is Django... It is fresh framework for >> open source community. > > Mmmh... I really don't know which one is better :( Django has similar aproach to Rails or Subway. Myghty is similar to Perl::Mason. I think those two are the most matured and powerfull. (I do not mean Zope and Plone which is specific to its own category) -- JZ From maxume at yahoo.com Mon Jul 18 20:52:27 2005 From: maxume at yahoo.com (max) Date: Tue, 19 Jul 2005 00:52:27 -0000 Subject: Help with images References: <1121731806.578272.174590@z14g2000cwz.googlegroups.com> Message-ID: "Chad" wrote in news:1121731806.578272.174590 at z14g2000cwz.googlegroups.com: > I have installed a TWAIN module(from > http://twainmodule.sourceforge.net) today and figured out how to > acquire an image. The only problem is that the image is way too > large in terms of filesize. It is over 1MB. > > I can do either one of two things. Try to figure out how to > manupilate the image with this module(which I am been doing all > day) or just use a module that can compress jpegs. Can anybody > help? > > Check out PIL: http://www.pythonware.com/products/pil/ http://www.pythonware.com/library/pil/handbook/ but also be sure to read the "Setting Capababilities" section of this document: http://twainmodule.sourceforge.net/docs/caps.html max From edvard+news at majakari.net Thu Jul 14 07:52:31 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Thu, 14 Jul 2005 14:52:31 +0300 Subject: How can I import a py script by its absolute path name? References: Message-ID: <87eka1eha8.fsf@titan.staselog.com> could ildg writes: > I want to import c:\xxx\yyy\zzz.py into my programme, > What should I do? > Thank you~ import sys sys.path.append('c:\xxx\yyy') import zzz (Untested, similar idiom would work in *nix systems, never programmed in Windows) However, I guess it is not very usual you should need to import stuff from arbitrary locations. Consider publishing those modules in normal Python include path (just see what ''print sys.path'' produces) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From christoph.rackwitz at gmail.com Tue Jul 12 02:55:46 2005 From: christoph.rackwitz at gmail.com (Christoph Rackwitz) Date: 11 Jul 2005 23:55:46 -0700 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' References: Message-ID: <1121151346.921786.135740@g43g2000cwa.googlegroups.com> foo = "C1, C2, C3" foo = foo.split(", ") # ['C1', 'C2', 'C3'] foo = ", ".join(foo[:-1]) + " and " + foo[-1] # just slicing and joining it you can always look for something here: http://docs.python.org/lib/lib.html and there: http://docs.python.org/ref/ if you want to know, what methods an object has, try this (i shortened the output a bit): >>> foo = "C1, C2, C3" >>> dir(foo) ['__add__', '__doc__', ..., 'capitalize', 'center', 'count', 'decode','encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> From benn at cenix-bioscience.com Mon Jul 11 08:22:37 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 11 Jul 2005 14:22:37 +0200 Subject: __eq__ on a dict In-Reply-To: References: Message-ID: <42D2648D.6070204@cenix-bioscience.com> Steven D'Aprano wrote: > On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote: > > > >> Hello, >> >> I can't find the docs for __eq__ on a dict and I can't >> find a description on what the eq does (strangely it does implement > >> and < but I have no idea what that does). Does anyone know >> (definitively) what the __eq__, __gt__, __lt__ methods do. >> >> BTW, google is not my friend - I invited it out for a drink last >> week and it stood me up :-) . >> > > > It works for me. Google on "__eq__ Python" and the 5th and 6th sites are: > > http://python.active-venture.com/ref/customization.html > http://www.network-theory.co.uk/docs/pylang/ref_32.html > > As previous reply > Normally, asking Python for help is a good way to read the docs, but in > this particular case, it is a big let-down: > > py> help({}.__eq__) > Help on method-wrapper: > > __eq__ = > > > For any two objects x and y, when you call > x == y > > > That's the empirical evidence that I got but I want to be 100% sure that this holds in all cases - I'm wary about using empirical evidence leading to assumptions in my code - I take the paradigm that 'Assumption is the mother of all f**k-ups'. > In general, you should not call __eq__ directly, but use the == operator > instead. > > > Yeah I'm aware of that, I didn't want to start talking about ==, etc or I may mislead people into the - this is what __eq__ means path of explanation. Thanks for your response. Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From rwgk at yahoo.com Sat Jul 9 04:08:05 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 9 Jul 2005 01:08:05 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <1120655839.962625.292170@f14g2000cwb.googlegroups.com> Message-ID: <20050709080805.42153.qmail@web31514.mail.mud.yahoo.com> --- NickC wrote: > I'd be very interested to hear your opinion on the 'namespace' module, > which looks at addressing some of these issues (the Record object, in > particular). The URL is http://namespace.python-hosting.com, and any > comments should be directed to the namespace at googlegroups.com > discussion list. Hi Nick, The namespace module looks interesting, thanks for the pointer! (I saw your other message but didn't have a chance to reply immediately.) I tried out the namespace.Record class. The resulting user code looks nice, but I have two concerns: - It requires a different coding style; until it is well established it will surprise people. - The runtime penalty is severe. Attached is a simple adopt_timings.py script. If I run it with Python 2.4.1 under RH WS3, 2.8GHz Xeon, I get: overhead: 0.01 plain_grouping: 0.27 update_grouping: 0.44 plain_adopt_grouping: 0.68 record_grouping: 10.85 I.e. record_grouping (using namespace.Record) is about 40 times slower than the manual self.x=x etc. implementation. My conclusion is that namespace.Record may have merits for specific purposes, but is impractical as a general-purpose utility like I have in mind. Note that the attached code includes a new, highly simplified "plain_adopt()" function, based on the information I got through other messages in this thread. Thanks to everybody for suggestions! Cheers, Ralf ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: adopt_timings.py URL: From cam.ac.uk at mh391.invalid Tue Jul 5 09:49:44 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 05 Jul 2005 14:49:44 +0100 Subject: f*cking re module In-Reply-To: <1120568322.948740.229830@g44g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> Message-ID: Greg Lindstrom wrote: > I hear that Perl 6 is > going to have a rewrite of regular expressions; it will be interesting > to see what their hard work produces. From what I saw a while ago, it didn't look like it would be any simpler or more elegant. But that was a while ago. -- Michael Hoffman From martin at v.loewis.de Mon Jul 11 18:45:27 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 12 Jul 2005 00:45:27 +0200 Subject: C API : Creating a Py_Method object from a C function. In-Reply-To: <1121101669.752932.217380@g14g2000cwa.googlegroups.com> References: <1121101669.752932.217380@g14g2000cwa.googlegroups.com> Message-ID: <42D2F687.3040003@v.loewis.de> Hugh Macdonald wrote: > The problem in this workflow is taking the C python function that I've > defined (using the standard "static PyObject *someFunction(PyObject > *self, PyObject *args)" method) and converting this into a Py_Object. > Any ideas? You should use PyCFunction_New(Ex), passing a static PyMethodDef variable that you define along with your function definition. Regards, Martin From samgurung at gmail.com Mon Jul 18 05:39:12 2005 From: samgurung at gmail.com (linuxfreak) Date: 18 Jul 2005 02:39:12 -0700 Subject: wxPython Menu problem Message-ID: <1121679552.543928.292670@g49g2000cwa.googlegroups.com> Hi all, I have a problem. I want to add items to a Menu iteratively and I'm stuck. Heres a snippet of my code fileMenuChoices=[('&New','Start a New Document',self.onClick), ('&Open File...','Open an Existing Document', self.onClick), ('&Save','Save Current Document', self.onClick), ('---'), ('E&xit','Close Window', self.onClick), ('&About','Information', self.onClick)] ..... ..... ..... ..... fileMenu = wxMenu() for opt in fileMenuChoices: fmID = wxNewId() if(opt[0] != '-'): fileMenu.Append(fmID,opt[0], opt[1]) EVT_MENU(self,fmID,opt[2]) else: fileMenu.AppendSeparator() #Creating the MenuBar menuBar = wxMenuBar() menuBar.Append(fileMenu, "&File") self.SetMenuBar(menuBar) #Add menubar to the Frame (Window) def onClick(self,e): ....... ....... The problem is I get an error saying name 'self' not defined... Any help will be appreciated From python at rcn.com Mon Jul 18 01:40:50 2005 From: python at rcn.com (Raymond Hettinger) Date: 17 Jul 2005 22:40:50 -0700 Subject: list implementation References: <1121655435.153214.292520@o13g2000cwo.googlegroups.com> Message-ID: <1121665250.103706.323680@g47g2000cwa.googlegroups.com> [sj] > I believe the type "list" is implemented as an array of pointers. Yes. > Thus, random access is an O(1) operation while insertion/deletion is an > O(n) operation. Yes. > 2. Implementing list as an array is part of language specification or > implementation-dependent? Implementation dependent but likely to be an array of pointers. > 3. What if I actually need a doubly-linked list for constant-time > insertion/deletion? Is there a built-in type or a standard class? Yes. Use collections.deque(). http://docs.python.org/tut/node13.html#SECTION0013700000000000000000 http://docs.python.org/lib/module-collections.html Raymond From istvan.albert at gmail.com Tue Jul 19 16:34:02 2005 From: istvan.albert at gmail.com (istvan.albert at gmail.com) Date: 19 Jul 2005 13:34:02 -0700 Subject: Web Framework Reviews In-Reply-To: References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121796584.974756.132430@g14g2000cwa.googlegroups.com> Message-ID: <1121805242.574679.298990@f14g2000cwb.googlegroups.com> > don't see why this would have problems 'scaling' or would be > more difficult to visualise than a the equivalent tag soup html. I think the difficulties will arise from the inability to visually track closing tags. ]]] versus > Templating engines like ZPT prefer to put some code in the template, > Nevow prefers to put code in python and allow you to write some xhtml in > python too. Oh yeah, now I remeber, I think this is a controversial idea. Istvan. From Scott.Daniels at Acm.Org Sat Jul 23 07:43:07 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 23 Jul 2005 04:43:07 -0700 Subject: tuple to string? In-Reply-To: References: <42E0EED4.4020001@gmx.net> Message-ID: <42e2250d@nntp0.pdx.net> Steven D'Aprano wrote: > On Fri, 22 Jul 2005 06:07:28 -0700, Robert Kern wrote: > ... or even: > >>>>''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D))) > > 'spam' This is exactly what is wrong with lambda. It yearns for over-use. This last should be: >>>''.join(map(chr, (0x73, 0x70, 0x61, 0x6D))) --Scott David Daniels Scott.Daniels at Acm.Org From ric at next-level.com.au Tue Jul 12 15:47:07 2005 From: ric at next-level.com.au (Ric Da Force) Date: Wed, 13 Jul 2005 03:47:07 +0800 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads'C1, C2 and C3' References: Message-ID: Hi guys, Thank you all for your input! It was good to see so much convergence in the approach! Again, I think that it speaks loudly for the concise way of doing thins in Python... Anyway, I have typed in all of the solutions and have gained a great understanding of how to do this in future. Thanks again! Ric "Brian van den Broek" wrote in message news:mailman.1635.1121152323.10512.python-list at python.org... > Ric Da Force said unto the world upon 12/07/2005 02:43: >> Hi, >> >> I have a string such as 'C1, C2, C3'. Without assuming that each bit of >> text is of fixed size, what is the easiest way to change this list so >> that it reads: >> 'C1, C2 and C3' regardless of the length of the string. >> >> Regards and sorry for the newbie question, >> >> Ric > > Hi Ric, > > the rsplit method of strings should get you going: > > >>> data = "the first bit, then the second, finally the third" > >>> chunks = data.rsplit(',', 1) > >>> chunks > ['the first bit, then the second', ' finally the third'] > >>> > > Best, > > Brian vdB > > From thorsten at thorstenkampe.de Sun Jul 10 08:13:16 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 10 Jul 2005 13:13:16 +0100 Subject: Should I use "if" or "try" (as a matter of speed)? References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> <11d0e158o1g8554@news.supernews.com> Message-ID: <18fearebf2js6$.9oemdgamm06p.dlg@40tude.net> * John Roth (2005-07-09 21:48 +0100) > "Thorsten Kampe" wrote in message > news:6i1zj31xlx8.yoof0r88btd1.dlg at 40tude.net... >>* Steve Juranich (2005-07-09 19:21 +0100) >>> I know that this topic has the potential for blowing up in my face, >>> but I can't help asking. I've been using Python since 1.5.1, so I'm >>> not what you'd call a "n00b". I dutifully evangelize on the goodness >>> of Python whenever I talk with fellow developers, but I always hit a >>> snag when it comes to discussing the finer points of the execution >>> model (specifically, exceptions). >>> >>> Without fail, when I start talking with some of the "old-timers" >>> (people who have written code in ADA or Fortran), I hear the same >>> arguments that using "if" is "better" than using "try". I think that >>> the argument goes something like, "When you set up a 'try' block, you >>> have to set up a lot of extra machinery than is necessary just >>> executing a simple conditional." >>> >>> I was wondering how true this holds for Python, where exceptions are >>> such an integral part of the execution model. It seems to me, that if >>> I'm executing a loop over a bunch of items, and I expect some >>> condition to hold for a majority of the cases, then a "try" block >>> would be in order, since I could eliminate a bunch of potentially >>> costly comparisons for each item. But in cases where I'm only trying >>> a single getattr (for example), using "if" might be a cheaper way to >>> go. >>> >>> What do I mean by "cheaper"? I'm basically talking about the number >>> of instructions that are necessary to set up and execute a try block >>> as opposed to an if block. >> >> "Catch errors rather than avoiding them to avoid cluttering your code >> with special cases. This idiom is called EAFP ('easier to ask >> forgiveness than permission'), as opposed to LBYL ('look before you >> leap')." >> >> http://jaynes.colorado.edu/PythonIdioms.html > > It depends on what you're doing, and I don't find a "one size fits all" > approach to be all that useful. I think, it's a common opinion in the Python community (see for instance "Python in a Nutshell") that EAFP is the Pythonic way to go and - except in very rare cases - much preferred to LBYL. Speed considerations and benchmarking should come in after you wrote the program. "Premature optimisation is the root of all evil" and "first make it work, then make it right, then make it fast" (but only if it's not already fast enough) - common quotes not only with Python developers. From duncan.booth at invalid.invalid Sat Jul 23 12:47:02 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jul 2005 16:47:02 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Just a note, though you probably know, that this is intended to be > written this way with path: > > >>> p / q > path(u'a/b/c/d') I know, but it really doesn't look right to me. I think that my fundamental problem with all of this is that by making path a subclass of str/unicode it inherits inappropriate definitions of some common operations, most obviously addition, iteration and subscripting. These operations have obvious meaning for paths which is not the same as the meaning for string. Therefore (in my opinion) the two ought to be distinct. From williams13 at llnl.gov Fri Jul 22 08:11:45 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Fri, 22 Jul 2005 05:11:45 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050719111537.GC532@tishler.net> References: <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> Message-ID: <42E0E281.6060009@llnl.gov> Hi Jason, I downloaded your new Cygwin from http://cygwin.com and tried to build install Python/CDAT again. It appears to have built properly, but when I try to execute, it receive a sock error. How do I get around this problem? When I built Cygwin, I instructed it to install everything. Thanks in advance for your help and best regards, Dean From bigfox at altern.org Wed Jul 27 18:13:20 2005 From: bigfox at altern.org (Nicolas Lebas) Date: Thu, 28 Jul 2005 00:13:20 +0200 Subject: getting Arrays and variables from R [fixed] In-Reply-To: <42E62AC0.9050201@grignon.inra.fr> References: <42E62AC0.9050201@grignon.inra.fr> Message-ID: <42E80700.6090808@altern.org> Finally i found the solution in Rpy-list : there is a bug in python2.4-rpy_0.4.1. An alternative solution which works fine it's to use the R get(str) function instead of using directly the variable (i.e r.tab) like that : r.get('tab') Nicolas Lebas a ?crit : > hello, > > i don't know if this is the best list to send this question, but i'm > already trying to ask. > > I need to import variables from .RData files (arrays or variables). > I'm trying to use the rpy module, but without success beccause when i > try to access to a variable loaded from the .RData file i have a > segmentation fault ! > > This is what i'm doing : > - in R-projet, i create a .RData file with some variables : > > tab<-c(2,5,8,6) > > v<-0.5 > > save.image("file.RData") > > - in Python : > > from rpy import * > > r.load("file.RData") > ['tab', '.Traceback', 'v'] > > r.tab > segmentation fault ! > > I don't understand very well what does python crash. > > If someone has an idea to solve my problem or to give me a method which > permit to import arrays and variables from .RData files with another module. > > Thanks > > Nicolas From duncan.booth at invalid.invalid Thu Jul 7 10:16:18 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jul 2005 14:16:18 GMT Subject: Windows Cmd.exe Window References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <1120742729.424832.189110@f14g2000cwb.googlegroups.com> <48cc122d9ef6d3dc90fd4ca36482a1da@upf.edu> Message-ID: harold fellermann wrote: > sorry, I did not think. if you want to wait for input _only_ if > an exception occured, your exit function needs to check for the > exception: > > >>> import atexit > >>> > >>> def wait_on_exc() : > ... import sys > ... if sys.exc_type : > ... raw_input() > ... > >>> atexit.register(wait_on_exc) > > this should do the job, now. > Did you think to test your code before posting it? sys.exc_type is deprecated (you should use sys.exc_info() instead), but neither will tell you whether the program is exiting as a result of an exception when called from an atexit function, by the time the atexit function is called the exception is no longer accessible. As Larry Bates suggested, the OP needs to use a sys.excepthook. Unfortunately he doesn't test his code either (the parameter 'traceback' conflicts with the module 'traceback'), but at least the principle is correct. From algebraist at gmail.com Wed Jul 20 14:22:31 2005 From: algebraist at gmail.com (algebraist) Date: 20 Jul 2005 11:22:31 -0700 Subject: access the text being generated in other windows In-Reply-To: References: <1121829930.938089.122070@g44g2000cwa.googlegroups.com> Message-ID: <1121883751.485847.43200@o13g2000cwo.googlegroups.com> yeah, someone else mentioned getting the window's handle (can use spyxx.exe for this) and then using hooks... but i'm not sure where to go to learn about using window hooks, in python (or in general, actually)... is this 'downright dirty screen scraping'? From bob at greschke.com Thu Jul 28 16:34:45 2005 From: bob at greschke.com (bob at greschke.com) Date: 28 Jul 2005 13:34:45 -0700 Subject: pySerial Windows write problem In-Reply-To: <3tudna94E-hWoXTfRVn-tw@nmt.edu> References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: <1122582885.387084.104280@g44g2000cwa.googlegroups.com> I forgot to mention that once the Python program(s) fail, THEN the C++ program also fails to opne the port, and the equipment has to be power-cycled to get things to work again. Bob From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 5 15:36:20 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 5 Jul 2005 21:36:20 +0200 Subject: Folding in vim References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: Benji York enlightened us with: > Your editor probably supports a "backspace unindents" option. Yes, it does. I'm using vim. > If using Vim it would be something like "set softtabstop=4". This gives you a mixture of tabs and spaces, which I don't like. I'd rather use real tabs for indenting. If you then use another tab width, you only see a wider indent, but the rest of the code is okay. When using a tab/space mixture, with eight spaces being one tab, and an indent of four spaces, things go wrong when the tab size is anything but eight spaces. My solution works for all tab sizes, the other solution only works for tabs of eight spaces. This is why in my opinion it's better to just use tabs. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From deets at web.de Mon Jul 4 05:08:52 2005 From: deets at web.de (Diez B. Roggisch) Date: Mon, 04 Jul 2005 11:08:52 +0200 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <3iscl4Fmt99eU1@uni-berlin.de> jwaixs wrote: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! There are only reference, and if you don't know how a > module work you won't learn it from a reference! > > This is the problem: > > >>>>import re >>>>str = "blablaRe modules sucks!blabla" >>>>re.search("()(/python>)", str).group() > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'NoneType' object has no attribute 'group' > > the only thing I want are the number of places blabla, Re modules > sucks! and blabla are. Others gave you advice on how to deal withe regexes. I'm going to add that regexes aren't the way to go for this - use HTMLParser. With your regex, you won't be able to handle correctly either this some textsome other text as you will get the whole string, not just the first match. You can alter the so-called longest match behaviour, but then some oute text some inner text some more outer text won't work.... Try and do not use regexps. Or at least do it in a way that you tokenize the text and then can sweep over it collecting the data you need yourself (but that's basically rewriting the html parsers out there). Diez From prabapython at yahoo.co.in Wed Jul 13 07:05:48 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 13 Jul 2005 12:05:48 +0100 (BST) Subject: reg php equivalent move_uploaded file function in python In-Reply-To: Message-ID: <20050713110548.84896.qmail@web8403.mail.in.yahoo.com> Dear all, Is there any php equivalent move_uploaded_file($source_path, "$upload_dir/$name"); function in python to upload a file to server? Kindly give me answer. regards Prabahar __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From mmrsva at gmail.com Mon Jul 4 09:36:02 2005 From: mmrsva at gmail.com (Marcio Rosa da Silva) Date: Mon, 04 Jul 2005 15:36:02 +0200 Subject: Where can I get the new version of python-mode for emacs? Message-ID: Hi all, My first try on using RST to write an email. so I can (will) make mistakes :-) I am experiencing the problem shown in this thread_ of the `python-mode`_ discussion list hosted at SourceForge. .. _thread: https://sourceforge.net/tracker/?func=detail&atid=581349&aid=1215039&group_id=86916 .. _`python-mode`: http://sourceforge.net/projects/python-mode/ I have version 4.70 installed in my debian system (installed with apt-get, so I don't know where the sources are from). After reading the thread_ at sourceforge, I did a google search for "python emacs" and found the `Emacs goodies`_ page at python.org .. _`Emacs goodies`: http://www.python.org/emacs/ where I was redirected to the `python-mode`_ page at SourceForge. There I could only find version 1.0alpha (4.6) (the one said too old in the thread_) I also tried the `Barry Warsaw's Elisp packages`_ as suggested at `Emacs goodies`_ page "for some more up-to-date versions of these files", but the link doesn't work. .. _`Barry Warsaw's Elisp packages`: http://barry.warsaw.us/elisp/ So, *where can I find a newer version of emacs' python-mode*? Thanks, Marcio From jurgenex at hotmail.com Mon Jul 18 20:13:19 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 19 Jul 2005 00:13:19 GMT Subject: Xah's edu corner: on Microsoft hatred References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > Dear Joe, > > It is well known that you are an avid hater of Microsoft, from their [...] Just for the records at Google et.al. in case someone stumbles across Xah's masterpieces in the future: Xah is very well known as the resident troll in many NGs and his 'contributions' are less then useless. Best is to just ignore him. But for heaven's sake unless you want to embarrass yourself really badly don't take any of his postings serious because he has proven again and again that he has no clue whatsoever about computer science or programming. jue From ggg at zzz.it Sun Jul 31 05:58:32 2005 From: ggg at zzz.it (deelan) Date: Sun, 31 Jul 2005 11:58:32 +0200 Subject: namespaces In-Reply-To: References: <42EC9690.2040301@tiscali.it> Message-ID: Paolino wrote: (...) > What I'm needing as a global (in globals() or at the module level or in > the module namespace) is 'translate'.The rest of bindings (all,badcars > and table) is something which is 'polluting' the module namespace. try this: ## yourmodule.py ## def _setup_table(): import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) return string.maketrans(badcars,'_'*len(badcars)) TABLE = _setup_table() # optional, get rid of _setup_table symbol del _setup_table() def translate(text): return text.translate(TABLE) HTH, deelan. -- deelan, #1 fan of adriana lima! From paul at boddie.org.uk Thu Jul 28 18:26:36 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 28 Jul 2005 15:26:36 -0700 Subject: Cgi scripts in apache not working References: <1122571679.788076.37080@g43g2000cwa.googlegroups.com> Message-ID: <1122589596.459515.261550@f14g2000cwb.googlegroups.com> David wrote: > > httpd.conf: > > << Tried it with "" and no "" > Options ExecCGI << Tried with "Options +ExecCGI" > AddHandler cgi-script .cgi .py << Tried with "SetHandler > cgi-script", but still no go > > > > error_log: > > [Thu Jul 28 11:44:53 2005] [error] [client xxx.xxx.xxx.xxx] Premature > end of script headers: test2.py I assume that you have a UserDir directive elsewhere in your configuration; otherwise, what you've written probably won't be enough. See this guide for the full details: http://httpd.apache.org/docs/2.0/howto/public_html.html I typically find that using the ScriptAlias directive does what I want, although I don't work with user directories myself. Here's an example: ScriptAlias /cgi/ "/home/paul/some_directory/" I imagine that the ScriptAliasMatch directive would also be able to do the home directory matching that you are doing in your configuration file. See the documentation for both directives here: http://httpd.apache.org/docs/2.0/mod/mod_alias.html#scriptalias Apart from using ScriptAlias, I don't usually do anything more than check the ownership/permissions on the CGI directory and the script. Naturally, the PYTHONPATH (or sys.path) needs to be configured to find non-installed modules and packages, but such things are beyond this particular problem. Paul From cyril.bazin at gmail.com Mon Jul 11 14:24:44 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Mon, 11 Jul 2005 20:24:44 +0200 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: Message-ID: Hum... I think an iteritems is better, this way, python don't need to create in memory a complete list of couple key, value. On 7/11/05, Markus Weihs wrote: > > Hi! > > > Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} > NewDic = {} > > for k,v in Dict.items(): > NewDic.setdefault(v, []).append(k) > > > Regards, mawe > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From c-bizhong.hu at mci.com Fri Jul 8 15:09:40 2005 From: c-bizhong.hu at mci.com (Hu, Bizhong) Date: Fri, 08 Jul 2005 19:09:40 +0000 Subject: qustion about build Python on the Solaris 9 Message-ID: Greeting to All: I am trying to build python-2.4.1 on the sun solairs 9 on SPARC hardware as a 64 bits application. I have all the compiler switch setup and python build is completed. But when the makefile try to Run python setup.py command, It coredumped. My question is that is anyone know if python can Be build as 64 bits application on SPARC ??? Thanks in advance. Regards Bizhong -------------- next part -------------- An HTML attachment was scrubbed... URL: From philippe at philippecmartin.com Thu Jul 7 18:43:51 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 07 Jul 2005 22:43:51 GMT Subject: Options to integrate Python modules into native windows applications References: Message-ID: Thanks Larry, I want to: 1) Modify my code as little as possible 2) Please/reassure the lambda VB or VC++ oriented company Regards, Philippe Larry Bates wrote: > Other methods (services, sockets, pipes, etc.) > can also work well, but it depends on what you > want to do and how you wish to communicate between > the modules. From rorley at gmail.com Tue Jul 12 13:10:26 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 10:10:26 -0700 Subject: Help with inverted dictionary In-Reply-To: References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> Message-ID: <1121188226.860632.311880@f14g2000cwb.googlegroups.com> Not quite homework but a special project. Thanks for the advice. I'll let you know if I run into anymore stumbling blocks. Reece From gsakkis at rutgers.edu Sun Jul 10 17:42:24 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jul 2005 14:42:24 -0700 Subject: Python Module Exposure References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> <1120934851.208175.19180@f14g2000cwb.googlegroups.com> <1120975905.198149.19240@z14g2000cwz.googlegroups.com> <1120998768.466586.269180@g47g2000cwa.googlegroups.com> Message-ID: <1121031744.956821.225880@g43g2000cwa.googlegroups.com> "Jacob Page" wrote: > OK, you've convinced me now to support and, or, and xor between every > combination of Intervals and IntervalSets, Intervals and IntervalSets, > and IntervalSets and Intervals. I'm sorry, this was not my intention . > However, I'm not sure I like the idea > of an operation generating either one type or another. I don't like it either; it makes the user's work harder by forcing him to check the result's type, and then either process each type differently or wrap Intervals into IntervalSets and deal with the latter only. > Thus, I'll have > | and ^ operations between Intervals always return an IntervalSet > instead of returning either an IntervalSet or an Interval. & will > return an Interval. I suppose that means I should just have + do a > union and - return an IntervalSet. It will just have to be documented > which types are to be expected for the return values depending on the > operands. This is better, but still I'm not sure if it's good enough. Splitting the set of operators into those returning Interval and those returning IntervalSet has to be documented of course, but nevertheles it is not intuitive for the simple user who doesn't think about closed and non-closed operations. It's a viable option though. The other two options are: - Return always an IntervalSet from all five operators (~, |, &, ^, -). This is inconvenient for at least intersection and difference which are known to be closed operations. - Go back to your initial preference, that is don't support any operator at all for Intervals. Given that in your new version there are factories in IntervalSet as well, it's not as bad as before; simply the user can create Intervals through the IntervalSet factories. You can take this even further by disallowing (or discouraging at least) the user to instantiate Intervals directly. An analogy is the Match type in the re module. Match objects are returned by re.match() and re.search() and they expose a set of useful methods (group(), groups(), etc.). However if the user attempts to create a Match instance, a TypeError is raised. Currently I like this option better; it's both user and developer friendly :) George From sjmachin at lexicon.net Wed Jul 13 18:49:05 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Jul 2005 08:49:05 +1000 Subject: all possible combinations In-Reply-To: References: <1121265581.28091.2.camel@athop1.ath.vt.edu> Message-ID: <42d59a61$1@news.eftel.com> Steven D'Aprano wrote: > On Wed, 13 Jul 2005 10:39:41 -0400, rbt wrote: [snip] > Ah, then that's easy. Sit down with pencil and paper, write out all 64 > combinations yourself, and then type them into a Python list. Then you can > access any one of those combinations with a single call. [snip] >>My list is not arbitrary. I'm looking for all 'combinations' as I >>originally posted. Order does not matter to me... just all possibilities. > > > That's good, since you only need combinations of "a", "b" and "c" the "You keep using that word. I do not think it means what you think it means." Both of you please google("define: combination") From steve at REMOVETHIScyber.com.au Sun Jul 3 14:00:02 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 04:00:02 +1000 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <42c7f923$1@nntp0.pdx.net> Message-ID: On Sun, 03 Jul 2005 08:14:28 -0700, Scott David Daniels wrote: > egbert wrote: >> On Sat, Jul 02, 2005 at 08:26:31PM -0700, Devan L wrote: >> >>>Also, map is easily replaced. >>>map(f1, sequence) == [f1(element) for element in sequence] >> >> How do you replace >> map(f1,sequence1, sequence2) >> especially if the sequences are of unequal length ? >> >> I didn't see it mentioned yet as a candidate for limbo, >> but the same question goes for: >> zip(sequence1,sequence2) > > OK, you guys are picking on what reduce "cannot" do. > The first is [f1(*args) for args in itertools.izip(iter1, iter2)] And now we get messier and messier... Compare these two idioms: "Map function f1 to each pair of items from seq1 and seq2." "Build a list comprehension by calling function f1 with the unpacked list that you get from a list built by zipping seq1 and seq2 together in pairs." Good thing that removing reduce is supposed to make code easier to understand, right? > How to _you_ use map to avoid making all the intermediate structures? I don't understand the question. Presumably the sequences already exist. That's not the point. > I never saw anything about making zip go away. It is easy to explain. I don't find map any less clear than zip. Except for the arbitrary choice that zip truncates unequal sequences while map doesn't, zip is completely redundant: def my_zip(*seqs): return map(lambda *t: t, *seqs) Zip is just a special case of map. I find it disturbing that Guido is happy to fill Python with special case built-ins like sum, zip and (proposed) product while wanting to cut out more general purpose solutions. [snip] > If you want functional programming in python, you have at least > three big problems: > > 1) Python has side effect like mad, so order of evaluation matters. Not if you *just* use functional operations. Not that I would ever do that. The point isn't to turn Python into a purely functional language, but to give Python developers access to functional tools for when it is appropriate to use them. > 2) Python's essential function call is not a single-argument > function which might be a tuple, it is a multi-argument function > which is not evaluated in the same way. And I'm sure that makes a difference to the functional programming purists. But not to me. > 3) Python doesn't have a full set of functional primitives. > Fold-right is one example, K-combinator is another, .... Why pick on > reduce as-is to keep? There is another slippery slope argument > going up the slope adding functional primitives. My car isn't amphibious, so I can't go everywhere with it. Should I throw it away just because I can't drive under water? No, of course not. Just because Python isn't a purely functional language doesn't mean that we should reject what functional idioms (like list comps, and zip, and reduce) it does have. Personally, I'd like to learn more about about fold-right and K-combinator, rather than dump reduce and map. Frankly, I find this entire discussion very surreal. Reduce etc *work*, right now. They have worked for years. If people don't like them, nobody is forcing them to use them. Python is being pushed into directions which are *far* harder to understand than map and reduce (currying, decorators, etc) and people don't complain about those. And yet something as simple and basic as map is supposed to give them trouble? These are the same people who clamoured for zip, which is just a special case of map? -- Steven. From bkhl at stp.ling.uu.se Thu Jul 7 13:10:01 2005 From: bkhl at stp.ling.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Thu, 07 Jul 2005 19:10:01 +0200 Subject: flatten() References: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: <87br5e7dau.fsf_-_@lucien.dreaming> Tom Anderson writes: > Stian S?iland wrote: > > > Or what about a recursive generator? > > That's the sort of thing i like to see! That can be a neat method. It's a pretty verbose way to do flatten(), but it's a good example: def flatten(l): for e in l: if isinstance(e, list): for f in flatten(e): yield f else: yield e for x in flatten([0, [1, 2, [3, 4], 5], 6, 7]): whatever() -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From bill.mill at gmail.com Mon Jul 11 11:54:57 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon, 11 Jul 2005 11:54:57 -0400 Subject: Yet Another Python Web Programming Question In-Reply-To: <1d6cdae305070913436fcef8b4@mail.gmail.com> References: <1d6cdae305070913436fcef8b4@mail.gmail.com> Message-ID: <797fe3d405071108547cb69f22@mail.gmail.com> > Python using CGI, for example, was enough for him until he started > getting 500 errors that he wasn't sure how to fix. A common error is that python cgi files need line endings to be in unix text file format, not windows text file format (\n instead of \r\n) [1]. Why this is, I don't know, but it causes a lot of errors for windows folks. I'm a frequent linux/windows switcher, and it's caused me no end of troubles - if you're getting "premature end of script headers" in your apache error logs, this may be your problem. Peace Bill Mill bill.mill at gmail.com From arutz at mimoza.pantel.net Fri Jul 22 06:12:41 2005 From: arutz at mimoza.pantel.net (Antal Rutz) Date: Fri, 22 Jul 2005 12:12:41 +0200 Subject: Multithreaded class with queues Message-ID: <42E0C699.1030507@mimoza.pantel.net> Hi! I wrote a little class to make multihreading easier. It's based on one of aahz's threading example scripts. What it does: It spawns up number of CollectorThreads and one ProcessThread. The CollectorThreads listen on one queue (inputqueue), read, process the data (with colfunc), put the result onto the outputqueue. The ProcessThread listens on the outputqueue, reads, processes (with prfunc). end. (more details in the attached file) it seems to work with test functions but when I use a network-intensive function (snmp-queries) it just gets slower with maxThreads set to more than 1. Any help? Thanks. see the class attached. ps. Maybe I basically don't understand something... -- --arutz -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: C.py URL: From bokr at oz.net Mon Jul 11 11:48:30 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 15:48:30 GMT Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com><20050710133959.83611.qmail@web31512.mail.mud.yahoo.com><7x64vip8eb.fsf@ruckus.brouhaha.com> <42d1d71e.340825300@news.oz.net> Message-ID: <42d29397.389074930@news.oz.net> On Mon, 11 Jul 2005 01:44:07 -0400, "Terry Reedy" wrote: > >"Bengt Richter" wrote in message >news:42d1d71e.340825300 at news.oz.net... >> Me too. I liked the leading _, but on second thought it is a weird >> language change >> re names in a special context. Probably not so good. > >To repeat: while my '_' proposal could have been for a language change (in >3.0), it was actually for a convention recognized by a metaclass or, more >likely, decorator (and implementable now, I think). *Any* flag would serve >the purpose, but I picked one that was a single char while being visually >striking and, as far as I know, rarely used in current practice even though >quite legal. A 'self_' prefix would do as well except for being more to >type. The prefix could even be an argument to the decorator! > Yes, sorry, I should have read more carefully. Yours is the high ground ;-) Regards, Bengt Richter From mwm at mired.org Sun Jul 3 16:06:10 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 16:06:10 -0400 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: <8664vr3b9p.fsf@bhuda.mired.org> Christopher Subich writes: > That, and the file format definitely isn't robust to bit-rot that > happened too often on FAT16/32 filesystems. >From where I sit, the critical difference between the registry and a set of .ini files (or Unix rc files) is that the registry requires special tools to tweak if it gets so busted you can't boot the system. The .ini (rc) files require nothing more complicated than an editor. Editors you sort of have to know - so fixing the .ini (rc) files doesn't require learning anything beyond the configuration system. To add insult to injury, the tools for hacking the Windows registry all require you to bring up a GUI, which means your "rescue" disk has to include a GUI. Note that Unix isn't immune to things like the registry. AIX(*) puts all the configuration information in an object database, that require special tools to manipulate. At least AIX provides CLI and curses-based tools to do the work. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ptmcg at austin.rr.com Fri Jul 1 21:25:47 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 1 Jul 2005 18:25:47 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <1120267547.570957.244300@g47g2000cwa.googlegroups.com> I have never written a line of Lisp or Scheme, so it took me a while to grok "lambda" as a synonym for "expression to be evaluated later". I then thought it was similar to Smalltalk's functional closures, since you can define local arguments at the beginning of the block, and then write the body of the block using those args. But then I saw that it was only a subset of that capability, since one may only implement an expression in a lambda, not a full code block. Even with those limitations, I've found lambda to be a nice compact form for specifying callbacks. It is especially helpful in pyparsing, where I define a mechanism for the programmer to specify a parse action to be performed, which can modify the matched tokens. Here is one that is very compact: quotedString.setParseResults( lambda s,loc,toks: toks[0][1:-1] ) Parse actions take 3 arguments: the original string being parsed, the location of the beginning of the match, and a ParseResults object containing the matched tokens (ParseResults objects can act as a list, dict, or object with attributes). The purpose of this parse action is to remove the opening and closing quotation marks from the matched quoted string. One of the things I especially like about this simplicity of parse actions is that there is no need for checking whether toks is an empty list, or if the first and last characters are quotation marks before stripping them - quotedStrings call their parse actions *only* with a single element list, and only with the first element containing a string with opening and closing quotes. Still, in anticipation of the demise of lambda, and because this function is frequently needed, I've added it as a built-in helper function to pyparsing, called removeQuotes. But lambda is very simple and immediate for defining such simple transforms, and there is no need to go track down where a named function definition may be found. (Yes, I *could* stop in my tracks just prior to this statement and define this one-line function, but then this interrupts the flow of my grammar definition.) It seems to me that lambda's built-in limitation of *only* supporting expressions, rather than complete code blocks, has led to people applying their boundless creativity to trying to cram conditional logic into bewildering and failure-prone boolean expressions, and it reminds me of some of the C macro coding that I had to sift through about 20 years ago. Not coincidentally, I think the lambda limitation is the true origin of may of the requests we read on c.l.py for the proper syntax for Python's version of the ternary ?: operator as in "how do I write (x>10? a : b) in Python", which is invariably followed by a post such as, "don't bother with that, just do "(x>10 and a or b)", which is then usually followed with, "but watch out in case a evaluates to False..." So personally, I like lambdas even if I am not found of the keyword "lambda". Maybe we could replace "lambda" with "@" or "$"? -- Paul From rrr at ronadam.com Thu Jul 7 14:24:41 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 18:24:41 GMT Subject: Use cases for del In-Reply-To: <42CCE6DA.5020402@REMOVEMEcyber.com.au> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Ron Adam wrote: > >> Why would you want to use None as an integer value? >> >> If a value isn't established yet, then do you need the name defined? >> Wouldn't it be better to wait until you need the name then give it a >> value? > > > Er, maybe I'm misunderstanding something here, but surely the most > obvious case is for default and special function arguments: > > def count_records(record_obj, start=0, end=None): > if end == None: > end = len(record_obj) > if start == None: # this is not the default! > # start at the current position > start = record_obj.current > n = 0 > for rec in record_obj.data[start:end]: > if not rec.isblank(): > n += 1 > return n > > which you call with: > > # current position to end > count_records(myRecords, None) > # start to end > count_records(myRecords) > # start to current position > count_records(myRecords, end=myRecords.current) You have three possible outcomes, count all count range count using current index count range from beginning to current count range from current to end The most consistent way to do this would be: def count_records(record_obj, start=0, end=len(record_obj)): n = 0 for rec in record_obj.data[start:end]: if not rec.isblank(): n += 1 return n # current position to end count_records(myRecords, myRecords.current) # start to end count_records(myRecords) # start to current position count_records(myRecords, end=myRecords.current) Cheers, Ron From bill.mill at gmail.com Thu Jul 21 11:16:11 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu, 21 Jul 2005 11:16:11 -0400 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <797fe3d405072108123df80a85@mail.gmail.com> References: <42dfb111@griseus.its.uu.se> <797fe3d405072108123df80a85@mail.gmail.com> Message-ID: <797fe3d4050721081632c1dea5@mail.gmail.com> On 7/21/05, Bill Mill wrote: > On 7/21/05, Jan Danielsson wrote: > > Hello all, > > > > How do I make a python script actually a _python_ in unix:ish > > environments? > > > > I know about adding: > > #!/bin/sh > > > > ..as the first row in a shell script, but when I installed python on > > a NetBSD system, I didn't get a "python" executable; only a "python2.4" > > executable. > > > > Adding "#!/usr/pkg/bin/python2.4" as the first row in the script > > would probably work, but that would be too specific for the system I'm > > using, imho. > > > > I saw someone using "#!/usr/bin/env python", but that failed on the > > system I'm using, so I assume that's something specific too (or is the > > installation broken?). > > The env program [1], which usually exists at least on a linux system, > executes the program given as its argument. Thus, "/usr/bin/env > python" tries to executes python, which bash will then use to run the > python script. As long as env exists, and python is somewhere in the > PATH, this is a fairly portable way to run python scripts. > > Does BSD really not come with the env program? I bet there's an > equivalent you could symlink to it. Unfortunately, I've never BSDed, > so I can't help you find it. To get a workable subset of the normal > env functionality, you could try (assuming you use bash): > > /home/llimllib $ echo "$@" > /usr/bin/env > /home/llimllib $ chmod a+x /usr/bin/env > ahhh, that should be: /home/llimllib $ echo "\$@" > /usr/bin/env otherwise bash tries to substitute into the string. Sorry bout that. Peace Bill Mill bill.mill at gmail.com From egbert.bouwman at hccnet.nl Sun Jul 3 05:12:01 2005 From: egbert.bouwman at hccnet.nl (egbert) Date: Sun, 3 Jul 2005 11:12:01 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120361191.481114.134500@z14g2000cwz.googlegroups.com> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: <20050703091201.GA1964@hccnet.nl> On Sat, Jul 02, 2005 at 08:26:31PM -0700, Devan L wrote: > > Also, map is easily replaced. > map(f1, sequence) == [f1(element) for element in sequence] > How do you replace map(f1,sequence1, sequence2) especially if the sequences are of unequal length ? I didn't see it mentioned yet as a candidate for limbo, but the same question goes for: zip(sequence1,sequence2) -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From alexis.robert at gmail.com Wed Jul 13 07:13:32 2005 From: alexis.robert at gmail.com (Alexis ROBERT) Date: Wed, 13 Jul 2005 13:13:32 +0200 Subject: Software needed In-Reply-To: <1121183089.760096.300450@z14g2000cwz.googlegroups.com> References: <1121183089.760096.300450@z14g2000cwz.googlegroups.com> Message-ID: <27ffa6590507130413750d99cf@mail.gmail.com> Where I could find the TWAIN python interface ? I'm quite interested :) 12 Jul 2005 08:44:49 -0700, Peter Herndon : > > "Document Management Software" is a little vague. What do you want it > to do? In general though, when someone says "content management" and > "Python", the general response is Zope, usually with Plone on top. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From philippe at philippecmartin.com Wed Jul 20 16:21:54 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 20 Jul 2005 20:21:54 GMT Subject: returning list of strings from Python COM to Visual basic 6 Message-ID: Hi, Is it possible ? ex: return ['1','2'] If so which type should I use in VB ? dim res as ??????? Set testObj = CreateObject("xxxx") res = testObj.AMethodThatReturnsAListOfStrings() Thanks, Philippe From donn at u.washington.edu Fri Jul 22 17:09:59 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 22 Jul 2005 14:09:59 -0700 Subject: Something that Perl can do that Python can't? References: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> Message-ID: In article <1122064588.174698.153220 at g43g2000cwa.googlegroups.com>, "Dr. Who" wrote: > So here it is: handle unbuffered output from a child process. Your Perl program works the same for me, on MacOS X, as your Python program. That's what we would expect, of course, because the problem is with the (Python) program on the other end - it's buffering output, because the output device is not a terminal. Donn Cave, donn at u.washington.edu > Here is the child process script (bufcallee.py): > import time > print 'START' > time.sleep(10) > print 'STOP' > > In Perl, I do: > open(FILE, "python bufcallee.py |"); > while ($line = ) > { > print "LINE: $line"; > } > > in which case I get > LINE: START > followed by a 10 second pause and then > LINE: STOP > > The equivalent in Python: > import sys, os > > FILE = os.popen('python bufcallee.py') > for line in FILE: > print 'LINE:', line > > yields a 10 second pause followed by > LINE: START > LINE: STOP > > I have tried the subprocess module, the -u on both the original and > called script, setting bufsize=0 explicitly but to no avail. I also > get the same behavior on Windows and Linux. > > If anyone can disprove me or show me what I'm doing wrong, it would be > appreciated. > > Jeff From s_t_a_n_i at gmx.net Wed Jul 20 20:21:51 2005 From: s_t_a_n_i at gmx.net (Stani) Date: 20 Jul 2005 17:21:51 -0700 Subject: ANN: SPE 0.7.4.a Python IDE Message-ID: <1121905311.650909.127700@g49g2000cwa.googlegroups.com> Quick release for wxPython2.6, use at your own risk Major bugfix release for wxPython 2.6+ and Mac Os X (This version doesn't work for sure with wxPython versions lower than 2.5.4.1) Bug reports which are related to wxPython 2.6- will be ignored. SPE has a new website: http://www.stani.be/python/blog Update your bookmarks! --------------------------------------------- :Contribute: - packagers for Linux and Mac Os X - patches - doc writers and translators - SVN development - donations --------------------------------------------- :New Features: - editor: call-tips for classes - preferences: configurable shortcuts (see shortcuts/__init__.py) - preferences: word characters for autocompletion and calltips - sidebar: improved browser with filters - sidebar: realtime updating now works ----------------------------------------------- :Bug fixes: - major bugfix for wxpython 2.6+ - major bugfix for Mac OS X - notebooksizer deprecations - blender: support only exposed if run inside blender - editor: autocompletion (case sensitive) - editor: correctly scrolling to lines - editor: encoding - editor: improved call tips for classes - editor: no sash, no crash - editor: save checks if file exists - editor: scrollbars (no invisible source anymore) - editor: source gets focus properly - editor: find dialog gets focus if already opened - editor: shortcut for dedent is now Shift+Tab - preferences: added word characters - sdi: Tool pane has no toolbar - shell: pressing Tab no longer inserts a tab in the editor - sidebar: realtime updating - tool: find now also executes on enter - tool: find doesn't use notebooksizer anymore - tool: find now also executes on enter (Yoyong Hernan) - tool: browser add new folder starts from current folder (Yoyong Hernan) --------------------------------------------- :Requirements: - full python 2.3+ - wxpython 2.6+ - optional blender 2.35 -------------------------------------------------- :Donations: - Howard Jones (75 euro, thanks!) - J P Dowd (8 euro) - Mickey Hadick (5.00) From tjreedy at udel.edu Thu Jul 7 16:49:36 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jul 2005 16:49:36 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com><1120610787.940292.15210@g43g2000cwa.googlegroups.com> <20050706184251.GT12095@itea.ntnu.no> Message-ID: "Stian S?iland" wrote in message news:20050706184251.GT12095 at itea.ntnu.no... On 2005-07-06 02:46:27, George Sakkis wrote: >> So, who would object the full-word versions for python 3K ? >> def -> define >> del -> delete >> exec -> execute >> elif -> else if >Objections for the "else if" might be that it sounds like you can >replace "else if" with "else x=94" if you want. Thumbs up for "else if" >because it explains what it is much better than "elif". "elseif" ? Today, on pydev list, in thread Chaining try statements: eltry?, Guido said 'and in fact I sometimes think it was a mistake to introduce elif just to save typing "else if".' So maybe this will be reconsidered for 3.0 Terry J. Reedy From frozenee at gmail.com Fri Jul 15 14:50:44 2005 From: frozenee at gmail.com (frozenee at gmail.com) Date: 15 Jul 2005 11:50:44 -0700 Subject: problems with python 2.4 help Message-ID: <1121453444.143877.143140@g44g2000cwa.googlegroups.com> I've noticed that the listings in help don't take you to correct topic. anyone else have this problem? Is there a fix? From steven.bethard at gmail.com Fri Jul 29 16:26:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 29 Jul 2005 14:26:29 -0600 Subject: Hiding In-Reply-To: <1122662993.207041.89630@f14g2000cwb.googlegroups.com> References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> <1122662993.207041.89630@f14g2000cwb.googlegroups.com> Message-ID: Jason Drew wrote: > Also, I think using file("C:\file.txt") is now preferred > to open("C:\file.txt"). Guido has said he wants to keep open() around as the way to open a file-like object, with the theory that in the future open might also support opening non-files (e.g. urls). So open("C:\file.txt") is still fine, though isinstance(f, open) is probably not. ;) STeVe From tlesher at gmail.com Sun Jul 24 22:36:20 2005 From: tlesher at gmail.com (Tim Lesher) Date: 24 Jul 2005 19:36:20 -0700 Subject: what's wrong with my code using subprocess? References: Message-ID: <1122258980.611277.89900@z14g2000cwz.googlegroups.com> I see the same behavior as you do. On Windows, the wait() isn't hanging--what's happening is that the subprocess just never receives anything. I don't quite understand why, but it works fine when I change the "if" clause in receiver.py to this: if count >= 1000: p.communicate('exit') p.wait() break Note the final break: if this isn't here, the next for iteration raises an exception, as p.stdout has been closed by p.communicate. From paustin at eos.ubc.ca Sun Jul 31 13:26:57 2005 From: paustin at eos.ubc.ca (Philip Austin) Date: Sun, 31 Jul 2005 10:26:57 -0700 Subject: c/c++ extensions and help() References: <1122591137.423810.286960@f14g2000cwb.googlegroups.com> Message-ID: Robert Kern writes: > Lenny G. wrote: >> Is there a way to make a c/c++ extension have a useful method >> signature? Right now, help(myCFunc) shows up like: >> myCFunc(...) >> description of myCFunc >> I'd like to be able to see: >> myCFunc(myArg1, myArg2) >> description of myCFunc >> Is this currently possible? > > There really isn't a way to let the inspect module know about > extension function arguments. Just put it in the docstring. > The next release of boost.python should do this automatically: (http://mail.python.org/pipermail/c++-sig/2005-July/009243.html) >>> help(rational.lcm) Help on built-in function lcm: lcm(...) C++ signature: lcm(int, int) -> int >>> help(rational.int().numerator) Help on method numerator: numerator(...) method of boost_rational_ext.int instance C++ signature: numerator(boost::rational {lvalue}) -> int Regards, Phil From rkern at ucsd.edu Sun Jul 10 17:01:58 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 10 Jul 2005 14:01:58 -0700 Subject: computer algebra packages In-Reply-To: <20050710171221.GA29664@phenix.progiciels-bpi.ca> References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> <20050710171221.GA29664@phenix.progiciels-bpi.ca> Message-ID: Fran?ois Pinard wrote: > [Florian Diesch] >>Description: A user-friendly frontend for MAXIMA >> Mascyma is (trying to be) a user-friendly graphical frontend for the Computer >> Algebra System GNU MAXIMA. It is written in Python and provides two GUIs, >> one of which based on PyGTK, the other based on wxPython. > > I was not successful googling for this one. Would you have an URL handy? Note the deliberate spelling, and cut-and-paste. http://home.arcor.de/mulk/projects/mascyma/index.xhtml.de -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From lordverminard at gmail.com Wed Jul 27 23:13:28 2005 From: lordverminard at gmail.com (mustafa) Date: Thu, 28 Jul 2005 08:13:28 +0500 Subject: any thing to do??? In-Reply-To: <200507271944.02906.jstroud@mbi.ucla.edu> References: <200507271944.02906.jstroud@mbi.ucla.edu> Message-ID: James Stroud wrote: > The world needs an open source tool for working with DNA sequences > graphically. I know what needs to be done, but I am not finding much time to > do it. I have already coded a graphical sequence editor and some cool tools > for sequence analysis. For this project I am using Tkinter as the gui and > biopython as the main code-base. Right now, a critical thing to do would be > to use the Tkinter Canvas to draw plasmid maps. Don't worry if you don't know > what a plasmid is. It is a simple concept. If you want to become a hero to > thousands in a field with 0 competition, this is the place. If you are > interested, let me know. Maybe we can find a way to harness your time and > enthusiasm. If you are good at organization, maybe you could help to turn > this into a true open source project that interfaces with biopython. (Does > anybody recognize the plea-for-help aspect of my message?) > > James > > On Wednesday 27 July 2005 08:00 am, mustafa wrote: > >>i hav just finished learning pythob from "A byte of python"(an online >>book) so i wanted to apply my new skills. to learn and to have some fun. >>is there any place which lists jobs to be done...you know minor jobs and >>requests thats nobody has found time to do. >>i would point out that i am not looking for a JOB as job with payment. >>i am looking for a JOB that is to be done and nobody has done it yet. >> >>also aside from this is there any other way i could use python and >>improve. i figure this practice will make me a lot better. but if anybody >>else has any ideas than that would be good too . > > sounds great. umm so i need to learn tinkter. well i guess i'll get started on it. and i hope i can help. From roccomoretti at hotpop.com Thu Jul 21 09:55:03 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 21 Jul 2005 08:55:03 -0500 Subject: goto In-Reply-To: <86y881qcol.fsf@bhuda.mired.org> References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <86psterxi3.fsf@bhuda.mired.org> <86y881qcol.fsf@bhuda.mired.org> Message-ID: > My "favorite" infinte loop with while is: > > i = 0 > while i < 20: > do_process(i) > > Note the prominent *lack* of any change to i here? > > Oh, for: > > from i = 0 > invariant 0 <= i <= 20 > variant 21 - i > until i > 19 > loop > do_process(i) > > which throws an exception at the beginning of the second loop. What language is that from? I take it the exception is from the "21-i" not changing as it goes around the loop, right? (But why can't "variant i" work just as well?) From williams13 at llnl.gov Mon Jul 25 15:37:50 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Mon, 25 Jul 2005 12:37:50 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050722164420.GA1912@tishler.net> References: <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <20050722164420.GA1912@tishler.net> Message-ID: <42E53F8E.5080406@llnl.gov> Hi Jason, To get "import socket" to work in Python2.4, I had to do something that I never recomend and that is hack the Python code. Since I need this to work for someone that is going on travel, I just modified the socketmodule.c file. REPLACE: /* Irix 6.5 fails to define this variable at all. This is needed for both GCC and SGI's compiler. I'd say that the SGI headers are just busted. */ #if defined(__sgi) && !defined(INET_ADDRSTRLEN) #define INET_ADDRSTRLEN 16 #endif WITH: #define INET_ADDRSTRLEN 16 This is a temporary fix until the Cygwin build works. Best regards, Dean >Dean, > >On Fri, Jul 22, 2005 at 05:11:45AM -0700, Dean N. Williams wrote: > > >>I downloaded your new Cygwin from http://cygwin.com and tried to build >>install Python/CDAT again. It appears to have built properly, but when >>I try to execute, it receive a sock error. How do I get around this >>problem? >> >> > >I don't know -- it is not clear what you are trying to do. Are you >trying to build Cygwin Python or just CDAT? > >On Fri, Jul 22, 2005 at 07:09:08AM -0700, Dean N. Williams wrote: > > >>To be more specific. If I try to import socket I get the "ImportError: >>No module named _socket". What do I need to install from Cygwin in >>order for this to work? >> >> > >AFAICT, nothing. The above seems to indicate your Python installation >is broken. > >Jason > > > From mwm at mired.org Tue Jul 19 23:31:00 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 19 Jul 2005 23:31:00 -0400 Subject: email format in python References: <20050718102120.64241.qmail@web42004.mail.yahoo.com> Message-ID: <86br4yrw5n.fsf@bhuda.mired.org> Jorgen Grahn writes: > Agree. In the case of user input validation, it might be ok to politely > inform the user that the address looks a bit funny, but refusing to work > with it will anger a user sooner or later. Yup. I use cryptographically signed addresses as one-time addresses for web forms. They look like mwm-keyword-site.com.2fef70 at mired.org. It really annoys me when some site decides that that can't be my real email address. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dave at pythonapocrypha.com Tue Jul 5 17:35:22 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 05 Jul 2005 15:35:22 -0600 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <42CAFD1A.5090406@pythonapocrypha.com> seberino at spawar.navy.mil wrote: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. > > It got me curious if Lisp > is inherently faster to develop complex apps in. It would seem if you > could create your own language in Lisp using macros that that would be > quite an advantage.... > > I realize that Python has operator overloading and OOP so I'm not sure. > > Any ideas? Any *evidence* one way or another? Well, his Viaweb company was founded in about '95, right? So he probably just used Lisp because Python wasn't as well known yet. ;-) IMO one of Python's strengths over Lisp is that it plays well with many other technologies. It should be remembered that Graham's use of Lisp in Viaweb was in building a web application, so that Lisp's main links to the "outside world" were the filesystem and Apache. They didn't use a database, and Apache had to be modified in order to work with Lisp. From daniel.dittmar at sap.corp Wed Jul 20 07:11:04 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 20 Jul 2005 13:11:04 +0200 Subject: is a file open ? In-Reply-To: References: Message-ID: luis wrote: > for root, dirs, files in os.walk(path): > for file in files: > # ? is opened ? On Linux and some other Unixes, you can probably read the /proc filesystem. On Windows, you'll probably get the quickest result by running handle.exe (http://www.sysinternals.com/Utilities/Handle.html). Either way, the information you'll get is restricted by your permissions. Either information will get stale really fast, so it's not suitable if your task is something like 'can I backup this directory or is someone writing to a file?' Daniel From ed at leafe.com Sat Jul 30 18:25:55 2005 From: ed at leafe.com (Ed Leafe) Date: Sat, 30 Jul 2005 18:25:55 -0400 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <200507301825.55095.ed@leafe.com> On Saturday 30 July 2005 17:44, Jorge Godoy wrote: > Bar and line graphics, mainly. ?In an easy and portable way. ?Something > that calculates the axis scales automatically, that allows users to change > some information, add legends, put values in specific points and all those > things that are common to business graphs. OIC - I thought that you were referring to a specific part of wxPython that we haven't wrapped yet. I'll defer this to my partner, Paul McNett. He's spearheading the reporting module for Dabo, and may know of some tools that are already out there that could generate the image, which Dabo could then display. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From edvard+news at majakari.net Sat Jul 16 15:12:34 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Sat, 16 Jul 2005 22:12:34 +0300 Subject: How can I import a py script by its absolute path name? References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> <87ackpeeag.fsf@titan.staselog.com> <42d7ee79$0$809$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <871x5yy38d.fsf@titan.staselog.com> "J.Bijsterbosch" writes: > Hmm, what you call special treatment comes from pythons deep underlying C > and C++ language heietidge I presume. A backslash in a C or C++ string means > the following character is a so called escape character, like \n represents > a newline and \r a return to the beginning of a line. > If you really want a backslash you need to type it twice like so \\. Has > nothing to do with Windows...;-)) Yes, I'm well aware of that. However, you can say that using '\' as a path separator needs special treatment, because it is conventionally treated as an escape character. Moreover, I wans't the one asking for information, I have privilidge to use real operating systems as a programming platform. Thanks for enthsiasm, though :) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! You shouldn't verb verbs. From roy at panix.com Fri Jul 22 14:08:42 2005 From: roy at panix.com (Roy Smith) Date: 22 Jul 2005 14:08:42 -0400 Subject: return None References: <3kcpbbFtjttlU1@individual.net> Message-ID: In article <3kcpbbFtjttlU1 at individual.net>, Ximo wrote: >Can I do a function which don't return anything? > >The question is that, if I do a function that have a return or without >return, it returns always "None", but i want that it doesnt return me >nothing What do you mean by "don't return anything", as oppossed to returning None? Let's say I had one of those functions, and did: foo = noReturnValue() print foo what would you expect (want?) to happen? From solar at infidel.ixx Sun Jul 24 16:46:09 2005 From: solar at infidel.ixx (James David) Date: Sun, 24 Jul 2005 20:46:09 GMT Subject: How to run python script in background after i logout References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> Message-ID: "Harlin Seritt" wrote in message news:1122198224.635804.316950 at g49g2000cwa.googlegroups.com... > I have a remote linux server where I can only access it via ssh. I have > a script that I need to have run all the time. I run like so: > > python script.py & > > It runs fine. When I log off ssh I notice that the script died when I > logged off. How do I make sure it stays running? It sounds like you want to run your script as a daemon. There are ways to do this and it is more of a *nix issue, but google "python" and "run as a daemon". Also check out the createDaemon() function. From peter at engcorp.com Sun Jul 3 17:12:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 17:12:31 -0400 Subject: What are the other options against Zope? In-Reply-To: References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> <6f-dnTeTQayMRVvfRVn-jQ@powergate.ca> Message-ID: Florian Lindner wrote: >>>Peter Hansen wrote: >>>>[Zope] doesn't include >>>>database interfaces other than to its own ZODB. > > Ok, you're right. But I don't really think it makes a difference to install > them afterwards. Probably not, but until the OP sheds more light on what this "companies proprietary database" actually is, and what "googling" means, none of us can do more than guess as to what would make a difference or not... -Peter From peter at engcorp.com Mon Jul 4 09:43:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Jul 2005 09:43:05 -0400 Subject: python project layout In-Reply-To: References: <9JqdnRP9IqxM_ljfRVn-rA@powergate.ca> Message-ID: Huron wrote: > Hi Peter, > Thanks for you detailed reply. > The layout that you suggest sounds wise to me (I'm about to start a > project). I wouldn't necessarily recommend something so complex (not that it's particular complex, but it's more than just "flat") for a newcomer, however. One of the few small issues you have to deal with in order to get such a layout working properly is the "python path" issue, and how to import modules that are in another folder. Normally (aside from the standard library and extensions) only the current directory is in sys.path. Any subfolders that contain __init__.py modules are "packages" and you can import from them using the "dotted" notation (e.g. "import mypkg.mymodule" will try to load a file from ./mypkg/mymodule.py if there is also a ./mypkg/__init__.py (even if that file is empty!)). To import a module in the *parent* directory, however, is another story entirely. You need to get it added to the sys.path, and that's one of the things done (dynamically) by our test utilities, so we can be in the tests subfolder and type "story015.py" and have it load modules in the parent folder. So in short, start simple and let your layout evolve as you need it to. Don't try to start with a more complex layout than you need or know how to handle. And if you're using a revision control system like Subversion (and you better be using something! :-) ) then it's an easy matter to rename or move folders at a later time, without losing your revision history. -Peter From Peter.Vandersteegen at gmail.com Tue Jul 12 08:31:49 2005 From: Peter.Vandersteegen at gmail.com (peter) Date: 12 Jul 2005 05:31:49 -0700 Subject: relative import packages/modules workaround In-Reply-To: References: <1121091566.327885.147380@g49g2000cwa.googlegroups.com> Message-ID: <1121171509.141112.212090@g44g2000cwa.googlegroups.com> hmm, it seems to be less trivial than you mentioned... hopefully this will be introduced fast in python From steve at REMOVETHIScyber.com.au Sat Jul 2 23:37:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 13:37:26 +1000 Subject: math.nroot [was Re: A brief question.] References: Message-ID: On Sun, 03 Jul 2005 02:22:23 +0200, Fredrik Johansson wrote: > On 7/3/05, Tom Anderson wrote: >> That's one way. I'd do: >> >> root = value ** 0.5 >> >> Does that mean we can expect Guido to drop math.sqrt in py3k? :) > > I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) > gives 3.9999999999999996, and this error could be avoided. py> 64**(1/3.0) 3.9999999999999996 Use the fact that if z = x**y, log(z) = y*log(x). py> import math py> math.exp(1/3.0*math.log(64)) 3.9999999999999991 That's even less accurate. py> math.exp(math.log(64)/3.0) 4.0 Success!!! Another (random-ish) example: py> 17**5 1419857 py> 1419857**(1.0/5) 17.000000000000004 py> math.exp(math.log(1419857)/5.0) 17.0 def nroot(x, y): """Returns the yth root of x. More accurate than using x**(1/y). Handles most, but not all, edge cases correctly. (Does not check for y as either negative zero or negative infinity.) """ if x < 0.0: raise ValueError("Complex valued result.") if y == 0.0: # x**inf if x > 1.0: try: return float("inf") except: try: return 1.0/0.0 except: raise ValueError("Overflow") elif x == 1.0: # 1**N = 1 for any positive N return 1.0 else: # 0**N = 0 for any non-zero N return 0.0 # check the limiting case where y is positive infinity if 1.0/y == 0.0: # x**0 = 1 for all real x (including the limiting case x = 0) return 1.0 if x == 0.0: # 0**N = 0 for any non-zero N return 0.0 else: return math.exp(math.log(x)/y) Note how much simpler this would be if we could guarantee proper infinities and NaNs in the code. We could turn a 23-line block to a one-liner. -- Steven. From gene.tani at gmail.com Tue Jul 19 09:04:00 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jul 2005 06:04:00 -0700 Subject: Python IDE In-Reply-To: References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121777586.893304.83560@g49g2000cwa.googlegroups.com> you have an embarassment of riches (i think that's the phrase) http://wiki.python.org/moin/IntegratedDevelopmentEnvironments also try Eric and Komodo (the other $30 IDE with free trial). From edvard+news at majakari.net Tue Jul 12 04:38:51 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Tue, 12 Jul 2005 11:38:51 +0300 Subject: Should I use "if" or "try" (as a matter of speed)? References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> <11d0e158o1g8554@news.supernews.com> <18fearebf2js6$.9oemdgamm06p.dlg@40tude.net> Message-ID: <871x64ifl0.fsf@titan.staselog.com> Thorsten Kampe writes: > Speed considerations and benchmarking should come in after you wrote > the program. "Premature optimisation is the root of all evil" and > "first make it work, then make it right, then make it fast" (but only > if it's not already fast enough) - common quotes not only with Python > developers. Just a minor note: regarding quote "first make it work, then make it right, then make it fast" Shouldn't one avoid doing it the wrong way from the very beginning? If you make it "just work" the first time, you'll probably use the old code later on because "functionality is already there" and temptatation to build on probably relatively bad architecture can be too strong. How about First make it work (but avoid ad-hoc designs), then make it right, then make it fast Of course, such emphasis doesn't go well with classic idioms.. (yeah, programmer's block at the moment: I should clean up a 120+ -line if-elif-elif-elif... else -block which tests a single variable and calls different methods with variable number of parameters depending on the value of the variable - guess I should apply command pattern or similar...) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From rkern at ucsd.edu Thu Jul 28 18:35:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 15:35:54 -0700 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Michael Hoffman wrote: > Aahz wrote: > >>>One of these days I'm going to figure out how to embody "Namespaces are >>>one honking great idea -- let's do more of those!" Then I shall be >>>enlightened. >> >>What don't you understand about it? (This is a serious question -- I >>can think of several answers to give you, but want to know what focus is >>needed first.) > > I wasn't expecting a serious answer to this, but here goes. > > First, I wasn't a Python user when namespaces were introduced. It's hard > for me to even imagine Python without namespaces. Did imported modules > just go into the same namespace as everything else? Yuck. It's too bad > this happened before there were PEPs so I could understand the design > and what came before. I'm pretty sure that namespaces are fundamental to the design of Python. I don't think there was any "before namespaces." > Is it the fact that Python is unimaginable without namespaces that makes > them such a honking great idea? Aren't they somewhat of an obvious idea? > Several other languages have them. > > Was the implementation of namespaces easy or hard to explain? It isn't just that Python has namespaces, but that they are the implementation for quite a lot of things. Modules: namespaces. Classes: namespaces. Instances: namespaces. Scope: namespaces. It's a very elegant way to handle a broad class of language features very consistently. That said, I made a boo-boo. The Zen of Python is really a set of design principles (and some of them, like this one, are more specifically *language* design principles), not Essential Development Practices. That'll teach me to not RTFA. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rorley at gmail.com Tue Jul 12 11:42:20 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 08:42:20 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121182769.717165.36690@f14g2000cwb.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> <1121182769.717165.36690@f14g2000cwb.googlegroups.com> Message-ID: <1121182939.929697.104220@g47g2000cwa.googlegroups.com> Yes, I am. Does that make it harder. From thanos at sians.org Sun Jul 24 07:04:58 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 14:04:58 +0300 Subject: Initializing interactive Python In-Reply-To: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> References: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> Message-ID: <20050724110458.GA32101@zermelo.sians.org> On Sun, Jul 24, 2005 at 03:26:06AM -0700, qwweeeit at yahoo.it wrote: > Hi all, > is it possible to enter an interactive session and automatically > do some initialization? set the enviroment variable PYTHONSTARTUP to point to a startup.py of your own, where you put all your initializations.. HTH -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From eurleif at ecritters.biz Fri Jul 8 20:02:20 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 09 Jul 2005 00:02:20 GMT Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Well, I want to offer a more radical proposal: why not free squared > braces from the burden of representing lists at all? It should be > sufficient to write > >>>>list() > > list() So then what would the expression list('foo') mean? Would it be equivalent to ['foo'] (if so, how would you convert a string or other iterable to a list under Py3k?), or would it be equivalent to ['f', 'o', 'o'] as it is in now (and is so, what gives?)? From itsoooook at yahoo.com Wed Jul 27 07:08:39 2005 From: itsoooook at yahoo.com (itsoooook at yahoo.com) Date: 27 Jul 2005 04:08:39 -0700 Subject: stuff from it Message-ID: <1122462519.813555.211860@g44g2000cwa.googlegroups.com> can i have my money back all i did was come across your site on top of that buy stuff from it From gsakkis at rutgers.edu Sat Jul 9 12:46:07 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Jul 2005 09:46:07 -0700 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> Message-ID: <1120927567.463458.289770@g49g2000cwa.googlegroups.com> "Raymond Hettinger" wrote: > In all probability, both list comprehensions and generator expressions > will be around in perpetuity. List comps have been a very successful > language feature. > > The root of this discussion has been the observation that a list > comprehension can be expressed in terms of list() and a generator > expression. No, the root of the discussion, in this thread at least, was the answer to "why not dict comprehensions ?", which was along the lines of "well, you can do it in one line by dict(gen_expression)". > However, the former is faster when you actually want a > list result and many people (including Guido) like the square brackets. Also dict comprehensions are faster if you actually want a dict result, set comprehensions for set result, and so on and so forth. > After the advent of generators, it seemed for a while that all > functions and methods that returned lists would eventually return > iterators instead. What we are learning is that there is a place for > both. Altering the result type of existing functions and methods is not exactly the same with the discussion on the future of list comprehensions; the latter affects only whether listcomps are special enough to be granted special syntax support, when there is an equivalent way to express the same thing. It's funny how one of the arguments for removing lambda -- you can do the same by defining a named function -- does not apply for list comprehensions. > It is darned inconvenient to get an iterator when you really > need a list, when you want to slice the result, when you want to see a > few elements through repr(), and when you need to loop over the > contents more than once. > > Raymond Hettinger Similar arguments can be given for dict comprehensions as well. George From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 08:10:52 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 14:10:52 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: <3l192cF109df7U1@individual.net> Ivan Van Laningham wrote: > Hi All-- > > Tony Meyer wrote: >> >> So far, there have been various statements that look like +0 for __div__, >> but no-one with a +1. (And I've said this a couple of times now, which >> really is just trolling for a +1 from someone). >> >> > It's not a question of saving characters, but readability which, as >> > you've said, is a matter of opinion. >> > > I like / as a shortcut to joinwith(). I like it a lot. I like it so > much I'll give you a +2. Add a +1 from me. >> (Those who are offended by sweeping generalisations should ignore this next >> bit) >> >> I think it's also worth considering that Windows users are more clueless >> than users of posix systems. The readability of __div__ comes from >> familiarity with posix filesystems; for a Windows user, \ would be the >> natural character. So we're making things more readable for users that are >> already more likely figure things out, and less readable for users that have >> trouble figuring things out. >> > > This is not only bullshit, it's elitist bullshit. "Windows users are > more clueless than users of posix systems." Pfui. Prove it or withdraw > it. Above all, nobody can tell me that there's any programmer who doesn't instantly recognize '/' as a directory separator. Reinhold From tjreedy at udel.edu Fri Jul 22 13:13:49 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Jul 2005 13:13:49 -0400 Subject: use libs from one of two releases References: <001c01c58ed6$30dd9260$1603a8c0@avc> Message-ID: "Alberto Vera" wrote in message news:001c01c58ed6$30dd9260$1603a8c0 at avc... >I have two versions of Python. They were intalled in two different >folders. (python22 and python23) >I have an old py that works in an older version. I presume you mean older than 2.2 > How can I change my old py to use libs of python22? Running it with Py2.2 should work. Exactly how you do that depends on the OS. TJR From daniel.dittmar at sap.corp Fri Jul 22 12:36:10 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 22 Jul 2005 18:36:10 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Duncan Booth wrote: > I would have expected a > path object to be a sequence of path elements rather than a sequence of > characters. Maybe it's nitpicking, but I don't think that a path object should be a 'sequence of path elements' in an iterator context. This means that for element in pathobject: has no intuitive meaning for me, so it shouldn't be allowed. Daniel From invalidemail at aerojockey.com Sun Jul 24 17:58:35 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 24 Jul 2005 14:58:35 -0700 Subject: Path inherits from basestring again In-Reply-To: <3kf4kmFsu26jU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> Message-ID: <1122242315.275407.9500@g44g2000cwa.googlegroups.com> Reinhold Birkenfeld wrote: > Peter Hansen wrote: > > Reinhold Birkenfeld wrote: > >> One thing is still different, though: a Path instance won't compare to a regular > >> string. > > > > Could you please expand on what this means? Are you referring to doing > > < and >= type operations on Paths and strings, or == and != or all those > > or something else entirely? > > All of these. Do you need them? [snip] > At the moment, I think about overriding certain string methods that make > absolutely no sense on a path and raising an exception from them. Ick. This reeks of the sort of hubris from people who think they anticipate all valid uses of something. Is it a basestring or not? If it is, then let it be a basestring. It is unreasonable to want to format a pathame for printing? We might want to retain ljust and friends. Maybe there's a filenaming scheme where files are related by having a character changed here or there. So we might want to iterate though the characters in a pathname. How do you know how people are going to use it? We're all supposed to be adults here. Let me suggest that wanting to remove all these methods/operations suggests that one doesn't really think it ought to be a basestring. The way I see it, the only compelling reason for it to be a basestring is to accommodate poorly designed functions that test whether an argument is a filename or a file object using isinstance(basestring,x) on it. But the best thing to do is fix those interfaces, and let path be what it should be, and not a hack to accommodate poor code. -- CARL BANKS From lbates at syscononline.com Wed Jul 13 11:05:35 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 13 Jul 2005 10:05:35 -0500 Subject: String Manipulation In-Reply-To: <1121265538.351527.158950@f14g2000cwb.googlegroups.com> References: <1121265538.351527.158950@f14g2000cwb.googlegroups.com> Message-ID: <42D52DBF.9080605@syscononline.com> Use .replace function to replace punctuation (you didn't say exactly what that means but just to get you started): # # Extend this list as needed # punctuations=',.;:()' # # Open input and output files # ifp=open(inputfilename,'r') ofp=open(outputfilename,'w') # # Strip out the punctuation characters # for line in ifp: for punctuation in punctuations: line=line.replace(punctuation,'') ofp.write(line) # # I'll leave the other part for homework but # you will need to use the .find method of the string # ifp.close() ofp.close() Larry Bates Michael Jordan wrote: > i'll be straight with you and say that this is a homework assignment. > ive tried to figure it out on my own but am now out of time. > > i need to go through a .txt file and get rid of all punctuation. also, > every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is > ANY number i need to get rid of that also. thanks a bunch. hurry > please! > > jen :) > From exarkun at divmod.com Sun Jul 3 15:15:12 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 3 Jul 2005 15:15:12 -0400 Subject: Using regular expressions in internet searches In-Reply-To: <1120412943.283248.100700@g14g2000cwa.googlegroups.com> Message-ID: <20050703191512.26278.3747857.divmod.quotient.4968@ohm> On 3 Jul 2005 10:49:03 -0700, mike.ceravolo at gmail.com wrote: >What is the best way to use regular expressions to extract information >from the internet if one wants to search multiple pages? Let's say I >want to search all of www.cnn.com and get a list of all the words that >follow "Michael." > >(1) Is Python the best language for this? (Plus is it time-efficient?) >Is there already a search engine that can do this? > >(2) How can I search multiple web pages within a single location or >path? > >TIA, > >Mike > Is a google search for "site:cnn.com Michael" not up to the task? Jp From fdeserres at gmx.net Fri Jul 15 06:29:57 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Fri, 15 Jul 2005 12:29:57 +0200 Subject: Documenting extension modules? Message-ID: <42D79025.4000405@gmx.net> Hiho, I can't seem to find a proper way to document my extension module. Following the C API doc: static PyMethodDef ioMethods[] = { {"o_count", o_count, METH_VARARGS, "Return the count of available MIDI outputs."}, .... } lacks: a) module level documentation b) function parameters Also, I'd like to know if there's a typical format for the help string (but in C), compatible with docstring's """short desription long description""" Any pointers please? TIA, Francois From __peter__ at web.de Fri Jul 29 13:11:51 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Jul 2005 19:11:51 +0200 Subject: can list comprehensions replace map? References: Message-ID: Andrew Dalke wrote: > Peter Otten wrote: >> Combining your "clever" and your "elegant" approach to something fast >> (though I'm not entirely confident it's correct): >> >> def fillzip(*seqs): >> def done_iter(done=[len(seqs)]): >> done[0] -= 1 >> if not done[0]: >> return >> while 1: >> yield None >> seqs = [chain(seq, done_iter()) for seq in seqs] >> return izip(*seqs) > > Ohh, that's pretty neat passing in 'done' via a mutable default argument. > > It took me a bit to even realize why it does work. :) Though I would never have come up with it, were it not for the juxtaposition of your two variants (I initially disliked the first and tried to improve on the second), it is an unobvious merger :) It's a bit fragile, too, as > Could make it one line shorter with > from itertools import chain, izip, repeat > def fillzip(*seqs): > def done_iter(done=[len(seqs)]): > done[0] -= 1 > if not done[0]: > return [] > return repeat(None) > seqs = [chain(seq, done_iter()) for seq in seqs] > return izip(*seqs) that won't work because done_iter() is now no longer a generator. In effect you just say seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], [])] I tried class Done(Exception): pass pad = repeat(None) def fillzip(*seqs): def check(active=[len(seqs)]): active[0] -= 1 if not active[0]: raise Done # just to turn check() into a generator if 0: yield None seqs = [chain(seq, check(), pad) for seq in seqs] try for item in izip(*seqs): yield item except Done: pass to be able to use the faster repeat() instead of the while loop, and then stared at it for a while -- in vain -- to eliminate the for item... loop. If there were a lazy ichain(iter_of_iters) you could tweak check() to decide whether a repeat(None) should follow it, but I'd rather not ask Raymond for that particular addition to the itertools. > Now add the performance tweak.... > > def done_iter(done=[len(seqs)], forever=forever, table=table) > > Okay, I'm over it. :) Me too. I think. For now... Peter From gdamjan at gmail.com Fri Jul 15 13:15:16 2005 From: gdamjan at gmail.com (Damjan) Date: Fri, 15 Jul 2005 19:15:16 +0200 Subject: ANN: CherryPy-2.1.0-beta released References: <1121379013.118775.278510@g49g2000cwa.googlegroups.com> Message-ID: <42d7eecf_1@x-privat.org> > I am happy to announce the first beta release of CherryPy-2.1 Can you briefly compare CherryPy to Quixote2 (+session2)? > unicode decoding/encoding, This especially interesting to me. Is CherryPy completelly unicode (and UTF-8) ready. The thing that frustrates me about quixote2 is that it has a lot of assumptions that text is a str object in the latin1 encoding. I succeded to patch quixote to be usable but that may not be enough. My quixote application works with unicode objects all the time, and the only place I want UTF-8 is when the content is sent to the client... (or when its stored in a database or file which I handle myself fine). -- damjan From roccomoretti at hotpop.com Thu Jul 7 16:24:05 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 07 Jul 2005 15:24:05 -0500 Subject: Python Module Exposure In-Reply-To: References: Message-ID: Robert Kern wrote: > Jacob Page wrote: > >> Does this newsgroup find attachments acceptable? > > No. Please put files somewhere on the web and post a URL. This would be > a good forum to informally announce and discuss your module. To add to what Robert said, keep in mind this newsgroup is also mirrored to a mailing list, so posting anything but example code snippets would quickly fill up people's inboxes. From jsbraich at gmail.com Tue Jul 19 14:50:02 2005 From: jsbraich at gmail.com (jb) Date: 19 Jul 2005 11:50:02 -0700 Subject: popen2 usage Message-ID: <1121799002.440543.206050@g43g2000cwa.googlegroups.com> Hi there: I need help with popen2 usage. I am coding on Windows 2000 environment and I am basically trying to run command line executable program that accepts command line arguments from user. I want to be able to provide these arguments through input pipe so that executable does not require any intervention from the user. The way I am doing this is as below: out1, in1 = popen2.popen2("testme.exe > abc.txt") in1.write('-test1') in1.flush() in1.close() But this does not seem to be working, when I open abc.txt file it does not show '-test1' argument that was supplied via in1.write method. This causing executable to wait forever unless user manually kills the process. Please help Regards, jb From reinhold-birkenfeld-nospam at wolke7.net Thu Jul 21 17:56:18 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 21 Jul 2005 23:56:18 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> Message-ID: <3kak02FtfejbU2@individual.net> Michael Hoffman wrote: > mkent at webmd.net wrote: >> I really love Jason's 'path' module. Sadly, I've encountered a serious >> problem with using it. When you try to 'freeze' an application module, >> and Jason's 'path' module is present in any of the directories that are >> looked at by freeze's module finder (your app doesn't have to import >> it), freeze goes into an infinite loop of imports, eventually getting a >> 'maximum recursion depth' exception. This seems to be related to >> freeze getting confused between 'os.path' and Jason's 'path'. >> >> I encountered this using Jason's latest 'path' module and Python 2.3.2. >> I was able to solve it for my use by renaming path.py to newpath.py >> and using 'from newpath import path' in my modules. >> >> I've just notified Jason about this. I presume a solution like mine >> will be used, and look forward to seeing Jason's module in stdlib. > > This sounds like a bug in "freeze" rather than something that should be > worked around in the standard library. Although there have already been > people opposed to naming it path because the duplication with os.path > might confuse humans. As the most likely placement will be a class named "Path" inside the "os.path" module, that bug with freeze won't apply to the "stdlib version" of Path. Reinhold From hancock at anansispaceworks.com Tue Jul 5 11:10:47 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 10:10:47 -0500 Subject: math.nroot [was Re: A brief question.] In-Reply-To: <42C8B151.2010503@REMOVEMEcyber.com.au> References: <42C8B151.2010503@REMOVEMEcyber.com.au> Message-ID: <200507051010.47079.hancock@anansispaceworks.com> On Sunday 03 July 2005 10:47 pm, Steven D'Aprano wrote: > Any floating point package that supports the IEEE > standard should give you a test to see if a float > represents a NaN. That's what you need. You certainly > can't rely on "x == SOME_NAN" because there are 254 > different NaNs. > > There is no sensible reason to test equality of NaNs. > It is logically nonsense to say that one NaN is equal > to another, as such a thing implies contradictions like > -1==-2. If you support IEEE, you will have a test for > NaNs, so you can detect them when you need to. I have to mention that the idea of a math package that allows NaN to propagate as though it were a number scares the willies out of me. God help me if I were to use it on something like Engineering where lives might depend on the answer being right. That'd be like having a math package that allowed, say 0/0 = 1 or Inf/Inf = 1. It's not hard at all to come up with dozens of problems for which that is the WRONG guess -- getting an actual answer for dividing two infinities requires using limits and calculus. The reason Inf/Inf isn't defined is that it can actually be just about any number --- finite or infinite. I can seriously imagine structures breaking and collapsing because they were designed using such a package, and a NaN was generated and missed somewhere. Really, the only *right* thing to do is to raise an exception ASAP after the NaN comes up. On a more practical note, *is* there a isNaN() function? Seems like it ought to be in the math module. Looks like you have to do it through "fpectl" as things stand. Is anyone else bothered that "math" and "cmath" are in the "Miscellaneous Services" section of the LR? Seems like we ought to get Numeric and/or Numarray and group all of these in a separate "Math & Science" section. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From olivier89.antispam at neuf.fr Mon Jul 25 06:00:17 2005 From: olivier89.antispam at neuf.fr (Olivier) Date: Mon, 25 Jul 2005 12:00:17 +0200 Subject: multilanguage site and user informations edition Message-ID: <42e4b845$2$13224$636a15ce@news.free.fr> i need to create a multilinguage site and i need help : first i want to know what is the best and simple solution for a multilinguage site with plone 2? i want some tutorial, how to and if possible exemple next i need to modify the user standard information to put my personnal information like address, phone numbre, city, ... and i want to modify the search member form to find member by all information like city. if anyone can help me please give me a link to a faq or how to . thanks PS: Sorry for the english. From darkcowherd at gmail.com Tue Jul 12 11:47:59 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Tue, 12 Jul 2005 21:17:59 +0530 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: <5f4d3cb5050712081414d59aca@mail.gmail.com> References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: <5f4d3cb505071208471c22ddb6@mail.gmail.com> I use Delphi in my day job and evaluating and learning Python over the weekends and spare time. This thread has been very enlightening to me. The comments that Joel of Joel on Software makes here http://www.joelonsoftware.com/items/2003/10/13.html was pretty convincing. But I can see from the comments made by various people here that since Python uses Duck typing and encourages typless styles of functions exceptions may actually be the better way to go. But one advise that he gives which I think is of great value and is good practice is "Always catch any possible exception that might be thrown by a library I'm using on the same line as it is thrown and deal with it immediately." DarkCowherd From cam.ac.uk at mh391.invalid Thu Jul 21 11:39:40 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 16:39:40 +0100 Subject: PEP on path module for standard library Message-ID: Many of you are familiar with Jason Orendorff's path module , which is frequently recommended here on c.l.p. I submitted an RFE to add it to the Python standard library, and Reinhold Birkenfeld started a discussion on it in python-dev . The upshot of the discussion was that many python-dev'ers wanted path added to the stdlib, but Guido was not convinced and said it must have a PEP. So Reinhold and I are going to work on one. Reinhold has already made some changes to the module to fit the python-dev discussion and put it in CPython CVS at nondist/sandbox/path. For the PEP, do any of you have arguments for or against including path? Code samples that are much easier or more difficult with this class would also be most helpful. I use path in more of my modules and scripts than any other third-party module, and I know it will be very helpful when I no longer have to worry about deploying it. Thanks in advance, -- Michael Hoffman From dbickett at gmail.com Wed Jul 27 10:22:18 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Wed, 27 Jul 2005 14:22:18 +0000 Subject: Safest manner to extend search path for modules? In-Reply-To: <1122353419.940318.226640@g47g2000cwa.googlegroups.com> References: <1122353419.940318.226640@g47g2000cwa.googlegroups.com> Message-ID: <1d6cdae305072707227ed062cf@mail.gmail.com> On 25 Jul 2005 21:50:20 -0700, Joseph Turian wrote: > What is the safest manner to extend search path for modules, minimizing > the likelihood of shooting oneself in the foot? Put a .pth file in a directoy already on the system path. http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/ -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From thomasbartkus at comcast.net Mon Jul 11 10:10:44 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 11 Jul 2005 09:10:44 -0500 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> Message-ID: <65ydnYOWkP_L4E_fRVn-qQ@telcove.net> wrote in message news:1120603785.494300.180940 at g49g2000cwa.googlegroups.com... > > > Well, his Viaweb company was founded in about '95, right? So he probably just > > used Lisp because Python wasn't as well known yet. ;-) > > David > > That is what I thought too. It makes sense but I wasn't sure. Still > ain't. > The problem is that questions like 'What lang is fastest to develop > in?' > are hard to answer definitively. No it's not. The answer is always whatever language you enjoy the most and know the best. That's a somewhat redundant statement because if you enjoy a language, you are highly motivated to use it often and learn it well. An intimate knowledge of any particular language is *far* more important than the syntactic and semantic arcana that people usually argue over. So - what the question really boils down to is which language(s) have the best balance of approachability (easy to learn!) and capability. Bear in mind though, that if the language sacrifices capability in favor of being easy, then the fun runs out of it too soon :-) Thomas Bartkus From bokr at oz.net Sun Jul 10 18:26:46 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 10 Jul 2005 22:26:46 GMT Subject: AST decoration vs byte-code-munging (Was: Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: <42d18ecf.322314173@news.oz.net> On Sun, 10 Jul 2005 16:26:24 -0400, "Terry Reedy" wrote: > >"Ralf W. Grosse-Kunstleve" wrote in message >news:20050710133959.83611.qmail at web31512.mail.mud.yahoo.com... > >I have a suggestion I don't remember seeing for flagging which vars to >autoinit without new syntax: use '_' instead of '.'. I have never seen >local vars with a leading '_'. So, in combination with whatever other >mechanism (metaclass, __init__ decorator?) > > def __init__(self, _x, y, _z) : > >would automatically do self.x = _x, self.z = _z, but not self.y = y. > Of course, if it works for __init__, it should work for an arbitrary method or even function (if a decorator is used). I think I could write a byte-code-modifying decorator that would insert code at the beginning of a function to do the self.x = _x; self.z = _z # but not self.y = y in your example, and similarly for others. But I am not sure it's not a waste of time to do these byte-code things except to see how using such decorators feels in practice, or whether any byte-code munging after generation is a good idea. What would be the next step? To implement the same in C as a built in decorator? I'm wondering if the effort of munging byte code isn't misplaced, and would create a growing maintenance problem as more built-in decorators like that accumulated. So, if we want alternate code generated, perhaps we need a way of talking to the original code generation process? I'm thinking some kind of source-processing-time decorator (maybe marked with double-@, like @@auto_init_self_attributes def __init__(self, _x, y, _z) : print 'self.y=%r not set'%y The idea is for @@deco to be intercepted as part of the AST of the unit being compiled, and be converted at that time to call with the AST and its own location in the tree being passed to it so it can do mods to the AST (and cut itself out), and then let the resulting AST be compiled as normal. Multiple @@decorators would each get their chance to mod the AST before compilation. This still would have some version dependency, but it wouldn't be byte code hacking ;-) One of these days I'll think some more on @@. As an experiment, I think the tokenizer could translate @@deco to _AT_AT_deco and let the AST be formed with that apparent function call at that place in the code. Then the AST could be walked to find the _AT_AT_ calls and extract them and compile them and execute them (the _AT_AT_deco functions would obviously have to be defined already, so they might be looked up in some standard place like trying to do place = __import__(_AT_AT_MODULE_) wher _AT_AT_MODULE_ gets defined sort of like __METACLASS__.), passing the AST and the _AT_AT_deco call location therein, and the rest of the parameters. AST decoration would introduce macro-like capabilities, but restricted to transforming valid ASTs, so it isn't like source text rewriting macros. Sorry for the run-on stream of consciousness ;-/ Regards, Bengt Richter From lyris-noreply at ryanairmail.com Mon Jul 4 06:04:59 2005 From: lyris-noreply at ryanairmail.com (Lyris ListManager) Date: Mon, 04 Jul 2005 11:04:59 +0100 Subject: your purge request Message-ID: Re: your purge request > purge Sorry, but your email address: python-list at python.org is not listed as a member of a mailing list. Thus, you could not be unsubscribed from any mailing lists. From sethjn at gmail.com Fri Jul 29 15:57:50 2005 From: sethjn at gmail.com (Seth Nielson) Date: Fri, 29 Jul 2005 12:57:50 -0700 Subject: Help with Asyncore Message-ID: Hello, I am using Asyncore.dispatcher around a socket (well call the wrapped version a channel). This channel is passed around to other objects. These objects call "send" on the channel. My question is, what do you do for "writable" and "handle_write"? Those seemed designed for channel-internal buffers. Should I also overwrite "send" and have the data appended to a buffer? If not, how should writable and handle_write be implemented? I'm not sure what to do here... Thank you in advance, -- Seth Nielson From rkern at ucsd.edu Fri Jul 22 09:03:58 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 22 Jul 2005 06:03:58 -0700 Subject: Python on a public library computer In-Reply-To: References: <1122035486.585382.15370@g44g2000cwa.googlegroups.com> Message-ID: Sybren Stuvel wrote: > Anton Vredegoor enlightened us with: > >>Some time ago I started a thread about it.(Google won't let me reply >>to older topics so I'm starting a new topic with the same title) > > Why not use a proper Usenet client? Because he's on a public computer without one installed? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From harlinseritt at yahoo.com Sun Jul 24 05:43:44 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 24 Jul 2005 02:43:44 -0700 Subject: How to run python script in background after i logout Message-ID: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> I have a remote linux server where I can only access it via ssh. I have a script that I need to have run all the time. I run like so: python script.py & It runs fine. When I log off ssh I notice that the script died when I logged off. How do I make sure it stays running? thanks, Harlin Seritt From siyer at Princeton.EDU Tue Jul 12 16:26:23 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Tue, 12 Jul 2005 16:26:23 -0400 Subject: plot module Message-ID: <126622653da8.42d3ef2f@Princeton.EDU> Hi, I am looking for documentation on the plot module. Does anyone know where I can find this information? Thanks. Shankar From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 23 17:05:34 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 23 Jul 2005 23:05:34 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> Message-ID: <3kfpovFu3rt9U1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: >> Peter Hansen wrote (on Paths not allowing comparison with strings): >>>Could you please expand on what this means? Are you referring to doing >>>< and >= type operations on Paths and strings, or == and != or all those >>>or something else entirely? >> >> All of these. Do you need them? > > I believe so. If they are going to be basestring subclasses, why should > they be restricted in any particular way? I suppose that if you wanted > to compare a Path to a string, you could just wrap the string in a Path > first, but if the Path is already a basestring subclass, why make > someone jump through that particular hoop? Do you have a use case for the comparison? Paths should be compared only with other paths. >>>>Other minor differences, as requested on python-dev, are: >>>> >>>>* size property -> getsize() method. >>>>* atime/mtime/ctime properties -> atime()/mtime()/ctime() methods >>> >>>What does this mean? The .size property and a getsize() method both >>>already exist (in my copy of path.py anyway) and do the same thing. >>>Same with the other ones mentioned above. Is someone working from an >>>out-of-date copy of path.py? >> >> No. But the size of a file is somewhat volatile, and does not feel like >> a "property" of the path to it. Remember: the path is not the file. Same >> goes with the xtime() methods. > > Oh, so your original text was meant to imply that those properties *were > being removed*. That wasn't at all clear to me. > > I understand the reasoning, but I'm unsure I agree with it. I fully > accept that the path is not the file, and yet I have a feeling this is a > pedanticism: most of the time when one is dealing with the _file_ one is > concerned with the content, and not much else. When one is dealing with > the _path_ one often wants to check the size, the modification time, and > so forth. For example, once one has the file open, one very rarely is > interested in when it was last modified. My line of thought is that a path may, but does not need to refer to an existing, metadata-readable file. For this, I think a property is not proper. > In other words, I feel once again that Jason's original intuition here > was excellent, and that he chose practicality over purity in appropriate > ways, in a very Pythonic fashion. I confess to feeling that the > suggested changes are being proposed by those who have never actually > tried to put path.py to use in practical code, though I'm sure that's > not the case for everyone making those suggestions. > > Still, once again this doesn't seem a critical issue to me and I'm happy > with either approach, if it means Path gets accepted in the stdlib. > >> At the moment, I think about overriding certain string methods that make >> absolutely no sense on a path and raising an exception from them. > > That would seem reasonable. It seems best to be very tolerant about > what "makes no sense", though istitle() would surely be one of those to > go first. Also capitalize() (in spite of what Windows Explorer seems to > do sometimes), center(), expandtabs(), ljust(), rjust(), splitlines(), > title(), and zfill(). Hmm... maybe not zfill() actually. I could > imagine an actual (if rare) use for that. I'll look into it. What about iteration and indexing? Should it support "for element in path" or "for char in path" or nothing? >>>.bytes() and friends have felt quite >>>friendly in actual use, and I suspect .read_file_bytes() will feel quite >>>unwieldy. Not a show-stopper however. >> >> It has even been suggested to throw them out, as they don't have so much to >> do with a path per se. When the interface is too burdened, we'll have less >> chance to be accepted. Renaming these makes clear that they are not operations >> on the path, but on a file the path points to. > > Here again I would claim the "practicality over purity" argument. When > one has a Path, it is very frequently because one intends to open a file > object using it and do reads and writes (obviously). Also very often, > the type of reading and writing one wants to do is an "all at once" type > of thing, as those methods support. They're merely a convenience, to > save one doing the Path(xxx).open('rb').read thing when one can merely > do Path(xxx).bytes(), in much the same way that the whole justification > for Path() is that it bundles useful and commonly used operations > together into one place. > >> Phillip J. Eby suggested these to be set_file_xxx and get_file_xxx to demonstrate >> that they do not read or write a stream; how about that? > > If they are there, they do exactly what they do, don't they? And they > do file.read() and file.write() operations, with slight nuances in the > mode passed to open() or the way the data is manipulated. Why would one > want to hide that, making it even harder to tie these operations > together with what is really going on under the covers? I think the > existing names, or at least ones with _read_ and _write_ in them > somewhere are better than set/get alternatives. It's just rare in > Python to encounter names quite as cumbersome as _write_file_bytes(). I think it is not exactly bad that these names are somehow outstanding, as that demonstrates that something complex and special happens. > It might be good for those involved to discuss and agree on the > philosophy/principles behind using Path in the first place. If it's one > of pragmatism, then the arguments in favour of strictly differentiating > between path- and file- related operations should probably not be given > as much weight as those in favour of simple and convenient access to > commonly needed functionality. If, on the other hand, Path is seen as > some kind of a Java-esque universal path object which is cleanly and > tightly decoupled from everything else, then it would probably be best > to eliminate things like .getsize() and .read_file_bytes()/.bytes() > entirely and leave those in the hands of the cleanly defined and tightly > decoupled File object (currently spelled "file"?), again in a Java-esque > fashion. IMHO. :-) Hm. No, that's not my intention either. I think that path as it is is already very good. The PEP must follow, and stress this point. > (I'll like to say for the record that I feel that just about *any* form > of Path with even just the basics, basestring-based or not, would be a > huge improvement over the status quo, and I'm not trying to make a big > war out of this. Just offering my own view as a recent (a month or two > ago) but very enthusiastic convert to path.py.) That's a basis we can build on. ;) Reinhold From p at ulmcnett.com Sun Jul 31 18:53:06 2005 From: p at ulmcnett.com (Paul McNett) Date: Sun, 31 Jul 2005 15:53:06 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <87vf2ryrk1.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> Message-ID: <42ED5652.9080909@ulmcnett.com> Torsten Bronger wrote: > Terry Hancock writes: >>I know I'm diving into this conversation late, and I haven't read >>the whole thread, but has someone yet mentioned the "anygui" >>project? This has stalled, but it was IMHO a good idea. > I don't know exactly why this project died, but I'd start with a > Pythonic variant of wxPython. I've read many discussions about the > people who didn't like the wxPython's C++ style, so there are > chances to get fellow developers and users. You must reach the > critical mass quickly in order to get a survivable project, and > being not too far away from an existing one is a good stating point. > > Possibly Dabo manages such a thing. Dabo does indeed begin to manage a pythonic wrapper to wxPython. When we originally began Dabo, we envisioned wrapping all the major UI toolkits, such as Tkinter, PyQt, wxPython, curses, and even http. You would define your subclasses of the Dabo base widgets, and then at app startup you'd specify which UI library you wanted to use. As long as your own code was clean of UI-library-specific references your UI could render on any supported library. I got some minimal proof-of-concept work done about a year ago, to show that the same code could render on wxPython as well as on Tkinter. But, unless we get a lot more help, developer or financial, I think it's safe to say Dabo wraps wxPython, and that's it. Now, that was only one part of the original Dabo vision, and the other parts of the vision may actually add too much baggage and bloat for people just interested in the UI aspect. Dabo also provides an Application object, a database layer, and a business object layer. Ed and I have discussed the possibility of ripping out the UI layer and putting it into a completely separate project for the purpose of getting more wxPython users interested. It wouldn't be all that hard to do, because we've kept all the UI code separate from the the other stuff by design. If we ever get to the "critical mass", we can start adding wrappers for other libraries, but this vision is always going to be limited by a "lowest common denominator" factor. But one of the other things we've done with Dabo is keep access to the base UI-library functionality if needed. IOW, say you are developing an app that you know will always use wxPython. For the most part, you will be able to use pure-Dabo properties, events, and methods to implement your UI. But, perhaps there is something more low-level that you need to do, such as using a DC to draw something on top of a widget, and Dabo doesn't wrap that. Dabo's UI classes are mixins to wxPython's, and you could just import wx manually to get access to the wx namespace and do whatever you want. While this goes against Dabo's vision on an idealistic level, it satisfies your needs at a practical level. You can benefit from Dabo's ease of use 80% of the time, and resort to doing lower-level stuff only when needed. As far as anygui goes, we only became aware of it after significant work had already gone into Dabo. I have looked at it and I think there may be possibility for some mindshare between the projects, but it is, alas, always easier to reinvent the wheel yourself than to try to design by committee. -- Paul McNett http://paulmcnett.com From bill.mill at gmail.com Wed Jul 27 14:18:25 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 27 Jul 2005 14:18:25 -0400 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: <797fe3d405072711186102fb37@mail.gmail.com> On 7/27/05, Tito wrote: > Hi all: > > Is there a metalanguage capability in Python (I know there are many) to > call a function having its name in a string? > > Something like: > __call__("foo") > > instead of: > foo() > >>> def foo(): print "foobarred" ... >>> foo() foobarred >>> eval("foo()") foobarred >>> Peace Bill Mill bill.mill at gmail.com From duncan.booth at invalid.invalid Tue Jul 5 10:25:36 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Jul 2005 14:25:36 GMT Subject: More On - deepcopy, Tkinter References: <42C9B738.7010604@anvilcom.com> Message-ID: phil wrote: > It is frustrating to think that in a language like python > there might be things which you can't make a copy of. > That is bizarre enough to wonder about a deep flaw or > hopefully I'm just doing something very wrong. To be honest, it doesn't really surprise me that you cannot copy Tkinter objects. If you could make a copy of an object which is displayed on the screen I would expect that copying would create another object on the screen, and that probably isn't what you want. Other uncopyable objects include files, stack frames and so on. The deepcopy protocol does allow you to specify how complicated objects should be copied. Try defining __deepcopy__() in your objects to just copy the reference to the Canvas object instead of the object itself. From amk at amk.ca Mon Jul 4 10:25:52 2005 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 04 Jul 2005 09:25:52 -0500 Subject: Accepted Summer of Code proposals References: Message-ID: On Fri, 1 Jul 2005 14:22:51 -0400, Terry Reedy wrote: > Thanks for posting this and thanks for coordinating the PSF effort. I did little beyond writing up that wiki page. David Ascher has been the primary coordinator for the PSF. --amk From bj_666 at gmx.net Thu Jul 7 18:01:07 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 08 Jul 2005 00:01:07 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <3j40aoFocvh4U1@individual.net> Message-ID: In , Ron Adam wrote: > Reinhold Birkenfeld wrote: >> Ron Adam wrote: >>>(a) == () >> >> >> Whoops! a (which is None) is equal to the empty tuple (which is not None)? > > It's not an empty tuple, it's an empty parenthesis. Using tuples it > would be. But empty parenthesis are parsed as empty tuple:: In [8]: type( () ) Out[8]: Ciao, Marc 'BlackJack' Rintsch From luismgz at gmail.com Fri Jul 1 09:04:39 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 1 Jul 2005 06:04:39 -0700 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: <1120223079.600208.133510@g43g2000cwa.googlegroups.com> Let me express it with an exaple (by the way, sorry for my bad english): Suppose you are planning to build a house. You have two choices: - Option one: Buy several thousands bricks, doors, tiles, windows, etc... put them all together according to the blueprints and build your home. - Option two: Get loads of sand, concrete, wood and raw materials, make your own bricks, make each door and windows with your prefered kind of wood, design and make your tiles, etc.. and after a long, long time, create a unique, one of a kind house. Option one would be like using Python for creating your programs. It gives you all the built-in functions and high level data structures with which you can create a solution for almost any kind of problem you might want to solve. You don't have to spend time allocating memmory, using pointers, creting your data structures from scratch, etc, etc.. because it's all there already available for you, and all these time consuming, error-prone tasks are very well hadled by python itself. Option two is like using C: It gives you full control in the creating on your program, but 90% of the times (or more) you might think "do I really need to go through all this hassle?". Sure, it will be faster but, "do I really need this extra speed?". I think that with the current processors, speed and performance is less an isue than it was a few years ago. Most of the times, developing time is paramount. And even if you need very good execution speed for a given task, you can still code an extension in c or c++ and keep all the benefits of a high level programming language such as python. And if these arguments still can't convince you, be adviced that there's a very ambicious and exciting project called "Pypy" which aims to create a high performance python implementation, and it is being developed very succesfully. They say that the secret goal is being faster than c... and I'm not sure but I think that there's a tentative hard line set to december of 2006. Check it out: http://codespeak.net/pypy/index.cgi?news Cheers, Luis From darkcowherd at gmail.com Sat Jul 30 12:38:32 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Sat, 30 Jul 2005 22:08:32 +0530 Subject: Python language ver 2.4 , development platform 0.4 Message-ID: <5f4d3cb50507300938569cedac@mail.gmail.com> The Python language is at ver 2.4 and a thing of beauty. As a development environment IMHO it is probably 0.4 I really like what I read when I say "import this" in Python. But as a development environment - TOOWTDI and "batteries included" are just not true. I would like to place my position in context. I work in a bread and butter development shop. There are one or two competent long term programmers. The others are freshers or average programmers who join and leave after a year or two etc. But we develop business products and projects for small companies. The natural development environment for companies like us are products like VB or Delphi. We wanted to move towards Linux instead of being purely Windows - centric. So I evaluated Python. This is the impressions I got. It is a hyper-productive environment for the following scenarios. Utilities - fetchmail being a prime example Really futuristic programming paradigms - an example being http://kamaelia.sourceforge.net/Home Large in house programming projects - Just a feeling I have, but I felt that most of the frameworks were scratchin the itch in such scenarios and they got released as open source projects. For a bread and butter programming shop Python looks like Shambles. Until TOOWTDI for GUI, 3 tier applications, Web applications are in place I would hesitate to jump in for day to day use. Calvin had pointed out WSGI and the anygui package. But long way to go. I have looked at DABO, it is impressive. So there are signs that things are going in the right direction but still I feel it is somewhere around 0.4 Small projects, utilities which I am going to code myself I will continue to use Python because I love it. I hope to learn Python well enough to be able to contribute to some projects to achieve this. But I still see that as six to nine months away. -- DarkCowherd From peter at engcorp.com Tue Jul 26 16:09:55 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Jul 2005 16:09:55 -0400 Subject: multiple inheritance super() In-Reply-To: References: Message-ID: km wrote: > Hi all, > > In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? > > thanks in advance for enlightment ... > > here's the snippet > > #!/usr/bin/python > > class A(object): > def __init__(self): > self.a = 1 > > class B(object): > def __init__(self): > self.b = 2 > > class C(object): > def __init__(self): > self.c = 3 > > class D(B, A, C): > def __init__(self): > self.d = 4 > super(D, self).__init__() Each class should do a similar super() call, with the appropriate name substitutions. Calls to __init__ must be made explicitly in subclasses, including in the case of multiple inheritance. Also note that often (usually) you would like the __init__ call to come *before* other location initializations, and it's the safest thing to do unless you have clear reasons to the contrary. -Peter From pink at odahoda.de Tue Jul 5 17:18:27 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Tue, 05 Jul 2005 23:18:27 +0200 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. > > It got me curious if Lisp > is inherently faster to develop complex apps in. It would seem if you > could create your own language in Lisp using macros that that would be > quite an advantage.... > > I realize that Python has operator overloading and OOP so I'm not sure. > > Any ideas? Any *evidence* one way or another? If that means that I have to learn a new programming language for every program I'd like to apply a minor fix/customization to: not a good idea. Probably not just for the casual hacker like me, but also for the maintainance phase of a project, when the former lead gurus lost interest and/or employment. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From michele.simionato at gmail.com Fri Jul 29 12:06:16 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 29 Jul 2005 09:06:16 -0700 Subject: multiple inheritance super() In-Reply-To: References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> Message-ID: <1122653176.013770.106080@g49g2000cwa.googlegroups.com> Sion Arrowsmith > That way lies Java well, no, a dynamic language such as Python with the possibility of adding methods on the fly and metaclasses could live pretty well without multiple inheritance. There would be no real loss of power and hopefully less monstruosities such a Zope 2. But maybe this is just wishful thinking ... Michele Simionato From osv at javad.ru Thu Jul 28 09:59:54 2005 From: osv at javad.ru (Sergei Organov) Date: 28 Jul 2005 17:59:54 +0400 Subject: easy float question just eludes me References: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> Message-ID: nephish at xit.net writes: > Hullo all ! > > i have a real easy one here that isn't in my book. > i have a int number that i want to divide by 100 and display to two > decimal places. > > like this float(int(Var)/100) > but i need it to display the .00 even if it does not have a .00 value > like this > if Var is 50, i need to display .50 instead of just .5 > > i know there is an easy way to do this. >>> print "%.2f" % (50./100) 0.50 From geon at post.cz Mon Jul 11 13:08:58 2005 From: geon at post.cz (geon) Date: Mon, 11 Jul 2005 19:08:58 +0200 Subject: ftputil - uploading many files too long Message-ID: Hi, When I try to upload many files I get such a error message: Traceback (most recent call last): File "I:\Python\my_py\wwwzaci\xcopy_ftp.py", line 51, in ? except: x=host.upload(zdroj, cilFTP,'b') File "C:\prg\python24\Lib\site-packages\ftputil\ftputil.py", line 463, in uplo ad self.__copy_file(source, target, mode, open, self.file) File "C:\prg\python24\Lib\site-packages\ftputil\ftputil.py", line 452, in __co py_file target = target_open(target, target_mode) File "C:\prg\python24\Lib\site-packages\ftputil\ftputil.py", line 265, in file host = self._copy() File "C:\prg\python24\Lib\site-packages\ftputil\ftputil.py", line 241, in _cop y return FTPHost(*self._args, **self._kwargs) File "C:\prg\python24\Lib\site-packages\ftputil\ftputil.py", line 138, in __in it__ self._session = self._make_session() File "C:\prg\python24\Lib\site-packages\ftputil\ftputil.py", line 235, in _mak e_session return ftp_error._try_with_oserror(factory, *args, **kwargs) File "C:\prg\python24\Lib\site-packages\ftputil\ftp_error.py", line 78, in _tr y_with_oserror raise TemporaryError(obj) ftputil.ftp_error.TemporaryError: 421 Login Timeout (25 seconds): closing contro l connection. I think its not about many files but because of it takes too long for my ftp server (25s). I tried many things but nothing helps. Any help is appreciated... -- geon From tprimke at interia.pl Fri Jul 22 03:42:02 2005 From: tprimke at interia.pl (TPJ) Date: 22 Jul 2005 00:42:02 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows Message-ID: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> GUI's etc: PyGtk on Windows "(...) So if someone develops mainly for X and just wants to make sure that it is not impossible to run on Windows, you can use PyGTK. (...)", July 2nd, 1999 pyGTK on Windows "(...) > can i use pyGTK under > Windows??? It's probably doable (...) but not worthy in my oppinion (...). A much better choice is wxPython (...)" "(...)even if it is made to work under windows, pygtk would not have a windows look and feel. wxPython is probably your best bet (...)" pygtk vs. wxPython 4. "(...) If you want cross-platform capabilities (...) then go wxWindows." May 17 2002 7. "(...) The pygtk (and gtk port in general) does not yet support threading on windows. (...) GTK 2.0 is supposed to fix it but support isn't available *yet*. (...)" May 17 2002 PyGTK vs. wxPython 7. "(...) wxPython would indeed be a better choice if your applications are only to run on a certain infamous legacy operating system from the Pacific Northwest. The PyGTK is a better choice if you are writing for Linux and want your application to also be able to run on windows. (...)" Apr 25 11. "(...) I'm using wxPython because GTK for windows wasn't ready three years ago when I initially had to write my first Windows application. If I evaluated both of them again today, I might choose GTK, and I might not." Apr 27 In the nearest future I will have to decide what to use: PyGTK or wxPython. I like those both APIs. wxPython has more widgets, but PyGTK seems to be faster. I can use them both for free (it's very important). My only concern is that although I'm doing development on Linux, I'd like to make my application runnable on Windows as well (Py2Exe). I'd like to choose PyGTK (because of its rich documentation), but I'm not sure if PyGTK is stable on Windows... For now I know that wxPython runs well on Windows. For now I haven't experienced any problems with wxPython on Linux (Slackware, Aurox /Polish RH-like distro/). I used wxPython on Linux, but I stopped because of its poor documentation (mainly C++ docs, not Python docs). But recently I noticed this documentation got better (*much* better!). How well does PyGTK run on Windows (98, 2K, XP)? How stable is it? Will I be able to make an executable (using Py2Exe) of an application that uses PyGTK? From alexis.robert at gmail.com Wed Jul 13 07:41:35 2005 From: alexis.robert at gmail.com (Alexis ROBERT) Date: Wed, 13 Jul 2005 13:41:35 +0200 Subject: Software needed In-Reply-To: References: <1121183089.760096.300450@z14g2000cwz.googlegroups.com> <27ffa6590507130413750d99cf@mail.gmail.com> Message-ID: <27ffa65905071304417ee9fa4f@mail.gmail.com> Thank you 2005/7/13, Richie Hindle : > > > [Fuzzy] > > There's a Python interface to TWAIN (the scanner protocol) > > [Alexis] > > Where I could find the TWAIN python interface ? > > Try typing "python twain" into Google. The first hit is: > > http://twainmodule.sourceforge.net/ > "The Python TWAIN module provides an interface to scanners, digital > cameras and other devices which implement TWAIN, for the Windows > platform. It provides the functionality to allow a Python > application to connect to the scanner/camera and to retrieve images > from that device." > > -- > Richie Hindle > richie at entrian.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 15 17:01:19 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 15 Jul 2005 23:01:19 +0200 Subject: What module to use to get a file from a website? References: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> Message-ID: SolaFide enlightened us with: > I'm sure this is builtin, I just don't know what module. Thank you > for any help! urllib, read the excellent free book "dive into python" at http://www.diveintopython.org/ for examples and usage. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From steve at holdenweb.com Thu Jul 28 10:08:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jul 2005 15:08:03 +0100 Subject: easy float question just eludes me In-Reply-To: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> References: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> Message-ID: nephish at xit.net wrote: > Hullo all ! > > i have a real easy one here that isn't in my book. > i have a int number that i want to divide by 100 and display to two > decimal places. > > like this float(int(Var)/100) > but i need it to display the .00 even if it does not have a .00 value > like this > if Var is 50, i need to display .50 instead of just .5 > > i know there is an easy way to do this. > thanks > Play with this: >>> "%.2f"%0.5 '0.50' >>> a = 50.0 >>> ("%.2f" % (a/100))[-3:] '.50' >>> I presume that a stays in the range 0 <= a < 100. If not you will have to handle the integral digits as well with something like >>> "%4.2f" % 3.1 '3.10' >>> "%6.2f" % 3.1 ' 3.10' >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rbt at athop1.ath.vt.edu Wed Jul 13 11:09:25 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 13 Jul 2005 11:09:25 -0400 Subject: all possible combinations In-Reply-To: References: Message-ID: <1121267364.28617.4.camel@athop1.ath.vt.edu> On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: > > 4^3 = 64 > > aaaa > abaa > aaba > aaab > acaa > aaca > aaac > ... > > What is the most efficient way to do this? Expanding this to 4^4 (256) to test the random.sample function produces interesting results. It never finds more than 24 combinations out of the possible 256. This leads to the question... how 'random' is sample ;) Try it for yourselves: test = list('1234') combinations = [] while 1: combo = random.sample(test, 4) possibility = ''.join(combo) if possibility not in combinations: print possibility combinations.append(possibility) continue else: continue From sybrenUSE at YOURthirdtower.com.imagination Wed Jul 6 08:56:09 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 6 Jul 2005 14:56:09 +0200 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> Message-ID: Jorgen Grahn enlightened us with: > I use no IDE, just emacs for editing my sources, and a terminal > window or two. And CVS for version control. Almost the same here, except that I use VIM and Subversion instead of Emacs and CVS. > If I get stuck or if the problem is non-trivial, or if I'm writing a > standalone module, I use module unittest so I have something easily > runnable at all times. This unittest code doesn't even have to be > true unit tests -- it can be any speculative code I want, driven by > the unittest framework. Same here. I really love unittest! > Between these two (interactive tinkering and unittest-based code) I > feel little need for IDEs or 'environments for experimentation'. I'm usually annoyed by IDEs because, for instance, they don't use VIM as an editor. Since I'm hooked to that, all IDEs I've used so far have failed to impress me. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From steve at REMOVEMEcyber.com.au Thu Jul 7 04:07:03 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 07 Jul 2005 18:07:03 +1000 Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] References: Message-ID: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Steven Bethard wrote: > If you're really afraid of two lines, write it as: > > def r(): randint(1, 100) > > This is definitely a bad case for an anonymous function because it's not > anonymous! You give it a name, r. This is something I've never understood. Why is it bad form to assign an "anonymous function" (an object) to a name? It isn't just that lambda _can_ create functions that aren't bound to any name. That I get. But why is it suppose to be wrong to bind such a function to a name? Sure, if the lambda is so complicated that it becomes unreadable, the usage case is wrong and a def should be used instead. But I see nothing wrong with doing this: func = lambda x: x**3 - 3*x**2 Why is it considered abuse of lambda to assign the functions to a name? Is it an abuse of lambda to do this? D = {"one": lambda noun: noun, "two": lambda noun: noun + 's', "many": lambda noun: 'lots of ' + noun + 's' } assert D["two"]("python") == "pythons" -- Steven. From steven.bethard at gmail.com Mon Jul 25 22:21:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 25 Jul 2005 20:21:08 -0600 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <5NCdnZOPgP-JA3jfRVn-tQ@comcast.com> Thanos Tsouanas wrote: > On Sun, Jul 24, 2005 at 02:14:15PM -0600, Steven Bethard wrote: > >>How about something like: >> dict((name, getattr(obj, name)) for name in dir(obj)) > > Pretty!!! > >>Looks like this will get instance attributes, class attributes and >>properties just fine. > > But not SQLObject's objects... > Any idea why? (Getting attribute errors, it seems that these > "attributoids" are not listed in dir(obj), so i have to use my ugly > dictobj class.. :( I don't know how SQLObjects are implemented, but I'm guessing they use __getattr__ or __getattribute__: py> class C(object): ... w = 1 ... @property ... def x(self): ... return 2 ... def __init__(self): ... self.y = 3 ... def __getattr__(self, name): ... if name == 'z': ... return 4 ... py> c = C() py> d = dict((name, getattr(c, name)) for name in dir(c)) py> d['w'], d['x'], d['y'] (1, 2, 3) py> d['z'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'z' Any attribute simulated through __getattr__ or __getattribute__ cannot be found by dir(): py> dir(c) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'w', 'x', 'y'] For this reason, I try to avoid implementing attributes through these methods, but sometimes it's unavoidable. STeVe From fumanchu at amor.org Sun Jul 10 02:15:33 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 9 Jul 2005 23:15:33 -0700 Subject: Yet Another Python Web Programming Question Message-ID: <3A81C87DC164034AA4E2DDFE11D258E377251F@exchange.hqamor.amorhq.net> Daniel Bickett wrote: > I neglected to mention an important fact, and that is the fact that I > am limited to Apache, which elminates several suggestions (that are > appreciated none-the-less). Do you have access to mod_python, mod_rewrite, FastCGI, or SCGI? Then CherryPy 2.1 is still a great option for you with Apache: http://www.cherrypy.org/wiki/WSGIServers http://www.cherrypy.org/wiki/BehindApache Robert Brewer System Architect Amor Ministries fumanchu at amor.org From jaquar310 at aol.com Sun Jul 3 20:10:37 2005 From: jaquar310 at aol.com (Fibvortex) Date: 3 Jul 2005 17:10:37 -0700 Subject: FIBVORTEX MANAGED FOREX MINI ACCOUNT Message-ID: <1120435836.958602.291520@g47g2000cwa.googlegroups.com> The Fibvortex is now offering Managed Mini Forex Accounts with NO Management Fee! Receive the same benefits as our regular managed account at a fraction of the price. You will designate the number of lots to be executed on your behalf for each trade. You will have 24 access to our Forex Chart Room so you can watch the real time trading whenever you have the time. Each and every trade is announced & posted immediately in the chat room, and directly onto our charts in our Forex Chart Room so you will always know the position that you are in. http://www.fibvortex.com/Managedmini.html For additional information, please contact us @ Email: managedmini at fibvortex.com From mwh at python.net Tue Jul 19 11:28:41 2005 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Jul 2005 15:28:41 GMT Subject: Are there any decent python memory profilers available? References: <1121288812.369538.201250@g49g2000cwa.googlegroups.com> Message-ID: lthompson at ixiacom.com writes: > I have a rather large python application (uses around 40MB of memory to > start) that gradually chews up memory over many hours. I've done a > little googling around, but it looks like I'm faced with prowling > through the gc.get_objects() myself. I need a tool to identify where > the memory is going. It might even be a leak in a DLL, so maybe a pure > python profiler isn't the best, although it would certainly help > localize the problem. One is being written as part of Google's Summer Of Code program. Cheers, mwh -- Java sucks. [...] Java on TV set top boxes will suck so hard it might well inhale people from off their sofa until their heads get wedged in the card slots. --- Jon Rabone, ucam.chat From elmo13 at jippii.fi Mon Jul 25 14:15:36 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Mon, 25 Jul 2005 21:15:36 +0300 Subject: How can I encode something in base32 preferably very fast? References: Message-ID: On Mon, 25 Jul 2005 16:51:05 +0200, Johannes Findeisen wrote: > On Mon, 2005-07-25 at 17:23 +0300, Elmo M?ntynen wrote: >> I want to encode a plaindigest or a hexdigest in base 32. Any hints? > > Search Google for "python base32" isn't as hard... > > First result are the original python lib documentation: > http://docs.python.org/lib/module-base64.html > > I think you need to convert to a String before encoding... > > Have fun, I thought I had looked at that particular module:). Thanks for pointing it out. Elmo From percivall at gmail.com Tue Jul 5 03:10:24 2005 From: percivall at gmail.com (Simon Percivall) Date: 5 Jul 2005 00:10:24 -0700 Subject: What are __slots__ used for? References: Message-ID: <1120547424.024497.111600@g44g2000cwa.googlegroups.com> Most have already been said, but have a look at http://docs.python.org/ref/slots.html for authoritative documentation. From 00515879256 at fastwebnet.it Fri Jul 8 10:23:50 2005 From: 00515879256 at fastwebnet.it (Glauco) Date: Fri, 08 Jul 2005 16:23:50 +0200 Subject: psycopg simplest problem In-Reply-To: <1110592231.853484.197370@z14g2000cwz.googlegroups.com> References: <1110592231.853484.197370@z14g2000cwz.googlegroups.com> Message-ID: I'm rebuilding my old library i've done some year ago using python and postgres. My problem is to do a middle layer over pycopg for eliminate type casting problem in postgres in all direction. i've resolved this doing a C extension in python and manipulating only string and int in my application. this is my example: import sqlvar sql = """insert into mytable (myint, mytext, maydate) values (%d,%s,%s);""" % (sqlvar.number(myvalue1), sqlvar.text(myvalue2), sqlvar.date(myvalue3) ) all problem concerning quoting, " ' -> ''", null, None, 0, empty string is solved by the sqlvar lib. I want to eliminate this problem forever, i want to manipulate only correct type as DateTime obj in my application so i want to arrive at this solution: sql = """insert into mytable (myint, mytext, maydate) values (%s,%s,%s);""" % (myvalue1, myvalue2, myvalue3) without all time check for none, empty string and so on... I've seen API of psycopg and some procedure for the solution but all are too spaghetti for me. I'm only with this problem ? Glauco -- \\\|/// \\ - - // ( @ @ ) +---------------------oOOo-( )-oOOo--------------------------+ | | | I have a dream that one day this nation will rise up and | | live out the true meaning of its creed: "We hold these | | truths to be self-evident:that all men are created equal.| | I have a dream that one day on the red hills of Georgia | | the sons of former slaves and the sons of former | | slaveowners will be able to sit down together at a table | | of brotherhood. | | I have a dream that one day even the state of Mississippi, | | a desert state, sweltering with the heat of injustice | | and oppression, will be transformed into an oasis of | | freedom and justice. | | I have a dream that my four children will one day live in | | a nation where they will not be judged by the color of | | their skin but by the content of their character. | | I have a dream today. | | | | Martin Luther King, Jr 28 Ago 1963 | +------------------------------------------------------------+ | glauco(at)uriland.it | | www.uriland.it .oooO ICQ: 115323690 | +--------------------- ( )------ Oooo.---------------------+ \ ( ( ) \_) ) / (_/ From steve at holdenweb.com Mon Jul 25 01:22:24 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Jul 2005 06:22:24 +0100 Subject: How to run python script in background after i logout In-Reply-To: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> Message-ID: Harlin Seritt wrote: > I have a remote linux server where I can only access it via ssh. I have > a script that I need to have run all the time. I run like so: > > python script.py & > > It runs fine. When I log off ssh I notice that the script died when I > logged off. How do I make sure it stays running? > > thanks, > > Harlin Seritt > If you want to trigger each run manually, try nohup python script.py & This should allow the job to continue running after you've logged out. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From aahz at pythoncraft.com Thu Jul 28 17:51:50 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Jul 2005 14:51:50 -0700 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: In article , Michael Hoffman wrote: >Robert Kern wrote: >> >> import this >> >> And you get 9 bonus Essential Development Practices, too! What a bargain! > >One of these days I'm going to figure out how to embody "Namespaces are >one honking great idea -- let's do more of those!" Then I shall be >enlightened. What don't you understand about it? (This is a serious question -- I can think of several answers to give you, but want to know what focus is needed first.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From diesch at spamfence.net Wed Jul 20 11:27:05 2005 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 20 Jul 2005 17:27:05 +0200 Subject: OO design References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: <20050720152705.23B2.1.NOFFLE@dieschf.news.arcor.de> chris wrote: > I've been scripting with python for a while now. Basically writing a few > functions and running in the ipython shell. That's been very useful. But the > more I do this the more I see that I'm doing more or less the same thing > over and over again. So its feels like I need to get into class programming > with all its attendant benefits. However my biggest problem is a conceptual > one. I just can't get my head around defining suitable classes, how they > aquire data and communicate with each other. I'm hoping some of you python > lamas out there might be able to share some of your wisdom on the subject. Just some thoughts about it: > What I basically do is a lot of the following:: > > 1. get arbitrary numerical data (typically large data sets in columnar > format or even via COM from other packages. I generally have to deal with > one or more sets of X,Y data) You may create a class for each data format that reads that data and creates a set from it. > 2. manipulate the data (scaling, least squares fitting, means, peaks, > add/subtract one XY set from another etc) This methods may either manipulate youe set's data or create a new set with the data > 3. plot data (original set, results of manipulation, scatterplot, histograms > etc - I use matplotlib) I never useds matplotlib. Maybe it's usefull to have one or more classes covering the functions you need. > 4. export data (print, csv, shelve) Again have a class for each output format. > I have no problem writing bits of functional code to do any of the above. > But for the life of me I can't see how I can hook them altogether in an OO > based framework that I can build and extend (with more data formats, > manipulations, GUI etc). > > When I think about what I should do I end up with a class XY that has a > method for everything I want to do eg. > > class XY: > def read_file > def scale_data > def plot_data > def shelve_data > > But somehow that doesn't feel right, especially when I expect the number of > methods will grow and grow, which would make the class very unwieldy. > > Even if that was a legitimate option, I don't understand conceptualy how I > would, for example, plot two different XY objects on the same graph or add > them together point by point. How do two different XY objects communicate Have a look at the IntervalSet module someone announced here some time before to get some ideas. > and how do you deal with the thing that they must have in common (the plot > screen for example). Create classes for this things. Then you may either pass XY to method of Thing or the Thing to a method of XY. Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From jkn_gg at nicorp.f9.co.uk Tue Jul 19 02:55:08 2005 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 18 Jul 2005 23:55:08 -0700 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? In-Reply-To: References: Message-ID: <1121756108.856316.135130@z14g2000cwz.googlegroups.com> Hi Chris > Could anyone write a small program to log the Signal-to-Noise figures > for a Netgear DG834 router? > many people could, I'm sure, if not quite _anyone_ > I have been getting very variable SNR readings - and I would like to > collect some evidence to analyse. I see. > > What is needed is a program that logs into the router's html page every > minute, and then extracts the time and the SNR figure, and writes a line > of a text file. Good, you've got the 'top level' of what you need. How would you break that down into smaller steps? > > I reckon it would be useful to many people. great - thanks! Jon N From me at privacy.net Sun Jul 17 05:56:35 2005 From: me at privacy.net (Stephen Illingworth) Date: Sun, 17 Jul 2005 10:56:35 +0100 Subject: SSL problem... SSL23_GET_SERVER_HELLO:unknown protocol In-Reply-To: References: Message-ID: John Reese wrote: > Morning. I've been running into an error message pertaining to SSL > that I don't understand, and I was hoping someone had some insight. > Gmail provides POP access over SSL on port 587, so I tried to use > poplib.POP_SSL, with the following results: [snip] > Any suggestions or insight? Try port 465. From tjreedy at udel.edu Sat Jul 23 01:54:03 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Jul 2005 01:54:03 -0400 Subject: Using python to runother programs References: <1122054694.450950.216900@g44g2000cwa.googlegroups.com> Message-ID: wrote in message news:1122054694.450950.216900 at g44g2000cwa.googlegroups.com... > HI guys, > I am trying to automate some project work which the accounting dept > of the company uses. They have to go through multiple steps to achieve > the final goal. Is there some way that I can use python to automate > these manual steps. I can give you an example. > > 1. run the crystal report using some ***.excel file > > 2. Store the output as *.txt file. > > 3. use accounting software and use the *.txt file (this step can be > excluded) > > I don't know how to use python to run the crystal report and save the > output as an txt file using python scripts. Is this even possible? Maybe. Details depend on your OS, which you neglected to mention ;-) Lookup os.system. There may also be a new module in 2.4 that is relevant (I forget name). If you are on Windows, PyWin gives you more options. tjr From cvrebert at gmail.com Fri Jul 1 18:29:02 2005 From: cvrebert at gmail.com (Chris Rebert (cybercobra)) Date: 1 Jul 2005 15:29:02 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <1120256942.763526.235000@g14g2000cwa.googlegroups.com> My personal favorite would be ruby's iterators and blocks. Instead of writing a bunch of repetitive list comprehensions or defining a bunch of utility functions, you just use the iterators supported by container objects. For instance, [f(x) for x in y] could be written in Ruby as y.collect |x| do #body of f end You don't have to use a lambda or define f() externally. Best of all, Ruby's containers come with many iterators for common cases builtin. Joseph Garvin wrote: > As someone who learned C first, when I came to Python everytime I read > about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > getattr/setattr, the % operator, all of this was very different from C. > > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > > Here's my current candidate: > > So the other day I was looking at the language Lua. In Lua, you make a > line a comment with two dashes: > > -- hey, this is a comment. > > And you can do block comments with --[[ and ---]]. > > --[[ > hey > this > is > a > big > comment > --]] > > This syntax lets you do a nifty trick, where you can add or subtract a > third dash to change whether or not code runs: > > --This code won't run because it's in a comment block > --[[ > print(10) > --]] > > --This code will, because the first two dashes make the rest a comment, > breaking the block > ---[[ > print(10) > --]] > > So you can change whether or not code is commented out just by adding a > dash. This is much nicer than in C or Python having to get rid of """ or > /* and */. Of course, the IDE can compensate. But it's still neat :) From fred at ucar.edu Wed Jul 6 19:04:02 2005 From: fred at ucar.edu (bandw) Date: 6 Jul 2005 16:04:02 -0700 Subject: Using Numeric 24.0b2 with Scientific.IO.NetCDF In-Reply-To: References: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> <1120590393.714232.34240@f14g2000cwb.googlegroups.com> Message-ID: <1120691042.889910.180520@g43g2000cwa.googlegroups.com> I am having more problems with 24.0b2. Consider the NetCDF file: netcdf very_simple { dimensions: num = 2 ; variables: float T(num) ; T:mv = 5.0f ; data: T = 1., 2. ; } and the python script: import Numeric from Scientific.IO.NetCDF import NetCDFFile file = NetCDFFile("simple.nc","r") T = file.variables["T"] a = T.mv print "T.mv = ", a print "type(T.mv) = ", type(a) print "len(T.mv) = ", len(a) print "T.mv[0] = ", a[0] print "len(T.mv[0]) = ", len(a[0]) print "type(T.mv[0]) = ", type(a[0]) which produces the output: T.mv = [ 5.] type(T.mv) = len(T.mv) = 1 T.mv[0] = 5.0 len(T.mv[0]) = 1 type(T.mv[0]) = I can see no reason why T.mv[0] should be typed as an array. From fperez.net at gmail.com Thu Jul 7 13:30:19 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 07 Jul 2005 11:30:19 -0600 Subject: question about introspection using inspect module References: <5vll4ihfvt.fsf@akron.bmi.ohio-state.edu> Message-ID: Benjamin Rutt wrote: > I'm trying to learn about introspection in Python. my ultimate goal > is to be able to build a module "text database" of all modules that > are in the sys.path, by discovering all candidate modules (I've > already done that), importing all of them, and then introspecting on > each module to discover its functions, globals and classes. But for > now I am having a problem with the latter. I certainly don't want to discourage you from learning about python introspection, it's one of the most fun aspects of the language. But just as an FYI, the pydoc system already does much of what you have in mind, at least if I'm reading your description correctly: planck[/tmp]> pydoc -p 12345 pydoc server ready at http://localhost:12345/ Just point your favorite webbrowser to that URL (use any port number you want, and which isn't already in use). Cheers, f From tim.peters at gmail.com Fri Jul 29 10:39:43 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 29 Jul 2005 10:39:43 -0400 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <1f7befae05072907396ceb4c8c@mail.gmail.com> [Steve Holden] >> If I canpoint out the obvious, the output from "import this" *is* >> headed "The Zen of Python", so clearly it isn;t intended to be >> universal in its applicability. [Michael Hudson] > It's also mistitled there, given that it was originally posted as '19 > Pythonic Theses' and nailed to, erm, something. 'Twas actually posted as "20 Pythonic Theses", although most times I count them I find19. Nevertheless, that there are in fact 20 was channeled directly from Guido's perfectly Pythonic mind, so 20 there must be. I suspect he withheld one -- although, as some argue, it's possible he thinks in base 9.5, that just doesn't seem Pythonic to me. From cyril.bazin at gmail.com Wed Jul 20 10:36:47 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Wed, 20 Jul 2005 16:36:47 +0200 Subject: python certification In-Reply-To: <1121863299.203822.33180@z14g2000cwz.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> <1121790230.580130.156410@o13g2000cwo.googlegroups.com> <1121863299.203822.33180@z14g2000cwz.googlegroups.com> Message-ID: Fine, Go to "http://www.pythonchallenge.com" and try the challenge, if you are able to get to the level 17-18, you can say you start to have good skills in Python. You will prove: you are not stupid, you know regex, basic sound/image treatment, the basics of zip/bz2, you understood how to use urllib/urllib2 and xmlrpc and many other things. When you get to the level 17-18, go to the IRC and ask to "theSamet" a certification. If he is in a good mood, maybe he will give you an ascii-art diplom like Rocco! ;-) Cyril On 20 Jul 2005 05:41:39 -0700, lordverminard at gmail.com < lordverminard at gmail.com> wrote: > > hi > i bassically need it cuz i am appyling to colleges this year and > i know this kind of stuff really helps. > besides since i am learning python i thought i might get some credit > for it as well. > its bassically for a mention in my resume/bio-data/appliccation > i am willing to spend about $50-100 but any more is out of my bugdet. > even $50 is hard on me. > i did find this great site that would let me give a perl exam in $9.99 > but they don't have python. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdsteph at mac.com Tue Jul 12 07:57:36 2005 From: rdsteph at mac.com (rdsteph at mac.com) Date: 12 Jul 2005 04:57:36 -0700 Subject: a new Python Podcast series (and the use of Python in creating podcasting tools) In-Reply-To: <2lHAe.21508$eM6.7938@newsread3.news.atl.earthlink.net> References: <1121135302.110610.188420@f14g2000cwb.googlegroups.com> <2lHAe.21508$eM6.7938@newsread3.news.atl.earthlink.net> Message-ID: <1121169456.458290.302230@g14g2000cwa.googlegroups.com> I'd love to get some guest "lectures" from advanced folks, and interviews with prominent Pythonista people etc. Ron From tundra at tundraware.com Fri Jul 8 18:36:43 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 08 Jul 2005 18:36:43 EDT Subject: Defending Python In-Reply-To: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> Message-ID: Charlie Calvert wrote: > I perhaps rather foolishly wrote two article that mentioned Python as a > good alternative language to more popular tools such as C# or Java. I > encountered more resistance than I had expected. If someone who really > knows a lot about Python would like to go over to the CodeFez website > and defend Python a bit better than I can, that would be appreciated. > > The articles are called "The War of the Virtual Bills," and "Ranking > Languages: Fear as a Career Move." > > Here are the links: > > http://www.codefez.com > > http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/135/RankingLanguagesFearasaCareerMove.aspx > > > http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/134/TheWaroftheVirtualBills.aspx > > > Thanks. > > - Charlie Something I wrote some time ago might be relevant: http://www.tundraware.com/Technology/Python-Is-Middleware/ -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From steven.bethard at gmail.com Wed Jul 6 19:17:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 06 Jul 2005 17:17:45 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: Daniel Sch?le wrote: > Removing lamdba would be reduce readability of Python, I think here > for examble of code like > > class App: > .... > .... > def drawLines(self, event): > from random import randint > r = lambda : randint(1, 100) > self.canvas.create_line(r(), r(), r(), r()) > > defining one extra function would only confuse and But you just did define one extra function!! If you're really afraid of two lines, write it as: def r(): randint(1, 100) This is definitely a bad case for an anonymous function because it's not anonymous! You give it a name, r. > and what about creating one liner factories like > from math import log10 > log = lambda basis: lambda x: log10(x) / log10(basis) > log2 = log(2) > log2(2**10) -> 10.0 This is slightly better, because at least one of your functions really is anonymous. I'm not really sure I'm convinced that it's any better than this though: def log(base): def log_in_base(x): return log10(x)/log10(base) return log_in_base because when I first read the code, I didn't catch the second, nested lambda. Of course, with a syntax-highlighting editor, I probably would have. Again though, to fix your abuse of anonymous function syntax for non-anonymous functions, you should write this as: def log(basis): return lambda x: log10(x) / log10(basis) Or if you're afraid of multiple lines: def log(basis): return lambda x: log10(x) / log10(basis) STeVe From rkern at ucsd.edu Tue Jul 26 01:19:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 25 Jul 2005 22:19:54 -0700 Subject: Suggestions for Python XML library which can search and insert In-Reply-To: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> References: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> Message-ID: lainedacier at gmail.com wrote: > Hi, > > I'm looking for a library that can search through an XML document tree, > locate an element by attribute (ideally this can be done through > XPath), and insert an element (as its child). Try lxml: http://codespeak.net/lxml/ In [25]: from lxml import etree In [26]: nbk = etree.parse('tut-2.3.5-db.nbk') In [27]: log = root.xpath('//ipython-log[@id="default-log"]')[0] In [28]: etree.SubElement(log, 'cell') Out[28]: -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From joe.woodward at padtinc.com Wed Jul 13 14:00:11 2005 From: joe.woodward at padtinc.com (Joe) Date: 13 Jul 2005 11:00:11 -0700 Subject: PY2EXE => Is there a way to go backwards? EXE2PY Message-ID: <1121277611.573163.318250@g49g2000cwa.googlegroups.com> I have the executable of a script that I wrote, that has been erased. Is there any way to retrieve the uncompiled python script from the executable that was created with py2exe? Thank you, Joe From martin.witte at gmail.com Sun Jul 3 07:57:01 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 3 Jul 2005 04:57:01 -0700 Subject: question In-Reply-To: References: Message-ID: <1120391821.867558.327480@g43g2000cwa.googlegroups.com> see the answer on your previous post ( http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/8e132d9c734907b/87fd1f579a362e71?q=&rnum=2&hl=en#87fd1f579a362e71), to get an interactive session open a command window and type ' python' From http Sun Jul 31 07:23:39 2005 From: http (Paul Rubin) Date: 31 Jul 2005 04:23:39 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> <7xhdebv1t0.fsf@ruckus.brouhaha.com> <87vf2rpc0i.fsf@wilson.rwth-aachen.de> Message-ID: <7xy87nw75w.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > >> Does py2exe work for all GUI libraries? > > No, it's Windows-only. > However, OS'es and GUI libraries are different axes in the space of > possibilities. I'm not sure what you mean. Whatever GUI library the Mac uses, py2exe doesn't work with it, since py2exe doesn't work for Macs. From gtg216r at mail.gatech.edu Fri Jul 22 22:59:11 2005 From: gtg216r at mail.gatech.edu (Kane Bonnette) Date: Fri, 22 Jul 2005 22:59:11 -0400 Subject: Clearing a Text Widget Message-ID: Does anyone know how the clear the text from a Tkinter Text Widget? The delete(0, END) trick that works for Entry widgets doesn't work for Text I get "0 is an invalid index" when i try to do so Thanks in advance From bingham at cenix-bioscience.com Mon Jul 11 07:54:05 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Mon, 11 Jul 2005 13:54:05 +0200 Subject: __eq__ on a dict In-Reply-To: (Steven D'Aprano's message of "Mon, 11 Jul 2005 21:48:11 +1000") References: Message-ID: "Steven D'Aprano" writes: > On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote: > >> Hello, >> >> I can't find the docs for __eq__ on a dict and I can't find >> a description on what the eq does (strangely it does implement > and < >> but I have no idea what that does). Does anyone know (definitively) >> what the __eq__, __gt__, __lt__ methods do. [snip] > For any two objects x and y, when you call > > x == y > > Python calls x.__eq__(y). That includes dicts: > > py> dictA = {0: "spam"} > py> dictB = {0: "sp" + "am"} > py> dictC = {1: "ham"} > py> > py> dictA == dictB > True > py> dictA.__eq__(dictB) # same as dictA == dictB > True > py> dictB == dictC # calls dictB.__eq__(dictC) > False > > Two dicts are equal if they have the same keys and the same values. That is what I would expect, but where is that documented? Also, where is the behavior of the much less obvious dictionary methods __ge__, __gt__, __le__, __lt__, and __cmp__ methods documented? > In general, you should not call __eq__ directly, but use the == operator > instead. That is clear enough, the OP was seeking information about the behavior of these operators when used with dictionaries. Thanks, -- -------------------------------------------------------------------- Aaron Bingham Senior Software Engineer Cenix BioScience GmbH -------------------------------------------------------------------- From rkern at ucsd.edu Tue Jul 12 04:29:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 01:29:36 -0700 Subject: Managment of Python Libraries In-Reply-To: References: Message-ID: Joseph Chase wrote: > I am new to Python. > > In the past, I have noticed that I have spent a lot of time managing my C++ > libraries. When my personal frameworks got large enough, and some moving > around/refactoring was apparent, it was an absolute nightmare. > > As I embark on the wonderful language of Python, or there any object > organizational tools that may help me to keep order? There's Bicycle Repair Man: http://bicyclerepair.sourceforge.net/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mwm at mired.org Tue Jul 26 23:58:26 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 26 Jul 2005 23:58:26 -0400 Subject: Counting processors References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> <1122389455.371659.229710@o13g2000cwo.googlegroups.com> Message-ID: <86ack8oq71.fsf@bhuda.mired.org> "k pur" <4krishan at gmail.com> writes: > You can use > > print os.sysconf("SC_NPROCESSORS_CONF") > > works on Linux Works on FreeBSD as well. It hooks up to the sysconf C call. That's a Posix call, so this should work portably across Posix systems. I know Windows can be made Posix compliant, but I'm no sure how much of that functionality you get out of the box. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From philippe at philippecmartin.com Thu Jul 7 22:05:10 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 08 Jul 2005 02:05:10 GMT Subject: Thoughts on Guido's ITC audio interview References: Message-ID: > For me, performance is the minor issue. Usability is the major issue. If > find Eclipse to be highly unusable, so I don't use it. I find it to be the best option out there From bronger at physik.rwth-aachen.de Sun Jul 31 12:12:06 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 18:12:06 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> <7xvf2rync2.fsf@ruckus.brouhaha.com> Message-ID: <87r7dfymy1.fsf@wilson.rwth-aachen.de> Hall?chen! Paul Rubin writes: > Ed Leafe writes: > >> But since UIs are incredibly complex beasts, we've chosen to >> tackle one at a time, and after looking at them all and >> considering different issues, we chose wxPython as the best >> toolkit for creating platform-independent apps. > > How on earth did you decide that, since tkinter actually runs out > of the box when you install Python on most platforms, and wxPython > doesn't? I can't really understand your hostility towards non-Tkinter toolkits. In the case of wxPython, it's part of SUSE, which is probably also true for Fedora and Mandriva. Installing is as easy as selecting a checkbox. This covers a very great deal of Linux users. On Windows you have to call an exe file. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From pinard at iro.umontreal.ca Fri Jul 1 16:23:12 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 1 Jul 2005 16:23:12 -0400 Subject: Assigning to None In-Reply-To: References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <86ekai5sk7.fsf@bhuda.mired.org> Message-ID: <20050701202312.GA16374@phenix.progiciels-bpi.ca> [Rocco Moretti] > foo, bar, _ = gen_tuple(stuff) > as '_' is already special cased (last result in interactive mode), and > is already used for "don't care" sematics in Prolog. `_' is also the `gettext' function in internationalised programs. It so seems that `_' is in great demand! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From spam.csubich+block at block.subich.spam.com Fri Jul 29 21:09:31 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Fri, 29 Jul 2005 21:09:31 -0400 Subject: A replacement for lambda In-Reply-To: <867jf9jmfw.fsf@bhuda.mired.org> References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > My choice for the non-name token is "@". It's already got magic > powers, so we'll give it more rather than introducing another token > with magic powers, as the lesser of two evils. Doesn't work. The crux of your change isn't introducing a meaning to @ (and honestly, I prefer _), it's that you change the 'define block' from a compound_stmt (funcdef) (see www.python.org/doc/current/ref/compound.html) to an expression_stmt (expresion). This change would allow some really damn weird things, like: if def _(x,y): return x**2 - y**2 (5,-5): # ?! How would you immediately call this 'lambda-like'?[1] print 'true' else: print 'false' [1] -- yes, it's generally stupid to, but I'm just pointing out what has to be possible. Additionally, Python's indenting Just Doesn't Work Like That; mandating an indent "after where the def came on the previous line" (as you do in your example, I don't know if you intend for it to hold in your actual syntax) wouldn't parse right -- the tokenizer generates INDENT and DEDENT tokens for whitespace, as I understand it. My personal favourite is to replace "lambda" entirely with an "expression comprehension", using < and > delimeters. It just looks like our existing list and generator comprehensions, and it doesn't use 'lambda' terminology which will confuse any newcomer to Python that has experience in Lisp (at least it did me). g = g(1) == 1 Basically, I'd rewrite the Python grammar such that: lambda_form ::= "<" expression "with" parameter_list ">" Biggest change is that parameter_list is no longer optional, so zero-argument expr-comps would be written as , which makes a bit more sense than . Since "<" and ">" aren't ambiguous inside the "expression" state, this shouldn't make the grammar ambiguous. The "with" magic word does conflict with PEP-343 (semantically, not syntactically), so "for" might be appropriate if less precise in meaning. From skip at pobox.com Thu Jul 7 16:46:13 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Jul 2005 15:46:13 -0500 Subject: Calculating average time In-Reply-To: <1120768294.287881.169030@z14g2000cwz.googlegroups.com> References: <1120768294.287881.169030@z14g2000cwz.googlegroups.com> Message-ID: <17101.38037.132718.739533@montanaro.dyndns.org> greg> 1. Is there a better time function to use? For this particular scenario I think time.time() is probably what you want: cumulative = 0.0 n = 0 for link in links: t = time.time() ie.Navigate(link) cumulative += time.time() - t n += 1 print "average page load time:", cumulative/n, "seconds" Skip From steve at holdenweb.com Fri Jul 29 10:27:21 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Jul 2005 15:27:21 +0100 Subject: Filtering out non-readable characters In-Reply-To: References: Message-ID: Adriaan Renting wrote: > def StripNoPrint(self, S): > from string import printable > return "".join([ ch for ch in S if ch in printable ]) > > > Adriaan Renting | Email: renting at astron.nl > ASTRON | Phone: +31 521 595 217 > P.O. Box 2 | GSM: +31 6 24 25 17 28 > NL-7990 AA Dwingeloo | FAX: +31 521 597 332 > The Netherlands | Web: http://www.astron.nl/~renting/ > >>>>"MKoool" 07/16/05 2:33 AM >>> > > I have a file with binary and ascii characters in it. I massage the > data and convert it to a more readable format, however it still comes > up with some binary characters mixed in. I'd like to write something > to just replace all non-printable characters with '' (I want to delete > non-printable characters). > > I am having trouble figuring out an easy python way to do this... is > the easiest way to just write some regular expression that does > something like replace [^\p] with ''? > > Or is it better to go through every character and do ord(character), > check the ascii values? > > What's the easiest way to do something like this? > > thanks > I'd consider using the string's translate() method for this. Provide it with two arguments: the first should be a string of the 256 ordinals from 0 to 255 (because you won't be changing any characters, so you need a translate table that effects the null transformation) and the second argument should a string containing all the characters you want to remove. So >>> tt = "".join([chr(i) for i in range(256)]) generates the null translate table quite easily. Then >>> import string >>> ds = tt.translate(tt, string.printable) sets ds to be all the non-printable characters (according to the string module, anyway). Now you should be able to remove the non-printable characters from s by writing s = s.translate(tt, ds) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From haraldarminmassa at gmail.com Fri Jul 22 07:07:47 2005 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 22 Jul 2005 04:07:47 -0700 Subject: PEP on path module for standard library In-Reply-To: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> References: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> Message-ID: <1122030467.268020.300590@z14g2000cwz.googlegroups.com> > When you try to 'freeze' an application module, >and Jason's 'path' module is present in any of the directories that are >looked at by freeze's module finder (your app doesn't have to import >it), freeze goes into an infinite loop of imports, eventually getting a >'maximum recursion depth' exception. This seems to be related to >freeze getting confused between 'os.path' and Jason's 'path'. This is a bug in distutils. Thomas Hellers py2exe encounters the same bug. As much as I remember our conversation, he submitted a patch to distutils. In the meanwhile I renamed path.py to jpath.py, usings Jason's first letter in a motion of honour while circumventing this bug. Harald From peter at engcorp.com Fri Jul 1 20:33:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 20:33:43 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> Message-ID: Sean McIlroy wrote: > personally i don't know lisp (or scheme), but now i've > decided to learn it, because eventually it will no longer be possible > in python to pass functions as arguments or return them as values. the > education sig will have to change its motto to "computer programming > for every C-programmer". Huh? Where did that come from? Functions are objects in Python and I've not heard the least discussion about this being changed, until now. Sean, what gave you the impression this would change? -Peter From theller at python.net Wed Jul 6 11:18:58 2005 From: theller at python.net (Thomas Heller) Date: Wed, 06 Jul 2005 17:18:58 +0200 Subject: Favorite non-python language trick? References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> <87hdf8ync5.fsf@titan.staselog.com> Message-ID: Edvard Majakari writes: > (sorry, my NUA had lost the original article) >> >>> I'm curious -- what is everyone's favorite trick from a non-python >>> language? And -- why isn't it in Python? > > Ability to tag some methods 'deprecated' as in Java (from 1.5 > onwards?). However, Python interpreter doesn't have to do it: pydoc and > similar tools could detect, say, '@deprecated' in method comment string and > warn user about it. I don't see what's wrong with this code, and if one wanted, one could also implement a decorator which calls warnings.warn when the function is called: def c_buffer(init, size=None): "deprecated, use create_string_buffer instead" import warnings warnings.warn("c_buffer is deprecated, use create_string_buffer instead", DeprecationWarning, stacklevel=2) return create_string_buffer(init, size) Thomas From sjmachin at lexicon.net Sun Jul 31 20:14:19 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 01 Aug 2005 10:14:19 +1000 Subject: subclassing list In-Reply-To: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> References: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> Message-ID: <42ed695a$1@news.eftel.com> spike wrote: > I've googled like crazy and can't seem to find an answer to why this > isn't working. > > I want to create a custom list class that acts as a circular list. > > ie: my_list = (0, 1, 2) Perhaps you mean [0, 1, 2] > > how I want it to behave: > > my_list[0] -> 0 > my_list[1] -> 1 > my_list[2] -> 2 > my_list[3] -> 0 > my_list[4] -> 1 > ...etc > > so, what I've tried to do is: > > def circular_list(list): > def __getitem__(self, i): > if (i >= len(self)): > return self[i % len(self)] > else: > return self[i] > > items = circular_list(range(8)) > > however, when I want to iterate over it with a for statement, I get: > > TypeError: iteration over non-sequence > > what am I missing? 0.1 Elementary debugging, like a "print" statement after "items = cir......" 0.2 pychecker -- These warning messages might have given you a clue: spike.py:2: Local variable (__getitem__) not used spike.py:2: Parameter (list) not used 1. A "class" statement. Your *function* circular_list returns None, which is a non-sequence. 2. A definition of what "in" a circular_list really means: in your example, 7 is obviously "in", but is 15 "in" or "not in"? Do you want "if x in a_circ_list" to be compatible with "for x in a_circ_list"? 3. An abhorrence of superfluous parentheses. 4. Battle-scars: you haven't been hit with "RuntimeError: maximum recursion depth exceeded" before, have you? After you've done s/def/class/ and put in some elementary test statements like "print items[3]", run it again and seen what happens, Google search for "__getitem__ infinite recursion" in this newsgroup. HTH, John From sjmachin at lexicon.net Thu Jul 14 09:04:57 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Jul 2005 23:04:57 +1000 Subject: How can I import a py script by its absolute path name? In-Reply-To: <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> Message-ID: <42d662f8$1@news.eftel.com> Thorsten Kampe wrote: > * Edvard Majakari (2005-07-14 12:52 +0100) > >>could ildg writes: >> >>>I want to import c:\xxx\yyy\zzz.py into my programme, >>>What should I do? >>>Thank you~ >> >>import sys >>sys.path.append('c:\xxx\yyy') > > > "sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')" or "sys.path.append(r'c:\xxx\yyy')" From roy at panix.com Fri Jul 8 13:01:37 2005 From: roy at panix.com (Roy Smith) Date: 8 Jul 2005 13:01:37 -0400 Subject: Use cases for del References: <42CE0E38.60305@REMOVEMEcyber.com.au> Message-ID: Daniel Dittmar wrote: > In a SQL database, NULL = NULL will always return NULL, which is prety > much the same as FALSE. Except for NOT, AS NOT NULL is NULL. SQL's NULL is very much akin to the IEEE NaN (not quite, but close). From cliff at develix.com Sun Jul 31 16:53:02 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 13:53:02 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <7xy87nctxm.fsf@ruckus.brouhaha.com> References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> Message-ID: <1122843183.19618.121.camel@localhost.localdomain> On Sun, 2005-07-31 at 00:32 -0700, Paul Rubin wrote: > Those issues about the 1600 dependencies don't apply nearly as much to > pure Python modules (e.g. Twisted) as they do to extension modules > that require the presence of further stuff on the system. E.g., on > Linux, to use wxPython, you need wxWidgets, which needs GTK 1.5, which > has been obsolete for years, and there are all sorts of build > conflicts when you try to compile this stuff out of the box. I don't > know where Dabo fits in. It does sound nice in some regards. wxWidgets/wxPython hasn't required GTK 1.x in quite a long time. Please get your facts straight. Also, the "1600" dependencies you complain about come standard on any modern Linux system or can be easily installed with the system's package management tool. I've also built wxPython from source on OS/X, which, while orders of magnitude more difficult than on Linux, still wasn't that hard. I'm seriously getting the impression you are criticizing something you've never even tried. > Pico Lisp uses an interesting approach to portable GUI's: it includes > a socket-based GUI API and a special Java applet that runs in a > browser and implements the API. All the issues of dealing with > OS-specific window systems go away, as long as you can run a > Java-enabled browser and point it at the Pico Lisp application. See: > > http://www.software-lab.de/down.html It sounded interesting until you said "Java Applet". Talk about causing deployment issues... Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From gene.tani at gmail.com Sun Jul 3 12:38:20 2005 From: gene.tani at gmail.com (gene tani) Date: 3 Jul 2005 09:38:20 -0700 Subject: website catcher In-Reply-To: <1120403696.212030.120390@g43g2000cwa.googlegroups.com> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> <3iq5e7Fmn8drU1@uni-berlin.de> <1120396132.606888.322880@g14g2000cwa.googlegroups.com> <3iq8juFmr22qU1@uni-berlin.de> <1120403696.212030.120390@g43g2000cwa.googlegroups.com> Message-ID: <1120408700.853912.150710@o13g2000cwo.googlegroups.com> maybe look at Harvestman http://cheeseshop.python.org/HarvestMan/1.4%20final From bokr at oz.net Fri Jul 1 23:55:43 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 02 Jul 2005 03:55:43 GMT Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> <5aj2c11l5vl4qds031uj7ucikikcf7uvji@4ax.com> Message-ID: <42c60f3b.300522458@news.oz.net> On Tue, 28 Jun 2005 14:44:21 +0100, Richie Hindle wrote: > >[Christos, on widening the Windows Command Prompt] >> Hm... right-click the cmd.exe window's title bar (or click on the >> top-left icon, or press Alt-Space), go to Properties, Layout tab, Window >> Size, Width. > >Just to take this thread *completely* off-topic: does anyone know of a way >to scroll a Command Prompt window using the keyboard? > Alt-spacebar, e, l, (uparrow/downarrow)*, Esc (lower case L)--^ ^^^^^^^^^^^^^^^^^--does the scrolling. Esc ends the scrolling mode. Seems to work for cmd.exe on NT4 Regards, Bengt Richter From jsbraich at gmail.com Thu Jul 21 09:10:03 2005 From: jsbraich at gmail.com (jb) Date: 21 Jul 2005 06:10:03 -0700 Subject: popen2 usage References: <1121799002.440543.206050@g43g2000cwa.googlegroups.com> Message-ID: <1121951403.051647.212920@g47g2000cwa.googlegroups.com> Actually, "-test1" is a text argument that testme.exe should receive from standard input. For example, Executing testme.exe generates the following output, Please select one of the following options: 1) test1 2) test2 3) exit Please enter your option here:-test1 <-This -test1 is what user would type Thanks, -JB Steven Bethard wrote: > jb wrote: > > Hi there: > > > > I need help with popen2 usage. I am coding on Windows 2000 environment > > and I am basically trying to run command line executable program that > > accepts command line arguments from user. I want to be able to provide > > these arguments through input pipe so that executable does not require > > any intervention from the user. The way I am doing this is as below: > > > > out1, in1 = popen2.popen2("testme.exe > abc.txt") > > in1.write('-test1') > > in1.flush() > > in1.close() > > > > But this does not seem to be working, when I open abc.txt file it does > > not show '-test1' argument that was supplied via in1.write method. This > > causing executable to wait forever unless user manually kills the > > process. > > I'm confused; is "-test1" a command line argument to testme.exe? Or is > it the text that testme.exe should receive from standard input? > > Either way, I would suggest using subprocess instead of popen*. > > To pass -test1 as a command line argument, do something like: > > import subprocess as sp > p = sp.Popen(["testme.exe", "-test1"], stdout=sp.PIPE) > out1 = sp.stdout.read() > > To pass -test1 through standard input, do something like: > > import subprocess as sp > p = sp.Popen(["testme.exe"], stdout=sp.PIPE) > p.stdin.write("-test1") > p.stdin.flush() > p.stdin.close() > out1 = p.stdout > > HTH, > > STeVe From nospam at [127.0.0.1] Tue Jul 19 02:24:19 2005 From: nospam at [127.0.0.1] (Chris) Date: Tue, 19 Jul 2005 07:24:19 +0100 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? Message-ID: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? I have been getting very variable SNR readings - and I would like to collect some evidence to analyse. What is needed is a program that logs into the router's html page every minute, and then extracts the time and the SNR figure, and writes a line of a text file. I reckon it would be useful to many people. -- Chris From p.c.j.kleiweg at rug.nl Wed Jul 6 15:35:45 2005 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Wed, 6 Jul 2005 21:35:45 +0200 Subject: from date/time string to seconds since epoch In-Reply-To: <1120677815.189895.11580@f14g2000cwb.googlegroups.com> References: <1120677815.189895.11580@f14g2000cwb.googlegroups.com> Message-ID: wittempj at hotmail.com schreef op de 6e dag van de hooimaand van het jaar 2005: > You can calculate the offset of where you are like this: > > martin at ubuntu:~ $ python > Python 2.4.1 (#2, Mar 30 2005, 21:51:10) > [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> import time > py> offset = 0 > py> if time.daylight: > py. offset = time.altzone > py. else: > py. offset = time.timezone > py. > py> print offset > -7200 > py> > > You can use time.time() to get the UTC time, then add the offset. The offset is for this moment, not for the date and time of the string parsed. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From peter at engcorp.com Sun Jul 24 15:09:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Jul 2005 15:09:32 -0400 Subject: tuple to string? In-Reply-To: References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> <42e381a6@news.eftel.com> Message-ID: <2IqdneotdYPhen7fRVn-gA@powergate.ca> Steven D'Aprano wrote: > Still, the subject is rapidly losing whatever interest it may have had. It had none. Kill it. "Kill the witch!" From eurleif at ecritters.biz Tue Jul 19 19:04:22 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 19 Jul 2005 23:04:22 GMT Subject: How to send a query to the browser from time to time? In-Reply-To: References: Message-ID: Admin wrote: > I am creating a chat application like Messenger for the web (using the > browser) and I'm wondering if there is a way to receive new messages > from time to time from the server other than refreshing the page each 5 > sec. Here's a pretty basic example I wrote a while ago using Twisted: . The server keeps the connection open and sends messages when they occur, with the side effect of keeping the browser's page-loading indicator alive indefinitely. From bokr at oz.net Sun Jul 10 17:03:57 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 10 Jul 2005 21:03:57 GMT Subject: decorators as generalized pre-binding hooks References: <42d02c21.231516573@news.oz.net> <9s2Ae.227054$w15.137655@tornado.tampabay.rr.com> Message-ID: <42d1813e.318841369@news.oz.net> On Sun, 10 Jul 2005 05:35:01 GMT, Ron Adam wrote: >Bengt Richter wrote: >> ;-) >> We have > >Have we? > >Looks like not a lot of interested takers so far. > >But I'll bite. ;-) > > > > >> So why not >> >> @deco >> foo = lambda:pass >> equivalent to >> foo = deco(lambda:pass) > > >> and from there, >> @deco >> = >> being equivalent to >> = deco() >> >> e.g., >> @range_check(1,5) >> a = 42 >> for >> a = range_check(1,5)(42) >> >> or >> @default_value(42) >> b = c.e['f']('g') >> for >> b = default_value(42)(c.e['f']('g')) > >So far they are fairly equivalent. So there's not really any advantage >over the equivalent inline function. But I think I see what you are >going towards. Decorators currently must be used when a function is >defined. This option attempts to makes them more dynamic so that they >can be used where and when they are needed. IMO part of the decorator benefit is clearer code, and also IMO the @range_check and @default_value decorators succeed in that. The code generated would presumably be the same, unless the exception capture discussed further down were implemented. > >How about if you make it optional too? > >if keep_log: > @log_of_interesting_values >b = get_value(c,d): > I'd probably pass the condition to the decorator for a less ragged look @log_of_interesting_values(keep_log) b = get_value(c,d) >Or... > >@@keeplog log_of_interesting_values # if keeplog decorate. >b = get_value(c,d) > >Just a thought. Yes, but that is too easy to do another way. Plus I want to reserve '@@' for an AST-time decoration idea I have ;-) > >> Hm, binding-intercept-decoration could be sugar for catching exceptions too, >> and passing them to the decorator, e.g., the above could be sugar for >> >> try: >> b = default_value(42)(c.e['f']('g')) >> except Exception, e: >> b = default_value(__exception__=e) # so decorator can check >> # and either return a value or just re-raise with raise [Note 1] > >I'm not sure I follow this one.. Well I do a little. Looks like it might >be going the direction of with statements, but only applied to a single >expression instead of a block or suite. Yes, it's just expanding on the idea of intercepting the value of the object being bound even if the creation of that object resulted in an exception, and allowing the decorator to handle it either way. > > >> This might be useful for plain old function decorators too, if you wanted the decorator >> to define the policy for substituting something if e.g. a default argument evaluation >> throws and exception. Thus >> >> @deco >> def foo(x=a/b): pass # e.g., what if b==0? >> as >> try: >> def foo(x=a/b): pass # e.g., what if b==0? >> foo = deco(foo) >> except Exception, e: >> if not deco.func_code.co_flags&0x08: raise #avoid mysterious unexpected keyword TypeError >> foo = deco(__exception__=e) > >Wouldn't this one work now? I think all the second-versions would work now, but a plain decorator won't get control if the def fails, so the def name won't get bound: >>> def deco(f): print f; return f # noop ... >>> @deco ... def foo(x=1/2): pass ... >>> foo >>> del foo >>> foo Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined >>> @deco ... def foo(x=1/0): pass ... Traceback (most recent call last): File "", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> foo Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined > >> [Note 1:] >> Interestingly raise doesn't seem to have to be in the same frame or down-stack, so a decorator >> called as above could re-raise: >> >> >>> def deco(**kw): >> ... print kw >> ... raise >> ... >> >>> try: 1/0 >> ... except Exception, e: deco(__exception__=e) >> ... >> {'__exception__': } >> Traceback (most recent call last): >> File "", line 2, in ? >> File "", line 1, in ? >> ZeroDivisionError: integer division or modulo by zero > >Interestin. Yes, it would seem to give one the option of catching an exception and doing some arbitarily (so long as not new-exception-raising) recursive or deep calls and bailing out from some leaf point with a raise. > >When it comes to decorators, and now the with statements, I can't help >but feel that there's some sort of underlying concept that would work >better. It has to do with generalizing flow control in a dynamic way >relative to an associated block. > >One thought is to be able to use a place holder in an expression list to >tell a statement when to do the following block of code. it depends on scope and control aspects of what you mean by "block". But I doubt if we have much chance of introducing something is one more bf in the storm of "with" ideas that have already been discussed. > >I'll use 'do' here... since it's currently unused and use @@@ as the >place holder. > >(These are *NOT* thought out that far yet, I know... just trying to >show a direction that might be possible.) > They strike me as a kind of macro idea where the only substitution argument is the block suite that follows, which IMO is a severe limitation on both the macro idea and the use of blocks ;-) [...] > >I like the place holders because I think they make the code much more >explicit and they are more flexible because you can put them where you >need them. Yes, but if you want to go that way, I'd want to have named place holders and be able to refer to arbitrary things that make sense in the context. > > >> orthogonal-musing-ly ;-) > >"Orthogonal is an unusual computer language in which your program flow >can go sideways. In actuality in can go in just about any direction you >could want." > > http://www.muppetlabs.com/~breadbox/orth/ Interesting. And an implementation from our own Jeff Epler? Regards, Bengt Richter From jrastrick at student.usyd.edu.au Wed Jul 27 21:04:51 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 27 Jul 2005 18:04:51 -0700 Subject: Path inherits from basestring again In-Reply-To: References: Message-ID: <1122512691.346915.43290@g49g2000cwa.googlegroups.com> Personally, I *like* the current distinction between + as a regular string join, which gives the already much discussed benefit of allowing paths to be dropped in seamlessly and painlessly anywhere strings are currently used, and then having in addition the / operator for "concatenate with a path separator." I think its intuitive, and the option least likely to surprise someone encountering code that uses the Path class for the first time - + works exactly like it always does, and if they see a slash, which is an entirely new operator for string-like objects, they'll be alerted to the fact they're getting behaviour that differs from familiar string operators and methods. Having + work differently when acting between a string and a path versus a path and a path is in my mind a potential source of annoying and subtle bugs, although hopefully they'd be rare in sensibly written path-oriented code. Sure, / means something completely different in the context of numbers. So what? + and * are very different operators for numbers vs. strings, but it doesn't generally trouble people too much; + has become pretty widespread in programming conciousness as a string concatinator. I don't think the argument that / and * are natural inverses holds much water, either. In the context of sets in Python, - means set difference, and +, its 'natural inverse', means nothing (in mathematics, it typically means symmetric difference, which is certainly not in any sense the inverse of -). This is all based on arbitrary mathematical convention. The important point is that it results in readable code for people who've dealt with sets before, while trying to minimise the potential for surprises; not that it tries to mirror the relationships between arithmetic operators, which I don't think is an especially reasonable or normal thing to expect. And I'm born and bred (unfortunately) on Windows machines, I do ALL my Python programming in a Windows environment, so the "forward slash is only an intuitive path seperator for POSIX hackers" argument doesn't apply. After all, anyone who's had any exposure to the internet can't be entirely unfamiliar with the fact that forward slash can be used as a path(-like) separator (please don't construe this as an attempt to resurrect the "path should be used for URLs too" debate, though). Ultimately, its just not different enough from backslash to be very confusing (hear I'll put in a disclaimer, that I don't have enough computing experience to know of any OS where neither type of slash is used in paths.) And thats my 14.5 cents :) - Jordan Rastrick Ron Adam wrote: > Michael Hoffman wrote: > > Ron Adam wrote: > > > >> In all current cases, (that I know of), of differing types, '+' raises > >> an error. > > > > > > Not quite: > > > > >>> "hello " + u"world" > > u'hello world' > > >>> 4.5 + 5 > > 9.5 > > > >> Question: Is a path object mutable? > > > > > > No. > > > > This should answer the rest of your questions. > > Yes it does, thanks. > > In the case of numeric types, it's an addition and not a join. I should > have specified in 'all cases, (I know of), where '+' is used to join > objects, but I thought that was clear from the context of the > discussion. I haven't needed to use unicode yet, so it didn't come to mind. > > > Although it raises other questions... ;-) > > Could a string prefix be used with paths as well? > > path = p"C://somedir//somefile" > > > Would that clash with the 'u' prefix? Or would we need a 'p' and a 'up' > prefix to differentiate the two? > > (Just a thought. I'm +0 on this, but this seems to be a new string type, > and file operations are frequent and common.) > > > > You could have both behaviors with the '+'. > > path_a + path_b -> join path_b to path_a using separator. > > path + string -> append string to path (no separator) > > string + path -> prepends string to path (no separator) > > > This would be similar, (but not exactly like), how u'text'+'text' and > 'text'+u'text' work. They both return unicode strings given a standard > string. It would allow the following to work. > > > path = path('C:')+path('somedir')+path('somefile.txt')+'.zip' > > ->> 'C://somedir//somefile.txt.zip' > > > > So I guess the question here is which of these is preferable with '+'? > > 1. Strings act like paths when one is a path. They will be joined with > a separator. > > 2. Paths are joined with separators *and* a string is prepended or > postpended "as is" with no separator. > > 3. All path objects (and strings) act like strings. No separator is > used when joining path objects with '+'. > > > (Seems like #3 defeats the purpose of path a bit to me.) > > > I'm +1 on #2 after thinking about it. > > Cheers, > Ron From brian at mirror.org Fri Jul 8 17:36:26 2005 From: brian at mirror.org (brian at mirror.org) Date: 8 Jul 2005 14:36:26 -0700 Subject: Legacy data parsing In-Reply-To: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: <1120858586.672988.130440@g44g2000cwa.googlegroups.com> > > Where I work, we receive large quantities of data which is currently > all printed on large, obsolete, dot matrix printers. This is a problem > because the replacement parts will not be available for much longer. > > So I'm trying to create a program which will capture the fixed width > text file data and convert as well as sort the data (there are several > different report types) into a different format which would allow it to > be printed normally, or viewed on a computer. > Do you have access to the programs that generate these reports? If so, its probably a simple fixed format, and you can pull the fields out with the slice operator (eg name = line[30:40]) -- no regular expressions necessary. I've done this in a couple of cases, and its easy *if* you know exactly what the report format is. Or, consider using another tool. I've also used Monarch (a purchased program) for parsing reports, and its works well on most formats. Brian. From steven.bethard at gmail.com Sat Jul 9 21:32:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 09 Jul 2005 19:32:11 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > The root of this discussion has been the observation that a list > comprehension can be expressed in terms of list() and a generator > expression. As George Sakkis already noted, the root of the discussion was actually the rejection of the dict comprehensions PEP. > However, the former is faster when you actually want a list result I would hope that in Python 3.0 list comprehensions and generator expressions would be able to share a large amount of implementation, and thus that the speed differences would be much smaller. But maybe not... > and many people (including Guido) like the square brackets. ^ | This --------------------------+ of course, is always a valid point. ;) STeVe From hancock at anansispaceworks.com Tue Jul 5 12:08:00 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 11:08:00 -0500 Subject: what is __init__.py used for? In-Reply-To: <11ckscdmaucfe81@news.supernews.com> References: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> <11ckscdmaucfe81@news.supernews.com> Message-ID: <200507051108.00204.hancock@anansispaceworks.com> On Tuesday 05 July 2005 06:39 am, John Roth wrote: > The real kicker here is that when I say that the > first module will be completely empty, it's not > quite true. First, it will have some standard > identifiers that all modules have, and second > it will have anything you put into the __init__.py > module file. It's not at all uncommon, for example, for __init__.py to contain a set of imports: from SubMod1 import * import SubMod2 as sub etc, this is one way to create the "interface" that the package will present to you when you import it. > This last is an advanced feature, and > you're well advised to stay away from it until > you've got a lot more experiance. Not until you are writing Python packages, anyway. But it's probably a good idea to know what it does so that you can read what it's doing in packages you use and/or study (and studying existing packages is one of the best ways to learn once you've gotten beyond the basic hurdle of writing simple programs). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From kay.schluehr at gmx.net Sat Jul 30 06:07:01 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Jul 2005 03:07:01 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <1122715993.183245.40940@g43g2000cwa.googlegroups.com> <7xmzo4d48p.fsf@ruckus.brouhaha.com> Message-ID: <1122718021.897290.280710@g14g2000cwa.googlegroups.com> Paul Rubin wrote: > "Kay Schluehr" writes: > > Examples: > > f = ( || x>=0 then f(x) || True then f(-x) from (x,) ) > > g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,)) > > Is this an actual language? It looks sort of like CSP. Python > with native parallelism, mmmmm. The syntax was inspired by OCamls pattern matching syntax: match object with pattern1 -> result1 | pattern2 -> result2 | pattern3 -> result3 ... But for Python we have to look for an expression not a statement syntax. In order to prevent ambiguities I used a double bar '||' instead of a single one. Kay From bokr at oz.net Sat Jul 30 16:58:55 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Jul 2005 20:58:55 GMT Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <42ebe919.164695739@news.oz.net> On Fri, 29 Jul 2005 18:07:31 -0400, Mike Meyer wrote: >I know, lambda bashing (and defending) in the group is one of the most >popular ways to avoid writing code. However, while staring at some Oz >code, I noticed a feature that would seem to make both groups happy - >if we can figure out how to avoid the ugly syntax. > >This proposal does away with the well-known/obscure "lambda" >keyword. It gives those who want a more functional lambda what they >want. It doesn't add any new keywords. It doesn't add any new magic >characters, though it does add meaning to an existing one. That could >be replaced by a new magic token, or adding magic meaning to a >non-magic token. It breaks no old code either way. > >I haven't really worked out all the implications; I just wanted to >throw it out and see what everyone else thought about it. As a >result, the code examples tend to be ugly. > >As previously hinted, this feature is lifted from Oz. try http://groups-beta.google.com/groups?as_q=anonymous+def&as_ugroup=comp.lang.python for much discussion of this ;-) Regards, Bengt Richter From kraus at hagen-partner.de Mon Jul 25 05:08:22 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Mon, 25 Jul 2005 11:08:22 +0200 Subject: Retrieving and saving images from internet address In-Reply-To: <1122282085.216772.286680@z14g2000cwz.googlegroups.com> References: <1122282085.216772.286680@z14g2000cwz.googlegroups.com> Message-ID: rock69 wrote: > Hi all :) > > I got this address: > > http://www.infomedia.it/immagini/riviste/covers/cp/cp137.jpg > > and I would like to download that image and save it to a local file. > How do you do that in Python? > Use urllib2: http://docs.python.org/lib/module-urllib2.html http://docs.python.org/lib/urllib2-examples.html HTH, Wolfram From cantabile.03 at wanadoo.fr Fri Jul 8 05:53:56 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Fri, 08 Jul 2005 11:53:56 +0200 Subject: Pattern question In-Reply-To: <42ce3f20$0$13033$636a15ce@news.free.fr> References: <42cd5493$0$900$8fcfb975@news.wanadoo.fr> <42ce3f20$0$13033$636a15ce@news.free.fr> Message-ID: <42CE4D34.2000008@wanadoo.fr> bruno modulix a ?crit : > You may want to have a look at the Factory pattern... > > # outrageously oversimplified dummy exemple > class Gui(object): > def __init__(self, installer): > self.installer = installer > > class PosixGui(Gui): > pass > > class Win32Gui(Gui): > pass > > class GuiFactory(object): > def getGui(self, installer): > if os.name == 'posix': > return PosixGui(installer) > elif os.name == 'win32': > return Win32Gui(installer) > else: > raise "os %s not supported" % os.name > > class Installer(object): > def __init__(self, guiFactory): > self.gui = guiFactory.getGui(self) > > def main(): > inst = Installer(GuiFactory()) > return inst.gui.main() > > NB 1: > You may want to hide away the gui stuff: > > class Installer(object): > def __init__(self): > self.gui = GuiFactory().getGui(self) > > def main(self): > return self.gui.main() > > def main(): > return Installer().main() > Thanks for this, Bruno. It is much more elegant and adaptable than my first attempt. > > NB 2 : > if it has to run in text mode, you should consider renaming "gui" to > "ui", since a CLI is not really a 'graphical' ui !-) You're right :)) > NB 3 : > I made the GuiFactory a class, but it could also be a simple function. > NB 4 : > there are of course other solutions to the problem, which may or not be > more appropriate... > Thanks a lot for these detailed explanations. From richie at entrian.com Fri Jul 22 04:43:08 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 22 Jul 2005 09:43:08 +0100 Subject: Lots of pdf files In-Reply-To: References: Message-ID: [Duncan] > a mere $29.90, except it is GPL'd so I'm not sure what the money is for "Tech support [...] free forever for registered users." But I've often wondered whether you could charge for mass-market GPL software simply because your ordinary punter doesn't know what the GPL is, and doesn't mind paying a small amount of money for decent software. Whether it's ethical, given that presumably the thing is GPL because it inherits GPL code from other developers, I don't know. Certainly the GPL itself has no objection to charging for binaries provided you ship the source as well. -- Richie Hindle richie at entrian.com From peter at engcorp.com Wed Jul 27 18:22:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Jul 2005 18:22:45 -0400 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: Tito wrote: > Thank you both for your quick answers. > > What I wanted is to parameterize a function with another member > function, like this: > > def printFunctionForEach(collection, functionName): > for elem in collection: > print eval("elem." + functionName + "()") Note: "member function" is spelled "method" in Python. > Moreover, I wanted to do it with a property: > > def printPropertyForEach(collection, propertyName): > for elem in collection: > print eval("elem." + propertyName) And "property" (the way you are using it) is spelled "attribute". In Python, properties are something else, similar to but more than just attributes. Use of such terms according to conventional Python usage will in future make it somewhat easier to be understood and for you to understand the responses. Cheers, -Peter From rbt at athop1.ath.vt.edu Tue Jul 12 10:59:49 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 12 Jul 2005 10:59:49 -0400 Subject: breaking out of nested loop In-Reply-To: References: Message-ID: <1121180389.6655.0.camel@athop1.ath.vt.edu> Thanks guys... that works great. Now I understand why sometimes logic such as 'while not true' is used ;) On Tue, 2005-07-12 at 10:51 -0400, Peter Hansen wrote: > rbt wrote: > > What is the appropriate way to break out of this while loop if the for > > loop finds a match? > > Define a flag first: > > keepGoing = True > > > while 1: > while keepGoing: > > > for x in xrange(len(group)): > > try: > ... > > if match == target: > > print "Collision!!!" > > print make_string > > Set the flag here, then do the break: > keepGoing = False > > > break > > Tada... > > -Peter From twic at urchin.earth.li Sun Jul 3 15:53:22 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 3 Jul 2005 20:53:22 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: On Mon, 4 Jul 2005, Steven D'Aprano wrote: > On Sun, 03 Jul 2005 15:46:35 +0100, Tom Anderson wrote: > >> I think there would be a lot less confusion over the alleged inaccuracy of >> floating point if everyone wrote in hex - indeed, i believe that C99 has >> hex floating-point literals. C has always been such a forward-thinking >> language! > > No, all that would do is shift the complaint from "Python has a bug when > you divide 10 into 1.0" to "Python has a bug when you convert 0.1 into hex". Ah, but since the programmer would have to do that conversion themself, they wouldn't be able to blame python got it! >>> But this works: >>> >>> py> inf = float("inf") >>> py> inf >>> inf >> >> True. Still, i'd rather not have to rely on string parsing to generate a >> fairly fundamental arithmetic quantity. > > What happens when your Python script is running on a platform that can > deal with 1e300*1e300 giving 1e600 without overflow? Then i lose. > Okay, maybe no such platform exists today (or does it?), but it could > exist, and your code will fail on those systems. > > I believe that the IEEE standard specifies that float("inf") should give > an infinity, just as float("0.0") should give a zero. I think it's been pointed out that this fails on (some versions of?) windows. > For production code, I'd wrap float("inf") in a try...except and only > fall back on your method if it raised an exception, and then I'd > actually test that your result was a real inf (eg by testing that > inf+inf=inf). Okay, let's try this ... def mkinf(): try: return float("inf") except ValueError: x = 1e300 while ((x + x) != x): x = x * x return x inf = mkinf() Is that a portable solution? >>>> The IEEE spec actually says that (x == nan) should be *false* for >>>> every x, including nan. I'm not sure if this is more or less stupid >>>> than what python does! >>> >>> Well, no, the IEEE standard is correct. NaNs aren't equal to anything, >>> including themselves, since they aren't numbers. >> >> I don't buy that. Just because something isn't a number doesn't mean it >> can't be equal to something else, does it? I mean, we even say x == None >> if x is indeed None. > > Yes, but None does equal None, since there is only one None, and by > definition, a thing is equal to itself. Yes. > But NaNs are _not_ things. I disagree. A NaN _is_ a thing; it's not a floating-point number, for sure, but it is a symbol which means "there is no answer", or "i don't know", and as such, it should follow the universal rules which apply to all things. > That is the whole point! Yes, we _represent_ INF-INF as a particular > bit-pattern and call it NaN, but mathematically subtracting infinity > from infinity is not defined. There is no answer to the question "what > is infinity subtracted from infinity?". There is a value at large in my programs, represented however, meaning whatever, and with whatever name, and it should follow the same fundamental rules as every single other value in the entire programmatic universe. Yes, NaN is a special case, but special cases aren't special enough to break the rules. > We pretend that the answer is NaN, but that isn't right. The NaN is just > there as a placeholder for "there is no answer", so that we don't have > to sprinkle our code with a thousand and one tests. In the same way as None is a placeholder for "there is no thing". These placeholders are themselves things! > Since INF-INF doesn't have an answer, we can't do this: > > x = inf - inf > y = inf - inf > > and expect that x == y. I think we can. Both x and y have the same value, a value of indeterminacy. NaN is a rigidly defined value of doubt and uncertainty! >> Moreover, this freaky rule about NaNs means that this is an exception >> to the otherwise absolutely inviolate law that x == x. > > Yes. So what? Remove the NaN shorthand: > > "The non-existent answer to this question is the same non-existent answer > to this other question." Make sense to me. > It doesn't make sense to say that a non-thing is equal to anything -- even > to itself, since itself doesn't exist. > > (Remember, a NaN is just an illusionary placeholder, not a number.) If you think it's illusionary, i invite you to inspect the contents of my variables - i have a real, live NaN trapped in one of them! >> I'd rather have that simple, fundamental logical consistency than some IEEE >> rocket scientist's practical-value-free idea of mathematical consistency. > > Ah, from a _programmer's_ perspective, there is an argument that the > simplicity of just testing NaNs with equality outweighs the logical > silliness of doing such a thing. Yes. It may not be mathematically pure (although i argue that it is, in fact, as long as you don't think of floats as being real numbers), it is practical, and practicality beats purity. > But, apart from testing whether a float is a NaN, why would you ever > want to do an equality test? By definition, never. Isn't that usage reason enough? > The only usage case I can think of is would be something like this: > > def isNaN(x): > return x == SOME_KNOWN_NAN > > But that won't work, because there are lots of different NaNs. 254 of > them, or twice that if you include signed NaNs (which you shouldn't, but > you do have to allow for them in equality testing). Ah, well. There we have the question of whether python should implement full-blown IEEE arithmetic. This is somewhat heretical, but i think it shouldn't; i think it would be much better to adopt Java's noddy-IEEE approach, where there's exactly one NaN (although with well-behaved equality comparison). I realise this isn't going to happen, though. > Any good IEEE compliant system should already have a built-in function > that tests for NaNs. Agreed. >>>> And while i'm ranting, how come these expressions aren't the same: >>>> >>>> 1e300 * 1e300 >>>> 1e300 ** 2 >>> >>> Because this is floating point, not real maths :-) >>> >>> I get inf and Overflow respectively. What do you get? >> >> The same. They really ought to give the same answer. > > In real numbers, yes they should. In floating point, that is too much to > expect. Why on earth is that? All the code handling exponentiation has to do is trap the OverflowError and return an inf instead! > In mathematics, the order you do your calculation shouldn't matter. But > in floating point, where there is rounding errors and finite precision > issues, it does. True but, in this case, quite irrelevant. >>>> And finally, does Guido know something about arithmetic that i don't, >>>> or is this expression: >>>> >>>> -1.0 ** 0.5 >>>> >>>> Evaluated wrongly? >>> >>> No, it is evaluated according to the rules of precedence. It is >>> equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which >>> fails as expected. >> >> Ah. My mistake. I submit that this is also a bug in python's grammar. >> There's probably some terribly good reason for it, though. > > Yes. You generally want exponentiation to have the highest precedence. > > 2*3**4 should give 162, not 1296. Think about how you would write > that mathematically, with pencil and paper: the 4 is written as a > superscript over the 3, and is applied to that before multiplying by the 2. > > Unary minus is equivalent to multiplying by -1, so -3**4 is equivalent to > -1*3**4. > > These are the rules of precedence mathematicians have worked out over > many centuries. Yes, some of them are arbitrary choices, but they do > work, and changing them for another arbitrary choice doesn't give us any > benefit. I am utterly baffled. Three people so far have told me that exponentiation has higher precedence than unary minus *in conventional notation*. Are you really telling me that you think this expression: 2 -1 Evaluates to -1? tom -- When you mentioned INSERT-MIND-INPUT ... did they look at you like this? From sbassi at gmail.com Wed Jul 20 12:39:26 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Wed, 20 Jul 2005 13:39:26 -0300 Subject: python certification In-Reply-To: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> Message-ID: On 16 Jul 2005 09:51:55 -0700, lordverminard at gmail.com wrote: > i want to get a small certificate or diploma in python. > it should be online cuz i live in pakistan and wont have teast centers > near me. > it should be low cost as i am not rich. > and hopefully it would be something like a a begginer certification cuz > i am new to python. I could make a program, upload it to sourceforge (or similar OSS repository) and add that to your resume. Another opcion is to help in the development of any python-based program and work enought to be included in the authors list. That could be useful too (because you learn and do some good for more people). I believe more in a working program than a paper based certificate. -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From cvrebert at gmail.com Thu Jul 7 06:34:16 2005 From: cvrebert at gmail.com (Chris Rebert (cybercobra)) Date: 7 Jul 2005 03:34:16 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: Message-ID: <1120732456.491954.17780@o13g2000cwo.googlegroups.com> Agreed, I dislike map and its ilk as well. However, they are handy in some cases. I particularly like the way Ruby deals with this problem. Instead of all these functions, internal iterators and true anonymous blocks are used. Case in point: def gt_than_5(obj): return obj > 5 results = filter(gt_than_5, seq) becomes results = seq.find_all do |item| item > 5 end This has the advantage of writing less code for the common cases by having them builtin to the class. Instead of everyone needlessly recoding these over and over again, they're implemented in one place. This could be done by defining an abstract class that enumerable objects inherit from. It's not practical, but I can dream, can't I? ;-) Also, you don't have to define a separate testing function. Granted, in this case, the test func is trivial, but when it's non-trivial, you really notice the advantages. Ivan Van Laningham wrote: > Hi All-- > > Tom Anderson wrote: > > > > Comrades, > > > > "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme > > folks. :-)" > > > > I disagree strongly with Guido's proposals, and i am not an ex-Lisp, > > -Scheme or -any-other-functional-language programmer; my only other real > > language is Java. I wonder if i'm an outlier. > > > > So, if you're a pythonista who loves map and lambda, and disagrees with > > Guido, what's your background? Functional or not? > > > > I'm a pythonista who doesn't love them. In fact, even though I've done > more than my fair share of lambda Tkinter programming using lambdas, > I've never been happy with lambda. And I've spent months inside of > Lisp/Emacs Lisp/Scheme, too (I have the world's second largest .emacs > file [my friend Andy Glew has the largest], even though I can't use it > on Windows;-). I find list comprehensions easier to understand than > map, and small named functions or, better yet, class methods, *tons* > easier to read/understand than lambda--there are too many restrictions > you have to remember. > > Personally, I find that Lisp & its derivatives put your head in a very > weird place. Even weirder than PostScript/Forth/RPN, when you come > right down to it. > > I won't miss them, but since I don't use them now, that doesn't mean a > whole lot. > > Metta, > Ivan > ---------------------------------------------- > Ivan Van Laningham > God N Locomotive Works > http://www.andi-holmes.com/ > http://www.foretec.com/python/workshops/1998-11/proceedings.html > Army Signal Corps: Cu Chi, Class of '70 > Author: Teach Yourself Python in 24 Hours From kay.schluehr at gmx.net Sat Jul 9 04:26:23 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 Jul 2005 01:26:23 -0700 Subject: Hosting Python projects References: Message-ID: <1120897583.911206.304810@g43g2000cwa.googlegroups.com> Jacob Page schrieb: > I have created what I think may be a useful Python module, but I'd like > to share it with the Python community to get feedback, i.e. if it's > Pythonic. If it's considered useful by Pythonistas, I'll see about > hosting it on Sourceforge or something like that. Is this a good forum > for exposing modules to the public, or is there somewhere > more-acceptable? Does this newsgroup find attachments acceptable? > > -- > Jacob One side-question: has anyone made experiences in hosting his open source project on http://www.python-hosting.com/ Regards, Kay From exarkun at divmod.com Sun Jul 3 14:59:20 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 3 Jul 2005 14:59:20 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: Message-ID: <20050703185920.26278.67383571.divmod.quotient.4961@ohm> On Sun, 03 Jul 2005 14:43:14 -0400, Peter Hansen wrote: >Steven D'Aprano wrote: >> Frankly, I find this entire discussion very surreal. Reduce etc *work*, >> right now. They have worked for years. If people don't like them, nobody >> is forcing them to use them. Python is being pushed into directions which >> are *far* harder to understand than map and reduce (currying, decorators, >> etc) and people don't complain about those. > >I find it surreal too, for a different reason. > >Python *works*, right now. It has worked for years. If people don't >like the direction it's going, nobody is forcing them to upgrade to the >new version (which is not imminent anyway). > >In the unlikely event that the latest and greatest Python in, what, five >years or more?, is so alien that one can't handle it, one has the right >to fork Python and maintain a tried-and-true-and-still-including-reduce- >-filter-and-map version of it, or even just to stick with the most >recent version which still has those features. And that's assuming it's >not acceptable (for whatever bizarre reason I can't imagine) to use the >inevitable third-party extension that will provide them anyway. > >I wonder if some of those who seem most concerned are actually more >worried about losing the free support of a team of expert developers as >those developers evolve their vision of the language, than about losing >access to something as minor as reduce(). This is a specious line of reasoning. Here's why: Lots of people use Python, like Python, want to keep using Python. Moreover, they want Python to improve, rather than the reverse. Different people have different ideas about what "improve" means. Guido has his ideas, and since he's the BDFL, those are the ideas most likely to influence the direction of Python's development. However, Guido isn't the only person with ideas, nor are his ideas the only ones that should be allowed to influence the direction of Python's development. Guido himself wouldn't even be silly enough to take this position. He knows he is not the ultimate source of wisdom in the world on all matters programming related. So when people disagree with him, suggesting that they should leave the Python community is ridiculous. Just like Guido (and the overwhelming majority of the Python community - heck, maybe even all of it), these people are trying to improve the language. Leaving the community isn't going to improve the language. Continuing to operate actively within it just might. For my part, I lack the time and energy to participate in many of these discussions, but anyone who knows me knows I'm not silent because I see eye to eye with Guido on every issue :) I'm extremely greatful to the people who do give so much of their own time to try to further the Python language. Suggesting people can "like it or lump it" is a disservice to everyone. (Sorry to single you out Peter, I know you frequently contribute great content to these discussions too, and that there are plenty of other people who respond in the way you have in this message, but I had to pick /some/ post to reply to) Jp From enas_khalil at yahoo.com Mon Jul 11 10:06:54 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Mon, 11 Jul 2005 07:06:54 -0700 (PDT) Subject: ImportError: No module named numarray Message-ID: <20050711140654.34220.qmail@web50302.mail.yahoo.com> when i write a code to import some module like the following : from nltk.probability import ConditionalFreqDist I got the error : Traceback (most recent call last): File "C:\Python24\toky.py", line 1, in -toplevel- from nltk.probability import ConditionalFreqDist File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, in -toplevel- import types, math, numarray ImportError: No module named numarray can you please tell me the cause --------------------------------- Sell on Yahoo! Auctions - No fees. Bid on great items. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Sun Jul 3 15:48:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 15:48:10 -0400 Subject: need to get an index for an item in a list In-Reply-To: References: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> Message-ID: Roy Smith wrote: > That being said, index() isn't isn't going to work if there are duplicate > lines in the file; it'll return the index of the first one. It will still work, if you are willing to do a bit of work to help it: >>> l = range(10) + [5] >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5] >>> l.index(5) 5 >>> l.index(5, 5+1) 10 As with str.index(), the one for list takes a second argument that specifies the index at which to start the search, allowing you to skip past items that have already been checked. That said, other approaches (such as Roy suggested in his other post) may well be more appropriate depending on the context. -Peter From daniel.dittmar at sap.corp Tue Jul 12 12:00:16 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 12 Jul 2005 18:00:16 +0200 Subject: automatic form filling In-Reply-To: References: Message-ID: > I would like to know how I could automatically fill a > (search) form on a web page and download the resulting > html page. http://wwwsearch.sourceforge.net/ClientForm/ Daniel From peter at engcorp.com Tue Jul 12 10:51:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Jul 2005 10:51:45 -0400 Subject: breaking out of nested loop In-Reply-To: References: Message-ID: rbt wrote: > What is the appropriate way to break out of this while loop if the for > loop finds a match? Define a flag first: keepGoing = True > while 1: while keepGoing: > for x in xrange(len(group)): > try: ... > if match == target: > print "Collision!!!" > print make_string Set the flag here, then do the break: keepGoing = False > break Tada... -Peter From news at bilnoski.net Sun Jul 10 23:07:28 2005 From: news at bilnoski.net (Paul Bilnoski) Date: Sun, 10 Jul 2005 22:07:28 -0500 Subject: What is Expresiveness in a Computer Language? In-Reply-To: <1121044120.904683.266560@g14g2000cwa.googlegroups.com> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <1121044120.904683.266560@g14g2000cwa.googlegroups.com> Message-ID: > The barbar generals will just grunt while the French generals > will inspire with some poetic invocation. For auction: One authentic French army-issued rifle. Only dropped once. --Paul From jepler at unpythonic.net Fri Jul 22 11:03:27 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 22 Jul 2005 10:03:27 -0500 Subject: time.time() under load between two machines In-Reply-To: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> Message-ID: <20050722150323.GA25836@unpythonic.net> What makes you believe that the two machines' clocks are perfectly synchronized? If they're not, it easily explains the result. I wrote a simple client/server program similar to what you described. Running on two RedHat 9 machines on a local network, I generally observed a time delta of 2ms (compared to typical 0.17ms latency reported by "ping"), never in a negative direction. These machines times are synchronized by ntpd from the package ntp-4.1.2-0.rc1.2. My program can be run like this: rsh otherhost python timely.py -s | python timely.py -r the values printed are the difference between the remote time before the message is sent and the local time after the message is received. You mention using Windows. I don't know whether Windows machines by default use anything as sophisticated as ntpd to keep their clocks accurate. Whatever is going on in your case, I suspect it is the operating system, not Python. Jeff import os, sys, time def serve(): while 1: data = struct.pack("!d", time.time()) os.write(1, data) time.sleep(1) def recv(fileno): while 1: data = struct.unpack("!d", os.read(fileno, 8))[0] now = time.time() print now - data if sys.argv[1] == "-s": serve() else: recv(0) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From francois.perche at gmail.com Sun Jul 10 18:21:52 2005 From: francois.perche at gmail.com (perchef) Date: 10 Jul 2005 15:21:52 -0700 Subject: ZipFile and file rigths In-Reply-To: References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> Message-ID: <1121034112.762673.31530@z14g2000cwz.googlegroups.com> > ZIP doesn't store file permissions. ok, but in that case how could stuffit retrieve these permissions ? Thanks for the link Robert. From godoy at ieee.org Sat Jul 30 17:44:36 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 30 Jul 2005 18:44:36 -0300 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Ed Leafe wrote: > On Saturday 30 July 2005 16:06, Jorge Godoy wrote: > >> If it is added, let us know. ?I can't think of a better way to visualize >> database reports in an easy and fast way. ?Specially for BI. > > What specifically are you looking for? We are working on the report > writing engine now, tying in ReportLab. Bar and line graphics, mainly. In an easy and portable way. Something that calculates the axis scales automatically, that allows users to change some information, add legends, put values in specific points and all those things that are common to business graphs. I know it is a lot complex, specially due to user interaction, but it is doable. I have some ideas and I'll be implementing them with PyQt for some projects, but they aren't my first priority now. -- Jorge Godoy From steven.bethard at gmail.com Sat Jul 9 00:29:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Jul 2005 22:29:30 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <78huc11mgkvn1sho01qegi221k7hhc5u1p@4ax.com> References: <78huc11mgkvn1sho01qegi221k7hhc5u1p@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Fri, 08 Jul 2005 16:07:50 -0600, Steven Bethard > declaimed the following in comp.lang.python: > >>I only searched a few relatively recent threads in c.l.py, so there are >>probably more, but it looks to me like the final decision will have to >>be made by a pronouncement from Guido. > > Great... It takes me two releases of Python to get comfortable > with them, and then they are threatened to be removed again... > > Might as well submit the language to ISO for standardization -- > then I wouldn't be following an erratic target Two points: (1) There's no reason to get uncomfortable even if they're removed. You'd just replace [] with list(). (2) *IMPORTANT* If this happens *at all*, it won't happen until Python 3.0, which is probably at least 5 years away. And the Python 2.X branch will still be available then, so if you don't like Python 3.0, you don't have to use it. STeVe From steve at holdenweb.com Mon Jul 25 01:51:57 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Jul 2005 06:51:57 +0100 Subject: Importing User-defined Modules In-Reply-To: References: Message-ID: Walter Brunswick wrote: > I need to import modules with user-defined file extensions that differ from '.py', and also (if possible) redirect the bytecode > output of the file to a file of a user-defined extension. > I've already read PEP 302 (http://www.python.org/peps/pep-0302.html), but I didn't fully understand it. Would someone [who > understands it] please be able to give me a synopsis of it, along with a few explanatory examples, or some other alternatives, if > any? > > Well, under the PEP302 regime, as well as all the usual suspects you can add to sys.path you can also add "importer" objects. These objects will have specific methods (find_module and load_module) called at specific times during the import process. Because there can be a significant amount of time spent initializing an importer object the system now uses a cache of importers, which it's sensible to clear when adding a new importer. I attach code below that implements an importer that loads modules from a database, plus the program that actually creates the database containing the modules. This was only a test of my understanding, but it may help you to move further towards PEP302. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -------------- next part -------------- A non-text attachment was scrubbed... Name: dbload.py Type: application/x-python Size: 4348 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dbimp.py Type: application/x-python Size: 2104 bytes Desc: not available URL: From sjmachin at lexicon.net Mon Jul 11 20:12:33 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 12 Jul 2005 10:12:33 +1000 Subject: extend for loop syntax with if expr like listcomp&genexp ? In-Reply-To: <42d30319.417620065@news.oz.net> References: <42d30319.417620065@news.oz.net> Message-ID: <42d30af1$1@news.eftel.com> Bengt Richter wrote: > E.g., so we could write > > for x in seq if x is not None: Chundrous; looks like that p**l language ... > print repr(x), "isn't None ;-)" > > instead of > > for x in (x for x in seq if x is not None): Byzantine ... > print repr(x), "isn't None ;-)" > > just a thought. > What's wrong with the following? for x in seq: if x is not None: print repr(x), "isn't None ;-)" From tim.peters at gmail.com Sun Jul 3 13:09:34 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 3 Jul 2005 13:09:34 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae050703100969999291@mail.gmail.com> [Fredrik Johansson] >>> I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) >>> gives 3.9999999999999996, and this error could be avoided. [Steven D'Aprano] >> >>> math.exp(math.log(64)/3.0) >> 4.0 >> >> Success!!! [Tom Anderson] > Eeeeeeenteresting. I have no idea why this works. Given that math.log is > always going to be approximate for numbers which aren't rational powers of > e (which, since e is transcendental, is all rational numbers, and > therefore all python floats, isn't it?), i'd expect to get the same > roundoff errors here as with exponentiation. Is it just that the errors > are sufficiently smaller that it looks exact? Writing exp(log(x)*y) rather than x**y is in _general_ a terrible idea, but in the example it happens to avoid the most important rounding error entirely: 1./3. is less than one-third, so 64**(1./3.) is less than 64 to the one-third. Dividing by 3 instead of multiplying by 1./3. is where the advantage comes from here: >>> 1./3. # less than a third 0.33333333333333331 >>> 64**(1./3.) # also too small 3.9999999999999996 >>> exp(log(64)/3) # happens to be on the nose 4.0 If we feed the same roundoff error into the exp+log method in computing 1./3., we get a worse result than pow got: >>> exp(log(64) * (1./3.)) # worse than pow's 3.9999999999999991 None of this generalizes usefully -- these are example-driven curiousities. For example, let's try 2000 exact cubes, and count how often "the right" answer is delivered: c1 = c2 = 0 for i in range(1, 2001): p = i**3 r1 = p ** (1./3.) r2 = exp(log(p)/3) c1 += r1 == i c2 += r2 == i print c1, c2 On my box that prints 3 284 so "a wrong answer" is overwhelmingly more common either way. Fredrik is right that if you want a library routine that can guarantee to compute exact n'th roots whenever possible, it needs to be written for that purpose. ... > YES! This is something that winds me up no end; as far as i can tell, > there is no clean programmatic way to make an inf or a NaN; All Python behavior in the presence of infinities, NaNs, and signed zeroes is a platform-dependent accident, mostly inherited from that all C89 behavior in the presence of infinities, NaNs, and signed zeroes is a platform-dependent crapshoot. > in code i write which cares about such things, i have to start: > > inf = 1e300 ** 1e300 > nan = inf - inf That would be much more portable (== would do what you intended by accident on many more platforms) if you used multiplication instead of exponentiation in the first line. ... > And then god forbid i should actually want to test if a number is NaN, > since, bizarrely, (x == nan) is true for every x; instead, i have to > write: > > def isnan(x): > return (x == 0.0) and (x == 1.0) The result of that is a platform-dependent accident too. Python 2.4 (but not eariler than that) works hard to deliver _exactly_ the same accident as the platform C compiler delivers, and at least NaN comparisons work "as intended" (by IEEE 754) in 2.4 under gcc and MSVC 7.1 (because those C implementations treat NaN comparisons as intended by IEEE 754; note that MSVC 6.0 did not): >>> inf = 1e300 * 1e300 >>> nan == nan >>> nan = inf - inf >>> nan == 1.0 False >>> nan < 1.0 False >>> nan > 1.0 False >>> nan == nan False >>> nan < nan False >>> nan > nan False >>> nan != nan True So at the Python level you can do "x != x" to see whether x is a NaN in 2.4+(assuming that works in the C with which Python was compiled; it does under gcc and MSVC 7.1). > The IEEE spec actually says that (x == nan) should be *false* for every x, > including nan. I'm not sure if this is more or less stupid than what > python does! Python did nothing "on purpose" here before Python 2.4. > And while i'm ranting, how come these expressions aren't the same: > > 1e300 * 1e300 > 1e300 ** 2 Because all Python behavior in the presence of infinities, NaNs and signed zeroes is a platform-dependent accident. > And finally, does Guido know something about arithmetic that i don't, Probably yes, but that's not really what you meant to ask . > or is this expression: > > -1.0 ** 0.5 > > Evaluated wrongly? Read the manual for the precedence rules. -x**y groups as -(x**y). -1.0 is the correct answer. If you intended (-x)**y, then you need to insert parentheses to force that order. From http Sun Jul 31 22:33:05 2005 From: http (Paul Rubin) Date: 31 Jul 2005 19:33:05 -0700 Subject: Dabo in 30 seconds? References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> <7xr7de5zoe.fsf@ruckus.brouhaha.com> <7x3bpuzf2n.fsf@ruckus.brouhaha.com> Message-ID: <7xhdeaxu72.fsf@ruckus.brouhaha.com> Cliff Wells writes: > > That's sort of interesting. I think I downloaded whatever was on > > wxpython.org. > > Usually there will be a link to a couple different builds on > wxpython.org. I can see where it would be pretty easy to grab the wrong > one. IIRC the problem I had wasn't really with wxpython, it was with wxwidgets. I can't say for sure that I didn't make an error choosing a download but I thought I was sort of careful. From eric_brunel at despammed.com Mon Jul 4 03:00:50 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 04 Jul 2005 09:00:50 +0200 Subject: custom Tkinter ListBox selectMode References: <72lxe.52775$iU.757@lakeread05> Message-ID: On Fri, 1 Jul 2005 20:19:20 -0400, Ron Provost wrote: > Hello, > > I've written a simple GUI which contains a listbox to hold some information. > I've found that the click-selection schemes provided by Tkinter are > insufficient for my needs. Essentiall I need to impletement a custom > selectMode. As a first go, I've attempted to implement a click-on-click-off > mode. So for each entry, a click on that entry toggels its selection mode. > A click on any entry does not affect the selection mode of any other entry. What you describe is exactly the behavior you get when you set selectmode='multiple' on a list box; see: http://www.tcl.tk/man/tcl8.3/TkCmd/listbox.htm#M57 HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From mwm at mired.org Wed Jul 27 22:59:27 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 27 Jul 2005 22:59:27 -0400 Subject: [OT] Problems with permissions etc References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: <86y87rljow.fsf@bhuda.mired.org> "Frank Millman" writes: > While developing under linux, I use my own computer, as the only user, > so it has become my habit to login as root and do all my work as a > superuser. I know that this is not desirable, but it has become a > habit, which I am now trying to get out of. Ack. Phht. Well, at least you're trying to get out of the habit. Your problems are generally caused by doing things as the wrong user. You need to figure out which things you have to do as root, and then do those (and only those) as root, and do the rest as you. > 1. The application I am developing will eventually be deployed as a > multi-user accounting/business system. I want to identify the physical > workstation that generates each transaction, so I am using the mac > address. My method for extracting this is as follows - > mac = os.popen("ifconfig|grep Ether|awk {print '$5'}").read()[:-1] # > I did not come up with this myself, I cribbed it from somewhere > > As root, this works fine. As non-root, ifconfig is not found. The > reason is that it is in /sbin, and this is not included in the default > path for non-root users. I could either include /sbin in my path, or I > could change the above line to /sbin/ifconfig ... Alternatively, there > may be a better way of getting the mac address or identifying the > workstation. Put "/sbin/ifconfig" in a string variable. Place that somewhere where a person porting the program will find it. Then use the variable name in the os.popen call. Of course, if ifconfig is in /sbin, it's likely that their ifconfig won't work that way anyway. Mine certainly doesn't. BTW, I'd consider doing the grep/awk part of the process via python. Python won't be as fast as the grep/awk, but ifconfig's output is short, so the cost of launching the new processes probably swamps that. Something like: for line in os.popen(IFCONFIG): if line.find('Ether'): mac = line.split()[4] break should do it. On the other hand, if its fast enough and works, don't touch it. > 2. I am using wxPython, which was compiled from source. It so happens > that I did this with a colleague who also has a user account on my > machine, so the compile and install of wxPython was done from his home > directory. Python modules should be installed as root. That should put them in the correct place. > When I start my app as non-root, the import of wx fails, as it cannot > find certain files. They are in the other user's home directory, but as > the top-level directory has permissions of drwx------, my user cannot > read anything in that directory. I can change the directory > permissions, or I can move the files to another area which all users > can read. If the latter, is there a 'correct' place to put them? Yes. In the python libraries site-packages directory. You really want to check out your platforms package management system. It's *much* easier to type "sudo port install wx-python" than it is to download, configure, compile, and install the package. The exact command will depend on your distro. It's probably one of rpm or apt-get, but might be emerge, or maybe even port. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From peter at engcorp.com Mon Jul 4 10:56:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Jul 2005 10:56:24 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: Message-ID: Terry Hancock wrote: > On Sunday 03 July 2005 07:05 pm, Erik Max Francis wrote: >>I personally think that map looks clearer than a list comprehension for >>a simple function call > This on the other hand, >> [str(x) for x in sequence] > is practically plain English: > > "call the function "str" on x, for every x in sequence" > > Other than chopping out a few words, and using the () operator instead > of "call", it's hard to imagine this being any closer to exactly what you > would say to describe the operation. And for most of us, English comes > easier than Computer Science jargon. And with a better choice of names than "x", that line becomes even more self-documenting. [str(parrot) for parrot in sequence], for example, tells you much more about what is going on than str(x) does. Exactly what, I have no idea... but it says _so_ much more. ;-) -Peter From peter at engcorp.com Sun Jul 10 10:16:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Jul 2005 10:16:26 -0400 Subject: Newbie Alert! Upgrading Python? In-Reply-To: <9xmcrg2yrg10$.dojk9yjyhf4i$.dlg@40tude.net> References: <9xmcrg2yrg10$.dojk9yjyhf4i$.dlg@40tude.net> Message-ID: Thorsten Kampe wrote: > * El (2005-07-10 11:56 +0100) >>Python 1.5.1 (final) and Python Win32 Extensions are installed on my 4 year > > If you don't use it: uninstall Python. If something else uses it: keep > it as it is as your app might break with the new Python - even though > 2.4 is backwards compatible. Python 2.4 is most definitely not 100% backwards compatible with Python 1.5.1, so "don't upgrade!" is correct advice if Python is in use by some application that expects it to be 1.5.1... -Peter From bokr at oz.net Wed Jul 27 17:17:46 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 27 Jul 2005 21:17:46 GMT Subject: Wrapping a class set method References: <1122489744.784822.187690@f14g2000cwb.googlegroups.com> Message-ID: <42e7e604.1309443450@news.oz.net> On 27 Jul 2005 11:42:24 -0700, "snoe" wrote: >Hi there, > >I have the following simplified classes: > >class Project: > def __init__(self,pname): > self.devices = {} # Dictionary of Device objects > self.pname = pname > > def setpname(self,pname): > self.pname = pname > > def adddevice(self,dname): > self.devices[dname] = Device(self,dname) > >class Device: > def __init__(self,parent,dname): > self.parent = parent > self.dname = dname > > def setdname(self,dname): > self.dname = dname > >Now, what I would like to do is wrap all of the set/add methods in a >function that pickles the Project object. I would then save the pickled >objects and use them to undo any changes to the above data structures. > >I have a suspicion that there's an easier way to do this than >explicitly adding a Project.pickleme() call to the beginning of all of >my set/add methods. > >So is there a way to wrap methods for this type of functionality or is >there another way of doing this, maybe without using setter methods? > I would look into using properties with the same names as attributes of interest, to store changes for possible undo/redo. For the devices attribute, you are not changing the attribute per se, so you need a dict-like object that will do the state tracking when you add devices. A dict subclass overriding __setitem__ should suffice for the usage you show. Then you can give the classes undo/redo methods, or whatever. You could also use a special object instead of a dict subclass, if you wanted some other interface. Regards, Bengt Richter From gustavo at niemeyer.net Thu Jul 7 02:40:10 2005 From: gustavo at niemeyer.net (Gustavo Niemeyer) Date: Thu, 7 Jul 2005 03:40:10 -0300 Subject: ANN: python-constraint 1.0 Message-ID: -------- Overview -------- **python-constraint** [1]_ is a Python module offering solvers for Constraint Solving Problems (CSPs) over finite domains in simple and pure Python. CSP is class of problems which may be represented in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...), and constraints (`a < b`, ...). . [1] http://codespeak.net/~niemeyer/constraint/ -------- Examples -------- Basic ----- Here is a basic interactive example:: >>> from constraint import * >>> problem = Problem() >>> problem.addVariable("a", [1,2,3]) >>> problem.addVariable("b", [4,5,6]) >>> problem.getSolutions() [{'a': 3, 'b': 6}, {'a': 3, 'b': 5}, {'a': 3, 'b': 4}, {'a': 2, 'b': 6}, {'a': 2, 'b': 5}, {'a': 2, 'b': 4}, {'a': 1, 'b': 6}, {'a': 1, 'b': 5}, {'a': 1, 'b': 4}] >>> problem.addConstraint(lambda a, b: a*2 == b, ("a", "b")) >>> problem.getSolutions() [{'a': 3, 'b': 6}, {'a': 2, 'b': 4}] >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(AllDifferentConstraint()) >>> problem.getSolutions() [{'a': 3, 'b': 2}, {'a': 3, 'b': 1}, {'a': 2, 'b': 3}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a': 1, 'b': 3}] Rooks ----- Here is an example solving the classical rooks problem:: problem = Problem() numpieces = 8 cols = range(numpieces) rows = range(numpieces) problem.addVariables(cols, rows) for col1 in cols: for col2 in cols: if col1 < col2: problem.addConstraint(lambda row1, row2: row1 != row2, (col1, col2)) solutions = problem.getSolutions() Magic squares ------------- And here is an example solving a 4x4 magic square:: problem = Problem() problem.addVariables(range(0, 16), range(1, 16+1)) problem.addConstraint(AllDifferentConstraint(), range(0, 16)) problem.addConstraint(ExactSumConstraint(34), [0,5,10,15]) problem.addConstraint(ExactSumConstraint(34), [3,6,9,12]) for row in range(4): problem.addConstraint(ExactSumConstraint(34), [row*4+i for i in range(4)]) for col in range(4): problem.addConstraint(ExactSumConstraint(34), [col+4*i for i in range(4)]) solutions = problem.getSolutions() -------- Features -------- The following solvers are available: - Backtracking solver - Recursive backtracking solver - Minimum conflicts solver Predefined constraint types currently available: - FunctionConstraint - AllDifferentConstraint - AllEqualConstraint - ExactSumConstraint - MaxSumConstraint - MinSumConstraint - InSetConstraint - NotInSetConstraint - SomeInSetConstraint - SomeNotInSetConstraint ------------- Documentation ------------- There's documentation for the module at: - http://codespeak.net/~niemeyer/constraint/doc/ -------- Download -------- **python-constraint** may be found at the following address: - http://codespeak.net/~niemeyer/constraint/files/ --------------------- Subversion repository --------------------- Available at: - http://codespeak.net/svn/user/niemeyer/constraint/ -- Gustavo Niemeyer http://niemeyer.net From agel_gr at fq.uniovi.es Tue Jul 26 16:02:49 2005 From: agel_gr at fq.uniovi.es (=?ISO-8859-1?Q?=C1ngel_Guti=E9rrez_Rodr=EDguez?=) Date: Tue, 26 Jul 2005 22:02:49 +0200 Subject: GUI - Windows: Where to get started References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: Well, Tkinter module (Tk) would be the simplestway to do it.. and it is included in your Windows Python distribution... From gnb at itga.com.au Fri Jul 8 03:05:18 2005 From: gnb at itga.com.au (Gregory Bond) Date: Fri, 08 Jul 2005 17:05:18 +1000 Subject: (Win32 API) callback to Python, threading hiccups In-Reply-To: References: <42cd46b5$1@nntp0.pdx.net> Message-ID: Tim Roberts wrote: >>> PyGILState_STATE gil = PyGILState_Ensure(); >>> result = PyEval_CallObject(my_callback, arglist); >>> PyGILState_Release(gil); >>> Py_DECREF(arglist); >>> Py_DECREF(result); > If someone else holds a reference to "arglist", then the > DECREF is just a nice, atomic decrement. If no one else holds a reference > to "arglist", then it's quite safe to delete it. What if anothere thread takes the GIL as soon as you release it, and is attempting to allcate a new opbject, and (at the same time - you might be on a multiprocessor!) your PyDECREF removes the last reference and starts freeing objects? From jwaixs at gmail.com Tue Jul 5 11:04:21 2005 From: jwaixs at gmail.com (jwaixs) Date: 5 Jul 2005 08:04:21 -0700 Subject: f*cking re module In-Reply-To: <1120568322.948740.229830@g44g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> Message-ID: <1120575861.296553.303750@z14g2000cwz.googlegroups.com> To reply to the last part of the discussion and esspecially to Gustavo Niemeyer, I really apriciate the way in which I had been answered. And I won't have any questions about the re module that I had before I post this threat. I was frustration and should, probebly, not post this frustration. But it was never my purpous to ask something stupid or asking it arrogant. The python re module is, in my opinion, a non beginner user friendly module. And it's not meant for beginning python programmers. I don't have any experience with perl or related script/programming languages like python. (I prefer to do things in c) So the re module is completely new for me. If I upset someones clean mind posting a "stupid" and "arrogant" question, I'm sorry and won't post my frustrasion on this usenet group anymore. But thank you for all your help about the re module, Noud Aldenhoven From prabapython at yahoo.co.in Sat Jul 30 00:50:40 2005 From: prabapython at yahoo.co.in (praba kar) Date: Sat, 30 Jul 2005 05:50:40 +0100 (BST) Subject: Python-cgi or Perl-cgi script doubt In-Reply-To: <1122640048.898562.3600@g43g2000cwa.googlegroups.com> Message-ID: <20050730045040.33004.qmail@web8404.mail.in.yahoo.com> Dear All, I want to know difference between Python-cgi and Perl-cgi and also I want to which one is efficient from the performance. regards Prabahar _______________________________________________________ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From jdennett at acm.org Sun Jul 31 18:59:04 2005 From: jdennett at acm.org (James Dennett) Date: Sun, 31 Jul 2005 15:59:04 -0700 Subject: how to write a line in a text file In-Reply-To: References: <42E5B0F0.6020206@REMOVEMEcyber.com.au> <42E5ED91.10402@REMOVEMEcyber.com.au> Message-ID: Peter Hansen wrote: > Steven D'Aprano wrote: > >> On Wed, 27 Jul 2005 04:26:31 +0000, Andrew Dalke wrote: >> >>> This isn't 1970. Why does your app code work directly with >>> files? Use a in-process database library (ZODB, SQLLite, >>> BerkeleyDB, etc.) to maintain your system state and let the >>> library handle transactions for you. >> >> >> And when users are happy to install a relational database system in order >> for their editor to save their letter to grandma, I'm sure your scheme >> will work well for them. > > > Given that ZODB and PySQLite are simply Python extension modules, which > get bundled by your builder tool and are therefore installed > transparently along with your app by your installer, this is a total > non-issue at least with those packages. > > After all, it's not 1970 any more. ;-) Indeed; since 1970 we learned to prefer straightforward file formats where possible, reserving use of databases for structured data where the extra costs are justified. Sometime maybe databases will get better to the point that we don't need to distinguish so much between them and filesystems, but we're not there yet. Managing raw files, carefully, still has a place. -- James From walterbrunswick at sympatico.ca Sat Jul 2 13:43:33 2005 From: walterbrunswick at sympatico.ca (Walter Brunswick) Date: Sat, 2 Jul 2005 13:43:33 -0400 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: Why not just update the local dictionary? class Grouping: def __init__(self,x,y,z): self.__dict__.update(locals()) From duvelbier-tsmets at yahoo.com Sun Jul 31 11:06:59 2005 From: duvelbier-tsmets at yahoo.com (Thomas SMETS) Date: Sun, 31 Jul 2005 17:06:59 +0200 Subject: Trimming X/HTML files In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 The regular expression remove script out of an HTML/XHTML file is simple enough but raises a major performance issue.... The following regular expression : r'()' takes ages to complete in python on simple HTML file more than 3 minutes of CPU time on a 150 lines HTML file. In jython it just never completes but returns a painfull RunTimeException : maximum number of ??? reached. Is the only way out dealing with strings and "match" instead of regular expression ? More over Jython is not yet 2.3 compliant, hence advanced features of 2.3 regular expression are not yet available ! \T, Thomas SMETS wrote: | | Dear, | | I need to parse XHTML/HTML files in all ways : | ~ _ Removing comments and javascripts is a first issue | ~ _ Retrieving the list of fields to submit is my following item (todo) | | Any idea where I could find this already made ... ? | | \T, | | - -- Thomas SMETS Bruxelles @ : duvelbier-tsmets at yahoo.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD4DBQFC7OkTqN0SJr+xLBURAuTYAKDLxLv+hpnSrZ6uowOmUczVxgxLqwCYhfJ3 fwjPZzg88gh3lNY8jkG3SA== =urIC -----END PGP SIGNATURE----- From mkb at incubus.de Sun Jul 10 17:54:09 2005 From: mkb at incubus.de (Matthias Buelow) Date: Sun, 10 Jul 2005 23:54:09 +0200 Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <1121005233.992711.141640@z14g2000cwz.googlegroups.com> Message-ID: <86u0j2e39a.fsf@drjekyll.mkbuelow.net> Steven D'Aprano writes: >On Sun, 10 Jul 2005 07:20:34 -0700, raptor wrote: > >> I think u are wrong.. I think perl is much more exrpressive in >> semantics than Python.. > >Well, with such great command of natural language as you are displaying, >how could anyone argue with your conclusion? Folks, Xah Lee is a known troll.. don't get into any arguments among yourselves over anything that person writes. mkb. From s_t_a_n_i at gmx.net Mon Jul 25 21:39:44 2005 From: s_t_a_n_i at gmx.net (Stani) Date: 25 Jul 2005 18:39:44 -0700 Subject: UPDATE: SPE 0.7.4.d Python Editor released In-Reply-To: <1121945693.157781.234540@g43g2000cwa.googlegroups.com> References: <1121942427.892536.12980@o13g2000cwo.googlegroups.com> <1121945693.157781.234540@g43g2000cwa.googlegroups.com> Message-ID: <1122341984.664133.271710@z14g2000cwz.googlegroups.com> Well, now you could go for n. I try to be as quick as my feedback from users. From roy at panix.com Wed Jul 27 12:00:45 2005 From: roy at panix.com (Roy Smith) Date: Wed, 27 Jul 2005 12:00:45 -0400 Subject: Need to understand python license In-Reply-To: <42E7AE8E.2040605@benjiyork.com> References: <42E7AE8E.2040605@benjiyork.com> Message-ID: <42E7AFAD.4060905@panix.com> Benji York wrote: > > See http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq > Thanks, that's exactly what I needed. From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 21 11:56:03 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 21 Jul 2005 16:56:03 +0100 Subject: difficulty connecting to networked oracle database In-Reply-To: References: Message-ID: yahibble wrote: > Now, I am no Python expert but I have dabbled and I have spent a > couple of days with another engineer unsuccessfully installing oracle > drivers for MS ODBC on the win XP machine. > > It looked to me like ODBC was the best way to get a (free) python > module to upload data to an oracle database table. Aside from > installing oracle clients to ODBC being a pain, I would like to > consider other ways to connect. > > Has anyone had experiences with Python connecting to oracle from Win > XP? I have searched the 'net for various modules and discussions but > have no success thus far. > > Thanks, Graeme. > > not used it on Windows XP (just 2000) but cx_Oracle worked for me http://sourceforge.net/projects/cx-oracle/ Martin From tzot at sil-tec.gr Sat Jul 2 06:55:15 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 13:55:15 +0300 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119956464.362328.290370@o13g2000cwo.googlegroups.com> <87ekala2xf.fsf@titan.staselog.com> Message-ID: On Wed, 29 Jun 2005 07:11:43 -0500, rumours say that phil might have written: >I wonder what percentage of the tools you refer to are >Eclipse and not Java per se. ?? I don't know. >The really big bucks of IBM sent Eclipse through the roof. The project name is pretty offensive too, since it's related to the term "Sun" and not the term "Java". If one has heard of the differences between Sun and IBM about Java, and knowing that Eclipse started as an IBM project, then the reasoning for choosing the name "Eclipse" becomes more obvious... -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From cam.ac.uk at mh391.invalid Wed Jul 27 08:49:10 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 27 Jul 2005 13:49:10 +0100 Subject: Extreme n00b question In-Reply-To: <1122358384.455900.91810@g44g2000cwa.googlegroups.com> References: <1122358384.455900.91810@g44g2000cwa.googlegroups.com> Message-ID: Anupam Kapoor wrote: > i generally name python sources as a-simple-python-example.py. when i > try to import a module named as above, i (obviously) get tracebacks > from python interpreter. > > is there a way to continue naming python sources as above, and still > use it as python modules ? i can ofcourse change the name to > 'a_simple_python_example.py', which then works. Your question has already been answered, but I think your life (and that of anyone trying to use your code) would probably be easier if you switched to underscores. -- Michael Hoffman From diesch at spamfence.net Wed Jul 6 21:59:09 2005 From: diesch at spamfence.net (Florian Diesch) Date: Thu, 7 Jul 2005 03:59:09 +0200 Subject: latex/bibtex python paper? References: <1120663725.339927.141870@g47g2000cwa.googlegroups.com> Message-ID: <20050707015909.1F47.3.NOFFLE@dieschf.news.arcor.de> schwehr at gmail.com wrote: > Does anyone have a good template that I might use for writing a python > paper in latex/bibtex? I've got the paper mostly done, but am having > issues with the references. I am definitely not an expert at > latex/bibtex. Right now, I have references defined like this: > > @article{imp, > title = {imp -- Access the import internals}, > journal = "http://www.python.org/doc/current/lib/module-imp.html", > author = {Python Software Foundation}, > year = {2005} > } > > When I cite these, I get something like this (Foundation[2005]). Is > anyone willing to offer up a tarball of a complete paper with sty and > bst that would make for a nice python paper? I would use @Manual{imp, title = {imp -- Access the import internals}, key = {imp}, organization = {Python Software Foundation}, address = {\url{http://www.python.org/doc/current/lib/module-imp.html}}, year = 2005 } You need hyperref for \url. With \bibliographystyle{apalike} I get imp (2005), but that depends on what you want your references look like. I think you better ask in a TeX group about that. Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From godwinburby at rediffmail.com Mon Jul 4 00:31:44 2005 From: godwinburby at rediffmail.com (godwin) Date: 3 Jul 2005 21:31:44 -0700 Subject: What are the other options against Zope? In-Reply-To: <1120342113.997667.41960@g44g2000cwa.googlegroups.com> References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <1120342113.997667.41960@g44g2000cwa.googlegroups.com> Message-ID: <1120451504.946482.190900@g44g2000cwa.googlegroups.com> You understood my request correctly. I thank u for pointing me to cherrypy. From tiissa at nonfree.fr Sun Jul 3 05:19:45 2005 From: tiissa at nonfree.fr (tiissa) Date: Sun, 03 Jul 2005 11:19:45 +0200 Subject: a question In-Reply-To: References: Message-ID: <42c7adb0$0$27606$636a15ce@news.free.fr> Xinyue Ye wrote: > when I type sys.ps2 after import sys, > I got the message like: > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.ps2 > AttributeError: 'module' object has no attribute 'ps2' > why does it happen? sys.ps2 is defined in an interactive session only as precised in the doc [1]: $ python Python 2.3.5 (#2, May 29 2005, 00:34:43) [GCC 3.3.6 (Debian 1:3.3.6-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.ps2 ... >>> compared to: $ cat ps2.py import sys print sys.ps2 $ python ps2.py Traceback (most recent call last): File "ps2.py", line 2, in ? print sys.ps2 AttributeError: 'module' object has no attribute 'ps2' $ [1] http://docs.python.org/lib/module-sys.html From steve at REMOVETHIScyber.com.au Sun Jul 31 12:40:32 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 01 Aug 2005 02:40:32 +1000 Subject: getting an empty tuple References: <1122824426.310199.136660@o13g2000cwo.googlegroups.com> Message-ID: On Sun, 31 Jul 2005 08:40:26 -0700, nephish wrote: > Hey there, > i have a simple database query that returns as a tuple the number of > rows that the query selected. > kinda like this > >>>> cursor.execute('select value from table where autoinc > 234') >>>> x = cursor.fetchall() >>>> print x > >>>> 21L 21L is not a tuple, it is a long integer. > ok, means 21 rows met the criteria of the query. but if there are none > that match, > like i do a > >>>> print x >>>> 0L > > how do i encorporate that into an equation ? > i have tried all kinds of stuff And did they work? If they didn't work, tell us the exact error message you got. > if x == 0L If x is a long integer, then that will work. Of just "if x == 0:" will work too. > if x(0) == None No. That means x is a function, and you are giving it an argument of 0, and it returns None. > if x == None You said that your query returns a tuple, but then gave an example where it returns a long int. None is not a tuple, nor a long int, so testing either of those things against None will never be true. Did you try any of these things in the interactive interpreter? Python is a great language for experimenting, because you can try this yourself: # run your setup code ... # and then do some experimenting cursor.execute('select value from table where autoinc > 99999999') # or some value that will never happen x = cursor.fetchall() print x What do you get? > anyway, what shoud i do to test if the result is empty? Long ints are never empty, but they can be zero: if x == 0: print "no rows were found" elif x == 1: print "1 row was found" else: print "%d rows were found" % x Tuples can be empty: if len(x) == 0: print "no rows were found" or if you prefer: if x == (): print "no rows were found" But the cleanest, most Pythonic way is just to do a truth-test: if x: print "something was found" else: print "x is empty, false, blank, nothing..." -- Steven. From darkcowherd at gmail.com Sun Jul 24 23:46:22 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Mon, 25 Jul 2005 09:16:22 +0530 Subject: Getting a dictionary from an object In-Reply-To: <42e3fd9f$0$18620$626a14ce@news.free.fr> References: <42e3fd9f$0$18620$626a14ce@news.free.fr> Message-ID: <5f4d3cb505072420464156cf0e@mail.gmail.com> > voiceless-ly'rs What does this mean?? Just curious (googled that and ly'rs and didnt find anything relevant) -- Dark Cowherd From bokr at oz.net Sun Jul 10 21:20:06 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 01:20:06 GMT Subject: Read-only class properties References: <1121027902.719545.103860@g14g2000cwa.googlegroups.com> Message-ID: <42d1b2af.331498399@news.oz.net> On 10 Jul 2005 13:38:22 -0700, "George Sakkis" wrote: >I'm trying to write a decorator similar to property, with the >difference that it applies to the defining class (and its subclasses) >instead of its instances. This would provide, among others, a way to >define the equivalent of class-level constants: > >class Foo(object): > @classproperty > def TheAnswer(cls): > return "The Answer according to %s is 42" % cls.__name__ > >>>> Foo.TheAnswer >The Answer according to Foo is 42 >>> Foo.TheAnswer = 0 >exceptions.AttributeError >... >AttributeError: can't set class attribute > >I read the 'How-To Guide for Descriptors' >(http://users.rcn.com/python/download/Descriptor.htm) that describes >the equivalent python implementation of property() and classmethod() >and I came up with this: > >def classproperty(function): > class Descriptor(object): > def __get__(self, obj, objtype): > return function(objtype) > def __set__(self, obj, value): > raise AttributeError, "can't set class attribute" > return Descriptor() > >Accessing Foo.TheAnswer works as expected, however __set__ is >apparently not called because no exception is thrown when setting >Foo.TheAnswer. What am I missing here ? > I suspect type(Foo).TheAnswer is not found and therefore TheAnswer.__set__ is not looked for, and therefore it becomes an ordinary attribute setting. I suspect this is implemented in object.__setattr__ or type.__setattr__ as the case may be, when they are inherited. So I introduced a __setattr__ in type(Foo) by giving Foo a metaclass as its type(Foo). First I checked whether the attribute type name was 'Descriptor' (not very general ;-) and raised an attribute error if so. Then I made a class Bar version of Foo and checked for __set__ and called that as if a property of type(Bar) instances. See below. ----< classprop.py >---------------------------------------------------- def classproperty(function): class Descriptor(object): def __get__(self, obj, objtype): return function(objtype) def __set__(self, obj, value): raise AttributeError, "can't set class attribute" return Descriptor() class Foo(object): class __metaclass__(type): def __setattr__(cls, name, value): if type(cls.__dict__.get(name)).__name__ == 'Descriptor': raise AttributeError, 'setting Foo.%s to %r is not allowed' %(name, value) type.__setattr__(cls, name, value) @classproperty def TheAnswer(cls): return "The Answer according to %s is 42" % cls.__name__ @classproperty def AnotherAnswer(cls): return "Another Answer according to %s is 43" % cls.__name__ class Bar(object): class __metaclass__(type): def __setattr__(cls, name, value): attr = cls.__dict__.get(name) if hasattr(attr, '__set__'): attr.__set__(cls, value) # like an instance attr setting else: type.__setattr__(cls, name, value) @classproperty def TheAnswer(cls): return "The Answer according to %s is 42" % cls.__name__ @classproperty def AnotherAnswer(cls): return "Another Answer according to %s is 43" % cls.__name__ if __name__ == '__main__': print Foo.TheAnswer Foo.notTheAnswer = 'ok' print 'Foo.notTheAnswer is %r' % Foo.notTheAnswer print Foo.AnotherAnswer try: Foo.TheAnswer = 123 except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e) try: Foo.AnotherAnswer = 456 except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e) print Bar.TheAnswer Bar.notTheAnswer = 'ok' print 'Bar.notTheAnswer is %r' % Bar.notTheAnswer print Bar.AnotherAnswer try: Bar.TheAnswer = 123 except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e) try: Bar.AnotherAnswer = 456 except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e) ------------------------------------------------------------------------ Result: [18:17] C:\pywk\clp>py24 classprop.py The Answer according to Foo is 42 Foo.notTheAnswer is 'ok' Another Answer according to Foo is 43 AttributeError: setting Foo.TheAnswer to 123 is not allowed AttributeError: setting Foo.AnotherAnswer to 456 is not allowed The Answer according to Bar is 42 Bar.notTheAnswer is 'ok' Another Answer according to Bar is 43 AttributeError: can't set class attribute AttributeError: can't set class attribute Regards, Bengt Richter From samrobertsmith at gmail.com Sun Jul 3 05:37:46 2005 From: samrobertsmith at gmail.com (shisa) Date: Sun, 3 Jul 2005 05:37:46 -0400 Subject: what is the difference between command prompt and IDLE? Message-ID: <1d987df305070302375f559498@mail.gmail.com> what is the difference between command prompt and IDLE? From cyril.bazin at gmail.com Thu Jul 21 17:24:26 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Thu, 21 Jul 2005 23:24:26 +0200 Subject: Hash functions In-Reply-To: References: Message-ID: Maybe in certain case you could use hash to compare objects (hashable of course) quicker by comparing there hash values, if the hash values are the same you test the equality between the objects. But the sets and dicts cover the greatest part of the use of hash. (Personally, I never used that explicitly in my programs) Cyril On 7/21/05, Michael Hudson wrote: > > Steven D'Aprano writes: > > > Do people often use hash() on built-in types? > > Only implicitly. > > > What do you find it useful for? > > Dictionaries :) > > > How about on custom classes? > > Same here. > > > Can anyone give me some good tips or hints for writing and using > > hash functions in Python? > > Well, the usual tip for writing them is, don't, unless you need to. > > If implement __eq__, then you need to, so it's fairly common to just > hash a tuple containing the things that are considered by the __eq__ > method. Something like: > > class C(object): > def __init__(self, a, b, c): > self.a = a > self.b = b > self.c = c > def __eq__(self, other): > return self.a == other.a and self.b == other.b > def __hash__(self): > return hash((self.a, self.b)) > > Cheers, > mwh > > -- > I'm a keen cyclist and I stop at red lights. Those who don't need > hitting with a great big slapping machine. > -- Colin Davidson, cam.misc > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rphillips at engineer.co.summit.oh.us Mon Jul 18 07:24:12 2005 From: rphillips at engineer.co.summit.oh.us (paron) Date: 18 Jul 2005 04:24:12 -0700 Subject: What is your favorite Python web framework? References: Message-ID: <1121685852.674382.216790@g14g2000cwa.googlegroups.com> Admin: >I have kept the following: > - PyWork - http://pywork.sourceforge.net (Not sure if it's mature) > - Django - http://www.djangoproject.com (Looks interesting) > - CherryPy - http://www.cherrypy.org (Unsure) >I have also found a more comprehensive list here: >http://wiki.python.org/moin/WebProgramming >But I'd like to know your opinion on what you think is best. . . . >I favor speed of development, intensive OO development, performance under >heavy load, short learning curve, good documentation and community. I settled on CherryPy: Performance under load -- can't say one way or the other. I do know it's lightweight -- 40kb download, I recall. Good documentation -- yeah, if you are using the "mainstream" features. It's pretty extensible, too, so there are some "secondary" functions and features that are not as well documented. I know that the documentation is a major concern of the oommunity, and that they are pretty quick to respond when the docs are unclear. I give CherryPy very high marks for: speed of development, intensive OO development, short learning curve (if you already know Python), and community. And, as I said, for extensibility. I found I had working apps running on my machine with CherryPy in less time than I needed to read the installation docs on some other frameworks. It's just like writing Python, but with one extra object (cpg (2.0) or cherrypy (2.1) and one extra setting ("exposed = True"). That's it. I'd say give it a try -- you can have it running apps and go through the tutorials in a morning, so why not get first-hand with it? From qwweeeit at yahoo.it Wed Jul 20 11:42:33 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 20 Jul 2005 08:42:33 -0700 Subject: What does "::" mean? References: <311b5ce1050719175054e268b6@mail.gmail.com> Message-ID: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Hi Robert, I didn't succeed in reversing a string with the "full form" you proposed: live[len(live)-1:-1:-1] # where live="live" The result is an empty string. To reverse "live" (in a "full form"), I have to put a char in front of the string and...: ('x'+live)[len(live)+1:0:-1] # --> "evil" Is it due to the Python's version (I still have 2.3.4)? Bye. From confirm-bounce-a285fefe95ba36aded1612a93a5711cc-python-list=python.org at lists.mysql.com Mon Jul 4 05:50:36 2005 From: confirm-bounce-a285fefe95ba36aded1612a93a5711cc-python-list=python.org at lists.mysql.com (MySQL Lists Automoderator) Date: 4 Jul 2005 09:50:36 -0000 Subject: MySQL posting confirmation for python-list@python.org Message-ID: <20050704095036.14260.qmail@lists.mysql.com> This is an automatic reply to an email you sent to a MySQL mailing address protected by our 'self-moderation' system. To reduce the amount of spam received at these addresses, we require you to confirm that you're a real person before your email will be allowed through. Unfortunately, we got a bounce for one of the confirmation emails we already sent, so you've been added to the list of addresses which will get bounced immediately. In order to have yourself added to the list of real email addresses, and removed from the list of those who have bounced, you need to click on the following link (or cut-and-paste it to a browser): http://lists.mysql.com/c/a285fefe95ba36aded1612a93a5711cc/python-list at python.org After we have received your confirmation, "python-list at python.org" will be added to the list of pre-approved mail addresses for all of the MySQL mail addresses and future emails from that address will be delivered without delay automatically. You will not receive an email confirmation of your confirmation -- future messages will simply be sent along without delay. Sorry for the hassle, but the volume of unsolicited commercial email sent to these addresses has made this step necessary. --- Your original email is below. From corey.coughlin at comcast.net Thu Jul 28 20:33:37 2005 From: corey.coughlin at comcast.net (corey.coughlin at comcast.net) Date: 28 Jul 2005 17:33:37 -0700 Subject: pyUI? Message-ID: <1122597217.928624.67290@f14g2000cwb.googlegroups.com> I think someone built a gui on top of pygame a while back, I think it was called pyUI or something, let's see what google gives me here, ah, here we go http://pyui.sourceforge.net/ Hope that helps. Looks like neat stuff anyway... From steve at REMOVETHIScyber.com.au Sun Jul 10 08:10:50 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 10 Jul 2005 22:10:50 +1000 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: On Sun, 10 Jul 2005 12:15:25 +0530, Dark Cowherd wrote: > http://www.joelonsoftware.com/items/2003/10/13.html Joel Spolsky might be a great C++ programmer, and his advice on user interface design is invaluable, but Python is not C++ or Java, and his arguments about exceptions do not hold in Python. Joel argues: "They are invisible in the source code. Looking at a block of code, including functions which may or may not throw exceptions, there is no way to see which exceptions might be thrown and from where. This means that even careful code inspection doesn't reveal potential bugs." I don't quiet get this argument. In a random piece of source code, there is no way to tell whether or not it will fail just by inspection. If you look at: x = 1 result = myfunction(x) you can't tell whether or not myfunction will fail at runtime just by inspection, so why should it matter whether it fails by crashing at runtime or fails by raising an exception? Joel's argument that raising exceptions is just a goto in disguise is partly correct. But so are for loops, while loops, functions and methods! Like those other constructs, exceptions are gotos tamed and put to work for you, instead of wild and dangerous. You can't jump *anywhere*, only highly constrained places. Joel also writes: "They create too many possible exit points for a function. To write correct code, you really have to think about every possible code path through your function. Every time you call a function that can raise an exception and don't catch it on the spot, you create opportunities for surprise bugs caused by functions that terminated abruptly, leaving data in an inconsistent state, or other code paths that you didn't think about." This is a better argument for *careful* use of exceptions, not an argument to avoid them. Or better still, it is an argument for writing code which doesn't has side-effects and implements data transactions. That's a good idea regardless of whether you use exceptions or not. Joel's concern about multiple exit points is good advice, but it can be taken too far. Consider the following code snippet: def myfunc(x=None): result = "" if x is None: result = "No argument given" elif x = 0: result = "Zero" elif 0 < x <= 3: resutl = "x is between 0 and 3" else: result = "x is more than 3" return result There is no benefit in deferring returning value as myfunc does, just for the sake of having a single exit point. "Have a single exit point" is a good heuristic for many functions, but it is pointless make-work for this one. (In fact, it increases, not decreases, the chances of a bug. If you look carefully, myfunc above has such a bug. Used correctly, exceptions in Python have more advantages than disadvantages. They aren't just for errors either: exceptions can be triggered for exceptional cases (hence the name) without needing to track (and debug) multiple special cases. Lastly, let me argue against one of Joel's comments: "A better alternative is to have your functions return error values when things go wrong, and to deal with these explicitly, no matter how verbose it might be. It is true that what should be a simple 3 line program often blossoms to 48 lines when you put in good error checking, but that's life, and papering it over with exceptions does not make your program more robust." Maybe that holds true for C++. I don't know the language, and wouldn't like to guess. But it doesn't hold true for Python. This is how Joel might write a function as a C programmer: def joels_function(args): error_result = 0 good_result = None process(args) if error_condition(): error_result = -1 # flag for an error elif different_error_conditon(): error_result = -2 else: more_processing() if another_error_conditon(): error_result = -3 do_more_work() good_result = "Success!" if error_result != 0: return (False, error_result) else: return (True, good_result) and then call it with: status, msg = joels_function(args) if status == False: print msg # and fail... else: print msg # and now continue... This is how I would write it in Python: def my_function(args): process(args) if error_condition(): raise SomeError("An error occurred") elif different_error_conditon(): raise SomeError("A different error occurred") more_processing() if another_error_conditon(): raise SomeError("Another error occurred") do_more_work() return "Success!" and call it with: try: result = my_function(args) print "Success!!!" except SomeError, msg: print msg # and fail... # and now continue safely here... In the case of Python, calling a function that may raise an exception is no more difficult or unsafe than calling a function that returns a status flag and a result, but writing the function itself is much easier, with fewer places for the programmer to make a mistake. In effect, exceptions allow the Python programmer to concentrate on his actual program, rather than be responsible for building error-handling infrastructure into every function. Python supplies that infrastructure for you, in the form of exceptions. -- Steven. From rorley at gmail.com Tue Jul 12 10:46:30 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 07:46:30 -0700 Subject: Help with inverted dictionary Message-ID: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> I'm new to Python and I'm struggling. I have a text file (*.txt) with a couple thousand entries, each on their own line (similar to a phone book). How do I make a script to create something like an inverted dictionary that will allow me to call "robert" and create a new text file of all of the lines that contain "robert"? Thanks so much. From sjmachin at lexicon.net Sun Jul 24 07:18:28 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 24 Jul 2005 21:18:28 +1000 Subject: tuple to string? In-Reply-To: References: <42E0EED4.4020001@gmx.net> <42e2457a@news.eftel.com> Message-ID: <42e37903@news.eftel.com> Steven D'Aprano wrote: > On Sat, 23 Jul 2005 23:26:19 +1000, John Machin wrote: > > >>Steven D'Aprano wrote: >> >> >>> >>>>>>''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D))) >>> >>>'spam' >> >>Why the verbal diarrhoea? > > > One line is hardly verbal diarrhoea. > > >>What's wrong with the (already posted) >> >>''.join(map(chr, (0x73, 0x70, 0x61, 0x6D))) >> >>??? > > > Nothing. > > If I had seen the already posted solution using chr on its own without > lambda, I wouldn't have bothered posting the lambda solution. But I > didn't, so I did. > > As another poster has already pointed out, lambda cries out for over-use, > and this was a perfect example of it. Here are a couple of reductions you can use in future, in the order given: (1) lambda : foo() -> foo # for *any* function foo, not just chr (2) lambda : -> def meaningful_func_name(): From roy at panix.com Sat Jul 2 14:48:21 2005 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jul 2005 14:48:21 -0400 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: In article , "Walter Brunswick" wrote: > Why not just update the local dictionary? > > class Grouping: > def __init__(self,x,y,z): > self.__dict__.update(locals()) That's pretty clever. The only minor annoyance is that it creates a self.self. If that bothers you, you can fix it with: def __init__ (self, x, y, z): vars = locals() del vars["self"] self.__dict__.update(vars) or, perhaps: def __init__ (self, x, y, z): self.__dict__.update(locals()) del self.self It doesn't give you all the flexibility of the original proposal (i.e. name-by-name selectivity of what gets imported into self), but it does solve the OP's OP (Original Poster's Original Problem). From rkern at ucsd.edu Sun Jul 31 21:27:37 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 18:27:37 -0700 Subject: Escaping certain characters In-Reply-To: <42ed7567$1@griseus.its.uu.se> References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> <42eca481$1@griseus.its.uu.se> <42ed452f$1@griseus.its.uu.se> <42ed7567$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Robert Kern wrote: > [---] > >>> I need to escape '\n', '"', '[' and ']'. I finally went with a few of >>>these: >>>string.replace('\n', '\\n') >>>string.replace('"', '\\"') >>>... >>> >>> I assume that's good enough, but I somehow expected there to exist >>>some form of "insert your conversion table here" built-in string escaper. >> >>Write a codec. > > Is that what string.encode() uses? Some behind-the-scenes "codec"? I > tried searching for it, but could only find UTF/Unicode-related > information. Is it in the normal python documentation? > > Semi-Offtopic: The "search" facility in the Python help has stopped > functioning for me (I'm using XP on this system). No matter what I > search for, I get no results. A week ago, I got a lot of hits for almost > anything I searched for. Anyone seen this behavior, and knows what to do > about it? Use Google: site:docs.python.org codecs -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From future_retro at yahoo.co.uk Fri Jul 1 08:01:42 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 1 Jul 2005 05:01:42 -0700 Subject: accessing individual element in a list. In-Reply-To: <1120217983.347814.172900@f14g2000cwb.googlegroups.com> References: <1120217689.339747.91140@g44g2000cwa.googlegroups.com> <1120217983.347814.172900@f14g2000cwb.googlegroups.com> Message-ID: <1120218299.042876.99100@g44g2000cwa.googlegroups.com> the square brackets round the output of split got me. Have plit into a new list and all works as expeted. Cheers, MW. From rkern at ucsd.edu Sun Jul 31 06:30:56 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 03:30:56 -0700 Subject: Escaping certain characters In-Reply-To: <42eca481$1@griseus.its.uu.se> References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> <42eca481$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Jan Danielsson wrote: > >>>In [3]: s.encode('string_escape') >>>Out[3]: 'Hello\\nWorld!' >>> >>>In [4]: Out[3].decode('string_escape') >>>Out[4]: 'Hello\nWorld!' >>> >>>Not *quite* what you asked for, but it ought to be close enough. >> >>That'll do just fine. Many thanks! > > Hmm... On second thought, I need to escape more characters. > > Is there no other way to escape characters in strings? Which characters? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sean_mcilroy at yahoo.com Fri Jul 1 22:11:49 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 1 Jul 2005 19:11:49 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> Message-ID: <1120270309.103244.53600@g49g2000cwa.googlegroups.com> Peter Hansen wrote: > Sean, what gave you the impression this would change? just inductive reasoning. i've been wrong before (like anyone who makes that claim), and i'm a former python enthusiast, so my judgement must be colored to some extent by bitterness. maybe they have solid reasons for scrapping the functional constructs. but to me it seems like they're eliminating them just because they offend the sensibilities of C-programmers. (i mean those stereotypical C-programmers, baffled by recursion and the like, who don't want to be reproached with the fact of their mathematical illiteracy.) if that's the case then list comprehensions and/or "first class functions" are likely to be the next target. even if they're not, it's pretty clear that python is leaving its multiparadigmatic origins behind. "do it our way," the pundits are effectively saying, "or get out". for my part, i'm getting out. From bokr at oz.net Wed Jul 6 13:03:04 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 06 Jul 2005 17:03:04 GMT Subject: Conditionally implementing __iter__ in new style classes References: Message-ID: <42cc0e23.693458660@news.oz.net> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller wrote: >I'm trying to implement __iter__ on an abstract base class while I don't >know whether subclasses support that or not. >Hope that makes sense, if not, this code should be clearer: > >class Base: > def __getattr__(self, name): > if name == "__iter__" and hasattr(self, "Iterator"): > return self.Iterator > raise AttributeError, name > >class Concrete(Base): > def Iterator(self): > yield 1 > yield 2 > yield 3 > >The idea is that if a subclass of Base defines an 'Iterator' method, >instances are iterable. They are not iterable otherwise. > >The above gives the expected behaviour: iter(Base()) raises a >"TypeError: iteration over non-sequence", and iter(Concrete()) returns a >generator. > >If, however, I make Base a newstyle class, this will not work any >longer. __getattr__ is never called for "__iter__" (neither is >__getattribute__, btw). Probably this has to do with data descriptors >and non-data descriptors, but I'm too tired at the moment to think >further about this. > >Is there any way I could make the above code work with new style >classes? Will a property or custom descriptor do what you want? E.g. >>> class Base(object): ... def __getIter(self): ... if hasattr(self, "Iterator"): ... return self.Iterator ... raise AttributeError, name ... __iter__ = property(__getIter) ... >>> class Concrete(Base): ... def Iterator(self): ... yield 1 ... yield 2 ... yield 3 ... >>> iter(Base()) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence >>> iter(Concrete()) >>> list(iter(Concrete())) [1, 2, 3] Regards, Bengt Richter From richie at entrian.com Wed Jul 13 07:24:50 2005 From: richie at entrian.com (Richie Hindle) Date: Wed, 13 Jul 2005 12:24:50 +0100 Subject: Software needed In-Reply-To: <27ffa6590507130413750d99cf@mail.gmail.com> References: <1121183089.760096.300450@z14g2000cwz.googlegroups.com> <27ffa6590507130413750d99cf@mail.gmail.com> Message-ID: [Fuzzy] > There's a Python interface to TWAIN (the scanner protocol) [Alexis] > Where I could find the TWAIN python interface ? Try typing "python twain" into Google. The first hit is: http://twainmodule.sourceforge.net/ "The Python TWAIN module provides an interface to scanners, digital cameras and other devices which implement TWAIN, for the Windows platform. It provides the functionality to allow a Python application to connect to the scanner/camera and to retrieve images from that device." -- Richie Hindle richie at entrian.com From roy at panix.com Tue Jul 12 16:53:49 2005 From: roy at panix.com (Roy Smith) Date: 12 Jul 2005 16:53:49 -0400 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: Christopher Subich wrote: >try: > f = file('file_here') > do_setup_code > do_stuff_with(f) >except IOError: # File doesn't exist > error_handle It's also a good idea to keep try blocks as small as possible, so you know exactly where the error happened. Imagine if do_setup_code or do_stuff_with(f) unexpectedly threw an IOError for some reason totally unrelated to the file not existing. From lbates at syscononline.com Wed Jul 27 14:29:50 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 27 Jul 2005 13:29:50 -0500 Subject: GUI - Windows: Where to get started In-Reply-To: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: <42E7D29E.7000406@syscononline.com> First you need to pick up a copy of Python Programming for Win32 book. It is a good starting place for GUI as well as COM and writing services. It was well worth the price to me. -Larry Ernesto wrote: > Hi all, > > Would anyone know a good place to start for learning how to build > simple GUI's in Windows XP? I just want users to be able to select a > few parameters from a pull-down menu, then be able to run some batch > files using the parameters from the pull down menus. I would also need > a "Browse" menu, so users could point to a place on the local disc (ie > C:\PointSystemHere). Can anyone give a noob some tips? THANKS!!! > From benji at benjiyork.com Fri Jul 29 16:43:42 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 29 Jul 2005 16:43:42 -0400 Subject: Hiding In-Reply-To: References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> <1122662993.207041.89630@f14g2000cwb.googlegroups.com> Message-ID: <42EA94FE.6040805@benjiyork.com> Steven Bethard wrote: > So open("C:\file.txt") is still fine I think it is more like it is recommended, not just OK. -- Benji York From saint.infidel at gmail.com Wed Jul 6 12:24:47 2005 From: saint.infidel at gmail.com (infidel) Date: 6 Jul 2005 09:24:47 -0700 Subject: Conditionally implementing __iter__ in new style classes References: <1120666643.702285.206670@f14g2000cwb.googlegroups.com> Message-ID: <1120667087.066460.207190@g49g2000cwa.googlegroups.com> Something like this: >>> class Base(object): ... def __getitem__(self, key): ... return key ... def __iter__(self): ... yield self[1] ... yield self['foo'] ... yield self[3.0] ... >>> class ConcreteIterable(Base): ... def __iter__(self): ... yield True ... yield 'Blue' ... yield 'Foo' ... >>> class ConcreteNotIterable(Base): ... pass ... >>> [x for x in Base()] [1, 'foo', 3.0] >>> [x for x in ConcreteIterable()] [True, 'Blue', 'Foo'] >>> [x for x in ConcreteNotIterable()] [1, 'foo', 3.0] >>> From claird at lairds.us Fri Jul 22 19:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 22 Jul 2005 23:08:03 GMT Subject: query regarding expect References: <1122041629.338563.26610@g47g2000cwa.googlegroups.com> Message-ID: In article <1122041629.338563.26610 at g47g2000cwa.googlegroups.com>, Girish wrote: >Hi, > >I wanna do some automation using "pexpect". >I have an application which must be invoked from the command line in >linux environment,it consists of buttons,textboxes etc can i access >those widgets using "pexpect",say i wanna enter a value 3.3 in the >textbox and then click on the ok button,to run the apllication.The >application is developed using wxpython.ur suggestions will be of gr8 >help.plz do reply. . . . You can't. That's not what pexpect does. There are alternatives. Android might interest you. From t-meyer at ihug.co.nz Thu Jul 28 22:48:55 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 29 Jul 2005 14:48:55 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > I, herewith, claim to have used it in the past. > > But I am indifferent as to if its needed, it just looks natural to me. So far there seem to have been a few +0s, but no +1s... > What I use quite often is:: > > path(__file__).dirname() / "somesiblingfileiknowisthere" > > you do not have to think about trailing slashes or absolute vs. > relative. and its much better than:: > > from os.path import * > join(dirname(__file__), "somesiblingfileiknowisthere") In what way is this "much better"? To me, this is much worse, because it is not at all clear what it means (a *huge* benefit of using Python is that you can read the code just like pseudocode). It is immediately clear from the second example that you are joining two things together. The first one, you could be joining, or you could be dividing. Compare: my_directory_string_object / "somesiblingfileiknowisthere" and my_directory_path_object / "somesiblingfileiknowisthere" These look the same, but one will raise a TypeError, and the other will result in a joined Path. How do I tell which is which when reading source, without explicitly saying that I'm using a Path object? > __div__ is actually very convenient to "build" / "a" / "very" > / "very" / "long" / "path" Would you really choose this: p = Path() / "build" / "a" / "very" / "very" / "long" / "path" Over this: p = Path(os.path.join("build", "a", "very", "very", "long", "path")) ? A saving of six characters, and the second one is a lot clearer. If there was a os.path.joinPath (or whatever name) function that returned a Path object rather than a string, then you'd get: p = joinPath("build", "a", "very", "very", "long", "path") Which is better (clearer, more concise) than either of the others, IMO. =Tony.Meyer From spam.csubich+block at block.subich.spam.com Sun Jul 3 00:39:19 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 00:39:19 -0400 Subject: Favorite non-python language trick? In-Reply-To: <1120362708.992006.49040@g14g2000cwa.googlegroups.com> References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> <1120362708.992006.49040@g14g2000cwa.googlegroups.com> Message-ID: Devan L wrote: > sum(sequence[0] + [1/element for element in sequence[1:]]) > > I think that should work. That won't work, because it misses the x*y part of the expression (x[n]*x[n+1] + 1/x[n+1], for people who haven't immediately read the grandparent). Personally, I think demanding that it be writable as a sum (or product, or any, or all) is a false standard -- nobody's claimed that these would replace all cases of reduce, just the most common ones. From t-meyer at ihug.co.nz Thu Jul 7 03:39:53 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 7 Jul 2005 19:39:53 +1200 Subject: Do a "Python beginners e-mail list" exist? In-Reply-To: Message-ID: > 1. I don't want to post banal questions about Python > to main Python list. Does a "banal Python questions > list" or a "Python beginners list" exist? Yes: There are plenty of people there that will be glad to help! =Tony.Meyer From mwm at mired.org Sat Jul 2 22:12:04 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 02 Jul 2005 22:12:04 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> <864qbf8hvr.fsf@bhuda.mired.org> Message-ID: <86oe9k3aff.fsf@bhuda.mired.org> Christos "TZOTZIOY" Georgiou writes: > On Thu, 30 Jun 2005 20:55:20 -0400, rumours say that Mike Meyer > might have written: > >>Actually, I was thinking of pre-K&R Unix compilers. > > There must be something I am missing here, cause I don't understand what > you mean; what is the earliest K&R C compiler ("Unix" compiler) you > consider as such? Were there other Unix C compilers before K&R wrote > one? Or are you considering as "K&R Unix compilers" those after the > publication of the white book and before C89? The latter. I was considering "K&R Unix compilers" to be the compiler described by the white K&R book - what is basically the v7 Unix C compiler. Thwe v6 compiler didn't do op=, it still did =op. We used the photo7 C compiler on our v6 system. I don't believe that was written by K&R. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jfouhy at paradise.net.nz Tue Jul 12 00:21:00 2005 From: jfouhy at paradise.net.nz (Repton) Date: 11 Jul 2005 21:21:00 -0700 Subject: Searching through a list of tuples Message-ID: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> I often find myself storing data in a list of tuples, and I want to ask questions like "what is the index of the first tuple whose 3rd element is x", or "give me the first tuple whose 2nd element is y". I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a better way? (something like lst.index(x, key=..) or lst.find(y, key=..) would be nice) -- John. From fuzzyman at gmail.com Sat Jul 23 03:23:43 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Jul 2005 00:23:43 -0700 Subject: return None In-Reply-To: <11e2dru68unf2e8@corp.supernews.com> References: <3kcpbbFtjttlU1@individual.net> <11e2dru68unf2e8@corp.supernews.com> Message-ID: <1122103423.636368.12170@o13g2000cwo.googlegroups.com> Grant Edwards wrote: [snip..] > Personally, I don't really like the idea that falling off the > botton of a function implicitly returns None. It's just not > explicit enough for me. My preference would be that if the > function didn't execute a "return" statement, then it didn't > return anyting and attempting to use a return value would be an > error. > > I suppose there probably is code out there that depends on the > implicit "return None" at the end of every function, so it's > too late to change things now. > Yeah - I frequently rely on that behaviour, but purely our of laziness. Best Regards, Fuzzy http://www.voidspace.org.uk/python > -- > Grant Edwards grante Yow! Is it FUN to be > at a MIDGET? > visi.com From donald.welch at NOSPAM.hp.com Tue Jul 5 12:32:32 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Tue, 05 Jul 2005 09:32:32 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <1120575861.296553.303750@z14g2000cwz.googlegroups.com> Message-ID: <42cab76f@usenet01.boi.hp.com> jwaixs wrote: > To reply to the last part of the discussion and esspecially to Gustavo > Niemeyer, I really apriciate the way in which I had been answered. And > I won't have any questions about the re module that I had before I post > this threat. > > I was frustration and should, probebly, not post this frustration. But > it was never my purpous to ask something stupid or asking it arrogant. > > The python re module is, in my opinion, a non beginner user friendly > module. And it's not meant for beginning python programmers. I don't > have any experience with perl or related script/programming languages > like python. (I prefer to do things in c) So the re module is > completely new for me. > > If I upset someones clean mind posting a "stupid" and "arrogant" > question, I'm sorry and won't post my frustrasion on this usenet group > anymore. > > But thank you for all your help about the re module, > > Noud Aldenhoven I would recommend that you give Kodos a try: http://kodos.sourceforge.net/ Doesn't make the re syntax any easier, but I find that it allows you to more quickly develop workable code. -Don From pyweek1 at mechanicalcat.net Thu Jul 7 22:22:53 2005 From: pyweek1 at mechanicalcat.net (pyweek1 at mechanicalcat.net) Date: Fri, 08 Jul 2005 12:22:53 +1000 Subject: Ann: The first PyWeek Python Game Programming Competition Message-ID: <1120789373.42cde37dba5af@webmail.obsidian.com.au> The date for the first PyWeek challenge has been set: Sunday 28th August to Sunday 4th September (00:00UTC to 00:00UTC). The PyWeek competition: - Invites all Python programmers to write a game in one week from scratch either as an individual or in a team, - Is intended to be challenging and fun, - Will hopefully increase the public body of python game tools, code and expertise, - Will let a lot of people actually finish a game, and - May inspire new projects (with ready made teams!) Entries must be developed during the competition, and must incorporate some theme decided at the start of the competition. See the competition timetable (including competition dates in various timezones), rules, sign-up (commencing 6th August) at: http://www.mechanicalcat.net/tech/PyWeek Richard, the PyWeek coordinator ------------------------------------------------- This mail was sent through http://webmail.obsidian.com.au Brought to you by Obsidian Consulting Group. From python at rcn.com Sun Jul 10 13:43:31 2005 From: python at rcn.com (Raymond Hettinger) Date: 10 Jul 2005 10:43:31 -0700 Subject: Efficiency of using long integers to hold bitmaps In-Reply-To: <42d14ec3@news.rivernet.com.au> References: <42d14ec3@news.rivernet.com.au> Message-ID: <1121017410.949244.288220@g44g2000cwa.googlegroups.com> [Jeff Melvaine] > I note that I can write expressions like "1 << 100" and the result is stored > as a long integer, which means it is stored as an integer of arbitrary > length. I may need to use a large number of these, and am interested to > know whether the storage efficiency of long integers is in danger of > breaking my code if I use too many. Would I do better to write a class that > defines bitwise operations on arrays of integers, each integer being assumed > to contain at most 32 bits? Both array() objects and long integers are equally space efficient. In contrast, a list of integers takes up a lot of space (the list is stored as an array of pointers to individual integer objects). Raymond From steve at REMOVETHIScyber.com.au Wed Jul 27 19:55:33 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 28 Jul 2005 09:55:33 +1000 Subject: [Beginner] Calling a function by its name in a string References: Message-ID: On Wed, 27 Jul 2005 14:18:25 -0400, Bill Mill wrote: > On 7/27/05, Tito wrote: >> Hi all: >> >> Is there a metalanguage capability in Python (I know there are many) to >> call a function having its name in a string? >> >> Something like: >> __call__("foo") >> >> instead of: >> foo() >> > >>>> def foo(): print "foobarred" > ... >>>> foo() > foobarred >>>> eval("foo()") > foobarred Which is dangerous beyond belief if you are getting your string "foo()" from a user, and if you aren't, you almost certainly can refactor your code so you don't need eval. You know, I really am getting sick of (1) people who ask how to shoot themselves in the foot and (2) people who cheerfully load the gun and hand it to them without a word of warning about the consequences. And then we all act surprised when we learn about the latest virus or security hole that allows a hostile user to use a music player or paint program to take over the entire operating system. Or whatever. "We're all adults here" only works for people who ARE adults. If you have to ask about eval, you can't be trusted with it without at least a warning. -- Steven. From simon.dahlbacka at gmail.com Wed Jul 20 16:22:31 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 20 Jul 2005 13:22:31 -0700 Subject: wxPython && wxGlade In-Reply-To: References: Message-ID: <1121890950.986577.101010@o13g2000cwo.googlegroups.com> basically, you can just stack an outer vertical box sizer with two items and in the upper "slot" you put a horizontal box sizer with your two buttons and in the bottom slot you put the big button hope this helps /Simon ps. as this is a wxpython related question, you might get better answers on the wxpython mailinglist (but afaik, this is the way this particular thing is done). From maxm at mxm.dk Fri Jul 1 06:47:05 2005 From: maxm at mxm.dk (Max M) Date: Fri, 01 Jul 2005 12:47:05 +0200 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: <42c51eeb$0$255$edfadb0f@dread12.news.tele.dk> Reinhold Birkenfeld wrote: > Hello, > > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? > > For my part, ctypes seems like a suggestion to start with. ctypes certainly. Even though it can crash Python. People using ctypes would be aware of this. Another good bet is BeautifulSoup, which is absolutely great for scraping content from webpages. http://crummy.com/software/BeautifulSoup/index.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From hpj at urpla.net Wed Jul 20 16:24:40 2005 From: hpj at urpla.net (Hans-Peter Jansen) Date: Wed, 20 Jul 2005 22:24:40 +0200 Subject: convert ascii escapes into binary form References: Message-ID: Hi Robert, Hans-Peter Jansen wrote: > Robert Kern wrote: > > That did the trick, thanks a lot, Peter. Unfortunately, on the s/Peter/Robert/g Sorry, Robert. That's the price to pay for doing multiple replies at the same time. Mea culpa.. > target system, there's still python 2.0 running :-( Looks like > I've to bite the apple.. > > Pete From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 17:13:54 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 23:13:54 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e3fd9f$0$18620$626a14ce@news.free.fr> *Grandmaster* Steven Bethard a ?crit : > > How about something like: > dict((name, getattr(obj, name)) for name in dir(obj)) > ... voiceless-ly'rs From steve at REMOVETHIScyber.com.au Mon Jul 11 07:20:39 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 11 Jul 2005 21:20:39 +1000 Subject: Cat and Mouse (wes Re: Efficiency of using long integers to hold bitmaps) References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> <42D1A678.1040705@v.loewis.de> <42d1dc75.342192997@news.oz.net> Message-ID: On Mon, 11 Jul 2005 02:58:29 +0000, Bengt Richter wrote: > I think you are right about some game happening, but I'm not sure it's cat and mouse. > To me, an incomplete question feels like an invitation to play "20 questions" regarding > what the real problem is. So I get a little annoyed, and often just bypass the post. > If I answer, the residual annoyance sometimes leads me to withhold my best guess, and > complain instead. Hence probably the cat and mouse impression. Not very big of me, but > OTOH a think a bit of a nudge towards better questions is not a bad thing. OTO3H, maybe > I should just silently pass up 20-questions invitations and not pollute this pleasant space > with perfumes of annoyance (since however diffuse, they are apparently pungent enough > for some to notice ;-) If it helps, I find the entertainment value of the gentle nudging is the only thing that makes the smell of stupid questions bearable. It isn't true that there is no such thing as a stupid question. There are intelligent questions that are asked in a rude and stupid way. Expecting people to read your mind and understand what your question is about is rude. Expecting people to decipher poorly written, badly spelt, incomprehensible ramblings is rude. (Allowance should be made for those whose native language is not English, and those with good excuses for bad spelling, eg broken keyboard, actual dyslexia.) Some allowance for the occasional brain-fart or typo should be made, but communication requires two parties. You wouldn't expect a mail server to accept any random malformed packets and try to make sense of it, and you shouldn't expect others to put in more work understanding your post than you put in writing it. As they say, be strict when sending and tolerant when receiving. I'm all for that. But when people insist on sending broken packets, I see nothing rude about bouncing those packets back with a error message or a creative misunderstanding. -- Steven From rorley at gmail.com Tue Jul 12 11:38:32 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 08:38:32 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121182343.731328.38020@g47g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> <1121182343.731328.38020@g47g2000cwa.googlegroups.com> Message-ID: <1121182712.452410.64240@g49g2000cwa.googlegroups.com> I will transfer eventually use a database but is there any way for now you could help me make the text files? Thank you so much. Reece From fowlertrainer at anonym.hu Mon Jul 4 10:49:22 2005 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 04 Jul 2005 16:49:22 +0200 Subject: wxPy + Py2Exe + sys.argv[0] Message-ID: <42C94C72.6090900@anonym.hu> Hi ! I have been finished my WMI information getter simple application, but the exe is not working as like the py modules before compilation. The problem that when I started the program from CMD, the sys.argv is show the good path (in my machine the c:\dev\xxxx...) from Dialog1.py. But when I compile it with Py2Exe, and try to start the exe, it has been not found the hwinfo.ini file what store the setup informations of the program. This file is write by my hand, and I place it with Dialog1.exe (in same directory). But the compiled exe is not use the good path... It use "/" only. When I started it from CMD with Dialog1.exe, it hasn't been found the ini file: Traceback (most recent call last): File "Dialog1.py", line 269, in ? File "Dialog1.py", line 201, in LoadIniFile IOError: [Errno 2] No such file or directory: '/hwinfo.ini' When I use full path: c:\dev\xxxx\Dialog1.exe, it have been found everything, and working good. I don't understand it, because I working with sys.argv[0], with this method: def LoadIniFile(): s=os.path.dirname(sys.argv[0])+'/hwinfo.ini' f=open(s,'r') l=(f.read()).split('\n') d={} for s in l: if s.find('=')<>-1: sl=s.split('=') sl[0]=sl[0].strip().lower() sl[1]=sl[1].strip() d[sl[0]]=sl[1] return d So that folder is must be correct ! Why I get error ? What I can do if I want to use it as normal py ? Thanx for help: ft From grig.gheorghiu at gmail.com Thu Jul 21 13:09:11 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 21 Jul 2005 10:09:11 -0700 Subject: difficulty connecting to networked oracle database In-Reply-To: References: Message-ID: <1121965751.373621.193380@o13g2000cwo.googlegroups.com> As the other posters already mentioned, cx_Oracle is the way to go. I'm using it to connect to Oracle not only on Windows, but also on Solaris, Linux and AIX. Grig From sjmachin at lexicon.net Tue Jul 12 19:57:28 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 13 Jul 2005 09:57:28 +1000 Subject: append one file to another In-Reply-To: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Message-ID: <42d458e8$1@news.eftel.com> b83503104 at yahoo.com wrote: > Hi, > > I want to append one (huge) file to another (huge) file. The current > way I'm doing it is to do something like: > > infile = open (infilename, 'r') > filestr = infile.read() > outfile = open(outfilename, 'a') > outfile.write(filestr) > > I wonder if there is a more efficient way doing this? Don't wonder, like the ancient philosophers; be an empiricist :-) > Thanks. > If the files are truly huge, you run the risk of exhausting real memory and having to swap. Try this: Having opened the files, for line in infile: outfile.write(line) Otherwise look at the docs for read the method and check out the "size" argument. General warnings: (1) If you want to be portable, consider text/binary differences. (2) Consider what to do if the last line in is not terminated. From rkern at ucsd.edu Sat Jul 2 13:49:34 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 02 Jul 2005 10:49:34 -0700 Subject: What's wrong with this code? In-Reply-To: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> References: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> Message-ID: Nathan Pinno wrote: > Hi all, > > What's wrong with the following code? It says there is name error, that > random is not defined. How do I fix it? You need to import random. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ivanlan at pauahtun.org Tue Jul 5 17:25:02 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Tue, 05 Jul 2005 15:25:02 -0600 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: <42CAFAAE.142C93B2@pauahtun.org> Hi All-- Tom Anderson wrote: > > I understand that the backslash is popular in some ivory-tower functional > languages. Currently, a backslash can be used for explicit line joining, > and is illegal elsewhere on a line outside a string literal, so i think > it's available for this. It would be utterly unpythonic to use puntuation > instead of a keyword, and it would make no sense to novices, but it would > scare the crap out of C programmers, which has to be worth something. > Oh, I don't think so. Don't forget that Perl was written by impatient C programmers. I think scaring C programmers, like giving engineers too much information, is really hard to do. Live by the sword, die by the sword. Metta, -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From philippe at philippecmartin.com Fri Jul 8 10:07:48 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 08 Jul 2005 14:07:48 GMT Subject: Options to integrate Python modules into native windows applications References: Message-ID: Hi, Thanks for your answers, has anyone also used .net for Python ? Regards, Philipe Philippe C. Martin wrote: > Hi, > > I am looking for the pros and cons as to how to integrate a Python module > into a Windows native application. > > So far I have looked at > > 1) coding the C wrapper myself > 2) using Pyrex > 3) go for pywin32 and COM > > Thanks, > > Philippe From peter at engcorp.com Tue Jul 12 08:21:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Jul 2005 08:21:09 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: <871x64ifl0.fsf@titan.staselog.com> References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> <11d0e158o1g8554@news.supernews.com> <18fearebf2js6$.9oemdgamm06p.dlg@40tude.net> <871x64ifl0.fsf@titan.staselog.com> Message-ID: Edvard Majakari wrote: > "first make it work, then make it right, then make it fast" > > Shouldn't one avoid doing it the wrong way from the very beginning? If you > make it "just work" the first time, you'll probably use the old code later on > because "functionality is already there" and temptatation to build on probably > relatively bad architecture can be too strong. The expression describes (most recently, if not originally) the practice in Test-Driven Development (TDD) of making your code pass the test as quickly as possible, without worrying about how nice it is. The "right" part doesn't refer to correctness, but to structure, style, readability, and all those other nice things that an automated test can't check. You aren't doing it "wrong" at first, just expediently. And it really does make sense, because at that early stage, you aren't even absolutely certain that your test is entirely correct, so making your code a paragon of elegance is a potential waste of time, and distracting. Once you've been able to pass that test (and all the others, since you have to make sure all previous tests still pass as well), then and only then is it sensible -- and required! -- to refactor the code to make it elegant, concise, clean, etc. Of course, your point about temptation is sound. Extreme Programming tries to avoid that problem partly by pairing programmers together, and it is the responsibility of both partners to encourage^H^H^H^H^H insist that the refactor "make it right" stage must occur _now_, before we check the code in. If you skip this step, you're failing to be an agile programmer, and your code base will become a tar pit even more quickly than it would in a traditional (non-agile) project... -Peter From steve at REMOVETHIScyber.com.au Sun Jul 10 11:33:39 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 11 Jul 2005 01:33:39 +1000 Subject: passing arguments to a function - do I need type ? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: On Sun, 10 Jul 2005 11:19:31 +0100, Philipp H. Mohr wrote: > Hello, > I got a newbie question, I have written the following distance function: Great. Now, how about you tell us what you expect it to do? I assume it calculates the Euclidean distance between two points. (If you don't know what Euclidean distance is, don't worry about it -- it is basically just the "normal" distance.) Should it calculate the distance between points on a line? 2-D points on a plane? 3-D points in space? Higher dimensions? I'm going to assume you want your function to operate on any number of dimensions. > def distance(self,element1, element2): You don't need "self" unless it is a method of a class. > dist = 0 > for n in range(len(element1)): > dist = dist + pow((element1[n] - element2[n]),2) > print 'dist' + dist Why are you printing the SQUARE of the distance? > return sqrt(dist) Okay, here is a simpler method, complete with comments: def distance(point1, point2): """Return the distance between two points in N-dimensional space. Example: if the points are (a,b) and (c,d) respectively, returns the Euclidean distance d = sqrt( (c-a)**2 + (d-b)**2 ) Both points should have the same number of coordinates, each of which is a float or int. Points can be given as lists or tuples. """ sum_sq = 0 # sum of squares of the differences if len(point1) != len(point2): # check for errors here because they might not be picked # up later if we don't raise ValueError("Points have different number of dimensions") for i in range(len(point1)): x, y = point1[i], point2[i] # extract the next two ordinates sum_sq = sum_sq + (y-x)**2 # and add the square of the difference return sum_sq**0.5 If you really care about accuracy, you should use the sqrt function from the math module rather than **0.5. Here is another version, using zip. def distance(point1, point2): if len(point1) != len(point2): raise ValueError("Points have different number of dimensions") L = zip(point1, point2) sum_sq = 0 for x,y in L: sum_sq = sum_sq + (y-x)**2 return sum_sq**0.5 And finally, a one-liner using list comprehensions and no error-checking. def distance(point1, point2): return sum([(y-x)**2 for x,y in zip(point1, point2)])**0.5 > and in order to be able to use len() and index element1[] the function > needs to know that the arguments element1 and element2 are both listst > or doesn't it ? No. Lots of things can be passed to len() and indexed. > I get the following error msg: > > Traceback (most recent call last): > File "Memory.py", line 105, in ? > start.inputVector(inP2) > File "Memory.py", line 97, in inputVector > allDimensions[0].newAttribute(vector) > File "Memory.py", line 56, in newAttribute > dist = self.distance(n.getCenter,newElement) > File "Memory.py", line 75, in distance > for n in range(len(element1)): > TypeError: len() of unsized object And what is element1 when you get that error message? That's the first thing I would look at. > AND if I take len out I get: > > > Traceback (most recent call last): > File "Memory.py", line 105, in ? > start.inputVector(inP2) > File "Memory.py", line 97, in inputVector > allDimensions[0].newAttribute(vector) > File "Memory.py", line 56, in newAttribute > dist = self.distance(n.getCenter,newElement) > File "Memory.py", line 76, in distance > dist = dist + pow((element1[n] - element2[n]),2) > TypeError: unsubscriptable object Firstly, you seem to have a lot of modules there. What happens when you call distance directly? Can you get it to work then? Secondly, what are the values for element1 and element2? -- Steven. From noreply at gcgroup.net Mon Jul 18 12:57:51 2005 From: noreply at gcgroup.net (William Gill) Date: Mon, 18 Jul 2005 16:57:51 GMT Subject: main window in tkinter app Message-ID: A short while ago someone posted that(unlike the examples) you should use Tk as the base for your main window in tkinter apps, not Frame. Thus : class MyMain(Frame): def __init__(self, master): self.root = master self.master=master self.createWidgets() def createWidgets(): ... root = Tk() app = MyMain(root) app.master.title("Object Editor") root.mainloop() would become: class MyMain(Tk): ... ... app = MyMain() app.title("My App") app.mainloop() When I try converting to this approach I run into a problem with the __init__() method. It appears to go into an infinite loop in tkinter.__getattr__(). If I omit __init__() I get a properly titled window, but must explicitly call my createWidgets method from __main__. class MyMain(Tk): createWidgets() ... ... app = MyMain() app.title("My App") app.createWidgets() app.mainloop() Am I missing something? Bill From kay.schluehr at gmx.net Tue Jul 19 09:10:01 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jul 2005 06:10:01 -0700 Subject: Documentation bug: Python console behaviour changed References: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> <-I2dnSVstZw-ekHfRVn-rA@powergate.ca> Message-ID: <1121777815.734892.40120@g49g2000cwa.googlegroups.com> Peter Hansen schrieb: > Kay Schluehr wrote: > > The documentation of the Python console behaviour is not correct > > anymore for Python 2.4.1. At least for the Win2K system I'm working on > > 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. > > > > The Python interpreter tells me instead: > > > > > >>>>quit > > > > 'Use Ctrl-Z plus Return to exit.' > > > > Nah, 'Ctrl-Z' is now undo :-) > > Are you really using the console, started with the "Command Prompt" icon > from the Start Menu (or some equivalent)? > And are you sure you haven't > installed something else that magically changed the behaviour of Ctrl-Z? > > (I get the documented behaviour with Python 2.4.1, under Win XP.) > > -Peter Well, Peter, I indeed changed the system magically but yet it was not Windows, but Python! In my description I told You that I installed IPython and IPython requires the readline package. If I rename the readline package ( e.g. _readline ) in the site-packages directory the console behaves as expected. Otherwise it shows the termination behaviour of IPython namely it shuts down with Ctrl-D. It's really sucking... Kay From renting at astron.nl Thu Jul 28 11:41:53 2005 From: renting at astron.nl (Adriaan Renting) Date: Thu, 28 Jul 2005 17:41:53 +0200 Subject: Rich Graphics? Message-ID: I realy like Qt through PyQt. The combination Eric3+Qtdesigner is quite useful. Maybe PyQt is not yet ready for the new Qt4 I think, but it does lot's of the graphical stuff you seem to require. Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> Chris Spencer 07/28/05 1:14 AM >>> I'm trying to write a Gui in Python for manipulating rich graphical representations, similar to something like Inkscape. I've tried tkinter, wxPython, pyGtk, and while they all do traditional widgets well enough, none of them really handle anti-aliased, transparent, transformed shapes typical of vector based displays. I've noticed tkZinc, which seems to better handle vector graphics through the use of openGL, but it's traditional widget set is still limited and based on tkinter. Ideally, what I'm looking for is something like wxWidgets which can display SVG along side standard widgets and allow there manipulation through Python. I was thinking of a web-based route, by accessing the SVG capabilities in Mozilla's Deer Park browser through Twisted+Livepage, but this has been extremely complicated and limiting. Are there any other options I haven't considered? Sincerely, Chris -- http://mail.python.org/mailman/listinfo/python-list From kay.schluehr at gmx.net Wed Jul 20 11:06:51 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 Jul 2005 08:06:51 -0700 Subject: python certification In-Reply-To: References: <20050720142210.56E6D7EC2B@postix.sdv.fr> Message-ID: <1121872011.306282.88950@g47g2000cwa.googlegroups.com> Andreas Kostyrka schrieb: > (These are the people look for Pearl and Pyhton programmers ;) ) Or Phyton :) Kay From none at no.chance Fri Jul 22 07:45:11 2005 From: none at no.chance (Peter Tillotson) Date: Fri, 22 Jul 2005 11:45:11 +0000 Subject: Detecting computers on network In-Reply-To: References: Message-ID: You could use a sniffer in promiscuous mode. pypcap -- or something like. This will record every packet seen by your network card. Whether is will work depends on whether you are on a true braodcast network. if a box is on and completely inactive you'll never see it, but most boxes do something. Windows boxes positively shout about there presence :-) baically this is pasive nmap, nmap will try to open a tcp or udp connection on every machine. your going to generat a lot of traffic. If you've got access to the boxes enabling ICMP and using that is the proper way. Sandeep Arya wrote: > Hello dear > > I had sent my earlier queries regarding same topic. However just to be > more specific this time.. > > I just wann try to detect that if there are some ip address in a list of > some ip address alive or not. > > How can i do this? > > Shall i try to connect them and check that my connection is working or > not? If working than means alive .... (connection based) > > SHalle i send some buffer value (whatever) to socket using sendto(...) > and then checking for return value? (Connectionless) > > Well for me it doesnot matter that i should have connection or > connectionless.. I just wannn know who are alive in my LAN? > > This application will be for my computers in lan. not for maganetwork. > > LAN will have just some bridges and computers. > > i need to detect tham all.. > > however i doesnot matter that all of them replies or not. I just wann > know that atleast some of them reply. Rest i will take care of... > > > Sandeep > > _________________________________________________________________ > NRIs, does your family in India need money urgently? > http://creative.mediaturf.net/creatives/icicibank/ICICI_NRI_ERA.htm Open > an ICICI Bank NRI savings A/c > From fotis77k at fmail.co.uk Mon Jul 4 04:20:54 2005 From: fotis77k at fmail.co.uk (fotis) Date: 4 Jul 2005 01:20:54 -0700 Subject: Debugging embedded python Message-ID: <1120465254.327966.196570@g14g2000cwa.googlegroups.com> hello there! I am playing with embedded python these days. I wrote sth like this: ------------------------------ Code ------------------------------- #include #include #include /* Return the square root of an argument */ static PyObject* Fotis_root(PyObject *self, PyObject *args) { double d=0; if(!PyArg_ParseTuple(args,"d",&d)) return NULL; return Py_BuildValue("d", sqrt(d)); } static PyMethodDef FotisMethods[] = { {"root",Fotis_root, METH_VARARGS, "Return the root of a double."}, {NULL, NULL, 0, NULL} }; int main(int argc,char** argv) { Py_Initialize(); Py_InitModule("fotis", FotisMethods); PyRun_SimpleString("from fotis import root"); PyRun_SimpleString("print \"Testing embedded python...\""); FILE* fp=stdin; char *filename="Embedded"; PyRun_InteractiveLoop(fp,filename); Py_Finalize(); return 0; } ------------------------------------------------------------------ I linked it to python24.lib (under eclipse cdt/win2k) and it compiles, links and runs fine. The problem is when I try to debug it (gdb). I cannot go single stepping into the code, more than one threads seem to be running, I get messages like "No source file named d:/workspace/pyTest/main.cpp", and if I set a breakpoint to the function Fotis_root then I cannot see any variables. In fact I cannot see no stack, no registers nothing, within this function! With msvc 6.0 debuging goes smoothly. Any ideas? Thank you. Fotis._ From __peter__ at web.de Tue Jul 12 02:31:01 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Jul 2005 08:31:01 +0200 Subject: automatically assigning names to indexes References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> Message-ID: simonwittber at gmail.com wrote: > However, I'd like to add attribute access (magically), so I can do > this: > > v = Vector((1,2,3)) > print v.x > print v.y > print v.z > > as well as: > > print v[0] > print v[1] > print v[2] > > Has anyone got any ideas on how this might be done? >>> class Vector(tuple): ... x = property(lambda self: self[0]) ... y = property(lambda self: self[1]) ... z = property(lambda self: self[2]) ... >>> Vector("abc") ('a', 'b', 'c') >>> Vector("abc").z 'c' >>> Vector("abc")[2] 'c' However, no magic is involved. Peter From rupole at hotmail.com Wed Jul 13 14:03:31 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 13 Jul 2005 14:03:31 -0400 Subject: exec method WMI References: <1121273148.010439.70100@g44g2000cwa.googlegroups.com> Message-ID: <42d55898$1_2@spool9-west.superfeed.net> You probably need to remove the SpawnInstance_() call. An abstract WMI class as returned by WBEM.Get should work for the DriverInfo parm, since the concrete Win32_PrinterDriver instance is what the AddPrinterDriver call is trying to create. hth Roger wrote in message news:1121273148.010439.70100 at g44g2000cwa.googlegroups.com... > Hi, I'm trying to use the AddPrinterDriver method of > Win32_PrinterDriver to create a new..... print driver. I can't get my > head round how I need to do this. So far I have > > import win32com.client > WBEM = > win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" > + "." + r"\root\cimv2") > WBEM.Security_.Privileges.AddAsString("SeLoadDriverPrivilege") > drv = WBEM.Get("Win32_PrinterDriver").SpawnInstance_() > drv.Properties_('Name').Value = "Marcs Printer 2550" > drv.Properties_('SupportedPlatform').Value = "Windows NT x86" > drv.Properties_('Version').Value = "3" > drv.Properties_('DriverPath').Value = 'C:\\test\\HPZPP034.DLL' > drv.Properties_('InfName').Value = 'C:\\test\\hpc2550d.inf' > method = drv.Methods_('AddPrinterDriver') > InParms = method.InParameters > InParms.Properties_.Item('DriverInfo').Value = drv > drv.ExecMethod_('AddPrinterDriver',InParms) > > I'm using spawninstance to create a new object and then editing the > properties of it. I'm then setting the InParameters for the method to > be the new object. When executing the method I get SWbemObjectEx > object not found. > > I think I am not setting the DriverInfo correctly, should it be an > object? The MSDN site doesn't say what DriverInfo should be. > > Any help would be grand. > > Thanks, MW. > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From thanos at sians.org Sun Jul 24 07:47:03 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 14:47:03 +0300 Subject: Getting a dictionary from an object In-Reply-To: <42e37c1e$0$30692$636a15ce@news.free.fr> References: <42e37c1e$0$30692$636a15ce@news.free.fr> Message-ID: <20050724114703.GA2845@zermelo.sians.org> On Sun, Jul 24, 2005 at 02:01:30PM +0200, Bruno Desthuilliers wrote: > Thanos Tsouanas a ?crit : > > On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote: > > > > Because *obviously* I don't know of these indexing and attribute > > grabbing machineries you are talking about in my case. If you cared to > > read my first post, all I asked was for the "normal", "built-in" way to > > do it. Now, is there one, or not? > > If you re-read your first post, you'll notice that you didn't say > anything about the intention, only about implementation !-) """The following works, but I would prefer to use a built-in way if one exists. Is there one?""" > Now if your *only* need is to access object as a dict for formated > output, you don't need to subclass dict. This is (well, should be) enough: > > class Wrapper(object): > def __init__(self, obj): > self._obj = obj > def __getitem__(self, name): > return getattr(self._obj, name) > > This works with 'normal' attributes as well as with properties. Notice > that this wrapper is read-only, and don't pretend to be a real > dictionnary - but still it implements the minimum required interface for > "%(attname)s" like formatting. Thanks!! You made clear what 'the extra functionality' was. Indeed there is no need to subclass dict... > HTH it does! > Bruno > -- > http://mail.python.org/mailman/listinfo/python-list -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From aisaac0 at verizon.net Fri Jul 22 00:14:10 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 22 Jul 2005 04:14:10 GMT Subject: Returning histogram-like data for items in a list References: Message-ID: "Ric Deez" wrote in message news:dbpat7$28o$1 at nnrp.waia.asn.au... > I have a list: > L1 = [1,1,1,2,2,3] > How can I easily turn this into a list of tuples where the first element > is the list element and the second is the number of times it occurs in > the list (I think that this is referred to as a histogram): For ease of reading (but not efficiency) I like: hist = [(x,L1.count(x)) for x in set(L1)] See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277600 Alan Isaac From cam.ac.uk at mh391.invalid Sun Jul 31 10:13:32 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 31 Jul 2005 15:13:32 +0100 Subject: keylogger in Python In-Reply-To: <1122817977.591696.198240@f14g2000cwb.googlegroups.com> References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> <1122817977.591696.198240@f14g2000cwb.googlegroups.com> Message-ID: simonwittber at gmail.com wrote: > Actually, it's pretty easy, using the pyHook and Python win32 modules. Well, I'll be. -- Michael Hoffman From tjreedy at udel.edu Fri Jul 22 14:11:34 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Jul 2005 14:11:34 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com><3kakh5Ftjd9mU1@individual.net><11e0cpe7vqrm18a@news.supernews.com><1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: "Daniel Dittmar" wrote in message news:dbr79q$ftg$1 at news.sap-ag.de... > Duncan Booth wrote: >> I would have expected a >> path object to be a sequence of path elements rather than a sequence of >> characters. Glad I'm not the only oddball. > Maybe it's nitpicking, but I don't think that a path object should be a > 'sequence of path elements' in an iterator context. > > This means that > > for element in pathobject: > > has no intuitive meaning for me, so it shouldn't be allowed. ???? The internal equivalent of (simplified, omitting error checking, etc.) for dir in pathobject: if isdir(dir): cd(dir) *is*, in essence, what the OS mainly does with paths (after splitting the string representation into pieces). Directory walks also work with paths as sequences (stacks, in particular). Terry J. Reedy From peter at engcorp.com Fri Jul 1 11:40:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 11:40:13 -0400 Subject: python project layout In-Reply-To: References: Message-ID: <9JqdnRP9IqxM_ljfRVn-rA@powergate.ca> Huron wrote: > What do you guys recommend in terms of python project layout, especially > unit tests layout ? > Zope has unit tests per packages, twisted has a big tests directory full of > tests ... and the file naming convention are also pretty differents ... > I guess there is part of "personnal choices" in those matters ... but there > is also good practice advices that can be gathered I think ... (This is the result of a few years of evolution of our source tree conventions.) We place all tests in subfolders (named "tests") of the folders containing the files under test. Unit tests are named for the unit (module) they are testing, so serial.py would have a unit test file at tests/serial_unit.py. "Acceptance" tests (higher level usually black-box functional tests) are in the "tests" folder of the top level source folder, along with any unit tests that reside there, and take their name from the number of the requirement that defined them. Since we're an XP team, we call these requirements "stories", so the files are named exciting things like "story001.py" and "story197.py". The specific numbers match up with either index cards with descriptions of the requirements, or an online "issue tracker", depending on the project. We have a little (quite simple) internal utility that lets us easily run all unit tests under the current folder, or all acceptance tests in the project, with one command. (Specifically, "uix" and "stix" for unit and story tests, respectively.) This "test runner" utility scans subfolders (doing an os.walk basically) and executes each test script in a new process, to avoid most potential undesirable interactions between tests. The benefits are straightforward. Tests are easy to find for any file, but don't "clutter up" the same folder as the files under test. The naming conventions makes it easy to automate things like the test runner or other utilities. Running tests (always from a console) takes only a few seconds so we can do it often. Multiple projects are easily supported in other directory trees. -Peter From chrisconnett at gmail.com Fri Jul 22 22:27:36 2005 From: chrisconnett at gmail.com (Chris Connett) Date: 22 Jul 2005 19:27:36 -0700 Subject: How to modify a file 'in place' ? In-Reply-To: <42e1194d$0$7428$626a14ce@news.free.fr> References: <42e1194d$0$7428$626a14ce@news.free.fr> Message-ID: <1122085656.080215.232230@g14g2000cwa.googlegroups.com> There is a module in the library called fileinput, should do what you're looking for. From hancock at anansispaceworks.com Fri Jul 1 15:29:14 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 14:29:14 -0500 Subject: LOC in Python and C++ in large projects In-Reply-To: References: Message-ID: <200507011429.14642.hancock@anansispaceworks.com> On Friday 01 July 2005 07:55 am, Adriaan Renting wrote: > I think it would be interesting if any readers with more experience as I > have would comment on how Python behaves in large projects, and how much > less lines they need compared to C++ or Java. > I have worked on several C++ projects with a few million lines of code, > I would appreciate experience with comparable projects. (can you do it > in 10.000 Lines of Python?) Well, Zope 2.7.0 is (about) 158,046 LOC by a simple wc (with full-line comments and blank lines stripped). Zope X3 is 175,818 LOC by the same wc method.* I am only counting the Python code, BTW, not the C extension modules. The thing that's coming into my mind, is what on Earth would require "a few million lines of code" in Python? And also, what would be comparable to Zope, written in C++? OTOH, Zope uses a number of techniques that trump your "C++ advantages" such as their own "interfaces" module which is probably superior to "static type checking" as a means of maintaining communications between programmers (even 3rd party programmers, which is very important on an open source project). Of course, you could argue that "static type checking" and "interfaces" are very similar, but I think the latter is a bit smarter, at least in Python using Zope3's interface module. So, in a sense, I agree with you that such tools help keep code manageable, but disagree that Python doesn't have them. *Which is just this: .../Zope-2.7.0/lib/python> find . -name "*.py" -exec grep -v -e "^#" {} \; | grep -v -e '^$' | wc 158046 591237 6312725 .../ZopeX3/lib/python> find . -name "*.py" -exec grep -v -e "^#" {} \; | grep -v -e '^$' | wc 175818 642486 7023206 I'm sure there are holes in this method, but it ought to give a rough count. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From apoco at cox.net Thu Jul 7 14:56:03 2005 From: apoco at cox.net (Jacob Page) Date: Thu, 07 Jul 2005 11:56:03 -0700 Subject: Python Module Exposure Message-ID: I have created what I think may be a useful Python module, but I'd like to share it with the Python community to get feedback, i.e. if it's Pythonic. If it's considered useful by Pythonistas, I'll see about hosting it on Sourceforge or something like that. Is this a good forum for exposing modules to the public, or is there somewhere more-acceptable? Does this newsgroup find attachments acceptable? -- Jacob From zen19725 at zen.co.uk Sun Jul 31 00:47:05 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 05:47:05 +0100 Subject: [path-PEP] Path inherits from basestring again References: <3l1q3tF10l1krU1@individual.net> Message-ID: On Sat, 30 Jul 2005 19:01:49 +0200, Reinhold Birkenfeld wrote: >phil hunt wrote: > >> def normalizePath(p, *pathParts): >> """ Normalize a file path, by expanding the user name and getting >> the absolute path.. >> @param p [string] = a path to a file or directory >> @param pathParts [list of string] = optional path parts >> @return [string] = the same path, normalized >> """ >> p1 = os.path.abspath(os.path.expanduser(p)) >> if len(pathParts)>0: >> allPathParts = [ p1 ] >> allPathParts.extend(pathParts) >> p1 = os.path.join(*allPathParts) >> p2 = os.path.abspath(p1) >> return p2 >> normalisePath=normalizePath # alternate spelling >> join=normalizePath # it works like os.path.join, but better >> >> >> To be honest I don't see the point of having a Path class. That's >> the way Java does it, and I find path handling in Java to be a lot >> more of a hassle than in Python. (Actually, most things are more of >> a hassle in Java, but that's another story). > >You see, with the Path class the above function could be written as > >def normalizePath(p, *pathParts): > """ Normalize a file path, by expanding the user name and getting > the absolute path.. > @param p [Path] = a path to a file or directory > @param pathParts [list of string/Path] = optional path parts > @return [Path] = the same path, normalized > """ > tp = p.expanduser().abspath() > return tp.joinwith(*pathParts).abspath() > >That's clearly an improvement, isn't it? An improvement to what? To how the class is implemented, or to how it is used? If you mean the former, yes is it, due to the os.path module not providing a function that does this. If you mean the latter, I disagree, because I would then have to call it with something like: pn = normalizePath(Path(p), q) and then I would have the problem that (pn) isn't a string so calling a function to write some data into the file at that filename would no longer work, i.e. this: writeFile(pn, someData) would become this: writeFile(pn.getString(), someData) I don't see what having a Path type buys me. -- Email: zen19725 at zen dot co dot uk From cam.ac.uk at mh391.invalid Mon Jul 25 04:44:05 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 25 Jul 2005 09:44:05 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kjihkFubvl6U1@individual.net> References: <3kjihkFubvl6U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Tony Meyer wrote: >>Do people really like using __div__ to mean join? On the python-dev >>discussion, Just van Rossum spoke out against it, but there weren't (IIRC) >>any other comments, either pro or con. > > I'm not too happy with it, too, but do we have alternatives? As paths are strings, > we can hardly override the '+' operator, so there's not much operators left. > > Of course, one can use joinwith() if he doesn't like '/'. I've used the path module pretty extensively and always use joinpath(). Personally, I'm -0 on __div__, but I suppose if anyone here claimed to have used in the past, rather than it just being some novelty that might be a good idea, that would be good enough for keeping it. -- Michael Hoffman From bokr at oz.net Tue Jul 5 11:46:26 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 05 Jul 2005 15:46:26 GMT Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Message-ID: <42ca8aa8.594263736@news.oz.net> On Mon, 4 Jul 2005 13:01:06 -0500, Jeff Epler wrote: > >--s2ZSL+KKDSLx8OML >Content-Type: text/plain; charset=us-ascii >Content-Disposition: inline > >This stupid code works for modules, but not for packages. It probably has bugs. > > >import marshal, types > >class StringImporter: > def __init__(self, old_import, modules): > self._import = old_import > self._modules = modules > > def __call__(self, name, *args): > module = self._modules.get(name, None) > if module is None: > return self._import(name, *args) > code = marshal.loads(module) > mod = types.ModuleType(name) > exec code in mod.__dict__ > return mod > >def test(): > import __builtin__ > __builtin__.__import__ = StringImporter(__builtin__.__import__, > { 'test_importer': open("/usr/lib/python2.3/os.pyc").read()[8:] }) > > import test_importer > print test_importer.path.join("a", "b") > print test_importer.__doc__ > >if __name__ == '__main__': test() I have a feeling that the OP might be looking for a way to convert source -> source, e.g., (sketch only, not even remotely tested ;-) # main.py import some_module import another into # main.py # prelim import marshal, sys # builtin ModuleType = type(__builtins__) # avoid import types def unscramble_proprietary_format(proprietary_string): # ... whatever def extract_code(proprietary_string): return marshal.loads(unscramble_proprietary_format(proprietary_string)) # replacing each import with try: some_module = sys.modules['some_module'] # don't re-"import" except KeyError: some_module = ModuleType('some_module') exec extract_code( "< ... string literal for proprietarily scrambled marshalled module body code" " generated by source -> source rewrite utility ... >" ) in some_module.__dict__ sys.modules['some_module'] = some_module try: another = sys.modules['another'] except NameError: another = ModuleType('another') exec extract_code('') sys.modules['another'] = another # etc so that his some_module and another scripts can be pre-compiled by the rewrite utility and embedded in a single source (e.g. main.py) so that he doesn't have to have external .pyc file accesses. His startup will then still cost the execs, but not the compiles, and if he doesn't "import" stuff he doesn't need, until he needs it, it should spread the import time load, if so desired. All the proprietary string literal sources should become efficiently represented as part of the single main.pyc IWT, assuming at least that one is used. Chasing various forms of import of non-builtins recursively to eliminate imports in imported modules before they are converted to marshalled form etc., all to avoid real imports, and statically determining that some imports don't need to be converted to marshalled string import form because a prior import can be proved, should be an interesting exercise, which I can't pursue at this point... ;-) But I may be reading too much between the lines ;-) Regards, Bengt Richter From avishorp at yahoo.com Wed Jul 20 03:03:33 2005 From: avishorp at yahoo.com (avishay) Date: 20 Jul 2005 00:03:33 -0700 Subject: Using SHFileOperation Message-ID: <1121843013.558480.43380@g43g2000cwa.googlegroups.com> Hi All, I want to use SHFileOperation using Python and Win32 extentions, in order to move a file to the trash can. The function itself can be accessed by importing win32com.shell.shell. However, I cannot find anywhere the SHFILEOPSTRUCT. This structure is mentioned in the documentation of the Win32 extentions, but I can't find a way to access it. I would appreciate your help. If there's an alternative way to send a file to the trash can, that can also help. Best Regards Avishay From joe.woodward at padtinc.com Wed Jul 13 17:24:36 2005 From: joe.woodward at padtinc.com (Joe) Date: 13 Jul 2005 14:24:36 -0700 Subject: Splitting on a word In-Reply-To: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> Message-ID: <1121289876.341736.320980@g49g2000cwa.googlegroups.com> # string s simulating an html file s='ffy: ytrty python fyt wx dtrtf' p=re.compile(r'\bhref\b',re.I) list=p.split(s) #<<<<<<<<<<<<<<<<< gets you your final list. good luck, Joe From jelee2 at uiuc.edu Mon Jul 4 01:50:39 2005 From: jelee2 at uiuc.edu (Jacob Lee) Date: Mon, 04 Jul 2005 01:50:39 -0400 Subject: Host resolution problems with socket module Message-ID: I'm getting a rather bizarre error while using the socket module. If I start out disconnected from the net and then connect while the program or interpreter session is open, I do not always gain the ability to resolve or connect to hosts by name. Here is the problematic scenario: >>> from socket import * >>> gethostbyname('google.com') # Fails as expected Traceback (most recent call last): File "", line 1, in ? File "", line 1, in connect socket.gaierror: (-3, 'Temporary failure in name resolution') >>> gethostbyname('google.com') # Should succeed Traceback (most recent call last): File "", line 1, in ? File "", line 1, in connect socket.gaierror: (-3, 'Temporary failure in name resolution') After some testing, I believe that this behavior is dependent on whether the first call to gethostbyname() succeeded or not. If the first call succeeded, subsequent calls will either resolve the host or raise an exception depending on the status of the internet connection. If the first call failed (i.e. raised the above exception), subsequent ones will always raise the same exception no matter if the connection has been restored. I should also add that getaddrinfo() and .connect() on socket objects both fail in the same way as gethostbyname(). Deleting the socket module and then importing it again does not help, nor does calling reload(socket). I've been testing this on Linux with both python 2.3 and python 2.4. As far as I can tell, the only variable that affects this behavior is the status of the connection at the time gethostbyname() is first called. Is there anything else I can do to fix this problem? Is it maybe a python bug, or is it representative of some lower-level subtlety (e.g. in the C libraries) that I'm unaware of? Has anyone else run into this before? -- Jacob Lee jelee2 at uiuc.edu | www.nearestneighbor.net From lbates at syscononline.com Thu Jul 7 18:26:49 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 07 Jul 2005 17:26:49 -0500 Subject: Upgrading from Python 2.2 to 2.4 (can't find _ssl.pyd) Message-ID: Well I'm still on my "quest". I've been putting this off for quite some time because I KNEW it was going to be hard. I tried to wait a while to upgrade to let all these things become readily available. So far Sam Rushing has been my hero in putting updated versions (2.4) of calldll and npstruct on his website: http://www.nightmare.com/~rushing/dynwin/index.html Thanks Sam! I've been able to track everything else down, but I have to admit that it has been harder than I thought...and I'm not done. Now I can't find _ssl.pyd compiled for Python 2.4. Anybody have a copy they can share? Thanks in advance, Larry Bates From future_retro at yahoo.co.uk Fri Jul 22 05:33:54 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 22 Jul 2005 02:33:54 -0700 Subject: RegUnloadkey access denied In-Reply-To: <1122022887.947520.152460@o13g2000cwo.googlegroups.com> References: <1122022887.947520.152460@o13g2000cwo.googlegroups.com> Message-ID: <1122024834.778860.321410@g44g2000cwa.googlegroups.com> I've worked out that I can open and close the key fine if I don't open a subkey. I've tried adding flush and close statements after opening the key and still get access denied when trying to unload. From trentm at ActiveState.com Tue Jul 26 11:48:52 2005 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 26 Jul 2005 08:48:52 -0700 Subject: problem with ActiveState install In-Reply-To: <1122383685.483563.137600@g47g2000cwa.googlegroups.com> References: <1122383685.483563.137600@g47g2000cwa.googlegroups.com> Message-ID: <20050726154852.GA14313@ActiveState.com> [Steve wrote] > I've installed the ActiveState binary distribution for Solaris in my > home directory, but I'm having problems with Tk. > > I think I did everything right -- I used gtar rather than Solaris tar, > and the install process indicated it was successful. I added the > python directory to ~/.bashrc. > > Python works fine from the command line. > > But if I try to execute anything that uses Tkinter (including Idle), > the console window goes blank and then nothing else happens. I have to > use control+z to break out. > > Does anyone have any idea what the problem might be, and how to fix it? What version did you install? I.e. what was the package name. Or do this: $ python >>> import activestate, pprint >>> pprint.pprint(activestate.version_info) What version of Solaris do you have? Run: uname -a Do you get an error doing the following minimal Tkinter test: >>> import Tkinter >>> Tkinter.Tk() Cheers, Trent -- Trent Mick TrentM at ActiveState.com From twic at urchin.earth.li Mon Jul 4 10:23:44 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 4 Jul 2005 15:23:44 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: On Sun, 3 Jul 2005, Robert Kern wrote: > Erik Max Francis wrote: >> Ron Adam wrote: >> >>> So you are saying that anything that has a 1% use case should be included >>> as a builtin function? >>> >>> I think I can find a few hundred other functions in the library that are >>> used more than ten times as often as reduce. Should those be builtins >>> too? >>> >>> This is a practical over purity issue, so what are the practical reasons >>> for keeping it. "It's already there" isn't a practical reason. And it >>> covers 100% of it's own potential use cases, is circular logic without a >>> real underlying basis. >> >> But the Python 3000 plan, at least what we've heard of it so far, isn't >> to move it to a standard library module. It's to remove it altogether, >> replacing it with sum and product. Since sum and product don't cover >> all the uses cases for reduce, this is a case of taking one function >> that handles all the required use cases and replacing it with _two_ >> functions that don't. Since it's doubling the footprint of the reduce >> functionality, arguments about avoiding pollution are red herrings. > > Four, in fact. sum(), product(), any(), and all(). I'll just chip in and say i'd quite like a flatten(), too; at the moment, i have one like this: def flatten(ll): return reduce(lambda a, l: a.extend(l), ll, []) A builtin, which had fast special-case code for then the argument is a list of lists (rather than an iterable of iterables), would be nice, since this is a reasonably big use of reduce for me. How would one do that as a list comp, by the way? I'm really not very good with them yet. > [1] Okay, there was that guy who predicted that list comprehensions and > first-class functions were the next to go. That was new. But also wrong. > I think we can discount that. True. Guido will only get rid of those after he's got rid of lowercase letters in identifiers. tom -- A military-industrial illusion of democracy From maxm at mxm.dk Mon Jul 4 02:56:37 2005 From: maxm at mxm.dk (Max M) Date: Mon, 04 Jul 2005 08:56:37 +0200 Subject: What are the other options against Zope? In-Reply-To: References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: <42c8dd47$0$298$edfadb0f@dread12.news.tele.dk> phil wrote: > Peter Hansen wrote: > Now understand, I know what very well what Python, Apache, PhP, > MySQL, IE and javascript do. I just don't know what Zope > does. > > And if the answer is going contain phrases like "brings together" > or "sits on top of", don't bother. :-) It's an object oriented database, with a structure that is similar to files and directories in an ordinary OS. But it is a lot smarter, because the files and directories are actually objects with different attributes and parameters. The methods on these objects can then be called eg. from a web browser with different parameters. But you can also use other protocols than http like dav, ftp etc. This is a very effective way to build web applications, and does not need sql-object remapping as normal web apps does. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From steve at REMOVETHIScyber.com.au Sun Jul 17 09:01:38 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 17 Jul 2005 23:01:38 +1000 Subject: Tuples in function argument lists Message-ID: I'm trying to understand the use of tuples in function argument lists. I did this: >>> def tester(a, (b,c)): ... print a, b, c ... >>> tester(1, 2) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in tester TypeError: unpack non-sequence That was obvious result. >>> tester(1, (2, 3)) 1 2 3 >>> tester('ab', 'ab') ab a b And so were those. Then I tried this: >>> def tester(a, (b,c)=None): ... if (b,c) is None: ... print a, None ... else: ... print a, b, c Needless to say, it did not do what I expected it to do. I didn't expect it to either :-) I tried looking at the language reference here: http://docs.python.org/ref/function.html but I can't seem to find anything in their that says that tuples-as-args are legal. Am I misreading the docs, or is this accidental behaviour that shouldn't be relied on? Does anyone use this behaviour, and if so, under what circumstances is it useful? -- Steven From k04jg02 at kzoo.edu Tue Jul 12 19:17:46 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Tue, 12 Jul 2005 17:17:46 -0600 Subject: Creating anonymous functions using eval In-Reply-To: References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> <1121184988.996652.126350@g47g2000cwa.googlegroups.com> Message-ID: <42D44F9A.20308@kzoo.edu> Robert Kern wrote: >Not everyone is reading this list in a conveniently threaded >form > > Why not? Just about every modern newsgroup reader and e-mail app has a threaded view option. From steven.bethard at gmail.com Fri Jul 8 13:03:54 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Jul 2005 11:03:54 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <74ize.27369$ho.19404@bignews6.bellsouth.net> <9nmze.144208$VH2.52770@tornado.tampabay.rr.com> Message-ID: Christopher Subich wrote: > Ron Adam wrote: >> I think the association of (lambda) to [list_comp] is a nice >> distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) > > Yeah, dictionary comprehensions would be an interesting feature. :) > Syntax might be a bit unwieldy, though, and I doubt they'd be used often > enough to be worth implementing, but still neat. Dict comprehensions were recently rejected: http://www.python.org/peps/pep-0274.html The reason, of course, is that dict comprehensions don't gain you much at all over the dict() constructor plus a generator expression, e.g.: dict((i, chr(65+i)) for i in range(4)) STeVe From enleverlesO.OmcO at OmclaveauO.com Fri Jul 8 02:49:55 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 8 Jul 2005 08:49:55 +0200 Subject: Options to integrate Python modules into native windows applications References: Message-ID: <42ce222b$0$22271$8fcfb975@news.wanadoo.fr> Hi ! I use, intensively, Python, via COM & PyWin32, from Paradox (Object-Pal), VBScript, Excel, Word, Internet-explorer, AutoIt, etc. It is simple, powerful and extensible dynamically. @-salutations -- Michel Claveau From bokr at oz.net Tue Jul 12 23:54:14 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Jul 2005 03:54:14 GMT Subject: Frankenstring References: <42d43047$1@nntp0.pdx.net> Message-ID: <42d48dba.41657380@news.oz.net> On Wed, 13 Jul 2005 03:49:16 +0200, Thomas Lotze wrote: >Scott David Daniels wrote: > >> Now if you want to do it for a file, you could do: >> >> for c in thefile.read(): >> .... > >The whole point of the exercise is that seeking on a file doesn't >influence iteration over its content. In the loop you suggest, I can >seek() on thefile to my heart's content and will always get its content >iterated over exactly from beginning to end. It had been read before any >of this started, after all. Similarly, thefile.tell() will always tell me >thefile's size or the place I last seek()'ed to instead of the position of >the next char I will get. > What I suggested in my other post (untested beyond what you see, so you may want to add to the test ): ----< lotzefile.py >-------------------------------------------------- class LotzeFile(file): BUFSIZE = 4096 def __init__(self, path, mode='r'): self.f = file(path, mode) self.pos = self.bufbase = 0 self.buf = '' def __iter__(self): return self def next(self): if not self.buf[self.pos:]: self.bufbase += len(self.buf) self.pos = 0 self.buf = self.f.read(self.BUFSIZE) if not self.buf: self.close() raise StopIteration byte = self.buf[self.pos] self.pos += 1 return byte def seek(self, pos, ref=0): self.f.seek(pos, ref) self.bufbase = self.f.tell() self.pos = 0 self.buf = '' def tell(self): return self.bufbase + self.pos def close(self): self.f.close() def test(): f = file('lotzedata.txt','w') for s in (' %3d'%i for i in xrange(1000)): f.write(s) f.close() it = iter(LotzeFile('lotzedata.txt')) hold4=[0,0,0,0] for i, c in enumerate(it): hold4[i%4] = c if i%4==3: print hold4 assert (i-3)/4 == int(''.join(hold4)) if i == 99: break print it.tell() it.seek(52) for i in xrange(8): print it.next(), print it.seek(990*4) for c in it: print c, if __name__ == '__main__': test() ---------------------------------------------------------------------- Result: [20:53] C:\pywk\clp>py24 lotze.py [' ', ' ', ' ', '0'] [' ', ' ', ' ', '1'] [' ', ' ', ' ', '2'] [' ', ' ', ' ', '3'] [' ', ' ', ' ', '4'] [' ', ' ', ' ', '5'] [' ', ' ', ' ', '6'] [' ', ' ', ' ', '7'] [' ', ' ', ' ', '8'] [' ', ' ', ' ', '9'] [' ', ' ', '1', '0'] [' ', ' ', '1', '1'] [' ', ' ', '1', '2'] [' ', ' ', '1', '3'] [' ', ' ', '1', '4'] [' ', ' ', '1', '5'] [' ', ' ', '1', '6'] [' ', ' ', '1', '7'] [' ', ' ', '1', '8'] [' ', ' ', '1', '9'] [' ', ' ', '2', '0'] [' ', ' ', '2', '1'] [' ', ' ', '2', '2'] [' ', ' ', '2', '3'] [' ', ' ', '2', '4'] 100 1 3 1 4 9 9 0 9 9 1 9 9 2 9 9 3 9 9 4 9 9 5 9 9 6 9 9 7 9 9 8 9 9 9 I suspect you could get better performance if you made LotzeFile instances able to return interators over buffer chunks and get characters from them, which would be string iterators supplying the characters rather than the custom .next, but the buffer chunks would have to be of some size to make that pay. Testing is the only way to find out what the crossing point is, if you really have to. Regards, Bengt Richter From jbellis at gmail.com Sat Jul 9 13:34:05 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 9 Jul 2005 10:34:05 -0700 Subject: calling python procedures from tcl using tclpython References: <1120740561.933409.221770@g14g2000cwa.googlegroups.com> <42CD292C.1010204@uni-oldenburg.de> <1120795908.918051.129670@g43g2000cwa.googlegroups.com> <42CF12BE.7040803@removethis.activestate.com> Message-ID: <1120930444.971061.302780@g47g2000cwa.googlegroups.com> Jeff Hobbs wrote: > chand wrote: > > can anyone help me how to provide the info about the python file > > procedure in the tcl script which uses tclpython i.e., is there a way > > to import that .py file procedure in the tcl script > > >>>currently I have wriiten this tcl code which is not working > >>> > >>>package require tclpython > >>>set interpreter [python::interp new] > >>>$interpreter eval {def test_function(): arg1,arg2} ; > >>>python::interp delete $interpreter > > You would call 'import' in the python interpreter, like so: > $interpreter eval { import testfile } > assuming it's on the module search path. Look in the python > docs about Modules to get all the info you need. Actually, both your import and the original "def" problem need to use exec instead of eval. Eval works with expressions; for statements you need exec. I blogged a brief example of tclpython over here: http://spyced.blogspot.com/2005/06/tale-of-wiki-diff-implementation.html -Jonathan From farcepest at gmail.com Tue Jul 19 16:06:57 2005 From: farcepest at gmail.com (Andy Dustman) Date: 19 Jul 2005 13:06:57 -0700 Subject: Cursor navigation References: <42dc3722$0$67264$157c6196@dreader2.cybercity.dk> Message-ID: <1121803616.965169.266920@g49g2000cwa.googlegroups.com> TA wrote: > Hi, > > This might be a silly question, but I was wondering how you would navigate > backwards in a PostgreSQL cursor when the Python DB-API 2.0 allows records > to be fetched in a forward-only manner? This is untrue: cursor.scroll() is an optional DB-API 2.0 extension. http://www.python.org/peps/pep-0249.html MySQLdb supports this, but I do not know about your case. From jason at tishler.net Mon Jul 25 12:55:30 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 25 Jul 2005 12:55:30 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E4E14B.2030905@llnl.gov> References: <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> <42E4E14B.2030905@llnl.gov> Message-ID: <20050725165530.GB2672@tishler.net> Dean, On Mon, Jul 25, 2005 at 05:55:39AM -0700, Dean N. Williams wrote: > >>Is there anyway for me to get back to an older version of Cygwin? > > > >What do you mean by the above? An older Cygwin? An older Cygwin > >Python? An older rebase? See below... > [snip] > > When installing from the internet, there is no way to specify which > version (or date) of Cygwin to download. I was wondering if you kept > version controls, so I could go back to the February version of Cygwin > since I know the Python Socket Module works. No, but see the Cygwin Time Machine: ftp://www.fruitbat.org/pub/cygwin/circa/2005/02/ > >>In my Python2.4 log file, I tracked it down to the file > >>Python2.4/Modules/socketmodule.c file: 3350 INET_ADDSTRLEN, which > >>says "INET_ADDSTRLEN" is undeclared. I know this has something to do > >>with the _ssl extension. > > > >Is the above from building Python or CDAT? > > > The above is building Python. Why are you trying to build Cygwin Python? Why can't you use the pre-built version? Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From python-url at phaseit.net Wed Jul 20 17:08:02 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 20 Jul 2005 21:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 20) Message-ID: QOTW: "Discussing goto statements and Microsoft together is like mixing dynamite and gasoline." - DH '"Spaghetti" doesn't quite describe it. I've settled on "Lovecraftian": reading the code, you can't help but get the impression of writhing tentacles and impossible angles.' - Robert Kern Highlight of the week; Jython 2.2a1: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9c3b6b2e10d8a490 Nearly-highlight of the week; Simon Willison introduces Django, the web framework for perfectionists with deadlines: http://simon.incutio.com/archive/2005/07/17/django But Jeff Shell remains more impressed with Subway: http://griddlenoise.blogspot.com/2005/07/python-off-rails.html CherryPy-2.1.0-beta released: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/18f2e97ab515891 With all this web framework activity, what are people using? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/63bdf6b93e1704d3 Bob Ippolito wonders; what happened to YAML? http://bob.pythonmac.org/archives/2005/07/19/what-happened-to-yaml/ MKoool (!) is looking for the simplest way of stripping non-printable characters from text: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/23d6fdc3c9148725 Discovering WSGI and XSLT as middleware http://www.decafbad.com/blog/2005/07/18/discovering_wsgi_and_xslt_as_middleware Is there any worthwhile Python certification available? Is there any worthwhile certification at all? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/49dc79507ca4567d Microsoft's very own Python scripts: http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx Another notable release; python-dateutil 1.0: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7d0f044f1a3c8959 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From enderlocke.dallin at gmail.com Sat Jul 23 12:20:01 2005 From: enderlocke.dallin at gmail.com (EnderLocke) Date: 23 Jul 2005 09:20:01 -0700 Subject: Friend wants to learn python Message-ID: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> I have a friend who wants to learn python programming. I learned off the internet and have never used a book to learn it. What books do you recommend? Any suggestions would be appreciated. From jepler at unpythonic.net Fri Jul 22 15:50:41 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 22 Jul 2005 14:50:41 -0500 Subject: Getting TypeError in Changing file permissions In-Reply-To: <20050722194044.99411.qmail@web32414.mail.mud.yahoo.com> References: <20050722194044.99411.qmail@web32414.mail.mud.yahoo.com> Message-ID: <20050722195041.GE25836@unpythonic.net> If you are using Unix, and all you have is the file object, you can use os.fchmod(outfile.fileno(), 0700) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVEMEcyber.com.au Thu Jul 21 21:25:41 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 22 Jul 2005 11:25:41 +1000 Subject: Apology [was: is this pythonic] Message-ID: <42E04B15.1040704@REMOVEMEcyber.com.au> It has been suggested to me off-list that my response(s) to Bill Mill in the "is this pythonic" thread were rude and hostile. If that is what people saw in my posts, then I apologise, because that wasn't my intention. In fact, my comments weren't especially even aimed at Bill -- they were intended as more general comments about finding a balance between dismissing questions by pointing to the Python references, and guiding the questioner to learn the skills to be able to use the references effectively. I know I'm not yet at that stage: I still hit road-blocks in knowing where to look at times, and I guess that made me over-sensitive. In hindsight, it would have been better for me to have cut Bill's comments from my reply, and just make allusions to a nebulous "they" who sometimes have a tendency towards using "RTFM" as an answer to anything, because Bill's specific was less dismissive and more supportive than what you can get on many newsgroups. I agree with his basic sentiments, although I might not have worded it in precisely the same way. (Given how I put my foot in it when I did reply, perhaps that's not a bad thing.) My apologies to Bill specifically, and [shameless brown-nosing here] thank you to the comp.lang.python community, which as a whole is far more tolerent than many other forums I've been on. -- Steven. From travislspencer at gmail.com Wed Jul 20 18:10:49 2005 From: travislspencer at gmail.com (travislspencer at gmail.com) Date: 20 Jul 2005 15:10:49 -0700 Subject: Filling up commands.getstatusoutput's buffer Message-ID: <1121897448.949323.8020@g43g2000cwa.googlegroups.com> Hey, Has anyone ever had commands.getstatusoutput's buffer fill up when executing a verbose command? If so, what workaround did you use? Did you just pipe the output into a file and then read it in or fork a processes or something else? -- Regards, Travis Spencer From peter at engcorp.com Sat Jul 9 17:42:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Jul 2005 17:42:28 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: Thomas Lotze wrote: > Steve Juranich wrote: >>What do I mean by "cheaper"? I'm basically talking about the number of >>instructions that are necessary to set up and execute a try block as >>opposed to an if block. > > I don't know about the implementation of exceptions but I suspect most > of what try does doesn't happen at run-time at all, and things get > checked and looked for only if an exception did occur. An I suspect that > it's machine code that does that checking and looking, not byte code. > (Please correct me if I'm wrong, anyone with more insight.) Part right, part confusing. Definitely "try" is something that happens at run-time, not compile time, at least in the sense of the execution of the corresponding byte code. At compile time nothing much happens except a determination of where to jump if an exception is actually raised in the try block. Try corresponds to a single bytecode SETUP_EXCEPT, so from the point of view of Python code it is extremely fast, especially compared to something like a function call (which some if-tests would do). (There are also corresponding POP_BLOCK and JUMP_FORWARD instructions at the end of the try block, and they're even faster, though the corresponding if-test version would similarly have a jump of some kind involved.) Exceptions in Python are checked for all the time, so there's little you can do to avoid part of the cost of that. There is a small additional cost (in the C code) when the exceptional condition is actually present, of course, with some resulting work to create the Exception object and raise it. Some analysis of this can be done trivially by anyone with a working interpreter, using the "dis" module. def f(): try: func() except: print 'ni!' import dis dis.dis(f) Each line of the output represents a single bytecode instruction plus operands, similar to an assembly code disassembly. To go further, get the Python source and skim through the ceval.c module, or do that via CVS http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Python/ceval.c?rev=2.424&view=auto , looking for the string "main loop". And, in any case, remember that readability is almost always more important than optimization, and you should consider first whether one or the other approach is clearly more expressive (for future programmers, including yourself) in the specific case involved. -Peter From skip at pobox.com Fri Jul 1 09:43:17 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Jul 2005 08:43:17 -0500 Subject: No subject In-Reply-To: References: Message-ID: <17093.18549.562510.978056@montanaro.dyndns.org> Adriaan> I'm not a very experienced Python programmer yet, so I might be Adriaan> mistaken, but there are a few things that would make me prefer Adriaan> C++ over Python for large (over 500.000 LOC) projects. Adriaan> - namespaces Python's go packages, modules, classes. Plenty of ways to isolate objects to different namespaces. Adriaan> - templates Not really needed. Adriaan> - strong type checking Python has strong type checking, it's just dynamic. Writing proper test cases (which you should be doing anyway) will catch most issues. Adriaan> - data hiding Walls are no substitute for intelligence. Adriaan> - more available libraries and more advanced developement tools. C++ has had a lot longer history of being a mainstream language and has had the resources of quite a few major corporations behind it, so I would be surprised if there weren't more libraries and advanced development tools available. I suspect the complexity of C++ sort of demands more sophisticated tools. Skip From sjmachin at lexicon.net Thu Jul 7 05:52:21 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 07 Jul 2005 19:52:21 +1000 Subject: Create datetime instance using a tuple. In-Reply-To: <2fdabf19.0507070123.76f2e6c2@posting.google.com> References: <2fdabf19.0507060101.6184974e@posting.google.com> <2fdabf19.0507070123.76f2e6c2@posting.google.com> Message-ID: <42ccfb51$1@news.eftel.com> Negroup wrote: >>Use: >>dt =3D datetime(*t) >> > > > Thanks for the quick reply. > I can't find any doc about '*' used in this context. Have you some url > or suggestion for which terms search in Google? http://www.python.org/doc/2.4.1/tut/tut.html Then read this section 4.7.4 Unpacking Argument Lists Then read all the other sections :-) From rrr at ronadam.com Thu Jul 7 23:45:17 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 08 Jul 2005 03:45:17 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <6oadncSMIs0fclDfRVn-jg@speakeasy.net> References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <3j40aoFocvh4U1@individual.net> <6oadncSMIs0fclDfRVn-jg@speakeasy.net> Message-ID: Erik Max Francis wrote: > Ron Adam wrote: > >> It's not an empty tuple, it's an empty parenthesis. Using tuples it >> would be. >> >> (a,) == (,) >> >> which would be the same as: >> >> (,) == (,) > > > >>> () > () > >>> a = () > >>> type(a) > > >>> (,) > File "", line 1 > (,) > ^ > SyntaxError: invalid syntax > > You've wandered way off into the woods now. Yes, ummm seems soo... err. This is one of those Python isn't quite consistent for practical reasons area. I don't create empty tuples that way very often, but [] is to () is to {} is pretty obvious so I don't really have a good excuse. >>> (1) 1 >>> () () >>> (((((1))))) 1 >>> ((())) () Well in my previous explanation I *mean* it to be empty parenthesis. Does that help? Cheers, Ron From sp1d3rx at gmail.com Mon Jul 18 19:01:12 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 18 Jul 2005 16:01:12 -0700 Subject: Windows command line problem In-Reply-To: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> Message-ID: <1121726398.861595.31350@g43g2000cwa.googlegroups.com> does it matter? Have it key off both "\x96" and "-". From gsakkis at rutgers.edu Sun Jul 3 11:25:49 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 08:25:49 -0700 Subject: How to get 4 numbers from the user in one line for easycomparision? References: Message-ID: <1120404349.608392.134700@g14g2000cwa.googlegroups.com> "Alan G" wrote: > > I .... Just need to figure out how to get 4 numbers from > > the player on one line for easy comparison, > > Unless there is a set of batteries somewhere that I don't know > about I think you have to rely on reading the line as a string > and then splitting it. > > line = raw_input('Type 4 numbers separated by spaces: ') > numbers = [int(n) for n in line.split(' ')] Or if you want to assign these 4 numbers to separate variables, you can use tuple unpacking: a,b,c,d = map(int, raw_input('Type 4 numbers separated ' 'by spaces:').split()) If you want to do error handling later, you may need to split this line into two steps so that you can distinguish between invalid values and wrong count of values (less or more than 4). George From peter at engcorp.com Fri Jul 22 14:24:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 14:24:33 -0400 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Duncan Booth wrote: > BTW, does it matter at all in practical use that the base class of path > varies between str and unicode depending on the platform? I haven't seen any problem. I confess I can't even imagine exactly what the problem might be, since they're both subclasses of basestring, aren't they? And current code should have exactly the same issues when using str or unicode in all the calls that path() merely wraps. So does it matter in practical use when one faces this issue and is *not* using "path"? -Peter From bogus@does.not.exist.com Fri Jul 1 10:25:02 2005 From: bogus@does.not.exist.com () Date: Fri, 01 Jul 2005 14:25:02 -0000 Subject: No subject Message-ID: #! rnews 1689 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Python for everything? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 29 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1120164834.057669.297840 at f14g2000cwb.googlegroups.com> Mime-Version: 1.0 Date: Fri, 1 Jul 2005 14:10:56 GMT Xref: news.xs4all.nl comp.lang.python:384366 Tom Anderson writes: > On Thu, 30 Jun 2005 xeys_00 at yahoo.com wrote: > > > can Python "do it all"? > [snip] > The other is in bit-twiddling - anything that involves > mucking about with data at the level of bits and bytes. Maybe this is > just blind prejudice, but i'm never as comfortable hacking on that > sort of stuff (writing a Huffman coder, say) in python as in java. Maybe we should distinguish: 1. Can you do it at all? Yes, via the struct package and via the bit operators. And, the bit operators support the same idioms we all know and love from C. 2. Can it be done "fast enough"? Maybe. I wrote a Morse code generator based on algorithms from a C program, which generated pcm files. The initial cut was way too slow. Then I did some caching and got it fast enough to use. Still not C speeds, but fast enough for the task. But if you are doing encryptions (where even C is giving way to hardware), then Python is not the answer. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From grante at visi.com Fri Jul 8 12:08:57 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Jul 2005 16:08:57 -0000 Subject: socket code References: Message-ID: <11ct98p5n9cos22@corp.supernews.com> On 2005-07-08, wrote: > Hello, > > I'm trying to create a broadcast socket in some portable code (windows XP & mandrake linux). When I run the following lines through idle: > > import socket > s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) > s.connect( ('', 17100) ) > > On windows, connect() returns and I have a broadcast socket to > which I can write. One LINUX connect() just tells me > 'Permission denied'. > > Does anybody know why? Any thoughts on how I can get around > this? I have to transmitt data to an old system. The system > only reads broadcast data on port 17100. Didn't we just answer this question for you two weeks ago? http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/6447ef29cf613660/dcdc52690aa562e1 -- Grant Edwards grante Yow! I'm RELIGIOUS!! I at love a man with a visi.com HAIRPIECE!! Equip me with MISSILES!! From bdesth.quelquechose at free.quelquepart.fr Wed Jul 6 17:08:07 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 06 Jul 2005 23:08:07 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <42cc41c5$0$23671$636a15ce@news.free.fr> Tom Anderson a ?crit : > Comrades, > > During our current discussion of the fate of functional constructs in > python, someone brought up Guido's bull on the matter: > > http://www.artima.com/weblogs/viewpost.jsp?thread=98196 > > He says he's going to dispose of map, filter, reduce and lambda. He's > going to give us product, any and all, though, which is nice of him. > > What really struck me, though, is the last line of the abstract: > > "I expect tons of disagreement in the feedback, all from > ex-Lisp-or-Scheme folks. :-)" > > I disagree strongly with Guido's proposals, and i am not an ex-Lisp, > -Scheme or -any-other-functional-language programmer; my only other real > language is Java. I wonder if i'm an outlier. > > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? > I discovered FP with David Mertz's papers about FP in Python. I had never read nor write a line of lisp, scheme, haskell, caml etc before. And I'd certainly start thinking of choosing another MYFL if anonymous functions where to disappear from Python. Note that I said "anonymous functions", not "lambda". Concerning map, filter, reduce etc, these functions can live in a separate module, and this wouldn't bother me. But anonymous functions are part of the language syntax, so there is no work-around. My 2 (euro) cents From michael at stroeder.com Mon Jul 25 05:55:54 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 25 Jul 2005 11:55:54 +0200 Subject: What license to choose for Python programs? (PSF License vs. GPL/LGPL) In-Reply-To: References: Message-ID: Volker Grabsch wrote: > > I noticed that many packages in the PyPI are using the PSF License. > Does this have a special reason? Personally I used Python style license to express that you can do with some of my modules exactly what you can do with Python itself. > So if it is complicated to include an LGPL'ed Python library in the > Python standard libraries, I'd release it under PSF License. Unfortunately the Python style license is not suitable to reach that goal. Recommended reading: http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq > Also, a quick overview about the various licenses would be nice. Maybe biased: http://www.gnu.org/licenses/license-list.html Ciao, Michael. From python-url at phaseit.net Wed Jul 20 16:28:21 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 20 Jul 2005 20:28:21 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 20) Message-ID: QOTW: "Discussing goto statements and Microsoft together is like mixing dynamite and gasoline." - DH '"Spaghetti" doesn't quite describe it. I've settled on "Lovecraftian": reading the code, you can't help but get the impression of writhing tentacles and impossible angles.' - Robert Kern Highlight of the week; Jython 2.2a1: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9c3b6b2e10d8a490 Nearly-highlight of the week; Simon Willison introduces Django, the web framework for perfectionists with deadlines: http://simon.incutio.com/archive/2005/07/17/django But Jeff Shell remains more impressed with Subway: http://griddlenoise.blogspot.com/2005/07/python-off-rails.html CherryPy-2.1.0-beta released: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/18f2e97ab515891 With all this web framework activity, what are people using? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/63bdf6b93e1704d3 Bob Ippolito wonders; what happened to YAML? http://bob.pythonmac.org/archives/2005/07/19/what-happened-to-yaml/ MKoool (!) is looking for the simplest way of stripping non-printable characters from text: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/23d6fdc3c9148725 Discovering WSGI and XSLT as middleware http://www.decafbad.com/blog/2005/07/18/discovering_wsgi_and_xslt_as_middleware Is there any worthwhile Python certification available? Is there any worthwhile certification at all? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/49dc79507ca4567d Microsoft's very own Python scripts: http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx Another notable release; python-dateutil 1.0: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7d0f044f1a3c8959 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From pinard at iro.umontreal.ca Fri Jul 8 08:07:17 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 8 Jul 2005 08:07:17 -0400 Subject: f*cking re module In-Reply-To: <86oe9dvs6d.fsf@bhuda.mired.org> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> <86oe9dvs6d.fsf@bhuda.mired.org> Message-ID: <20050708120717.GA7808@phenix.progiciels-bpi.ca> [Mike Meyer] > Steven D'Aprano writes: > > > Is there any possible sequence of bytes that will not be a valid > > Perl expression or operator? Perl has lots of syntax, and good warning facilities, it is not so bad. > [...] TECO, where guessing what your name did as a command sequence > was a popular past time? Yes, this is much more likely to be meaningful! Yet, don't laugh at this venerable editor. Remember that Emacs started as an *E*xtended set of TECO *mac*ros, as its name still say. :-) I once worked with a PL/I compiler (on a big IBM mainframe), which was trying to be helpful by spitting pages of: Error SUCH AND SUCH, assuming that THIS AND THIS was meant. and continuing compilation nevertheless. It was a common joke to say that PL/I would compile some random valid program out of any garbage! -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From dbickett at gmail.com Sun Jul 10 00:38:03 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 10 Jul 2005 04:38:03 +0000 Subject: Yet Another Python Web Programming Question In-Reply-To: <1120959373.895552.161480@f14g2000cwb.googlegroups.com> References: <1120959373.895552.161480@f14g2000cwb.googlegroups.com> Message-ID: <1d6cdae305070921387b177f09@mail.gmail.com> I neglected to mention an important fact, and that is the fact that I am limited to Apache, which elminates several suggestions (that are appreciated none-the-less). -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From jlconlin at lanl.gov Wed Jul 6 15:52:16 2005 From: jlconlin at lanl.gov (Jeremy) Date: Wed, 06 Jul 2005 13:52:16 -0600 Subject: inheriting file object In-Reply-To: References: <42CC13F2.4050808@bellsouth.net> Message-ID: harold fellermann wrote: >>I don't know if I should be inheriting file or just using a file >>object. >> How would I determine which one would be more appropriate? > > > Inheritance is often refered to as an IS relation, whereas using an > attribute > is a HAS relation. > > If you inherit from file, all operations for files should be valif for > your > class also. Usually the file-operations would be directly inherited and > not > overwritten. > > However, if you don't want to expose all file functionalities, a HAS > relation > is more appropriate. if you plan to use your class as a file handle, > e.g. for > formatting output in a special way, I woould prefer to make the file an > attribute: > If you would tell as your use case, it would be easier to give you an > advice. That is an excellent explanation and the example is similar to what I want to do. I have a file I want to look through and change if needed. I think I will follow you suggestion and not inherit from the file object. Thanks, Jeremy From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 23 05:35:50 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 23 Jul 2005 11:35:50 +0200 Subject: [path-PEP] Path inherits from basestring again Message-ID: <3kehbmFtv6lpU1@individual.net> Hi, the arguments in the previous thread were convincing enough, so I made the Path class inherit from str/unicode again. It still can be found in CVS: /python/nondist/sandbox/path/{path.py,test_path.py} One thing is still different, though: a Path instance won't compare to a regular string. Other minor differences, as requested on python-dev, are: * size property -> getsize() method. * atime/mtime/ctime properties -> atime()/mtime()/ctime() methods * dirname() method -> directory property * no parent property * basename() method -> basename property * no name property * listdir() method -> children() method * there is still a listdir() method, but with the semantics of os.listdir * dirs() method -> subdirs() method * joinpath() method -> added alias joinwith() * splitall() method -> parts() method * Default constructor: Path() == Path(os.curdir) * staticmethod Path.getcwd() -> Path.cwd() * bytes() / lines() / text() -> read_file_{bytes,lines,text} methods * write_{bytes,lines,text} -> write_file_{bytes,lines,text} methods These may be removed though. Reinhold From philippe at philippecmartin.com Tue Jul 5 22:19:09 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 06 Jul 2005 02:19:09 GMT Subject: adding a character to the last string element of a list References: <-rOdncUnLNafg1bfRVn-qw@powergate.ca> Message-ID: Thanks, I though it was a reference (tough to implement I'm sure) Regards, Philippe Peter Hansen wrote: > Philippe C. Martin wrote: >> l = ['ABCDE','FGHI'] > > Okay so far... > >> l[1:] #returns ['FGHI'] > > Which is a _copy_ (via slicing) of part of the list. Another way of > saying this is that it is a _new_ list which has a copy of the > references from the appropriate part of the old list. > > Try "l[1:] is l[1:]" to prove that... > >> l[1:][0] #return 'FGHI' > > Sure does. From the new list. > >> a = l[1:][0] + 'J' #a becomes 'FGHIJ' > > Because you are actually storing a reference to the new list, whose > first element you have modified. > >> l[1:][0] += 'J' #NO ERROR BUT l[1:][0] == 'FGHI' > > You are modifying the first element of the *copy* of the slice of the > list, but you don't ever store a copy of it. When you try to check what > happened with the second part, you are creating yet another copy of part > of the list and sure enough the original has never been changed. > >> What am I missing ? > > That slicing makes copies. If you directly access the element in the > first list (without using a slice) it will work. > > (I think I've got most of the correct...) > > -Peter From inigoserna at terra.es Sun Jul 24 05:59:00 2005 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Sun, 24 Jul 2005 11:59:00 +0200 Subject: ANN: MyNewspaper 1.2 Message-ID: <1122199140.25854.10.camel@inigo.katxi.org> Hi there, I'm really pleased to announce the second public release of MyNewspaper. MyNewspaper v1.2: "faster (25-35%), cleaner (100%), smaller(69%) and even more robust(100%)". If you liked the first version but thought... uhmm it's buggy and slow, then this is your release. In fact first version was a proof of concept to get some attention and feedback. What is MyNewspaper after all? ============================== MyNewspaper is a personal RSS Aggregator and Reader, licensed under GPL. Why? As everybody says, I couldn't find any which fulfills all my requirements. In fact I used liferea and was pretty happy with it, but it eats lot of memory when you have many feeds and the program is running for much time, but the main problem was that it's a desktop program and I couldn't read the feeds from the work. So I started writing my own RSS aggregator and reader. MyNewspaper is written in Python with a bit of javascript and uses sqlite as permanent storage for the articles. From v1.2 up sqlobject is used as an abstraction layer for database access, so it would be very easy to support other database engines. It is installed as a CGI, so in order to use and manage it you need a web browser and a web server. Feeds are updated by a command run by cron or from the WebUI. Changes ======= v1.2: "faster (25-35%), cleaner (100%), smaller(69%) and even more robust(100%)" * a major rewrite and clean up of the whole code * uses sqlobject as database abstraction layer * uses Cheetah Template as html template * generated html is valid now * bugs fixing IMPORTANT NOTE to upgrade from v1.0: * download and install sqlobject and Cheetah Template * copy all the needed files to the directory overwriting old ones * you need to upgrade db: $ cd /path_to/mynewspaper $ ./migrate_db.py Home page and download ====================== Read more and download it from: http://inigo.katxi.org/devel/mynewspaper or http://www.terra.es/personal7/inigoserna/mynewspaper Of course, all comments, suggestions etc. are welcome. And yes, I know code is really awful now, but I wanted to make a public release to get some feedback while improving the code. Best regards, -- I?igo Serna Katxijasotzaileak -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From reinhold-birkenfeld-nospam at wolke7.net Sun Jul 24 08:34:52 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 24 Jul 2005 14:34:52 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> Message-ID: <3khg7cFuh446U1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: > [on comparing Paths and stings] >> Do you have a use case for the comparison? Paths should be compared only >> with other paths. > > I can think of lots, though I don't know that I've used any in my > existing (somewhat limited) code that uses Path, but they all involve > cases where I would expect, if comparisons were disallowed, to just wrap > the string in a Path first, even though to me that seems like it should > be an unnecessary step: > > if mypath.splitpath()[0] == 'c:/temp': > > if 'tests' in mypath.dirs(): > > and lots of other uses which start by treating a Path as a string > first, such as by doing .endswith('_unit.py') endswith is okay, since it is an inherited method from str. > Any of these could be resolved by ensuring both are Paths, but then I'm > not sure there's much justification left for using a baseclass of > basestring in the first place: > > if mypath.splitpath()[0] == Path('c:/temp'): But you must admit that that't the cleaner solution. > if Path('tests') in mypath.dirs(): > > Question: would this latter one actually work? Would this check items > in the list using comparison or identity? Identity would simply be > wrong here. Yes, it works. I didn't do anything to make it work, but Path seems to inherit the immutableness from str. > [on removing properties in favour of methods for volatile data] >> My line of thought is that a path may, but does not need to refer to an >> existing, metadata-readable file. For this, I think a property is not >> proper. > > Fair enough, though in either case an attempt to access that information > leads to the same exception. I can't make a strong argument in favour > of properties (nor against them, really). Okay. >> What about iteration and indexing? Should it support >> "for element in path" or "for char in path" or nothing? > > As John Roth suggests, the former seems a much more useful thing to do. > The latter is probably as rarely needed as it is with regular strings > (which I believe is roughly "never" in Python). > > [on .read_file_bytes() etc] >> I think it is not exactly bad that these names are somehow outstanding, >> as that demonstrates that something complex and special happens. > > Point taken. What about ditching the "file" part, since it is redundant > and obvious that a file is in fact what is being accessed. Thus: > .read_bytes(), .read_text(), .write_lines() etc. Hm. Is it so clear that a it's about a file? A path can point to anything, so I think it's better to clearly state that this is only for a file at the path, if it exists. Reinhold From zathras at thwackety.com Fri Jul 1 15:44:05 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 01 Jul 2005 21:44:05 +0200 Subject: Europython 2005 notes online Message-ID: <42c59d08$0$2056$ed2e19e4@ptn-nntp-reader04.plus.net> Back from Europython 2005 - I'd just like to thank all the organisers of Europython this year - it was probably the best conference I've been to - for developers, by developers. Also, for anyone who wasn't able to attend (come next year!), I've taken the majority of the notes I made in the talks I attended, including all the lightning talks (well, except mine(!)) and placed them up here: * http://cerenity.org/Europython/2005.html Hope someone finds them useful! I'm likely to continue sorting them out a bit further, and may move them, but if I do I'll leave a link behind to the new location. Corrections welcome, and opinions may abound! ObPython (if needed ;) : Notes were taken using a wysiwyg editor of mine written using PyQT :-) Have fun... Michael. -- http://kamaelia.sourceforge.net/ From db3l at fitlinxx.com Wed Jul 6 12:32:03 2005 From: db3l at fitlinxx.com (David Bolen) Date: 06 Jul 2005 12:32:03 -0400 Subject: debugger? References: Message-ID: Qiangning Hong writes: (...) > However, while I use pdb or inserting "print" statement to debug my > apps, sometimes it is a pain. I think I need a good GUI debugger to > help me. The debugger should meet _most_ of the following > requirements: > > 1. can debug wxPython applications (and other GUI lib). > 2. an intuitive way to set/clear/enable/disable breakpoints. > 3. can set conditional breakpoints (i.e. break when some condition satisfied). > 4. variable watch list, namescope watching (local, global) > 5. evaluate expression, change variable values, etc within debugging. > 6. change the running routine, (i.e. go directly to a statement, skip > some statements, etc) > 7. clever way to express objects, not just a string returned by repr() > 8. perform profiling > 9. a clear interface. > 10. cross-platform. > 11. free, or better, open source. Although we typically use unit tests and 'print' debugging, I settled on Wing IDE as having the best debugger for the times when something more was needed. It's not free (pretty reasonable cost for an IDE though), but otherwise I think would meet your other points, except perhaps for profiling. It's easy enough to grab an evaluation version to try out (http://www.wingide.com). For us, a big point was wxPython debugging, and being able to stop at exceptions within wxPython event handlers. Interestingly enough, that's seems to be a tough requirement for many of the existing debuggers because the exceptions occur in code that has been called out to from within a C++ layer, and thus have to be caught before the C++ layer gets a chance to clear the exception. -- David From lordverminard at gmail.com Sat Jul 30 01:20:11 2005 From: lordverminard at gmail.com (mustafa) Date: Sat, 30 Jul 2005 10:20:11 +0500 Subject: HTML Scraping?? Message-ID: anyone know some good reliable html scraping (with python) tutorials. i have looked around and found a few. one uses urllib2 and beautifull soap modules for scraping and parsing http://www.dalkescientific.com/writings/diary/archive/2005/04/21/screen_scraping.html and the other uyses mechanize, clientcookie ,clientform. http://sig.levillage.org/?p=588 which one should i go with. i am looking for and html scraping solution that works with the registrar of a college and return stuff like course dtails. From bgporter at acm.org Wed Jul 13 09:15:32 2005 From: bgporter at acm.org (Brett g Porter) Date: Wed, 13 Jul 2005 09:15:32 -0400 Subject: Defending Python In-Reply-To: References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> <42d17b1f$0$19917$636a15ce@news.free.fr> Message-ID: <42D513F4.70005@acm.org> Jorey Bump wrote: > > Monty Python's Flying Circus used to begin with "It's..." I had read at one > time that "It's" was one of the original names proposed for the > troupe/show, although I can't seem to find verification. "In fact, one of the titles of the show was 'It's', so he must have been in there fairly early on. On a list of titles I've got scribbled in a notebook was 'It's' and just 'It,' so that's probably where he came from." -- Michael Palin (referring to the "It's" man) in _The First 20 Years of Monty Python_ by Kim "Howard" Johnson (St. Martin's Press, 1989), p.20 -- // Today's Oblique Strategy (? Brian Eno/Peter Schmidt): // Change instrument roles // Brett g Porter * BgPorter at acm.org // http://bgporter.inknoise.com/JerseyPorkStore From duncan.booth at invalid.invalid Tue Jul 19 11:50:01 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2005 15:50:01 GMT Subject: print ending with comma References: <1121787376.815068.145060@g49g2000cwa.googlegroups.com> Message-ID: wrote: > I recently ran into the issue with 'print' were, as it says on the web > page called "Python Gotchas" > (http://www.ferg.org/projects/python_gotchas.html): > > The Python Language Reference Manual says, about the print statement, > > A "\n" character is written at the end, unless the print statement ends > with a comma. > > What it doesn't say is that if the print statement does end with a > comma, a trailing space is printed. > -- > But this isn't exactly correct either. If you run this program: > import sys > print '+', > print '-', > sys.stdout.write('=') > print > -- > the output is: > + -= > Note that there is no space after the '-'. (Tested on Win 2000 python > 2.3.4, OS X 10.3.9 python 2.3 & 2.4) > > I know that this is not a massively important issue, but can someone > explain what's going on? > The space isn't appended to the value printed, it is output before the next value is printed. The file object has an attribute softspace (initially 0). If this is 0 then printing a value simply writes the value to the file. If it is 1 then printing a value writes a space followed by the value. After any value which ends with a newline character is printed the softspace attribute is reset to 0 otherwise it is set to 1. Also when a print statement ends without a trailing comma it outputs a newline and resets softspace. Change your print test a little to see this: >>> print "+",;print "-",;sys.stdout.write("=");print "X" + -= X Or try this to suppress unwanted spaces in your output: >>> def nospace(s): sys.stdout.softspace = 0 return s >>> print "a",nospace("b"),"c" ab c From bvande at po-box.mcgill.ca Sat Jul 2 15:22:17 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 15:22:17 -0400 Subject: Bad Math In-Reply-To: References: <42C61223.1040605@po-box.mcgill.ca> <42C67CCA.1040807@po-box.mcgill.ca> Message-ID: <42C6E969.8040406@po-box.mcgill.ca> Patrick Rutkowski said unto the world upon 02/07/2005 09:25: > On 7/2/05, Brian van den Broek wrote: > >>Patrick Rutkowski said unto the world upon 02/07/2005 00:12: >> >>>That's... annoying, to say the least. And my number 4/5 was a rational >>>number too; I can understand how when doing 1/3 things can get funky. >>>Really though... 4/5 = 0.8 right on the nose, whats up? >>> >>>I read that http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate >>>I'd like to find out more, is there anyway for this issue to be >>>circumvented? That "is within a reasonable limit check" seams like way >>>too much just to get a proper result from something simple like 4/5. >>> >>> >> >>Hi Patrick, >> >>my quick piece of code became something I thought might someday be >>useful. So, I expanded it with tests, and sanity checks, etc. It >>doesnt' yet have the full functionality I'd like (see docstrings), but >>I won't get to fixing it anytime real soon. >> >>So, in case you are interested, it is attached. It allows you to >>compute the value of a rational[*] as expressed in any base, 1 < base >>< 37, to arbitrary precision. > I just got up and read your mail. However, I'm going away for the day > so I didn't have time to look over your code. Thanks for the advice > and explanations, they really helped. I understand the problem now... > /me waves fist a base 2 fractions. If your code can fix it, then > that's pretty great! What was that "import decimal" idea you proposed? > Does it contain some functions that can sanely work with floating > points? I'm not a new programmer, but my main arena is the simple side > of Java, so I'm not really too far along yet. > > Hoping Python will be fun, > Patrick Rutkowski > > P.S. I responded to the list this time. Hi all, :-( Patrick had originally posted with the "why is Python getting the math wrong?" floating point issue. I'd responded to him with the FAQ link. He wrote back privately (top of quoting above). I replied privately and explained that the "better" behaviour of 4/5.0 as compared to 1/3.0 is a product of base 10 representation. To substantiate this, I coded up something (incomplete) to represent rationals in arbitrary bases, for base 1< base < 37, and sent it privately. Patrick then replied to the message with that code to the list :-( I'd not intended it to be posted publicly, not out of any code hoarding impulse, but from thinking it isn't good enough to put forth to the world. (I'm only a hobbyist.) But, since the decision to put it out there was taken for me, if anyone read the code, I'd appreciate comments. (The code is in the msg to which this is a reply -- it is long enough I didn't want to post it twice.) Thanks, and best to all, Brian vdB From peter at engcorp.com Fri Jul 22 17:53:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 17:53:22 -0400 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Michael Hoffman wrote: > Peter Hansen wrote: > >> When files are opened through a "path" object -- e.g. >> path('name').open() -- then file.name returns the path object that was >> used to open it. > > Also works if you use file(path('name')) or open(path('name')). Since that's exactly what the path module does, it's not surprising. Practically everything that path does, with a few useful exceptions, is a thin wrapper around the existing calls. path.open, for example is merely this: def open(self, mode='r'): return file(self, mode) -Peter From cam.ac.uk at mh391.invalid Fri Jul 22 15:22:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 20:22:45 +0100 Subject: PEP on path module for standard library In-Reply-To: <42e1245c@nntp0.pdx.net> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <42e1245c@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Duncan Booth wrote: > >> BTW, does it matter at all in practical use that the base class of >> path varies between str and unicode depending on the platform? > > Isn't it even worse than this? > On Win2K & XP, don't the file systems have something to do with the > encoding? So D: (a FAT drive) might naturally be str, while C: > (an NTFS drive) might naturally be unicode. The current path module handles these situations at least as well as the libraries that come with Python do. ;-) -- Michael Hoffman From jan.danielsson at gmail.com Sun Jul 31 06:20:35 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Sun, 31 Jul 2005 12:20:35 +0200 Subject: Escaping certain characters In-Reply-To: <42ec15c0$1@griseus.its.uu.se> References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> Message-ID: <42eca481$1@griseus.its.uu.se> Jan Danielsson wrote: >>In [3]: s.encode('string_escape') >>Out[3]: 'Hello\\nWorld!' >> >>In [4]: Out[3].decode('string_escape') >>Out[4]: 'Hello\nWorld!' >> >>Not *quite* what you asked for, but it ought to be close enough. > > That'll do just fine. Many thanks! Hmm... On second thought, I need to escape more characters. Is there no other way to escape characters in strings? From roccomoretti at hotpop.com Thu Jul 7 10:45:33 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 07 Jul 2005 09:45:33 -0500 Subject: HELP! In-Reply-To: References: Message-ID: Ert Ert wrote: > Please help me i down loaded python nd itplays on MS-DOS mode and not on normal please help Python itself is a command line program. "MS-DOS mode" *is* it's normal mode. As other's have mentioned, there are graphical front ends to Python which you may be more comforatble with. You can either download something extra, or on the standard windows installer there is an Integrated Development Environment (IDE) called Idle. If you go: Start Menu->(All Programs)->Python2.4 one of the icons should be for "IDLE 2.4 (Python GUI)" You may also be interested in the python tutor mailing list. You'll find that info, along with a bunch of other great stuff, on the python website (www.python.org). If I've misunderstood you, you'll have to clarify what you want. From agriff at tin.it Sun Jul 31 12:19:15 2005 From: agriff at tin.it (Andrea Griffini) Date: Sun, 31 Jul 2005 16:19:15 GMT Subject: Wheel-reinvention with Python References: <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <7x3bpve8w5.fsf@ruckus.brouhaha.com> Message-ID: <59tpe1p337c3pbf0ui3neocqi2d5ucgk9t@4ax.com> On Sun, 31 Jul 2005 02:23:39 -0700, Robert Kern wrote: >Like PyGUI, more or less? > >http://www.cosc.canterbury.ac.nz/~greg/python_gui/ We ended up using (py)Qt, and it's a nice library but to my eyes is a lot un-pythonic. In many cases there are convoluted solutions that seem to me good ideas for a C++ library, but that just do not make any sense in Python where the problem they solve simply do not exist. My impression about PyGUI is that it would be (would have been?) a nice plug for a hole in the python offer, unfortunately I also perceive the clear impression the authors don't (didn't?) actually want it to be used in the real world. Andrea From jstroud at mbi.ucla.edu Tue Jul 5 19:24:34 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 5 Jul 2005 16:24:34 -0700 Subject: multiple checkboxes highlighted when one clicked = not good In-Reply-To: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> References: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> Message-ID: <200507051624.34724.jstroud@mbi.ucla.edu> On Tuesday 05 July 2005 04:11 pm, MooMaster wrote: > ?self.InUse =[BooleanVar(), BooleanVar(), BooleanVar(), BooleanVar(), > BooleanVar(), BooleanVar(), BooleanVar()] > ? ? ? ? for i in range(1,11): ? ? ? ? ? ? for t in range(7): ? ? ? ? ? ? ? ? if(t==0): ? ? ? ? ? ? ? ? ? ? Checkbutton(self.frame2, variable = self.InUse[t]).grid(row= i, column = t) should this last line read "self.InUse[i]" ? What I mean to say is that t is always 0 when you assign variable. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From miki.tebeka at zoran.com Fri Jul 8 13:14:13 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Fri, 8 Jul 2005 20:14:13 +0300 Subject: Learning Python - IM Wiki In-Reply-To: References: Message-ID: <20050708171413.GI344@zoran.com> Hello Jorge, > Is there some sort of a Wiki where I could post the code and have > advice on what, how and where to improve? Or should I post the code it > here? You can always get help here, the Python community is *very* helpful. If you prefer a Wiki, try www.wikispaces.org for free Wiki hosting. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From EP at zomething.com Sat Jul 30 03:05:19 2005 From: EP at zomething.com (EP) Date: Fri, 29 Jul 2005 23:05:19 -0800 Subject: Python-cgi or Perl-cgi script doubt In-Reply-To: <20050730045040.33004.qmail@web8404.mail.in.yahoo.com> References: <1122640048.898562.3600@g43g2000cwa.googlegroups.com> <20050730045040.33004.qmail@web8404.mail.in.yahoo.com> Message-ID: <20050729230519.1730464714.EP@zomething.com> Prabahar wrote: > I want to know difference between > Python-cgi and Perl-cgi and also I want > to which one is efficient from the performance. The difference between a cgi program written in Perl and a cgi program written in Python is the choice of programming language. Both work quite well. You probably want to use whichever programming language you like best, and that can only be discovered from writing programs in both. In terms of "efficient" (efficiency) , are you talking about how much memory the program uses, how fast the program executes, or how much time it takes to write and debug the program? There are differences between the two in these regards, but I do not have any reliable information that quantifies those differences, and the differences are likely to vary greatly depending on the nature and length of the program, and how efficiently written the code is. I think, generally, if you really like programming in Perl, there is probably no reason not to use it (at least for typical/short cgi programs) - it has been the default choice for years; conversely, if you really like programming in Python, you will probably be happy to tackle any challenges associated with using it for cgi. Notes: Perl cgi execution is generally offered by all hosts that offer cgi; Python cgi execution is offered by fewer hosts (but some of those hosts are really great). With either language, if execution "performance" is a concern, you may want to use something along the lines of mod_python or mod_perl which embed a persistent interpreter in your web server. This lets you avoid the overhead of starting an external interpreter and avoids the penalty of Perl/Python start-up time, giving faster time to execution. Was this at all the information you were looking for? Why do I think you may have intended a very technical question? If so, you may have to be a little more specific about the sort of differences you are interested in understanding. Eric From fdeserres at gmx.net Wed Jul 13 09:59:40 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 15:59:40 +0200 Subject: Building a function call? (update) In-Reply-To: References: <42D50A88.3070909@gmx.net> Message-ID: <42D51E4C.70905@gmx.net> Duncan Booth wrote: >Francois De Serres wrote: > > > >>Sorry, I was unclear about the fact that the args are formals. I'm >>trying to do something like: >> >>func = "dothat" >>args = ('x','y') >>localcontext = () >>r = None >>while r is None: >> try: >> r = eval("dothat(x,y)", None, localcontext) #how do I construct >>"dothat(x,y)"? with 'dothat(%s,%s)' % args? >> except NameError: >> ensure_context(args) #find/compute the formals, eg: localcontext >>= (('x', 100), ('y', 200)) >> >> > >I think when your code ends up in as big a mess as this, you need to take a >step back. Forget about asking us how you get at functions or arguments as >strings, instead tell us what problem you are really trying to solve. > >I'm pretty sure that whatever your problem is, the solution won't involve >using 'eval', and it almost certainly won't involve looking up variables >or functions from their names. > > Sure? okay, let me take the time to formulate a thorough blueprint of my context, and I'll come back to you... F. From fuzzyman at gmail.com Fri Jul 29 04:12:06 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jul 2005 01:12:06 -0700 Subject: how to append cgi FieldStorage Class instance In-Reply-To: References: <20050727163522.220b01b2.pedro.werneck@terra.com.br> Message-ID: <1122624726.598516.281570@g43g2000cwa.googlegroups.com> praba kar wrote: > Dear All, > I have doubt in python cgi script. I describe > that doubt with below code > import cgi > form = cgi.FieldStorage() > passwd = form['passwd'].value > print passwd > But Now I want to assign some value to form['passwd'] > field value > form['passwd'] = 'surese' > Now If I try to print > print form['passwd'].value. It will raise error. > So kinldy let me how to edit or append instance > of FieldStorage class > A form *isn't* a dictionary, this means that your code : form['passwd'] = 'surese' is wrong. Turn the form into a dictionary and use that. Why are you trying to assign values directly in the form ? Best Regards, Fuzzy http://www.voidspace.org.uk/python > regards > PRabahar > > > > > _______________________________________________________ > Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From ajikoe at gmail.com Tue Jul 12 11:20:02 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 12 Jul 2005 08:20:02 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> Message-ID: <1121181602.408662.210790@g14g2000cwa.googlegroups.com> Hello, First I'm not so clear about your problem, but you can do the following steps: 1. Transform your file into list (list1) 2. Use regex to capture 'robert' in every member of list1 and add to list2 3. Transform your list2 into a file pujo From tim.peters at gmail.com Tue Jul 12 21:15:28 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 12 Jul 2005 21:15:28 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae05071218155d2a0c12@mail.gmail.com> [Michael Hudson] > I doubt anyone else is reading this by now, so I've trimmed quotes > fairly ruthlessly :) Damn -- there goes my best hope at learning how large a message gmail can handle before blowing up . OK, I'll cut even more. [Michael] >>> Can't we use the stuff defined in Appendix F and header of >>> C99 to help here? I know this stuff is somewhat optional, but it's >>> available AFAICT on the platforms I actually use (doesn't mean it >>> works, of course). [Tim] >> It's entirely optional part of C99. > Hmm, is optional? I'm not finding those words. I know > Appendix F is. fenv.h is required, but the standard is carefully worded so that fenv.h may not be of any actual use. For example, a conforming implementation can define FE_ALL_EXCEPT as 0 (meaning it doesn't define _any_ of the (optional!) signal-name macros: FE_DIVBYZERO, etc). That in turn makes feclearexcept() (& so on) pretty much useless -- you couldn't specify any flags. If the implementation chooses to implement the optional Appendix F, then there are stronger requirements on what fenv.h must define. >> Python doesn't require C99. > Sure. But it would be possible to, say, detect C99 floating point > facilities at ./configure time and use them if available. Yes. >> The most important example of a compiler that doesn't support any of >> that stuff is Microsoft's, although they have their own MS-specific >> ways to spell most of it. > OK, *that's* a serious issue. > > If you had to guess, do you think it likely that MS would ship fenv.h > in the next interation of VC++? Sadly not. If they wanted to do that, they had plenty of time to do so before VC 7.1 was released (C99 ain't exactly new anymore). As it says on http://en.wikipedia.org/wiki/C_programming_language MS and Borland (among others) appear to have no interest in C99. In part I expect this is because C doesn't pay their bills nearly so much as C++ does, and C99 isn't a standard from the C++ world. >>> In what way does C99's fenv.h fail? Is it just insufficiently >>> available, or is there some conceptual lack? >> Just that it's not universally supported. Look at fpectlmodule.c for >> a sample of the wildly different ways it _is_ spelled across some >> platforms. > C'mon, fpectlmodule.c is _old_. Maybe I'm stupidly optimistic, but > perhaps in the last near-decade things have got a little better here. Ah, but as I've said before, virtually all C compilers on 754 boxes support _some_ way to get at this stuff. This includes gcc before C99 and fenv.h -- if the platforms represented in fpectlmodule.c were happy to use gcc, they all could have used the older gcc spellings (which are in fpectlmodule.c, BTW, under the __GLIBC__ #ifdef). But they didn't, so they're using "minority" compilers. I used to write compilers for a living, but I don't think this is an inside secret anymore : there are a lot fewer C compiler writers than there used to be, and a lot fewer companies spending a lot less money on developing C compilers than there used to be. As with other parts of C99, I'd be in favor of following its lead, and defining Py_ versions of the relevant macros and functions. People on non-C99 platforms who care enough can ugly-up pyport.h with whatever their platform needs to implement the same functionality, and C99 platforms could make them simple lexical substitutions. For example, that's the path we took for Python's C99-workalike Py_uintptr_t and Py_intptr_t types (although those are much easier to "fake" across non-C99 platforms). >> A maze of #ifdefs could work too, provided we defined a >> PyWhatever_XYZ API to hide platform spelling details. > Hopefully it wouldn't be that bad a maze; frankly GCC & MSVC++ covers > more than all the cases I care about. I'd be happy to settle for just those two at the start, As with threading too, Python has suffered from trying to support dozens of unreasonable platforms, confined to the tiny subset of abilities common to all of them. If, e.g., HP-UX wants a good Python thread or fp story, let HP contribute some work for a change. I think we have enough volunteers to work out good gcc and MSVC stories -- although I expect libm to be an everlasting headache (+ - * are done in HW and most boxes have fully-conforming 754 semantics for them now; but there are no pressures like that working toward uniform libm behaviors; division is still sometimes done in software, but the divide-by-0 is check is already done by Python and is dead easy to do). From klachemin at comcast.net Sat Jul 30 14:08:29 2005 From: klachemin at comcast.net (Kamilche) Date: 30 Jul 2005 11:08:29 -0700 Subject: Printing Docstrings Without Importing Message-ID: <1122746909.441941.226760@o13g2000cwo.googlegroups.com> I have a large project that is getting complex, and I would like to print the docstrings without importing the modules. The only Python utility I could find references is apparently defunct and hasn't been updated in 4 years. I don't care how spartan the output is - it could look exactly like python's internal docstrings, for all I care. It would be a nice added bonus if it printed to HTML, but not if it greatly increased the interface complexity. But I don't want to have to import the module to run it! I want to just have a function that I pass a list of filenames to. Does anyone know of such a utility? From nospam at me.invalid Sun Jul 3 12:35:16 2005 From: nospam at me.invalid (anthonyberet) Date: Sun, 03 Jul 2005 17:35:16 +0100 Subject: How do you program in Python? Message-ID: <3iqif8Fmj34kU1@individual.net> My question isn't as all-encompassing as the subject would suggest... I am almost a Python newbie, but I have discovered that I don't get along with IDLE, as i can't work out how to run and rerun a routine without undue messing about. What I would really like is something like an old-style BASIC interpreter, in which I could list, modify and test-run sections of code, to see the effects of tweaks, without having to save it each time, or re-typing it over and over (I haven't even worked out how to cut and paste effectively in the IDLE environment). I see lots of alternate IDEs etc, but which would allow me the simple interface that I have described? - I really don't know about IDEs in general, and I suspect I would be out of my depth with one of those. Thanks, and feel free to mock ;) From seberino at spawar.navy.mil Tue Jul 5 16:58:25 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 5 Jul 2005 13:58:25 -0700 Subject: Lisp development with macros faster than Python development?.. Message-ID: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> I've been reading the beloved Paul Graham's "Hackers and Painters". He claims he developed a web app at light speed using Lisp and lots of macros. It got me curious if Lisp is inherently faster to develop complex apps in. It would seem if you could create your own language in Lisp using macros that that would be quite an advantage.... I realize that Python has operator overloading and OOP so I'm not sure. Any ideas? Any *evidence* one way or another? thanks! Chris From bdesth.quelquechose at free.quelquepart.fr Wed Jul 20 16:19:06 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 20 Jul 2005 22:19:06 +0200 Subject: Printing a variable's name not its value In-Reply-To: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> References: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> Message-ID: <42deaadb$0$6734$626a14ce@news.free.fr> travislspencer at gmail.com a ?crit : > Hey, > > I am trying to write a function that takes an arbitrary number of > arguments and does one of two things. If the variable is a key in a > dictionary, it prints the key and its value. Otherwise, if any of the > variables isn't in the dictionary, the function prints the variable's > name and value. > > Here is what I have so far: > > globals = {} globals() is a builtin function, you should no shadow it. > HOME_DIR = "The user's home directory" > SHELL = "The user's shell" > > def someFunction(): > someString = "This is a test" > globals[VERBOSE] = True > globals[HOME_DIR] = os.getenv("HOME") > globals[SHELL] = os.getenv("SHELL") > > printVerbose(someString, HOME_DIR, SHELL) -> printVerbose(HOME_DIR, SHELL, someString=someString) > def printVerbose(*args): def printVerbose(*args, **kwargs): > if VERBOSE in globals: > for a in args: > if a in globals: > value = globals[a] for k, v in kwargs: > print "%s: %s" % (k, v) > (snip) > I've been told on #python that there isn't a way to get a variable's > name. I hope this isn't so. It is so. In fact, there is nothing like a 'variable' in Python. What we have are names bound to objects. Names 'knows' what objects are bound to them, but objects knows *nothing* about names they are bound to. From gnb at itga.com.au Wed Jul 6 00:29:18 2005 From: gnb at itga.com.au (Gregory Bond) Date: Wed, 06 Jul 2005 14:29:18 +1000 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? In-Reply-To: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: markturansky at gmail.com wrote: > I'd like to dynamically find and invoke a method in a Python CGI. > boundmeth = obj.meth # nb: no () # stuff..... boundmeth() # call it, with args if needed From vivek7006 at yahoo.com Mon Jul 11 15:53:06 2005 From: vivek7006 at yahoo.com (Vivek Chaudhary) Date: Mon, 11 Jul 2005 19:53:06 -0000 Subject: Environment Variable Message-ID: Is it possible to set an environment variable in python script whose value is retained even after the script exits. Doing the following creates an environment variable "name" which is visible to only subprocesses created by os.system() and os.popen(). os.putvar("name", "vivek") Is it possible to somehow create this environment variable inside python script which will be avaibale even after the script exits. In otherwords, after I run my script, if I do a "echo $name" in my shell, it should return the value "vivek" From fdeserres at gmx.net Wed Jul 13 08:54:13 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 14:54:13 +0200 Subject: Building a function call? In-Reply-To: References: Message-ID: <42D50EF5.4050708@gmx.net> Roland Heiber wrote: >Francois De Serres wrote: > > >>Hiho, >> >>Having a string: "dothat" >>and a tuple: (x, y) >>1. What's the best way to build a function call like: dothat(x,y)? >> >> > >Not the best (not at all) but one way: > > Still pretty interesting, thx. >def dothat(x,y): > print "Called with:", x, y > >c = (1,2) > >locals().get("dothat")(*c) > >---- >Called with: 1 2 > >HtH, Roland > > From jeff.maitland at gmail.com Tue Jul 5 10:57:18 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Tue, 5 Jul 2005 10:57:18 -0400 Subject: threads and sleep? In-Reply-To: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> Message-ID: <6829832e050705075798ca35c@mail.gmail.com> Hello all, First off Thanks for the responses on the sleep() part I suspected as much but I wasn't 100% sure. To continue this I just want to pre thank anyone that contributes to this thread(lol). Ok here goes. The problem I have is I had an application (wrote/co-wrote) that has a long run time dependant on some variables passed to it (mainly accuracy variables, the more accurate the longer the run time - makes sense). However in the hopes to speed it up I decided to write a threaded version of the program to try and speed it up. How ever what I am noticing is that the threaded version is taking as long possibly longer to run. The thing is the threaded version is running on an 8 ia-64 proccessor system and it seems to only be using 2 or 3 porcessors at about 30% (fluxiates). My guess is that 6 threads are running they are using 30% sprox each of a 2 given CPUS. What I would like to do is have say 1 thread use as much of a given CPU as possible and if a new thread is started (added) that if a CPU is available use it instead of using the same cpu. That way it should speed the application up. The standalone (non-threaded) app uses 90+ % of a single cpu when in this part of the algorithm, that is why I split and threaded that part of the algorithm there to try and speed it up because this part is repeated several times. I can post generic code of what I am doing but can't post the actuall code because of the confidentially of it. Thanks again in advance for any and all comments (even any spitefull ones) Jeff From andreas at kostyrka.org Fri Jul 1 12:50:36 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 01 Jul 2005 18:50:36 +0200 Subject: No subject In-Reply-To: <1120231547.928636.59270@g43g2000cwa.googlegroups.com> References: <1120231547.928636.59270@g43g2000cwa.googlegroups.com> Message-ID: <1120236637.6823.48.camel@andi-lap> Am Freitag, den 01.07.2005, 08:25 -0700 schrieb George Sakkis: > > > > Again, how? Is there a way to force that an external user of my lib can > > not use my internal data/methods/classes, unless he uses odd compiler > > hacks? > Well, one could probably argue it the other way. In Python you can at least prevent Python code to access internals of a C-language module. In C/C++, anything is just one cast away :) > so. I never understood how mainstream OO languages expect the designer > of a class to know in advance that an attribute should be hidden or > unnecessary to its subclasses by being declared "private" instead of > "protected". The distinction between public and non-public (private + > protected) is more understandable, but again python's philosophy is > "we're all consenting adults here". _single_underscored names just > flash a "use at your own risk" signal, instead of tying your hands in > case the original class designer made a wrong assumption. The problem is, that the classic private/protected/public visibility tags try to solve multiple problems. Private: Ok, that's all that's really only for the implementation. public: Well, that's all for my "customers". Hmm. What if I've got two kinds of customers? Say a customer like in bank customer, and second customer that plays the role of the bank employee? oops. One can try to give a certain kind of customer more access by using protected, but that forces the developer to subclass. So basically the data hiding as C++ and Java provide are sensible only in a limited way. It does little beyond disallowing direct member variable access. Nothing that couldn't be provided in Python with some stack hacking and a metaclass. It just happens that by the time on knows enough Python to be able to implement this kind of stuff, the motivation to do this kind of stupid tricks is usually gone. Python provides much stronger "data hiding and modelling" support via properties and the __getattr__ (and friends) special methods. So yeah, even if takes some violence to explain it to C++/Java developers, good python code doesn't have getters and setters ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From rkern at ucsd.edu Sat Jul 23 10:43:00 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 23 Jul 2005 07:43:00 -0700 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> Message-ID: Peter Hansen wrote: > Under Linux isn't it possible to open and read from directories much as > with files? Not really, no. Python 2.3.4 (#2, Jan 5 2005, 08:24:51) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d = open('/usr/bin') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 21] Is a directory >>> -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From me at privacy.net Thu Jul 14 04:28:36 2005 From: me at privacy.net (Simon Morgan) Date: Thu, 14 Jul 2005 08:28:36 GMT Subject: constructor list slice confusion References: Message-ID: On Thu, 14 Jul 2005 08:38:36 +0200, Peter Otten wrote: > Maybe, after a little renaming you can see it yourself: > > class SomeClass: > def __init__(self, default_contents=[]): > # make a copy of default_contents that is # kept in a SomeClass > instance > self.contents = default_contents[:] > def add(self, element): > # modify the *copy* of default_contents... > self.contents.append(element) Aha, I think I get it now. default_contents will always be an empty list because before anything is added to it, a copy is made. I think I was focusing too hard on the constructor. :) Thanks for your help. From Soeren.Sonnenburg at first.fraunhofer.de Sun Jul 24 10:31:23 2005 From: Soeren.Sonnenburg at first.fraunhofer.de (Soeren Sonnenburg) Date: Sun, 24 Jul 2005 16:31:23 +0200 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: <1122136203.26083.103.camel@localhost> Message-ID: <1122215484.30698.48.camel@localhost> On Sat, 2005-07-23 at 12:15 -0700, Robert Kern wrote: > Soeren Sonnenburg wrote: > > Hi all, > > > > Just having started with python, I feel that simple array operations '*' > > and '+' don't do multiplication/addition but instead extend/join an > > array: > > > > a=[1,2,3] > > This isn't an array. It is a list. If you want an array, use > Numeric/numarray. If you want lists, use lists. Lists will never grow > the kind of behavior you're asking for. Sorry, but I still don't understand the reasons for that. Lists are infect arrays so why does it make sense to have another *array ? All that is missing is ufuncs and 'fixing' (as I see it) '+','*' ? Soeren -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From devlai at gmail.com Mon Jul 25 00:14:33 2005 From: devlai at gmail.com (Devan L) Date: 24 Jul 2005 21:14:33 -0700 Subject: Problem loading a file of words In-Reply-To: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> Message-ID: <1122264873.347064.195990@f14g2000cwb.googlegroups.com> teoryn wrote: > I've been spending today learning python and as an exercise I've ported > a program I wrote in java that unscrambles a word. Before describing > the problem, here's the code: > > *--beginning of file--* > #!/usr/bin/python > # Filename: unscram.py > > def sort_string(word): > '''Returns word in lowercase sorted alphabetically''' > word = str.lower(word) > word_list = [] > for char in word: > word_list.append(char) > word_list.sort() > sorted_word = '' > for char in word_list: > sorted_word += char > return sorted_word > > print 'Building dictionary...', > > dictionary = { } > > # Notice that you need to have a file named 'dictionary.txt' > # in the same directory as this file. The format is to have > # one word per line, such as the following (of course without > # the # marks): > > #test > #hello > #quit > #night > #pear > #pare > > f = file('dictionary.txt') > > # This loop builds the dictionary, where the key is > # the string after calling sort_string(), and the value > # is the list of all 'regular' words (from the dictionary, > # not sorted) that passing to sort_string() returns the key > > while True: > line = f.readline() > if len(line) == 0: > break > line = str.lower(line[:-1]) # convert to lowercase just in case > and > # remove the return at the end of > the line > sline = sort_string(line) > if sline in dictionary: # this key already exist, add to > existing list > dictionary[sline].append(line) > print 'Added %s to key %s' % (line,sline) #for testing > else: # create new key and list > dictionary[sline] = [line] > print 'Created key %s for %s' % (sline,line) #for > testing > f.close() > > print 'Ready!' > > # This loop lets the user input a scrambled word, look for it in > # dictionary, and print all matching unscrambled words. > # If the user types 'quit' then the program ends. > while True: > lookup = raw_input('Enter a scrambled word : ') > > results = dictionary[sort_string(lookup)] > > for x in results: > print x, > > print > > if lookup == 'quit': > break > *--end of file--* > > > If you create dictionary.txt as suggested in the comments, it should > work fine (assumeing you pass a word that creates a valid key, I'll > have to add exceptions later). The problem is when using a large > dictionary.txt file (2.9 MB is the size of the dictionary I tested) it > always gives an error, specifically: > (Note: ccehimnostyz is for zymotechnics, which is in the large > dictionary) > > > *--beginning of example--* > Enter a scrambled word : ccehimnostyz > Traceback (most recent call last): > File "unscram.py", line 62, in ? > results = dictionary[sort_string(lookup)] > KeyError: 'ccehimnostyz' > *--end of example--* > > > If you'd like a copy of the dictionary I'm using email me at teoryn at > gmail dot com or leave your email here and I'll send it to you (It's > 702.2 KB compressed) > > Thanks, > Kevin Heh, it reminds me of the code I used to write. def sort_string(word): return ''.join(sorted(list(word.lower()))) f = open('dictionary.txt','r') lines = [line.rstrip('\n') for line in f.readlines()] f.close() dictionary = dict((sort_string(line),line) for line in lines) lookup = '' while lookup != 'quit': lookup = raw_input('Enter a scrambled word:') if dictionary.has_key(lookup): word = dictionary[lookup] else: word = 'Not found.' print word You need python 2.4 to use this example. From ric at next-level.com.au Mon Jul 11 22:24:04 2005 From: ric at next-level.com.au (Ric Da Force) Date: Tue, 12 Jul 2005 10:24:04 +0800 Subject: Tricky Dictionary Question from newbie References: <3jftckFpvhv2U2@individual.net> Message-ID: How does setdefault work exactly? I am looking in the docs and can't figure it out... Ric "Ric Da Force" wrote in message news:dav1ui$nn2$1 at nnrp.waia.asn.au... > Thank you guys! (Reinhold, Mark and Markus) I must confess that I am > absolutely awe struck at the power of this language! There is no way in > the world that I would have envisaged such simple and elegant solutions!!! > > Reinhold, is your solution specific to 2.4? > > Kind Regards, > > Ric > > "Reinhold Birkenfeld" wrote in > message news:3jftckFpvhv2U2 at individual.net... >> Mark Jackson wrote: >>> "Ric Da Force" writes: >>> >>>> It is hard to explain but this is what I mean: >>>> >>>> Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This >>>> is >>>> not'} >>>> >>>> I want this to return a new dict with string keys and lists containing >>>> the >>>> previous keys for repeated values. >>>> >>>> NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} >>> >>> NewDict = {} >>> for x in Dict.keys(): >>> try: >>> NewDict[Dict[x]].append(x) >>> except KeyError: >>> NewDict[Dict[x]] = [x] >> >> Or, more up-to-date: >> >> NewDict = {} >> for key, val in Dict.iteritems(): >> NewDict.setdefault(val, []).append(key) >> >> Reinhold > > From c at cdot.de Sat Jul 30 16:03:19 2005 From: c at cdot.de (Chris) Date: Sat, 30 Jul 2005 22:03:19 +0200 Subject: showing help(M) when running module M standalone In-Reply-To: References: Message-ID: hello, thanks for all suggestions, if __name__ == '__main__': __name__ = 'MODULENAME' help(__name__) does actually work any even shows the modulename it should. chris From roy at panix.com Sun Jul 3 18:13:44 2005 From: roy at panix.com (Roy Smith) Date: Sun, 03 Jul 2005 18:13:44 -0400 Subject: looping over a big file References: Message-ID: Jp Calderone wrote: > Yes, but you need to do it like this: > > fileIter = iter(big_file) > for line in fileIter: > line_after = fileIter.next() That's better than the solution I posted. From tjreedy at udel.edu Mon Jul 4 17:48:15 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jul 2005 17:48:15 -0400 Subject: "long int..." exception reported with strange traceback location References: Message-ID: "Michael Hoffman" wrote in message news:dac6v4$5m1$1 at gemini.csx.cam.ac.uk... > I came up with a simpler testcase. Strangely, the exception occurs in > the statement *following* the os.utime() call: > > >>> import os, sys > >>> os.utime("foo_test_file", (0, float(sys.maxint+1))) > >>> print "hi" > OverflowError: long int too large to convert to int > > Looks like a bug. You should report it on the SourceForge tracker. Please include this simpler test, which make clear that bug not just in deprecated (I believe) rfc module. Also note: Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os, sys >>> os.utime("foo_test_file", (0, float(sys.maxint+1))) Traceback (most recent call last): File "", line 1, in ? TypeError: utime() arg 2 must be a tuple (atime, mtime) which is quite sane. So maybe bug was introduced in 2.3 which you were running. From ed at leafe.com Sun Jul 31 20:55:10 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 20:55:10 -0400 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42ED5652.9080909@ulmcnett.com> Message-ID: <200507312055.10189.ed@leafe.com> On Sunday 31 July 2005 19:51, Andr? Roberge wrote: > On a somewhat unrelated note: is there any "overlap"/"possibility of > collaboration" between Dabo-UI and Wax? ?(I have use neither, sticking > to pure wxPython so far.) I've contacted Hans and we've discussed the possibility, but he didn't seem to feel that it would worth it to him. He works on Wax as he needs to, and is kind enough to share his work with the rest of us. It certainly isn't his main focus, though. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From max at alcyone.com Fri Jul 1 16:25:27 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Jul 2005 13:25:27 -0700 Subject: Accepted Summer of Code proposals In-Reply-To: References: Message-ID: <7IWdnYR9K8cqO1jfRVn-3w@speakeasy.net> A.M. Kuchling wrote: > For anyone who's interested: the Python wiki now contains a list of the > PSF-mentored proposals that were accepted for Google's Summer of Code: > http://wiki.python.org/moin/SummerOfCode That's great, it looks like quite a number of useful projects got approved. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Heaven ne'er helps the man who will not act. -- Sophocles From frank at chagford.com Thu Jul 28 04:02:23 2005 From: frank at chagford.com (Frank Millman) Date: 28 Jul 2005 01:02:23 -0700 Subject: Problems with permissions etc In-Reply-To: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: <1122534295.713767.61190@o13g2000cwo.googlegroups.com> Thanks for all the replies. They were useful. I think that my situation was best summed up by Mike - I need to figure out which things I have to do as root and which I have to do as me. I guess this only comes from experience, but it seems a good rule to follow. My reasons for wanting the mac address are nothing to do with security. I have in mind a retail point-of-sale situation, where I want to record which transactions took place at which point-of-sale. I hope that, in this context, my use of the mac address will be safe enough. As for wxPython, it is correctly installed in /usr/local/lib/python2.4/site-packages. However, as part of the build process, wxPython builds its own version of gtk. It does not install it, but stores the generated files in the original build directory, and then hard-codes the path to the shared object files. As the original build directory happened to be under another user's home directory, my user could not read the files. I have deleted wxPython and reinstalled it from another directory which all users can read, and it now works fine. It was this 'other' directory that I was referring to when I asked if there was a 'correct' place, but I guess that anywhere reasonable is fine. Many thanks to all Frank From me at privacy.net Thu Jul 28 19:12:16 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 28 Jul 2005 19:12:16 -0400 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 28 Jul 2005 15:35:54 -0700, Robert Kern wrote: > That said, I made a boo-boo. The Zen of Python is really a set of > design principles (and some of them, like this one, are more > specifically *language* design principles), not Essential Development > Practices. That'll teach me to not RTFA. May I respectfully disagree? The Zen applies to all aspects of software (and other things, too, but they're off topic here), from human readable reports and requirements and documentation, to GUI's, to test cases, to code, to database schemta, as well as the development methodology and practices themselves. Sometimes you have to look at the Zen sideways, so that "implementation" appears to be replaced by the particular aspect or aspects (or the software, or just software, as a whole, for the true Masters out there) you happen to be working on at the time, but such is the nature of Zen. Regards, Dan -- Dan Sommers From googlinggoogler at hotmail.com Wed Jul 27 16:23:07 2005 From: googlinggoogler at hotmail.com (googlinggoogler at hotmail.com) Date: 27 Jul 2005 13:23:07 -0700 Subject: searching string url Message-ID: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> Hiya, Im trying to find a method of searching a html file (ive grabbed it with FancyURLopener), basically in the html file there is a series of links in the following format - A HREF="../../company/11/13/820.htm">some name -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm interested in various metadata extraction/prosessing/distribution/something tools(including ways of differentiating between files, eg hashing etc) and especially python enabled ones. I'm also considering content-recognition/differentiating eg. image recognition. I'm already aware of these: python-bitzi, python-musicbrainz, mmpython, IMDbPY, python-mhash and imgSeek. If you could point me to other relating resources it would be great. Elmo -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFC1Q3WctNFyQJObrsRAjXbAJ92B53YC9NqtC9nymK07OL+L3mNTwCgmlbb dPfSDsqJzBh+xa3h5L28Qac= =AtAo -----END PGP SIGNATURE----- From spam.csubich+block at block.subich.spam.com Fri Jul 22 23:14:42 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Fri, 22 Jul 2005 23:14:42 -0400 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: <1122083350.151604.87980@g44g2000cwa.googlegroups.com> References: <1122083350.151604.87980@g44g2000cwa.googlegroups.com> Message-ID: ncf wrote: > Well, suffice to say, having the class not inherit from object solved > my problem, as I suspect it may solve yours. ;) Actually, I did a bit of experimenting. If the __str__ reassignment worked as intended, it would just cause an infinite recursion. To paste the class definition again: > class MyClass(object): > > def Edit(self): > return "I, %s, am being edited" % (self) > > def View(self): > return "I, %s, am being viewed" % (self) > > def setEdit(self): > self.__str__ = self.__repr__ = self.Edit > > def setView(self): > self.__str__ = self.__repr__ = self.View Notice the % (self) in Edit and View -- those recursively call str(self), which causes infinite recursion. In the spirit of getting the class working, though, the class-method behavior of __str__ for new-style classes can be fixed with an extremely ugly hack: class MyClass(object): def __init__(self): self.__str__ = lambda : object.__str__(self) def Edit(self): return "I, %s, am being edited" def View(self): return "I, %s, am being viewed" def setEdit(self): self.__str__ = self.__repr__ = self.Edit def setView(self): self.__str__ = self.__repr__ = self.View def __str__(self): return self.__str__() (Notice that I've removed the string substitution in Edit and View. This also does not change the __repr__ method; it also acts as a class method. But that's also easy enough to change in the same way.) I also would be interested in knowing why new-style classes treat __str__ as a class method. From me at privacy.net Wed Jul 6 14:00:36 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 06 Jul 2005 14:00:36 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 06 Jul 2005 15:18:31 GMT, Ron Adam wrote: > Dan Sommers wrote: >> On Wed, 06 Jul 2005 14:33:47 GMT, >> Ron Adam wrote: >> >>> Since this is a Python 3k item... What would be the consequence of >>> making None the default value of an undefined name? And then assigning >>> a name to None as a way to delete it? >> [ ... ] >> >>> Any drawbacks? >> Lots more hard-to-find errors from code like this: >> filehandle = open( 'somefile' ) >> do_something_with_an_open_file( file_handle ) >> filehandle.close( ) >> Regards, >> Dan [ ... ] > If "file_handle" (vs "filehandle") is None. Then you will still get an > error as soon as you tried to use the invalid file handle. > AttributeError: 'NoneType' object has no attribute 'read' This is the one of which I was thinking. So you see this error at the end of a (long) traceback, and try to figure out where along the (long) line of function calls I typed the wrong name. Currently, the very end of the traceback points you right at the bad code and says "NameError: name 'filehandle' is not defined," which tells me (very nearly) exactly what I did wrong. > If the error was filehundle.close() you will get: s/u/a/ ;-) > I don't think any of those would be hard to find. I guess it depends on how long your traceback is and how big those functions are. Also, from the Zen: Explicit is better than implicit. although from previous threads, we know that every pythonista has his or her own definitions of "explicit" and "implicit." Regards, Dan -- Dan Sommers From http Sun Jul 31 20:16:48 2005 From: http (Paul Rubin) Date: 31 Jul 2005 17:16:48 -0700 Subject: Dabo in 30 seconds? References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> <7xr7de5zoe.fsf@ruckus.brouhaha.com> Message-ID: <7x3bpuzf2n.fsf@ruckus.brouhaha.com> Cliff Wells writes: > > It did last time I tried installing it, which was maybe 3-6 months ago. > > Someone posted that it had been updated recently. > > Looking on SourceForge, I see that 2.4.2.4 had GTK2 builds and it's > dated 2003-10-01. That's sort of interesting. I think I downloaded whatever was on wxpython.org. I also know that GTK2 support came well before this > and was in fact a build option long before Robin made an official > release. Unfortunately SF doesn't go back any further than this and I > don't have time to research it further. Nevertheless it's provable > that wxPython had GTK2 releases almost 2 years ago. > > http://sourceforge.net/project/showfiles.php?group_id=10718&package_id=10559 > > > I spent several hours trying to install wxPython on Linux without > > success (a lot of that was figuring out that some undefined symbol it > I've seen a few people run into issues like this, usually as the result > of autoconf/automake finding obsolete libraries on a system (e.g. if you > upgraded your redhat from 7.3 to 9.0 and stale libraries were left around). No this was definitely a GTK issue. I avoid OS upgrades because of issues like what you describe. If I want a new OS, I buy a new hard drive and install the new OS from scratch, or even buy a new computer. From edgrsprj at ix.netcom.com Mon Jul 11 17:21:30 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Mon, 11 Jul 2005 21:21:30 GMT Subject: Minor correction July 11, 2005 References: Message-ID: "edgrsprj" wrote in message news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... > PROPOSED EARTHQUAKE FORECASTING > COMPUTER PROGRAM DEVELOPMENT EFFORT > it jumps strait to the display routine and uses the entered command to begin Should be the word "straight" instead of strait. From fjs205 at gmail.com Tue Jul 5 15:22:21 2005 From: fjs205 at gmail.com (fjs205 at gmail.com) Date: 5 Jul 2005 12:22:21 -0700 Subject: PyUnicodeUCS4_AsUnicode error Message-ID: <1120591341.342746.114500@g49g2000cwa.googlegroups.com> When I try to import gtk, or even start some programs that use Python I get the error: "ImportError: /usr/lib/python2.4/site-packages/gtk-2.0/gobject.so: undefined symbol: PyUnicodeUCS4_AsUnicode" Can anyone shed some light on this? FWIW, I have reinstalled python, tried v2.3.4 instead of 2.4, reinstalled GTK, searched for a unicode library problem (I reinstalled libunicode too). Thanks for any assistance. From steve at REMOVETHIScyber.com.au Mon Jul 18 09:18:48 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 18 Jul 2005 23:18:48 +1000 Subject: Dictionary, keys and alias References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> <5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote: > I want to insert a concept of alias in a dict_based class. > > The idea is to have a facoltative name in the same dict that correspond > at the same value. With this alias i can change original value. > > example: > > mydict['a'] = 1 > I must define an alias example: myFunctAlias( mydict, 'a', 'b') > print mydict > {'a':1, 'b':1} > mydict['b'] = 2 > print mydict > {'a':2, 'b':2} > > > The only idea i have is to implement two dictionary one for convert > name, alias in two keys with the same value (eg.numeric) in the first > dict. The second for store only one time the k, v . You need some sort of redirection, something like this (untested): class Doubledict: def __init__(self, **kargs): self.data = {} self.aliases = {} for key in kargs: # Point the key to a hash. self.aliases[key] = hash(key) # And point the hash at the value. self.data[hash(key)] = kargs[key] def setalias(self, key, alias): # Point the alias to the same hash as the real key. self.aliases[alias] = hash(key) def __getitem__(self, key): return self.data[self.aliases[key]] def __setitem__(self, key, value): self.data[self.aliases[key]] = value The only niggly worry I have is I'm not sure when hash can be used, when it is unique, or even if is it guaranteed to be unique. -- Steven. From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 13:13:15 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 19:13:15 +0200 Subject: Path inherits from basestring again In-Reply-To: References: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> <3l186cF10lgkmU1@individual.net> Message-ID: <3l1qpbF10ngb6U2@individual.net> Michael Hoffman wrote: > Reinhold Birkenfeld wrote: > >> It's much the same as with @ decorators. Those who have used them much >> don't object to the syntax any more. > > I do and I still think they are ugly. Shouldn't have generalized that. Add "most of" where you like. Reinhold From peter at engcorp.com Thu Jul 28 21:46:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Jul 2005 21:46:32 -0400 Subject: pySerial Windows write problem In-Reply-To: References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: Bob Greschke wrote: > I didn't write the C++ program, but it looks like it never closes the serial > port. It opens it when it starts up, then keeps it open until it quits. > Tsk tsk tsk. Sloppy. Maybe they did that to cover up this problem. :) Actually, I'm curious why you don't do the same. I'd call it very unusual (in my experience) to have a program open and close a serial port repeatedly. Among other things, this means that the DSR/DTR lines are toggling high and low repeatedly, and that alone could cause undesirable behaviour in certain devices. In none of my own serial-based programs (perhaps a few dozen such to date) have I ever opened and closed a port other than at startup and shutdown (just as your C++ program does). Unless you've got a good reason to do otherwise, if this solves your problem it's certainly the most direct approach to do so. -Peter From tjreedy at udel.edu Tue Jul 5 21:02:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 5 Jul 2005 21:02:31 -0400 Subject: flatten(), [was Re: map/filter/reduce/lambda opinions andbackground unscientific mini-survey] References: <11cbl3rb2alb32@news.supernews.com><1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: "Tom Anderson" wrote in message news:Pine.LNX.4.62.0507052310110.13421 at urchin.earth.li... > I guess setslice is a lot faster than i thought. Nope, the example is too short to be meaningful. > How are python lists > implemented? Presumably not as straightforward arrays, where inserting a > bunch of items at the head would mean moving everything else in the list > along? They *are* extensible arrays, and insertion *does* mean exactly that -- moving everything else along -- although CPython probably does it with C memcopy(). So the littly puny 'test' example with about 20 total elements is testing overhead, not large-list behavior. So you are right, *much* longer lists are needed. You could start, for example, with a list of 1000 lists of 1000 elements (all 0 would be fine). Or maybe 100 of 100 of 100. For that, I would start with something that appended and extended the result list. Or try writing a generator iflatten that yielded elements in order: def flatten(iterable): return list(iflatten(iterable)) which pushes appending down into the C code of list(). Terry J. Reedy From simon.brunning at gmail.com Mon Jul 4 04:14:37 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Jul 2005 09:14:37 +0100 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <8c7f10c605070401147ca5fe57@mail.gmail.com> On 4 Jul 2005 01:04:47 -0700, jwaixs wrote: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! http://www.amk.ca/python/howto/regex/ -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From peter at engcorp.com Wed Jul 6 08:50:41 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Jul 2005 08:50:41 -0400 Subject: Using Ghostscript DLL via ctypes in Py2.3/Win In-Reply-To: References: Message-ID: Adam Twardoch wrote: > I'd prefer to use the GhostScript DLL API* and call it using ctypes under > Windows. > Has anyone perhaps written something like that already and cares to share a > code snippet? There is a ctypes mailing list where you might have more success getting a reply (though I suspect most people there read this forum as well). -Peter From twic at urchin.earth.li Sat Jul 2 20:04:55 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 3 Jul 2005 01:04:55 +0100 Subject: A brief question. In-Reply-To: References: Message-ID: On Sat, 2 Jul 2005, Tom Brown wrote: > On Saturday 02 July 2005 10:55, Nathan Pinno wrote: > >> Brief question for anyone who knows the answer, because I don't. Is >> there anyway to make Python calculate square roots? > > from math import sqrt That's one way. I'd do: root = value ** 0.5 Does that mean we can expect Guido to drop math.sqrt in py3k? :) tom -- That's no moon! From theller at python.net Sat Jul 30 12:48:28 2005 From: theller at python.net (Thomas Heller) Date: Sat, 30 Jul 2005 18:48:28 +0200 Subject: showing help(M) when running module M standalone References: Message-ID: Chris writes: > hello, > I have a small module which only contains some utility functions. when > running this standalone I would like to show the module docs and each > function docs, as if doing > > import M > help(M) > > I came up with the following but I reckon there is a much simpler way? > > if __name__ == '__main__': > print __doc__ > print "\nFUNCTIONS:\n" > for x in __all__: > print x > exec "print " + x + ".__doc__" > > Works but does not seem right using exec for such a task. > > any hint would be great! if __name__ == "__main__": help("__main__") The only downside is that the module name is printed as '__main__'. Thomas From pinard at iro.umontreal.ca Fri Jul 8 13:40:38 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 8 Jul 2005 13:40:38 -0400 Subject: distutils is able to handle... In-Reply-To: <1120570259.138484.140720@f14g2000cwb.googlegroups.com> References: <1120570259.138484.140720@f14g2000cwb.googlegroups.com> Message-ID: <20050708174038.GB15762@phenix.progiciels-bpi.ca> [George Sakkis] > I would suggest SCons (http://www.scons.org/), a modern > make/automake/autoconf replacement that uses python for its > configuration files instead of yet another cryptic half-baked > mini-language or XML. Python might not be the most legible way to describe what a Makefile has to describe, it asks for more syntax that we really need. On the other hand, it is convenient having Python handy for extending the capabilities of your description file, that is, having Python has a provisional, supplementary card, instead the only and mandatory one. I'm exploring with some pleasure Bram Moolenaar's A-A-P tool (see http://www.a-a-p.org). This is implemented in Python, but does not force people into Python syntax for Makefiles. It might be a nicer compromise. As usual from Bram, documentation is abundant and useful. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From franz.steinhaeusler at gmx.at Tue Jul 26 04:46:27 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 26 Jul 2005 10:46:27 +0200 Subject: [ANN] XPN 0.5.0 released References: <20050725083558.1974.41689.XPN@orion.homeinvalid> <20050725134745.11684.60211.XPN@orion.homeinvalid> Message-ID: On Mon, 25 Jul 2005 15:47:13 GMT, Nemesis wrote: >[...] Hello Nemesis, >> Would it be possible to also customize the fonts in the >> groups and threads pane (I'd like to have everywhere proportional >> (monospaced fonts). > >Not at the moment, maybe in the future ... but of course if you can't >wait you can modify the source by yourself, the files to modify are >xpn_src/Groups_Pane.py and xpn_src/Threads_Pane.py >just add the line > >import pango > >in the both the files, and then: >at the end of Groups_Pane.py add this line (do not change the >indentation): > > self.groups_list.modify_font(pango.FontDescription("monospace 10")) > >at the end of Threads_Pane.py add this line (do not change the >indentation): > > self.threads_tree.modify_font(pango.FontDescription("monospace 10")) > >of course you can change the font description as you like. thank you for the tip. -- Franz Steinhaeusler From jan.danielsson at gmail.com Mon Jul 25 12:16:01 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Mon, 25 Jul 2005 18:16:01 +0200 Subject: First app, thanks people In-Reply-To: References: <42e4eff3$1@griseus.its.uu.se> Message-ID: <42e50ed3$1@griseus.its.uu.se> Dark Cowherd wrote: [---] > In case you are interested in bug report. Always! > class LineTool > method OnLeftUp > needs > self.done = True > > or else if you are in Line mode and you just click with out moving the > mouse you get an error. Many thanks; I can't believe I hadn't stumbled across that bug myself while testing it. Though you are free to do whatever you want with the code, I wouldn't mind seeing any improvements made to it by others, so that I myself may learn from it. From tjreedy at udel.edu Tue Jul 19 16:55:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 19 Jul 2005 16:55:44 -0400 Subject: socket programming References: <20050719184205.GA24773@mail.smule.com> <20050719204601.GB24773@mail.smule.com> Message-ID: "Helge Aksdal" wrote in message news:20050719204601.GB24773 at mail.smule.com... >* Jaime Wyant [2005/07/19 21:26]: > >> It sounds really strange to connect to a server "several hundred" >> times. If I had to guess, the server monitored all of the connects >> coming from your IP address and eventually stopped accepting ANY >> connections. > > That's really what it eventually does, just that it refuses my > connection, and a connection to another server is established. > > The alternative is to do it by http connection, but i'm afraid > that's going to be too slow. or am i wrong here? > > To help you understand me better, this is a server at work that > gives me some account information, so when i want to check "several > hundred" accounts i need to look them up one by one since the server > closes the connection after each query. Ask your server administrator if you are bumping up against a hidden connection limit. Or if a query can ask about multiple accounts. tjr From mwh at python.net Wed Jul 13 08:00:51 2005 From: mwh at python.net (Michael Hudson) Date: Wed, 13 Jul 2005 12:00:51 GMT Subject: math.nroot [was Re: A brief question.] References: Message-ID: Tim Peters writes: > [Michael Hudson] > > I doubt anyone else is reading this by now, so I've trimmed quotes > > fairly ruthlessly :) > > Damn -- there goes my best hope at learning how large a message gmail > can handle before blowing up . OK, I'll cut even more. Heh. > [Michael] > >>> Can't we use the stuff defined in Appendix F and header of > >>> C99 to help here? I know this stuff is somewhat optional, but it's > >>> available AFAICT on the platforms I actually use (doesn't mean it > >>> works, of course). > > [Tim] > >> It's entirely optional part of C99. > > > Hmm, is optional? I'm not finding those words. I know > > Appendix F is. > > fenv.h is required, but the standard is carefully worded so that > fenv.h may not be of any actual use. For example, a conforming > implementation can define FE_ALL_EXCEPT as 0 (meaning it doesn't > define _any_ of the (optional!) signal-name macros: FE_DIVBYZERO, > etc). That in turn makes feclearexcept() (& so on) pretty much > useless -- you couldn't specify any flags. Makes sense. > >> The most important example of a compiler that doesn't support any of > >> that stuff is Microsoft's, although they have their own MS-specific > >> ways to spell most of it. > > > OK, *that's* a serious issue. > > > > If you had to guess, do you think it likely that MS would ship fenv.h > > in the next interation of VC++? > > Sadly not. If they wanted to do that, they had plenty of time to do > so before VC 7.1 was released (C99 ain't exactly new anymore). As it > says on > > http://en.wikipedia.org/wiki/C_programming_language > > MS and Borland (among others) appear to have no interest in C99. > > In part I expect this is because C doesn't pay their bills nearly so > much as C++ does, and C99 isn't a standard from the C++ world. This also makes sense, in a slightly depressing way. > >>> In what way does C99's fenv.h fail? Is it just insufficiently > >>> available, or is there some conceptual lack? > > >> Just that it's not universally supported. Look at fpectlmodule.c for > >> a sample of the wildly different ways it _is_ spelled across some > >> platforms. > > > C'mon, fpectlmodule.c is _old_. Maybe I'm stupidly optimistic, but > > perhaps in the last near-decade things have got a little better here. > > Ah, but as I've said before, virtually all C compilers on 754 boxes > support _some_ way to get at this stuff. This includes gcc before C99 > and fenv.h -- if the platforms represented in fpectlmodule.c were > happy to use gcc, they all could have used the older gcc spellings > (which are in fpectlmodule.c, BTW, under the __GLIBC__ #ifdef). Um, well, no, not really. The stuff under __GLIBC___ unsurprisingly applies to platforms using the GNU project's implementation of the C library, and GCC is used on many more platforms than just that (e.g. OS X, FreeBSD). This is all part of the "what exactly are you claiming supports 754, again?" game, I guess. Even given that, the glibc section looks mighty Intel specific to me (I don't see why 0x1372 should have any x-architecture meaning). Now that GCC supports, or aims to support, or will one day support C99 I think you're right in that any GCC-using code can use the same spelling. One thing GCC doesn't yet support, it turns out, is the "#pragma STDC FENV_ACCESS ON" gumpf, which means the optimiser is all too willing to reorder feclearexcept(FE_ALL_EXCEPT); r = x * y; fe = fetestexcept(FE_ALL_EXCEPT); into feclearexcept(FE_ALL_EXCEPT); fe = fetestexcept(FE_ALL_EXCEPT); r = x * y; Argh! Declaring r 'volatile' made it work. > But they didn't, so they're using "minority" compilers. I used to > write compilers for a living, but I don't think this is an inside > secret anymore : there are a lot fewer C compiler writers than > there used to be, and a lot fewer companies spending a lot less > money on developing C compilers than there used to be. Indeed. Also, less architectures and less C libraries. > As with other parts of C99, I'd be in favor of following its lead, and > defining Py_ versions of the relevant macros and functions. Makes sense! > >> A maze of #ifdefs could work too, provided we defined a > >> PyWhatever_XYZ API to hide platform spelling details. > > > Hopefully it wouldn't be that bad a maze; frankly GCC & MSVC++ covers > > more than all the cases I care about. > > I'd be happy to settle for just those two at the start, As with > threading too, Python has suffered from trying to support dozens of > unreasonable platforms, confined to the tiny subset of abilities > common to all of them. If, e.g., HP-UX wants a good Python thread or > fp story, let HP contribute some work for a change. I think we have > enough volunteers to work out good gcc and MSVC stories -- although I > expect libm to be an everlasting headache Well, yes. I think a 'thin wrapper' approach like some of the os module stuff makes sense here. Cheers, mwh -- I've reinvented the idea of variables and types as in a programming language, something I do on every project. -- Greg Ward, September 1998 From limi at plone.org Wed Jul 27 15:01:12 2005 From: limi at plone.org (limi at plone.org) Date: 27 Jul 2005 12:01:12 -0700 Subject: multilanguage site and user informations edition In-Reply-To: <42e719cc$0$6425$626a14ce@news.free.fr> References: <42e4b845$2$13224$636a15ce@news.free.fr> <1122406220.372545.113870@g43g2000cwa.googlegroups.com> <42e719cc$0$6425$626a14ce@news.free.fr> Message-ID: <1122487495.731429.175040@g49g2000cwa.googlegroups.com> Plone 2.1 RC is released on Monday. Hopefully the LinguaPlone update is available that same week. If you can't wait that long, I suggest you stick to Plone 2.0.5 and LinguaPlone 0.7.x. -- Alexander From mailman at hanez.org Sat Jul 16 21:47:56 2005 From: mailman at hanez.org (Johannes Findeisen) Date: Sun, 17 Jul 2005 03:47:56 +0200 Subject: Python vs. Access VBA In-Reply-To: <1121556646.5653.43.camel@phantom.wg.xw3.org> References: <1121556646.5653.43.camel@phantom.wg.xw3.org> Message-ID: <1121564876.6789.3.camel@phantom.wg.xw3.org> On Sun, 2005-07-17 at 01:30 +0200, Johannes Findeisen wrote: > My recommendation: > > Use Python! You will love me in some years because i have said this. > When using Access you are binding your application to Microsoft. You > need a runtime version of Access when distributing the application to > others. When using Python you could build an install CD for more the > windows and you didn't have to bother about proprietary licensing > issues. P.S.: Before i forget: MS-Access doesn't care about security in any way. In Python you need to implement most features by yourself but you have the ability. In MS-Access you must trust Microsoft! This is the truth... Regards, -- Johannes Findeisen http://hanez.org/ From pinard at iro.umontreal.ca Fri Jul 22 09:09:02 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 22 Jul 2005 09:09:02 -0400 Subject: Difference between " and ' In-Reply-To: References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <20050722010657.GA24716@unpythonic.net> Message-ID: <20050722130902.GB2284@alcyon.progiciels-bpi.ca> [Robert Kern] > One habit that seems to crop up, though, is that I will use '' for > internal strings and "" for strings that will eventually get seen by > the user. Don't ask me why. One sure thing is that it would help, later, if you ever want to internationalise a Python program. Not that it occurs that often! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From hancock at anansispaceworks.com Thu Jul 21 21:08:32 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 21 Jul 2005 20:08:32 -0500 Subject: Generating images with text in them In-Reply-To: References: Message-ID: <200507212008.32759.hancock@anansispaceworks.com> On Thursday 21 July 2005 05:23 am, Daren Russell wrote: > I've just been playing around with this. You can use truetype fonts with: > > font = ImageFont.truetype("/path/to/font.ttf", 12) > > from version 1.1.4 > > http://www.pythonware.com/library/pil/handbook/imagefont.htm for more Wow, I didn't know about that new feature. I gotta use that. ;-) I'd say that if you can do that, it's probably not worth messing with the PIL fonts. There are lots of suitable free TrueType fonts available on the web (many of which are also free-licensed, IIRC). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From Scott.Daniels at Acm.Org Wed Jul 6 13:47:42 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 06 Jul 2005 10:47:42 -0700 Subject: Avoiding NameError by defaulting to None In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <42cc1177$1@nntp0.pdx.net> Ron Adam wrote: > Dan Sommers wrote: >> Lots more hard-to-find errors from code like this: >> filehandle = open( 'somefile' ) >> do_something_with_an_open_file( file_handle ) >> filehandle.close( ) > > If do_something_with_an_open_file() is not defined. Then you will get: > TypeError: 'NoneType' object is not callable > > > If "file_handle" (vs "filehandle") is None. Then you will still get an > error as soon as you tried to use the invalid file handle. Ah, but where you use it can now far from the error in the source. The None could get packed up in a tuple, stored in a dictionary, all manner of strange things before discovering it was an unavailable value. I would love the time back that I spent chasing bugs when Smalltalk told me (I forget the exact phrasing) "nil does not respond to message abc." My first reaction was always, "of course it doesn't, this message is useless." You really want the error to happen as close to the problem as possible. --Scott David Daniels Scott.Daniels at Acm.Org From mauriceling at acm.org Mon Jul 4 07:56:15 2005 From: mauriceling at acm.org (Maurice LING) Date: Mon, 04 Jul 2005 21:56:15 +1000 Subject: Connecting to Firebird database using Kinterbasdb+Python Message-ID: Hi, I've been using FB1.5 and access the database using Kinterbasdb + Python. My connection is established using kinterbasdb.connect() method and the parameters host, dns, database, user, password are all defaulted to 'None'. On my own machine running Mac OSX 10.3, I can connect using the following: host = 'localhost' database = '' user = '' password = '' At the same time, I can also connect if I set host=None on my machine. However, I cannot use 'localhost' on a shared Linux machine (not allowed. Don't ask why, system admin's mandate. And the Linux machine is without inetd). So when I set host=None, I get this error: Connecting to Muscopedia Database Connection: localhost:/mnt/disk/home/mling/muscorian/BioDatabases/muscopedia.fdb:mouse:mouse <-- default None <-- actual host (with 'print self.dbhost' where kinterbasdb.connect(host = self.dbhost,.....) OperationalError (-902, 'isc_attach_database: Unable to complete network request to host "localhost".. Failed to establish a connection.. Connection refused. ') File "muscorian.py", line 641, in main result = mosys.run(command) File "muscorian.py", line 597, in run elif (command[0] == 'linkmuscopedia'): self.commandLinkMuscopediaDB(command) File "muscorian.py", line 129, in commandLinkMuscopediaDB self.muscopedia = PubMedGrabber.FBUtilities(str(command[1])) File "abcrawl/PubMedGrabber.py", line 340, in __init__ user = self.dbuser, password = self.dbpwd, charset='UNICODE_FSS') File "/usr/lib/python2.2/site-packages/kinterbasdb/__init__.py", line 470, in connect return Connection(*args, **keywords_args) File "/usr/lib/python2.2/site-packages/kinterbasdb/__init__.py", line 608, in __init__ self._C_con = _k.attach_db(dsn, dpb, dialect) Any ideas or solutions? Thanks in advance. Cheers maurice From gene.tani at gmail.com Fri Jul 8 13:31:39 2005 From: gene.tani at gmail.com (gene tani) Date: 8 Jul 2005 10:31:39 -0700 Subject: Learning Python - IM Wiki In-Reply-To: References: Message-ID: <1120843898.908411.54190@z14g2000cwz.googlegroups.com> The python tutor good for this http://mail.python.org/mailman/listinfo/tutor Miki Tebeka wrote: > Hello Jorge, > > > Is there some sort of a Wiki where I could post the code and have > > advice on what, how and where to improve? Or should I post the code it > > here? > You can always get help here, the Python community is *very* helpful. > > If you prefer a Wiki, try www.wikispaces.org for free Wiki hosting. > > Bye. > -- > ------------------------------------------------------------------------ > Miki Tebeka > http://tebeka.bizhat.com > The only difference between children and adults is the price of the toys From future_retro at yahoo.co.uk Thu Jul 14 06:24:15 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 14 Jul 2005 03:24:15 -0700 Subject: exec method WMI In-Reply-To: <42d55898$1_2@spool9-west.superfeed.net> References: <1121273148.010439.70100@g44g2000cwa.googlegroups.com> <42d55898$1_2@spool9-west.superfeed.net> Message-ID: <1121336654.970734.142250@g14g2000cwa.googlegroups.com> Got it working, removed spawninstance and the driver path should have been "C:\\test\\" Cheers for your help Roger. From falcon at intercable.ru Sun Jul 31 13:41:30 2005 From: falcon at intercable.ru (falcon) Date: Sun, 31 Jul 2005 21:41:30 +0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) Message-ID: <992707259.20050731214130@intercable.ru> Hello python-list, As I Understood, semantic may be next: def qwerty(a,a.i,b,b.i,f.j): pass Would work like: def qwerty(anonymous1,anonymous2,anonymous3,anonymous4,anonymous5): (a,a.i,b,b.i,f.j)=(anonymous1,anonymous2,anonymous3,anonymous4,anonymous5) del anonymous1 del anonymous2 del anonymous3 del anonymous4 del anonymous5 If so then I like it, because it more explicit than anything other and it is working right now. I just tryed: >>> class Stub: ... pass >>> def qwer(a1,a2,a3,a4,a5): ... (a,a.i,b,b.i,f['i'])=(a1,a2,a3,a4,a5) ... del a1 ... del a2 ... del a3 ... del a4 ... del a5 ... print (a,a.i,b,b.i,f['i']) >>> f={} >>> qwer(Stub(),1,Stub(),2,3) (<__main__.Stub instance at 0x00C49530>, 1, <__main__.Stub instance at 0x00C498C8>, 2, 3) So there are not too much for implement. Another question - named arguments. How I can assign to them? May be so: f={} def qwerty(a,a.i,f['i']): print (a,a.i,f['i']) qwerty(f['i']=3,a=Stub(),a.i=4) - ? and for __init__: class MyClass: def __init__(self,self.i,self.j,self.k): pass MyObject = MyClass(self.i=1,self.j=2,self.k=3) ? or may be there can be an aliase syntax? class MyClass: def __init__(self, self.i by i,self.j by j, self.k by k): pass MyObject = MyClass(i=1,j=2,k=3) -- Sokolov Yura falcon at intercable.ru From vibtrip at yahoo.com Fri Jul 1 12:39:33 2005 From: vibtrip at yahoo.com (Vibha Tripathi) Date: Fri, 1 Jul 2005 09:39:33 -0700 (PDT) Subject: Regular Expression for pattern substitution Message-ID: <20050701163933.35954.qmail@web53912.mail.yahoo.com> It'd be silly to write the code for it if it already exists somewhere in the Python re or sre library module: I need to find and replace all strings in a text file from a certain pattern to another pattern. so for example if I see 'this(\D*)that' anywhere in the file then I'd like to make is 'that(\D*)this' where the middle part of the strings remains unmodified. Any suggestions? Peace. Vibha PS. How do I avoid getting my email ID web-published for this mailing list.? ____________________________________________________ Yahoo! Sports Rekindle the Rivalries. Sign up for Fantasy Football http://football.fantasysports.yahoo.com From donnal at donnal.net Fri Jul 1 08:41:39 2005 From: donnal at donnal.net (Donnal Walter) Date: Fri, 01 Jul 2005 07:41:39 -0500 Subject: class attribute to instance attribute In-Reply-To: <1120165777.941654.13390@f14g2000cwb.googlegroups.com> References: <1120165777.941654.13390@f14g2000cwb.googlegroups.com> Message-ID: Devan L wrote: > Why make it an instance attribute? Couldn't you just look at > the class attribute? Each "presenter" (instance) needs its own "view" (instance). The class attribute references a wxPython class. The resulting instance attribute references a wxPython object (widget or container). > If its something that depends on each instance's value > assigned to the attribute, why not make it an instance attribute to > start with? The view instance is not known at design time; it can only be created at runtime. To do this requires doing so in the __init__() method, either in a separate version method for every different presenter class, or once in the superclass, as I have done. Donnal From godwinburby at rediffmail.com Sat Jul 2 05:31:42 2005 From: godwinburby at rediffmail.com (godwin) Date: 2 Jul 2005 02:31:42 -0700 Subject: What are the other options against Zope? Message-ID: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> Hi all, I wanna thank Martin for helping out with my ignorance concerning execution of stored procedure with python. Now i have decided to write a web app that googles into my companies proprietary database. I need to know whether zope is good for that job. But even the introduction to zope in the zope book was intimidating. Are there any simple options? If so plz tell me how i can obtain it and study it. I should say that i am new to web programming. Thank you From d0153030 at hotmail.com Thu Jul 21 23:35:49 2005 From: d0153030 at hotmail.com (Sandeep Arya) Date: Fri, 22 Jul 2005 09:05:49 +0530 Subject: Detecting computers on network In-Reply-To: Message-ID: Hello dear I had sent my earlier queries regarding same topic. However just to be more specific this time.. I just wann try to detect that if there are some ip address in a list of some ip address alive or not. How can i do this? Shall i try to connect them and check that my connection is working or not? If working than means alive .... (connection based) SHalle i send some buffer value (whatever) to socket using sendto(...) and then checking for return value? (Connectionless) Well for me it doesnot matter that i should have connection or connectionless.. I just wannn know who are alive in my LAN? This application will be for my computers in lan. not for maganetwork. LAN will have just some bridges and computers. i need to detect tham all.. however i doesnot matter that all of them replies or not. I just wann know that atleast some of them reply. Rest i will take care of... Sandeep _________________________________________________________________ NRIs, does your family in India need money urgently? http://creative.mediaturf.net/creatives/icicibank/ICICI_NRI_ERA.htm Open an ICICI Bank NRI savings A/c From albert at compuscan.co.za Mon Jul 11 10:42:34 2005 From: albert at compuscan.co.za (Albert Leibbrandt) Date: Mon, 11 Jul 2005 16:42:34 +0200 Subject: cursor positioning In-Reply-To: <42D281D2.9060302@mage.hu> Message-ID: <20050711144249.374391E4002@bag.python.org> -----Original Message----- From: python-list-bounces+albert=compuscan.co.za at python.org [mailto:python-list-bounces+albert=compuscan.co.za at python.org] On Behalf Of Mage Sent: 11 July 2005 04:28 PM To: python-list at python.org Subject: Re: cursor positioning Larry Bates wrote: >While not "curses" based this class will update screen as you >want. You could use it as a basis upon which to do a curses >version with your cursor positioning. > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 > > > Thank you. This is good for displaying the percentage. However it fails to display this: 100 files read 200 files read 300 files read .... of course all in the same line and not under the last line. Mage -- Why not use something like this? counter = 0 while 1: if (counter % 100) == 0: print'%s files read '%counter counter += 1 From dalke at dalkescientific.com Sat Jul 23 04:03:37 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 23 Jul 2005 08:03:37 GMT Subject: unit test nested functions References: Message-ID: Andy wrote: > How can you unit test nested functions? I can't think of a good way. When I write a nested function it's because the function uses variables from the scope of the function in which it's embedded, which means it makes little sense to test it independent of the larger function. My tests in that case are only of the enclosing function. > Or do you have to pull them out to > unit test them, which basically means I will never use nested functions. You don't test every line in a function by itself, right? Nor every loop in a function. It should be possible to test the outer function enough that the implementation detail - of using an inner function - doesn't make much difference. > Also, same thing with private member functions protected by __. Seems > like there is a conflict there between using these features and unit > testing. In that case the spec defined that the real function name is of the form "___". For example >>> class Spam: ... def __sing(self): ... print "I don't see any Vikings." ... >>> spam = Spam() >>> spam._Spam__sing() I don't see any Vikings. >>> I've found though that the double-leading-underscore is overkill. Using a single underscore is enough of a hint that the given method shouldn't be called directly. Then again, I don't write enough deep hierarchies where I need to worry about a subclass implementation using the same private name as a superclass. Andrew dalke at dalkescientific.com From gsakkis at rutgers.edu Wed Jul 6 20:02:33 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 6 Jul 2005 17:02:33 -0700 Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> <42cbdbde$0$10471$da0feed9@news.zen.co.uk> <1120670131.471176.133020@g14g2000cwa.googlegroups.com> Message-ID: <1120694552.885184.318200@g44g2000cwa.googlegroups.com> "Steven D'Aprano" wrote: > On Wed, 06 Jul 2005 10:15:31 -0700, George Sakkis wrote: > > > Well, they *may* be interchangable under some conditions, and that was > > the OP's point you apparently missed. > > I didn't miss anything of the sort. That's why I spent 15 minutes actually > producing test cases to MEASURE if there was any detectable speed > differences between accessing set and frozenset instead of wasting time > worrying about "tiny" differences in performance that are almost certainly > lost in the noise in real code. > > If, over a thousand runs of the program, you save a millisecond of time in > total, but it costs you two seconds to type the comment in the code > explaining why you used frozenset instead of the more natural set, then > your "optimization" is counter-productive. Even just considering the > question is a waste of valuable developer time! THAT is the lesson of > premature optimization: don't even THINK about optimizing code until you > have it WORKING and you have MEASURED that it is too slow. I fully agree with your last sentence, first profile and then consider if it's worth optimizing. Still, you either missed the point again or you are arguing for the sake of the argument. Neither me nor the OP claimed that it's worthwhile saving a millisecond or two. The OP hadn't done the timing measurements you did, so he didn't know in advance if the difference is 1 millisecond or 500. After you replied with evidence that it's not worth it, he made clear that he was just enquiring, not optimizing prematurely as you took for granted and ranted against it from the beginning. Hope it's clear now, George From darkcowherd at gmail.com Mon Jul 4 13:19:03 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Mon, 4 Jul 2005 22:49:03 +0530 Subject: Considering moving from Delphi to Python [Some questions] Message-ID: <5f4d3cb505070410192ba525d7@mail.gmail.com> Hi, We program in Delphi in our shop and are generally very happy with it. We are now looking at cross-platform options especially for middle tier and web server. I have been doing a lot of reading and testing of Python, I am falling in love with the language :-) But seems to be be very difficult for what I am trying to do :-( So looking for advise here We would like to work as following. Front ends in Delphi. Middle tier in Python working as SOAP servers: Serious work on Twisted needed here ?elementree? are there any other options. Lots of learning to do. Doesnt seem to be simple way to do this. Most of our applications are business applications so we basically we want to do a lot of data entry forms including entry in grid like interfaces etc. At this point i am looking at nevow with twisted. Again lot of learning to do here. darkcowherd From spike.666 at gmail.com Sun Jul 31 21:53:41 2005 From: spike.666 at gmail.com (spike grobstein) Date: 31 Jul 2005 18:53:41 -0700 Subject: subclassing list References: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> Message-ID: <1122861221.206598.6300@g47g2000cwa.googlegroups.com> >You also need to post the code that raises the error, or no one else can debug it. sorry, I thought I had pasted that line in there, but I guess I missed it. Here's the full code (after modifying it slightly based on your post): #! /usr/bin/env python def circular_list(list): def __getitem__(self, i): return list.__getitem__(self, i % len(self)) items = circular_list(range(8)) for i in items: print i [/end code] spike at flaphead ~/tests/afx-view $ ./circular.py Traceback (most recent call last): File "./circular.py", line 10, in ? for selected in items: TypeError: iteration over non-sequence if I just try to call: print items[12] I get this error: spike at flaphead ~/tests/afx-view $ ./circular.py Traceback (most recent call last): File "./circular.py", line 9, in ? print items[12] TypeError: unsubscriptable object I'm using python 2.3.5 From rrossi at edmaster.it Fri Jul 22 06:51:13 2005 From: rrossi at edmaster.it (rock69) Date: 22 Jul 2005 03:51:13 -0700 Subject: Get directory from http web site Message-ID: <1122029473.532056.215900@z14g2000cwz.googlegroups.com> Hi all :) I was wondering if there's some neat and easy way to get the entire contents of a directory at a specific web url address. I have the following link: http://www.infomedia.it/immagini/riviste/covers/cp and as you can see it's just a list containing all the files (images) that I need. Is it possible to retrieve this list (not the physical files) and have it stored in a variable of type list or something? And, if so, what would be the easiest and most efficient way? Thank you so much in advance. Rock From roy at panix.com Fri Jul 1 15:38:33 2005 From: roy at panix.com (Roy Smith) Date: 1 Jul 2005 15:38:33 -0400 Subject: map vs. list-comprehension References: <42c586d1$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: >Roy Smith wrote: >> Look at what happened to C when it mutated into C++. In isolation, most of >> the features of C++ seem like good ideas. Taken together, it's a huge >> hairy mess that most people only understand increasingly larger subsets of. >> Fred Brooks called it the second system syndrome. > >If you read "The Design and Evolution of C++" by Stroustrupp, you can >see how most of current C++ is a direct result of its initial design >requirements, not an aglomeration of features, each of which is a "good >idea." I take from the resulting big hairy mess that the design goals >themselves are at fault for the big hairy mess. I havn't read the book, but, wasn't the whole STL dropped into place quite late, long after the basic language design was done? There's a fair amount of hair in the STL. I thought exceptions and the myriad of cast operators were latecomers to the party too. Or is it simply that some compilers didn't support those features (or support them well) until recently? I've heard some people say that one of the reasons C++ is such a mess is because it had to retain backwards compatability with C. I don't buy that. There's nothing in the miserably complex class inheritance, polymorphism, access control, argument defaulting machinery that harkens back to C. There's nothing about template error messages that don't fit on a single screen that harkens back to C. About the only major problem which I can see that traces to C is the memory management. From steve at REMOVEMEcyber.com.au Mon Jul 25 23:41:36 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 26 Jul 2005 13:41:36 +1000 Subject: how to write a line in a text file References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> <1122335135.915411.321900@g44g2000cwa.googlegroups.com> Message-ID: <42E5B0F0.6020206@REMOVEMEcyber.com.au> Wade wrote: > Steven D'Aprano wrote: > >>I'm usually opposed to creeping featuritis in programming languages ("it >>would be really cool if Python had a built-in command to do my entire >>application") but safe over-writing of files does cry out for a "batteries >>included" approach: > > > > How about the fileinput module? > > http://docs.python.org/lib/module-fileinput.html Close, but not quite: the "inplace" argument is more specific and less general than what I was talking about. The fileinput solution only works for the specific idiom: read file A in text mode process text write standard output back to file A compared to the more general idiom: get data from somewhere process data write data to existing file A In the more general idiom, you don't care whether your data is text or binary data, whether you got it from a file, whether it was the same file you are writing to, or anything else. All you care about is that the file you write to happens to already exist. Long ago, when dinosaurs roamed the Earth, (a.k.a. "before OS X on the Macintosh") Apple suggested a bit of Pascal code for safely updating a file: http://developer.apple.com/documentation/mac/Files/Files-25.html#MARKER-9-163 Most of the code is Macintosh-specific, but the principle is not: when over-writing a file, make sure that the user can recover from any error up to and including power failure without losing the data on disk. (Presumably if the sun explodes and destroys the Earth, your program is allowed to lose data.) -- Steven. From noreply at gcgroup.net Wed Jul 20 09:16:55 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 20 Jul 2005 13:16:55 GMT Subject: main window in tkinter app In-Reply-To: <0FmDe.8922$TU.2673@bignews1.bellsouth.net> References: <0FmDe.8922$TU.2673@bignews1.bellsouth.net> Message-ID: That does it!, thanks. Thinking about it, when I created a derived class with an __init__ method, I overrode the base class's init. It should have been intuitive that I needed to explicitly call baseclass.__init(self), it wasn't. It might have hit me if the fault was related to someting in baseclass.__init() not taking place, but the recursion loop didn't give me a clue. Any idea why failing to init the base class caused the loop? Bill Christopher Subich wrote: > William Gill wrote: > >> O.K. I tried from scratch, and the following snippet produces an >> infinite loop saying: >> >> File "C:\Python24\lib\lib-tk\Tkinter.py", line 1647, in __getattr__ >> return getattr(self.tk, attr) >> >> If I comment out the __init__ method, I get the titled window, and >> print out self.var ('1') >> >> >> import os >> from Tkinter import * >> >> class MyApp(Tk): >> var=1 >> def __init__(self): >> pass >> def getval(self): >> return self.var >> >> >> app = MyApp() >> >> app.title("An App") >> print app.getval() >> app.mainloop() > > > You're not calling the parent's __init__ inside your derived class. I > would point out where the Python Tutorial points out that you should do > this, but it's not in the obvious place (Classes: Inheritance). > > Python does -not- automagically call parent-class __init__s for derived > classes, you must do that explicitly. Changing the definition of your > class to the following works: > >>> class MyApp(Tk): > var=1 > def __init__(self): > Tk.__init__(self) > pass > def getval(self): > return self.var > > It works when you comment out __init__ because of a quirk in Python's > name resolution. As you'd logically expect, if you don't define a > function in a derived class but call it (such as instance.method()), it > will call the method from the base class. > > You just proved that this works for __init__ methods also. When you > didn't define __init__ for your derived class, MyApp() called > Tk.__init__(), which Does the Right Thing in terms of setting up all the > specific Tkinter-specific members. From jgrahn-nntq at algonet.se Thu Jul 7 03:39:02 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 7 Jul 2005 07:39:02 GMT Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> Message-ID: On Wed, 6 Jul 2005 14:56:09 +0200, Sybren Stuvel wrote: ... > I'm usually annoyed by IDEs because, for instance, they don't use VIM > as an editor. Since I'm hooked to that, all IDEs I've used so far have > failed to impress me. Same here (s/VIM/Emacs/, or course). I try not to make myself too dependent on some specialized software, because (a) I tend to work on different Linux or Unix machines, or even on Windows and (b) my development cycle is almost the same whether I'm programming in Python, Perl, C++ or C (or writing in HTML, troff or LaTeX, for that matter). Emacs and vim are almost always installed, or trivially installable. All I need to remember is to bring my emacs config file. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From mwm at mired.org Sat Jul 23 13:25:34 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 23 Jul 2005 13:25:34 -0400 Subject: time.time() under load between two machines References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> <1122050067.793702.164780@o13g2000cwo.googlegroups.com> Message-ID: <86fyu5ph81.fsf@bhuda.mired.org> kwharrigan at yahoo.com writes: > I am seeing negative latencies of up to 1 second. I am using ntp to > synchronize both machines at an interval of 2 seconds, so the clocks > should be very much in sync (and are from what I have observed). I > agree that it is probably OS, perhaps I should hop over to a Microsoft > newsgroup and pose the question, although I'm sure they will find a way > to blame it on Python. We're getting off topic here, but what are the two machines ntp syncing to? Specifically, is one syncing to the other, or are they both syncing to the same external source, or - worst case - are they syncing to different external sources? Have you checked the drift file on the two machines? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gene.tani at gmail.com Sun Jul 17 09:03:00 2005 From: gene.tani at gmail.com (gene tani) Date: 17 Jul 2005 06:03:00 -0700 Subject: I just wanna know about os.path module.. In-Reply-To: References: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> Message-ID: <1121605380.129426.8930@g43g2000cwa.googlegroups.com> look at 'path' module too http://www.jorendorff.com/articles/python/path/ From joe at skyrush.com Mon Jul 4 16:16:17 2005 From: joe at skyrush.com (Joe Peterson) Date: Mon, 04 Jul 2005 14:16:17 -0600 Subject: "long int..." exception reported with strange traceback location Message-ID: <42C99911.5050205@skyrush.com> I could not find another example of this via internet searches, so here it is... I am wondering if this is a python bug or otherwise. The first example of this happened in a larger program of mine, and the traceback reports the problem at the start of a "for" loop (making no sense), but I cannot easily include the full code and instructions here. So I wrote a small test program containing the offending code, and in this case the traceback reports the problem happening "during garbage collection." So in either case, there's something funny going on here. The call the causes it is "os.utime()". Note that the trigger is a rediculous timezone value that causes an overflow. But the surprize is that the traceback does not report its happening in utime. If anyone has a clue what's really happening, I'd love to know. Anyway, here is the sample program: ------------- import os import rfc822 fp = file("foo_test_file", "w") fp.write("hi") fp.close() tt = rfc822.parsedate_tz("Fri, 01 Jul 2005 05:04:23 -4000000000000") t = rfc822.mktime_tz(tt) print tt print t os.utime("foo_test_file", (t, t)) ------------- Running this gives: (2005, 7, 1, 5, 4, 23, 0, 0, 0, -144000000000000L) 1.44001120194e+14 Exception exceptions.OverflowError: 'long int too large to convert to int' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection I am running Fedora Core 3, and it is Python version 2.3.4 [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)]. Thanks, Joe From grante at visi.com Wed Jul 6 17:57:54 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Jul 2005 21:57:54 -0000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> Message-ID: <11cokv26rabdndf@corp.supernews.com> On 2005-07-06, Ron Adam wrote: > It would be a way to set an argument as being optional without actually > assigning a value to it. The conflict would be if there where a global > with the name baz as well. Probably it would be better to use a valid > null value for what ever baz if for. If it's a string then "", if its a > number then 0, if it's a list then [], etc... Except those aren't "null values" for those types. 0 is a perfectly good integer value, and I use it quite often. There's a big difference between an "invalid integer value" and an integer with value 0. -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From fred at ucar.edu Tue Jul 5 17:46:19 2005 From: fred at ucar.edu (bandw) Date: 5 Jul 2005 14:46:19 -0700 Subject: Using Numeric 24.0b2 with Scientific.IO.NetCDF In-Reply-To: References: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> <1120590393.714232.34240@f14g2000cwb.googlegroups.com> Message-ID: <1120599979.936820.210160@g43g2000cwa.googlegroups.com> Thanks again. I will take your advice. My concern is in not knowing where in all my python code I am assuming a scalar return in certain circumstances. But I guess I can take care of the errors as they come up. Fred From rorley at gmail.com Wed Jul 13 12:00:54 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 13 Jul 2005 09:00:54 -0700 Subject: Help with mass remove in text file Message-ID: <1121270454.812750.235980@o13g2000cwo.googlegroups.com> I'm trying to open a text file, remove all instances of the words "f=x;" and "i=x;" where x can be any number 0-14. Also, I want to remove all { " or ) or ( or ' } each time one of those characters occurs respectively. This is what I've been able to piece together... import os, string x = ("f=;") y = ("i=;) inputFile = open('abcd.txt','r') data = inputFile.read() inputFile.close() search = string.find(data, x) if search >=1: data = data.replace(x) data = data.replace(y) outputFile = open('abcd.txt','w') outputFile.write(data) outputFile.close() This doesn't work, even to just remove "f=;". Any help would be great. Thanks, Reece From sybrenUSE at YOURthirdtower.com.imagination Sun Jul 10 16:28:39 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 10 Jul 2005 22:28:39 +0200 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Steve Juranich enlightened us with: > Without fail, when I start talking with some of the "old-timers" > (people who have written code in ADA or Fortran), I hear the same > arguments that using "if" is "better" than using "try". Then here is the counter argument: - Starting a 'try' is, as said somewhere else in this thread, a single bytecode, hence simple. - Those old-timers will probably check the data before they pass it to a function. Because their function has to be stable and idiot-proof as well, the function itself performs another check. Maybe the data is passed even further down a function chain, making checks before and after the function calls. After all, we want to be sure to only call a function when we're sure it won't fail, and every function has to gracefully bail when it's being passed bad data. This means that there will be a _lot_ of checks in the code. Now compare this by setting up a single try-block, and catching the exception at the proper place in case it's being thrown. The important part is this: those old-timers' "if" statements are always executed - it doesn't matter whether the data is correct or incorrect. The "heavy" part of exceptions only comes into play when the data is incorrect, which by proper design of the program shouldn't happen often anyway. As far as I see it, try/except blocks are "cheaper" than "if" statements. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From mwh at python.net Fri Jul 15 05:14:25 2005 From: mwh at python.net (Michael Hudson) Date: Fri, 15 Jul 2005 09:14:25 GMT Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? References: <11ddckucctde603@corp.supernews.com> Message-ID: Grant Edwards writes: > I've read over and over that Python leaves floating point > issues up to the underlying platform. Please read the conversation Tim and I are having in the "Re: math.nroot [was Re: A brief question.]" elsewhere in this same newsgroup. Cheers, mwh -- "Also, does the simple algorithm you used in Cyclops have a name?" "Not officially, but it answers to "hey, dumb-ass!" -- Neil Schemenauer and Tim Peters, 23 Feb 2001 From ed at leafe.com Sun Jul 31 11:23:07 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 11:23:07 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <87vf2ryrk1.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> Message-ID: <200507311123.07475.ed@leafe.com> On Sunday 31 July 2005 10:32, Torsten Bronger wrote: > > I know I'm diving into this conversation late, and I haven't read > > the whole thread, but has someone yet mentioned the "anygui" > > project? ?This has stalled, but it was IMHO a good idea. > > > I don't know exactly why this project died, but I'd start with a > Pythonic variant of wxPython. ?I've read many discussions about the > people who didn't like the wxPython's C++ style, so there are > chances to get fellow developers and users. ?You must reach the > critical mass quickly in order to get a survivable project, and > being not too far away from an existing one is a good stating point. > > Possibly Dabo manages such a thing. We certainly are striving for such a goal. And while Dabo only supports wxPython now, we've designed the UI layer so that it is toolkit-agnostic (in theory, at least). After we have a full, robust implementation using wxPython, we then plan on implementing Tkinter and Qt, assuming that there is demand for those toolkits. But since UIs are incredibly complex beasts, we've chosen to tackle one at a time, and after looking at them all and considering different issues, we chose wxPython as the best toolkit for creating platform-independent apps. -- -- Ed Leafe -- http://leafe.com -- http://dabodev.com From steven.bethard at gmail.com Sun Jul 31 18:35:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 31 Jul 2005 16:35:27 -0600 Subject: python-dev summary for 2005-07-01 to 2005-07-15 Message-ID: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-07-01_2005-07-15.html] ============= Announcements ============= ------------------------------ QOTF (Quotes of the Fortnight) ------------------------------ Marc-Andre Lemburg provides perhaps the best summary to date of `how strings and Unicode should be used`_ in Python: To untie this Gordian Knot, we should use strings and Unicode like they are supposed to be used (in the context of text data): * strings are fine for text data that is encoded using the default encoding * Unicode should be used for all text data that is not or cannot be encoded in the default encoding Later on in Py3k, all text data should be stored in Unicode and all binary data in some new binary type. On a more entertaining note, Anthony Baxter describes the general outlook outlook on handling `threads vs signals`_: threads vs signals is a platform-dependant trail of misery, despair, horror and madness .. _how strings and Unicode should be used: http://mail.python.org/pipermail/python-dev/2005-July/054854.html .. _threads vs signals: http://mail.python.org/pipermail/python-dev/2005-July/054832.html ========= Summaries ========= --------------------------------------- PEP 343 Documentation: Context Managers --------------------------------------- Raymond Hettinger started a thread discussing how objects with __enter__ and __exit__ methods should be referred to in the official Python documentation. A few terms were thrown around, with "resource manager" being one of the early favorites. However, because the __enter__/__exit__ protocol handles a much more general construct that just the acquisition and release of a resource, this term steadily lost ground. Things like "locking objects are resource managed" and "decimal.Context() is a resource manager" sounded awkward and hard to explain. Phillip J. Eby suggested that objects with __enter__ and __exit__ methods could be called "context managers", and people seemed generally happy with this term. Nick Coghlan took this term, and some example use cases for "context managers", and put together a `draft documentation`_ for the section in the Python Library Reference. People liked Nick's wording, and after a few minor revisions (mainly to add more examples), it looked pretty complete. Nick promised to add a bit to the Python tutorial after he got a chance to play with the PEP 342_/343_ implementations. There was also a brief followup thread that discussed which objects in the stdlib should gain __enter__ and __exit__ methods in Python 2.5. It looks like decimal.Context objects will almost certainly become context managers, and there is some chance that a sys.redirected_stdout context manager might appear. .. _draft documentation: http://www.python.org/sf/1234057 .. _342: http://www.python.org/sf/1223381 .. _343: http://python.org/sf/1235943 Contributing threads: - `Terminology for PEP 343 `__ - `Terminology for PEP 343 `__ - `'With' context documentation draft (was Re: Terminology for PEP 343 `__ - `PEP 343 documentation on Sourceforge Patch tracker `__ - `Possible context managers in stdlib `__ [SJB] ----------------------- GCC/G++ Issues on Linux ----------------------- While in the past Python and Python extension modules could be compiled on Linux with different GCC versions as long as the 'C' ABIs were compatible, David Abrahams reported that Python extensions on Linux now crash if they are not compiled with exactly the same version of GCC as the Python they're loaded into. This is apparently due to the fact that on these systems Python is being linked with CXX when it should be linked with CC. The solution turned out to be to pass --without-cxx to configure; if it is not specified, configure runs a linking test that (improperly) determines that linking with CXX is necessary. When the --without-cxx flag is specified, configure does not perform this linking test, so Python is linked with CC. In the same discussion, Christoph Ludwig pointed out another problem in the above linking test. The current test compiles a single translation unit program using CXX and sees if linking it using CC fails. For GCC 3.x, it does, but because GCC 4.0 does a better job of eliminating unreachable code, with GCC 4.0 it does not. Thus make fails using GCC 4.0. Christoph showed that compiling a program with two tranlation units, one of which calls an 'extern "C"' function in the other, restores the original behavior. He provided the corresponding patch_ to configure.in. While Christoph's patch stops make from failing on Linux with ELF shared binaries and GCC 4.x, it did not address David Abrahams original concern -- that on Linux with ELF shared binaries and GCC 3.x or 4.x, configure should determine that Python can be compiled *without* CXX. Christoph promised to work on a more comprehensive patch to address this problem for Python 2.5. .. _patch: http://www.python.org/sf/1239112 Contributing threads: - `GCC version compatibility `__ - `Linux Python linking with G++? `__ - `[C++-sig] GCC version compatibility `__ [SJB] -------------------------------------------------------- Behavior of Sourceforge when replying to python-checkins -------------------------------------------------------- At the moment, replying to a message in the check-ins list defaults to directing the reply to python-dev. After this lead to some confusion, Guido questioned whether this was a good idea or not; the two main problems are that it is more difficult than necessary to send notes to the committer, and difficult to follow such threads (the past is in the check-in message, and future messages might be on python-dev or the check-ins list). Only one person replied to Guido's suggestion (agreeing) - nothing appears to have changed so far, so it seems that perhaps the status quo rules. Contributing thread: - `floatobject.c 2.136 `__ [TAM] ---------------------------------------- Removing else clauses from while and for ---------------------------------------- Thomas Lotze suggested that an 'eltry' keyword be introduced, to be the counterpart of 'elif' for try statements; this idea was quickly shot down by Guido (the use case is rare, using both "else" and "try" is fine, a loop solution often works well). As a result, however, Guido wondered whether else clauses on for/while were a good idea, even though he dislikes flag variables. He was joined by various people, some of whom did not know (or had forgotten) that the clauses even existed - some people wondered whether they made the language harder to learn. These people were outnumbered, though, but people who felt that these loop else clauses were an elegant part of the language and should definitely stay. Interestingly, Guido noted that he wonders whether "elif" was a mistake, and should have been "else if" (although there was no indication that he felt that this should be changed in Python 3000). Contributing thread: - `Chaining try statements: eltry? `__ [TAM] --------------------------------------------------------- Adding Syntactic Support for Instance Variable Assignment --------------------------------------------------------- Ralf W. Grosse-Kunstleve asked for syntactic support for the common idiom:: def __init__(self, x, y, z): self.x = x self.y = y self.z = z using the syntax:: def __init__(self, .x, .y, .z): pass People pointed out that with a properly-defined initialize() function you could use existing Python syntax and only need a single function call in __init__:: def __init__(self, x, y, z): initialize(self, locals()) The thread_ was moved to comp.lang.python before it had a chance to turn into a decorator-syntax-like discussion. ;) .. _thread: http://mail.python.org/pipermail/python-list/2005-July/288292.html Contributing thread: - `reducing self.x=x; self.y=y; self.z=z boilerplate code `__ [SJB] ------------------------------------- Changing Triple-quoted String Parsing ------------------------------------- Andrew Durdin suggested a change in the way that triple-quoted strings are parsed. Strings like:: myverylongvariablename = """\ This line is indented, But this line is not. Note the trailing newline: """ would have the initial indents on all lines but the first ignored when they were parsed. People seemed generally to dislike the proposal, for a number of reasons: - "It smells too much of DWIM, which is very unpythonic" -- Guido - it is backwards incompatible in a number of ways - textwrap.dedent covers pretty much all of the use cases Andrew Durdin said he would write the PEP anyway so that at least if the idea was rejected, there would be some official documentation of the rejection. Contributing thread: - `Triple-quoted strings and indentation `__ [SJB] ----------------------- path module and Unicode ----------------------- Continuing last month's discussion on including the path module in the standard library, Neil Hodgson pointed out that path makes it easier to handle Unicode directory paths on Windows-based platforms; currently, this requires user code. Further replies pointed out similar Unicode handling problems in sys.argv and os.listdir, leading Guido to comment, "Face it. Unicode stinks (from the programmer's POV). But we'll have to live with it." Neil boiled this down to four high-level strategies for dealing with attributes that can Unicode: always returning Unicode, returning Unicode only when a value can't be represented in ASCII, returning Unicode only when a value can't be represented in the current code page, or creating "separate-but-equal" APIs (like sys.argvu and os.environu). Marc-Andre Lemburg and Guido both expressed strong preferences for the second option, with Marc-Andre formulating the rule as presented in this issue's QotF. Contributing threads: - `Adding the 'path' module (was Re: Some RFE for review) `__ - `Adding the 'path' module (was Re: Some RFE for review) `__ - `Adding the 'path' module (was Re: Some RFE for review) `__ [TDL] -------------------------------------- Improving decimal module documentation -------------------------------------- Facundo Bastista couldn't find the explanation of the decimal module's rounding modes. Nick Coghlan helped him find it in section for `Context objects`_ but noted that the wording for the round-half modes was sparse. Raymond Hettinger then improved the docs by adding a few words to the effect that the various round-half modes are rules for breaking ties when two integers are equally near. He also switched the presentation from paragraph-form to list-form so to make it easier to find and read. .. _Context objects: http://docs.python.org/lib/decimal-decimal.html Contributing threads: - `Decimal rounding doc `__ - `Missing docs (was Decimal rounding doc) `__ [TAM] ---------------- getch() behavior ---------------- Darryl Dixon pointed out that the getpass() function in the getpass module does not accept extended characters on Windows, where the msvcrt module is used to capture one character at a time from stdin via the _getch() function defined in conio.h. Windows supports `capturing extended characters`_ via _getch, but it requires making a second call to getch() if one of the 'magic' returns is encountered in the first call (0x00 or 0xE0). Darryl asked whether a patch for the msvcrt module that added support for capturing extended characters would be considered. However, no support was received (although it was suggested that a patch submitted through sourceforge, possibly implemented via a new function, would be considered), as the thinness of the msvcrt wrapper is intentional, and it was not clear that this was a problem (i.e., that two calls could not be made). .. _capturing extended characters: http://support.microsoft.com/default.aspx?scid=kb;en-us;57888 Contributing threads: - `getch() in msvcrt does not accept extended characters. `__ - `getch() in msvcrt does not accept extended characters. `__ [TAM] ------------------- Threads and signals ------------------- Florent Pillet noticed that when using Python 2.3 on Max OS X, calling tmpfile() from a C extension had the side-effect of disabling Control-C keyboard interruption (SIGINT). Further digging revealed that on both Darwin and FreeBSD platforms, tmpfile() does play with the signal handling, but appears to change it back. Michael Hudson noted that Florent's code also involved threads, and that mixing threads and signal handling involved "enormously subtle" issues. Anthony Baxter also replied that Python 2.4 should be less subject to harmful effects from these bugs, but as a rule, mixing threads and signals is a recipe for "misery, despair, horror, and madness." Contributing threads: - `C bindings calling tmpfile() blocks interrupt signal `__ [TDL] -------- List API -------- Nicolas Fleury proposed adding copy() and clear() functions to lists, to be more consistent with dict and set. It was pointed out that the copy module (copy.copy()) can be used for generic copying, or a copy constructor and that clearing can be done with slicing (seq[:] = []) or the del keyword (del seq[:]). The advocate of the clear method argued that a clear() method would be easy to find in documentation, and wouldn't require understanding slicing to use it, but none of the developers would agree to expand the API just to add a third-way to do it, so it seems unlikely that anything more will come of this at this time. Raymond Hettinger also noted that slicing is one of the first concepts presented in the tutorial -- it is so basic to the language that it would be a mistake steer people away from learning it. Contributing threads: - `List copy and clear (was Re: Inconsistent API for sets.Set and build-in set) `__ - `List copy and clear (was Re: Inconsistent API for sets.Set and build-in set) `__ [TAM] ------------ Money Module ------------ Facundo Batista announced that the `Money module`_ is taking form quickly, a "pre-PEP", and unit tests have been written. Raymond Hettinger and Aahz noted that a "pre-PEP" is really a misnomer: PEPs describe enhancements to the Python core and standard library, while Money is still rather experimental and unlikely to see inclusion anytime soon. Facundo invited any interested parties to join the discussion in the pymoney-general list on SourceForge. .. _Money module: http://sourceforge.net/projects/pymoney Contributing threads: - `Money module `__ [TDL] ------------------------ Bug-reporting Checklists ------------------------ Brett Cannon posted a draft of a checklist to help users report bugs. Several minor improvements were suggested, but Raymond Hettinger expressed mild dislike for the idea, describing it as "administrivia" that might actually prevent people from filing bugs. Terry Reedy suggested, along with the checklists, some minor changes to the structure of the python.org site (to define bugs, help determine whether a bug has already been reported, etc.) would help even more. Contributing threads: - `checklist for filing a bug `__ [TDL] =============== Skipped Threads =============== - `how to create single exe dos file `__ - `cephes module missing `__ - `Inconsistent API for sets.Set and build-in set `__ - `python-dev Summary for 2005-06-16 through 2005-06-30 [draft] `__ - `using pyhon from the MSYS shell `__ - `Possible C API problem? `__ - `Weekly Python Patch/Bug Summary `__ - `Expanding max chunk size to 4GB. `__ - `Request to add developer `__ - `C bindings calling tmpfileblocks interrupt signal `__ - `Another SoC student for CVS access `__ - `__autoinit__ `__ - `SF patch #1214889 - file.encoding support `__ - `e-mail addresses `__ - `[Python-checkins] python/dist/src/Miscdevelopers.txt, 1.15, 1.16 `__ - `Is PEP 237 final -- Unifying Long Integers and Integers `__ - `Python on PyPI `__ ======== Epilogue ======== ------------ Introduction ------------ This is a summary of traffic on the `python-dev mailing list`_ from July 01, 2005 through July 15, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the seventh summary written by the python-dev summary cabal of Steve Bethard, Tim Lesher, and Tony Meyer. To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tim Lesher (tlesher at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. I do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow me to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/ .. _original text file: http://www.python.org/dev/summary/2005-07-01_2005-07-15.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From fdeserres at gmx.net Wed Jul 13 13:31:44 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 19:31:44 +0200 Subject: Building a function call? (update) In-Reply-To: <42d53131$1@nntp0.pdx.net> References: <42D50A88.3070909@gmx.net> <42d53131$1@nntp0.pdx.net> Message-ID: <42D55000.7050502@gmx.net> Scott David Daniels wrote: >Francois De Serres wrote: > > >>Francois De Serres wrote: >> >> >>>Having a string: "dothat" >>>and a tuple: (x, y) >>>1. What's the best way to build a function call like: dothat(x,y)? >>> >>>Assuming dothat is def'd in the same module, >>>2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) >>>the right way to have it executed? >>> >>> > >You do know that you could do something like: > result = eval('dothat')(100, 200) > >That is, eval of the function name gives you a function. > >--Scott David Daniels >Scott.Daniels at Acm.Org > > No I did not know. And, that, is smart! Many thanks, F. From reid at reidster.net Mon Jul 11 19:45:20 2005 From: reid at reidster.net (Reid Priedhorsky) Date: Mon, 11 Jul 2005 18:45:20 -0500 Subject: Access descendant class's module namespace from superclass Message-ID: Dear group, I'd have a class defined in one module, which descends from another class defined in a different module. I'd like the superclass to be able to access objects defined in the first module (given an instance of the first class) without importing it. Example of what I'm looking for: <<>> class Spam(object): def fish(self): a = self.__module__.Ham() <<>> import spam class Eggs(spam.Spam): pass class Ham(object): pass The above doesn't work because __module__ is a string, not a module object: >>> import eggs >>> b = eggs.Eggs() >>> b.fish() Traceback (most recent call last): File "", line 1, in ? File "spam.py", line 3, in foo a = self.__module__.Ham() AttributeError: 'str' object has no attribute 'Ham' (I suppose I could call __import__(self.__module__), but that seems kind of awkward.) Is this possible using Python 2.3? Any better ways to accomplish this? Thanks very much for any help, Reid From rrr at ronadam.com Mon Jul 18 15:21:04 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 18 Jul 2005 19:21:04 GMT Subject: Efficiently Split A List of Tuples In-Reply-To: <1121670421.128485.262420@g47g2000cwa.googlegroups.com> References: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> <1121670421.128485.262420@g47g2000cwa.googlegroups.com> Message-ID: Simon Dahlbacka wrote: > Oooh.. you make my eyes bleed. IMO that proposal is butt ugly (and > looks like the C++.NET perversions.) I haven't had the displeasure of using C++.NET fortunately. point = [5,(10,20,5)] size,t = point x,y,z = t size,x,y,z = point[0], point[1][0], point[1][1], point[1][2] size,x,y,z = point[0], ^point[1] # Not uglier than the above. size,(x,y,z) = point # Not as nice as this. I forget sometimes that this last one is allowed, so ()'s on the left of the assignment is an explicit unpack. Seems I'm tried to reinvent the wheel yet again. Cheers, Ron From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 03:34:51 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 09:34:51 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kehbmFtv6lpU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> Message-ID: <3kjj0sFukvmcU1@individual.net> Reinhold Birkenfeld wrote: > Hi, > > the arguments in the previous thread were convincing enough, so I made the > Path class inherit from str/unicode again. Current change: * Add base() method for converting to str/unicode. * Allow compare against normal strings. Reinhold From cjw at sympatico.ca Sat Jul 2 10:05:03 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 02 Jul 2005 10:05:03 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: Gregory Pi?ero wrote: > While that policy does make sense, I think a database program falls > somewhere in between an OS and an everyday third party program. For > web developers, the database might as well be the OS. I use the > database to store everything in my web app. That way I can just worry > about 1 place to access information and not have to fool with files > and other OS issues. > > So I humbly suggest the policy should be : > > Python will not include interface code for third party programs which > are not part of an operating system or database system. > > ... Isn't this where the discussion should start? There should be some general policy guiding the types of modules which should be in the standard library. Clearly, size is a factor as the msi version of Python 2.4 is now 10 MB. if there were some sort of package manager which took account of dependencies would that reduce the need to expand the standard library? Colin W. > But I have no experience in designing world class programming > langauges so forgive me if I am too bold. > > -Greg > > > On 6/29/05, Rocco Moretti wrote: > >>Paul Rubin wrote: >> >>>Gregory Pi?ero writes: >>> >>> >>>>I'd like to see some database API's to the most common databases >>>>included. >>> >>>Yes, certainly, this is a serious deficiency with Python. >> >>Except that (please correct me if I'm wrong) there is somewhat of a >>policy for not including interface code for third party programs which >>are not part of the operating system. (I.e. the modules in the standard >>libary should all be usable for anyone with a default OS + Python install..) >> >>A notable exception is the dbm modules, but I seem to recall hearing >>that the official position is that it was a mistake. (Now only kept for >>backward compatability.) >>-- >>http://mail.python.org/mailman/listinfo/python-list >> From mediocre_person at hotmail.com Mon Jul 25 00:19:48 2005 From: mediocre_person at hotmail.com (Terrance N. Phillip) Date: Sun, 24 Jul 2005 23:19:48 -0500 Subject: Problem loading a file of words In-Reply-To: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> Message-ID: <42e46873$1_2@alt.athenanews.com> Kevin, I'm pretty new to Python too. I'm not sure why you're seeing this problem... is it possible that this is an "out-by-one" error? Is zymotechnics the *last* word in dictionary.txt? Try this slightly simplified version of your program and see if you have the same problem.... def sort_string(word): '''Returns word in lowercase sorted alphabetically''' return "".join(sorted(list(word.lower()))) dictionary = {} f = open('/usr/bin/words') # or whatever file you like for line in f: sline = sort_string(line[:-1]) if sline in dictionary: dictionary[sline].append(line) else: dictionary[sline] = [line] f.close() lookup = raw_input('Enter a scrambled word : ') while lookup: try: results = dictionary[sort_string(lookup)] for x in results: print x, print except: print "?????" lookup = raw_input('Enter a scrambled word : ') Good luck, Nick. From andreas at kostyrka.org Wed Jul 13 04:23:00 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 10:23:00 +0200 Subject: threads and sleep? In-Reply-To: <11cnr7tsn7m25d8@corp.supernews.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <6ijmc1d5f066he8p09a406irsdabbh6ljc@4ax.com> <11cnr7tsn7m25d8@corp.supernews.com> Message-ID: <1121242980.5240.79.camel@andi-lap> Am Mittwoch, den 06.07.2005, 14:38 +0000 schrieb Grant Edwards: > > Unfortunately that means you've got to debug a number cruncher > that's written in C. If one is careful, one can use Pyrex :) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From spam.csubich+block at block.subich.spam.com Tue Jul 12 15:43:46 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 12 Jul 2005 15:43:46 -0400 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: Dark Cowherd wrote: > But one advise that he gives which I think is of great value and is > good practice is > "Always catch any possible exception that might be thrown by a library > I'm using on the same line as it is thrown and deal with it > immediately." That's fine advice, except for when it's not. Consider the following code: try: f = file('file_here') do_setup_code do_stuff_with(f) except IOError: # File doesn't exist error_handle To me, this code seems very logical and straightfoward, yet it doesn't catch the exception on the very next line following its generation. It relies on the behavior of the rest of the try-block being skipped -- the "implicit goto" that Joel seems to loathe. If we had to catch it on the same line, the only alternative that comes to mind is: try: f=file('file_here') except IOError: #File doesn't exist error_handle error_flag = 1 if not error_flag: do_setup_code do_stuff_with(f) which nests on weird, arbitrary error flags, and doesn't seem like good programming to me. From williams13 at llnl.gov Fri Jul 22 10:09:08 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Fri, 22 Jul 2005 07:09:08 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E0E281.6060009@llnl.gov> References: <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> Message-ID: <42E0FE04.7040709@llnl.gov> Hi Jason, To be more specific. If I try to import socket I get the "ImportError: No module named _socket". What do I need to install from Cygwin in order for this to work? Thanks, Dean > > > Hi Jason, > > I downloaded your new Cygwin from http://cygwin.com and tried to > build install Python/CDAT again. It appears to have built properly, > but when I try to execute, it receive a sock error. How do I get > around this problem? > > When I built Cygwin, I instructed it to install everything. > > Thanks in advance for your help and best regards, > Dean > > From renato.ramonda at gmail.com Wed Jul 6 14:25:42 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Wed, 06 Jul 2005 20:25:42 +0200 Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: Terry Hancock ha scritto: > > Yep, this is what I just set up in my .vimrc. Works beautifully. And (you probably already know, but it could be of use to others) you can bind the activation of some or all of those commands to au (autocommand) depending on the file extension. That way you can have 8 spaces real tabs in C files, for examples, without touching your conf. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From rbt at athop1.ath.vt.edu Mon Jul 18 13:53:08 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 18 Jul 2005 13:53:08 -0400 Subject: Python scripts wont run - HELP In-Reply-To: References: Message-ID: <1121709188.16026.7.camel@athop1.ath.vt.edu> On Mon, 2005-07-18 at 17:22 +0100, John Abel wrote: > windozbloz wrote: > > >Bye Bye Billy Bob... > > > >Hello All, > >I'm a fairly literate windoz amateur programmer mostly in visual basic. I > >have switched to SuSE 9.2 Pro and am trying to quickly come up to speed > >with Python 2.3.4. I can run three or four line scripts from the command > >line but have not been able to execute a script from a file. > > > >I have used EMACS and JEDIT to create small test routines. I would right > >click the file and set properties to executable. I would then click the > >icon, the bouncy ball would do its thing then a dialog box would flash on > >the screen for a fraction of a second. I could tell it had a progress bar > >on it but could not catch anything else on it. Then nothing else would > >happen. > > > >If I could execute a script the world would once again be my playground... > >PLEASE HELP. > > > > > > > > > > > You will need to include > > #!/usr/bin/python > > At the top of your script. > > HTH > > J Or, better yet: #!/usr/bin/env python ;) From peter at engcorp.com Tue Jul 26 16:08:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Jul 2005 16:08:04 -0400 Subject: GUI - Windows: Where to get started In-Reply-To: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: Ernesto wrote: > Would anyone know a good place to start for learning how to build > simple GUI's in Windows XP? I just want users to be able to select a > few parameters from a pull-down menu, then be able to run some batch > files using the parameters from the pull down menus. I would also need > a "Browse" menu, so users could point to a place on the local disc (ie > C:\PointSystemHere). If you would like to try using wxPython, download and install both it and the Demo/Docs package, then run the wxPython Demo from your Start Menu. It demonstrates a huge variety of features, including pull-down menus and even (as I recall) running external commands, and more than that the demo itself provides access to the source code for each feature so that you can copy and paste into your own program (and edit, of course, since it's never a perfect fit as-is). Of course wxPython is just one possible approach to doing GUI work with Python, and not necessarily the best. With Python it's easy to quickly try out each of the main contenders (including Tkinter which, as someone mentioned, is included standard in Python), so there's no excuse for not experimenting for an hour first... -Peter From rkern at ucsd.edu Sun Jul 24 12:06:29 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 09:06:29 -0700 Subject: tuple to string? In-Reply-To: <42E36CA9.5070403@gmx.net> References: <42E0EED4.4020001@gmx.net> <42E36CA9.5070403@gmx.net> Message-ID: Francois De Serres wrote: > I'll pick ('%c' * len(t)) % t, for it's readability and the fact that > join() is on the deprec'd list. ''.join() is certainly not deprecated. What made you think that? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From duncan.booth at invalid.invalid Thu Jul 21 06:14:43 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jul 2005 10:14:43 GMT Subject: Lots of pdf files References: Message-ID: Greg Lindstrom wrote: > I'm running Python 2.3 on a Linux system and have lots (about 2000) > files in pdf format to print each day. If I just wind up and fire all > the files at the printer at once (as 2000 separate print jobs), the > print server throws a fit and our system admin comes down and slaps me > around for a few minutes (which, I guess, is fair). > > There does not appear to be a simple way to merge many pdf's into one. > I could, for example, merge all of the files for a particular provider > into one pdf for that provider and then print it (or, better > yet...encrypt it and ship it!), but I do not see a way. > A quick Google search turns up lots of program which claim to merge PDFs files. e.g. http://www.verypdf.com/pdfpg/index.html (for a mere $29.90, except it is GPL'd so I'm not sure what the money is for). Or perhaps PDCAT, http://www.pdf-tools.com/asp/products.asp?name=CLE for $150, or $250 if you want to be able to encrypt the output and ship it. From gene.tani at gmail.com Sat Jul 23 13:52:27 2005 From: gene.tani at gmail.com (gene tani) Date: 23 Jul 2005 10:52:27 -0700 Subject: PostgreSQL & Python vs PHP In-Reply-To: <1122139628.703635.48610@g14g2000cwa.googlegroups.com> References: <3kfaucFu3tlfU1@individual.net> <1122139628.703635.48610@g14g2000cwa.googlegroups.com> Message-ID: <1122141147.604862.54030@g49g2000cwa.googlegroups.com> ok, to make this less open-ended, you should mention what O/S and web server you have in mind, whether the web and DB servers will be under your admin (big diff betw python and PHP, as far as finding shared server accounts at web hosts), what kinds of queries, concurrent read/write volumes, transactions, dirtiness, etc. etc Also if you build your questions to this newsgroup on past threads you've read, you will get absolute superb information, I guarantee it. From tjreedy at udel.edu Thu Jul 7 16:15:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jul 2005 16:15:38 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com><1120635034.080123.218060@g47g2000cwa.googlegroups.com><1120636418.166800.42290@o13g2000cwo.googlegroups.com><1120642040.109796.212450@o13g2000cwo.googlegroups.com> Message-ID: "Antoon Pardon" wrote in message news:slrndcpoan.5vp.apardon at rcpc42.vub.ac.be... > I'll clarify. A lot of the time I hear arguments against > features that boils down to. > > 1) I don't need it. > > 2) Having the feature will make my job more difficult. > > 3) I don't understand the merrits of the feature or I > have difficulty understanding what it does when I > encounter it. > > IMO these are arguments if followed sufficiently will lead to > a language that is only usefull for mediocre programmers. True. But these arguments did not stop expert-level features like metaclasses, decorators, and (in 2.5) context-management blocks (with-blocks). TJR From darkcowherd at gmail.com Tue Jul 12 13:10:18 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Tue, 12 Jul 2005 22:40:18 +0530 Subject: Help with inverted dictionary In-Reply-To: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> Message-ID: <5f4d3cb5050712101053acc5e7@mail.gmail.com> As Steven said this looks too much like home work But what the heck I am also learning python. So I wrote a small program. A very small program. I am fairly new to Python, I am stunned each time to see how small programs like this can be. Since I am also learning can somebody comment if anything here is not Pythonesque. dictwords = dict() for line in open('testfile.txt','r'): for word in line.rstrip('\n').split(): dictwords.setdefault(word,set()).update((line.rstrip('\n'),)) for wordfound in dictwords.items(): open(wordfound[0],'w').write('\n'.join(wordfound[1])) From nephish at xit.net Wed Jul 27 07:29:33 2005 From: nephish at xit.net (nephish at xit.net) Date: 27 Jul 2005 04:29:33 -0700 Subject: question about deleting records from mysql Message-ID: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> Hey there, sorry , second question in as many days. i am trying to do some stuff with MySQLdb and the thing is, i can select records and such, but when i try to delete them, they dont really go away. like this >>> cursor.execute("DELETE FROM table WHERE autoinc > 1000") 240L >>> cursor.execute("SELECT * FROM table WHERE autoinc > 1000") 0L so it looks like it worked, but when i use something else to look at the table (phpmyadmin, mysql-query-browser, knoda) the records are still there! what do i do? From gene.tani at gmail.com Fri Jul 1 01:20:59 2005 From: gene.tani at gmail.com (gene tani) Date: 30 Jun 2005 22:20:59 -0700 Subject: Escaping commas within parens in CSV parsing? In-Reply-To: <1120188654.466828.257540@g44g2000cwa.googlegroups.com> References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> <1120188654.466828.257540@g44g2000cwa.googlegroups.com> Message-ID: <1120195259.579766.232640@g14g2000cwa.googlegroups.com> Why don't you use a different delimiter when you're writing the CSV? From lbates at syscononline.com Thu Jul 7 09:41:56 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 07 Jul 2005 08:41:56 -0500 Subject: Windows Cmd.exe Window In-Reply-To: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: <42CD3124.2010202@syscononline.com> Use sys.excepthook to hook a function you define and in that function print a traceback and pause before exiting. Something like (not tested but copied from working example): import sys def Myexcepthook(type, value, traceback): print "in Myexcepthook-type=", type," value=",value," traceback=",traceback import traceback lines=traceback.format_exception(type, value, traceback) print "---------------------Traceback lines-----------------------" print "\n".join(lines) print "-----------------------------------------------------------" t=raw_input("Press return to continue") sys.exit(2) # # set sys.excepthook # sys.excepthook=Myexcepthook # # create an uncaught divide by zero exception # a=1/0 -Larry Bates Giles Brown wrote: > For my sins I'm a MS Windows user at work and apart from that I have a > small problem ... > > I like to write python scripts to do small tasks and then double click > on them from the file explorer to run them. > > Unfortunately I'm not perfect and sometimes I make mistakes and have > unhandled exceptions or syntax errors when running the scripts. The > default behaviour is to shut down the command window which leaves you > no chance of reading the exception. > > In the past I have created .bat wrapper files that just call the python > interpreter, but it is a bit tedious to have to create a matching .bat > file for every script. So I came up with the following approach... > > 1. Copy python.exe to pythoncmd.exe > 2. Add a bit of stuff to sitecustomize.py > 3. Add a special first line to every python script and give it a .cmd > extension. > > The stuff added to sitecustomize.py (actually I created a > sitecustomize.py for this) is: > """ > import sys > import os > > if os.path.basename(sys.executable) == 'pythoncmd.exe': > > def cmdexcepthook(*args): > sys.__excepthook__(*args) > # Let use confirm/inspect error > os.system('pause') > > sys.excepthook = cmdexcepthook > """ > > The special first line is: > > @pythoncmd -x "%~f0" %* & exit /b > > (In the python.org FAQ for windows it says > @setlocal enableextensions & python -x %~f0 %* & goto :EOF > but since I have no idea which is "right" I chose the simpler looking > one) > > This approach does require pythoncmd.exe to by in your %PATH% but I > think that is reasonable ;) > > I am a bit disappointed I couldn't think of a way of deciding if I was > running a ".cmd" file in sitecustomize.py so that I could just use the > normal python.exe. Using a renamed interpreter .exe is just a trick > for detecting when I am running .cmd files, but it means that the > script won't run on another machine that hasn't had the python.exe > copied to pythoncmd.exe on it. Which is a shame. > > So my question. Is there a better way? I'm not really happy with this > approach. Should I stop worrying and go and play my new ukulele? > Answers please. > > Giles > From xen0n at vodafone.it Mon Jul 18 06:32:01 2005 From: xen0n at vodafone.it (xen0n at vodafone.it) Date: 18 Jul 2005 03:32:01 -0700 Subject: Python s60 Message-ID: <1121682721.727110.91100@g14g2000cwa.googlegroups.com> Hi, I have looked around for any type of example of script that claims to read the contacts database from an s60 phone, but i cant figure how to use that examples. All i want is a simple, CLEAR, script that show how to open contact database of an s60 phone and load all contacts present into a listbox, nothing else. This will be easy for the experts! please help me! Thanks in advance! From mwm at mired.org Fri Jul 1 13:50:12 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 13:50:12 -0400 Subject: No subject References: Message-ID: <86acl65sbv.fsf@bhuda.mired.org> Harry George writes: >> > - more available libraries and more advanced developement tools. > If the library is in C, C++, or FORTRAN, Python can use it. Worst > case you have to write your own bindings. Are there really that many more libraries for C++? I'm not talking about data structures that you'd replace with builtins, I'm talking about high level libraries that deal with real world things. As a couple of examples, I went looking for something like smtplib. The only thing I turned up was a windows-only smtp/pop library. I also tried finding a C++ version of mailbox, and the best I could do was the GNU mailutils library. And that's in C, not C++. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From grante at visi.com Wed Jul 6 10:38:53 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Jul 2005 14:38:53 -0000 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <6ijmc1d5f066he8p09a406irsdabbh6ljc@4ax.com> Message-ID: <11cnr7tsn7m25d8@corp.supernews.com> On 2005-07-06, Dennis Lee Bieber wrote: > On Tue, 05 Jul 2005 16:01:23 -0000, Grant Edwards > declaimed the following in comp.lang.python: > >> Or is the Python interpreter actually doing the context >> switches itself? > > It would seem to be close to doing that, if it has that internal > "quantum" of releasing the GIL every 100 bytecodes... Right, but I think that's just _allowing_ a context switch rather than performing one. The other interpreters are blocked waiting for the GIL and releasing it lets one of them run. Though the effect is pretty much the same, it's quite different than having a single interpreter that does the scheduling and context switching itself within a single OS process/thread. > At the least, the GIL release/reacquire would be similar to > having a C-language program doing sleep() to let other tasks > run. I'll admit that I don't know if creating a Python thread > also creates a new interpreter from scratch (after all, > Windows doesn't have a fork() operation). If I were doing it, I don't think I'd use fork() and create a second address space. I'd use a "lightweight" thread. All of the interpreter instances would share a single address space. I know that Win32 has threads. > It may be that the GIL toggle is part of a thread state > save/restore operation, and could thereby be looked on as a > high-level context switch with the OS-level context switch > basically selecting from the threads blocked on the GIL. Right -- I think that's what's hapenning. I really ought to go look at the CPython source code instead of just sputing conjecture. > {I'm going to louse up the message tracking here by pasting part of your > follow-up into one response} > > 2> Upon further thought, that just can't be the case. There has > 2> to be multiple instances of the intepreter because the > 2> interpreter can make C system calls that block (thus blocking > 2> that instance of the interpreter). Other Python threads within > 2> the program continue to run, so there must be multiple Python > 2> intepreters. > > From the documentation: > > """ > The lock is also released and reacquired around potentially blocking I/O > operations like reading or writing a file, so that other threads can run > while the thread that requests the I/O is waiting for the I/O operation > to complete. > """ I know. I've worked on modules that release the GIL and call blocking operations. My point is that when an interpreter calls a blocking operation, the interpreter itself blocks. It stops running. It goes to sleep. But, other Python threads keep running, so there must be other interpreters running those threads. > Otherwise, I'd say convert the number cruncher to a compiled > module that can be started as a Python thread, drop into the > compiled code, give up the GIL, and crunch away -- only > acquiring the GIL when it has results to give back. Unfortunately that means you've got to debug a number cruncher that's written in C. -- Grant Edwards grante Yow! I'm shaving!! I'M at SHAVING!! visi.com From spam.csubich+block at block.subich.spam.com Sun Jul 3 19:17:23 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 19:17:23 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <1120424454.854518.100610@o13g2000cwo.googlegroups.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> <1120424454.854518.100610@o13g2000cwo.googlegroups.com> Message-ID: Carl Banks wrote: > > Christopher Subich wrote: >>I've heard this said a couple times now -- how can listcomps not >>completely replace map and filter? > If you're doing heavy functional programming, listcomps are > tremendously unwieldy compared to map et al. Interesting; could you post an example of this? Whenever I try to think of that, I come up with unwieldly syntax for the functional case. In purely functional code the results of map/filter/etc would probably be directly used as arguments to other functions, which might make the calls longer than I'd consider pretty. This is especially true with lots of lambda-ing to declare temporary expressions. From mwh at python.net Mon Jul 25 08:06:42 2005 From: mwh at python.net (Michael Hudson) Date: Mon, 25 Jul 2005 12:06:42 GMT Subject: What license to choose for Python programs? (PSF License vs. GPL/LGPL) References: Message-ID: volker_grabsch at v.notjusthosting.com (Volker Grabsch) writes: > Hi! > > I noticed that many packages in the PyPI are using the PSF License. > Does this have a special reason? Lots of people are misguided, maybe. Anyway, you want to be reading this: http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq Cheers, mwh -- Roll on a game of competetive offence-taking. -- Dan Sheppard, ucam.chat From mkent at webmd.net Thu Jul 21 15:23:38 2005 From: mkent at webmd.net (mkent at webmd.net) Date: 21 Jul 2005 12:23:38 -0700 Subject: PEP on path module for standard library References: Message-ID: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> I really love Jason's 'path' module. Sadly, I've encountered a serious problem with using it. When you try to 'freeze' an application module, and Jason's 'path' module is present in any of the directories that are looked at by freeze's module finder (your app doesn't have to import it), freeze goes into an infinite loop of imports, eventually getting a 'maximum recursion depth' exception. This seems to be related to freeze getting confused between 'os.path' and Jason's 'path'. I encountered this using Jason's latest 'path' module and Python 2.3.2. I was able to solve it for my use by renaming path.py to newpath.py and using 'from newpath import path' in my modules. I've just notified Jason about this. I presume a solution like mine will be used, and look forward to seeing Jason's module in stdlib. From none at no.chance Fri Jul 8 05:12:28 2005 From: none at no.chance (Peter Tillotson) Date: Fri, 08 Jul 2005 09:12:28 +0000 Subject: Calculating average time In-Reply-To: <1120768294.287881.169030@z14g2000cwz.googlegroups.com> References: <1120768294.287881.169030@z14g2000cwz.googlegroups.com> Message-ID: have a look at the "timeit" module aswell GregM wrote: > Hi, > I'm hoping that someone can point me in the right direction with this. > What I would like to do is calculate the average time it takes to load > a page. I've been searching the net and reading lots but I haven't > found anything that helps too much. I'm testing our web site and hiting > +6000 urls per test. Here is a subset of what I'm doing. > > import IEC > #IE controller from http://www.mayukhbose.com/python/IEC/index.php > from win32com.client import Dispatch > import time > import datetime > from sys import exc_info, stdout, argv, exit > failedlinks = [] > links = open(testfile).readlines() > totalNumberTests = len(links) > ie = IEC.IEController() > start = datetime.datetime.today() > # asctime() returns a human readable time stamp whereas time() doesn't > startTimeStr = time.asctime() > for link in links: > start = datetime.datetime.today() > ie.Navigate(link) > end = datetime.datetime.today() > pagetext = ie.GetDocumentText() > #check the returned web page for some things > if not (re.search(searchterm, pagetext): > failedlinks.append(link) > ie.CloseWindow() > finised = datetime.datetime.today() > finishedTimeStr = time.asctime() > # then I print out results, times and etc. > > So: > 1. Is there a better time function to use? > > 2. To calculate the average times do I need to split up min, sec, and > msec and then just do a standard average calculation or is there a > better way? > > 3. is there a more efficient way to do this? > > 4. kind of OT but is there any control like this for Mozilla or > firefox? > > This is not intended to be any sort of load tester just a url > validation and page check. > > Thanks in advance. > Greg. > From ahabib at engin.umich.edu Thu Jul 28 14:49:58 2005 From: ahabib at engin.umich.edu (Asad Habib) Date: Thu, 28 Jul 2005 14:49:58 -0400 (EDT) Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: I agree with Mustafa. After all, we are a bunch of professionals and not vagabonds hired to take pot shots at one another. - Asad On Thu, 28 Jul 2005, mustafa wrote: > Rocco Moretti wrote: > > projecktzero wrote: > > > >>but..but...It's so much more fun to unleash your anger and fire back > >>with all guns blazing fanning the flame war that most discussion groups > >>degenerate into after a couple of responses. =) > >> > >>Actually, I had some self restraint yesterday. I wanted to write a > >>ripping response to an antagonistic flame bait message on another > >>group. I wrote it, decided it wouldn't help much, and deleted it. I > >>guess I got it out of my system by just writing it. > > > > > > That's what I do. I sometimes have something I want to say, so I write > > my rant. Once I get it out of my system, I realize that it isn't adding > > anything to the discussion, and delete it. The part of my brain that > > wants to rant is happy because it got its say in, and the rest of the > > world is happier for not having to read it. > > > > I highly recommend that people try it. It works wonders. > > thats wrong. > you should atleast reprimand the person whose bieng rude. > otherwise that type of behavior spreads. > ppl have to realise that ifyou want ppl to help > asking nicely can and will do wonders > > -- > http://mail.python.org/mailman/listinfo/python-list > From mwm at mired.org Wed Jul 6 22:47:30 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 06 Jul 2005 22:47:30 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <8664vnwcvx.fsf@bhuda.mired.org> Ron Adam writes: > So doing this would give an error for functions that require an argument. > > def foo(x): > return x > > a = None > b = foo(a) # error because a dissapears before foo gets it. So how do I pass None to a function? > >>TypeError: foo() takes exactly 1 argument(0 given) > > > So they wouldn't propagate like you would expect. > > Hmmm.... interesting that would mean... lets see. > > > 1. var = None # removes ref var, this is ok > > 2. None = var # give an error of course > > 3. var = undefined_var # same as "var = None", that's a problem! > > Ok... this must give an error because it would delete var silently! > Definitely not good. So going on, on that basis. > > 4. undefined == None # Special case, evaluates to True. > > 5. def foo():return None # same as return without args > > 6. x = foo() # Would give an error if foo returns None Why? Shouldn't it delete x? > This might be an improvement over current behavior. Breaks a lot of > current code though. I don't think so. I've programmed in langauges that gave undefined variables a value rather than an exception. It almost inevitabley led to hard-to-find bugs. FORTRAN used to give all variables a type, so that a typo in a variable name could well lead to a valid expression. The technic for disabling this was baroque ("IMPLICIT BOOLEAN*1 A-Z"), but so common they invented a syntax for it in later versions of FORTRAN ("IMPLICIT NONE"). http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From duncan.booth at invalid.invalid Tue Jul 26 09:29:28 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jul 2005 13:29:28 GMT Subject: regex problem References: <42e62ff6$1@news.eftel.com> Message-ID: John Machin wrote: > So here's the mean lean no-flab version -- you don't even need the > parentheses (sorry, Thomas). > > >>> rx1=re.compile(r"""\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,""") > >>> rx1.findall("1234,2222-8888,4567,") > ['1234,', '2222-8888,', '4567,'] No flab? What about all that repetition of \d? A less flabby version: >>> rx1=re.compile(r"""\b\d{4}(?:-\d{4})?,""") >>> rx1.findall("1234,2222-8888,4567,") ['1234,', '2222-8888,', '4567,'] From duncan.booth at invalid.invalid Fri Jul 22 04:59:32 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jul 2005 08:59:32 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: George Sakkis wrote: >> Read literally, this says (at least to me) "I don't want to fix it >> because I don't think it's broke." > > Or rather "I prefer a single existing mediocre solution than two > solutions (even if the second was better)". > Except that he is open to persuasion, so the PEP has to demonstrate that the duplication is worth the benefit. Personally I think the concept of a specific path type is a good one, but subclassing string just cries out to me as the wrong thing to do. In other words, to me a path represents something in a filesystem, the fact that it has one, or indeed several string representations does not mean that the path itself is simply a more specific type of string. You should need an explicit call to convert a path to a string and that forces you when passing the path to something that requires a string to think whether you wanted the string relative, absolute, UNC, uri etc. It may even be that we need a hierarchy of path classes: URLs need similar but not identical manipulations to file paths, so if we want to address the failings of os.path perhaps we should also look at the failings of urlparse at the same time. From tzot at sil-tec.gr Sat Jul 2 06:55:00 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 13:55:00 +0300 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <70iwe.89655$yV4.47526@okepread03> Message-ID: <1ascc1du4f4trt4apvtpavv1nt7u4gb9ej@4ax.com> On Tue, 28 Jun 2005 12:58:21 -0700, rumours say that Dave Benjamin might have written: >BORT wrote: >> I am toying with the idea of teaching my ten year old a little about >> programming. I started my search with something like "best FREE >> programming language for kids." After MUCH clicking and high-level >> scanning, I am looking at Python and Forth. Both have advocates that >> say each is a great approach to learning computers. >Kids your backwards talking like if forth love will they then. I have a nephew that would love Forth only for that. The perfect language for many kids I know would be Python with boolean operators reversed. Oh, and 'print' should be 'do_NOT_print'. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From edgrsprj at ix.netcom.com Mon Jul 11 21:16:12 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Tue, 12 Jul 2005 01:16:12 GMT Subject: Posts to other newsgroups July 11, 2005 References: Message-ID: "edgrsprj" wrote in message news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... > PROPOSED EARTHQUAKE FORECASTING > COMPUTER PROGRAM DEVELOPMENT EFFORT > Posted July 11, 2005 The first posting in this series should have provided computer programming groups around the world with a good understanding of what is involved with this earthquake forecasting research effort. And I am not planning to add too many additional comments unless someone posts a response to the first report. However, a shorter summary report is being posted to a number of other newsgroups such as sci.geo.geology pointing interested parties to that first report. To see that summary report you can try visiting the sci.geo.earthquakes or alt.disasters.misc newsgroups. It briefly discusses two dramatically different approaches to doing scientific research. From cc at carmen.com Mon Jul 11 18:53:57 2005 From: cc at carmen.com (Chuck E. Cheese) Date: Mon, 11 Jul 2005 22:53:57 GMT Subject: How long is a piece of string? How big's a unit? References: <1120935315.336081.114480@g43g2000cwa.googlegroups.com> Message-ID: The correct answer to the above question How long is a piece of string? is 2 times half it's length CEC From bvande at po-box.mcgill.ca Tue Jul 12 03:03:44 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 12 Jul 2005 03:03:44 -0400 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' In-Reply-To: References: Message-ID: <42D36B50.2000108@po-box.mcgill.ca> Ric Da Force said unto the world upon 12/07/2005 02:43: > Hi, > > I have a string such as 'C1, C2, C3'. Without assuming that each bit of > text is of fixed size, what is the easiest way to change this list so that > it reads: > 'C1, C2 and C3' regardless of the length of the string. > > Regards and sorry for the newbie question, > > Ric > Hi Ric, the rsplit method of strings should get you going: >>> data = "the first bit, then the second, finally the third" >>> chunks = data.rsplit(',', 1) >>> chunks ['the first bit, then the second', ' finally the third'] >>> Best, Brian vdB From snail at objmedia.demon.co.uk Sat Jul 2 08:37:57 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Sat, 2 Jul 2005 13:37:57 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <3ih84nFlkegqU1@individual.net> <1120230975.207574.136930@f14g2000cwb.googlegroups.com> Message-ID: In message <1120230975.207574.136930 at f14g2000cwb.googlegroups.com>, Chan.Fonseka at oracle.com writes >T can be silent in England too .. > >frui' >cricke' Both of those words (fruit and cricket) have the letter T sounded. Stephen (Nationality: English). -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From mwm at mired.org Thu Jul 14 21:55:54 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 14 Jul 2005 21:55:54 -0400 Subject: Native ODBC access for python on linux? References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> <8NCdnRaSkdR-XkvfRVn-jg@telcove.net> Message-ID: <86r7e0al3p.fsf@bhuda.mired.org> "Thomas Bartkus" writes: > Although I hear rumors about ODBC drivers on Linux, I confess I don't > understand the need. Certainly you can use Python with the MySQLdb module > from any Linux machine and query away at the server. As long as the MySQL > server accepts your IP/usr/pwd, it will respond to the SQL you pass it from > Python. > > IOW - who/what needs an ODBC driver here? ODBC provides one thing that db native api's don't - binary interoperability. If you have a binary application that talks odbc, you can talk to pretty much any db that someone has writte an odbc driver for. To talk to the db native api, the application has to be built against that api. For instance, I use the unixODBC driver to connect applix office's spreadsheet tool to my postgresql databases. If everything you run is open source - especially if it's written in Python - this is pretty much irrelevant. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From diesch at spamfence.net Wed Jul 27 01:47:31 2005 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 27 Jul 2005 07:47:31 +0200 Subject: Emacs skeletons References: Message-ID: <20050727054731.7038.1.NOFFLE@dieschf.news.arcor.de> Michael Hoffman wrote: > Does anyone have any Emacs skeletons they find useful for Python? I > Googled a little but didn't find anything enticing. I already have a > script that sets up script/module templates, so those aren't all that > useful. else-mode seems to be nice after you get used to it. Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From cam.ac.uk at mh391.invalid Mon Jul 4 16:42:09 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 04 Jul 2005 21:42:09 +0100 Subject: "long int..." exception reported with strange traceback location In-Reply-To: References: Message-ID: Joe Peterson wrote: > I could not find another example of this via internet searches, so here > it is... I am wondering if this is a python bug or otherwise. The > first example of this happened in a larger program of mine, and the > traceback reports the problem at the start of a "for" loop (making no > sense), but I cannot easily include the full code and instructions here. > > So I wrote a small test program containing the offending code, and in > this case the traceback reports the problem happening "during garbage > collection." So in either case, there's something funny going on here. > The call the causes it is "os.utime()". Note that the trigger is a > rediculous timezone value that causes an overflow. But the surprize is > that the traceback does not report its happening in utime. I came up with a simpler testcase. Strangely, the exception occurs in the statement *following* the os.utime() call: >>> import os, sys >>> os.utime("foo_test_file", (0, float(sys.maxint+1))) >>> print "hi" OverflowError: long int too large to convert to int Looks like a bug. You should report it on the SourceForge tracker. -- Michael Hoffman From nick at no.spam.org Thu Jul 21 08:28:47 2005 From: nick at no.spam.org (nick at no.spam.org) Date: Thu, 21 Jul 2005 12:28:47 +0000 (UTC) Subject: Lots of pdf files References: <7xu0iptbi7.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Greg Lindstrom writes: > > There does not appear to be a simple way to merge many pdf's into one. > There's probably some way to do it with pstops or some related program > or set of programs. Google for "multivalent tools" - a collection of Java applications for PDF manipulation... N. From pydecker at gmail.com Mon Jul 18 11:10:23 2005 From: pydecker at gmail.com (Peter Decker) Date: Mon, 18 Jul 2005 11:10:23 -0400 Subject: wxPython date In-Reply-To: <1121698326.616726.284280@o13g2000cwo.googlegroups.com> References: <1121698326.616726.284280@o13g2000cwo.googlegroups.com> Message-ID: On 18 Jul 2005 07:52:06 -0700, Jason wrote: > How do I form a new wxPython date using day, month and year? > > I've tried the wx.DateTimeFromDMY but it crashes in Pythonwin when I > test it out and I get all manner of complaints when I try it from the > command line. > > Surely there's an equivalent to the python datetime.date(2005,07,18) Are you specifying the date in DMY format? Also, remember that the months are zero based. This works fine on my systems (both OS X and Linux): import wx dt = wx.DateTimeFromDMY(18, 6, 2005) print dt -> Mon Jul 18 00:00:00 2005 From deets at web.de Sun Jul 3 14:18:23 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 03 Jul 2005 20:18:23 +0200 Subject: Using regular expressions in internet searches In-Reply-To: <1120412943.283248.100700@g14g2000cwa.googlegroups.com> References: <1120412943.283248.100700@g14g2000cwa.googlegroups.com> Message-ID: <3iqoffFmp1vmU1@uni-berlin.de> mike.ceravolo at gmail.com wrote: > What is the best way to use regular expressions to extract information > from the internet if one wants to search multiple pages? Let's say I > want to search all of www.cnn.com and get a list of all the words that > follow "Michael." > > (1) Is Python the best language for this? (Plus is it time-efficient?) > Is there already a search engine that can do this? > > (2) How can I search multiple web pages within a single location or > path? You'd probably better off using htdig. Diez From johng2001 at rediffmail.com Sat Jul 16 08:04:00 2005 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 16 Jul 2005 05:04:00 -0700 Subject: Python Newbie In-Reply-To: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> References: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> Message-ID: <1121515440.347079.303840@g43g2000cwa.googlegroups.com> The usual order I recommed is ... http://honors.montana.edu/~jjc/easytut/easytut/ http://www.ibiblio.org/obp/thinkCSpy/ http://docs.python.org/tut/tut.html Ron's list is quite a good place for tutorials http://www.awaretek.com/tutorials.html From lordverminard at gmail.com Wed Jul 27 13:12:24 2005 From: lordverminard at gmail.com (mustafa) Date: Wed, 27 Jul 2005 22:12:24 +0500 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? In-Reply-To: References: Message-ID: Chris wrote: > In article , > Steven D'Aprano writes > >>On Tue, 19 Jul 2005 07:24:19 +0100, Chris wrote: > > >>>Could anyone write a small program to log the Signal-to-Noise figures >>>for a Netgear DG834 router? > > >>Are you offering to pay somebody to do it, or just suggesting a project >>for some Python programmer who is bored and looking for a small project to >>work on out of love? > > > Yes, Steven, the latter. Sometimes programmers need an idea for a > project - and, for them, knowing that someone would actually value what > they did might make it more fun for them. hey i would help i am noob at programming but this will give me good experiance. please contact me and on the subject write router SNR issue cuz i get a lot of mail and most i don't open but then i will be able to spot yours. hope i can help. From steven.bethard at gmail.com Sun Jul 3 19:28:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 03 Jul 2005 17:28:14 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> <86irzu5sp9.fsf@bhuda.mired.org> Message-ID: Christopher Subich wrote: > One caevat that I just noticed, though -- with the for-solution, you do > need to be careful about whether you're using a generator or list if you > do not set an explicit initial value (and instead use the first value of > 'sequence' as the start). The difference is: > _accum = g.next() > for i in g: _accum = stuff(_accum,i) > > versus > _accum = g[0] > for i in g[1:]: _accum = stuff(_accum,i) If you want to be general for all iterables (list, generators, etc), you can write the code like: itr = iter(g) _accum = itr.next() for i in itr: _accum = stuff(_accum, i) STeVe From hancock at anansispaceworks.com Fri Jul 1 22:23:13 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 21:23:13 -0500 Subject: Python, mysql, floating point values question In-Reply-To: <43b72594050701154055297e73@mail.gmail.com> References: <43b72594050701154055297e73@mail.gmail.com> Message-ID: <200507012123.13272.hancock@anansispaceworks.com> On Friday 01 July 2005 05:40 pm, Christopher Kang wrote: > Anyway, I have a problem where I am pulling floating point values out > of mysql and into python using the MYSQLdb module. > > However, the values seem to be altered a little when I store them in python. I'm not even going to start to explain why, but this is a given with floating point values. They *always* have a degree of imprecision. You're just tickling this problem by changing representations from Python to SQL and back. Long, long ago when all I knew how to program in was Basic and Fortran, I learned the fundamental rule of comparing floats --- you must always allow a tolerance, e.g.: epsilon = 0.0001 if abs(a-b) > epsilon: print "a ~= b" else: print "a != b" There is no "equals" with floating point numbers. Just remember that, and you'll go far. ;-) As for how to do this in SQL? I'm pretty sure that you can do ranges in SQL, but I'd have to look up the syntax for inequality statements. The python equivalent would be to write it out as: if a > b-epsilon and a < b+epsilon: print "a~=b" -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Sat Jul 23 23:58:08 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 13:58:08 +1000 Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> <11e5m07ef4nq339@news.supernews.com> Message-ID: On Sat, 23 Jul 2005 17:51:31 -0600, John Roth wrote: > I also like to know the number of elements, which seems to make > sense as len(path). Again, the number of characters in the path seems > to be utterly useless information - at least, I can't imagine a use for > it. There are (were?) operating systems that could only deal with a maximum length for pathnames. If I recall correctly, and I probably don't, Classic Mac (pre-OS X) was limited to file names of 31 or fewer characters and no more than 250-odd for the entire pathname. At the very least, some file manager routines would work and some would not. If you are printing the pathname, you may care about the length so that you can truncate it: longname = "C:\really\really\really\really\really\long\path\name.txt" if len(longname) > 30: # do magic here print "C:\really\ ... \path\name.txt" else: print longname -- Steven. From rkern at ucsd.edu Tue Jul 12 21:26:35 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 18:26:35 -0700 Subject: plot module In-Reply-To: <126622653da8.42d3ef2f@Princeton.EDU> References: <126622653da8.42d3ef2f@Princeton.EDU> Message-ID: Shankar Iyer (siyer at Princeton.EDU) wrote: > Hi, > > I am looking for documentation on the plot module. Does anyone know where I can find this information? Thanks. What is "the plot module"? There are any number of Python modules for making plots and charts. Some of them may even be called "plot". Which one are you talking about? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tta013 at yahoo.co.uk Thu Jul 21 17:13:58 2005 From: tta013 at yahoo.co.uk (Tin) Date: Thu, 21 Jul 2005 21:13:58 -0000 Subject: Python Programming Patterns Message-ID: Hi, I have listed Python Programming Patterns ISBN:0130409561 on ebay.co.uk A brand new with really cheap price-4.99 If you are interested, go and have a look at www.ebay.co.uk and locate that one. Come one, fish and chips would cost more than that. Surely. Cheers Tin From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 07:30:09 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 13:30:09 +0200 Subject: Initializing interactive Python In-Reply-To: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> References: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> Message-ID: <42e374c5$0$15019$626a14ce@news.free.fr> qwweeeit at yahoo.it a ?crit : > Hi all, > is it possible to enter an interactive session and automatically > do some initialization? > I explain better: > I want that when I start interactive Python on a console (I use Linux) > two command lines be executed automatically: bruno at bibi bruno $ python -h (snip) Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) (snip) > Python 2.3.4 (#2, Aug 19 2004, 15:49:40) > [GCC 3.4.1 (Mandrakelinux (Alpha 3.4.1-3mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import sys >>>>x01=x02=0 > > > I would like not to have to write anything at the prompt >>> to run > the two commands, but be ready to start the interactive session. > Bye. bruno at bibi bruno $ cat ~/.pythonrc.py import sys x01=x02=0 bruno at bibi bruno $ export PYTHONSTARTUP=~/.pythonrc.py bruno at bibi bruno $ python Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> sys >>> x01 0 >>> x02 0 >>> Easy as pie !-) HTH Bruno From flamesrock at gmail.com Sat Jul 2 22:33:42 2005 From: flamesrock at gmail.com (flamesrock) Date: 2 Jul 2005 19:33:42 -0700 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: <1120358022.536372.30420@o13g2000cwo.googlegroups.com> I've needed to do something similar in the past and used free ntp servers. Of course you need an internet connection: http://ntp.isc.org/bin/view/Servers/NTPPoolServers http://www.nightsong.com/phr/python/setclock.py You could also have a startup script spawn a thread that stores the time persistently in a shelf object, sleeps for a minute, and checks to see if the current clock time is greater than a minute (+/-sec,) and subtracts the difference. Or even check it against an NTP server if you can. From fotis77k at fmail.co.uk Mon Jul 4 09:23:32 2005 From: fotis77k at fmail.co.uk (fotis) Date: 4 Jul 2005 06:23:32 -0700 Subject: Debugging embedded python In-Reply-To: References: <1120465254.327966.196570@g14g2000cwa.googlegroups.com> Message-ID: <1120483412.295166.62410@g47g2000cwa.googlegroups.com> Thank's a lot miki for your response! It seems that this problem is now solved, yet a new one now occured. And the name of my new problem is... "" Let me rewrite the code a little bit more clearly... //******************************************************************* // C O D E //******************************************************************* 01 //___________________________________________________________________ 02 // Includes mpla, mpla mpla... 03 #include 04 #include 05 #include 06 using namespace std; 07 08 //___________________________________________________________________ 09 // My function 10 /* Return the sqrt of a double */ 11 static PyObject* Fotis_root(PyObject *self, PyObject *args) 12 { 13 double d=0; 14 if(!PyArg_ParseTuple(args,"d",&d)) return NULL; 15 return Py_BuildValue("d", sqrt(d)); 16 } 17 18 //___________________________________________________________________ 19 // Some python module stuff 20 static PyMethodDef FotisMethods[] = { 21 {"root",Fotis_root, METH_VARARGS, 22 "Return the root of a double."}, 23 {NULL, NULL, 0, NULL} 23 }; 24 25 //___________________________________________________________________ 26 // Main program 27 int main(int argc,char** argv) 28 { 29 Py_Initialize(); 30 Py_InitModule("fotis", FotisMethods); 31 PyRun_SimpleString("from fotis import root"); 32 FILE* fp=stdin; 33 char *filename="Solver"; 34 PyRun_InteractiveLoop(fp,filename); 35 Py_Finalize(); 36 return 0; 37 } Now lets say i set two breakpoints: line 29, and line 13. This is what happens: 1. Breakpoint at line 29: There is a strange combination of next, step, and other stuff that can move me from line 29 to line 34. No matter how deeply I digged everywhere I cannot realy understand what really happens there, but what the hack this is not what I'm really interested in. by the way if i try too many steps then there is no way back... 2. Breakpoint at line 13: When I finally reach the much awaited line 34, the python interpreter is there and running and waiting for my commands, which here is the fotis.root(double) command. when I give though this command control is totally lost: i get the message described above and after that everything seems to be dead. I really do not know where I am, why am I there, and what exactly I am doing at the point that I am. What is really happening? Any help will be very appreciated. fotis._ From peter at engcorp.com Sat Jul 30 13:41:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 13:41:19 -0400 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> Message-ID: Ed Leafe wrote: > On Saturday 30 July 2005 12:28, Peter Decker wrote: >>It would be great if the wxPython folks would adopt Dabo, > > Thanks for the vote of encouragement! > > Our goal isn't to muddy the waters; it is simply to create a consistent API > for coding. There is already a great GUI toolkit for Python; we're just > trying to make it easier to code. The last time I checked (as I recall), at least Wax and possibly Dabo both either lagged well behind recent wxPython developments of provide relatively limited support, leaving out a sizable and (to me) important number of features from what they wrapped. Is this a remotely accurate and current picture of things? Or is it more fair to say that by adopting Dabo (or Wax?) one really loses nothing in terms of flexibility, and gains only improved write- and readability? -Peter From rrr at ronadam.com Wed Jul 6 01:36:28 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 05:36:28 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1120621580.107813.47100@g43g2000cwa.googlegroups.com> Message-ID: Robert Kern wrote: > Dan Bishop wrote: > >> There's also the issue of having to rewrite old code. > > > It's Python 3000. You will have to rewrite old code regardless if reduce > stays. > And from what I understand Python 2.x will still be maintained and supported. It will probably be more reliable than Python 3000 for a version or two as well. It's going to take time for all the batteries included to catch up, so it won't be like we have to all of a sudden rewrite all the old Python programs over night. We'll probably have a couple of years to do that to our own programs if we decide it's worth while. And if not, Python 2.x will still work. From peter at engcorp.com Mon Jul 4 10:27:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Jul 2005 10:27:30 -0400 Subject: curses -- getxy() error In-Reply-To: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> References: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> Message-ID: <6pqdnbyb__6_2lTfRVn-iA@powergate.ca> shablool wrote: > Hi, > Could someone please explain why stdscr.getxy() always raise an > exception: If you post the exception traceback here (the whole thing, cut and pasted from your terminal window), we can show you how to analyze it to determine for yourself exactly what the problem is. This will help you in the future, even if k33rni's answer solves your immediate problem... -Peter From sklass at pointcircle.com Mon Jul 18 09:54:15 2005 From: sklass at pointcircle.com (rh0dium) Date: 18 Jul 2005 06:54:15 -0700 Subject: Python ldap pointers for a newbie - Actually just trying to decifer the error.. Message-ID: <1121694855.926576.15570@o13g2000cwo.googlegroups.com> Hi all, I have a script which appears to work but it errors and the following output is given. My code is listed below.. Traceback (most recent call last): File "./ldap-nsc2.py", line 96, in ? truc.search() File "./ldap-nsc2.py", line 49, in search (result_type, result_data) = cnx.result(ldap_result_id, 0) File "/usr/local/lib/python2.4/site-packages/ldap/ldapobject.py", line 406, in result res_type,res_data,res_msgid = self.result2(msgid,all,timeout) File "/usr/local/lib/python2.4/site-packages/ldap/ldapobject.py", line 410, in result2 res_type, res_data, res_msgid, srv_ctrls = self.result3(msgid,all,timeout) File "/usr/local/lib/python2.4/site-packages/ldap/ldapobject.py", line 416, in result3 rtype, rdata, rmsgid, serverctrls = self._ldap_call(self._l.result3,msgid,all,timeout) File "/usr/local/lib/python2.4/site-packages/ldap/ldapobject.py", line 94, in _ldap_call result = func(*args,**kwargs) TypeError: an integer is required So I dig into the docs at /usr/local/lib/python2.4/site-packages/ldap/ldapobject.py to see what the problem is.. def result(self,msgid=ldap.RES_ANY,all=1,timeout=None): """ result([msgid=RES_ANY [,all=1 [,timeout=None]]]) -> (result_type, result_data) . . . """ So.. That's what I have in my code.. result_type, result_data = cnx.result(ldap_result_id, 0) Can Someone please point me in the right direction. I want to know WHY it's failing. I think it's right? Anyone? My Code... ---------------------------- import ldap class NSCLdap(object): def __init__(self, server="sc-ldap.nsc.com", baseDN="o=nsc.com", who=None, cred=None): self.server = server self.baseDN = baseDN if who is None: self.who = "" else: self.who = who if cred is None: self.cred = "" else: self.cred = cred self.connection = None def connect(self): print "LDAP Version", ldap.__version__ self.connection = ldap.open(self.server) self.connection.simple_bind_s( self.who, self.cred) self.connection.protocol_version=ldap.VERSION3 def search(self, baseDN=None, searchScope=ldap.SCOPE_SUBTREE, retrieveAttrs=None, searchAttrs="l=ny5*" ): cnx = self.connection if baseDN is None: baseDN = self.baseDN try: ldap_result_id = cnx.search_s(baseDN, searchScope, searchAttrs, retrieveAttrs) while 1: result_type, result_data = cnx.result(ldap_result_id, 0) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) if len(result_set) == 0: print "No Results." return for i in range(len(result_set)): for entry in result_set[i]: try: name = entry[0][i]['cn'] email = entry[0][i]['mail'] phone = entry[0][i]['telephonenumber'] loc = entry[0][i]['l'] count = count + 1 print "%d.\nName: %s\nDescription: %s\nE-mail: %s\nPhone: %s\n" %\ (count, name, desc, email, phone) except: pass except ldap.LDAPError, error_message: print error_message if __name__ == '__main__': truc = NSCLdap() truc.connect() truc.search() From bokr at oz.net Fri Jul 8 02:16:19 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 08 Jul 2005 06:16:19 GMT Subject: Conditionally implementing __iter__ in new style classes References: <42cc0e23.693458660@news.oz.net> <7jg35a0h.fsf@python.net> <42cd51aa.44517973@news.oz.net> Message-ID: <42ce18ec.95527841@news.oz.net> On Thu, 07 Jul 2005 22:04:31 +0200, Thomas Heller wrote: >bokr at oz.net (Bengt Richter) writes: > >> On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller wrote: >> >>>bokr at oz.net (Bengt Richter) writes: >>> >>>> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller wrote: >>>> >>>>>I'm trying to implement __iter__ on an abstract base class while I don't >>>>>know whether subclasses support that or not. >>> >>>> Will a property or custom descriptor do what you want? E.g. >>>> >>>> >>> class Base(object): >>>> ... def __getIter(self): >>>> ... if hasattr(self, "Iterator"): >>>> ... return self.Iterator >>>> ... raise AttributeError, name >>>> ... __iter__ = property(__getIter) >> [...] >>> >>>Yep, that's exactly what I need - thanks. >>> >> BTW, I forgot to mention that you could use property as a decorator >> in the above single-argument case: >> >> >>> class Base(object): >> ... @property >> ... def __iter__(self): >> ... if hasattr(self, "Iterator"): >> ... return self.Iterator >> ... raise AttributeError, name > >Of course. I didn't spot this, but I cannot use this anyway for 2.3 >compatibility. > >> ... >> >>> class Concrete(Base): >> ... def Iterator(self): >> ... yield 1 >> ... yield 2 >> ... yield 3 >> ... >> >>> iter(Base()) >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: iteration over non-sequence >> >>> iter(Concrete()) >> >> >>> list(iter(Concrete())) >> [1, 2, 3] >> >> Hope there isn't a gotcha for your use case in the way an instance attribute >> of the same name is allowed. A custom descriptor could eliminate that. >> >> >>> inst = Concrete() >> >>> list(iter(inst)) >> [1, 2, 3] >> >>> inst.__init__ = 'abc' >> >>> list(iter(inst)) >> [1, 2, 3] >> >>> inst.__init__ >> 'abc' > >I don't understand what you mean here. A __iter__ instance attribute? > Yes, but it seems very unlikely to cause a problem, especially since iter(inst) bypasses it, as you probably would want. In other words, never mind ;-) Regards, Bengt Richter From __peter__ at web.de Sun Jul 17 05:34:20 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 17 Jul 2005 11:34:20 +0200 Subject: I just wanna know about os.path module.. References: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> Message-ID: kimes wrote: > But the only os.path doesn't have their own file.. > ye I know is has actually depending on os like in my case posixpath.. > > What I'd love to know is.. > when I call import os.path.. > how happened under the hood? At first os - module, or package, it doesn't matter here - is imported. In its code, it detects the proper path module and imports it. The module cache is then manipulated and the name 'path' is bound to posixpath, too: sys.modules["os.path"] = posixpath path = posixpath The second stage of the import then reduces to just a lookup in the cache instead of a search for the inexistent .../os/path.py in the filesystem. Both the module attribute and the cache update are necessary when you want to pull off similar tricks. Here is an example of the odd behaviour that results from them being out of sync: >>> import os >>> os.path = 42 >>> from os import path # binds the path attribute of module os >>> path 42 >>> import os.path >>> os.path 42 >>> old_globals = set(globals().keys()) >>> from os.path import * # looks up os.path module as found in the cache >>> set(globals().keys()) - old_globals set(['pardir', 'sameopenfile', 'exists', 'sep', 'splitext', 'basename', 'walk', 'expandvars', 'old_globals', 'expanduser', 'getmtime', 'defpath', 'dirname', 'isfile', 'supports_unicode_filenames', 'pathsep', 'getsize', 'samestat', 'split', 'devnull', 'islink', 'curdir', 'samefile', 'realpath', 'commonprefix', 'abspath', 'normcase', 'getatime', 'isdir', 'join', 'altsep', 'getctime', 'isabs', 'normpath', 'ismount', 'splitdrive', 'extsep']) Peter From python at rcn.com Sat Jul 9 10:29:42 2005 From: python at rcn.com (Raymond Hettinger) Date: 9 Jul 2005 07:29:42 -0700 Subject: removing list comprehensions in Python 3.0 References: Message-ID: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> In all probability, both list comprehensions and generator expressions will be around in perpetuity. List comps have been a very successful language feature. The root of this discussion has been the observation that a list comprehension can be expressed in terms of list() and a generator expression. However, the former is faster when you actually want a list result and many people (including Guido) like the square brackets. After the advent of generators, it seemed for a while that all functions and methods that returned lists would eventually return iterators instead. What we are learning is that there is a place for both. It is darned inconvenient to get an iterator when you really need a list, when you want to slice the result, when you want to see a few elements through repr(), and when you need to loop over the contents more than once. Raymond Hettinger From sun.aries at gmail.com Thu Jul 14 08:41:11 2005 From: sun.aries at gmail.com (Aries Sun) Date: 14 Jul 2005 05:41:11 -0700 Subject: Consecutive Character Sequences In-Reply-To: <1121343722.7ebce1b2a41714687db3ed336af5fc19@teranews> References: <1121318559.d582247e6e25443e247191d29f60b3b0@teranews> <1121325469.494500.291730@z14g2000cwz.googlegroups.com> <1121343722.7ebce1b2a41714687db3ed336af5fc19@teranews> Message-ID: <1121344871.471781.37180@z14g2000cwz.googlegroups.com> Hi George, I used Python 2.4.1, the following are the command lines. But the reslut was still False. Is there anything wrong with below codes? >>> import itertools as it >>> def hasConsequent(aString, minConsequent): for _,group in it.groupby(aString): if len(list(group)) >= minConsequent: return True return False >>> hasConsequent("taaypiqee88adbbba", 3) False >>> Regards, Aries From lordverminard at gmail.com Wed Jul 27 11:00:56 2005 From: lordverminard at gmail.com (mustafa) Date: Wed, 27 Jul 2005 20:00:56 +0500 Subject: any thing to do??? Message-ID: i hav just finished learning pythob from "A byte of python"(an online book) so i wanted to apply my new skills. to learn and to have some fun. is there any place which lists jobs to be done...you know minor jobs and requests thats nobody has found time to do. i would point out that i am not looking for a JOB as job with payment. i am looking for a JOB that is to be done and nobody has done it yet. also aside from this is there any other way i could use python and improve. i figure this practice will make me a lot better. but if anybody else has any ideas than that would be good too . From simon.dahlbacka at gmail.com Tue Jul 12 05:07:47 2005 From: simon.dahlbacka at gmail.com (simon.dahlbacka at gmail.com) Date: 12 Jul 2005 02:07:47 -0700 Subject: pychecker filtering Message-ID: <1121159266.992345.109330@g47g2000cwa.googlegroups.com> Hi, I'm trying to make a decent .pycheckrc for our project and have stumbled on a few issues. (the pychecker-list would have seemed like the appropriate place, but the S/N ratio seemed very low with all the spam) - for various reasons we decided to add an attribute to a module in the stdlib, lets say os.foo. Now, pychecker screams "No module attribute (foo) found" in a lot of places, which is not desirable. (Yes I know, don't do that, fix the original problem etc.. We probably will eventually, but for now, I just don't want to see those) I thought of doing something with the suppressions dict, but could not figure out how to use that in this particular case. Another thing, we have a lot of autogenerated files which contain a function _translateException which is basically a huge dictionary lookup. Here pychecker complains about too many lines, can I somehow suppress Wrapper.._translateException or failing that, all _translateException (manually including every name does not seem like fun..) /Simon From kst-u at mib.org Sun Jul 10 16:02:58 2005 From: kst-u at mib.org (Keith Thompson) Date: Sun, 10 Jul 2005 20:02:58 GMT Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: "Xah Lee" writes: > What is Expresiveness in a Computer Language > > 20050207, Xah Lee. +-------------------+ .:\:\:/:/:. | PLEASE DO NOT | :.:\:\:/:/:.: | FEED THE TROLLS | :=.' - - '.=: | | '=(\ 9 9 /)=' | Thank you, | ( (_) ) | Management | /`-vvv-'\ +-------------------+ / \ | | @@@ / /|,,,,,|\ \ | | @@@ /_// /^\ \\_\ @x@@x@ | | |/ WW( ( ) )WW \||||/ | | \| __\,,\ /,,/__ \||/ | | | jgs (______Y______) /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ============================================================== -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From invalidemail at aerojockey.com Mon Jul 4 04:41:03 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Jul 2005 01:41:03 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <42C8B26D.3030704@REMOVEMEcyber.com.au> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <42c7f923$1@nntp0.pdx.net> <1120424107.153904.238480@f14g2000cwb.googlegroups.com> <42C8B26D.3030704@REMOVEMEcyber.com.au> Message-ID: <1120466463.439269.305090@z14g2000cwz.googlegroups.com> Steven D'Aprano wrote: > Carl Banks wrote: > > > The shamelessness with which you inflated the verbosity of the latter > > is hilarious. > > [snip] > > > [ x**2 + y**2 for (x,y) in izip(xlist,ylist) ] > > > > Now there's no longer much advantage in conciseness for the map version > > (seeing that you'd have to define a function to pass to map), and this > > is more readable. > > and then, five minutes later in another post, wrote: > > > If you're doing heavy functional programming, > > listcomps are tremendously unwieldy compared to > > map et al. > > Having a dollar each way I see :-) Don't think so. The verbosity I spoke of was your describing the code snippets in English, not the conciseness of the example. map and friends are more concise than listcomps, I wasn't arguing that, except that for the typical Pythonic use of listcomps it isn't much. One listcomp or one call to map is not "heavily functional." -- CARL BANKS From majromax at gmail.com Fri Jul 22 11:08:08 2005 From: majromax at gmail.com (Christopher Subich) Date: 22 Jul 2005 08:08:08 -0700 Subject: Help with regexp please References: <4z_De.13539$Wt3.3395@bignews3.bellsouth.net> Message-ID: <1122044888.898262.217870@g43g2000cwa.googlegroups.com> Terry Hancock wrote: > I think this is the "regexes can't count" problem. When the repetition > count matters, you usually need something else. Usually some > combination of string and list methods will do the trick, as here. Not exactly, regexes are just fine at doing things like "first" and "last." The "regexes can't count" saying applies mostly to activities that reduce to parentheses matching at arbitrary nesting. The OP's problem could easily be written as a regex substitution, it's just that there's no need to; I believe that the sub would be (completely untested, and I'm probably going to use the wrong call to re.sub anyway since I don't have the docs open): re.sub(outline_value,'([0-9.]+)\.[0-9]+','\1') It's just that the string.rsplit call is much more legible, much more intutitive, doesn't do strange things if it's accidentally called on a top-level outline value, and also extends immediately to handle outlines of the form I.1.a.i. From bobofficers at invalid.net Mon Jul 18 14:54:37 2005 From: bobofficers at invalid.net (Bob Officer) Date: Mon, 18 Jul 2005 11:54:37 -0700 Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> <2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net> <6DhBe.3077$dU3.691@newsread2.news.pas.earthlink.net> Message-ID: On Wed, 13 Jul 2005 23:39:46 GMT, in sci.geo.earthquakes, "Hank Oredson" wrote: >"edgrsprj" wrote in message >news:2OeBe.2928$oZ.770 at newsread2.news.atl.earthlink.net... >> "Hank Oredson" wrote in message >> news:1vYAe.2575$dU3.2553 at newsread2.news.pas.earthlink.net... >>> "edgrsprj" wrote in message >>> news:pmXAe.9096$aY6.3897 at newsread1.news.atl.earthlink.net... >>> > "Hank Oredson" wrote in message >>> > news:7%UAe.4148$BK1.174 at newsread3.news.pas.earthlink.net... >>> >> "edgrsprj" wrote in message >>> >> news:upBAe.1915$oZ.930 at newsread2.news.atl.earthlink.net... >>> >> > "edgrsprj" wrote in message >>> >> > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... >>> >> >> PROPOSED EARTHQUAKE FORECASTING >>> >> >> COMPUTER PROGRAM DEVELOPMENT EFFORT >> >>> I guess my question was not specific enough. >>> What I wanted was the exact sources, so I could access the data. >>> The exact data sets you used. >> >> July 13, 2005 >> >> Thanks again for the comments and interest. >> >> The original report in this thread should have contained pointers to >> all of the information you are requesting. But once again, here are some >> of >> the important URLs. >> >> http://www.freewebz.com/eq-forecasting/301.html >> >> That Web page contains information regarding the details of how the >> forecasting program works. Also stored there are copies of an early >> Zipped .txt version of the Perl program I am using along with Zip file >> versions of earlier versions of the .txt format database files that I am >> using. I had to Zip them because of their size and the limited bandwidth >> of >> that Web site. If you would prefer to receive them as regular text files >> then you can try contacting me by e-mail and I will try to send them >> along. >> >> Perl users who downloaded and ran that .pl program some time ago >> said >> that they had no trouble getting it to run on a Window's XP system. Other >> operating system users might encounter a few formatting problems etc. >> >> http://www.freewebz.com/eq-forecasting/90-05.html >> http://www.freewebz.com/eq-forecasting/128.html >> >> Those Web pages discuss the theories involved with this forecasting >> method. Some of the most important information is at the end of that >> 128.html Web page. > >I found no equations there, nor any links to the original data sources. > >> http://www.freewebz.com/eq-forecasting/Data.html >> >> That Web page contains several types of forecast data along with >> some >> information regarding how to interpret them. > >Did not find any information on the source of the data. > >> http://www.freewebz.com/eq-forecasting/151.html >> >> That Web page contains some "Help" information with details >> regarding >> things such as the U.S. Navy's MICA computer program which I use to >> generate >> data for things such as the locations of the Earth, sun, and moon relative >> to the J2000 reference system. >> >> You should not expect to be able to instantly absorb all of that >> information though it sounds like understanding it should not be a problem >> for you. I have been working on the project for about 15 years. And >> unfortunately, every improvement seems to take days, weeks, months, ... > >Everything looked fairly obvious, except that there did not seem >to be any reference to the source of the datasets. > >> Additionally, as I said in my first report in this thread, the >> multiple participants part of the project is not yet operational. For one >> thing, a suitable Web site has to be found. Right now I am simply >> trying to determine what the interest level there might be in such a >> project. And positive feedback that I have been getting by e-mail etc. >> has been encouraging. > >Perhaps I was not clear enough in my previous posts. > >I am looking for the SOURCE of the data, that is, where did >YOU get the data from, so that I may obtain my own datasets. > >In particular I am interested in the EM dataset. There isn't any "data set" There are no "formula"... There is only EGD Crackpot. http://www.crank.net/geology.html Look down to the middle of the page E.D.G. Listed as "Cranky" -- Ak'toh'di From renting at astron.nl Fri Jul 1 04:54:03 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 01 Jul 2005 10:54:03 +0200 Subject: No subject Message-ID: I'm not a very experienced Python programmer yet, so I might be mistaken, but there are a few things that would make me prefer C++ over Python for large (over 500.000 LOC) projects. - namespaces - templates - strong type checking - data hiding - more available libraries and more advanced developement tools. I'm talking about managing the code, not the programmers, the project or schedules or what have you. Those are independent from the chosen programming language. > Ultimately, manageability of a project is far and away more about the > people involved and the techniques used than it is about any single > technology involved. Agreed. Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> 06/30/05 4:15 PM >>> Peter Hansen writes: > Harry George wrote: > > "Adriaan Renting" writes: > >>Both VB and Python are easier to learn as the more powerful > >>languages, the price is that they lack features that make it easier to > >>manage large and complex projects. > > What is a large project, and what is Python missing that C++ and Java > > have for such tasks? > > But C++ and Java have features that *management* likes, thus making it > "easier to manage large projects". (That says nothing about whether > or not it makes it easier to produce quality code, successful > projects, happy customers, large profits, or any such silly > things... just that it's "easier to manage". ;-) > > Less facetiously: I have managed a large Python project or three, and > several large C++ projects (and, thankfully, no large Java projects) > and found Python quite up to the task. In fact, if anything the C++ > projects ended up more in danger of succumbing to the sheer weight of > the code than did the Python projects. But I attribute this more to > the fact that we had evolved to using agile approaches with the Python > projects than to any of those special features either present or > lacking in C++. > > Ultimately, manageability of a project is far and away more about the > people involved and the techniques used than it is about any single > technology involved. > > -Peter That's our experience too (and the reason I asked). I wonder if the OP will respond. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list From stephen.thorne at gmail.com Mon Jul 18 01:12:19 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Mon, 18 Jul 2005 15:12:19 +1000 Subject: Who uses input()? [was Re: question on "input"] In-Reply-To: <200507141240.14373.hancock@anansispaceworks.com> References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> <1121179143.995844.28690@g47g2000cwa.googlegroups.com> <200507141240.14373.hancock@anansispaceworks.com> Message-ID: <3e8ca5c8050717221220121c54@mail.gmail.com> On 15/07/05, Terry Hancock wrote: > On Thursday 14 July 2005 07:00 am, Michael Hoffman wrote: > > Devan L wrote: > > > Use raw_input instead. It returns a string of whatever was typed. Input > > > expects a valid python expression. > > > > Who actually uses this? It's equivalent to eval(raw_input(prompt)) but > > causes a lot of newbie confusion. Python-dev archives revealed that > > someone tried to get this deprecated but Guido disagreed. > > I don't think it should disappear, but it *does* seem more sensible for > "raw_input" to be called "input" (or "readstring" or some such thing) and > "input" to vanish into greater obscurity as "eval_input" or something. > > Unfortunately, that would break code if anything relied on "input", so I > guess that would be a Py3K idea, and maybe the whole I/O concept > will be rethought then (if the "print" statement is going to go away, > anyway). I don't see as "break input() using code" -> "not until py3k" as a logical cause/effect. No one should be using input() anyway, the only place it's at-all appropriate is in a python tutorial, with the 'guess the number' game. -- Stephen Thorne Development Engineer From detlev at die-offenbachs.de Sat Jul 9 06:57:31 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 09 Jul 2005 12:57:31 +0200 Subject: ANN: eric3 3.7.1 available Message-ID: Hi, I am proud to announce the availability of eric3 3.7.1. This is a bug fix release which fixes a severe bug next to some normal ones. NOTE: Everybody using 3.7.0 or 3.6.x should upgrade. It is available via http://www.die-offenbachs.de/detlev/eric3.html. What is it? ----------- Eric3 is a Python and Ruby IDE with all batteries included. Please see a.m. website for more details. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From news at NOwillmcguganSPAM.com Thu Jul 21 18:19:48 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 21 Jul 2005 23:19:48 +0100 Subject: dictionary that discards old items Message-ID: <42e01f85$0$1586$da0feed9@news.zen.co.uk> Hi folks, I need a collection class that behaves like a dictionary but when it reaches 'n' items it discards the oldest item so that the length never goes above 'n'. (Its for caching search results) I have a vague memory of a module that does this, but I cant remember where I read about it. Can anyone enlighten me? Regards, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From girish.14 at gmail.com Fri Jul 22 10:13:49 2005 From: girish.14 at gmail.com (Girish) Date: 22 Jul 2005 07:13:49 -0700 Subject: query regarding expect Message-ID: <1122041629.338563.26610@g47g2000cwa.googlegroups.com> Hi, I wanna do some automation using "pexpect". I have an application which must be invoked from the command line in linux environment,it consists of buttons,textboxes etc can i access those widgets using "pexpect",say i wanna enter a value 3.3 in the textbox and then click on the ok button,to run the apllication.The application is developed using wxpython.ur suggestions will be of gr8 help.plz do reply. Regards Girish From sjmachin at lexicon.net Thu Jul 14 20:14:19 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 15 Jul 2005 10:14:19 +1000 Subject: readlines() doesn't read entire file In-Reply-To: References: Message-ID: <42d6ffdb@news.eftel.com> Jeremy wrote: > I have a most aggravating problem. I don't understand what is causing > readlines() not to read all the lines in the file. Answer all of Peter Hansen's questions, then read on ... You are on platform X; did you get the file from platform Y where Y != X? Where did you get the file from? How was it constructed? What is the encoding: ascii/utf-8/iso-something/cp125x/dunno/what's-an-encoding ... > I have the following > syntax: > > > > # some initial stuff > XS = xsdir(Datapath + '/xsdir', options.debug) > # some more stuff > > class xsdir(object): #{{{1 > """This class handles all of the data and methods for reading > the xsdir file.""" > > def __init__(self, Datapath, debug=False): > self.xsdir = file(Datapath, 'r') # File object If you replace 'r' by 'rU', does the behaviour change? > self.lines = self.xsdir.readlines() > if debug: > print self.lines Add this: print len(self.lines) > # and then other stuff as well > > > I can see all the lines in the list self.lines, These are *not* pedantic questions: How many can you "see"? What does "see" mean? What is your definition of "line"? > but they are not all the > lines in the file. When I look at the file in Vim, I can see all the > lines, Repeat above questions. AND where are the extra lines that you can "see" with vim? In one block at the end/beginning/middle? Randomly interspersed? Are you sure you are not being confused by a screen-wraparound effect? but Python cannot. Can someone help me with this one? > Thanks, > Jeremy > What does "wc -l yourfile" tell you? [If you are on Windows, get a copy of wc.exe from the gnuwin32 site.] From fdeserres at gmx.net Wed Jul 13 09:32:46 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 15:32:46 +0200 Subject: Building a function call? (update) In-Reply-To: <42D50A88.3070909@gmx.net> References: <42D50A88.3070909@gmx.net> Message-ID: <42D517FE.4020906@gmx.net> Francois De Serres wrote: >Hiho, > >Having a string: "dothat" >and a tuple: (x, y) >1. What's the best way to build a function call like: dothat(x,y)? > >Assuming dothat is def'd in the same module, >2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) >the right way to have it executed? > >If dothat is def'd in another module: >3. what would be the right way to initialize the globals to pass to eval ? > > >TIA, >Francois > > > > Sorry, I was unclear about the fact that the args are formals. I'm trying to do something like: func = "dothat" args = ('x','y') localcontext = () r = None while r is None: try: r = eval("dothat(x,y)", None, localcontext) #how do I construct "dothat(x,y)"? with 'dothat(%s,%s)' % args? except NameError: ensure_context(args) #find/compute the formals, eg: localcontext = (('x', 100), ('y', 200)) F. From harold.fellermann at upf.edu Wed Jul 6 12:17:25 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 6 Jul 2005 18:17:25 +0200 Subject: Conditionally implementing __iter__ in new style classes In-Reply-To: References: Message-ID: <8d2bb545283299c8b70633fea905b003@upf.edu> > I'm trying to implement __iter__ on an abstract base class while I > don't > know whether subclasses support that or not. > Hope that makes sense, if not, this code should be clearer: > > class Base: > def __getattr__(self, name): > if name == "__iter__" and hasattr(self, "Iterator"): > return self.Iterator > raise AttributeError, name > > class Concrete(Base): > def Iterator(self): > yield 1 > yield 2 > yield 3 I don't know how to achieve it, but why don't you simply use class Base: pass class Concrete(Base): def __iter__(self) : yield 1 yield 2 yield 3 What is the advantage to have a baseclass that essentially does some method renaming __iter__ ==> Iterator? - harold - -- Always remember that you are unique; just like everyone else. -- From rutski89 at gmail.com Mon Jul 4 17:43:35 2005 From: rutski89 at gmail.com (Patrick Rutkowski) Date: Mon, 4 Jul 2005 17:43:35 -0400 Subject: Trapping user logins in python =?iso-8859-6?q?=09?=( post #1) In-Reply-To: <20050704174908.GA21332@unpythonic.net> References: <1120477906.956606.119040@g14g2000cwa.googlegroups.com> <20050704174908.GA21332@unpythonic.net> Message-ID: <200507041743.35278.rutski89@gmail.com> On Monday 04 July 2005 13:49, Jeff Epler wrote: > I don't know of a portable way for an inetd-style daemon to "listen" for > user logins. > > On some systems (including RedHat/Fedora and debian), you may be able to > use PAM to do this. (pam modules don't just perform authentication, > they can take other actions. As an example, pam_lastlog "prints the > last login on successful login". I'm not sure what priviledge a pam > module has when it executes. > > A more standard way to do this would be to place lines in /etc/profile > /etc/csh.login and so forth for any other shells used on your system. > RedHat-style systems have an /etc/profile.d where you can drop a file > that will be executed at login, too. This will, of course, be executed > with the user's privilege level. Another problem with this approach is > that /etc/profile is executed for a "login shell", but a graphical login > is not a login shell. > > Jeff If you'd like to hack and slash your way to a solution then you could run "watch who" in a daemon that then sed's the output to your desired format and then dumps it to a log/notification. From macaronikazoo at gmail.com Sat Jul 16 21:33:35 2005 From: macaronikazoo at gmail.com (macaronikazoo) Date: 16 Jul 2005 18:33:35 -0700 Subject: secure uploading In-Reply-To: <7xoe922p88.fsf@ruckus.brouhaha.com> References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> <7x4qauaccl.fsf@ruckus.brouhaha.com> <1121563713.124461.230540@g47g2000cwa.googlegroups.com> <7xoe922p88.fsf@ruckus.brouhaha.com> Message-ID: <1121564015.242118.12780@g44g2000cwa.googlegroups.com> ok, so what can I do to get something uploaded? how can I upload something via http? From hancock at anansispaceworks.com Tue Jul 5 11:25:51 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 10:25:51 -0500 Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: <200507051025.51628.hancock@anansispaceworks.com> On Monday 04 July 2005 01:12 am, Andrea Griffini wrote: > - never ever use tabs; tabs were nice when they had > - stick to 4-space indent Nice ideals to which I ascribe. But if your editor isn't configured to support you on this, spacing over to, say column 24 gets pretty dull. Mine wasn't configured to do anything special, so I was leaving tabs in the file and etc. So I wasn't really living up to my ideals. ;-) Bad habits, I agree. I now have things working so that "tab" actually uses spaces in the file. The problems arose because I was still working with my old "tainted" files. All better now. :-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From peter at engcorp.com Thu Jul 14 10:51:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 10:51:31 -0400 Subject: how to get rate of pop3 receiving progress? In-Reply-To: References: Message-ID: <6pGdnUrmweJP5kvfRVn-iA@powergate.ca> Leo Jay wrote: > when i use POP3.retr() in poplib module, the retr() function will not > return until the receiving progress is finished > > so, is there any way to get the rate of receiving progress? Not a supported one, but you could just create a POP3 subclass and override the implementation of _getlongresp() to do what you need. The best way to learn about this sort of thing is to view the source directly and read... -Peter From M.Waack at gmx.de Mon Jul 4 09:10:33 2005 From: M.Waack at gmx.de (Mathias Waack) Date: Mon, 04 Jul 2005 13:10:33 GMT Subject: Connecting to Firebird database using Kinterbasdb+Python References: Message-ID: Maurice LING wrote: > I've been using FB1.5 and access the database using Kinterbasdb + > Python. My connection is established using kinterbasdb.connect() method > and the parameters host, dns, database, user, password are all defaulted > to 'None'. > > On my own machine running Mac OSX 10.3, I can connect using the following: > host = 'localhost' > database = '' > user = '' > password = '' > > At the same time, I can also connect if I set host=None on my machine. > > However, I cannot use 'localhost' on a shared Linux machine (not > allowed. Don't ask why, system admin's mandate. And the Linux machine is > without inetd). So when I set host=None, I get this error: Just for my understanding: if you start your script on the machine hosting the DB you're able to connect. If you start it on a different machine, you are not able to connect without giving a hostname? Whats wrong with offering the the name (or IP-address) of your MacOS-box instead of 'localhost' to the script? Mathias From jepler at unpythonic.net Mon Jul 18 13:05:15 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Jul 2005 12:05:15 -0500 Subject: Image orientation and color information with PIL? In-Reply-To: <42DBDF0E.C380CB11@pauahtun.org> References: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> <42DBDF0E.C380CB11@pauahtun.org> Message-ID: <20050718170515.GH2199@unpythonic.net> On Mon, Jul 18, 2005 at 10:55:42AM -0600, Ivan Van Laningham wrote: > How are you going to determine the orientation of an image without > sophisticated image analysis? There is research on automatic image > orientation detection. [...] > If you write it I'll use it;-) There's research going on in this area. Here are a few papers: http://www.dcs.shef.ac.uk/teaching/eproj/msc2004/abs/m3zs2.htm http://research.microsoft.com/research/pubs/view.aspx?pubid=918 there are probably many others. I considered implementing one of these algorithms back in 2003 or so, but instead I bought a digital camera with an orientation sensor. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From twic at urchin.earth.li Sun Jul 3 05:56:42 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 3 Jul 2005 10:56:42 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: On Sun, 3 Jul 2005, Steven D'Aprano wrote: > On Sun, 03 Jul 2005 02:22:23 +0200, Fredrik Johansson wrote: > >> On 7/3/05, Tom Anderson wrote: >>> That's one way. I'd do: >>> >>> root = value ** 0.5 >>> >>> Does that mean we can expect Guido to drop math.sqrt in py3k? :) >> >> I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) >> gives 3.9999999999999996, and this error could be avoided. > > py> math.exp(math.log(64)/3.0) > 4.0 > > Success!!! Eeeeeeenteresting. I have no idea why this works. Given that math.log is always going to be approximate for numbers which aren't rational powers of e (which, since e is transcendental, is all rational numbers, and therefore all python floats, isn't it?), i'd expect to get the same roundoff errors here as with exponentiation. Is it just that the errors are sufficiently smaller that it looks exact? > Note how much simpler this would be if we could guarantee proper > infinities and NaNs in the code. We could turn a 23-line block to a > one-liner. YES! This is something that winds me up no end; as far as i can tell, there is no clean programmatic way to make an inf or a NaN; in code i write which cares about such things, i have to start: inf = 1e300 ** 1e300 nan = inf - inf Every bloody time. I'm going to be buggered if python ever rolls out some sort of bigfloat support. And then god forbid i should actually want to test if a number is NaN, since, bizarrely, (x == nan) is true for every x; instead, i have to write: def isnan(x): return (x == 0.0) and (x == 1.0) The IEEE spec actually says that (x == nan) should be *false* for every x, including nan. I'm not sure if this is more or less stupid than what python does! And while i'm ranting, how come these expressions aren't the same: 1e300 * 1e300 1e300 ** 2 And finally, does Guido know something about arithmetic that i don't, or is this expression: -1.0 ** 0.5 Evaluated wrongly? tom -- Please! Undo clips before opening handle. From tzot at sil-tec.gr Sat Jul 2 09:25:48 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 16:25:48 +0300 Subject: MD5 problem References: <42ad7561$0$1325$636a15ce@news.free.fr> Message-ID: On Mon, 13 Jun 2005 14:00:33 +0200, rumours say that fargo might have written: >If I use the md5 module with .txt files, it'ok. > >The Problem comes from the .msg files. I get the same signature for >every .msg file I try to hash with the md5 algorithm. I think some >character are strange for python, and makes it stop before the end of >the .msg file. FYI: the character that was strange for Windows (not Python) was chr(26), or Ctrl-Z, or end-of-file, which is special for files opened as text instead of binary. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From giles_brown at hotmail.com Thu Jul 7 09:25:29 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 7 Jul 2005 06:25:29 -0700 Subject: Windows Cmd.exe Window In-Reply-To: References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: <1120742729.424832.189110@f14g2000cwb.googlegroups.com> Nah. You're missing my point. I only want the command window not to be closed if there is an *exception*. Picky I know, but there you go. Giles From hancock at anansispaceworks.com Thu Jul 21 03:44:03 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 21 Jul 2005 02:44:03 -0500 Subject: Generating images with text in them In-Reply-To: References: Message-ID: <200507210244.03423.hancock@anansispaceworks.com> On Wednesday 20 July 2005 11:59 pm, phil hunt wrote: > I am trying to generate some images (gifs or pngs) with text in > them. I can use the Python Imaging Library, but it only has access > to the default, rather crappy, font. On the fly, or just during development? In any case, you should be aware of the Skencil vector graphic program which is written in Python (with some C extensions), and which is also, of course, a python vector-graphics library. Unfortunately, getting it to work in a server environment might not be too pretty (requires GTK, etc, even if you don't actually use it). I tried to make a stripped down version that didn't require the desktop stuff, but it hasn't worked out so well yet. > Alternately, is there a good source of PIL font files (.pil files) > somewhere? I believe there is a utility for converting other types of fonts, you might have to go through a couple of different conversions from the font files you have. > If the writers of the Python Imaging Library are reading this, may I > suggest that they add more fonts to it. Yes, that would increase > the size, but these days disk space is cheap and programmer time > expensive. While bitmap font files are not copyrightable, there are license issues with most of the "nicer" fonts you are probably talking about. That complicates bundling them with the software. The PIL site does actually have some additional fonts for download, though, IIRC. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From rrr at ronadam.com Mon Jul 18 21:15:06 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 19 Jul 2005 01:15:06 GMT Subject: Ordering Products In-Reply-To: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Here might be an interesting puzzle for people who like sorting > algorithms ( and no I'm not a student anymore and the problem is not a > students 'homework' but a particular question associated with a > computer algebra system in Python I'm currently developing in my > sparetime ). > > For motivation lets define some expression class first: This works for (simple) expressions with mixed multiplication and addition. class F(list): def __init__(self,*x): #print '\nF:',x list.__init__(self,x) def __add__(self, other): return A(self,other) def __radd__(self, other): return A(other,self) def __mul__(self, other): return M(self,other) def __rmul__(self, other): return M(other,self) def __repr__(self): return str(self[0]) def __order__(self): for i in self: if isinstance(i,A) \ or isinstance(i,M): i.__order__() self.sort() class A(F): def __init__(self, *x): #print '\nA:',x list.__init__(self, x) def __repr__(self): self.__order__() return "+".join([str(x) for x in self]) class M(F): def __init__(self,*x): #print '\nM:',x list.__init__(self,x) def __repr__(self): self.__order__() return "*".join([str(x) for x in self]) a = F('a') b = F('b') c = F('c') d = F('d') print '\n a =', a print '\n b+a+2 =', b+a+2 print '\n c*b+d*a+2 =', c*b+d*a+2 print '\n 7*a*8*9+b =', 7*a*8*9+b >>> a = a b+a+2 = 2+a+b c*b+d*a+2 = 2+a*d+b*c 7*a*8*9+b = 9*8*7*a+b <-- reverse sorted digits? >>> The digits sort in reverse for some strange reason I haven't figured out yet, but they are grouped together. And expressions of the type a*(c+b) don't work in this example. It probably needs some better logic to merge adjacent like groups. I think the reverse sorting my be a side effect of the nesting that takes place when the expressions are built. Having the digits first might be an advantage as you can use a for loop to add or multiply them until you get to a not digit. Anyway, interesting stuff. ;-) Cheers, Ron From roy at panix.com Sat Jul 2 09:25:46 2005 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jul 2005 09:25:46 -0400 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: "Ralf W. Grosse-Kunstleve" wrote: > class grouping: > > def __init__(self, .keep_this, .and_this, but_not_this, .but_this_again): > # real code right here I'm really torn about this. On the one hand, my first thought was "you shouldn't be writing constructors with arguments lists so long that this is a problem", but you showed a reasonable counter-example to that argument. I'm a big fan of DRY (Don't Repeat Yourself), sometimes expressed as "Once And Only Once", and your proposal lets you do that. It also has the nice feature that it doesn't break any existing code; the suggested syntax is not currently legal Python. What happens if I do: def __init__ (self, .x, .y, .z): x = 0 what does the assignment x do? Does it automatically get promoted to an assignment to self.x? Does it generate an error? The big question in my mind is not "Is this useful" (since it clearly is), but "Does the utility justify the cost?". In other words, will it be used frequently enough to compensate for the added complexity to the language? I'm not convinced of that. There have been some proposals floating around to implement a "with" keyword which would create implicit namespaces. That's sort of what you're proposing here. I'm not convinced either is a good idea, but if they were to be adopted, I'd certainly want to see the them done in a uniform, logically consistent way. From peter at engcorp.com Thu Jul 21 13:42:44 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Jul 2005 13:42:44 -0400 Subject: PEP on path module for standard library In-Reply-To: References: Message-ID: Michael Hoffman wrote: > For the PEP, do any of you have arguments for or against including path? > Code samples that are much easier or more difficult with this class > would also be most helpful. I believe the strongest argument for "path" can be made for how it integrates functionality which, although closely related conceptually, is currently distributed across a half dozen or more different modules in the standard library. Especially for newbies (I can only imagine, at this stage) it would make working with files much easier in a many ways. "Easier" or "more difficult" is a subjective thing, of course, but one can't argue with the fact that path can sometimes do through a single object what would otherwise require several imports and a bunch of calls into things like open(), os.path, grep, and shutil. Examples showing effective uses of path that simplify those cases would probably merit the label "easier" even in Guido's mind, though unfortunately that's not certain. "Easier" in some minds might simply translate to "many lines less code", and while path can sometimes do that, aside from the ease of splitting and joining stuff without multiple calls to os.path.this-and-that, it really doesn't often reduce code size _that_ much, in my experience. (Postings to c.l.p showing a 50% reduction in code size for contrived examples notwithstanding.) A related thoughts: since paths are objects, they have attributes or properties, and having things like ".basename" and ".parent" readily available without having to do obscure things like os.path.split(somepath)[0] makes things much easier to read (therefore more maintainable). In fact, I'd propose that as another strong argument in path's favour: it makes code much more readable, even if not "easier" to write. Hmm... does "easier" or "more difficult" apply to the writing of the code or the reading of it? I find it self-evident that code written using "path" is much easier to read, not necessarily much easier to write (for non-newbies). I'd summarize this by saying that the integration of "path" in the stdlib would make it easier for newbies to write code (that might not be obvious to a non-newbie... shall we ask some to help?), and easier for everyone to read code (self-evident, no?), and if that's not a sufficient condition for inclusion I don't know what is. -Peter From spam.csubich+block at block.subich.spam.com Tue Jul 12 01:29:42 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 12 Jul 2005 01:29:42 -0400 Subject: Help with report In-Reply-To: References: <11d5scbb63afhee@corp.supernews.com> Message-ID: ChrisH wrote: > Oh. The one other thing I forgot to mention is that the data needs to be > already updated every 10 minutes or so automatically. You know, this is the most concise example of feature-creep in a specification that I've ever seen. From brian at sweetapp.com Wed Jul 20 05:26:10 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 20 Jul 2005 11:26:10 +0200 Subject: Python Programming Contest In-Reply-To: <1121838061.749455.44630@g14g2000cwa.googlegroups.com> References: <1121838061.749455.44630@g14g2000cwa.googlegroups.com> Message-ID: <42DE18B2.903@sweetapp.com> Raymond Hettinger wrote: > I'm curious about the stability of your timing setup. If you run your > own version of fly.py several times with the same starting seed, how > much variation do you see between runs? There is very little variation (about 0.1%) but my solution is over an order of magnitude slower than some of the submissions that I've gotten. It is likely that the overhead of my timing code is significant when running your solution. I may have to *slightly* revise my test code to get better results. I think that I can do so without changing the distribution of the random schedule so as not to be biased against some solutions. Cheers, Brian From hancock at anansispaceworks.com Thu Jul 14 14:02:06 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 14 Jul 2005 13:02:06 -0500 Subject: How can I import a py script by its absolute path name? In-Reply-To: <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> Message-ID: <200507141302.06890.hancock@anansispaceworks.com> On Thursday 14 July 2005 07:43 am, Thorsten Kampe wrote: > * Edvard Majakari (2005-07-14 12:52 +0100) > > could ildg writes: > >> I want to import c:\xxx\yyy\zzz.py into my programme, > >> What should I do? > >> Thank you~ > > > > import sys > > sys.path.append('c:\xxx\yyy') > > "sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')" While this will work, I think the OP may want something simpler: my_mod = __import__('c:\\xxx\\yyy\\mymodule.py') especially if this is following up on the relative path workaround (in which case the result will be buried in the relative path import function). The sys.path solution is the technique you should be using to establish a top-level directory for your package. Once you do that, you can use __init__.py and dotted imports to get to everything in your package by "absolute" paths (that is, relative to the top-level package, rather than to each sub-package). This is the preferred Python approach in the current design. However, the idea that it would be desireable to import packages by something like "../main_package/other_subpackage/module2.py" has been suggested, and you can implement something like this using the __import__ built-in as suggested above. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From simon.dahlbacka at gmail.com Thu Jul 21 04:37:29 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 21 Jul 2005 01:37:29 -0700 Subject: spurious syntax error when updating to 2.4 ? Message-ID: <1121935049.573062.191030@g49g2000cwa.googlegroups.com> Hi, I'm doing some preparation for a hopefully upcoming transition to python 2.4 (from 2.3.4) on winxp platform However, I'm getting SyntaxErrors in files that worked fine in 2.3, it tells me that e.g. newLanguage.language = languageElement[0].firstChild.data.encode("ascii") this line is broken However, if I modify my file just for the heck of it and comment that particular line, I still might get syntax error on that particular line, or if I insert a line before that particular line I might get away with it? Has anyone seen anything similar, or even better knows what causes this? /Simon From dave at boost-consulting.com Wed Jul 6 19:40:36 2005 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 06 Jul 2005 19:40:36 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: Tom Anderson writes: > Comrades, > > During our current discussion of the fate of functional constructs in > python, someone brought up Guido's bull on the matter: > > http://www.artima.com/weblogs/viewpost.jsp?thread=98196 > > He says he's going to dispose of map, filter, reduce and lambda. He's > going to give us product, any and all, though, which is nice of him. > > What really struck me, though, is the last line of the abstract: > > "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme > folks. :-)" > > I disagree strongly with Guido's proposals, and i am not an ex-Lisp, > -Scheme or -any-other-functional-language programmer; my only other real > language is Java. I wonder if i'm an outlier. > > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? Not. But I've gained a real appreciation for functional programming from my use of both C++ and Python. -- Dave Abrahams Boost Consulting www.boost-consulting.com From rswerdlow at goombah.com Mon Jul 18 10:22:05 2005 From: rswerdlow at goombah.com (Bob Swerdlow) Date: Mon, 18 Jul 2005 10:22:05 -0400 Subject: os.path.expanduser on Windows: UnicodeEncodeError Message-ID: <018801c58ba4$2531b840$066fa8c0@RSWERDLOW800> My application is getting this error on Windows XP (works fine on Mac OS X) when it calls os.path.expanduser: UnicodeEncodeError: 'ascii' codec can't encode characters in position 52-56: ordinal not in range(128) The code was built with Python 2.3.4. I found referenes to Path 957650, but I'm not familiar with how such fixes are processed. Is there a patch I can add to fix this? How do I know what version of Python it is fixed in - that is, will upgrading to Python 2.3.5 fix this? Thanks for your help, Bob Swerdlow VP Engineering Goombah - Music Discovery rswerdlow at goombah.com From mwm at mired.org Wed Jul 13 21:57:35 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 13 Jul 2005 21:57:35 -0400 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <1120625123.135496.318590@g44g2000cwa.googlegroups.com> <1120678061.051033.230090@f14g2000cwb.googlegroups.com> Message-ID: <86slyib14g.fsf@bhuda.mired.org> Andreas Kostyrka writes: > That doesn't change the contrary facts: > > -) the general threading programming model is very hard to get right. > It's basically at the moment where we were with memory management at C > level. Painful, and errorprone. Nothing to be happy about. I'd say the common threading programming model is very hard to get right. There are other models that are easy to get right. They've been around for 20+ years. The problem is, they didn't make it into any popular languages, so you're stuck with the model that you talk about. Or maybe you're aware of those, and are saying all of those models aren't "right" in some way? People say good things about using the Queue module for Python. I haven't investigated it thoroughly, so I have no idea how general it is. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From erinhouston at gmail.com Fri Jul 1 11:05:35 2005 From: erinhouston at gmail.com (ina) Date: 1 Jul 2005 08:05:35 -0700 Subject: is there a better way to walk a file system? Message-ID: <1120230335.548382.96880@z14g2000cwz.googlegroups.com> I want to walk a folder structor and group all the files by extention. Here is the code I put together is there a better way of doing this? import os folderKey = "Folders" dicExt = {} tDicKey = [] tDicKey.append(folderKey) dicExt[folderKey] = [] walkPath = r"\\zek\C$\AST" for d in os.walk(walkPath): (dirpath, dirnames, filenames) = d dicExt[folderKey].append(dirpath) for fname in filenames: fs = os.path.splitext(fname) if dicExt.has_key(fs[-1]): dicExt[fs[-1]].append(os.path.join(dirpath,fname)) else: dicExt[fs[-1]] = [] dicExt[fs[-1]].append(fname) tDicKey.append(fs[-1]) for k in tDicKey: print k +" "+ str(len(dicExt[k])) Right now it is just prints out the counts. Thanks Erin From grante at visi.com Fri Jul 22 14:14:22 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 22 Jul 2005 18:14:22 -0000 Subject: return None References: <3kcpbbFtjttlU1@individual.net> Message-ID: <11e2dru68unf2e8@corp.supernews.com> On 2005-07-22, Roy Smith wrote: > In article <3kcpbbFtjttlU1 at individual.net>, Ximo wrote: >>Can I do a function which don't return anything? >> >>The question is that, if I do a function that have a return or without >>return, it returns always "None", but i want that it doesnt return me >>nothing > > What do you mean by "don't return anything", as oppossed to returning > None? Let's say I had one of those functions, and did: > > foo = noReturnValue() > print foo > > what would you expect (want?) to happen? One supposes that if noReturnValue() really didn't return anything, then the above code would cause an exception. Personally, I don't really like the idea that falling off the botton of a function implicitly returns None. It's just not explicit enough for me. My preference would be that if the function didn't execute a "return" statement, then it didn't return anyting and attempting to use a return value would be an error. I suppose there probably is code out there that depends on the implicit "return None" at the end of every function, so it's too late to change things now. -- Grant Edwards grante Yow! Is it FUN to be at a MIDGET? visi.com From zsolt-google1 at mailblocks.com Thu Jul 28 11:23:01 2005 From: zsolt-google1 at mailblocks.com (pythonUser_07) Date: 28 Jul 2005 08:23:01 -0700 Subject: Freeze In-Reply-To: <1122459808.800070.219980@g47g2000cwa.googlegroups.com> References: <1122459808.800070.219980@g47g2000cwa.googlegroups.com> Message-ID: <1122564181.185167.97200@g49g2000cwa.googlegroups.com> What happens when you take a copy of python23.dll and put it in the path on that machine? Does the program run? If so, (and I am not familiar with freeze) it seems freeze did not put the dll into the .exe file. From gsakkis at rutgers.edu Fri Jul 1 13:09:23 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 10:09:23 -0700 Subject: Regular Expression for pattern substitution References: <1120236251.006103.97030@g43g2000cwa.googlegroups.com> Message-ID: <1120237763.216043.148480@g14g2000cwa.googlegroups.com> "Deval L" wrote: > re.replace. There isn't a re.replace; be careful when you reply to newbies. > "Vibha Tripathi" wrote: > > > It'd be silly to write the code for it if it already > > exists somewhere in the Python re or sre library > > module: > > > > I need to find and replace all strings in a text file > > from a certain pattern to another pattern. > > > > so for example if I see 'this(\D*)that' anywhere in > > the file then I'd like to make is 'that(\D*)this' > > where the middle part of the strings remains > > unmodified. > > > > Any suggestions? > > > > Peace. > > Vibha Fire up the interpreter and write: >>> import re >>> line = 'see this man with that woman holding this dog and that cat' >>> r = re.compile(r'this(\D*?)that') >>> r.sub(r'that\1this',line) 'see that man with this woman holding that dog and this cat' George From t-meyer at ihug.co.nz Sun Jul 31 21:24:42 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 1 Aug 2005 13:24:42 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > Above all, nobody can tell me that there's any programmer who > doesn't instantly recognize '/' as a directory separator. There is a programmer who doesn't instantly recognise '/' as a directory separator. I teach programming. The above is true. I think that the statement "any programmer would instantly recognise '/' as division (and associate it therewith)" is much more likely to be true. =Tony.Meyer From dial#####$$NOSPAM##$#$##tone at gmail.com Tue Jul 19 13:30:21 2005 From: dial#####$$NOSPAM##$#$##tone at gmail.com (Valentino Volonghi aka Dialtone) Date: Tue, 19 Jul 2005 19:30:21 +0200 Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> Message-ID: <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> istvan.albert at gmail.com wrote: > I have not used Nevow but I have seen a few examples of how it works > and I kept track of it over the years. > > It used to be very similar to how Cheetah or ZPT does its job. You had > a template, and you filled it with data to produce an output. It seems > that it has now more features such a form submission and validation. Formless has been part of nevow since the very beginning. It has also been part of woven (Nevow predecessor), just like liveevil (now enhanced and called livepage). The only part of nevow that you can compare to ZPT or Cheetah is its xmlfile template language. There is no way you can run Nevow on top of any other framework. Also you don't pass data to the templating engine. It's nevow that parses the template and iterates over it to render the page. The template is very stupid in nevow and everything is done in nevow.flat.flattenFactory called by nevow.rend.Page. > On the other hand I even in its current form I don't see how I would to > the simple things that I need every day. Create a session, set a > cookie, redirect to another url, perform HTTP autentication, create > filter, use another templating language? This is also integral part of > the functionality that I expect from an web framework. Web specific > things exposed in some python ic way. Sessions are handled by default with twisted.web: from twisted.application import service, strports from nevow import appserver from nevow import rend, loaders, tags as t, inevow class RootPage(rend.Page): addSlash = True def display_session(self, ctx, data): return inevow.ISession(ctx).uid docFactory = loaders.stan( t.html[t.head[t.title["Session example"]], t.body[display_session]] ) application = service.Application('Foobar') site = appserver.NevowSite(RootPage()) server = strports.service('8080', site) server.setServiceParent(application) Save this in a .py or .tac and run it with twistd -noy filename.tac/.py and open http://localhost:8080/ in your browser to see your session uid. If you want autentication: http://nevowexamples.adytum.us/sources/guarded.py http://nevowexamples.adytum.us/sources/guarded2.py There are 2 examples (in the standard nevow distribution) that show how to handle authentication in an application transparent way (you don't have to touch your application by any means to add user authentication, which means you can write everything without taking care of this aspect of the app and then add it later). To redirect to another url just call IRequest(ctx).redirect(newurl) before the rendering begins (like in rend.Page.beforeRender) or in rend.Page.locateChild. HTTPAuthentication is easily handled: http://nevowexamples.adytum.us/sources/http_auth.py just use that class as a base class for your blocked page. (this example is part of the standard nevow distribution). Nevow doesn't have filters because they are handled by twisted.web or twisted.web2 (which is, hopefully soon, going to be one of the required webservers to run nevow, the others are lighttpd, apache, any WSGI application server, nevow was in fact the first framework to support WSGI servers). If you want to use a different templating language you just need to write a custom loader. Somebody did this in the past (I don't recall the url of the project) that used cheetah-like templates. Then for the last point: you can expose directories or files using nevow.static.File exposed objects are: those set as a value in rend.Page.children dict, you can reach them with an url like: http://www.example.com/url/that/returns/a/page/inst/key_in_children_dict Or assign an object to a child_foobar attribute like: p = rend.Page() p.child_foobar = static.File('/etc/') Or return an object from a child_foobar method. Or override rend.Page.childFactory(self, ctx, segment) to return an object in a dynamic way depending on the value of the segment argument. It seems to me that you really never tracked Nevow, your information is very incomplete. I think you should complete it before talking about Nevow :). -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.4 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From Vajrala.Madhusudana at mayo.edu Thu Jul 14 13:23:29 2005 From: Vajrala.Madhusudana at mayo.edu (Madhu R. Vajrala) Date: Thu, 14 Jul 2005 12:23:29 -0500 Subject: Python Installation error on Solaris-9-SPARC Message-ID: <1121361810.31924.5.camel@indica> Hello All, I am very new to Python, trying to install it from source (ftp://ftp.sunfreeware.com/pub/freeware/SOURCES/python-2.3.3.tar.gz) on Sun Solaris-9 (SPARC). But getting the below error message during configure. Also while uncompressing, it is returning the checksum doesnt match error as well. Configure Error: config.status: error: cannot find input file: Modules/Setup.config.in untar error: . . . . . . x Python-2.3.3/Mac/OSXResources/app/Resources/English.lproj/Documentation/doc, 0 bytes, 0 tape blocks x Python-2.3.3/Mac/OSXResources/app/Resources/English.lproj/Documentation/doc/index.html, 882 bytes, 2 tape blocks x Python-2.3.3/Mac/OSXResources/app/Resources/English.lproj/Documentation/ide, 0 bytes, 0 tape blocks x Python-2.3.3/Mac/OSXResources/app/Resources/English.lproj/Documentation/ide/index.html, 9909 bytes, 20 tape blocks x Python-2.3.3/Mac/OSXResources/app/Resources/English.lproj/Documentation/ide/IDE.gif, 10249 bytes, 21 tape blocks tar: directory checksum error Can someone help me understand why it is returning error, Also I do not 'root' privileges on the server that i am trying install. So I will be installing my home directory. Thank You, Madhu From devlai at gmail.com Tue Jul 12 16:34:20 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 13:34:20 -0700 Subject: Creating anonymous functions using eval In-Reply-To: References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> <1121184988.996652.126350@g47g2000cwa.googlegroups.com> Message-ID: <1121200460.620017.6780@g49g2000cwa.googlegroups.com> > You missed Steven's point which is to quote the message to which you are > replying. Not everyone is reading this list in a conveniently threaded > form, so you need to provide some context for them to be able to follow > along. Ah, sorry, I didn't quite get what he was referring to. From draghuram at gmail.com Mon Jul 4 20:30:57 2005 From: draghuram at gmail.com (draghuram at gmail.com) Date: 4 Jul 2005 17:30:57 -0700 Subject: pexpect question.... In-Reply-To: References: <1120236289.836018.234240@f14g2000cwb.googlegroups.com> Message-ID: <1120523457.383717.109480@g14g2000cwa.googlegroups.com> Hi, I actually replied saying that the process dies when close(wait=0) is done (the reply doesn't show up yet). It is not correct. The process actually runs but ends up in zombie status (defunct). Raghu. From miki.tebeka at zoran.com Mon Jul 4 08:43:57 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 4 Jul 2005 15:43:57 +0300 Subject: OT: ^ in redirection (windows) Message-ID: <20050704124357.GC3876@zoran.com> Hello All, Can someone explain me the difference between: echo 1 > 1.txt 2>&1 and echo 1 > 1.txt 2>^&1 (Windows XP "cmd" shell) Both produce 1.txt with the content 1. (Sadly, I don't know how to search for ^ in google). Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From nothingcanfulfill at gmail.com Sun Jul 24 22:07:43 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 24 Jul 2005 19:07:43 -0700 Subject: Simple Problem In-Reply-To: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> References: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> Message-ID: <1122257263.827269.56730@f14g2000cwb.googlegroups.com> Thank you all for your replies. The repr() solution wasn't exactly what I was looking for, as I wasn't planning on eval()ing it, but the (en|de)code solution was exactly what I was looking for. An extended thanks to Jp for informing me of the version compatibility :) Have a GREAT day :) -Wes From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 12:43:41 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 18:43:41 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> Message-ID: <3kkj5tFv0el1U1@individual.net> skip at pobox.com wrote: > Reinhold> Right, that was a concern of mine, too. > Reinhold> "tobase"? > Reinhold> "tostring"? > Reinhold> "tobasestring"? > > If we're on a filesystem that understands unicode, would somepath.tostring() > return a unicode object or a string object encoded with some > to-be-determined encoding? Whatever the base of the Path object is. It selects its base class based on os.path.supports_unicode_filenames. > Why not just add __str__ and __unicode__ methods to the class and let the > user use str(somepath) or unicode(somepath) as needed? > > Or am I missing something fundamental about what the base() method is > supposed to do? It should provide an alternative way of spelling Path.__bases__[0](path). Reinhold From me at privacy.net Mon Jul 18 09:15:58 2005 From: me at privacy.net (Admin) Date: Mon, 18 Jul 2005 10:15:58 -0300 Subject: What is your favorite Python web framework? References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> Message-ID: On Mon, 18 Jul 2005 10:06:21 -0300, Peter Hansen wrote: > I'm not familiar with this expression. What do you mean by "black > horse"? That will help me too :) -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From uwb at uwbomb.net Fri Jul 8 15:55:37 2005 From: uwb at uwbomb.net (uwb) Date: Fri, 08 Jul 2005 19:55:37 GMT Subject: file handling in a server (.py) file using xmlrpc References: Message-ID: Jeremy Jones wrote: >>The script executes, no error messages, but the glob call turns up nothing >>while the identical call running from a console does in fact turn up files >>names as expected. >> >> > Wild guess, but I'm thinking your webserver process doesn't have > permissions to look in your directory. > > Following is alternating root shell and IPython shell: > > root at qiwi:~ # chmod 777 /bam > root at qiwi:~ # ls -ld /bam > drwxrwxrwx 2 root root 96 Jul 8 14:53 /bam > > In [4]: glob.glob("/bam/*txt") > Out[4]: ['/bam/foo.txt', '/bam/bar.txt'] > > root at qiwi:~ # chmod 000 /bam > root at qiwi:~ # ls -ld /bam > d--------- 2 root root 96 Jul 8 14:53 /bam > > In [5]: glob.glob("/bam/*txt") > Out[5]: [] > > > HTH, > > Jeremy Jones Thanks! Thing does work when I do globs of the local apache directories. From grante at visi.com Mon Jul 11 17:44:08 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Jul 2005 21:44:08 -0000 Subject: read output and store in file References: <1121117484.692617.76590@o13g2000cwo.googlegroups.com> Message-ID: <11d5q185v26lt6f@corp.supernews.com> On 2005-07-11, b83503104 at yahoo.com wrote: > I'm a beginner, and what I want to accomplish is this: > > 1. For all files under several folders, do some processing (using an > existing program). The program will output one line of text for each > file. > > 2. Store the output of all files in one file. > > It would be great if someone can give me a crash start on accomplishing > this. If you think there is a definitely better tool than Python for > doing this, please tell me so. I just heard that Python or Perl are > better in these kind of jobs. Using bash and find: (find path1 path2 path3 -type f -exec existingProgram {} \;) >outputFile -- Grant Edwards grante Yow! You can't hurt at me!! I have an ASSUMABLE visi.com MORTGAGE!! From hancock at anansispaceworks.com Sat Jul 2 17:23:06 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 16:23:06 -0500 Subject: shelve in a ZipFile? In-Reply-To: <1120254041.6823.70.camel@andi-lap> References: <42c57b58$1@nntp0.pdx.net> <1120254041.6823.70.camel@andi-lap> Message-ID: <200507021623.06336.hancock@anansispaceworks.com> On Friday 01 July 2005 04:40 pm, Andreas Kostyrka wrote: > It's even worse: shelve is basically a class that wraps a dictionary. It > provides a dictionary string -> pickable object based on a dictioary > string -> string. bsddb, gdbm etc. probably access files via lowlevel > calls that are not interceptable. > > One way to achieve your goals would be to add compression and/or a key > prefix (which would allow multiple dictionaries or at least key spaces > in one file) Yeah, I'm already using a character prefix for header data in the 1st file. Right now, one of the headers tells where to find the 2nd file. Seems to be working okay. I'm a little bothered by the idea of lumping both into one dictionary, though I see this could be done the same way. I wasn't really looking for a way to compress the data (just thought it was a nice side benefit), but your post reminded me that I could do it with zlib on the data *before* storing them in the shelf. I guess if bulk becomes an issue I'll try that. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at holdenweb.com Thu Jul 28 10:01:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jul 2005 15:01:13 +0100 Subject: all possible combinations In-Reply-To: References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> <42d6de96@news.eftel.com> <1122547119.104995.43340@o13g2000cwo.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Thu, 28 Jul 2005 12:30:23 +0100, Steve Holden wrote: > > >>>This makes me wonder why we still don't have something like the unint >>>function above in the standard distribution. >>> >> >>Because it's not what you'd call (or, at least, it's not what I'd call) >>universally required. As you have shown it is relatively easy to hack >>something supp when it's needed, so since it isn't something that's >>required by the majority it hasn't been added to the library. > > > Have you looked at what's in the standard Python library? > > aifc.py => Stuff to parse AIFF-C and AIFF files. > imghdr.py => Recognize image file formats based on their first few bytes. > gopher.py => Gopher protocol client interface. > token.py => Token constants (from "token.h"). > > I'm sure they are useful to somebody, but do you really think that the > majority of Python users need to parse AIFF files? > > Converting base-19 strings into integers is a rather niche need, but if > somebody bothered to write, document and provide unittests for such a > module, I'm sure it could be added to the standard library. It isn't as if > there is any policy of prohibiting specialist modules just because they > don't have universal need. > > And no, I'm not volunteering. I may, if I get an itch, but at this moment > in my life I'm not that fussed one way or another. > > > Well, here I have to fall back on history. I only started using Python in the mid-to-late 1990's. In those days modules were added to the language because they existed, and it was an easy way to distribute them. Now Python has a significant user base the development of the language, and the structure of the libraries, comes under more scrutiny, and there is a general feeling that parsimony is to be preferred to bloat. I can hardly disagree with you that aifc.py represents bloat by today's standards, and I don't think I could name a single gopher user (though that was certainly NOT the case in the mid-1990s). and-i-still-can't-find-an-email-tool-with-dwim-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From lthompson at ixiacom.com Wed Jul 13 17:06:52 2005 From: lthompson at ixiacom.com (lthompson at ixiacom.com) Date: 13 Jul 2005 14:06:52 -0700 Subject: Are there any decent python memory profilers available? Message-ID: <1121288812.369538.201250@g49g2000cwa.googlegroups.com> I have a rather large python application (uses around 40MB of memory to start) that gradually chews up memory over many hours. I've done a little googling around, but it looks like I'm faced with prowling through the gc.get_objects() myself. I need a tool to identify where the memory is going. It might even be a leak in a DLL, so maybe a pure python profiler isn't the best, although it would certainly help localize the problem. From python-url at phaseit.net Fri Jul 29 14:08:02 2005 From: python-url at phaseit.net (Simon Brunning) Date: Fri, 29 Jul 2005 18:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 29) Message-ID: QOTW: "Guido has marked the trail; don't ignore the signs unless you really know where you're going." - Raymond Hettinger 'Proverbs 28:14 JPS "Happy is the man that feareth alway; but he that hardeneth his heart shall fall into evil." Obviously an exhortation to not ignore raised exceptions with "except: pass".' - Robert Kern Jason Orendorff's path module is a popular alternative to the build in os.path and shutil modules. Michael Hoffman and Reinhold Birkenfeld are working on a PEP suggesting that it be included in the standard library: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1f5bcb67c4c73f15 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/df1b647a0f103640 Java has nearly as many web frameworks as Python, but you can run any of them on any of the Java web application servers because they are all built on the Java Servlet specification. PEP 333, the Python Web Server Gateway Interface, aims to bring something similar to the world of Python: http://www.python.org/peps/pep-0333.html A short but sweet day-of-the-month suffix generator from John Machin: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/904fa627890c85dd Thanos Tsouanas wants access to an object's namespace dictionary: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5cc509d138e1701 David Isaac wants to avoid map(), but he wants a zip() function that runs to the length of the longest sequence. It's suggested that zip() should be able to do this, but Raymond Hettinger channels Guido and thinks that this would be a bad idea: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/265675b50fee8ec1 Tiny.be release four open source enterprise applications: http://lwn.net/Articles/145209/ Who needs "Ten Essential Development Practices"? We've got The Zen of Python: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c52d3c17f1ea9ec5 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From tpc247 at gmail.com Mon Jul 11 18:22:59 2005 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Mon, 11 Jul 2005 15:22:59 -0700 Subject: [Baypiggies] BayPIGgies: July 14, 7:30pm (Google) In-Reply-To: <20050711205549.GA14110@panix.com> References: <20050711205549.GA14110@panix.com> Message-ID: I'd like to proffer the suggestion we meet for dinner at 6pm at Mei Long in Mountain View, although it's probably best to run it past our dinner coordinator first to make sure it gets his OK. What say you Brian ? On 7/11/05, Aahz wrote: > > > Before the meeting, we may meet at 6pm for dinner. Discussion of dinner > plans is handled on the BayPIGgies mailing list. This week, there has > been discussion of a potluck -- if you want a potluck, speak up NOW on > the mailing list. > > Advance notice: The August 11 meeting agenda has not been set. Please send > e-mail to baypiggies at baypiggies.net if you want to suggest an agenda (or > volunteer to give a presentation). > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > f u cn rd ths, u cn gt a gd jb n nx prgrmmng. > _______________________________________________ > Baypiggies mailing list > Baypiggies at baypiggies.net > http://www.baypiggies.net/cgi-bin/mailman/listinfo/baypiggies > From Scott.Daniels at Acm.Org Tue Jul 12 16:15:14 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 12 Jul 2005 13:15:14 -0700 Subject: Searching through a list of tuples In-Reply-To: References: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> Message-ID: <42d41cde$1@nntp0.pdx.net> Peter Otten wrote: > Repton wrote: > >>I often find myself storing data in a list of tuples, and I want to ask >>questions like "what is the index of the first tuple whose 3rd element >>is x", iter(n for n, elem in enumerate(lst) if elem[3] == x).next() >>or "give me the first tuple whose 2nd element is y". iter(elem in lst if elem[3] == x).next() Does this look any better? At least it stops when the answer is found. --Scott David Daniels Scott.Daniels at Acm.Org From peter at engcorp.com Mon Jul 18 21:33:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 21:33:57 -0400 Subject: Help with images In-Reply-To: <1121731806.578272.174590@z14g2000cwz.googlegroups.com> References: <1121731806.578272.174590@z14g2000cwz.googlegroups.com> Message-ID: Chad wrote: > I have installed a TWAIN module(from > http://twainmodule.sourceforge.net) today and figured out how to > acquire an image. The only problem is that the image is way too large > in terms of filesize. It is over 1MB. > > I can do either one of two things. Try to figure out how to manupilate > the image with this module(which I am been doing all day) or just use a > module that can compress jpegs. Can anybody help? PIL does that. From steve at REMOVEMEcyber.com.au Tue Jul 26 04:00:17 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 26 Jul 2005 18:00:17 +1000 Subject: how to write a line in a text file References: <42E5B0F0.6020206@REMOVEMEcyber.com.au> Message-ID: <42E5ED91.10402@REMOVEMEcyber.com.au> en.karpachov at ospaz.ru wrote: > Tue, Jul 26, 2005 at 01:41:36PM +1000, Steven D'Aprano ?????: > >>Long ago, when dinosaurs roamed the Earth, (a.k.a. >>"before OS X on the Macintosh") Apple suggested a bit >>of Pascal code for safely updating a file: >> >>http://developer.apple.com/documentation/mac/Files/Files-25.html#MARKER-9-163 > > > That snippet doesn't write data to the existing file. It writes data into > the new tempfile and then renames it, as well as the FileInput object does. Obviously you can't *directly* overwrite a file and expect good things to happen if the disk crashes half-way through. Any sort of safe overwrite must use an intermediate file somewhere. That goes without saying. As for the FileInput object doing the job "as well as" the old Mac file system, no it does not. I've already described how the FileInput object is only usable in a vanishingly small subset of all potential file overwrites, namely when you are writing stdout to the same text file you read from -- or at least one of the multiple files you read from. If that solution works for your needs, you should use it. But if you are not writing to stdout, your data isn't text, and you didn't get it from the same file you are overwriting, the FileInput solution is no solution at all. >>Most of the code is Macintosh-specific, but the >>principle is not: when over-writing a file, make sure >>that the user can recover from any error up to and >>including power failure without losing the data on disk. > > > Well, it's what (R)DBMS are for, but plain files are not. This isn't 1970, users expect more from professional programs than "keep your fingers crossed that nothing bad will happen". That's why applications have multiple levels of undo (and some of them even save the undo history in the file) and change-tracking, and auto-save and auto-backup. Even in the less-than-user-friendly world of Linux many applications implement their own version of data protection. Now maybe you feel that it is overkill for your program to bother about the tiny chance of data loss when saving data. That's fine. For 99% of my scripts, I don't even bother with try...except blocks when writing to a file. I just open it and write to it and hope it all works. But for that other 1%, I take the time to check for errors and allow the program to recover gracefully. And that means, if you are about to save the user's work, you better be sure that if the save fails for any reason, you haven't blown away their precious data. If you want to live dangerously with your own data, go for it. But destroying the user's data is the biggest programming sin of all. -- Steven. From theller at python.net Tue Jul 5 10:43:34 2005 From: theller at python.net (Thomas Heller) Date: Tue, 05 Jul 2005 16:43:34 +0200 Subject: Py2Exe and the log file... References: Message-ID: "fowlertrainer at anonym.hu" writes: > Hi ! > > 1. Thanx for your answer in the theme of Unicode, and other things. > 2. The problem: > I need to create an application that not need Python libs to install. > Py2Exe is good for that, but I need to copy the "dist" to the network > drive what mapped readonly. > This is a protection. > > So: in this time I have been use same applications, but they are > created by Delphi. > These apps make logs into user's temp to avoid the log merging, and > log creation problems (in readonly drive). > > Py2Exe have an exception catcher "module", that log the errors in the > log file that created in app dir. > This is problem, because the log file creation have been failed in RO drive. > > How to I redirect this log file, or can I do anything to aviod the log > file creation error ? > > Thanx for your help: ft The code that creates the logfile is in "Lib/site-packages/py2exe/boot_common.py". This code is executed before the main script is started. You can override it by assigning another object to sys.stderr, at the start of your main script, which has a write method doing what YOU want. Thomas From andreas at kostyrka.org Wed Jul 13 04:21:36 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 10:21:36 +0200 Subject: threads and sleep? In-Reply-To: <6ijmc1d5f066he8p09a406irsdabbh6ljc@4ax.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <6ijmc1d5f066he8p09a406irsdabbh6ljc@4ax.com> Message-ID: <1121242896.5240.77.camel@andi-lap> Am Mittwoch, den 06.07.2005, 04:00 +0000 schrieb Dennis Lee Bieber: > {I'm going to louse up the message tracking here by pasting part of > your > follow-up into one response} > > 2> Upon further thought, that just can't be the case. There has > 2> to be multiple instances of the intepreter because the > 2> interpreter can make C system calls that block (thus blocking > 2> that instance of the interpreter). Other Python threads within > 2> the program continue to run, so there must be multiple Python > 2> intepreters. > > From the documentation: > > """ > The lock is also released and reacquired around potentially blocking > I/O > operations like reading or writing a file, so that other threads can > run > while the thread that requests the I/O is waiting for the I/O > operation > to complete. > """ > > It will take someone who's actually worked on the runtime > interpreter, or studied the code, to, uhm, "interpret" all the above > tidbits... Not really, it's quite trivial. Anything that touches the Python/C API needs the GIL. [Python] <--Python/C API --> [Python module in C] <--some API--> [legacy C code] Now a well behaved Python C module does release the GIL before doing anything that might block/take a long time. The drawback in a Python with threading support that runs just one thread is the additional locking overhead. OTOH it's only done for operatations that will probably take a long time anyway. (And long is a relative term here *g*). Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From philippe at philippecmartin.com Fri Jul 1 14:52:42 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 01 Jul 2005 18:52:42 GMT Subject: No subject References: Message-ID: <_hgxe.2819$cb6.2350@newssvr30.news.prodigy.com> Being a C programmer before a C++ I am not certain my opinon qualifies. Yet I have seen myself avoiding C++ contracts lately because I dread going back to that type of work: why use silex when you got a match ? Adriaan Renting wrote: > I'm not a very experienced Python programmer yet, so I might be > mistaken, but there are a few things that would make me prefer C++ over > Python for large (over 500.000 LOC) projects. > - namespaces > - templates > - strong type checking > - data hiding > - more available libraries and more advanced developement tools. > > I'm talking about managing the code, not the programmers, the project or > schedules or what have you. Those are independent from the chosen > programming language. > http://www.compusa.com/products/product_info.asp?product_code=301605&pfp=cat3 >> Ultimately, manageability of a project is far and away more about the >> people involved and the techniques used than it is about any single >> technology involved. > > Agreed. > > Adriaan Renting | Email: renting at astron.nl > ASTRON | Phone: +31 521 595 217 > P.O. Box 2 | GSM: +31 6 24 25 17 28 > NL-7990 AA Dwingeloo | FAX: +31 521 597 332 > The Netherlands | Web: http://www.astron.nl/~renting/ >>>> 06/30/05 4:15 PM >>>> > Peter Hansen writes: > >> Harry George wrote: >> > "Adriaan Renting" writes: >> >>Both VB and Python are easier to learn as the more powerful >> >>languages, the price is that they lack features that make it easier > to >> >>manage large and complex projects. >> > What is a large project, and what is Python missing that C++ and > Java >> > have for such tasks? >> >> But C++ and Java have features that *management* likes, thus making it >> "easier to manage large projects". (That says nothing about whether >> or not it makes it easier to produce quality code, successful >> projects, happy customers, large profits, or any such silly >> things... just that it's "easier to manage". ;-) >> >> Less facetiously: I have managed a large Python project or three, and >> several large C++ projects (and, thankfully, no large Java projects) >> and found Python quite up to the task. In fact, if anything the C++ >> projects ended up more in danger of succumbing to the sheer weight of >> the code than did the Python projects. But I attribute this more to >> the fact that we had evolved to using agile approaches with the Python >> projects than to any of those special features either present or >> lacking in C++. >> >> Ultimately, manageability of a project is far and away more about the >> people involved and the techniques used than it is about any single >> technology involved. >> >> -Peter > > That's our experience too (and the reason I asked). I wonder if the > OP will respond. > > From istvan.albert at gmail.com Tue Jul 19 12:56:02 2005 From: istvan.albert at gmail.com (istvan.albert at gmail.com) Date: 19 Jul 2005 09:56:02 -0700 Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> Message-ID: <1121792162.939519.9890@g43g2000cwa.googlegroups.com> I have not used Nevow but I have seen a few examples of how it works and I kept track of it over the years. It used to be very similar to how Cheetah or ZPT does its job. You had a template, and you filled it with data to produce an output. It seems that it has now more features such a form submission and validation. On the other hand I even in its current form I don't see how I would to the simple things that I need every day. Create a session, set a cookie, redirect to another url, perform HTTP autentication, create filter, use another templating language? This is also integral part of the functionality that I expect from an web framework. Web specific things exposed in some python ic way. To avoid any negative feelings I'll remove all remarks to what I think is not a web framework. Istvan. From skip at pobox.com Thu Jul 21 07:25:26 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 21 Jul 2005 06:25:26 -0500 Subject: gdb python C API In-Reply-To: <42df7bfa$0$4724$636a15ce@news.free.fr> References: <42df7bfa$0$4724$636a15ce@news.free.fr> Message-ID: <17119.34342.249422.534689@montanaro.dyndns.org> fraca7> derrick a ?crit : >> are there any tools / methods that others have used to get what line >> of the python script is being executed while running in gdb? or if it >> would actually show me the source python script (instead of the the >> python c source) that would help. fraca7> I don't think so, but when having a memory problem I usually fraca7> find valgrind very useful. Actually, take a look in the distribution at Misc/gdbinit. In particular, check out the pystack command. Skip From newsgroups at jhrothjr.com Mon Jul 4 08:56:31 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 4 Jul 2005 06:56:31 -0600 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> <1120368681.573445.199710@g44g2000cwa.googlegroups.com> <1120371274.448543.145890@g43g2000cwa.googlegroups.com> <1120398483.415818.95360@o13g2000cwo.googlegroups.com> Message-ID: <11cicg4fbeer8e8@news.supernews.com> "Peter Maas" wrote in message news:dab25m$dvk$1 at swifty.westend.com... > George Sakkis schrieb: >> Given that the latest 2.x python will be 2.9 > > Why not 2.13 or 2.4711? Version strings are sequences of arbitrary > integers separated by dots and not decimal numbers, or are they? Because Guido said (somewhere) that he didn't want to go over release 2.9. John Roth > > -- > ------------------------------------------------------------------- > Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') > ------------------------------------------------------------------- From steve at REMOVEMEcyber.com.au Sun Jul 3 23:31:59 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 13:31:59 +1000 Subject: math.nroot [was Re: A brief question.] References: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> <8AXxe.3186$HV1.2814@fed1read07> Message-ID: <42C8ADAF.1040708@REMOVEMEcyber.com.au> James Dennett wrote: > > Yes: 5^2 + -2^2 is 29, however you write it. > > *If* you take -2 as a number, but not if you take the number > as 2 and the unary minus as an operator with lower precedence > than exponentiation. [snip] > Not in this respect. However, the question is whether that's > a unary -, which binds lower than exponentiation in most systems, > or part of the negative number minus 2. In Python, all numbers are positive. -2 is a unary minus in front of 2. -- Steven. From peter at engcorp.com Sat Jul 23 10:23:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Jul 2005 10:23:11 -0400 Subject: PEP on path module for standard library In-Reply-To: <1122103716.047d4c80bde51f39c1c9b5251fd07bfc@teranews> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> <1122074127.098fda4a2097406639f8c6b7f8b523ed@teranews> <1122103716.047d4c80bde51f39c1c9b5251fd07bfc@teranews> Message-ID: <2vmdnTyi-uRJz3_fRVn-1A@powergate.ca> George Sakkis wrote: > "Andrew Dalke" wrote: >>I think that the string representation of a path is so important that >>it *is* the path. > > There are (at least) two frequently used path string representations, > the absolute and the relative to the working directory. Which one > *is* the path ? Depending on the application, one of them woud > be more natural choice than the other. Sorry, George, but that's now how it works. Whether using the regular string-based Python paths or the new path module, a path *is* either absolute or relative, but cannot be both at the same time. This is therefore not an issue of "representation" but one of state. -Peter From hpj at urpla.net Wed Jul 20 12:30:36 2005 From: hpj at urpla.net (Hans-Peter Jansen) Date: Wed, 20 Jul 2005 18:30:36 +0200 Subject: convert ascii escapes into binary form Message-ID: Hi Pythonistas, I need to convert ascii escapes into binary form, e.g.: \f -> ^L \033@\x1bk\000 -> ^[@^[k^@ (rvalues in terminal representation) Any idea, how to do this most elegantly in python? Do I really need to do a search n'replace orgy, combined with regex for this task? TIA, Pete From sjmachin at lexicon.net Fri Jul 22 09:31:29 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jul 2005 23:31:29 +1000 Subject: Difference between " and ' In-Reply-To: <2b-dnStjP7tKdH3fRVn-sA@powergate.ca> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> <2b-dnStjP7tKdH3fRVn-sA@powergate.ca> Message-ID: <42e0f530$1@news.eftel.com> Peter Hansen wrote: > Steven D'Aprano wrote: > >> It may shock some people to learn that difference in the sense of >> mathematical subtraction is not the only meaning of the word, but >> there it is. One wouldn't, I hope, misunderstand "What is the >> difference between spaghetti marinara and spaghetti pescatora?" and >> attempt to subtract one from the other, since subtraction is not >> defined for foodstuffs. > > > >>> sum(ord(c) for c in 'spaghetti marinara') - sum(ord(c) for c in > "spaghetti pescatora") > -119 > > Works for me... ;-) Works for me too: C:\junk>python --fuzzy --punt Python 9.4.1 (#165, Mar 30 3005, 09:13:57) [MSC v.13109 1024 bit (Intel)] on win1024 Type "help", "copyright", "credits" or "license" for more information. >>> a = foodstuff('spaghetti marinara') >>> b = foodstuff('spaghetti pescatora') >>> a - b 0 >>> explain a.base is b.base a.topping != b.topping but fuzzy mode selected a.topping isa salty_smelly_stuff b.topping isa salty_smelly_stuff punt mode selected prob(customer_knows_difference) = 0.01 PSF interdiction all your operator are belong to us From mrvajrala at yahoo.com Thu Jul 14 13:50:16 2005 From: mrvajrala at yahoo.com (Madhu R. Vajrala) Date: 14 Jul 2005 10:50:16 -0700 Subject: Python Installation error on Solaris-9-SPARC References: <1121362775.799428.239840@g47g2000cwa.googlegroups.com> Message-ID: <1121363416.498522.138420@g43g2000cwa.googlegroups.com> I did... 1. wget http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz 2. gunzip -c Python-2.4.1.tgz | tar xvf - the above step errors: -------- tar: directory checksum error gunzip: stdout: Broken pipe -------- 3. Later.... in ./configure step... This step also fails...(I did run this by ignoring the checksum error in the previous step). checking for build directories... done configure: creating ./config.status config.status: creating Makefile.pre config.status: creating Modules/Setup.config **config.status: error: cannot find input file: Modules/Setup.config.in** ____________________________________________________ Thank You, madhu From rocky at serverzen.com Fri Jul 29 21:24:08 2005 From: rocky at serverzen.com (Rocky Burt) Date: Fri, 29 Jul 2005 22:54:08 -0230 Subject: ANN: PyDev 0.9.7 released In-Reply-To: <42E6412A.4020905@esss.com.br> References: <42A720BD.5050701@esss.com.br> <42C175A5.5000206@esss.com.br> <42E6412A.4020905@esss.com.br> Message-ID: <1122686648.30014.16.camel@zebrax.local.carterscove.com> Installing fresh PyDev 0.9.7 onto eclipse 3.1 (no prior PyDev installed) yields the following error when opening a python file. Seems like a simple enough error... the PyEdit class seems to be present. java.lang.ClassNotFoundException: org.python.pydev.editor.PyEdit at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:403) at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:350) at org.eclipse.osgi.framework.adaptor.core.AbstractClassLoader.loadClass(AbstractClassLoader.java:78) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at org.eclipse.osgi.framework.internal.core.BundleLoader.loadClass(BundleLoader.java:275) at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:227) at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1259) at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:152) at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:142) at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:129) at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:48) at org.eclipse.ui.internal.WorkbenchPlugin $1.run(WorkbenchPlugin.java:240) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.ui.internal.WorkbenchPlugin.createExtension(WorkbenchPlugin.java:236) at org.eclipse.ui.internal.registry.EditorDescriptor.createEditor(EditorDescriptor.java:252) at org.eclipse.ui.internal.EditorManager.createPart(EditorManager.java:837) at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:543) at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:365) at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:552) at org.eclipse.ui.internal.EditorAreaHelper.setVisibleEditor(EditorAreaHelper.java:258) at org.eclipse.ui.internal.EditorManager.setVisibleEditor(EditorManager.java:1216) at org.eclipse.ui.internal.EditorManager$5.run(EditorManager.java:944) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1044) at org.eclipse.core.runtime.Platform.run(Platform.java:783) at org.eclipse.ui.internal.EditorManager.restoreState(EditorManager.java:939) at org.eclipse.ui.internal.WorkbenchPage.restoreState(WorkbenchPage.java:2535) at org.eclipse.ui.internal.WorkbenchWindow.restoreState(WorkbenchWindow.java:1819) at org.eclipse.ui.internal.Workbench.doRestoreState(Workbench.java:2566) at org.eclipse.ui.internal.Workbench.access$14(Workbench.java:2515) at org.eclipse.ui.internal.Workbench$19.run(Workbench.java:1514) at org.eclipse.ui.internal.Workbench$16.run(Workbench.java:1263) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:346) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:291) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:447) at org.eclipse.ui.internal.Workbench.runStartupWithProgress(Workbench.java:1258) at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1512) at org.eclipse.ui.internal.Workbench.access$12(Workbench.java:1491) at org.eclipse.ui.internal.Workbench$17.run(Workbench.java:1374) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1044) at org.eclipse.core.runtime.Platform.run(Platform.java:783) at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1318) at org.eclipse.ui.internal.WorkbenchConfigurer.restoreState(WorkbenchConfigurer.java:183) at org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:700) at org.eclipse.ui.internal.Workbench.init(Workbench.java:1034) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1636) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:367) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:143) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:103) at org.eclipse.core.internal.runtime.PlatformActivator $1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:376) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:163) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.invokeFramework(Main.java:334) at org.eclipse.core.launcher.Main.basicRun(Main.java:278) at org.eclipse.core.launcher.Main.run(Main.java:973) at org.eclipse.core.launcher.Main.main(Main.java:948) On Tue, 2005-07-26 at 10:56 -0300, Fabio Zadrozny wrote: > Hi All, > > PyDev - Python IDE (Python Development Enviroment for Eclipse) version > 0.9.7 has just been released. > > Check the homepage (http://pydev.sourceforge.net/) for more details. > > Release Highlights: > > This build fixes some nasty bugs from 0.9.6... it is highly recommended > you install it. (right now, everything but the debugger should work fine > with 3.1). > > Important notes > > Note 1: Because of some issues with Eclipse, you have to uninstall all > previous PyDev installations before installing the new release. > Note 2: This release only works with Eclipse 3.1 (and from now on, > Eclipse 3.0.x is no longer supported). > Note 3: Java 5.0 is required from now on. > > Regards, > > Fabio > From golancester at gmail.com Wed Jul 13 10:38:58 2005 From: golancester at gmail.com (Michael Jordan) Date: 13 Jul 2005 07:38:58 -0700 Subject: String Manipulation Message-ID: <1121265538.351527.158950@f14g2000cwb.googlegroups.com> i'll be straight with you and say that this is a homework assignment. ive tried to figure it out on my own but am now out of time. i need to go through a .txt file and get rid of all punctuation. also, every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is ANY number i need to get rid of that also. thanks a bunch. hurry please! jen :) From steve at REMOVETHIScyber.com.au Sun Jul 31 07:05:56 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 21:05:56 +1000 Subject: How to convert a string like '777' to an octal integer like 0777? References: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> <42ec640a@news.eftel.com> <1122794648.326967.284070@g47g2000cwa.googlegroups.com> Message-ID: On Sun, 31 Jul 2005 00:24:08 -0700, KB wrote: > Thanks, John. > > But my point is how to keep the leading zero in 0777, > in order to be used in os.chmod('myfile', 0777)? os.chmod('myfile', 0777) Python will recognise integers written in octal if you leave a leading zero, and in hex if you use a leading 0x or 0X. >>> 010 8 >>> 0x10 16 >>> 010 + 0x10 24 As John pointed out, you don't have to use octal for chmod. You can use decimal, or hex -- anything that is an integer. -- Steven. From jstier at cs.uvic.ca Fri Jul 8 18:51:52 2005 From: jstier at cs.uvic.ca (J) Date: 8 Jul 2005 15:51:52 -0700 Subject: embedding a new method In-Reply-To: <1120862935.199471.147610@g47g2000cwa.googlegroups.com> References: <1120862935.199471.147610@g47g2000cwa.googlegroups.com> Message-ID: <1120863112.606147.173020@g44g2000cwa.googlegroups.com> If your are reading this, I am sorry but I forgot to finish the first paragraph.... :(. I am trying to externalize some methods of a C++ object using python. User will be able to implement the function via the GUI and I then would like to add it to an instance... So the class consits of both python and c++ methods... Cheers From irmen.NOSPAM at xs4all.nl Fri Jul 1 20:33:23 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 02 Jul 2005 02:33:23 +0200 Subject: I am a Java Programmer In-Reply-To: <1120200059.025267.12090@f14g2000cwb.googlegroups.com> References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> <1120200059.025267.12090@f14g2000cwb.googlegroups.com> Message-ID: <42c5e0d4$0$62866$e4fe514c@news.xs4all.nl> George Sakkis wrote: > "mjmri... at gmail.com" wrote: > > >>I am a java programmer and I want to learn Python Please help me. > > > Google Is Your Friend: > > http://www.razorvine.net/python/PythonForJavaProgrammers > http://www.ferg.org/projects/python_java_side-by-side.html > > George > The first link is down at the moment because I'm switching computers :) Sorry about that. I expect it to be available again in a week or so. --Irmen From cam.ac.uk at mh391.invalid Thu Jul 21 11:28:38 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 16:28:38 +0100 Subject: What does "::" mean? In-Reply-To: References: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Message-ID: Robert Kern wrote: > Rob Williscroft wrote: > >> import sys >> >> live = 'live' >> >> print live[ sys.maxint : : -1 ] >> print live[ len(live)-1 : : -1 ] >> >> print live[ len(live)-1 : -len(live)-1 : -1 ] >> print live[ len(live)-1 : -sys.maxint : -1 ] >> print live[ sys.maxint : -sys.maxint : -1 ] >> print live[ -1 : -len(live)-1 : -1 ] >> >> Of course there is only one obvious way to do it, but alas >> as I'm not Dutch I can't tell which it is. > > Well, that part's easy at least: > > live[::-1] > > :-) And so the circle is complete ... What about reversed(live)? Or if you want a list instead of an iterator, list(reversed(live))? -- Michael Hoffman From tzot at sil-tec.gr Sat Jul 2 09:25:41 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 16:25:41 +0300 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) References: <42C54915.3020501@lexicon.net> Message-ID: On Fri, 01 Jul 2005 23:45:57 +1000, rumours say that John Machin might have written: >Simon Brunning wrote: >> On 7/1/05, Peter Maas wrote: >> >>>Simon Brunning schrieb: >>> >>>> Sibylle Koczian needs to sort part of a list. His first attempt made >>>> the natural mistake - sorting a *copy* of part of the list: [Peter] >>>I think it was _her_ first attempt. [Simon] >> Ooops! Sorry, Sibylle. [John] >Obviously haven't spent enough time watching Fawlty Towers :-) Then surely it should have been "its" first attempt? Aren't piranhas neutral? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From rrr at ronadam.com Thu Jul 7 01:52:05 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 05:52:05 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <8664vnwcvx.fsf@bhuda.mired.org> References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <8664vnwcvx.fsf@bhuda.mired.org> Message-ID: <9q3ze.143370$VH2.71961@tornado.tampabay.rr.com> Mike Meyer wrote: > Ron Adam writes: > >>So doing this would give an error for functions that require an argument. >> >> def foo(x): >> return x >> >> a = None >> b = foo(a) # error because a dissapears before foo gets it. > > > So how do I pass None to a function? You wouldn't. What would a function do with it anyway? If you wanted to pass a neutral value of some sort, then you'd just have to pick something else and test for it. Maybe we could use Nil as an alternative to None for that purpose? >> 6. x = foo() # Would give an error if foo returns None > > Why? Shouldn't it delete x? That was my first thought as well. It would cause all sorts of problems. One way to avoid those is to insist that the only way to assign (delete) a name to None is by literally using "None" and only "None" on the right side of the = sign. Any undefined name on the right side would give an error except for None itself. >>This might be an improvement over current behavior. Breaks a lot of >>current code though. > > I don't think so. I've programmed in langauges that gave undefined > variables a value rather than an exception. It almost inevitabley led > to hard-to-find bugs. That is why the above should give an error I believe. ;) > FORTRAN used to give all variables a type, so that a typo in a > variable name could well lead to a valid expression. The technic for > disabling this was baroque ("IMPLICIT BOOLEAN*1 A-Z"), but so common > they invented a syntax for it in later versions of FORTRAN ("IMPLICIT > NONE"). It's been so long since I did anything if Fortran I've actual don't recall any of it. :) '83-'84 I went from that to pascal, which I thought was a big improvement at the time. Cheers, Ron From bhoel at despammed.com Fri Jul 22 15:16:24 2005 From: bhoel at despammed.com (=?utf-8?q?Berthold_H=C3=B6llmann?=) Date: Fri, 22 Jul 2005 21:16:24 +0200 Subject: tuple to string? References: Message-ID: Francois De Serres writes: > hiho, > > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) > to the string 'spam'? .>>> t = (0x73, 0x70, 0x61, 0x6D) .>>> ''.join('%c' % c for c in t) 'spam' -- "Es gelten die Regeln der christlichen Seefahrt: Rot und Gr?n markiert das sichere Fahrwasser, Schwarz und Gelb markieren Untiefen und Wracks." Christa Sager, Bundestagsfraktionsvorsitzende B?ndnis 90/Gr?ne From max at alcyone.com Sun Jul 3 02:44:11 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 02 Jul 2005 23:44:11 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: Ron Adam wrote: > But together, sum and product, probably cover about 90% of situations in > which you would use reduce. Getting a total (sum) from a list probably > covers 80% of the situations reduce would be used on it's own. (I can't > think of any real uses of product at the moment. It's late.) It's not uncommon in mathematics to do repeated products. If you're familiar with the capital Greek letter sigma notation, if it's replaced with a capital Greek letter pi, then it's an iterated product, rather than an iterated sum: http://mathworld.wolfram.com/Product.html In general, pretty much _any_ operator can be replaced in this symbol to indicate a repeated operation. Function composition, set unions and intersections, logical conjunctions and disjunctions, direct sums and products, the list goes on and on. > I'm just estimating, but I think that is the gist of adding those two in > exchange for reduce. Not that they will replace all of reduce use > cases, but that sum and product cover most situations and can be > implemented more efficiently than using reduce or a for loop to do the > same thing. The other situations can easily be done using for loops, so > it's really not much of a loss. I really don't understand this reasoning. You essentially grant the position that reduce has a purpose, but you still seem to approve removing it. Let's grant your whole point and say that 90% of the use cases for reduce are covered by sum and product, and the other 10% are used by eggheads and are of almost no interest to programmers. But it still serves a purpose, and a useful one. That it's not of immediate use to anyone is an argument for moving it into a functional module (something I would have no serious objection to, though I don't see its necessity), not for removing it altogether! Why would you remove the functionality that already exists _and is being used_ just because? What harm does it do, vs. the benefit of leaving it in? I'm not myself a huge functional programming guy, but I'm certainly not in favor of the proposal to remove map, filter, reduce, and lambda. For map and filter, I can at least see the argument, because they truly are expressible with list comprehensions (which I do use myself, of course). lambda I also don't buy, but at least there, yes, you can just define a local function and use it locally, although I think expressively that it skirts the line between expressivity and verbosity (if you know what lambda is, straightforward use of lambda is not at all unclear, in fact it's quite clear). So at least there's something to that, but I don't follow it the whole way. But removing reduce is just removing functionality for no other reason, it seems, than spite. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Who knows whether any of us will be around in 1972? -- John F. Kennedy From piet at cs.uu.nl Fri Jul 8 04:54:59 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 08 Jul 2005 10:54:59 +0200 Subject: mail sending using telnet in python References: Message-ID: >>>>> praba kar (PK) wrote: >PK> Normally we can send mail using >PK> telnet in linux. In the following way >PK> [~user]telnet Ipaddress 25 In fact you are using SMTP through the telnet program. So in Python use the smtplib module. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP E17999C4] Private email: piet at vanoostrum.org From nothingcanfulfill at gmail.com Fri Jul 22 21:49:10 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 22 Jul 2005 18:49:10 -0700 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: References: Message-ID: <1122083350.151604.87980@g44g2000cwa.googlegroups.com> In trying to develop a protocol for a current app I'm working on, I was using classes which inherited from object for my core packet, and using str(Message) to convert it to an encoded packet. However, I found that this did not work, and it drove me insane, so in a test file, I wrote the following code: class Whatever: ''' Supposed to be inheritable ''' def __init__(self): self.__str__ = self._encode # Dynamically set the __str__ from superclass(?) Well, suffice to say, having the class not inherit from object solved my problem, as I suspect it may solve yours. ;) I havn't a clue why it acts that way, however, I hope knowledge of my past experiances helps you also. Have a GREAT day :) -Wes From fuzzyman at gmail.com Thu Jul 7 07:27:52 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Jul 2005 04:27:52 -0700 Subject: Python exception hook simple example needed In-Reply-To: References: <1120654753.122331.109950@g43g2000cwa.googlegroups.com> Message-ID: <1120735672.230582.244060@g43g2000cwa.googlegroups.com> Do you have an exception handling dialog ? Can you use the UI layer without being tied to the rest of the framework ? They seemed pretty integrated to me. Best Regards, Fuzzy http://www.voidspace.org.uk/pythonhave an From bokr at oz.net Sat Jul 9 17:06:13 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 21:06:13 GMT Subject: decorators as generalized pre-binding hooks Message-ID: <42d02c21.231516573@news.oz.net> ;-) We have @deco def foo(): pass as sugar (unless there's an uncaught exception in the decorator) for def foo(): pass foo = deco(foo) The binding of a class name is similar, and class decorators would seem natural, i.e., @cdeco class Foo: pass for class Foo: pass Foo = cdeco(Foo) What is happening is we are intercepting the binding of some object and letting the decorator do something to the object before the binding occurs. So why not @deco foo = lambda:pass equivalent to foo = deco(lambda:pass) and from there, @deco = being equivalent to = deco() e.g., @range_check(1,5) a = 42 for a = range_check(1,5)(42) or @default_value(42) b = c.e['f']('g') for b = default_value(42)(c.e['f']('g')) Hm, binding-intercept-decoration could be sugar for catching exceptions too, and passing them to the decorator, e.g., the above could be sugar for try: b = default_value(42)(c.e['f']('g')) except Exception, e: b = default_value(__exception__=e) # so decorator can check # and either return a value or just re-raise with raise [Note 1] This might be useful for plain old function decorators too, if you wanted the decorator to define the policy for substituting something if e.g. a default argument evaluation throws and exception. Thus @deco def foo(x=a/b): pass # e.g., what if b==0? as try: def foo(x=a/b): pass # e.g., what if b==0? foo = deco(foo) except Exception, e: if not deco.func_code.co_flags&0x08: raise #avoid mysterious unexpected keyword TypeError foo = deco(__exception__=e) [Note 1:] Interestingly raise doesn't seem to have to be in the same frame or down-stack, so a decorator called as above could re-raise: >>> def deco(**kw): ... print kw ... raise ... >>> try: 1/0 ... except Exception, e: deco(__exception__=e) ... {'__exception__': } Traceback (most recent call last): File "", line 2, in ? File "", line 1, in ? ZeroDivisionError: integer division or modulo by zero orthogonal-musing-ly ;-) Regards, Bengt Richter From steve at REMOVETHIScyber.com.au Sun Jul 17 01:23:58 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 17 Jul 2005 15:23:58 +1000 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Replying to myself... this is getting to be a habit. On Sun, 17 Jul 2005 15:08:12 +1000, Steven D'Aprano wrote: > I hope that makes sense to you. That wasn't meant as a snide little dig at Peter, and I'm sorry if anyone reads it that way. I found myself struggling to explain simply the different behaviour between list comps and generator expressions, and couldn't be sure I was explaining myself as clearly as I wanted. It might have been better if I had left off the "to you". -- Steven From guettli at thomas-guettler.de Tue Jul 12 10:12:19 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 12 Jul 2005 16:12:19 +0200 Subject: Missing Something Simple References: Message-ID: Am Tue, 12 Jul 2005 14:44:00 +0100 schrieb John Abel: > Hi, > > I have a list of variables, which I am iterating over. I need to set > the value of each variable. My code looks like: > > varList = [ varOne, varTwo, varThree, varFour ] > > for indivVar in varList: > indivVar = returnVarFromFunction() > > However, none of the variables in the list are being set. I thought of > using setattr, but this code sits in a function, and not class, so I'm > unsure what the object would be. Hi, "indivVar" is a *reference* to a value. You only change the reference, not the value. Maybe this code helps you: a="a" b="b" c="c" varList = [a, b, c] for x in varList: x = "foo" # nothing changed print varList # --> ["a", "b", "c"] for i in range(len(varList)): varList[i]="foo" # List was changed print varList # --> ["foo", "foo", "foo"] HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From not at active.invalid Fri Jul 22 07:10:41 2005 From: not at active.invalid (TA) Date: Fri, 22 Jul 2005 13:10:41 +0200 Subject: Cursor navigation References: <42dc3722$0$67264$157c6196@dreader2.cybercity.dk> <1121803616.965169.266920@g49g2000cwa.googlegroups.com> Message-ID: <42e0d381$0$78282$157c6196@dreader1.cybercity.dk> "Andy Dustman" wrote in message news:1121803616.965169.266920 at g49g2000cwa.googlegroups.com... > > This is untrue: cursor.scroll() is an optional DB-API 2.0 extension. > > http://www.python.org/peps/pep-0249.html > > MySQLdb supports this, but I do not know about your case. Yes 'cursor.scroll()' is optional and pySqlite supports it too, but pyPgSQL does not. Thanks for replying. -- TA From peter at engcorp.com Mon Jul 25 10:56:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 10:56:33 -0400 Subject: GPRS Connection name on Python s60 In-Reply-To: <1122294420.896414.152630@f14g2000cwb.googlegroups.com> References: <1122294420.896414.152630@f14g2000cwb.googlegroups.com> Message-ID: xen0n at vodafone.it wrote: > Hi, I have a question for the experts of Python for series60! > > When I use the ".connect" method of the socket, a list with all > connection available pop-up, and, after selecting one, the soft go on. > > My question is that: Can i use the ".connect" method passing connection > name, resulting in a connection without the pop up list with connection > names? TCP connections don't normally have any "connection name", so this must be a platform-specific question. Have you thought of asking on the mailing list for Series 60 Python? -Peter From python-ml at nn7.de Mon Jul 25 16:31:23 2005 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Mon, 25 Jul 2005 22:31:23 +0200 Subject: Thanks (was Re: consistency: extending arrays vs. multiplication ?) In-Reply-To: <1122238945.724456.292440@f14g2000cwb.googlegroups.com> References: <1122238945.724456.292440@f14g2000cwb.googlegroups.com> Message-ID: <1122323484.30698.122.camel@localhost> Thanks a lot for all the answers!! Soeren From lbates at syscononline.com Thu Jul 14 14:57:30 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 14 Jul 2005 13:57:30 -0500 Subject: Native ODBC access for python on linux? In-Reply-To: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> Message-ID: ODBC is a vanilla interface that puts a layer between the program and the database. In theory, this would allow you to write a program that supports ODBC compliant databases and it would work with any of them. In practice it always seems like this doesn't work as well as everyone had hoped (performance is quite often a problem with ODBC interface and time/date handling can be an issue). There are people that provide ODBC drivers for Linux but normally they are used to communcate back to MSSQL servers or other Windows applications from Linux box. The native interfaces are almost always better performing and support more features because ODBC is basically a lowest common denominator approach. The native API can provide access to all the (even unique) features of the particular database IMHO-For Python to MySQL on Linux use the native interface is the way to go. Larry Bates callmebill at gmail.com wrote: > I'm getting my feet wet with making Python talk to MySQL via ODBC. I > started on Windows, and it went smoothly enough due to the ODBC stuff > that apparently is native to Python at least on windows (I've been > following ch. 13 of Mark Hammond's py on win32 book). > > But now I'm trying to do equivalent stuff on linux (Fedora Core 3) with > python 2.3.5 and mysql. I'd like to stick with packages that are > native to python, rather than relying on external stuff (e.g., MySQLdb > and mxODBC). Is this possible, or do I have to use 3rd party pieces to > use ODBC with Python under linux? > > > As an aside, I've only used ODBC to access db's, period. I've never > used, for example, MySQL's API for working with a MySQL db. I'm > curious to see what that looks like, if anyone has any examples > (python, c, or otherwise). > > Thanks in advance for any help. > -Bill > From cmake-bounces at cmake.org Tue Jul 19 13:46:08 2005 From: cmake-bounces at cmake.org (cmake-bounces at cmake.org) Date: Tue, 19 Jul 2005 13:46:08 -0400 Subject: Your message to CMake awaits moderator approval Message-ID: Your mail to 'CMake' with the subject test will be discarded. The reason it is being discarded is: Post by non-member to a members-only list The mailing lists at Kitware all require membership on the list to post. This is to avoid SPAM. If you are not a member on the list, and you post to the list, your message will be discarded. Do not take it personally, we just do not have enough time to approve every email posted to the list. If you have more than one email account, you can subscribe them all to the list, then set all but one of them to nomail from the mailman web GUI. Also, some mailers tend to add a few extra characters to your return address, if you think you have subscribed, but it is still not accepting your email, try sending yourself an email, and then reply to it. Look at the address that you are replying to, and make sure that is the EXACT same address that you subscribed to on the list. You can join the list here: http://public.kitware.com/mailman/listinfo/CMake If the message is too large, it will also be discarded, try putting the large file on a web server and using a link in your message. Bugs can be reported here: http://public.kitware.com/Bug/ From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 12:57:28 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 18:57:28 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e3c181$0$28434$626a14ce@news.free.fr> Steven D'Aprano a ?crit : > On Sun, 24 Jul 2005 12:03:47 +0300, Thanos Tsouanas wrote: >> >>Please, tell me, how would you print it in my case? > > If I have understood you, you have some object like such: > > obj.foo = 1 > obj.bar = 2 > obj.spam = 'a' > obj.eggs = 'b' > > say. > > You want to use it something like this: > > print "My object has fields %(foo)s; %(bar)s; %(spam)s; %(eggs)s." % obj > > except that doesn't work. So I would simply change the reference to obj to > obj.__dict__ and it should do exactly what you want. Nope, it doesn't work with computed attributes (properties, descriptors, ...). The most obvious solution is the decorator pattern - which is somewhat the op was trying to do. Another solution is to dynamically add a __getitem__ method to obj before using'em that way, either by setting explicitly the method as an attribute of the object's class or by using the import_with_metaclass() trick from David Mertz. (snip) > It really does help to explain what your functional requirements are, > instead of focusing on one, possibly pointless, implementation. > +1 on this !-) From steven.bethard at gmail.com Fri Jul 1 13:24:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 01 Jul 2005 11:24:50 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> Message-ID: mcherm at gmail.com wrote: > I avoid map sometimes, because I find its syntax less readable > than list (and expression) comprehensions. But occasionally it > is the most readable way to do something, and I wouldn't want to lose > it. I tend to avoid map as much as possible. The only places I'm still tempted to use map is in cases like: ' '.join(map(str, objects)) But I'm slowly moving towards: ' '.join(str(o) for o in objects) because it's easier to fix when I realize later that I should have written: ' '.join('x%sy' % o for o in objects) In general, I don't think I'll really miss any of map, filter, reduce, etc. My background's a lot of Java and and a little bit of LISP and ML. I was never a fan of LISP, but I did like ML a lot. However, for Python, I definitely find list comprehensions and generator expressions easier to read, especially when I have to read back through code I wrote a long time ago. STeVe From rrr at ronadam.com Tue Jul 26 02:32:17 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 26 Jul 2005 06:32:17 GMT Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <74SdndmpGeuannjfRVn-1w@powergate.ca> References: <3kjihkFubvl6U1@individual.net> <74SdndmpGeuannjfRVn-1w@powergate.ca> Message-ID: Peter Hansen wrote: > Michael Hoffman wrote: > >> Reinhold Birkenfeld wrote: >> >>> Tony Meyer wrote: >>> >>>> Do people really like using __div__ to mean join? >>> >>> >>> I'm not too happy with it, too, but do we have alternatives? ... >>> Of course, one can use joinwith() if he doesn't like '/'. >> >> >> I've used the path module pretty extensively and always use >> joinpath(). Personally, I'm -0 on __div__, but I suppose if anyone >> here claimed to have used in the past, rather than it just being some >> novelty that might be a good idea, that would be good enough for >> keeping it. > > > I've tried it both ways, and ended up accepting / as a useful and clean > approach, though as a general rule I find operator-overloading to be > fairly hideous and to lead to Perlish code. This one I resisted for a > while, then found it fairly pleasant, making it perhaps the exception to > the rule... > > Perhaps it's just that in code that builds paths out of several > components, it seemed quite straightforward to read when it used / > instead of method calls. > > For example, from one program: > > scripts = userfolder / scriptfolder > scriptpath = scripts / self.config['system']['commandfile'] > > instead of what used to be: > > scripts = userfolder.joinpath(scriptfolder) > scriptpath = scripts.joinpath(self.config['system']['commandfile']) > > Even so I'm only +0 on it. > > -Peter I think the '+' is used as a join for both strings and lists, so it would probably be the better choice as far as consistency with the language is concerned. Cheers, Ron As for features we don't have yet, you could use an "inerator". Something that gets stuff a little bit at a time. If you combine an iterator with a inerator, you would have a itinerator which would be quite useful for managing 'flight-paths'. ;-) From miki.tebeka at zoran.com Sun Jul 3 01:47:59 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 3 Jul 2005 08:47:59 +0300 Subject: POP3 and "seen" flag In-Reply-To: References: Message-ID: <20050703054759.GE3808@zoran.com> Hello Peter, > > Is there a way to know in a POP session of a message was seen (old) or not > > (new)? > > Define "seen". It could be interpreted as either "TOP" or "RETR" having > been executing for a message, or something like "this client has seen > this message before" ... not sure what you mean. That the message have been read (RETR executed on it). The "seen flag" is taken from 'retr' documentation at http://docs.python.org/lib/pop3-objects.html. > In any case, the short answer is "no". Good to know :-) > The longer answer is that _some_ POP3 servers provide non-standard > support for this by doing things like adding a special header to the > message, things like "X-Seen", which can be seen by using the TOP > command. This sort of thing is entirely non-standard and you can't rely > on it in general, AFAIK. No such luck for me. > A better approach would be to have your client software track the > Message-ID header, but something tells me you are interpreting "seen" as > meaning "anyone has RETRed the message", so that won't work either. You're right. I'm trying to delete only read messages from Exchange server, *another* client is used for reading. (It's a long story involving me and IT here ...) Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From peter at engcorp.com Wed Jul 6 08:44:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Jul 2005 08:44:34 -0400 Subject: threads and sleep? In-Reply-To: <1120625123.135496.318590@g44g2000cwa.googlegroups.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <1120625123.135496.318590@g44g2000cwa.googlegroups.com> Message-ID: Jonathan Ellis wrote: > Peter Hansen wrote: >>Or investigate the use of Irmen's Pyro package and how it could let you >>almost transparently move your code to a *multi-process* architecture > > Unless you're doing anything that would require distributed locking. > Many if not most such projects do, which is why almost everyone prefers > to use threads on an SMP machine instead of splitting it across > multiple smaller boxes. I can't address the issue of whether or not "most" such projects require distributed locking, because I'm not familiar with more than half of such projects, as you appear to be. On the other hand, I am (somewhat) familiar with Jeffrey's stated problem area (two postings of his earlier in the thread) and it really doesn't sound like he needs such a thing. Would you normally expect to need distributed locking for a simple system where you had long-running computations and wanted to improve performance by using multiple CPUs? Of course, only he can tell for sure. -Peter From me at privacy.net Fri Jul 22 15:01:18 2005 From: me at privacy.net (Dan Sommers) Date: Fri, 22 Jul 2005 15:01:18 -0400 Subject: Setting environment variables for tcsh session References: Message-ID: On Fri, 22 Jul 2005 10:56:22 -0500, David Durkee wrote: > I didn't get much from the discussion of Command Substitution. Any tips > on how to do that? I don't use tcsh, so there may be some subtleties I don't get, but it's going to look something like this: ----------------changefoo.py print 'setenv foo bar' ----------------end of changefoo.py Then the shell session would look like this: % `python changefoo.py` % echo $foo bar or you may need to "eval" the output: % eval `python changefoo.py` $ echo $foo bar or you could it like this: ----------------changefoo.py: print 'foo bar' ----------------end of changefoo.py Then the shell session would look like this: % setenv `python changefoo.py` % echo $foo bar But we're veering dangerously off topic for c.l.python. HTH, Dan -- Dan Sommers From twic at urchin.earth.li Tue Jul 5 09:20:10 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 5 Jul 2005 14:20:10 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: On Mon, 4 Jul 2005, Ron Adam wrote: > George Sakkis wrote: > >> And finally for recursive flattening: >> >> def flatten(seq): >> return reduce(_accum, seq, []) >> >> def _accum(seq, x): >> if isinstance(x,list): >> seq.extend(flatten(x)) >> else: >> seq.append(x) >> return seq >> >> >>>>> flatten(seq) >> >> [1, 2, 3, 4, 5, 6] > > How about this for a non recursive flatten. > > def flatten(seq): > s = [] > while seq: > while isinstance(seq[0],list): > seq = seq[0]+seq[1:] > s.append(seq.pop(0)) > return s > > seq = [[1,2],[3],[],[4,[5,6]]] > flatten(seq) The trouble with these is that they make a lot of temporary lists - George's version does it with the recursive calls to flatten, and Ron's with the slicing and concatenating. How about a version which never makes new lists, only appends the base list? We can use recursion to root through the lists ... def isiterable(x): return hasattr(x, "__iter__") # close enough for government work def visit(fn, x): # perhaps better called applytoall if (isiterable(x)): for y in x: visit(fn, y) else: fn(x) def flatten(seq): a = [] def appendtoa(x): a.append(x) visit(appendtoa, seq) return a If you hate recursion, you can write a non-recursive version of visit; you'll have to manage a stack of lists yourself, though. Something like: def visit(fn, x): if (not isiterable(x)): x = (x,) stack = [None] # stack of iterators cur = iter(x) # current iterator while (cur != None): try: thing = cur.next() if (isiterable(thing)): stack.append(cur) cur = iter(thing) else: fn(thing) except StopIteration: cur = stack.pop() There might be a cleverer way to do this. tom -- The revolution will not be televised. The revolution will be live. From cyril.bazin at gmail.com Sat Jul 9 10:41:21 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Sat, 9 Jul 2005 16:41:21 +0200 Subject: FORTRAN like formatting In-Reply-To: <7fhuc19d6dma38457scg5g7pp18bqrjd0g@4ax.com> References: <0DF798CBF125BF4AA1227F26431C29BD01A32ECA@pnlmse27.pnl.gov> <7fhuc19d6dma38457scg5g7pp18bqrjd0g@4ax.com> Message-ID: Ok, dennis, your solution may be better, but is quite dangerous: Python can't handle if there is exactly 3 arguments passed to the function. The created code is correct but the error will appear when your run Fortran. Cyril On 7/9/05, Dennis Lee Bieber wrote: > On Fri, 8 Jul 2005 20:31:06 +0200, Cyril BAZIN > declaimed the following in comp.lang.python: > > > > > > def toTable(n1, n2, n3): > > return "%20s%20s%20s"%tuple(["%.12f"%x for x in [n1, n2, n3]]) > > > Ugh... > > def toTable(*ns): > return ("%20.12f" * len(ns)) % ns > > toTable(3.14, 10.0, 3, 4, 5.999999) > ' 3.140000000000 10.000000000000 3.000000000000' > toTable(3.14, 10.0, 3, 4, 5.999999) > ' 3.140000000000 10.000000000000 3.000000000000 > 4.000000000000 5.999999000000' > toTable(1) > ' 1.000000000000' > > The second one IS one line, it just wraps in the news message. > Using the *ns argument definition lets the language collect all > arguments into a tuple, using * len(ns) creates enough copies of a > single item format to handle all the arguments. > > Oh, a top-poster... No wonder I didn't recall seeing any > Fortran. > > > On 7/8/05, Einstein, Daniel R wrote: > > > > > > > > > Hi, > > > > > > Sorry for this, but I need to write ASCII from my Python to be read by > > > FORTRAN and the formatting is very important. Is there any way of doing > > > anything like: > > > > > > write(*,'(3(" ",1pe20.12))') (variable) > > > > > Which Fortran compiler? I know VMS Fortran was very friendly, > when specifying "blanks not significant" or something like that... To > read three floating numbers (regardless of format) merely required > something like: > > read(*, '(bn,3f)') a, b, c > > (or 'bs' for blanks significant -- I forget which one enabled free > format input processing) > > You aren't going to get prescaling; Python follows C format > codes (if one doesn't use the generic %s string code and rely on Python > to convert numerics correctly). > > def toTable(*ns): > return ("%20.12e" * len(ns)) % ns > > toTable(3.14, 10.0, 3) > ' 3.140000000000e+000 1.000000000000e+001 3.000000000000e+000' > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < > -- > http://mail.python.org/mailman/listinfo/python-list > From davecook at nowhere.net Tue Jul 19 14:45:22 2005 From: davecook at nowhere.net (Dave Cook) Date: Tue, 19 Jul 2005 18:45:22 GMT Subject: OO design References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: On 2005-07-19, chris wrote: > I've been scripting with python for a while now. Basically writing a few > functions and running in the ipython shell. That's been very useful. But the > more I do this the more I see that I'm doing more or less the same thing > over and over again. When that happens, it's probably a good sign that you need to create a module for that functionality. As for OO in Python, IMO it's best just to dive in and not worry about being "methodologically correct" at first. Unfortunately, most books on OO use static languages for their examples, which usually obscures concepts that are extremely simple in Python. Books using Smalltalk are not too bad, though, for example _Smalltalk, Objects, and Design_ by Chamond Liu. Book chapters on Python OO basics: http://diveintopython.org/object_oriented_framework/index.html http://www.ibiblio.org/g2swap/byteofpython/read/oops.html http://www.pasteur.fr/formation/infobio/python/ch18.html fraca7 series on design patterns, where the moral of the story is often "You don't need to do that in Python.": http://fraca7.free.fr/blog/index.php?Python Dave Cook From kay.schluehr at gmx.net Sun Jul 31 15:48:43 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Jul 2005 12:48:43 -0700 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <1122829672.285541.45710@g43g2000cwa.googlegroups.com> Message-ID: <1122839323.736894.74620@f14g2000cwb.googlegroups.com> Cliff Wells wrote: > > My objection with wrappers around wrappers around wrappers is that I > > have no hope ever watching the ground. If some error occurs, which > > layer has to be addressed? Which developing group is reponsible? My own > > or that of team A, team B, team C ... ? The baroque concept is > > repulsive to me and only acceptable in case of legacy code that gets > > wrapped around old one and is dedicated to substitute it continously. > > Of course, Tkinter is still a wrapper around a third party library (Tk) > borrowed from a different language (Tcl) and written again in a third > language (C), much the same as wxPython. Yes, sorrowly. But the discussion was focussed around another layer above wxPython, Tkinter etc. to make those toolkits more pythonic. Ed promised to support many GUI toolkits as backend in future ( reviving the failed AnyGUI approach ). That's o.k. as long as tedious maintenance is a fun job for some people and they do it right. I don't say that Ed produces crap, but I'll be carefull and wait a couple of years before using such kind of stuff in production code. > Your concerns are valid in a theoretical sense, but in practice make > little difference. It makes all difference in practice. A few levels of stacking does not hurt in theory because it is easy to abstract them away by perfect machinery. > If you are using Tkinter and it exposes a bug in Tk, > then you report to the Tkinter maintainers and they will get it fixed. As long as the chain of layers does not break and the conveyor-belt rolls efficiently it's like living in theory ;) Kay From jforcier at strozllc.com Mon Jul 25 18:47:05 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: Mon, 25 Jul 2005 18:47:05 -0400 Subject: Time formatting and date suffixes Message-ID: This seems like a dead simple question, as it's so rudimentary I can't believe it hasn't been addressed before. I'm using the time.strftime() function (actually the mxDateTime implementation, but they're compatible so it shouldn't matter) to spit out fairly basic date formats, to wit: January 25th, 2005 The various and sundry date objects in both mxDateTime and Python proper's time/datetime don't seem to have anything anywhere dealing with the 'th' suffix on the date. So in other words, I can use strftime() to get 'January 25, 2005' but don't see anything dealing with outputting the suffixes like 'th', 'nd' and the like. Googling around and searching this list's archives aren't turning anything up, either. Am I missing something obvious, or is it just really, really frowned upon to use such a locale-specific function as English date suffixes? Thanks, Jeff -- Jeffrey E. Forcier Junior Developer, Research and Development Stroz Friedberg, LLC 15 Maiden Lane, 12th Floor New York, NY 10038 [main]212-981-6540 [direct]212-981-6546 http://www.strozllc.com This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by any error in transmission. If you have received this message in error, please immediately notify the sender by e-mail or by telephone at 212.981.6540, delete the message and all copies from your system and destroy any hard copies. You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient. From pipene-news at pu.kielce.pl Mon Jul 25 19:45:47 2005 From: pipene-news at pu.kielce.pl (Artur M. Piwko) Date: Mon, 25 Jul 2005 23:45:47 +0000 (UTC) Subject: Try this References: <1122232247.337991.322150@o13g2000cwo.googlegroups.com> Message-ID: In the darkest hour on 24 Jul 2005 12:10:47 -0700, RunLevelZero screamed: > list = os.walk("C:\python24\Tools") r"C:\python24\Tools" Artur -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:230B ] [ 01:45:21 user up 10684 days, 13:40, 1 user, load average: 0.06, 0.06, 0.06 ] Backup not found: A)bort, R)etry, M)assive heart failure? From Scott.Daniels at Acm.Org Sun Jul 3 17:39:11 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 03 Jul 2005 14:39:11 -0700 Subject: map/filter/reduce/lambda opinions and backgroundunscientificmini-survey In-Reply-To: References: Message-ID: <42c8534d$1@nntp0.pdx.net> Jp Calderone wrote: > Suggesting people can "like it or lump it" is a disservice to everyone. However, when people start with "why is this so" and rather than listen for information, try to argue that they are right, that behavior is a disservice to the group. Preparing a cogent argument to convince others is one thing. Insisting on being convinced oneself is another. For the latter, the only excuse I immediately forgive is for those who have invested significant time and effort in providing the language, its support tools, and/or its documents. For others it sounds a lot like whining. --Scott David Daniels Scott.Daniels at Acm.Org From and-google at doxdesk.com Sat Jul 9 08:26:46 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 9 Jul 2005 05:26:46 -0700 Subject: why UnboundLocalError? In-Reply-To: References: Message-ID: <1120912006.484157.131500@g44g2000cwa.googlegroups.com> Alex Gittens wrote: > I'm getting an UnboundLocalError > def fieldprint(widths,align,fields): [...] > def cutbits(): [...] > fields = fields[widths[i]:] There's your problem. You are assigning 'fields' a completely new value. Python doesn't allow you to rebind a variable from an outer scope in an inner scope (except for the special case where you explicitly use the 'global' directive, which is no use for the nested scopes you are using here). So when you assign an identifier in a function Python assumes that you want that identifier to be a completely new local variable, *not* a reference to the variable in the outer scope. By writing 'fields= ...' in cutbits you are telling Python that fields is now a local variable to cutbits. So when the function is entered, fields is a new variable with no value yet, and when you first try to read it without writing to it first you'll get an error. What you probably want to do is keep 'fields' pointing to the same list, but just change the contents of the list. So replace the assign operation with a slicing one: del fields[:widths[i]] -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From istvan.albert at gmail.com Tue Jul 19 11:20:19 2005 From: istvan.albert at gmail.com (istvan.albert at gmail.com) Date: 19 Jul 2005 08:20:19 -0700 Subject: Web Framework Reviews Message-ID: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> Hello All, I thought it would make sense to write up some of my experiences with python based web frameworks: http://www.personal.psu.edu/staff/i/u/iua1/python_reviews.html best, Istvan. From kboruff at _*_&&_*_optonline.net Sun Jul 24 09:30:00 2005 From: kboruff at _*_&&_*_optonline.net (Keith P. Boruff) Date: Sun, 24 Jul 2005 09:30:00 -0400 Subject: FAQ? In-Reply-To: References: Message-ID: Michael Hoffman wrote: > Keith P. Boruff wrote: > >> Is there an FAQ available specific to this NG as I'm sure some of the >> list slicing questions I have have been asked before. > > > Try Google for . I tried and didn't find one. That's why I asked here. > I don't know why you would want to look in > a FAQ *specific* to a newsgroup to look up slicing questions, I have a specific question about list slicing and this is a python NG. What's not to understand? > since slicing has little to do with the newsgroup. I thought this was a python NG. > A more general Python FAQ will be more helpful. A more general FAQ (or the stuff I've accessed on slicing) didn't answer my question. It doesn't matter now. I've since found the answer. Is your attitude indicitive of most people on this NG or are you just one of those NG guys who gets off on making the new people feel stupid? If it's the former, I'll just go away. If it's the latter, I'll *PLONK* you. KPB From roccomoretti at hotpop.com Fri Jul 1 16:02:10 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 01 Jul 2005 15:02:10 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: Joseph Garvin wrote: > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? I'm not aware of a language that allows it, but recently I've found myself wanting the ability to transparently replace objects. For example, if you have a transparent wrapper class around a certain object, and then determine that you no longer need to wrap the object, you can say the magic incantation, and the wrapper instance is replaced by what it is wrapping everywhere in the program. Or you have a complex math object, and you realize you can reduce it to a simple integer, you can substitue the integer for the math object, everywhere. I mainly look for it in the "object replaces self" form, but I guess you could also have it for arbitrary objects, e.g. to wrap a logging object around a function, even if you don't have access to all references of that function. Why isn't it in Python? It's completely counter to the conventional object semantics. From flyaflyaa at gmail.com Fri Jul 29 10:34:23 2005 From: flyaflyaa at gmail.com (flyaflya) Date: Fri, 29 Jul 2005 22:34:23 +0800 Subject: How to do this? Message-ID: the codes as follow: class Base: def fun(self): print "base_fun" def fun2(self): print "base_fun2" class Foo: def __init__(self, base): self.__base = base def fun3(self): print "foo_fun3" b = Base() foo = Foo(b) my aim is:when "foo.fun3()" be called,it run as usually, but when "foo.fun()" or "foo.fun2() be called, as Foo hasn't attribute "fun()" and "fun2()", foo will call "self.__base.fun()" or "self.__base.fun2()". when a attr can't be find in foo, it's will try to search 'self.__base". I think this maybe need to use "__getattr__" and "__setattr__" ,but I cant do it successfully. can someone help me? From duws at baow.com Tue Jul 5 23:56:09 2005 From: duws at baow.com (Du Wenshan) Date: 5 Jul 2005 20:56:09 -0700 Subject: ANN: BAOW 1.1 Released Message-ID: <1120622169.040325.37230@o13g2000cwo.googlegroups.com> BAOW is a lightweight content manage system based on python language and SQL database, help you to develop complex web applications. = Highlights = * BBS or forum system, like phpBB. * Documents manage. * News manage. * Private messages. * with some Wiki or Blog features. * use MoinMoin Wiki marks to edit your contents * Unicode (utf-8) support * International support * built in HTML widget, like GTK * easy to extend and maintain. * user manage and role check and manage. = Homepage and Demo Site = * home page: http://www.baow.org * demo site: http://demo.baow.org = Download = source: http://down.baow.org/baow-1.1.tgz = Install = http://www.baow.org/topic/show/6 = Forums = http://www.baow.org/bbs/cat/main = License = GNU General Public License (GPL) = Author = Du Wenshan duws at baow.com Enjoys! From max at alcyone.com Sun Jul 3 21:51:58 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 03 Jul 2005 18:51:58 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Ron Adam wrote: > Each item needs to stand on it's own. It's a much stronger argument for > removing something because something else fulfills it's need and is > easier or faster to use than just saying we need x because we have y. > > In this case sum and product fulfill 90% (estimate of course) of reduces > use cases. It may actually be as high as 99% for all I know. Or it may > be less. Anyone care to try and put a real measurement on it? Well, reduce covers 100% of them, and it's one function, and it's already there. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I'm not jumping in / A wave that just passes -- Sandra St. Victor From pink at odahoda.de Mon Jul 4 16:44:10 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 04 Jul 2005 22:44:10 +0200 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> <1120507976.901769.141170@o13g2000cwo.googlegroups.com> Message-ID: George Sakkis wrote: > Hi Josiah, > >> Hello. I am very new to Python, and have been unable to figure out how >> to check if a variable exists or not. In the following code I have made >> a kludge that works, but I think that it would be clearer to check if >> closest exists and not have to initialize it in the first place. How is >> that check done? >> >> The following code finds the closest place to a position and rejects >> places that are too far away. >> >> dist = 1e9 >> closest = -1 >> >> for n,p in galaxy.places.iteritems(): >> dif = p.pos - pos >> len = dif.len() >> if len < dist and len < 10.0/self.zoom: >> dist = len >> closest = p >> >> if closest != -1: >> self.sel = [closest.name] > > I would write it like this: > > def setClosest(self, pos, galaxy): > minDist, closestPlace = min([((place.pos-pos).len(), place) > for place in galaxy.places.itervalues()]) > if minDist < 10.0/self.zoom: > self.sel = [closestPlace.name] > else: > raise RuntimeError("No place close enough") A galaxy can be pretty big and contain a lot of places ;) You'll easily run out of memory, if you try to build a list of (dist, place) tuples. Better use the generator syntax (requires python 2.4): minDist, closestPlace = min(((place.pos-pos).len(), place) for place in galaxy.places.itervalues()) -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From nospam at hetnet.nl Sun Jul 3 17:52:12 2005 From: nospam at hetnet.nl (martian) Date: Sun, 3 Jul 2005 23:52:12 +0200 Subject: looping over a big file Message-ID: <11cgnhp3j4th442@corp.supernews.com> Hi, I've a couple of questions regarding the processing of a big text file (16MB). 1) how does python handle: > for line in big_file: is big_file all read into memory or one line is read at a time or a buffer is used or ...? 2) is it possible to advance lines within the loop? The following doesn't work: > for line in big_file: line_after = big_file.readline() the function readline (file pointer) is "out of sync" with the loop (and this suggests bug_file is not read one line at a time in the loop). Thanks, Fernando Martins From hancock at anansispaceworks.com Mon Jul 4 06:32:13 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 4 Jul 2005 05:32:13 -0500 Subject: looping over a big file In-Reply-To: References: <11cgnhp3j4th442@corp.supernews.com> Message-ID: <200507040532.13759.hancock@anansispaceworks.com> On Sunday 03 July 2005 08:28 pm, Peter Hansen wrote: > If open() can ever return things other than files, it seems likely it > will do so only under conditions that make it pretty much safe to assume > that existing code will continue to operate "as expected" (note: not > "always with a file"). WHEN it returns things other than files. Like a StringIO object, which can be quite handy. True, it won't be a "big file", but it'd be nice if the same code would tolerate it. I've used this with e.g. PIL quite a bit when working with Zope, because it isn't really desireable to have to write the file out to disk and read it back when you've already got it in memory. Quack! ;-) Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From fb102 at soton.ac.uk Wed Jul 20 18:12:40 2005 From: fb102 at soton.ac.uk (Floris Bruynooghe) Date: Thu, 21 Jul 2005 00:12:40 +0200 Subject: native hotshot stats module Message-ID: As part of my Google Summer of Code project I have developed a hstats module. It reads a file with profile data saved by hotshot and displays statistics of it after sorting it. The current interface is very basic in the philosophy of You Arent Gonna Need It[1]. So my question here is: please test it and comment on the missing features and other problems you'd like to see. You can just grab the hprof/hstats.py file from CVS[2] and use it right away. It only depends on the standard library, so just make sure you can import it. It is (hopefully) sufficiently documented in the docstrings. >From my experience with pystones it is 35% faster in loading the hotshot data then the hotshot.stats.load() method. So there is actually some motivation to use this module. I'm eager to hear your comments. Floris [1] http://c2.com/cgi/wiki?YouArentGonnaNeedIt [2] http://savannah.nongnu.org/cvs/?group=pyprof -- Debian GNU/Linux -- The power of freedom www.debain.org | www.gnu.org | www.kernel.org From rkern at ucsd.edu Tue Jul 5 15:45:04 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 05 Jul 2005 12:45:04 -0700 Subject: distutils is able to handle... In-Reply-To: <1120570259.138484.140720@f14g2000cwb.googlegroups.com> References: <1120570259.138484.140720@f14g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > "mg" wrote: > > >>Hello >> >>I work on an finite element framework and Python bindings have been >>developped. >>Actually, we use Boost.Build as build system but we would like to change >>it. >> >>We have two kinds of problems. First, the framework is used for generate >>pure C++ applications with static libraries ; second, the framework have >>some dependencies to fortran projects. >>Then, in order to know if Distutils can be use in our case, I would like >>to know if : >>- Can distutil compile static C/C++ libraries ? >>- Can distutil compile C/C++ applications ? >>- Can distutil manage fortran compiler and compile fortran libraries and >>applications ? >> >>Thank for your answers > > I don't think distutils can handle all these, especially the last one, > so I doubt it's the right tool in your case. I would suggest SCons > (http://www.scons.org/), a modern make/automake/autoconf replacement > that uses python for its configuration files instead of yet another > cryptic half-baked mini-language or XML. It does handle FORTRAN when using the scipy_distutils extensions. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From spam.csubich+block at block.subich.spam.com Sun Jul 24 22:34:07 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 24 Jul 2005 22:34:07 -0400 Subject: return None In-Reply-To: <1122247418.319999.20220@f14g2000cwb.googlegroups.com> References: <3kcpbbFtjttlU1@individual.net> <1122247418.319999.20220@f14g2000cwb.googlegroups.com> Message-ID: Repton wrote: > 'Well, there's your payment.' said the Hodja. 'Take it and go!' +1: the koan of None "Upon hearing that, the man was enlightened." From hancock at anansispaceworks.com Thu Jul 14 13:40:13 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 14 Jul 2005 12:40:13 -0500 Subject: Who uses input()? [was Re: question on "input"] In-Reply-To: References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> <1121179143.995844.28690@g47g2000cwa.googlegroups.com> Message-ID: <200507141240.14373.hancock@anansispaceworks.com> On Thursday 14 July 2005 07:00 am, Michael Hoffman wrote: > Devan L wrote: > > Use raw_input instead. It returns a string of whatever was typed. Input > > expects a valid python expression. > > Who actually uses this? It's equivalent to eval(raw_input(prompt)) but > causes a lot of newbie confusion. Python-dev archives revealed that > someone tried to get this deprecated but Guido disagreed. I don't think it should disappear, but it *does* seem more sensible for "raw_input" to be called "input" (or "readstring" or some such thing) and "input" to vanish into greater obscurity as "eval_input" or something. Unfortunately, that would break code if anything relied on "input", so I guess that would be a Py3K idea, and maybe the whole I/O concept will be rethought then (if the "print" statement is going to go away, anyway). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From Scott.Daniels at Acm.Org Fri Jul 8 11:42:19 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 08 Jul 2005 08:42:19 -0700 Subject: Pattern question In-Reply-To: <42CE4D34.2000008@wanadoo.fr> References: <42cd5493$0$900$8fcfb975@news.wanadoo.fr> <42ce3f20$0$13033$636a15ce@news.free.fr> <42CE4D34.2000008@wanadoo.fr> Message-ID: <42ce9707@nntp0.pdx.net> cantabile wrote: > bruno modulix a ?crit : >>You may want to have a look at the Factory pattern... >> ... demo of class Factory ... Taking advantage of Python's dynamic nature, you could simply: # similarly outrageously oversimplified dummy example class Gui(object): def __init__(self, installer): self.installer = installer class PosixGui(Gui): pass class Win32Gui(Gui): pass if os.name == 'posix': makeGui = PosixGui elif os.name == 'win32': makeGui = Win32Gui else: raise "os %s not supported" % os.name class Installer(object): def __init__(self, guiFactory): self.gui = guiFactory(self) def main(): inst = Installer(makeGui) return inst.gui.main() --Scott David Daniels Scott.Daniels at Acm.Org From roccomoretti at hotpop.com Fri Jul 1 15:08:01 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 01 Jul 2005 14:08:01 -0500 Subject: Assigning to None In-Reply-To: <86ekai5sk7.fsf@bhuda.mired.org> References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <86ekai5sk7.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Peter Hansen writes: > > >>Mike Meyer wrote: >> >>>Yes. I once grabbed an old program that did assignments to None. But >>>that's always been a bad idea. >> >>What was the use case!? > > > Unpacking a tuple. Something like this: > > (foo, bar, None) = gen_tuple(stuff) Goodness, that's bad form. I can just see someone copying it and doing: (foo, bar, None) = gen_tuple(stuff) if foo is None: ...... and wondering why the program doesn't work properly. If you had to do that, you might try: foo, bar, _ = gen_tuple(stuff) or in a more complex case. foo, _, _, bar, _, baz, _ = gen_tuple(stuff) as '_' is already special cased (last result in interactive mode), and is already used for "don't care" sematics in Prolog. From ptmcg at austin.rr.com Sun Jul 10 11:29:24 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Jul 2005 08:29:24 -0700 Subject: passing arguments to a function - do I need type ? In-Reply-To: References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: <1121009364.541781.17880@g14g2000cwa.googlegroups.com> Is getCenter a function? If so, you need to invoke distance using: dist = self.distance( n.getCenter(), newElement ) Of course, that is assuming that newElement is a local variable of type list/tuple/etc. -- Paul From afriere at yahoo.co.uk Wed Jul 6 01:45:07 2005 From: afriere at yahoo.co.uk (Asun Friere) Date: 5 Jul 2005 22:45:07 -0700 Subject: looping over a big file References: <11cgnhp3j4th442@corp.supernews.com> Message-ID: <1120628707.185004.227910@g49g2000cwa.googlegroups.com> Jp Calderone wrote: > fileIter = iter(big_file) > for line in fileIter: > line_after = fileIter.next() > > Don't mix iterating with any other file methods, since it will confuse the buffering scheme. > Isn't a file an iterable already? [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> foo = open('sample.txt') >>> bar = iter(foo) >>> bar is foo True From benji at benjiyork.com Tue Jul 26 15:15:06 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 26 Jul 2005 15:15:06 -0400 Subject: Emacs skeletons In-Reply-To: References: Message-ID: <42E68BBA.3090301@benjiyork.com> Michael Hoffman wrote: > I have this in my .emacs: > > (global-set-key "\M-/" 'hippie-expand) > > This means that M-/ will do dumb code completion based on stuff that is > already in an open buffer Even though I don't know how to configure Emacs to do it (I'm a degenerate Vim user), I've found ctags completion very handy. I currently have my (inferior) editor set up to scan the current buffer, other buffers, then tags files when doing completion. I'm sure (the superior) Emacs can do something similar. -- self-editor-abasing-ly y'rs, Benji York From mwm at mired.org Tue Jul 19 23:13:33 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 19 Jul 2005 23:13:33 -0400 Subject: retrieving https pages References: Message-ID: <86k6jmrwyq.fsf@bhuda.mired.org> Eric writes: > I'm using Linux - Manriva LE2005, python 2.3 (or i can also use python 2.4 > on my other system just as well). > Anyways... > I want to get a web page containing my stock grants. > The initial page is an https and there is a form on it to > fill in your username and password and then click "login" > I played with python's urlopen and basically it complains "your browser > doesnt support frames" meaning the urlopen call makes it unhappy somehow. > Is it reasonable to think i can build a script to login to this secure > website, move to a different page (on that site) and download it to disk? > Or am i just looking at a ling complicated task. It's not that bad. It took me about half a day to do this for a site I wanted scraped regularly, and what I had to do was much more complicated than what you describe. I had to deal with an optional second login page (a "security feature" of the site), http-equiv redirects (which urlopen doesn't handle), and then digging the URL of the page I wanted to get information from from the resulting page. The complaint about your browser may be their inadequate attempt to deal with browser portability by putting that on the resulting framed page in the NOFRAMES element. In which case, you just need to find the URL for the frame that's got the information you want, and get that page. On the other hand, as Wes said, they may be browser-sniffing. In which case you'll have to set the User-Agent to something they won't complain about. Personally, I always try "Your Web Site Developer Sucks" to see if they have a list of disallowed browsers. If that fails, try the User-Agent string of a well-known browser. For page scraping, install BeautifulSoup. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Sat Jul 30 05:37:10 2005 From: http (Paul Rubin) Date: 30 Jul 2005 02:37:10 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <1122715993.183245.40940@g43g2000cwa.googlegroups.com> Message-ID: <7xmzo4d48p.fsf@ruckus.brouhaha.com> "Kay Schluehr" writes: > Examples: > f = ( || x>=0 then f(x) || True then f(-x) from (x,) ) > g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,)) Is this an actual language? It looks sort of like CSP. Python with native parallelism, mmmmm. From cam.ac.uk at mh391.invalid Thu Jul 21 18:21:06 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 23:21:06 +0100 Subject: PEP on path module for standard library In-Reply-To: <3kakh5Ftjd9mU1@individual.net> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > John Roth wrote: > >>Why did Guido want a PEP? > > He said, > > """ > Whoa! Do we really need a completely different mechanism for doing the > same stuff we can already do? The path module seems mostly useful for > folks coming from Java who are used to the Java Path class. > """ What is this Java Path class? I have been STFWing and have found nothing on it in the. Indeed if you search for "Java Path class" (with quotes) almost half of the pages are this message from Guido. ;) Any Java hackers here want to tell us of the wonders of the Java Path class? I would be interested in seeing how other OO languages deal with paths. -- Michael Hoffman From devlai at gmail.com Mon Jul 4 01:10:15 2005 From: devlai at gmail.com (Devan L) Date: 3 Jul 2005 22:10:15 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> <1120362708.992006.49040@g14g2000cwa.googlegroups.com> Message-ID: <1120453815.248707.210020@g47g2000cwa.googlegroups.com> Okay, maybe that was too restrictive, reduce can *usually* be replaced with sum. Sorry about that. From rrr at ronadam.com Fri Jul 8 16:52:40 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 08 Jul 2005 20:52:40 GMT Subject: Use cases for del In-Reply-To: <1120825627.498017.19370@g47g2000cwa.googlegroups.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <1120825627.498017.19370@g47g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > I get: > > None: 0.549999952316 > String: 0.498000144958 > is None: 0.450000047684 What do yo get for "name is 'string'" expressions? Or is that a wrong way too? On my system testing "if string is string" is slightly faster than "if True/ if False" expressions. But the actual different is so small as to be negligible. I'm just kind of curious why testing is objects isn't just as fast as testing is string? Cheers, Ron From rkern at ucsd.edu Thu Jul 21 21:12:04 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 21 Jul 2005 18:12:04 -0700 Subject: Difference between " and ' In-Reply-To: <20050722010657.GA24716@unpythonic.net> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <20050722010657.GA24716@unpythonic.net> Message-ID: jepler at unpythonic.net wrote: > The only difference is when you want to include " or ' inside the string. If > you want to include the "like" quote, then escape it ("\"", '\''). If you > include the "unlike" quote, no escape is needed ("'" or '"'). > > I think that people new to programming will use '' if it is unshifted on their > keyboards. People from a "C" background may use "" for strings (since in that > language, '' is for a single character only). I find that I switch between the two pretty freely. One habit that seems to crop up, though, is that I will use '' for internal strings and "" for strings that will eventually get seen by the user. Don't ask me why. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 05:13:30 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 11:13:30 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kjihkFubvl6U1@individual.net> Message-ID: <3kjopqFuhhgeU1@individual.net> Stefan Rank wrote: > on 25.07.2005 10:44 Michael Hoffman said the following: >> Reinhold Birkenfeld wrote: >>>Tony Meyer wrote: >>>>Do people really like using __div__ to mean join? >>>Of course, one can use joinwith() if he doesn't like '/'. >> Personally, I'm -0 on __div__, but I suppose if anyone here claimed to >> have used in the past, rather than it just being some novelty that might >> be a good idea, that would be good enough for keeping it. > > I, herewith, claim to have used it in the past. > > But I am indifferent as to if its needed, it just looks natural to me. > > What I use quite often is:: > > path(__file__).dirname() / "somesiblingfileiknowisthere" > > you do not have to think about trailing slashes or absolute vs. > relative. and its much better than:: > > from os.path import * > join(dirname(__file__), "somesiblingfileiknowisthere") > > __div__ is actually very convenient to "build" / "a" / "very" / "very" / > "long" / "path" (of course assuming the parts are strings not known > initially...) Even knowing the parts that can be helpful if you want to be cross-platform. Reinhold From newptcai at gmail.com Sun Jul 3 13:05:57 2005 From: newptcai at gmail.com (Peter Cai) Date: Mon, 4 Jul 2005 01:05:57 +0800 Subject: How execute a .py in this way? Message-ID: If it's a executable file, a ".exe" file, you can launch it in this way, "xxx.exe < input.txt". The text file "input.txt" will be considered as the standard input. But when I use this trick on python, it doesn't work. The only way to do so is like this "python xxx.py < input.txt". But this method has a problem, that you have to include the full path of "xxx.py" unless it's in your current folder even if "xxx.py" is in a folder which has been include in the eviorment variable "path" on windows. Thus, you can execute you "py" program anywhere by using the command "xxx.py", but when you want to use an exsiting file as it's input, you have to use something like "pythong xxx.py < input.txt". It's very inconvenient as I tried to make my python programs cowork with vim. Sorry for my poor english! delete From facundobatista at gmail.com Fri Jul 1 12:43:07 2005 From: facundobatista at gmail.com (Facundo Batista) Date: Fri, 1 Jul 2005 13:43:07 -0300 Subject: Money module Message-ID: People: The Money two-days sprint in EuroPython 2005 has finished. We advanced a lot. The pre-PEP is almost done, and the corresponding test cases are all written. We need to finish the structure procesing for currency general information, and bring general functions to the module, but most of the decision-taking part is done. So, it's not a chaos any more, it's in a very coherent state, but yet it's not everything written in stone. So, if you want to influence somehow in the Money module, this is the moment to get in and participate. The project is in SourceForge (http://sourceforge.net/projects/pymoney), and there we have a mailing list (just to not bloat this one). Thank you. . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From bokr at oz.net Mon Jul 11 12:01:23 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 16:01:23 GMT Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> <1121059708.002859.67570@g44g2000cwa.googlegroups.com> <3jei85FpehftU1@individual.net> <3jfb10Fpga3qU1@individual.net> Message-ID: <42d295eb.389670396@news.oz.net> On Mon, 11 Jul 2005 15:37:35 +0200, Reinhold Birkenfeld wrote: >Dan Sommers wrote: > >> Without thinking it all the way through, I suppose these: >> >> def method_1(self, *self.l): >> pass >> def method_2(self, **self.d): >> pass >> >> could act as if they were these: >> >> def method_1(self, *args): >> self.l = args >> del args >> def method_2(self, **kw): >> self.d = kw >> del kw > >I still think it's too specialized. What would, hypothetically, this do? > >class Bar: pass > >class Foo: > x = Bar() > def method_1(self, x.y): > pass > >It's hard to explain that you can autoassign self.y but not x.y. > No, that limitation wouldn't exist, so you wouldn't have to explain it ;-) I.e., the above would act like class Foo: x = Bar() def method_1(self, _anonymous_arg_1): x.y = _anonymous_arg_1 and would do whatever it would do now (probably look for a global x or a closure cell x, but it wouldn't find the class variable in a normal method call) Regards, Bengt Richter From wccppp at gmail.com Thu Jul 21 05:34:02 2005 From: wccppp at gmail.com (wcc) Date: 21 Jul 2005 02:34:02 -0700 Subject: newbie - mode for directory Message-ID: <1121938442.571119.29800@f14g2000cwb.googlegroups.com> Hello, When using os.mkdir, what are the numeric numbers for different modes? I could only find mode=0777 means read-only. Thanks, - wcc From rkern at ucsd.edu Fri Jul 1 17:24:49 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 01 Jul 2005 14:24:49 -0700 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: <42C5AD1F.5060902@po-box.mcgill.ca> References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> <42c41ef2@usenet01.boi.hp.com> <42C5AD1F.5060902@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote: > Well, I found it ironic, but only when you add that the genetic > algorithm approach came up in the context of a "best fit" problem. > Survival of the fittest indeed :-) Optimization codes don't always succeed. What's the irony? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From onurb at xiludom.gro Thu Jul 21 05:02:46 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 21 Jul 2005 11:02:46 +0200 Subject: File Table List in Plone In-Reply-To: <1121898146.737821.198540@z14g2000cwz.googlegroups.com> References: <1121898146.737821.198540@z14g2000cwz.googlegroups.com> Message-ID: <42df64b8$0$7310$636a15ce@news.free.fr> groups at jpprice.info wrote: > All, > > Is there is a Plone type or product for generating a file list on a > plone page, eg: a list of downloadable files in a table? An example of > what I want can be found at > http://www.zope.org/Members/MacGregor/ExtFile under "Available > Releases" where a list of files resides. > > Is this a manually generated table or is there a way I can drop a Plone > type into a page to generate such a list? > I think you'll get better answers on a plone mailing-list. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From brian at sweetapp.com Tue Jul 19 04:52:42 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 19 Jul 2005 10:52:42 +0200 Subject: Python Programming Contest In-Reply-To: References: Message-ID: <42DCBF5A.8060905@sweetapp.com> ThanhNam Nguyen wrote: > Since my NNTP server doesnt allow posting, I'll ask you directly > instead. > > Must I start from the first day? No. > For example: > > 1st day: A --> B 100 bucks > 2nd day: A --> B 60 bucks > 3rd day: A --> B 40 bucks > > What would the solution be? And for how much in total? There are two correct solutions: ["A", "B"] # spend one night in A, then fly to B on day two (cost 80) ["A", "A", "B"] # spend two nights in A, then fly to B on day two (cost 80) Cheers, Brian From jurgenex at hotmail.com Sun Jul 10 12:37:05 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 10 Jul 2005 16:37:05 GMT Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > What is Expresiveness in a Computer Language[...] Just for the records at Google et.al. in case someone stumbles across Xah's masterpieces in the future: Xah is very well known as the resident troll in many NGs and his 'contributions' are less then useless. Best is to just ignore him. But for heaven's sake unless you want to embarrass yourself really badly don't take any of his postings serious because he has proven again and again that he has no clue whatsoever about computer science or programming. jue From pinard at iro.umontreal.ca Fri Jul 22 09:05:14 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 22 Jul 2005 09:05:14 -0400 Subject: Difference between " and ' In-Reply-To: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: <20050722130514.GA2284@alcyon.progiciels-bpi.ca> [b83503104 at yahoo.com] > Can someone tell me the difference between single quote and double > quote? There is no strong reason to use one and avoid the other. Yet, while representing strings, Python itself has a _preference_ for single quotes. Programmers can put this duality to good use, by adopting reasonable conventions, which are nothing more than conventions! :-) I would guess many people choose one over the other for minimizing the amount of backslash escape needed. Some people keep double quotes for strings that would later undergo formatting, maybe because in most shells and some other languages, double quotes allow for substitution and single quotes prevent it. But in my opinion, while not dismissing a lot of wisdom developed within other languages, it may be foolish letting other languages blindly dictate what is best Python style. Personally, I keep single quotes for "computer" strings, and double quotes for "human" strings. To segregate between "computer" and "human" character for a string, I merely ask myself: "If I wanted to use this program in another language, would I want this particular string translated or not?". Yes means double quotes, no means single quotes. As single quotes are often use within human text, as apostrophes, this was a wise choice as far as shell escaping goes. This is extendable to triple-quoted strings. I use triple-double quotes for doc strings meant to hold documentation, which is the usual case. If doc strings are used for BNF snippets, like with SPARK, or any other machine data, triple-single quotes are mandatory by my own convention. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From jeremysanders at gmail.com Sat Jul 23 13:15:45 2005 From: jeremysanders at gmail.com (Jeremy Sanders) Date: Sat, 23 Jul 2005 18:15:45 +0100 Subject: ANN: Veusz 0.7 - a scientific plotting package Message-ID: Veusz 0.7 --------- Velvet Ember Under Sky Zenith ----------------------------- http://home.gna.org/veusz/ Veusz is a scientific plotting package written in Python (currently 100% Python). It uses PyQt for display and user-interfaces, and numarray for handling the numeric data. Veusz is designed to produce publication-ready Postscript output. Veusz provides a GUI, command line and scripting interface (based on Python) to its plotting facilities. The plots are built using an object-based system to provide a consistent interface. Changes from 0.6: Please refer to ChangeLog for all the changes. Highlights include: * 2D image support * FITS file data import (1D + 2D) with PyFITS module * Support for line separated blocks of data when importing * Reversed axes supported * Key length option * Linked dataset reload UI * Plot functions over specific range * Several UI improvements Features of package: * X-Y plots (with errorbars) * Images (with colour mappings) * Stepped plots (for histograms) * Line plots * Function plots * Fitting functions to data * Stacked plots and arrays of plots * Plot keys * Plot labels * LaTeX-like formatting for text * EPS output * Simple data importing * Scripting interface * Save/Load plots * Dataset manipulation * Embed Veusz within other programs To be done: * Contour plots * UI improvements * Import filters (for qdp and other plotting packages, fits, csv) Requirements: Python (probably 2.3 or greater required) http://www.python.org/ Qt (free edition) http://www.trolltech.com/products/qt/ PyQt (SIP is required to be installed first) http://www.riverbankcomputing.co.uk/pyqt/ http://www.riverbankcomputing.co.uk/sip/ numarray http://www.stsci.edu/resources/software_hardware/numarray Microsoft Core Fonts (recommended) http://corefonts.sourceforge.net/ PyFITS (optional) http://www.stsci.edu/resources/software_hardware/pyfits For documentation on using Veusz, see the "Documents" directory. The manual is in pdf, html and text format (generated from docbook). Cheers Jeremy From edgrsprj at ix.netcom.com Wed Jul 13 16:26:38 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Wed, 13 Jul 2005 20:26:38 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> Message-ID: <2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net> "Hank Oredson" wrote in message news:1vYAe.2575$dU3.2553 at newsread2.news.pas.earthlink.net... > "edgrsprj" wrote in message > news:pmXAe.9096$aY6.3897 at newsread1.news.atl.earthlink.net... > > "Hank Oredson" wrote in message > > news:7%UAe.4148$BK1.174 at newsread3.news.pas.earthlink.net... > >> "edgrsprj" wrote in message > >> news:upBAe.1915$oZ.930 at newsread2.news.atl.earthlink.net... > >> > "edgrsprj" wrote in message > >> > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... > >> >> PROPOSED EARTHQUAKE FORECASTING > >> >> COMPUTER PROGRAM DEVELOPMENT EFFORT > I guess my question was not specific enough. > What I wanted was the exact sources, so I could access the data. > The exact data sets you used. July 13, 2005 Thanks again for the comments and interest. The original report in this thread should have contained pointers to all of the information you are requesting. But once again, here are some of the important URLs. http://www.freewebz.com/eq-forecasting/301.html That Web page contains information regarding the details of how the forecasting program works. Also stored there are copies of an early Zipped .txt version of the Perl program I am using along with Zip file versions of earlier versions of the .txt format database files that I am using. I had to Zip them because of their size and the limited bandwidth of that Web site. If you would prefer to receive them as regular text files then you can try contacting me by e-mail and I will try to send them along. Perl users who downloaded and ran that .pl program some time ago said that they had no trouble getting it to run on a Window's XP system. Other operating system users might encounter a few formatting problems etc. http://www.freewebz.com/eq-forecasting/90-05.html http://www.freewebz.com/eq-forecasting/128.html Those Web pages discuss the theories involved with this forecasting method. Some of the most important information is at the end of that 128.html Web page. http://www.freewebz.com/eq-forecasting/Data.html That Web page contains several types of forecast data along with some information regarding how to interpret them. http://www.freewebz.com/eq-forecasting/151.html That Web page contains some "Help" information with details regarding things such as the U.S. Navy's MICA computer program which I use to generate data for things such as the locations of the Earth, sun, and moon relative to the J2000 reference system. You should not expect to be able to instantly absorb all of that information though it sounds like understanding it should not be a problem for you. I have been working on the project for about 15 years. And unfortunately, every improvement seems to take days, weeks, months, ... Additionally, as I said in my first report in this thread, the multiple participants part of the project is not yet operational. For one thing, a suitable Web site has to be found. Right now I am simply trying to determine what the interest level there might be in such a project. And positive feedback that I have been getting by e-mail etc. has been encouraging. From luismgz at gmail.com Mon Jul 18 16:26:16 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 18 Jul 2005 13:26:16 -0700 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: <1121718376.592482.36110@g14g2000cwa.googlegroups.com> I'd suggest you take another path: Since we're in a python mailing list, I assume you like python, so instead of Kylix (or Object Pascal), you could try Boo (boo.codehaus.org) . Boo is not python, but it is very similar. It could be described as a statically typed version of python for the .NET framework (it also works in Linux with Mono and in Mac Osx). It has borrowed from python as much syntax as possible and uses a handy type inference system, which allows you to code without having to declare types everywhere, making it very similar to a dynamic language while being static. As I said, "it is not python" (Peter Hansen, please don't jump to my jugular...), but it's been inspired and takes a lot from it. In words of Guido Van Rossum, it is 95% python. You get all the niceties you got used to enjoy in python, such as list comprehensions, generator expressions, slicing, dictionaries, lists, etc, etc.. and you get all the speed and performance of a static language for free. As for IDEs, you can use SharpDevelop in Windows (free) or MonoDevelop in Linux (free). And if you are patient, soon you'll be able o use regular python in .NET and Mono, and I'm sure that there will be support for SharpDevelop and MonoDevelop for it as well. At the present time, python for .NET (code named Ironpython) is still at pre-alpha state (version 0.7.6). From peter at engcorp.com Sat Jul 2 16:04:37 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 16:04:37 -0400 Subject: wxPython: Terminal Output -> Scrollable Panel? In-Reply-To: <1120333932.108782.45740@g49g2000cwa.googlegroups.com> References: <1120289025.359671.148450@g14g2000cwa.googlegroups.com> <-uOdneuY58vY4VvfRVn-sA@powergate.ca> <1120333932.108782.45740@g49g2000cwa.googlegroups.com> Message-ID: flamesrock wrote: > I looked at PyCrust, and while its given me a few cool ideas, I may > have described the problem incorrectly. What I really need is not > something that takes input, but merely redirects the 'print' statements > to something like a terminal window. > > Is this even possible without entering the function calls directly into > a pycrust like terminal? Maybe I'm trying to do the wrong thing. PyCrust would show you a mechanism to get lines of text into a "terminal window". Actually capturing those lines of output is a different story. Here's one approach, if you have control over the print statements: class Redirector: def __init__(self, infoAboutTerminal): # store "infoAboutTerminal" in local attributes def write(self, text): '''output lines of text to terminal window''' # here you do whatever PyCrust does to get output to its window # using the info stored in the constructor Assuming you have a PyCrust-like terminal window open somewhere, you would create a Redirector and pass it whatever info about the terminal window that it might need. terminal = Redirector(infoAboutPyCrustLikeWindow) Then just send your prints to this location using the >> syntax sugar: print >>terminal, 'This line of text goes to the GUI window.' print >>terminal, 'So does all this\neven multiple lines...' If you *don't* have the ability to change the print statements like this, then you can install a Redirector in place of sys.stdout, but that will affect all prints, including those in standard library modules and elsewhere. HTH -Peter From steve at holdenweb.com Thu Jul 28 16:33:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jul 2005 21:33:15 +0100 Subject: retrieve data from 2 database In-Reply-To: <1122520735.066339.235110@z14g2000cwz.googlegroups.com> References: <1122520735.066339.235110@z14g2000cwz.googlegroups.com> Message-ID: crespoh wrote: > Hi, > > How do I select data from two tables from two different databases and > compare them? using dbi,odbc > Well, a lot depends on the database. If it's two Access .mdb files, for example, or two different databases in a single SQL Server instance, sometimes you can use SQL statements that cross-refer. Not possible with ODBC, though, I fear. In that case, we have to hope that the datasets are small enough to hold in memory, as Python data structures, and then operate on them as Python sets or some such. The DB API delivers the results of queries as lists of tuples, each tuple representing a row, but of course they can easily be transformed into other Python objects with more convenient properties to join the two sets together. Much then depends on how you want to join the two sets. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fuzzyman at gmail.com Wed Jul 20 04:44:14 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Jul 2005 01:44:14 -0700 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121849054.781584.279470@g14g2000cwa.googlegroups.com> Hmmm.. I've *never* hada problem with SPE crashing.. at least not under Windoze... Regards, Fuzzy http://www.voidspace.org.uk/python From peter at engcorp.com Sat Jul 16 10:25:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Jul 2005 10:25:29 -0400 Subject: Filtering out non-readable characters In-Reply-To: <42d85d5d.291420430@news.oz.net> References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Bengt Richter wrote: > >>> identity = ''.join([chr(i) for i in xrange(256)]) > >>> unprintable = ''.join([c for c in identity if c not in string.printable]) And note that with Python 2.4, in each case the above square brackets are unnecessary (though harmless), because of the arrival of "generator expressions" in the language. (Bengt knows this already, of course, but his brain is probably resisting the reprogramming. :-) ) -Peter From grante at visi.com Tue Jul 5 11:48:41 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Jul 2005 15:48:41 -0000 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> Message-ID: <11claupqtv4rs4a@corp.supernews.com> On 2005-07-05, Jeffrey Maitland wrote: > Ok here goes. The problem I have is I had an application > (wrote/co-wrote) that has a long run time dependant on some variables > passed to it (mainly accuracy variables, the more accurate the longer > the run time - makes sense). However in the hopes to speed it up I > decided to write a threaded version of the program to try and speed > it up. How ever what I am noticing is that the threaded version is > taking as long possibly longer to run. The thing is the threaded > version is running on an 8 ia-64 proccessor system and it seems to > only be using 2 or 3 porcessors at about 30% (fluxiates). My guess is > that 6 threads are running they are using 30% sprox each of a 2 given > CPUS. Because of the global interpreter lock, a multi-threaded python program does not take advantage of multiple processors. No matter how many CPUs you have, only one thread is allowed to run at any point in time. Multi-threading in Python is useful for simplifying the architecture of a program that has to do multiple independent tasks, but it isn't useful for actually running multiple threads in parallel. -- Grant Edwards grante Yow! Inside, I'm already at SOBBING! visi.com From me at privacy.net Thu Jul 14 22:54:18 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 14 Jul 2005 22:54:18 -0400 Subject: System calls not using correct permissions? References: <1121381512.615154.186430@o13g2000cwo.googlegroups.com> Message-ID: On 14 Jul 2005 15:51:52 -0700, "skilpat at gmail.com" wrote: [ os.system doesn't work right, even when I set umask to 0 ] > Anyone know what the deal might be? It might be anything, but without more details (like what operating system you're running, what version of Python you're running, an actual error message, a traceback, what your program is supposed to do that you think it isn't doing, etc.), it's absolutely impossible for anyone to make even an educated guess. See also www.catb.org/~esr/faqs/smart-questions.html. Regards, Dan -- Dan Sommers From hancock at anansispaceworks.com Mon Jul 11 15:18:07 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 11 Jul 2005 14:18:07 -0500 Subject: relative import packages/modules workaround In-Reply-To: <1121091566.327885.147380@g49g2000cwa.googlegroups.com> References: <1121091566.327885.147380@g49g2000cwa.googlegroups.com> Message-ID: <200507111418.08126.hancock@anansispaceworks.com> On Monday 11 July 2005 09:19 am, peter wrote: > I've read all the posts concerning relative imports of modules and I am > glad I saw some consensus on a syntax. > At this moment I am however bound to python 2.3. > > Does anyone know a good workaround (or a library) which can achieve a > relative import for this python version Basically, you can use information from the sys module to dynamically determine your module or package's absolute path. Then you construct the absolute path to the module you want by a fairly simple application of os.path from the relative path. How exactly to do that is not something I remember off the top of my head, but I remember it's not hard -- check the "sys" and "os.path" modules' documentation. You probably also want to look at the "__path__" property of packaged loaded with __init__.py, as I believe there is some special "magic" behavior designed for packages to make this a little easier. You can easily encapsulate this in a function under your module with just a few lines of code. Zope provides a function called "package_home" that does this. I'm sure there are other examples. The missing thing here is not that there's no way to do it, but rather that it's a common enough task that there ought to be *one* way to do it and it ought to be in the library. Otherwise, there's a lot of redundancy. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tprimke at interia.pl Sun Jul 24 09:28:43 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jul 2005 06:28:43 -0700 Subject: Friend wants to learn python References: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> Message-ID: <1122211723.440485.136090@g47g2000cwa.googlegroups.com> Why not start with Python's standard documentation? There are Python Tutorial and Library Reference. IMHO it's the best place to start. From mauriceling at acm.org Mon Jul 4 19:35:25 2005 From: mauriceling at acm.org (Maurice LING) Date: Tue, 05 Jul 2005 09:35:25 +1000 Subject: Connecting to Firebird database using Kinterbasdb+Python References: Message-ID: Mathias Waack wrote: > Maurice LING wrote: > > >>I've been using FB1.5 and access the database using Kinterbasdb + >>Python. My connection is established using kinterbasdb.connect() method >>and the parameters host, dns, database, user, password are all defaulted >>to 'None'. >> >>On my own machine running Mac OSX 10.3, I can connect using the following: >>host = 'localhost' >>database = '' >>user = '' >>password = '' >> >>At the same time, I can also connect if I set host=None on my machine. >> >>However, I cannot use 'localhost' on a shared Linux machine (not >>allowed. Don't ask why, system admin's mandate. And the Linux machine is >>without inetd). So when I set host=None, I get this error: > > > Just for my understanding: if you start your script on the machine hosting > the DB you're able to connect. If you start it on a different machine, you > are not able to connect without giving a hostname? Whats wrong with > offering the the name (or IP-address) of your MacOS-box instead of > 'localhost' to the script? > Hi Mathias, What I am trying to do is "port" a workable program from my own machine (Mac OSX) to a larger machine (Linux). So, the DB and the program are also on the same Linux machine. On the Linux machine, I cannot use localhost, so I set host parameter in kinterbasdb.connect() method to None, which is the default kinterbasdb uses. On Linux machine, I get the error as posted. On my Mac OSX machine, initiating host parameter to 'localhost' or None has no difference, it works. Thanks and cheers Maurice From mcherm at gmail.com Fri Jul 1 12:13:58 2005 From: mcherm at gmail.com (mcherm at gmail.com) Date: 1 Jul 2005 09:13:58 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> Tom Anderson wrote: > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? I avoid map sometimes, because I find its syntax less readable than list (and expression) comprehensions. But occasionally it is the most readable way to do something, and I wouldn't want to lose it. Lambda serves a very specific purpose: declaring small, in-place functions which are no bigger than a single expression. I do this often enough that I DO want special syntax for it. But I'll admit that I wish "lambda" were about 5 or 6 characters shorter and didn't have such an obscure name. I disagree (and I've mentioned it before) with Guido's plan to remove these eventually. I'm perfectly satisfied with the alternate plan to move the functions like map to a module (perhaps named "functional"). (That doesn't help with lambda, though since it requires syntactical support.) And my background is definitely NOT functional: I started with Basic, then learned Pascal well, then _lots_ of other languages (including Lisp) to an academic level. I've been using Java and Python heavily now for about 8 or 9 years. I _DO_ however feel quite comfortable using a functional approach *for certain problems*. -- Michael Chermside From hancock at anansispaceworks.com Tue Jul 19 22:07:08 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 19 Jul 2005 21:07:08 -0500 Subject: OO design In-Reply-To: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: <200507192107.08141.hancock@anansispaceworks.com> On Tuesday 19 July 2005 05:09 am, chris wrote: > So its feels like I need to get into class programming > with all its attendant benefits. However my biggest problem is a conceptual > one. I just can't get my head around defining suitable classes, how they > aquire data and communicate with each other. I'm hoping some of you python > lamas out there might be able to share some of your wisdom on the subject. Doubtful, Llamas speak Perl. It's some kind of rodent that does Python. "Womp rats", probably. And Pythons, of course. > What I basically do is a lot of the following:: > > 1. get arbitrary numerical data (typically large data sets in columnar > format or even via COM from other packages. I generally have to deal with > one or more sets of X,Y data) > 2. manipulate the data (scaling, least squares fitting, means, peaks, > add/subtract one XY set from another etc) > 3. plot data (original set, results of manipulation, scatterplot, histograms > etc - I use matplotlib) > 4. export data (print, csv, shelve) Well, obviously you have some options, but let's think about everything in that description that *could* be an object: * Data set (1) * Individual row of a data set (1) * Transformation of a data set (2) * Plot data (3) * Plot (3) (probably same as "Plot data" Chances are that "Individual row of a data set" is a dumb enough object to be represented by a built-in type (maybe a tuple). "Data set" is obviously a collection, possibly ordered, so it might subclass "list" (or just be a list). So far, though, you could just use a "list of tuples". Serialization/deserialization of the data is one reason for subclassing list, though. Or you could have an object representing the file or serialized version, which has a method for returning the data set as a list. "Transformation" is almost certainly a class you want to define. This would obviously hold the data required to define the transformation and at least one method for applying the transformation to a data set. You might even define math operators on it so you can use operator notation like: my_transform = Transformation(... initialization values defining the transform ...) xformed_data_set = my_transform * original_data_set But of course, you could just use methods: xformed_data_set = my_transform.apply(original_data_set) "Plot" is another good defined-class. Initialize it with things like the plotting window, scaling, etc and what data set it applies to. It's nice because it can be 1:1 with the actual display widget in your GUI (if you have one). Candidates for attributes would include the lower and upper X and Y limits, log or linear scale, etc. Candidates for methods would be displaying the plot, printing the plot, converting to a string description, etc. > Clearly I'm having some conceptualisation problems here. Hope someone can > shed some light on the subject I think you are trying to use an object as a module. Better to use a module for that. ;-) Meanwhile, meditate on what "object" or "thing" means to you, and how it might map to programming concepts. What is each "thing" that you can imagine swapping out in a more sophisticated implementation with lots of different variations (e.g. data formats, guis, etc). Clearly modularizing along the lines of interchangeable elements is also a good approach. HTH, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From seberino at spawar.navy.mil Sun Jul 3 02:14:34 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 2 Jul 2005 23:14:34 -0700 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? In-Reply-To: <1120368681.573445.199710@g44g2000cwa.googlegroups.com> References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> <1120368681.573445.199710@g44g2000cwa.googlegroups.com> Message-ID: <1120371274.448543.145890@g43g2000cwa.googlegroups.com> Thanks! Even the fact that these ideas have been organized into a PEP is exciting to me....there is hope that they may *someday* be implemented. Maybe sooner than people think. Another reason to love Python like no other. Chris From jgrh2 at hermes.cam.ac.uk Tue Jul 26 08:38:22 2005 From: jgrh2 at hermes.cam.ac.uk (J.G.R. Hewer) Date: Tue, 26 Jul 2005 13:38:22 +0100 (BST) Subject: psp & php integration In-Reply-To: <393862241.20050726142911@semagia.com> References: <20050725185152.1B9D81E4007@bag.python.org> <393862241.20050726142911@semagia.com> Message-ID: That looks great! Being able to embed Python inside PHP like that should allow to achieve what I intend to do without using PSP in this case. Cheers! Jon On Tue, 26 Jul 2005, Lars Heuer wrote: > Hi Jon, > > [ PHP / Python ] >> If not, is there any other way in Python (or PHP) to achieve this? > > I'm not sure if it helps, but here is package that integrates the > Python into PHP: > > http://www.csh.rit.edu/~jon/projects/pip/ > > > Best regards, > Lars > -- > http://semagia.com > > From cam.ac.uk at mh391.invalid Thu Jul 21 19:50:40 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 00:50:40 +0100 Subject: Returning histogram-like data for items in a list In-Reply-To: References: Message-ID: Ric Deez wrote: > Hi there, > > I have a list: > L1 = [1,1,1,2,2,3] > > How can I easily turn this into a list of tuples where the first element > is the list element and the second is the number of times it occurs in > the list (I think that this is referred to as a histogram): > > i.e.: > > L2 = [(1,3),(2,2),(3,1)] >>> import itertools >>> L1 = [1,1,1,2,2,3] >>> L2 = [(key, len(list(group))) for key, group in itertools.groupby(L1)] >>> L2 [(1, 3), (2, 2), (3, 1)] -- Michael Hoffman From roccomoretti at hotpop.com Thu Jul 28 16:23:46 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 28 Jul 2005 15:23:46 -0500 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Asad Habib wrote: > I agree with Mustafa. After all, we are a bunch of professionals and not > vagabonds hired to take pot shots at one another. Except that we're not all professionals. There are a large number of hobbyists who use Python and this list. At any rate, my suggestion was not to forswear gentle corrections toward better list behavior, (emphasis on gentle) but to address the case where one would be tempted to "fight fire with fire", and answer a potshot with another potshot. Professionals (and even decent hobbyists) don't escalate flame wars, even unintentionally. From bouncer at nowhere.org Mon Jul 25 11:30:49 2005 From: bouncer at nowhere.org (Vladimir Konrad) Date: Mon, 25 Jul 2005 16:30:49 +0100 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: > > Does anyone of you have experiance with KYLIX 3 and do you think I should > consider buying it? Thank You, I'll go oil my keyboard now. http://www.lazarus.freepascal.org/ Sorry if the above came out somewhere else in the thread, did not read all. Vlad From chase at youknowwho.com Sat Jul 16 15:17:22 2005 From: chase at youknowwho.com (Joseph Chase) Date: Sat, 16 Jul 2005 19:17:22 GMT Subject: Django - Rails killer comes... References: <15cuhhg8i6mrg$.ekh1brvux44n$.dlg@40tude.net> Message-ID: <63dCe.3754$uo6.2965@tornado.rdc-kc.rr.com> I can't wait to try this out. We'll see how it stacks up next to ROR. "JZ" wrote in message news:15cuhhg8i6mrg$.ekh1brvux44n$.dlg at 40tude.net... > http://www.djangoproject.com/ > > -- > JZ From gustavo at niemeyer.net Mon Jul 4 15:39:21 2005 From: gustavo at niemeyer.net (Gustavo Niemeyer) Date: Mon, 4 Jul 2005 16:39:21 -0300 Subject: f*cking re module In-Reply-To: <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> Message-ID: <20050704193920.GB9841@burma.localdomain> > > the only thing I want are the number of places blabla, Re modules > > sucks! and blabla are. > > Your question is still not clear. What you're searching for is > '', which isn't there, so .search returns None, and so > you get that exception (.group takes an argument, anyway). That's what I love in that news group. Someone comes with a stupid and arrogant question, and someone else answers in a calm and reasonable way. Thanks Erik. -- Gustavo Niemeyer http://niemeyer.net From gazelle at yin.interaccess.com Sun Jul 10 17:50:34 2005 From: gazelle at yin.interaccess.com (Kenny McCormack) Date: Sun, 10 Jul 2005 21:50:34 GMT Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: In article , Pete Barrett wrote: >On 10 Jul 2005 02:57:04 -0700, "Xah Lee" wrote: > >>Similarly, in computer languages, expressiveness is significant with >>respect to semantics, not syntactical variation. >> >It may just be me, but I tend to think of a computer language as a >tool for directing computers to perform specific actions. Do we talk >about the expressiveness of a spade? Most people think of natural language as "a tool for directing people to perform specific actions" and have as much need for anything beyond that as you seem to have. Luckily, some people (writers, artists) are able to do more with natural language than boss people around. But make no mistake, that is its primary purpose. From cam.ac.uk at mh391.invalid Fri Jul 22 09:48:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 14:48:37 +0100 Subject: dictionary that discards old items In-Reply-To: <42e0b79a$0$30800$db0fefd9@news.zen.co.uk> References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> <42e0b79a$0$30800$db0fefd9@news.zen.co.uk> Message-ID: Will McGugan wrote: >> You want a Least Recently Used, or LRU, cache. Here's one: >> > Thanks. I found the one I saw originally in the Python Cookbook. Only > they call it a FIFO cache. A FIFO cache is different, as gene tani points out. You need to consider which one it is you want. -- Michael Hoffman From exogen at gmail.com Sat Jul 30 12:57:13 2005 From: exogen at gmail.com (Brian Beck) Date: Sat, 30 Jul 2005 12:57:13 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Ivan Van Laningham wrote: > I like / as a shortcut to joinwith(). I like it a lot. I like it so > much I'll give you a +2. +1 here. Extremely practical. -- Brian Beck Adventurer of the First Order From prabapython at yahoo.co.in Tue Jul 26 04:20:04 2005 From: prabapython at yahoo.co.in (praba kar) Date: Tue, 26 Jul 2005 09:20:04 +0100 (BST) Subject: how to build email message with attachment? In-Reply-To: <42E5EEB7.400@REMOVEMEcyber.com.au> Message-ID: <20050726082004.87922.qmail@web8401.mail.in.yahoo.com> Dear All, Can any one let me know? How to build email in python? with some some examples. regards Prabahar _______________________________________________________ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From fuzzyman at gmail.com Wed Jul 6 05:47:04 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jul 2005 02:47:04 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 5) In-Reply-To: References: Message-ID: <1120643223.993202.41910@g49g2000cwa.googlegroups.com> Simon Brunning wrote: [snip..] > > The online Python Journal is posted at pythonjournal.cognizor.com. > editor at pythonjournal.com and editor at pythonjournal.cognizor.com > welcome submission of material that helps people's understanding > of Python use, and offer Web presentation of your work. > Does the 'pythonjournal' still deserve it's place in these posts ? It doesn't *seem* to have been updated for some years. Regards, Fuzzy http://www.voidspace.org.uk/python From jasondrew72 at gmail.com Fri Jul 29 15:02:49 2005 From: jasondrew72 at gmail.com (Jason Drew) Date: 29 Jul 2005 12:02:49 -0700 Subject: Hiding In-Reply-To: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> Message-ID: <1122662993.207041.89630@f14g2000cwb.googlegroups.com> Well, using the open function in Python doesn't launch any application associated with the file (such as Media Player). It just makes the contents of the file accessible to your Python code. Also, I think using file("C:\file.txt") is now preferred to open("C:\file.txt"). To answer the specific question of how to play a music file in Python, search Google Groups for: pygame.mixer.music.load("music.mp3") That will bring up a useful thread. Note that you will need to install a module such as pygame or pymedia; they are not in the standard library. In general, I would also recommend some of the many good Python tutorials. Some are listed here: http://wiki.python.org/moin/BeginnersGuide Good luck! From ms at cerenity.org Sat Jul 30 12:21:35 2005 From: ms at cerenity.org (Michael Sparks) Date: Sat, 30 Jul 2005 18:21:35 +0200 Subject: Python language ver 2.4 , development platform 0.4 References: Message-ID: <42ebb71f$0$14646$ed2619ec@ptn-nntp-reader02.plus.net> Dark Cowherd wrote: > The Python language is at ver 2.4 and a thing of beauty. As a > development environment IMHO it is probably 0.4 Have you considered looking at any of the commercial IDEs? Personally I *like* command line based systems, but I do know many people who swear by GUI based IDEs. If you have, what did want to see but didn't see ? (System usability from my perspective starts with developers, since whilst beauty is skin deep, ugly goes to the bone) Most of these IDEs tend to integrate with one of the more common GUI toolkits as well, which /may/ be more TOOWTDI from your perspective. As for batteries included, I suspect it depends on what you expect as batteries :-) > Small projects, utilities which I am going to code myself I will > continue to use Python because I love it. Nice to hear. > I hope to learn Python well enough to be able to contribute to some > projects to achieve this. But I still see that as six to nine months > away. I'm sure such contributions would be welcome - especially if you're scratching an itch to help resolve the things you currently suggest as deficiencies :-) Regards, Michael. From thomas at thomas-lotze.de Thu Jul 14 07:10:27 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Thu, 14 Jul 2005 13:10:27 +0200 Subject: Frankenstring References: Message-ID: Andreas Lobinger wrote: > >>> t2 = f.find('2')+1 This is indeed faster than going through a string char by char. It doesn't make for a nice character-based state machine, but of course it avoids making Python objects for every character and uses the C implementation of str for searching. However, it's only fine if you are looking for single characters. As soon as you're looking for classes of characters, you need the (slower) regex machinery (as you well know, but for the sake of discussion...). > A string, and a pointer on that string. If you give up the boundary > condition to tell backwards, you can start to eat up the string via f = > f[p:]. There was a performance difference with that, in fact it was faster > ~4% on a python2.2. When I tried it just now, it was the other way around. Eating up the string was slower, which makes sense to me since it involves creating new string objects all the time. > I dont't expect any iterator solution to be faster than that. It's not so much an issue of iterators, but handling Python objects for every char. Iterators would actually be quite helpful for searching: I wonder why there doesn't seem to be an str.iterfind or str.itersplit thing. And I wonder whether there shouldn't be str.findany and str.iterfindany, which takes a sequence as an argument and returns the next match on any element of it. -- Thomas From benn at cenix-bioscience.com Mon Jul 25 09:55:38 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 25 Jul 2005 15:55:38 +0200 Subject: Vanilla python path Message-ID: <42E4EF5A.8080702@cenix-bioscience.com> Hello, I'm attempting to determine what paths I would need on a win32, Linux, OSX box to run python. This should be a vanilla python with no extra packages (including tk). The paths I have beneath are what I think I need, excluding the lib\site-packages entry. The questions that I have are two fold: 1. Is this correct does anyone know if there is something I've missed out? 2. Does python _need_ the /lib/sitepackages directory in sys.path or will it simply be happy enough if it is not there? FYI, I intend to rebuild the paths after this so that I can point python to load required packages and libraries from any location I wish - probably by passing the path as an option to the start script and also the location of the module which will do the reassembling of the python path. This module will be loaded by sitecustomise.py - the reason that sitecustomise.py will not do this itself is that it is automatically a client based file and would require updating on the client - thereby requiring work to maintain the clients. Thanks, in advance for your help, here are the 'vanilla' python paths that I can see - obviously I am aware that the path will change on the system according to where you install python on the box : ------ LINUX ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-dynload'] WIN32 ['', 'C:\\WINDOWS\\system32\\python23.zip', 'C:\\Python23', 'C:\\Python23\\DLLs', 'C:\\Python23\\lib', 'C:\\Python23\\lib\\plat-win'] OSX ['', '/Library/Frameworks/Python.framework/Versions/2.3/lib/python23.zip', '/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3', '/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-dynload'] ----- Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From thanos at sians.org Mon Jul 25 16:48:46 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Mon, 25 Jul 2005 23:48:46 +0300 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <20050725204846.GA32124@zermelo.sians.org> On Sun, Jul 24, 2005 at 02:14:15PM -0600, Steven Bethard wrote: > > How about something like: > dict((name, getattr(obj, name)) for name in dir(obj)) Pretty!!! > Looks like this will get instance attributes, class attributes and > properties just fine. But not SQLObject's objects... Any idea why? (Getting attribute errors, it seems that these "attributoids" are not listed in dir(obj), so i have to use my ugly dictobj class.. :( -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From ivanlan at pauahtun.org Mon Jul 18 15:21:49 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Mon, 18 Jul 2005 13:21:49 -0600 Subject: Earthquake Forecasting Program July 11, 2005 References: <83und1pv3du700os4oug71i6ks242ojqfp@4ax.com> Message-ID: <42DC014D.8CF261E9@pauahtun.org> Hi All-- Bob Officer wrote: > > On Mon, 11 Jul 2005 08:31:31 GMT, in sci.geo.earthquakes, "edgrsprj" > wrote: > > >PROPOSED EARTHQUAKE FORECASTING > >COMPUTER PROGRAM DEVELOPMENT EFFORT > > here we go again... > > EDG is not a computer programmer, nor is he a geologist... > > The best guess seems to be that he is he is crackpot, often going from group > to group espousing some sort of knowledge and asking for people to forward > his articles to government, schools and other professional bodies with a > demand that public monies be giving to him to support his "research". > Well, I guess this is in line with how I persist in seeing the Subject: header. _Every_ time I look at it, my brain sees "Re: Earthquake Fornicating Program". Brings a whole new dimension to "Did the earth move for you too, honey?", doesn't it? Metta, -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From siggy2 at supereva.it Tue Jul 12 07:52:49 2005 From: siggy2 at supereva.it (siggy2 at supereva.it) Date: 12 Jul 2005 04:52:49 -0700 Subject: how to stop execution in interactive window? In-Reply-To: References: <1120833596.025452.166020@g14g2000cwa.googlegroups.com> Message-ID: <1121169168.968704.11760@g47g2000cwa.googlegroups.com> > Right-click on the Pythonwin icon in the tray and select "Break into running > code". [CUT] Thanks a lot! Oddly enough I'm looking into PythonWin manual to see why I did not find it before... and there is no mention of it! Now if only I could find out how to free pythonwin interactive window memory (I'm not talking about interactive window output - cleanable with ctrl-a + delete, but about variable valorization, function definition etc )... IIRC there was already a post in this newsgroup that explained how to do this... but yesterday google searches return me that the only way was to force this by closing and re-opening pythonwin... Maybe I was wrong and there's no other way... Again: thanks a lot for your help! bye, PiErre From pthorstenson at co.montezuma.co.us Mon Jul 25 13:21:22 2005 From: pthorstenson at co.montezuma.co.us (Patrick Thorstenson) Date: Mon, 25 Jul 2005 11:21:22 -0600 Subject: how to imput usernames and passwords?? Message-ID: <000201c5913d$47909f20$8235a8c0@co.montezuma.co.us> I am scripting GIS (mapping) applications at a very very basic level... One of our processes involves connecting to an Oracle database. When the connection occurs, we are prompted to enter a user name and password. That is OK when we are sitting right there but we want to be able to enter this information automatically so these update scripts can run at night. Is there a way I can have Python tell Oracle what the username and password is? Thanks for your help in advance. Patrick Thorstenson GIS Specialist Montezuma County (970) 564-9298 ext 4169 pthorstenson at co.montezuma.co.us -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Jul 27 21:48:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Jul 2005 21:48:34 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Ron Adam wrote: > Michael Hoffman wrote: >> Ron Adam wrote: >>> In all current cases, (that I know of), of differing types, '+' >>> raises an error. >> >> Not quite: >> >>> "hello " + u"world" >> u'hello world' >> >>> 4.5 + 5 >> 9.5 >> > In the case of numeric types, it's an addition and not a join. I should > have specified in 'all cases, (I know of), where '+' is used to join > objects, but I thought that was clear from the context of the > discussion. I haven't needed to use unicode yet, so it didn't come to > mind. I believe Michael intended to show that "4.5 + 5" actually represents using + with two different types, specifically a float and an int, thus giving at least two common cases where errors are not raised. (While the issue of "addition" vs. "join" is merely a (human) language issue... one could just as well say that those two numbers are being "joined" by the "+".) -Peter From cliff at develix.com Sun Jul 31 15:09:48 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 12:09:48 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <1122829672.285541.45710@g43g2000cwa.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <1122829672.285541.45710@g43g2000cwa.googlegroups.com> Message-ID: <1122836989.19618.88.camel@localhost.localdomain> On Sun, 2005-07-31 at 10:07 -0700, Kay Schluehr wrote: > Some other people already abandoned Python not for the worst reasons: > > http://www.kevin-walzer.com/pivot/entry.php?id=69 Being a developer requires not only a bit of brains, but quite a bit of tenacity as well. Apparently Kevin lacks the second. > My objection with wrappers around wrappers around wrappers is that I > have no hope ever watching the ground. If some error occurs, which > layer has to be addressed? Which developing group is reponsible? My own > or that of team A, team B, team C ... ? The baroque concept is > repulsive to me and only acceptable in case of legacy code that gets > wrapped around old one and is dedicated to substitute it continously. Of course, Tkinter is still a wrapper around a third party library (Tk) borrowed from a different language (Tcl) and written again in a third language (C), much the same as wxPython. Your concerns are valid in a theoretical sense, but in practice make little difference. If you are using Tkinter and it exposes a bug in Tk, then you report to the Tkinter maintainers and they will get it fixed. The same can be said for wxPython. Robin Dunn is a wxWidgets developer and if wxPython exposes a bug in wxWidgets, then he will be responsible for getting that bug fixed. As an aside, at one time, Tkinter required that Tcl be installed (and used) in order to interface with Tk. This is no longer the case. Tk has been abstracted into a standalone library (quite some time ago, actually) and Python uses it pretty much the same way Tk does. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From ncoghlan at gmail.com Wed Jul 6 09:17:20 2005 From: ncoghlan at gmail.com (NickC) Date: 6 Jul 2005 06:17:20 -0700 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: <1120655839.962625.292170@f14g2000cwb.googlegroups.com> Ralf, I'd be very interested to hear your opinion on the 'namespace' module, which looks at addressing some of these issues (the Record object, in particular). The URL is http://namespace.python-hosting.com, and any comments should be directed to the namespace at googlegroups.com discussion list. Regards, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.blogspot.com From caleb1 at telkomsa.net Mon Jul 18 16:07:45 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Mon, 18 Jul 2005 22:07:45 +0200 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: Hi Doug Not only was Kylix a letdown, there is talk also of it being discontinued. To be fair though, it is easy to see the difficulty for Borland to deploy a Linux IDE of the same quality as Delphi when so much in different Linux distributions is variable, the widget set being a prime example: CLX just never caught on, amongst the myriad of more mature and more open toolsets. I am assuming that you have experience with pascal, or ObjectPascal as the Delphi manuals call it (if not, why Kylix?). If so, may I suggest you look into a) fpc (Free Pascal Compiler, http://www.freepascal.org) b) Lazarus (An fpc IDE, aims to be an open-source Delphi clone, supports multiple widget sets [Win32 native on Windows!], can't remember the URL) Though python is probably my favourite language for general purpose hacking, there is a lot to be said for a native compiled language (sometimes speed _is_ an issue), and in particular there is a lot to be said for fpc: - Something like 99% Turbo Pascal compliant - Very nearly Delphi compliant (object-pascal) - (IMHO) Much cleaner language than C, still natively compiled - Supports operator overloading & inlining - Can be used to develop python extensions - Supports nearly effortless cross-compiling There are some problems with Lazarus at the moment, here is the biggie: It creates binaries of around 5MB for a minimal app, and this is because, at the moment it seems like it compiles the component library into the executable. This is somewhat of a problem for me but I expect this will change within a release or two. Lazarus is _very_ much like Delphi, and works on Windows, Linux, and possibly several other platforms. cya Caleb > and net for info about Borlands KYLIX 3 and have found little technical > info about it. Their screen shots are very impressive, similar to Visual > Basic. I have sent several emails to Borlands Sales and Pre-Sales > departments. Pre-Sales bounces and Sales won't answer. I'm sitting here > with money in hand ready to buy but not from a company that won't give me > the time of day. > > Does anyone of you have experiance with KYLIX 3 and do you think I should > consider buying it? Thank You, I'll go oil my keyboard now. > > Doug > From supermetan at yahoo.fr Mon Jul 18 06:21:20 2005 From: supermetan at yahoo.fr (met@n) Date: Mon, 18 Jul 2005 12:21:20 +0200 (CEST) Subject: email format in python Message-ID: <20050718102120.64241.qmail@web42004.mail.yahoo.com> I want to have the python equivalent function of this (that checks email format) function CheckEmail($Email = "") { if (ereg("[[:alnum:]]+@[[:alnum:]]+\.[[:alnum:]]+", $Email)) { return true; } else { return false; } } ___________________________________________________________________________ Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger T?l?chargez cette version sur http://fr.messenger.yahoo.com From Sebastien.Boisgerault at gmail.com Sun Jul 3 13:52:21 2005 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 3 Jul 2005 10:52:21 -0700 Subject: C parser with spark Message-ID: <1120413141.629730.268190@g49g2000cwa.googlegroups.com> Hi, Has anybody already implemented a full ANSI C parser with John Aycock's spark module ? (spark : http://pages.cpsc.ucalgary.ca/~aycock/spark/) Cheers, SB From steve at REMOVETHIScyber.com.au Tue Jul 19 09:48:25 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 19 Jul 2005 23:48:25 +1000 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: On Tue, 19 Jul 2005 02:33:02 +0000, Leif K-Brooks wrote: > rbt wrote: >> IMO, most of the people who deride goto do so because they heard or read >> where someone else did. > > 1 GOTO 17 > 2 mean, GOTO 5 > 3 could GOTO 6 [snip] That's great, but not a patch on the power of COMEFROM! Or, to put it another way: 1 2 readability COMEFROM 4 3 that's COMEFROM 6 4 hurt COMEFROM 7 5 to COMEFROM 10 6 but COMEFROM 2 7 might COMEFROM 9 8 nothing COMEFROM 3 9 goto COMEFROM 12 10 compared COMEFROM 8 11 comefrom COMEFROM 5 12 using COMEFROM 1 -- Steven. From kay.schluehr at gmx.net Wed Jul 20 01:51:38 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jul 2005 22:51:38 -0700 Subject: Ordering Products In-Reply-To: References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121752847.005587.145960@g44g2000cwa.googlegroups.com> Message-ID: <1121838698.759788.310170@g14g2000cwa.googlegroups.com> Ron Adam wrote: > Kay Schluehr wrote: > > > > Hi Ron, > > > > I really don't want to discourage you in doing your own CAS but the > > stuff I'm working on is already a bit more advanced than my > > mono-operational multiplicative algebra ;) > > I figured it was, but you offered a puzzle: > > "Here might be an interesting puzzle for people who like sorting > algorithms ..." > > And asked for suggestions: > > "It would be interesting to examine some sorting algorithms on factor > lists with constrained item transpositions. Any suggestions?" > > So I took you up on it. ;-) > > > BTW.. Usually when people say "I don't want to discourage...", They > really want or mean the exact oppisite. Yes, but taken some renitence into account they will provoke the opposite. Old game theoretic wisdoms ;) > This is a organizational problem in my opinion, so the challenge is to > organize the expressions in a way that can be easily manipulated > further. Groupings by operation is one way. As far as inheritance > goes, it's just another way to organize things. And different algebra's > and sub-algebra's are just possible properties of a group. The groups > can easily be customized to have their own behaviors or be created to > represent custom unique operations. > > The sort method I'm suggesting here, with examples, is constrained by > the associated properties of the group that is being sorted. Basically, > weather or not it's and associative operation or not. So when a group > is asked to sort, it first asks all it's sub groups to sort, then it > sorts it self if it is an associative group. Ie.. from inner most group > to outer most group but only the associative ones. But you seem to fix behaviour together with an operation i.e. declaring that __mul__ is commutative. But in a general case you might have elements that commute, others that anti-commute ( i.e. a*b = -b*a ) and again others where no special rule is provided i.e. they simply don't commute. But much worse than this the definition of the operations __add__, __mul__ etc. use names of subclasses A,D explicitely(!) what means that the framework can't be extended by inheritance of A,D,M etc. This is not only bad OO style but customizing operations ( i.e. making __mul__ right associative ) for certain classes is prevented this way. One really has to assume a global behaviour fixed once as a class attribute. > > Playing with it further I get the following outputs. > > ( The parenthesis surround a group that is associated to the operation. > This is the same idea/suggestion I first proposed, it's just been > developed a little further along.) > > > b+a+2 = (2+a+b) <- addition group > > a*(b+45+23) = ((68+b)*a) <- addition group within multiply group > > a-4-3-7+b = ((a-14)+b) <- sub group within add group > > c*b-d*a+2 = (2+((b*c)-(a*d))) <- mults within subs within adds > > 7*a*8*9+b = ((504*a)+b) > > a*(b+c) = ((b+c)*a) > > c*3*a*d*c*b*7*c*d*a = (21*a*a*b*c*c*c*d*d) I still don't see how you distinguish between factors that might commute and others that don't. I don't want a and b commute but c and d with all other elements. > d*b/c*a = (((b*d)/c)*a) > > (d*b)/(c*a) = ((b*d)/(a*c)) > > d*b-a/e+d+c = (((b*d)-(a/e))+c+d) > > a/24/2/b = (a/48/b) > > c**b**(4-5) = (c**(b**-1)) > > (d**a)**(2*b) = ((d**a)**(2*b)) If you have fun with those identities you might like to find simplifications for those expressions too: a*0 -> 0 a*1 -> a 1/a/b -> b/a a+b+a -> 2*a+b a/a -> 1 a**1 -> a etc. > The next step is to be able to convert groups to other groups; an > exponent group to a multiply group; a subtract group to an addition > group with negative prefix's.. and so on. > > That would be how expansion and simplifying is done as well as testing > equivalence of equations. > > if m*c**2 == m*c*c: > print "Eureka!" > > > > Mixing operators is not really a problem, but one has to make initial > > decisions ( e.g about associativity i.e. flattening the parse-tree ) > > and sub-algebra generation by means of inheritance: > > What do you mean by 'sub-algebra generation'? Partially what I described in the subsequent example: the target of the addition of two elements x,y of X is again in X. This is not obvious if one takes an arbitrary nonempty subset X of Expr. > >>>>a,b = seq(2,Expr) > >>>>type(a+b) > > > > > > > >>>>class X(Expr):pass > >>>>x,y = seq(2,X) > >>>>type(x+y) > > > > > > > > This is not particular hard. It is harder to determine correspondence > > rules between operations on different levels. On subalgebras the > > operations of the parent algebra are induced. But what happens if one > > mixes objects of different algebras that interoperate with each other? > > It would be wise to find a unified approach to make distinctive > > operations visually distinctive too. Infix operators may be > > re-introduced just for convenience ( e.g. if we can assume that all > > algebras supporting __mul__ that are relevant in some computation have > > certain properties e.g. being associative ). > > Different algebras would need to be able to convert themselves to some > common representation. Then they would be able to be mixed with each > other with no problem. Well, it is a problem not only of representation. You might have three algebras A,B,C each providing a different multiplication operator and also interoperation capabilities: A*B = B*A may hold but (A,*) is not associative and neither A nor B interoperates with C i.e. an operation C*A or C*B is not defined. > Or an operation on an algebra group could just accept it as a unique > term, and during an expansion process it could convert it self (and it's > members) to the parents type. That would take a little more work, but I > don't see any reason why it would be especially difficult. > > Using that methodology, an equation with mixed algebra types could be > expanded as much as possible, then reduced back down again using a > chosen algebra or the one that results in the most concise representation. Maybe you should simply do that. > > > ########################################################################## > > > > After thinking about M ( or Expr ;) a little more I come up with a > > solution of the problem of central elements of an algebra ( at least > > the identity element e is always central ) that commute with all other > > elements. > > What is a "central" element? I can see it involves a set, but the > context isn't clear. "Central" elements are exactly those that commute with all other elements. In In abelian groups they constitute the groups itself. In non-abelian groups they are subgroups ( the center always exist and is contains at least the unit element ). Since each group has a center one can make general assertions without considering elements individually. It is a common pattern of reasoning to abstract from concrete elements and rely on properties of classes of elements. Kay From awaretek at gmail.com Fri Jul 29 10:20:39 2005 From: awaretek at gmail.com (Ron Stephens) Date: 29 Jul 2005 07:20:39 -0700 Subject: Friend wants to learn python In-Reply-To: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> References: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> Message-ID: <1122646839.822416.36880@g14g2000cwa.googlegroups.com> EnderLocke wrote: > I have a friend who wants to learn python programming. I learned off > the internet and have never used a book to learn it. What books do you > recommend? > > Any suggestions would be appreciated. I have just uploaded a podcast specifically about which tutorials and books might be best for newbies to Python, depending on their background. It can be reached at http://www.awaretek.com/python/index.html Ron From prakashreghate at yahoo.co.in Mon Jul 25 05:03:10 2005 From: prakashreghate at yahoo.co.in (prakash reghate) Date: Mon, 25 Jul 2005 10:03:10 +0100 (BST) Subject: regarding porting to windows. Message-ID: <20050725090310.61441.qmail@web8506.mail.in.yahoo.com> Respected Sir / Madam , I am Prakash . I am also working on porting C PROGRAMS to windows from Linux , but i doesn't get any clue yet. I have some C - programs written on Linux & i have to port it on windows . The problem starts from header files. So if you have any help or document, link related to this which will help me in this scenario ,let me know. Thanks !!! Regards, Prakash Reghate --------------------------------- How much free photo storage do you get? Store your friends n family photos for FREE with Yahoo! Photos. http://in.photos.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From spike666 at mac.com Mon Jul 11 11:14:47 2005 From: spike666 at mac.com (spike grobstein) Date: 11 Jul 2005 08:14:47 -0700 Subject: importing files from a directory In-Reply-To: References: <1120966204.900591.212980@g44g2000cwa.googlegroups.com> Message-ID: <1121094887.008492.49580@z14g2000cwz.googlegroups.com> my reason for loading both the .py and .pyc files was just in case compiled files were supplied as modules... but I'm gonna disallow that, so yeah. I also got a response in email and I've been dabbling with my code since I posted this and found a slightly better way of handling this plugin system... I stuck the import code into the Modules/__init__.py file, so it can act as a kind of manager (instead of moving the files to a Modules(disabled) directory) and appended the __import__s to an array. like this: spike at flaphead ~/Aphex $ cat Modules/__init__.py module_list = [] def load_module(mod_name): mod = __import__("Modules.%s" % mod_name) mod = getattr(mod, mod_name) module_list.append(mod.module()) def load_modules(): load_module("nes") load_module("snes") load_module("mame") load_modules() [end code] I then just have to 'import Modules' from my main program and the whole module import thing is encapsulated and invisible to my main program. I'm gonna add some functions to the Modules module to make fetching plugins a little less ambiguous (get_module(index) and get_named_module(module_name), etc). Thanks for the help. Python's making me have to think a little backwards. I have to make sure I declare my functions before I call them, but it's a very cool language overall. ...spike From duncan.booth at invalid.invalid Thu Jul 7 10:35:42 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jul 2005 14:35:42 GMT Subject: Windows Cmd.exe Window References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: Giles Brown wrote: > The special first line is: > > @pythoncmd -x "%~f0" %* & exit /b > > (In the python.org FAQ for windows it says > @setlocal enableextensions & python -x %~f0 %* & goto :EOF > but since I have no idea which is "right" I chose the simpler looking > one) > > This approach does require pythoncmd.exe to by in your %PATH% but I > think that is reasonable ;) > > I am a bit disappointed I couldn't think of a way of deciding if I was > running a ".cmd" file in sitecustomize.py so that I could just use the > normal python.exe. Using a renamed interpreter .exe is just a trick > for detecting when I am running .cmd files, but it means that the > script won't run on another machine that hasn't had the python.exe > copied to pythoncmd.exe on it. Which is a shame. I'm having problems understanding your problem. If the file is a .cmd file then surely the second line (i.e. the one immediately following the python -x command) could simply do "import sethook" where sethook would be a module that sets your excepthook. Alternatively you could check at any point whether sys.argv[0] ends with '.cmd' or '.bat' (after lowercasing). > > So my question. Is there a better way? I'm not really happy with > this approach. Should I stop worrying and go and play my new ukulele? > Answers please. Go on, upload some ukulele playing somewhere. BTW, another solution is to push the pause command out to the shell: ----------------------- @setlocal enableextensions & (python -x %~f0 %* || pause) & goto :EOF import sys if len(sys.argv) > 1: sys.exit("this will pause") ----------------------- will pause only if the python program terminates with a non-zero exit code. This means messages from sys.exit will cause a pause as well as exceptions. From tvmaly at gmail.com Mon Jul 18 12:43:57 2005 From: tvmaly at gmail.com (tvmaly at gmail.com) Date: 18 Jul 2005 09:43:57 -0700 Subject: Image orientation and color information with PIL? Message-ID: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> Does anyone know if it is possible to determine if an image is horizontal/vertical and color or black & white using the python image library? I have been searching this news group and the information was not all clear on this. Best Regards Ty From cliff at develix.com Sat Jul 30 16:55:38 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 13:55:38 -0700 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <42EB882B.2DF04797@pauahtun.org> References: <42EB882B.2DF04797@pauahtun.org> Message-ID: <1122756939.19618.28.camel@localhost.localdomain> On Sat, 2005-07-30 at 08:01 -0600, Ivan Van Laningham wrote: > Tony Meyer wrote: > > > > >> (Those who are offended by sweeping generalisations should > > >> ignore this next bit) > > [...generalisation bit snipped...] > > > This is not only bullshit, it's elitist bullshit. "Windows users are > > > more clueless than users of posix systems." Pfui. Prove it > > > or withdraw it. > > > > Sigh. I guess you didn't read or understand the first sentence? > > > > Yes, I read and understood it. Saying "Don't read this if you don't > want to be offended" doesn't make an offensive statement inoffensive. While people are loathe to admit it, many stereotypes have some basis in fact. The problem is when people extend that to generalize about others (especially in a negative way). It's probably true that, as a whole, most Windows users are quite a bit less knowledgeable about their systems than *nix users. This is probably the result of Windows being quite a bit more user-friendly than *nix systems (another generalization!), hence demanding less of the user, and also, I suspect, due to the fact that *nix users tend to be a self-selected crowd (they chose *nix because they wanted to learn more, and are willing to accept the larger demand the OS places on them in exchange for the added flexibility it provides). Of course, this is impossible to prove, but anyone who's done support knows where the majority of the silly questions come from. That being said, there is a big difference between a Windows *user* and a Windows *developer*. I doubt many Windows *users* will be writing Python code. I would expect that any Windows *programmer* would have no problem using "/" as a path delimiter (and in fact, Microsoft APIs have supported / as a path delimiter since MS-DOS days). Programmers are as much a self-selected crowd as the *nix users and this puts them on par with *nix developers. > Using __div__ to mean path concatenation is no worse than > using __add__ to mean string concatenation, and it is both easy to > remember (once the manual is read) and easy to type. I agree. I like overloading as long as it makes sense when I read it. Python's use of "+" to mean concatenation doesn't make me blink, nor does overloading "/" in this case. In fact, I'm surprised it's only now been proposed. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From peter at engcorp.com Sun Jul 3 17:05:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 17:05:38 -0400 Subject: How do you program in Python? In-Reply-To: <1120420258.718480.262220@g44g2000cwa.googlegroups.com> References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Message-ID: James wrote: > Peter Hansen wrote: >>I edit in the Scite window, hit Alt-Tab (under Windows XP) to change >>focus to the cmd console (and instantly all my modified files are >>saved), press the Cursor Up key to retrieve the previous command (which >>is generally the name of my script, or a command like "python >>myscript.py"), and hit Enter to execute it. > > Just curious. Why do you Alt-Tab to a console when you can just hit F5 > in SciTE? That's just 1 key instead of 4. And yes, SciTE can autosave > here too. Probably a variety of reasons. You might say ignorance is one of them (since I wasn't consciously aware of that feature), but it's really that I deliberately choose not to use and learn about such features of editors because I absolutely _hate_ getting tied to such things and finding myself stuck in other editors or on other machines and having my productivity drop to zero because a simple feature is missing. This is the same reason I no longer use any IDE, nor have any interest whatsoever in them other than out of simple curiosity. I used to learn all kinds of details about things like VisualCafe, CodeWright, IDLE, Boa Constrictor, Borland C++, a dozen different Microsoft products... no longer! If I didn't have Scite, I'd be able to use DOS Edit almost as effectively, and by observation I've concluded that using such primitive tools I'm often more effective than others around me who are "stuck" using the latest featureful tools... Also, I lied when I said cursor up retrieved the name of the script. Since I develop using Test-Driven Development, and use a simple suite of utilities to manage the test files and such, I'm more often executing something like "story015 TestCase.test03", or perhaps just "u" (which runs all unit tests in the current folder), rather than the name of the script which I happen to be editing. Judging by how F5 appears to work, it wouldn't save me keystrokes either: I'd most likely be in some *other* file making changes (i.e. one of the modules under test) but would need to hit Alt-9 (or a bunch of Ctrl-Tabs) to switch to wherever story015.py was sitting. The file I want to run won't always be the one under my cursor, nor perhaps even loaded. After 25 years doing this, I've become something of a Luddite as far as fancy IDEs and non-standard features go... and a huge believer in strict decoupling between my tools, to the point of ignoring things that bundle them together in ways that are, in my opinion, too tight. Sorry! :-) -Peter From tuxlover at gmail.com Mon Jul 11 17:53:56 2005 From: tuxlover at gmail.com (tuxlover) Date: 11 Jul 2005 14:53:56 -0700 Subject: read output and store in file In-Reply-To: <1121117484.692617.76590@o13g2000cwo.googlegroups.com> References: <1121117484.692617.76590@o13g2000cwo.googlegroups.com> Message-ID: <1121118836.741524.130510@g43g2000cwa.googlegroups.com> use os.path.walk() or os.walk() Tuxlover From bokr at oz.net Tue Jul 12 19:07:51 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 23:07:51 GMT Subject: Inconsistency in hex() References: Message-ID: <42d44b4b.24650135@news.oz.net> On Tue, 12 Jul 2005 21:17:07 +1000, Steven D'Aprano wrote: >hex() of an int appears to return lowercase hex digits, and hex() of a >long uppercase. > >>>> hex(75) >'0x4b' >>>> hex(75*256**4) >'0x4B00000000L' > >By accident or design? Apart from the aesthetic value that lowercase hex >digits are ugly, should we care? > >It would also be nice if that trailing L would disappear. > >>> '%010X'% 0x12345678 '0012345678' >>> '%010X'% 75 '000000004B' >>> '%010X'% (75*256**4) '4B00000000' >>> '%010X'% (-75*256**4) '-4B00000000' >>> '%010X'% (-75) '-00000004B' I've ranted about the lack of a natural format for showing the hex of a canonical twos-complement representation of a negative number, but I guess I'll let it go with this mention ;-) BTW, yeah, I know it's not so hard to write >>> '%010X'% (-75 &0xffffffffff) 'FFFFFFFFB5' >>> '%010X'% (-75*256**4 &0xffffffffff) 'B500000000' or a helper or a str subclass that does __mod__ differently but that's not with the batteries ;-/ Regards, Bengt Richter From tharakawick at gmail.com Mon Jul 25 00:06:07 2005 From: tharakawick at gmail.com (tharaka) Date: 24 Jul 2005 21:06:07 -0700 Subject: Fire event when variable is Set/Get In-Reply-To: References: Message-ID: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> You are in luck because Python has "Properties" just like .NET. For details lookup the documentation of the built-in function property(). I'll just paste it here: property( [fget[, fset[, fdel[, doc]]]]) Return a property attribute for new-style classes (classes that derive from object). fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") ... now u can use x like any variable and, python will get & set it through the appropriate methods. Hope this answers your question. From jgrh2 at cam.ac.uk Sun Jul 31 16:59:13 2005 From: jgrh2 at cam.ac.uk (Jon Hewer) Date: Sun, 31 Jul 2005 21:59:13 +0100 Subject: Python IDE's Message-ID: <20050731205901.53A6E1E4005@bag.python.org> Hi I am yet to find a Python IDE (for both Windows and Mac) that I like. Any suggestions? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From stygian at tesco.net Sun Jul 31 08:30:43 2005 From: stygian at tesco.net (glen) Date: Sun, 31 Jul 2005 13:30:43 +0100 Subject: Newb: Telnet 'cooked data','EOF' queries. Message-ID: <42ECC473.4050307@tesco.net> While experimenting with telnetlib, Ive come across a couple of 'features' that confuse me a little (lot!). Could someone explain what "cooked data" is. Also when trying read_all() the program seems to lock up, which I assume is because it is waiting for an EOF, but 'when' is an EOF received. Glen From mwm at mired.org Sun Jul 31 01:20:19 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 01:20:19 -0400 Subject: multiple inheritance super() References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> <1122653176.013770.106080@g49g2000cwa.googlegroups.com> <86br4ljnxs.fsf@bhuda.mired.org> <1122716129.428629.273960@g49g2000cwa.googlegroups.com> Message-ID: <86slxvh7qk.fsf@bhuda.mired.org> "Michele Simionato" writes: I think you're replying to me, but you didn't include any indication so I can't be sure. > If I understand correcly you have a situation like this: > > Base > > | > > Parent1 Mixin > | | > | | > Children1 > > Base > > | > > Parent2 Mixin > | | > | | > Children2 > > > Base > > | > > Parent3 > | > | > Children3 Mostly right. What missing from the diagram is that there are three Base classes: Base1, Base2 and Base3. They have no methods in common. > The Base class is pretty general, Parent1, Parent2 and Parent3 are more > specific, Children1 and Children2 requires the Mixin class, but > Children3 does > not require it. At least one ParentX also uses Mixin. > Let me note that this looks like a sensible design and that I agree > that in simple > situations multiple inheritance could be the simplest solution. Thank you. > Nevertheless 1) I am scared of the case where you have hundreds of > methods coming from everywhere (ex. Zope) and Any tool can be abused. > Various solutions (using pseudocode): > 1. use single inheritance and attach the mixin methods by hand: > 2. use single inheritance and delegation. If "mixin" is a proxy to > the methods in the mixin (for instance implemented as an attribute > descriptor) you could do These two are cases of what I was talking about when I referred to the Church-Turing thesis. Also, I don't see how they make the situation you are scared of above any better. > 3. think differently and use multimethods > > There are implementations of multimethods in Python (for instance in > PEAK). > This example looks like a good candidate for a multiple dispatch > solution. > You would use single inheritance and promote the mixin methods to > multimethods. I don't see how that would help at all. You haven't done anything about solving the base problem - that getting the methods into my classes cleanly needs multiple inheritance. Further, I don't need methods that are distinguished based on their arguments - they all take a fixed set of arguments, and operate on them and the state of the instance. None seem to be candidates for being multimethods. The mixin methods tend to provide general functionality, and get used in radically different places by the different child classes. You did miss the one alternative I considered: making the methods of Mixin stand-alone functions, and passing them extra arguments instead of using attributes of the instance. They would all then look like mixin_func(self.foo, self.bar, var, value). I decided that this wasn't as readable as inherting the methods. > BTW, I think multimethods are pretty nifty and I would welcome them > in standard Python. I wouldn't bet on it happening. They seem to violate "explicit is better than implicit". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rkern at ucsd.edu Sun Jul 3 15:45:52 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 03 Jul 2005 12:45:52 -0700 Subject: Accepted Summer of Code proposals In-Reply-To: References: <68e6a54a005f51ae50ada6932ea22d09@wolke7.net> Message-ID: Peter Decker wrote: > On 7/2/05, Reinhold Birkenfeld wrote: > >>A.M. Kuchling wrote: >> >>>For anyone who's interested: the Python wiki now contains a list of the >>>PSF-mentored proposals that were accepted for Google's Summer of Code: >>> http://wiki.python.org/moin/SummerOfCode >> >>Is it right that two Wax proposals were accepted? > > Or that Wax is being promoted over Dabo, which wraps wxPython just as > elegantly in its UI tier, and which is further along (more controls > supported) than Wax, is more powerful (data binding is built in), and > is still being actively developed? I would suggest not speculating on biased or malicious intentions. It is possible that no one applied with a proposal to work on Dabo, or that such a proposal was poorly written, or that the author had too little experience, or any number of other things. (Disclosure: I am now a co-mentor on an unrelated SoC project, but I wasn't part of the group rating and selecting proposals.) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From roccomoretti at hotpop.com Thu Jul 14 10:14:41 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 14 Jul 2005 09:14:41 -0500 Subject: Porting from Python 2.3 to 2.4 In-Reply-To: References: <1121318153.193982.31460@g44g2000cwa.googlegroups.com> Message-ID: Joseph Garvin wrote: > Anand wrote: > >> Hi >> >> Are there any tools that would help in porting code from >> Pyton 2.3 to 2.4 ? I have gone through the whatsnew documents >> and created a document comparing Python 2.4 to 2.3. But so far >> has not been able to find any tool that will signal code in >> Python 2.3 that can cause errors in Python 2.4 . >> >> rgds >> >> -Anand >> >> >> > All 2.x versions are backwards compatible. Porting just means taking > advantage of new features. Unless you've been naughty and are accessing > private methods in stdlib, you're probably fine. Not strictly speaking true - if your program is taking advantage of some of the dark corners of the language, there is a chance your program might not work. Be aware though, that programs that take advantage of "features" which change between 2.x releases likely aren't using best practices anyway. (The Python team strongly hesitates to change behavior if it breaks backward compatibility for a large number of programs.) See http://www.python.org/doc/2.4.1/whatsnew/whatsnew24.html for details on what changes. Possible non-backward compatible changes for 2.3->2.4 transition: *Int/long operations no longer produces FutureWarnings that can be suppressed. (Uses new behavior instead.) *Integer operations will no longer trigger an OverflowWarning. *You can't rebind None. *New modules/builtin functions added - if you've used the same names, you may get the wrong module/function in corner cases. Minor issues all, but if you happen to rely on that behavior, your code will now fail, sometimes silently. From roy at panix.com Mon Jul 4 08:35:59 2005 From: roy at panix.com (Roy Smith) Date: Mon, 04 Jul 2005 08:35:59 -0400 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <42c929dc$0$27601$636a15ce@news.free.fr> Message-ID: bruno modulix wrote: > Try Emacs + python-mode. Emacs surely has a lot of warts, but I'm still > looking for a better and more versatile code editor/IDE - specially when > it comes to languages with REPL (-> Read-Eval-Print Loop). When you build Python, make sure you build it with Gnu readline support. Then you can just fire up an interpreter, and use emacs (or, I suppose, vi) editing commands to scroll back through (and change) your input history. It's not as good as a real IDE, but it's still very handy for quick explorations. The next step up would be to run a real emacs, do M-X shell, then fire up a Python interpreter inside that. Or, go into split screen mode in emacs, editing your python source file in one window and running a shell in the other. Edit some code in the source window, and it takes about 6 keystrokes to save it, flip to the other window, and re-run the file (you can get it down to a single keystroke by defining a simple macro and binding it to a function key). From sjmachin at lexicon.net Wed Jul 13 19:02:51 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Jul 2005 09:02:51 +1000 Subject: all possible combinations In-Reply-To: <1121267364.28617.4.camel@athop1.ath.vt.edu> References: <1121267364.28617.4.camel@athop1.ath.vt.edu> Message-ID: <42d59d9b@news.eftel.com> rbt wrote: > On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: > >>Say I have a list that has 3 letters in it: >> >>['a', 'b', 'c'] >> >>I want to print all the possible 4 digit combinations of those 3 >>letters: >> >>4^3 = 64 >> >>aaaa >>abaa >>aaba >>aaab >>acaa >>aaca >>aaac >>... >> >>What is the most efficient way to do this? > > > Expanding this to 4^4 (256) to test the random.sample function produces > interesting results. It never finds more than 24 combinations out of the Uh-oh -- there's that word again! What you mean to say is that it never finds more than 24 *PERMUTATIONS*. 1. google("define: permutation") 2. Consider that 24 == 4 * 3 * 2 * 1 3. RTFM("random.sample"), paying particular attention to the word "unique" > possible 256. This leads to the question... how 'random' is sample ;) > > Try it for yourselves: > > test = list('1234') > > combinations = [] > while 1: > combo = random.sample(test, 4) > possibility = ''.join(combo) > if possibility not in combinations: > print possibility > combinations.append(possibility) > continue > else: > continue > Instead of the utterly pointless continue/else/continue, shouldn't you have some method (other than keyboard interrupt) of jumping off the merry-go-round? From ville at spammers.com Fri Jul 1 04:57:48 2005 From: ville at spammers.com (Ville Vainio) Date: 01 Jul 2005 11:57:48 +0300 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: >>>>> "Timothy" == Delaney, Timothy (Tim) writes: Timothy> Absolutely. I've really tried to use Eclipse - it's the Timothy> standard editor for my current project (Java - blegh!). I Timothy> *hate* it. It's huge, bulky, slow ... I've gone back to Timothy> my text editor. I'm a hell of a lot more Have you tried the recently released 3.1 version? It seems to be a tad snappier than the old version. Timothy> The only IDE I've ever actually liked using was Timothy> Metrowerks CodeWarrior (on MacOS classic). Simple, Timothy> unobtrusive. Good project management, without trying to Timothy> control every aspect of the development process. And The debugger in CodeWarrior is quite crappy IMHO. Unlike visual studio, it doesn't show the return values of function calls. The editor is also quite lacking, without the ability to create macros etc. I agree about the project management part. Though I would still love to use Eclipse instead, if it only was supported for my line of work :-/. Timothy> it allowed me to use the entire screen for editing if I Timothy> wished whilst still having everything readily available. Eclipse allows this as well. ctrl+m is maximize/unmaximize. -- Ville Vainio http://tinyurl.com/2prnb From fred at adventistcare.org Tue Jul 12 09:53:28 2005 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 12 Jul 2005 09:53:28 -0400 Subject: Yet Another Python Web Programming Question Message-ID: <777056A4A8F1D21180EF0008C7DF75EE0331754D@sunbelt.org> FWIW there's "dos2unix" program that fixes this on most systems. -----Original Message----- From: Bill Mill [mailto:bill.mill at gmail.com] Sent: Monday, July 11, 2005 11:55 AM To: Daniel Bickett Cc: python-list at python.org Subject: Re: Yet Another Python Web Programming Question > Python using CGI, for example, was enough for him until he started > getting 500 errors that he wasn't sure how to fix. A common error is that python cgi files need line endings to be in unix text file format, not windows text file format (\n instead of \r\n) [1]. Why this is, I don't know, but it causes a lot of errors for windows folks. I'm a frequent linux/windows switcher, and it's caused me no end of troubles - if you're getting "premature end of script headers" in your apache error logs, this may be your problem. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From daniel at dittmar.net Fri Jul 22 17:24:51 2005 From: daniel at dittmar.net (Daniel Dittmar) Date: Fri, 22 Jul 2005 23:24:51 +0200 Subject: Extending python - undefined symbol error on import In-Reply-To: <1122047378.752186.6840@z14g2000cwz.googlegroups.com> References: <1122047378.752186.6840@z14g2000cwz.googlegroups.com> Message-ID: <3kd6iiFtliitU1@uni-berlin.de> ch424 wrote: > However, when I open up the python command line, and type "from gpib > import *" or "import gpib" I get "ImportError: /usr/.../gpibmodule.so: > undefined symbol: ibdev" -- but I know it's defined in the ni488.h > file, especially as I can use this code from actual C programs without > problems. The ni488.h file in in the right place to be used for C > compilation. I guess ibdev is *declared* in ni488.h and you'll have to add the lib where it is *defined*. You'll probably have to add a libraries = ['gpip'] to setup.py. Daniel From c at cdot.de Thu Jul 28 12:17:30 2005 From: c at cdot.de (Chris) Date: Thu, 28 Jul 2005 18:17:30 +0200 Subject: Regex for nested {} Message-ID: hello, I have a problem matching nested levels of {}, example: >>> import re >>> text = """ outer { inner1 { ... } inner2 { ... } } simple { ... } """ >>> r = re.compile(r""" ( # OPTION1 .*? # begin \{ # starting { (?: \{.*?\} )* # inner groups \} # ending } )| # OR ( # OPTION2 .*? { .*? } # simple group may also happen ) """, re.DOTALL|re.IGNORECASE|re.UNICODE|re.VERBOSE ) >>> r.findall(text) >>> [('', '\n\touter { \n\t\tinner1 { ... }'), ('', ' \n\t\tinner2 { ... }'), ('', ' \n\t}\n\tsimple { ... }')] the regex I currently use stops at the first closing } but what I am looking for is a result as: [ "outer { inner1 { ... } inner2 { ... } }", "simple { ... }" ] is something like that possible? thanks for any hint chris From pinard at iro.umontreal.ca Sun Jul 31 12:04:24 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 31 Jul 2005 12:04:24 -0400 Subject: keylogger in Python In-Reply-To: References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> Message-ID: <20050731160424.GA10627@phenix.progiciels-bpi.ca> [Michael Hoffman] > You think this is a suitable beginner project? One surely learns a lot! :-) > And for that matter, it doesn't sound like you were doing keylogging, as > it is usually understood to mean globally logging keypresses, no matter > the application being presented to the user. One possible avenue to keylogging might be to start a shell, over the keyboard processing layer, presuming the shell do only simple things over its standard input. But most likely, the shell is playing termios trickery and such things. So one might have to use pty's to get a working solution. Agreed, this is not all evident, and probably too much of a challenge for a beginner. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From negroup at gmail.com Thu Jul 7 05:23:03 2005 From: negroup at gmail.com (Negroup) Date: 7 Jul 2005 02:23:03 -0700 Subject: Create datetime instance using a tuple. References: <2fdabf19.0507060101.6184974e@posting.google.com> Message-ID: <2fdabf19.0507070123.76f2e6c2@posting.google.com> > > Use: > dt =3D datetime(*t) > Thanks for the quick reply. I can't find any doc about '*' used in this context. Have you some url or suggestion for which terms search in Google? From phillip.watts at anvilcom.com Sun Jul 3 20:38:28 2005 From: phillip.watts at anvilcom.com (phil) Date: Sun, 03 Jul 2005 19:38:28 -0500 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <42C7067E.4090609@anvilcom.com> <200507022213.13343.hancock@anansispaceworks.com> Message-ID: <42C88504.1090905@anvilcom.com> > I did already post a serious reply, but now I'm afraid I've been > trolled. :-P > I hope you did not think I was dissing your response, because I certainly was not and in fact recognized your response as a sincere effort to enlighten. To whomever I directed sarcasm I apologize. My frustration is 20 years old and has nothing to do with you or Zope. Anyway, thanks Terry, I still don't know what Zope is but I need to accept that it's just a toolkit and I'm not gonna know until I dig in and as long as my web needs are simple, I probably won't. From zen19725 at zen.co.uk Sun Jul 31 01:38:14 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 06:38:14 +0100 Subject: shelve: writing out updates?! References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: On Sat, 30 Jul 2005 17:57:17 -0700, Robert Kern wrote: >Paul Rubin wrote: >> Shelve uses dbm and pickle to make a persistent object store. The >> "db" in "dbm" stands for "database" and while I didn't expect full >> ACID capability, I'd have thought there'd be at least some minimum >> gesture towards durability of updates. But say that s is a shelve >> object. If I say >> >> s[whatever] = value >> >> there is no way apparent from the shelve docs to get the update >> flushed out to the disk file until the shelve is actually closed. If >> I'm using the shelve to store stuff in a long-running server, it could >> be months before the shelve closes. >> >> Is shelve really missing this capability? > >No. Call the .sync() method. Unfortunately, the shelve module is not >well-documented. Obviously it's good when stuff is well documented. I wonder if the barrier to good documentation is set too high? If i wanted to add some documentation here, I'd have to download the current source for the latest Python documentation, download, install and learn the code that processes the source documentation, write my changes then send the results into the CVS. (I'm assuming that's roughly correct -- I haven't actually done it). The point is, that would be a major effort, too major to merely add a few lines detailing the .sync method. But, what if the Python documentation was on a Wiki? Then it would be easy to update! Of course, we would have to guard against false or malicious updates, but Wikipedia manage that OK. The Documentation Wiki could then be used as a basis for the "official" documentation that comes with each new release. Does this idea make some sense? Or are there hidden pitfalls? -- Email: zen19725 at zen dot co dot uk From bokr at oz.net Thu Jul 7 12:45:31 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 07 Jul 2005 16:45:31 GMT Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: <42cd58d9.46356757@news.oz.net> On 7 Jul 2005 15:46:23 GMT, Duncan Booth wrote: >Steven D'Aprano wrote: > >> Put it this way: whenever I see a two-line def as above, I can't help >> feeling that it is a waste of a def. ("Somebody went to all the trouble >> to define a function for *that*?") Yet I would never think the same about >> a lambda -- lambdas just feel like they should be light-weight. > >Obviously we think differently there. I don't see why lambdas are any >different than single expression functions. I certainly don't think of them >as lighter weight; they take just as long to call; and they involve just as >much stack setup/tear down. On the other hand I don't consider functions as >heavyweight, I'm happy to define short helper functions anywhere I think it >makes the code more expressive. > >> Am I just weird? > >No, just different[*]. There's nothing wrong with different. > >[*] conclusion based entirely on your postings here. I have no evidence >beyond that. > I think def is a form of assignment, with the target binding name specified inside the expression syntax instead of to the left of an '=' as usual. I.e., def f(args): suite is like f = def(args): suite except that I can't use an arbitrary left-hand side in the assignment, such as MyClass.method = def(self, args): suite or somedict['foo'] = def(self, args): suite Personally, I think def(args): suite ought to be allowed as an expression that you could put in parentheses like any other expression if you need/want to write it with multiple lines. Obviously this could both replace and expand the functionality of lambda ;-) Regards, Bengt Richter From cjw at sympatico.ca Sun Jul 3 12:38:04 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 03 Jul 2005 12:38:04 -0400 Subject: A Policy for Inclusion in the Standard Library: was Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: Terry Reedy wrote: > "Colin J. Williams" wrote in message > news:gaxxe.15816$mK5.1126958 at news20.bellglobal.com... > >>Isn't this where the discussion should start? There should be some >>general policy guiding the types of modules which should be in the >>standard library. > > > A couple of times, Guido has given his general policy as generally useful; > best-of-breed, tested and accepted by the community; and backed by a > developer who will adapt it and its doc up to stdlib standards (if > necessary) and commit to maintainence for a few years. > > Terry J. Reedy > This is a good base. Presumably "accepted by the community" means with some minimum number of ongoing users. Colin W. From mwm at mired.org Wed Jul 27 22:40:27 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 27 Jul 2005 22:40:27 -0400 Subject: multiple inheritance super() References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> <42e748e9$0$32207$626a14ce@news.free.fr> <1122454160.835071.87690@z14g2000cwz.googlegroups.com> Message-ID: <863bpzmz50.fsf@bhuda.mired.org> "Michele Simionato" writes: >>I am mostly >>using old style (without type unification) init but this motivate the >>shift for the new style. Is there somewhere a document about this? > Yes, see http://www.python.org/2.3/mro.html by yours truly I'd also recommend reading . It's got some good practical advice on using super in your code. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tjreedy at udel.edu Sun Jul 10 19:46:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jul 2005 19:46:38 -0400 Subject: decorators as generalized pre-binding hooks References: <42d02c21.231516573@news.oz.net> <1121034087.932596.221010@g43g2000cwa.googlegroups.com> Message-ID: "George Sakkis" wrote in message news:1121034087.932596.221010 at g43g2000cwa.googlegroups.com... > "Terry Reedy" wrote: >> This possibility was discussed on the py-dev list about a year or so >> ago. >> The twice monthly summaries should include this topic. As I remember, >> the >> reason for limiting to functions included: >> >> 1. classes have metaclasses, functions don't have metafunctions. No one >> gave an example for classes not handled at least as well with a >> metaclass. > > Would something like the following count ? [snip] Not qualified to comment. >> 2. certain applications require long-function_names_like_this, for which >> triple typing is substantially annoying and error-prone. > > I'm not sure what you mean here; where is the 'triple typing' ? def long-function_names_like_this(arg1, b, xx , sklfjsl, uuuu): 'body of fuction here' pass long-function_names_like_this = \ some_decorator(long-function_names_like_this) And for the example I am thinking of (integrating Python with Objective-C, I believe), the above name is apparently not an exaggeration. > And how is this an argument against class decorators ? It is an argument for function decos that does not apply to classes. The does not seem to be a similar need for long, convoluted, class names. (And there is the metaclass option for classes that there is not for functions.) So, in relative terms, it is an argument that function decos are relatively more needed than class decos. Given that the decision to add them all was a fairly closely balanced one, relative differences can tip the balance one way one time and the other way the other. Guido did not permanently rule out class decos, that I know of, but he noted that it would be easier to add them later if really needed than to remove them later is not really needed. Terry J. Reedy From uche.ogbuji at gmail.com Fri Jul 29 19:39:22 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 29 Jul 2005 16:39:22 -0700 Subject: Suggestions for Python XML library which can search and insert In-Reply-To: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> References: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> Message-ID: <1122680362.868093.100510@f14g2000cwb.googlegroups.com> "I'm looking for a library that can search through an XML document tree, locate an element by attribute (ideally this can be done through XPath), and insert an element (as its child). Simple? Yes? ...but the code I've seen so far which does this uses 'nested for loops' for trees which are relatively shallow compared to mine. " Amara can easily do this using XPath (complete with predicates, functions, etc.), without nested for loops: http://uche.ogbuji.net/tech/4Suite/amara/ -- Uche http://uche.ogbuji.net From cam.ac.uk at mh391.invalid Thu Jul 21 18:40:47 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 23:40:47 +0100 Subject: dictionary that discards old items In-Reply-To: <42e01f85$0$1586$da0feed9@news.zen.co.uk> References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> Message-ID: Will McGugan wrote: > I need a collection class that behaves like a dictionary but when it > reaches 'n' items it discards the oldest item so that the length never > goes above 'n'. (Its for caching search results) > > I have a vague memory of a module that does this, but I cant remember > where I read about it. Can anyone enlighten me? You want a Least Recently Used, or LRU, cache. Here's one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524 Google for to find others. -- Michael Hoffman From thomasbartkus at comcast.net Fri Jul 15 15:07:36 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 15 Jul 2005 14:07:36 -0500 Subject: Native ODBC access for python on linux? References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> <8NCdnRaSkdR-XkvfRVn-jg@telcove.net> <86r7e0al3p.fsf@bhuda.mired.org> <1121446822.710877.312020@g44g2000cwa.googlegroups.com> Message-ID: <_ICdne5Z-td7lUXfRVn-2A@telcove.net> wrote in message news:1121446822.710877.312020 at g44g2000cwa.googlegroups.com... > All, > > This info was very helpful, and I'm up and running with MySQLdb on > linux, and the native ODBC support on Windows. > > One last question I have: In vbs (specifically with .asp) I can make a > connection to an ODBC provide _without_ the need to specify a system > DSN in the Control Panel. It's easy to do with MySQLdb.connect( > host,user,pass,etc), but is this possible with the ODBC module in > Python on win32? > Ahhh - But that's the point! If you are "up and running with MySQLdb on linux" then you should be up and running with with the same code on Windows. The exact same Python script you run on Linux will work for you on windows! I *think* you might be able to attach the ODBC driver but it would be a complication and an unnecessary one at that. Just point MySQLdb.connect() at the servers IP address. Go to SourceForge and download the MySQLdb installation for win32 [MySQL-python.exe-1.2.0.win32-py2.4.exe]. Sometimes you can't believe it because it's too easy :-) Thomas Bartkus From cantabile.03 at wanadoo.fr Sun Jul 17 13:43:46 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Sun, 17 Jul 2005 19:43:46 +0200 Subject: ConfigParser : overwrite ? In-Reply-To: References: <42da80cf$0$25057$8fcfb975@news.wanadoo.fr> Message-ID: <42da98d2$0$891$8fcfb975@news.wanadoo.fr> Robert Kern a ?crit : > cantabile wrote: > >> Hi, I'm trying and updating an .ini file with ConfigParser but each time >> I call 'write', it appends the whole options another time to the file. >> For example : >> Here's the inital ini file >> >> [section1] >> foodir: %(dir)s/whatever >> dir: foo >> >> Here's my code : >> filename = ... >> config = ConfigParser.ConfigParser() >> config.read(filename) >> config.set('section1', 'dir', 'anotherdir') >> f = open(filename, 'r+') >> config.write(f) >> f.close() >> >> Then I get : >> >> [section1] >> foodir: %(dir)s/whatever >> dir: anotherdir >> >> [section1] >> foodir: %(dir)s/whatever >> dir: foo >> >> I tried also with 'w', 'w+', 'a' ... > > > Are you sure you tried it with 'w' as the mode? > > In [1]: !cat foo.ini > [section1] > foodir: %(dir)s/whatever > dir: foo > In [2]: fn = 'foo.ini' > > In [3]: import ConfigParser > > In [4]: cfg = ConfigParser.ConfigParser() > > In [5]: cfg.read(fn) > Out[5]: ['foo.ini'] > > In [6]: cfg.set('section1', 'dir', 'anotherdir') > > In [7]: f = open(fn, 'w') > > In [8]: cfg.write(f) > > In [9]: f.close() > > In [10]: !cat foo.ini > [section1] > foodir = %(dir)s/whatever > dir = anotherdir > You are right, it works. I thought I had tried it ... Thanks. :) From steven.bethard at gmail.com Sat Jul 23 22:07:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 23 Jul 2005 20:07:25 -0600 Subject: dictionary that discards old items In-Reply-To: <42e2dfa0.980127588@news.oz.net> References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> <1121999372.836621.190950@o13g2000cwo.googlegroups.com> <42e2dfa0.980127588@news.oz.net> Message-ID: [Raymond Hettinger] >>class Cache(dict): >> def __init__(self, n, *args, **kwds): >> self.n = n >> self.queue = collections.deque() >> dict.__init__(self, *args, **kwds) [Bengt Richter] > Minor comment: There is a potential name collision problem for keyword n=something, > so what is considered best practice to avoid that? __n or such as the n arg? I don't know what best practice is, but if you want to guarantee to avoid the name collision, you can write: def __init__(*args, **kwargs): self = args[0] self.n = args[1] self.queue = collections.deque() dict.__init__(self, *args[2:], **kwargs) It's not pretty though. ;) STeVe From ed at leafe.com Sat Jul 30 12:42:14 2005 From: ed at leafe.com (Ed Leafe) Date: Sat, 30 Jul 2005 12:42:14 -0400 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> Message-ID: <200507301242.14860.ed@leafe.com> On Saturday 30 July 2005 12:28, Peter Decker wrote: > It would be great if the wxPython folks would adopt Dabo, and > eventually integrate it so that there is but a single, Pythonic way of > working with wxPython, but it seems that they have their hands full > just wrapping the C++ code of wxWidgets. ?Thanks for the vote of encouragement! ? ?Our goal isn't to muddy the waters; it is simply to create a consistent API for coding. There is already a great GUI toolkit for Python; we're just trying to make it easier to code. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From wccppp at gmail.com Mon Jul 4 03:35:54 2005 From: wccppp at gmail.com (wcc) Date: 4 Jul 2005 00:35:54 -0700 Subject: question about raw_input References: <1120380440.564612.160180@g47g2000cwa.googlegroups.com> Message-ID: <1120462554.395174.6670@g49g2000cwa.googlegroups.com> Thanks for your suggestion Michael. -wcc From rkern at ucsd.edu Mon Jul 25 00:18:02 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 21:18:02 -0700 Subject: Problem loading a file of words In-Reply-To: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> Message-ID: teoryn wrote: > I've been spending today learning python and as an exercise I've ported > a program I wrote in java that unscrambles a word. Before describing > the problem, here's the code: > > *--beginning of file--* > #!/usr/bin/python > # Filename: unscram.py > > def sort_string(word): > '''Returns word in lowercase sorted alphabetically''' > word = str.lower(word) > word_list = [] > for char in word: > word_list.append(char) > word_list.sort() > sorted_word = '' > for char in word_list: > sorted_word += char > return sorted_word An idiomatic Python 2.4 version of this function would be: def sort_string(word): word = word.lower() sorted_list = sorted(word) sorted_word = ''.join(sorted_list) return sorted_word > print 'Building dictionary...', > > dictionary = { } > > # Notice that you need to have a file named 'dictionary.txt' > # in the same directory as this file. The format is to have > # one word per line, such as the following (of course without > # the # marks): > > #test > #hello > #quit > #night > #pear > #pare > > f = file('dictionary.txt') > > # This loop builds the dictionary, where the key is > # the string after calling sort_string(), and the value > # is the list of all 'regular' words (from the dictionary, > # not sorted) that passing to sort_string() returns the key > > while True: > line = f.readline() > if len(line) == 0: > break > line = str.lower(line[:-1]) # convert to lowercase just in case > and > # remove the return at the end of > the line > sline = sort_string(line) > if sline in dictionary: # this key already exist, add to > existing list > dictionary[sline].append(line) > print 'Added %s to key %s' % (line,sline) #for testing > else: # create new key and list > dictionary[sline] = [line] > print 'Created key %s for %s' % (sline,line) #for > testing > f.close() # this really should all be within a function, but let's just carry on dictionary = {} f = open('dictionary.txt') try: # enclose this in a try: finally: block in case something goes wrong for line in f: line = line.strip().lower() sline = sort_string(line) val = dictionary.setdefault(sline, []) val.append(line) print "Added %s to key %s" % (line, sline) finally: f.close() > print 'Ready!' > > # This loop lets the user input a scrambled word, look for it in > # dictionary, and print all matching unscrambled words. > # If the user types 'quit' then the program ends. > while True: > lookup = raw_input('Enter a scrambled word : ') > > results = dictionary[sort_string(lookup)] > > for x in results: > print x, > > print > > if lookup == 'quit': > break > *--end of file--* > > > If you create dictionary.txt as suggested in the comments, it should > work fine (assumeing you pass a word that creates a valid key, I'll > have to add exceptions later). The problem is when using a large > dictionary.txt file (2.9 MB is the size of the dictionary I tested) it > always gives an error, specifically: > (Note: ccehimnostyz is for zymotechnics, which is in the large > dictionary) Well, my version works (using /usr/share/dict/words from Debian as dictionary.txt). Yours does, too. Are you sure that you are using the right dictionary.txt? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ahabib at engin.umich.edu Thu Jul 28 16:14:22 2005 From: ahabib at engin.umich.edu (Asad Habib) Date: Thu, 28 Jul 2005 16:14:22 -0400 (EDT) Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: What, do you not consider yourself a professional? Just because you are in academia does not justify attacking people on a mailing list and then justifying your attack with Harter's quote! Life is more than a quote - look outside your academic cocoon and you will realize what I mean. - Asad On Thu, 28 Jul 2005, Robert Kern wrote: > Asad Habib wrote: > > I agree with Mustafa. After all, we are a bunch of professionals and not > > vagabonds hired to take pot shots at one another. > > Speak for yourself. ;-) > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > > -- > http://mail.python.org/mailman/listinfo/python-list > From mike.ceravolo at gmail.com Sun Jul 3 13:49:03 2005 From: mike.ceravolo at gmail.com (mike.ceravolo at gmail.com) Date: 3 Jul 2005 10:49:03 -0700 Subject: Using regular expressions in internet searches Message-ID: <1120412943.283248.100700@g14g2000cwa.googlegroups.com> What is the best way to use regular expressions to extract information from the internet if one wants to search multiple pages? Let's say I want to search all of www.cnn.com and get a list of all the words that follow "Michael." (1) Is Python the best language for this? (Plus is it time-efficient?) Is there already a search engine that can do this? (2) How can I search multiple web pages within a single location or path? TIA, Mike From tim.peters at gmail.com Sat Jul 9 11:22:16 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 9 Jul 2005 11:22:16 -0400 Subject: PPC floating equality vs. byte compilation In-Reply-To: <1120888655.953163@yasure> References: <1120888655.953163@yasure> Message-ID: <1f7befae05070908227704f21@mail.gmail.com> [Donn Cave] > I ran into a phenomenon that seemed odd to me, while testing a > build of Python 2.4.1 on BeOS 5.04, on PowerPC 603e. > > test_builtin.py, for example, fails a couple of tests with errors > claiming that apparently identical floating point values aren't equal. > But it only does that when imported, and only when the .pyc file > already exists. Not if I execute it directly (python test_builtin.py), > or if I delete the .pyc file before importing it and running test_main(). It would be most helpful to open a bug report, with the output from failing tests. Can't guess much from the above. In general, this can happen if the platform C string<->float routines are so poor that eval(repr(x)) != x for some float x, because .pyc files store repr(x) for floats in 2.4.1. The 754 standard requires that eval(repr(x)) == x exactly for all finite float x, and most platform C string<->float routines these days meet that requirement. > For now, I'm going to just write this off as a flaky build. I would > be surprised if 5 people in the world care, and I'm certainly not one > of them. I just thought someone might find it interesting. There are more than 5 numeric programmers even in the Python world , but I'm not sure there are more than 5 such using BeOS 5.04 on PowerPC 603e. > The stalwart few who still use BeOS are mostly using Intel x86 hardware, > as far as I know, but the first releases were for PowerPC, at first > on their own hardware and then for PPC Macs until Apple got nervous > and shut them out of the hardware internals. They use a Metrowerks > PPC compiler that of course hasn't seen much development in the last > 6 years, probably a lot longer. The ultimate cause is most likely in the platform C library's string<->float routines (sprintf, strtod, that kind of thing). From joe at skyrush.com Tue Jul 5 00:42:10 2005 From: joe at skyrush.com (Joe Peterson) Date: Mon, 04 Jul 2005 22:42:10 -0600 Subject: "long int..." exception reported with strange traceback location In-Reply-To: References: Message-ID: <42CA0FA2.8040401@skyrush.com> Yep, my thinking too. Well, maybe it's all related to the same bug somehow. OK, I submitted a bug report, and I included a slight modification of the test case you guys suggested: ---------------- import sys import os t = 2147483648L os.utime("foo_test_file", (t, t)) print "hi" ---------------- This way, there's no "float" call, simply an asignment of a long int... Thanks, Joe Peter Otten wrote: > Terry Reedy wrote: > > >>>>>os.utime("foo_test_file", (0, float(sys.maxint+1))) >> >>Traceback (most recent call last): >>File "", line 1, in ? >>TypeError: utime() arg 2 must be a tuple (atime, mtime) >> >>which is quite sane. So maybe bug was introduced in 2.3 which you were >>running. > > > But arg 2 *is* a tuple. So a least the error message is wrong, too. > > Peter > From jlconlin at lanl.gov Wed Jul 6 14:35:23 2005 From: jlconlin at lanl.gov (Jeremy) Date: Wed, 06 Jul 2005 12:35:23 -0600 Subject: inheriting file object In-Reply-To: <42CC13F2.4050808@bellsouth.net> References: <42CC13F2.4050808@bellsouth.net> Message-ID: Jeremy Jones wrote: > Something like this? I put the following code in test_file.py: > > class MyFile(file): > def doing_something(self): > print "in my own method" > > > And used it like this: > > In [1]: import test_file > > In [2]: f = test_file.MyFile("foobar.file", "w") > > In [3]: f.write("foo\n") > > In [4]: f.doing_something() > in my own method > > > But do you really need to subclass file, or can you just use a file > instance in your class? > > > Jeremy Jones I don't know if I should be inheriting file or just using a file object. How would I determine which one would be more appropriate? Thanks, Jeremy From janssen at parc.com Tue Jul 12 21:50:57 2005 From: janssen at parc.com (Bill Janssen) Date: Tue, 12 Jul 2005 18:50:57 PDT Subject: Browser plug-in for Python? In-Reply-To: Your message of "Tue, 12 Jul 2005 17:27:50 PDT." <20050713002747.GA26579@unpythonic.net> Message-ID: <05Jul12.185105pdt."58617"@synergy1.parc.xerox.com> Yes, thanks, back in the day I used Grail and played with rexec. I notice that one of the Summer of Code projects was to recreate rexec, but don't know if it was funded. Presumably a Firefox plug-in for Python would restrict the execution environment in some safe way, and provide some kind of UI toolkit API so that the Python program could draw on the area given to the plug-in. If I were doing it, I'd probably add something like Joel Bartlett's "ezd" drawing system (see http://www.hpl.hp.com/techreports/Compaq-DEC/WRL-91-6.pdf), replacing the Scheme used in ezd with Python. Bill From rkern at ucsd.edu Mon Jul 25 01:40:09 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 22:40:09 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <874qajbg9d.fsf@wilson.rwth-aachen.de> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> <878xzwarjy.fsf@wilson.rwth-aachen.de> <874qajbg9d.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > As far as i know, there is nothing official. But I've read several > times that it's the most likely candidate for a seconds GUI system > for being included. I think you're reading *way* too much into people engaging in wishful thinking. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tvmaly at gmail.com Wed Jul 20 12:05:52 2005 From: tvmaly at gmail.com (tvmaly at gmail.com) Date: 20 Jul 2005 09:05:52 -0700 Subject: Image orientation and color information with PIL? In-Reply-To: References: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> Message-ID: <1121875551.959511.238850@f14g2000cwb.googlegroups.com> Jeff, this was exactly what I was looking for. I wrote a script with this code and it worked perfectly. Thanks Ty From daniel.dittmar at sap.corp Fri Jul 8 04:33:17 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 08 Jul 2005 10:33:17 +0200 Subject: python nested class In-Reply-To: References: Message-ID: Vedanta Barooah wrote: > in a python nested class is it possible to change the value of the > parent class's variable without actually creating an instance of the > parent class Python nested classs are like *static* Java nested classes. Non-static Java classes are very different in that they have an implicit reference to an instance of the enclosing class. This is why you can instantiate non-static inner classes only in the context (= non-static method) of a specific object. There is no direct equivalent to this in Python, so you have to do the steps yourself. - the constructor takes an additional argument, the 'outer' object, which has to be kept in the object: def __init__ (self, outer, ...): self.outer = outer - when creating the inner object, the outer object must be passed to the constructor obj = InnerClass (self) - the outer object must be explicitely referenced: self.outer.increase (20) Daniel From rkern at ucsd.edu Mon Jul 25 00:19:34 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 21:19:34 -0700 Subject: Problem loading a file of words In-Reply-To: <1122264873.347064.195990@f14g2000cwb.googlegroups.com> References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> <1122264873.347064.195990@f14g2000cwb.googlegroups.com> Message-ID: Devan L wrote: > Heh, it reminds me of the code I used to write. > > def sort_string(word): > return ''.join(sorted(list(word.lower()))) > f = open('dictionary.txt','r') > lines = [line.rstrip('\n') for line in f.readlines()] > f.close() > dictionary = dict((sort_string(line),line) for line in lines) That's definitely not the kind of dictionary that he wants. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From grante at visi.com Wed Jul 27 14:38:35 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 27 Jul 2005 18:38:35 -0000 Subject: [Beginner] Calling a function by its name in a string References: Message-ID: <11efl5b3i827o2a@corp.supernews.com> On 2005-07-27, Paolino wrote: >> Is there a metalanguage capability in Python (I know there are many) to >> call a function having its name in a string? > eval('foo()') should do, but it's said a bad practice ;) An alternative to eval() is: >>> def foo(): ... print "foo was called" ... >>> s = "foo" >>> globals()[s]() foo was called >>> -- Grant Edwards grante Yow! I'm meditating on at the FORMALDEHYDE and the visi.com ASBESTOS leaking into my PERSONAL SPACE!! From sybrenUSE at YOURthirdtower.com.imagination Sun Jul 10 16:16:58 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 10 Jul 2005 22:16:58 +0200 Subject: ZipFile and file rigths References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> Message-ID: perchef enlightened us with: > it works well but i have a small problem : i can't see how i can > deal with file rights. When I unzip files with this script all the > unzipped files haven't the good rights. That's right. Why should they? ZIP doesn't store file permissions. > ZipInfo objects doesn't store informations about rights ? Correct. > How can i fix this ? Don't use ZIP. Use tar instead. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From mwm at mired.org Sun Jul 31 14:52:58 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 14:52:58 -0400 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <87ek9fr0c3.fsf@wilson.rwth-aachen.de> Message-ID: <86ack2hkol.fsf@bhuda.mired.org> Torsten Bronger writes: > Hall??chen! > Mike Meyer writes: >> Torsten Bronger writes: >>> Calvin Spealman writes: >>>> The choice is GUI toolkits is largely seperate from >>>> Python. Consider that they are just bindings to libraries that >>>> are developed completely seperate of the language. GUI is should >>>> be seperate from the language, and thus not bound to same >>>> expectations and desires as elements of the language itself. >>> I disagree. A modern language must provide a convenient and >>> well-embedded way to write GUI applications. >> The tools for writing GUI applications belong in a library, not >> the langauge. > None of us has talked about changing syntax. However, the standard > library is part of the language unless you're really very petty. Or you use different Python implementations. There are four different Python implementations in the world. Not everything in the CPYthon standard library runs in all of them. Or are you going to claim that someone usin Jython isn't using Python because they can't use the full standard library? If they're using python, then the parts of the standard library they can't use aren't part of the language. Which calls into question everything in the standard library. >>> This is not a sign of decadence, but a very good promotional >>> argument. >> But it's not required for the language to succeed. > Today it is (except for very special-purpose languages). To put this differently, it's required if you want to succeed as a language for the specific purpose of creating GUI applications. I'd agree to that. But there are *lots* of other application areas around, so limiting your definition of "success" to that one field is very short-sighted. >> C and C++ are both doing very well without your a well-embedded >> way to write GUI applications. > I don't think that much money is made with new C programs. Almost > all money with C++ is made with VC which has been having a GUI > toolkit in its standard library right from the beginning. And most > money is made with VB AFAIK. Your definition of success is clearly different than mine. You restrict your definition of success to proprietary applications - which I almost never use. If I were using a definition as stilted as yours, I'd say that success was measured by the number of lines of source code in that language that were freely available. By which measure C is still immensely popular, because of the large number of older applications that are written in it that are available - Python being one such. On the other hand, I do recognize that proprietary applications exist. The only real measure of the success of a language is how many applications are being written in it - and that measure will change depending on the application area in question. I'd say Python has succeeded as a web development language, and as a systems scripting language - and I've certainly missed some. Now that it's available for the S60 series phone (I'm going to get one, I swear), I'd say it's set to succeed as a development language for portable devices. None of these are what you call "specific-purpose" areas, just application development areas that don't need a GUI. By restricting yourself to projects that make money, you're also limiting the apparent success of VB. From what I can tell, most applications written in VB are in-house tools of various kinds. That makes it even more successful than your measure would lead you to believe. C++ succeeded on platforms that VC doesn't run on, so you can hardly claim that VC was responsible for C++'s success. Since you brought up the off-topic point of VB, I'd say that the *most* money is made with SQL. That's based on far to many years of watching the want ads. Almost all of them require some language other than SQL, and a lot of those are indeed VB. >> However, you can get compilers for both that come bundled with a >> good GUI library. Could it be that that's what you really want - >> someone to distribute Python bundled with an enterprise-class GUI >> library and IDE? > Well, a nice thing to have, but besides my point. Then you seem to have missed some of your own points. C++ succeeded without having a standard GUI library. You claimed that that success was because of a single distribution that included the things you are looking for. Why can't the same thing work for Python? > We do have a standard library with a robust GUI package, and a > standard distribution with a so-called IDE. What I really want is a > better GUI included into the standard library. I think you're the first person I've heard call IDLE an IDE. Then again, I don't pay much attention to it. Or maybe you meant something else. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From phillip.watts at anvilcom.com Wed Jul 6 10:33:55 2005 From: phillip.watts at anvilcom.com (phil) Date: Wed, 06 Jul 2005 09:33:55 -0500 Subject: More On - deepcopy, Tkinter References: Message-ID: <42CBEBD3.3050605@anvilcom.com> Thanks, I used some of your methods and believe it is now working. I also did a lot of experiments, which I've needed to do, investigating when references vs values are passed and returned. Not as obvious as I thought. Duncan Booth wrote: > phil wrote: > > >> >> >>>The deepcopy protocol does allow you to specify how complicated >>>objects should be copied. Try defining __deepcopy__() in your objects >>>to just copy the reference to the Canvas object instead of the object >>>itself. >>> >> >>I can't figure out from the docs what __deepcopy__ is or how it >> >>works. >>I have about 25 classes of drawn objects. for instance >>class linefromslope creates an instance of class line. >>One of my "ugly solutions" involves a class prop: within each class, >>put properties like slope and midpoint within the self.prop instance >>and making a copy of that. >>Would __deepcopy__ facilitate this? >>Or am I assuming too much: is __deepcopy__ just a method >>I invent to do what I want? >> >> > > The docs say: > > >>In order for a class to define its own copy implementation, it can >>define special methods __copy__() and __deepcopy__(). The former is >>called to implement the shallow copy operation; no additional >>arguments are passed. The latter is called to implement the deep copy >>operation; it is passed one argument, the memo dictionary. If the >>__deepcopy__() implementation needs to make a deep copy of a >>component, it should call the deepcopy() function with the component >>as first argument and the memo dictionary as second argument. >> > > __deepcopy__ is a method which overrides the default way to make a deepcopy > of an object. > > So, if you have a class with attributes a, b, and c, and you want to ensure > that deepcopy copies a and b, but doesn't copy c, I guess you could do > something like: > > >>>>class MyClass: >>>> > _dontcopy = ('c',) # Tuple of attributes which must not be copied > > def __deepcopy__(self, memo): > clone = copy.copy(self) # Make a shallow copy > for name, value in vars(self).iteritems(): > if name not in self._dontcopy: > setattr(clone, name, copy.deepcopy(value, memo)) > return clone > > >>>>class Copyable(object): >>>> > def __new__(cls, *args): > print "created new copyable" > return object.__new__(cls, *args) > > > >>>>m = MyClass() >>>>m.a = Copyable() >>>> > created new copyable > >>>>m.b = Copyable() >>>> > created new copyable > >>>>m.c = Copyable() >>>> > created new copyable > >>>>clone = copy.deepcopy(m) >>>> > created new copyable > created new copyable > >>>>m.a is clone.a >>>> > False > >>>>m.c is clone.c >>>> > True > > > As you can see, the deepcopy only creates deep copies of 2 of the 3 > attributes, 'c' is simply copied across as a shallow copy. > > and if you subclass MyClass you can modify the _dontcopy value to add > additional attributes which must not be copied. > From maxilys at SPAMCOP_tele2.fr Fri Jul 8 20:38:42 2005 From: maxilys at SPAMCOP_tele2.fr (Remi Villatel) Date: Sat, 09 Jul 2005 02:38:42 +0200 Subject: Polling, Fifos, and Linux In-Reply-To: References: Message-ID: Jeremy Moles wrote: > This is my first time working with some of the more lower-level python > "stuff." I was wondering if someone could tell me what I'm doing wrong > with my simple test here? > > Basically, what I need is an easy way for application in userspace to > simply echo values "down" to this fifo similar to the way proc files are > used. Is my understanding of fifo's and their capabilities just totally > off base? Funny coincidence... I was also trying some FIFO stuff today. I came to a very simple solution for just one writer and one listener. I make this stuff send text (strings) from one Konsole to another Konsole. The FIFO was created from Bash with: $ mkfifo -m 666 fifo listener.py ------------------ #! /usr/bin/env python fifo = open("fifo","r") while True: print fifo.readline()[:-1] # [:-1] because of the newline added by print. # ------------------ writer.py ------------------ #! /usr/bin/env python fifo = open("fifo", "a") # Mode "a" or "w" try: fifo.write("This string goes down the pipe.\n") # Newline is important because the listener uses readline(). fifo.flush() # Output is buffered. except IOError: pass # ------------------ If you kill the writer, the listener remains quiet until somebody writes into the pipe. The same happens if there is no writer. If you kill the listener, the writer reports a broken pipe when it tries to flush(). The writer can close and open the pipe to its liking, the listener doesn't care. The only problem is that the writer freezes when it opens the pipe until there is a listener at the other end. Any way, it's very simple and it uses 0% of the CPU. Just my 2 Euro cents, -- ================== Remi Villatel maxilys_ at _tele2.fr ================== From gene.tani at gmail.com Tue Jul 19 09:09:54 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jul 2005 06:09:54 -0700 Subject: How to send a query to the browser from time to time? In-Reply-To: References: Message-ID: <1121778594.008969.237970@f14g2000cwb.googlegroups.com> not clear if you're asking about XMLHttpRequest http://www.modernmethod.com/sajax/ http://nevow.com/Nevow2004Tutorial.html#livepage or custom browser object: http://wwwsearch.sourceforge.net/mechanize/ From johnandsarah at estragon.freeserve.co.uk Fri Jul 29 18:11:37 2005 From: johnandsarah at estragon.freeserve.co.uk (John Perks and Sarah Mount) Date: Fri, 29 Jul 2005 23:11:37 +0100 Subject: Block-structured resource handling via decorators Message-ID: When handling resources in Python, where the scope of the resource is known, there seem to be two schools of thought: (1) Explicit: f = open(fname) try: # ... finally: f.close() (2) Implicit: let the GC handle it. I've come up with a third method that uses decorators to achieve a useful mix between the two. The scope of the resource is clear when reading the code (useful if the resource is only needed in part of a function), while one does not have to write an explicit cleanup. A couple of examples: @withFile(fname, 'w') def do(f): # ... write stuff into file f ... @withLock(aLock): def do(): # ... whatever you needed to do once the lock was acquired, # safe in the knowledge it will be released afterwards ... (The name "do" is arbitrary; this method has the "mostly harmless" side-effect of assigning None to a local variable with the function name.) I find it clear because I come from a C++/C#/Java background, and I found C#'s using-blocks to very useful, compared to the explicit finallys of Java. I know that Python's deterministic finalization sort of achieves the same effect, but I had been led to believe there were complications in the face of exceptions. The implementation is easily extensible: a handler for a new type of resource can be written in as a couple of lines. For the examples above: class withFile(blockScopedResource): init, cleanup = open, 'close' It's so simple I was wondering why I haven't seen it before. Possibly: it's a stupid idea and I just can't see why; everyone knows about it except me; it's counter-intuitive (that's not the way decorators were intended); it's "writing C# in Python" or in some other way unPythonic; I've actually had an idea that is both Original and non-Dumb. If the last is the case, can someone let me know, and I'll put up the code and explain how it all works. On the other hand, if there is something wrong with it, please can someone tell me what it is? Thanks John Perks From pbq51h702 at sneakemail.com Mon Jul 11 21:30:09 2005 From: pbq51h702 at sneakemail.com (Jules Dubois) Date: Mon, 11 Jul 2005 19:30:09 -0600 Subject: tuple.index(item) References: Message-ID: <2357634.ngsvs5RTyu@knode.kde> On Monday 11 July 2005 15:23, David Isaac () wrote: > Why don't tuples support an index method? 19:27:32:~ $ python Python 2.3.5 (#2, Jun 19 2005, 13:28:00) [GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> t = ('a', 'b', 'c') >>> t[1] 'b' >>> > It seems natural enough ... It does to me, too. From donn at drizzle.com Fri Jul 15 11:46:12 2005 From: donn at drizzle.com (Donn Cave) Date: Fri, 15 Jul 2005 15:46:12 -0000 Subject: Reading variables from a forked child (Python C/API) References: <42d7ab64@duster.adelaide.on.net> Message-ID: <1121442371.861520@yasure> Quoth MrEntropy : | I'm having a little trouble getting an idea running. I am writing a C | program which is really a frontend to a Python program. Now, my C | program starts up, does some initialisation like initialisation of it's | variables and Py_Initialize() and then it fork()s. After forking the | child launches the python program with Py_Main() and with the parent I | want to be able to read the variables of the Python program. I have | tried many ways but cannot find a solution to do this. That's because there is no solution. After a fork, the only effect observable in the parent process is the return value of fork, which will have a non-zero value. Subsequent execution in the child process occurs completely independently from the parent, and leaves no trace whatever. So you can't read variables from memory, that were set by the child. Past that, I deleted the rest of your post because it sort of avoids the question of what you're really trying to accomplish and what errors you actually got, but note that just for the sake of avoiding segmentation faults etc., it's a good idea when writing in C to check return values: obj = PyMapping_GetItemString(dict, "foo"); if (obj) { ... } else { ... } Anyway, if you really need a subprocess, you're going to have to communicate with it via some sort of I/O, like UNIX pipes or temporary files or something. You probably don't need to call Python from C, may as well just invoke python (cf. os.spawnv) Donn Cave, donn at drizzle.com From steve at REMOVETHIScyber.com.au Mon Jul 18 09:04:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 18 Jul 2005 23:04:04 +1000 Subject: goto References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: On Mon, 18 Jul 2005 14:06:14 +0200, Mage wrote: > Hayri ERDENER wrote: > >>hi, >>what is the equivalent of C languages' goto statement in python? >>best regards >> >> > You really shouldn't use goto. > > Fortunately you can't. Of course you can :-) You can write your own Python interpreter, in Python, and add a goto to it. You can use while or for loops, which are like goto, only they have all the advantages and none of the disadvantages. The same goes for continue and break, and try...except blocks: they are safe, tame gotos, not wild, dangerous ones that are out of control. You can call functions. Functions are implemented at the machine code level with the assembly language equivalent of a goto. Or you can tell us what problem you want to solve with a goto, and we'll tell you the proper way to solve it. -- Steven. From onurb at xiludom.gro Fri Jul 8 04:33:25 2005 From: onurb at xiludom.gro (bruno modulix) Date: Fri, 08 Jul 2005 10:33:25 +0200 Subject: python nested class In-Reply-To: References: Message-ID: <42ce3a56$0$5428$626a14ce@news.free.fr> Roland Heiber wrote: > Vedanta Barooah wrote: > >> o = mother() >> o.show() >> y=mother.child() >> y.increase(20) >> # this should print 20 >> o.show() >> >> ...... is it possible somehow ??? > > > Hi, > > this should do what you want: > > --- test.py > class mother: > x=0 > def __init__(self): > mother.x=1 > def show(self): > print mother.x > class child: > def increase(self,num): > mother.x=num > > o = mother() > o.show() > y=mother.child() > y.increase(20) > # this should print 20 > o.show() > --- >>pythonw -u "test.py" > 1 > 20 This may *not* be what the op want... #--- test2.py class mother(object): x=0 def __init__(self, name): self.name = name mother.x=1 def show(self): print "in %s: %d" % (self.name, mother.x) class child(object): def increase(self,num): mother.x=num o = mother('o') o.show() y=mother.child() y.increase(20) # this should print 20 o.show() o2 = mother('o2') o2.show() y2=mother.child() y2.increase(10) o2.show() o.show() -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From twic at urchin.earth.li Sun Jul 3 10:46:35 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 3 Jul 2005 15:46:35 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: On Mon, 4 Jul 2005, Steven D'Aprano wrote: > On Sun, 03 Jul 2005 10:56:42 +0100, Tom Anderson wrote: > >> On Sun, 3 Jul 2005, Steven D'Aprano wrote: >> >>> On Sun, 03 Jul 2005 02:22:23 +0200, Fredrik Johansson wrote: >>> >>>> On 7/3/05, Tom Anderson wrote: >>>>> That's one way. I'd do: >>>>> >>>>> root = value ** 0.5 >>>>> >>>>> Does that mean we can expect Guido to drop math.sqrt in py3k? :) >>>> >>>> I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) >>>> gives 3.9999999999999996, and this error could be avoided. >>> >>> py> math.exp(math.log(64)/3.0) >>> 4.0 >>> >>> Success!!! >> >> Eeeeeeenteresting. I have no idea why this works. Given that math.log is >> always going to be approximate for numbers which aren't rational powers of >> e (which, since e is transcendental, is all rational numbers, and >> therefore all python floats, isn't it?), i'd expect to get the same >> roundoff errors here as with exponentiation. Is it just that the errors >> are sufficiently smaller that it looks exact? > > I have no idea :-) > > Unfortunately, floating point maths is a bit of a black art. Try this > simple calculation: > > py> 4.0/3 - 5.0/6 > 0.49999999999999989 > > Should be 0.5 exactly. > > Many numbers which you can write exactly in decimal cannot be > stored exactly in floating point. Even something as simple as one tenth > 0.1 doesn't have an exact representation in binary: > > py> 1.0/10 > 0.10000000000000001 I realise that - but all that argues that your example shouldn't work either! I think there would be a lot less confusion over the alleged inaccuracy of floating point if everyone wrote in hex - indeed, i believe that C99 has hex floating-point literals. C has always been such a forward-thinking language! >>> Note how much simpler this would be if we could guarantee proper >>> infinities and NaNs in the code. We could turn a 23-line block to a >>> one-liner. >> >> YES! This is something that winds me up no end; as far as i can tell, >> there is no clean programmatic way to make an inf or a NaN; in code i >> write which cares about such things, i have to start: >> >> inf = 1e300 ** 1e300 >> nan = inf - inf >> >> Every bloody time. I'm going to be buggered if python ever rolls out some >> sort of bigfloat support. > > It fails for me: > > py> inf = 1e300 ** 1e300 > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Numerical result out of range') Oops. I meant to write "1e300 * 1e300" - multiplication, not exponentiation. My bad. > But this works: > > py> inf = float("inf") > py> inf > inf True. Still, i'd rather not have to rely on string parsing to generate a fairly fundamental arithmetic quantity. >> And then god forbid i should actually want to test if a number is NaN, >> since, bizarrely, (x == nan) is true for every x; > > Well dip me in chocolate and call me a Tim Tam, you're right. That is > bizarre. No, that's not the word I want... that behaviour is broken. > >> instead, i have to >> write: >> >> def isnan(x): >> return (x == 0.0) and (x == 1.0) >> >> The IEEE spec actually says that (x == nan) should be *false* for every x, >> including nan. I'm not sure if this is more or less stupid than what >> python does! > > Well, no, the IEEE standard is correct. NaNs aren't equal to anything, > including themselves, since they aren't numbers. I don't buy that. Just because something isn't a number doesn't mean it can't be equal to something else, does it? I mean, we even say x == None if x is indeed None. Moreover, this freaky rule about NaNs means that this is an exception to the otherwise absolutely inviolate law that x == x. I'd rather have that simple, fundamental logical consistency than some IEEE rocket scientist's practical-value-free idea of mathematical consistency. > Apple Computer had a maths library that implemented a superset of IEEE > arithmetic. It allowed for 254 different NaNs (twice that if you looked > at the sign bit, which you weren't supposed to do). This wasn't a > deliberate feature as such, it merely fell out naturally from the > bit-patterns that represented NaNs, but it was useful since Apple took > advantage of it by specifying certain particular NaNs for certain > failure modes. Eg NaN(1) might represent the square root of a negative > number, but NaN(2) might be INF-INF. > > Furthermore, you could easily query the class of a number (zero, > normalised, denormalised, infinity, NaN), so you would test for a NaN by > doing something like: > > if Kind(x) == NanKind: ... > > or > > if isNaN(x): ... We should add that to python - although it would one one small step for NaN, one giant leap for NanKind. Sorry. >> And while i'm ranting, how come these expressions aren't the same: >> >> 1e300 * 1e300 >> 1e300 ** 2 > > Because this is floating point, not real maths :-) > > I get inf and Overflow respectively. What do you get? The same. They really ought to give the same answer. >> And finally, does Guido know something about arithmetic that i don't, or >> is this expression: >> >> -1.0 ** 0.5 >> >> Evaluated wrongly? > > No, it is evaluated according to the rules of precedence. It is > equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which > fails as expected. Ah. My mistake. I submit that this is also a bug in python's grammar. There's probably some terribly good reason for it, though. tom -- Links are content. From gsakkis at rutgers.edu Sun Jul 10 16:38:22 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jul 2005 13:38:22 -0700 Subject: Read-only class properties Message-ID: <1121027902.719545.103860@g14g2000cwa.googlegroups.com> I'm trying to write a decorator similar to property, with the difference that it applies to the defining class (and its subclasses) instead of its instances. This would provide, among others, a way to define the equivalent of class-level constants: class Foo(object): @classproperty def TheAnswer(cls): return "The Answer according to %s is 42" % cls.__name__ >>> Foo.TheAnswer The Answer according to Foo is 42 >> Foo.TheAnswer = 0 exceptions.AttributeError ... AttributeError: can't set class attribute I read the 'How-To Guide for Descriptors' (http://users.rcn.com/python/download/Descriptor.htm) that describes the equivalent python implementation of property() and classmethod() and I came up with this: def classproperty(function): class Descriptor(object): def __get__(self, obj, objtype): return function(objtype) def __set__(self, obj, value): raise AttributeError, "can't set class attribute" return Descriptor() Accessing Foo.TheAnswer works as expected, however __set__ is apparently not called because no exception is thrown when setting Foo.TheAnswer. What am I missing here ? George From mwm at mired.org Fri Jul 8 00:27:06 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 08 Jul 2005 00:27:06 -0400 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> Message-ID: <86oe9dvs6d.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Thu, 07 Jul 2005 06:47:54 -0400, Chris Smith wrote: >> Oh, come on: what's a Perliodic Table of Operators, between friends? >> http://www.ozonehouse.com/mark/blog/code/PeriodicTable.html > That, and the discussion on operators by Larry Wall, are two of the most > scary things I've ever seen. Is there any possible sequence of bytes that > will not be a valid Perl expression or operator? Yes, but will it get as bad as TECO, where guessing what your name did as a command sequence was a popular past time? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From python at rcn.com Wed Jul 6 10:21:49 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jul 2005 07:21:49 -0700 Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> Message-ID: <1120659709.712391.128150@g44g2000cwa.googlegroups.com> Will McGugan wrote: > Are there any benefits in using a frozenset over a set, other than it > being immutable? No. The underlying implementation is identical with set. The only difference is the addition of a hash method and absence of mutating methods. Everything else is the same. Raymond From rkern at ucsd.edu Fri Jul 29 02:16:29 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 23:16:29 -0700 Subject: why functions in modules need 'global foo' for integer foo but not dictionary foo? In-Reply-To: <1122616696.886226.279510@f14g2000cwb.googlegroups.com> References: <1122616696.886226.279510@f14g2000cwb.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > At top of a module I have an integer like so... > > foo = 4 > > In a function in that module I know I need to do 'global foo' to get at > the value 4. > ... You don't. You need the global declaration to *set* the value of "foo" in the module's namespace. When getting the value of "foo" within the function, if it's not been defined in the function's local namespace, it automatically looks in the global namespace with or without the "global foo" declaration. When assigning a value to the name "foo" within the function, however, without the global declaration, the value will only be assigned to the name "foo" within the local namespace. http://docs.python.org/ref/naming.html > IIRC, for dictionaries you DO NOT have this issue? > > Why this scope problem with integers but not dictionaries? I presume you are trying code like the following: foo = 4 bar = {} def fun1(): foo = 5 def fun2(): bar['baz'] = 4 Since integers are immutable, all that fun1() does is assign 5 to the name "foo" within fun1()'s namespace and doesn't touch the module-level namespace. fun2(), on the other hand, only gets the dictionary from the module-level namespace with the name "bar". Then it modifies that dictionary (since it's mutable). It does not try to assign a new object to the name "bar". I hope that's clear, but I'm pretty tired right now, and it may not be. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From skip at pobox.com Thu Jul 28 23:08:58 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 28 Jul 2005 22:08:58 -0500 Subject: Regex for nested {} In-Reply-To: References: Message-ID: <17129.40394.953475.703935@montanaro.dyndns.org> Chris> I have a problem matching nested levels of {} ... Regular expressions can't count, so you'd be better off sticking with regexes to tokenize the source, then use a real parser to parse the tokens it produces. Skip From bokr at oz.net Sun Jul 24 02:22:13 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 06:22:13 GMT Subject: dictionary that discards old items References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> <1121999372.836621.190950@o13g2000cwo.googlegroups.com> <42e2dfa0.980127588@news.oz.net> Message-ID: <42e33285.1001348202@news.oz.net> On Sat, 23 Jul 2005 20:07:25 -0600, Steven Bethard wrote: >[Raymond Hettinger] >>>class Cache(dict): >>> def __init__(self, n, *args, **kwds): >>> self.n = n >>> self.queue = collections.deque() >>> dict.__init__(self, *args, **kwds) > >[Bengt Richter] >> Minor comment: There is a potential name collision problem for keyword n=something, >> so what is considered best practice to avoid that? __n or such as the n arg? > >I don't know what best practice is, but if you want to guarantee to >avoid the name collision, you can write: > >def __init__(*args, **kwargs): > self = args[0] > self.n = args[1] > self.queue = collections.deque() > dict.__init__(self, *args[2:], **kwargs) > >It's not pretty though. ;) Bullet proofing doesn't have to be ;-) Best solution I've seen yet, thanks. Regards, Bengt Richter From twic at urchin.earth.li Tue Jul 5 19:51:28 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 6 Jul 2005 00:51:28 +0100 Subject: flatten(), [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: On Tue, 5 Jul 2005, Ron Adam wrote: > Tom Anderson wrote: > >> The trouble with these is that they make a lot of temporary lists - >> George's version does it with the recursive calls to flatten, and Ron's >> with the slicing and concatenating. How about a version which never >> makes new lists, only appends the base list? We can use recursion to >> root through the lists ... > > Ok... How about a non-recursive flatten in place? ;-) How about, er, oh, i give up. > def flatten(seq): > i = 0 > while i!=len(seq): > while isinstance(seq[i],list): > seq.__setslice__(i,i+1,seq[i]) > i+=1 > return seq > > seq = [[1,2],[3],[],[4,[5,6]]] > print flatten(seq) > > I think I'll be using the __setslice__ method more often. Um, can't you just do slice assignment? Make that line: seq[i:i+1] = seq[i] > And the test: Stupendous and timely work! > The results on Python 2.3.5: (maybe someone can try it on 2.4) > > recursive flatten: 23.6332723852 > flatten in place-non recursive: 22.1817641628 > recursive-no copies: 30.909762833 > smallest recursive: 35.2678756658 > non-recursive flatten in place without copies: 7.8551944451 GAAAAH! > A 300% improvement!!! > > This shows the value of avoiding copies, recursion, and extra function > calls. Specifically, it shows the value of avoiding extra function calls, since my zerocopy version is slower than the copy-happy single-function versions. Also, there are some differences between the functions which constitute potential hillocks on the playing field - i test flattenability by looking for an __iter__ method, whereas other implementations mostly ask "instanceof list?" (less general, and less in the spirit of duck typing, IMNERHO). I'd argue that my decomposition into functions is this sort of difference, too - a matter of style (good style!), not algorithm. So, levelling those differences, and throwing in my non-recursive zerocopy foolery, here's my take on it ... # ---- # here be a quick reimplementation of timeit to time function objects # no exec for me no siree bob # all you need to know is that timeit(fn) gives you time taken to run fn import sys import time TIMERS = { "win32": time.clock } timer = TIMERS.get(sys.platform, time.time) def timeit(fn, n=None): if (n == None): t = 0.1 n = 1 while (t < 1.0): n = max(int((n * min((1.0 / t), 10))), (n + 1)) t = _timeit(fn, n) else: t = _timeit(fn, n) return t / n def _timeit(fn, n): it = xrange(n) t0 = timer() for i in it: fn() t1 = timer() return float((t1 - t0)) # there is real code now # i've rewritten the functions to use uniform variable names # and to use isiterable def isiterable(obj): return hasattr(obj, "__iter__") def georges_recursive_flatten(seq): return reduce(_accum, seq, []) def _accum(a, item): if isiterable(item): a.extend(georges_recursive_flatten(item)) else: a.append(item) return a def rons_nonrecursive_flatten(seq): a = [] while seq: while isiterable(seq[0]): seq = seq[0] + seq[1:] a.append(seq.pop(0)) return a def toms_recursive_zerocopy_flatten(seq, a=[]): if (isiterable(seq)): for item in seq: toms_recursive_zerocopy_flatten(item, a) else: a.append(seq) return a def toms_iterative_zerocopy_flatten(seq): stack = [None] cur = iter(seq) a = [] while (cur != None): try: item = cur.next() if (isiterable(item)): stack.append(cur) cur = iter(item) else: a.append(item) except StopIteration: cur = stack.pop() return a def devans_smallest_recursive_flatten(seq): if (isiterable(seq)): return sum([devans_smallest_recursive_flatten(item) for item in seq], []) else: return [seq] def rons_nonrecursive_inplace_flatten(seq): i = 0 while (i != len(seq)): while (isiterable(seq[i])): seq[i:(i + 1)] = seq[i] # setslice takes iterators! i = i + 1 return seq flattens = [ georges_recursive_flatten, rons_nonrecursive_flatten, toms_recursive_zerocopy_flatten, toms_iterative_zerocopy_flatten, devans_smallest_recursive_flatten, rons_nonrecursive_inplace_flatten ] seq = [[1,2],[3],[],[4,[5,6]]] def timeflatten(flatten): return timeit(lambda: flatten(seq)) def funcname(fn): return fn.func_name print zip(map(funcname, flattens), map(timeflatten, flattens)) # ---- The output (in python 2.3 on a 1.5 GHz G4 pbook with OS X 10.3) is: [ ('georges_recursive_flatten', 0.00015331475192276888), ('rons_nonrecursive_flatten', 0.00015447115513356376), ('toms_recursive_zerocopy_flatten', 0.00012239551614106925), ('toms_iterative_zerocopy_flatten', 0.00035910996630353429), ('devans_smallest_recursive_flatten', 0.00019606360118084218), ('rons_nonrecursive_inplace_flatten', 5.8524826144294404e-05) ] So, my zerocopy flatten is, after all, faster than George, you and Devan's copy-happy versions, although not by much, my iterative version is much, much slower, and the winner is still your in-place flatten, which beats my not-too-bad 122 microseconds with a scorching 58! I guess setslice is a lot faster than i thought. How are python lists implemented? Presumably not as straightforward arrays, where inserting a bunch of items at the head would mean moving everything else in the list along? We really ought to do this benchmark with a bigger list as input - a few thousand elements, at least. But that would mean writing a function to generate random nested lists, and that would mean specifying parameters for the geometry of its nestedness, and that would mean exploring the dependence of the performance of each flatten on each parameter, and that would mean staying up until one, so i'm not going to do that. tom -- [Philosophy] is kind of like being driven behind the sofa by Dr Who - scary, but still entertaining. -- Itchyfidget From samgurung at gmail.com Tue Jul 19 01:32:43 2005 From: samgurung at gmail.com (linuxfreak) Date: 18 Jul 2005 22:32:43 -0700 Subject: Python IDE Message-ID: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Hi guys, Got going with python...and i must say its a pretty cool language. Been using Xemacs to write me programs. But I want an IDE that would give me auto-completion, online help and the like... Tried SPE and Dr.Pyhton but the former crashes regulary and the latter is quite unweildy and does not have a great many features. I quite like the UML feature found in SPE but the damn thing crashes way too often. What are you guys using and what do you think is the best IDE...or should i stick with Xemacs/emacs??? From bill.mill at gmail.com Wed Jul 20 16:30:10 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 20 Jul 2005 16:30:10 -0400 Subject: is this pythonic? In-Reply-To: <8c7f10c605072006192d8ae378@mail.gmail.com> References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: <797fe3d405072013305d35745d@mail.gmail.com> On 7/20/05, Simon Brunning wrote: > On 7/20/05, Mage wrote: > > Or is there better way? > > > > for (i, url) in [(i,links[i]) for i in range(len(links))]: > > for i, url in enumerate(links): > +2 for creating seeing a need and crafting a reasonable solution, but -1 for not reading the section on builtins to see if it existed already. (As for its pythonicity, I would have recommended isolating it into a function and making it a generator: def my_enumerate(enumerable): i = 0 for elt in enumerable: yield (i, elt) i += 1 for i, url in my_enumerate(links): but it's not too bad as it is. Also, my function is completely untested - it's close to right though.) Peace Bill Mill From devlai at gmail.com Tue Jul 12 11:39:29 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 08:39:29 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121181950.339056.171260@g44g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> Message-ID: <1121182769.717165.36690@f14g2000cwb.googlegroups.com> Oh, I seem to have missed the part saying 'or other word'. Are you doing this for every single word in the file? From jgrahn-nntq at algonet.se Mon Jul 4 11:20:37 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 4 Jul 2005 15:20:37 GMT Subject: unittest: collecting tests from many modules? References: Message-ID: On 12 Jun 2005 10:14:50 GMT, Jorgen Grahn wrote: [regarding module unittest] > What's the best way of creating a test.py which > - aggregates the tests from all the test_*.py modules? > - doesn't require me to enumerate all the test classes in test.py > (forcing each module to define test_foo.theSuite or someting would > be OK though) > - retains the ability to select tests and verbosity (-q, -v) from the > command line? Thanks for all the input. Three weeks later I stumble across this thread again and notice I didn't report what I ended up with. I ended up doing the thing I wanted to avoid in the first place: hardcoding everything. import unittest import test_bibdb import test_citefmt import test_person import test_refsfmt suite = unittest.TestSuite() suite.addTest(test_bibdb.suite()) suite.addTest(test_citefmt.suite()) suite.addTest(test_person.suite()) suite.addTest(test_refsfmt.suite()) if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite) My test modules are, after all, a fairly fixed set, and if I want to run specific tests, or with a specific verbosity, I can execute the individual test modules. BR, /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From http Wed Jul 27 15:02:41 2005 From: http (Paul Rubin) Date: 27 Jul 2005 12:02:41 -0700 Subject: [Beginner] Calling a function by its name in a string References: Message-ID: <7xll3scbse.fsf@ruckus.brouhaha.com> Tito writes: > def printPropertyForEach(collection, propertyName): > for elem in collection: > print eval("elem." + propertyName) > > Is there another approach to do it? Yes, use the getattr function: for elem in collection: print getattr(elem, propertyName) From mwh at python.net Mon Jul 11 09:22:33 2005 From: mwh at python.net (Michael Hudson) Date: Mon, 11 Jul 2005 13:22:33 GMT Subject: pyo contains absolute paths References: Message-ID: David Siroky writes: > Hi! > > When I "compile" my python files with "python -OO ...." into pyo files > then they still contain absolute paths of the source files which is > undesirable for me. How can I deal with that? Are you trying to save space? In 2.4 and later each code object will contain the same copy of the absolute path, so you can't save that much space. There are probably ways to make .pycs that have a path of "", if you really want (see py_compile in the stdlib). Cheers, mwh -- I located the link but haven't bothered to re-read the article, preferring to post nonsense to usenet before checking my facts. -- Ben Wolfson, comp.lang.python From cjw at sympatico.ca Fri Jul 1 08:36:18 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 01 Jul 2005 08:36:18 -0400 Subject: Debugger Confusion In-Reply-To: References: Message-ID: <6Naxe.14033$mK5.871567@news20.bellglobal.com> Adriaan Renting wrote: > I use the debugger that comes with Eric3, but it is only free for Linux/ > OS X, as it needs PyQt. > asside from setting (conditional) breakpoints, one of it's features is > that it can show you a browsable tree of all your variables. something > like this: > class MyClass > | > L-- string 'username' - 'myuser' > | > L-- list > L-[0] - 1 > L-[1] - 'some value' > > You should know by now that I like this IDE ;-) > PythonWin has a similar capability for Windows and Boa-constructor for Linux or Windows. Colin W. > Adriaan Renting | Email: renting at astron.nl > ASTRON | Phone: +31 521 595 217 > P.O. Box 2 | GSM: +31 6 24 25 17 28 > NL-7990 AA Dwingeloo | FAX: +31 521 597 332 > The Netherlands | Web: http://www.astron.nl/~renting/ > >>>>"Robert Brewer" 06/28/05 11:02 PM >>> > > Rex Eastbourne wrote: > >>I'm a little confused about which debugging utilities do what, and >>which I should use for my Python code. I'd like to be able to step >>through my code, insert breakpoints, etc. I haven't been able to do >>this yet (I'm using Emacs on Windows). I have seen references to GDB, >>GUD, PDB, and others. Which ones do I need? > > > 1. At the point you would like to start the debugger, insert the > following 2 lines: > > import pdb > pdb.set_trace() > > 2. Run your script from the command line. > 3. When your script executes the above lines, the pdb debugger will > start up, and give you a prompt. Type 'h' at the prompt (and hit > 'enter'), and you'll be shown a list of pdb commands. 's' to step > through your code, 'c' to continue processing (and stop the debugger, > essentially). The prompt is interactive, so you can inspect program > variables as you like. > > Start with that, and come back if you have any more questions. :) > > > Robert Brewer > System Architect > Amor Ministries > fumanchu at amor.org From en.karpachov at ospaz.ru Tue Jul 26 00:53:33 2005 From: en.karpachov at ospaz.ru (en.karpachov at ospaz.ru) Date: Tue, 26 Jul 2005 08:53:33 +0400 Subject: how to write a line in a text file In-Reply-To: <42E5B0F0.6020206@REMOVEMEcyber.com.au> References: <42E5B0F0.6020206@REMOVEMEcyber.com.au> Message-ID: <20050726045333.GA863@jk.dev> Tue, Jul 26, 2005 at 01:41:36PM +1000, Steven D'Aprano ?????: > Long ago, when dinosaurs roamed the Earth, (a.k.a. > "before OS X on the Macintosh") Apple suggested a bit > of Pascal code for safely updating a file: > > http://developer.apple.com/documentation/mac/Files/Files-25.html#MARKER-9-163 That snippet doesn't write data to the existing file. It writes data into the new tempfile and then renames it, as well as the FileInput object does. > Most of the code is Macintosh-specific, but the > principle is not: when over-writing a file, make sure > that the user can recover from any error up to and > including power failure without losing the data on disk. Well, it's what (R)DBMS are for, but plain files are not. -- jk From brian9511 at dslextreme.com Thu Jul 21 17:20:22 2005 From: brian9511 at dslextreme.com (muldoon) Date: 21 Jul 2005 14:20:22 -0700 Subject: Difference between " and ' References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: <1121980822.209906.142810@g47g2000cwa.googlegroups.com> b83503104 at yahoo.com wrote: > Hi, > > Can someone tell me the difference between single quote and double > quote? > > Thanks And please settle the dispute between "xxx". And "xxx". There was a fellow at Oxford who decided these things but I hear he went mad. From harold.fellermann at upf.edu Wed Jul 6 15:00:30 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 6 Jul 2005 21:00:30 +0200 Subject: inheriting file object In-Reply-To: References: <42CC13F2.4050808@bellsouth.net> Message-ID: > I don't know if I should be inheriting file or just using a file > object. > How would I determine which one would be more appropriate? Inheritance is often refered to as an IS relation, whereas using an attribute is a HAS relation. If you inherit from file, all operations for files should be valif for your class also. Usually the file-operations would be directly inherited and not overwritten. However, if you don't want to expose all file functionalities, a HAS relation is more appropriate. if you plan to use your class as a file handle, e.g. for formatting output in a special way, I woould prefer to make the file an attribute: class myFile : def __init__(self,fname,mode="r") : self.file = file(fname,mode) def write_formatted(self,string) : # format string self.file.write() If you would tell as your use case, it would be easier to give you an advice. - harold - -- Yesterday is but today's memory and Tomorrow is today's dream. -- From dalke at dalkescientific.com Fri Jul 29 02:24:47 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 29 Jul 2005 06:24:47 GMT Subject: can list comprehensions replace map? References: Message-ID: Christopher Subich wrote: > My naive solution: ... > for i in ilist: > try: > g = i.next() > count += 1 > except StopIteration: # End of iter > g = None ... What I didn't like about this was the extra overhead of all the StopIteration exceptions. Eg, zipfill("a", range(1000)) will raise 1000 exceptions (999 for "a" and 1 for the end of the range). But without doing timing tests I'm not sure which approach is fastest, and it may depend on the data set. Since this is code best not widely used, I don't think it's something anyone should look into either. :) Andrew dalke at dalkescientific.com From pinard at iro.umontreal.ca Wed Jul 6 09:58:20 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 6 Jul 2005 09:58:20 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <20050706135820.GA28691@alcyon.progiciels-bpi.ca> [Tom Anderson] > > del -> delete > How about just getting rid of del? [...] i'm not convinced that > deleting variables is something we really need to be able to do While surely not in every program, I still use `del' often. Compare: x = None del x when the goal is to cut the reference being held in x. Both statements do it, yet the intent is expressed more legibly by the second. > (most other languages manage without it). Hardly an excuse against some good ideas Python has on its own! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From gene.tani at gmail.com Sun Jul 24 09:35:20 2005 From: gene.tani at gmail.com (gene tani) Date: 24 Jul 2005 06:35:20 -0700 Subject: FAQ? In-Reply-To: References: Message-ID: <1122212120.494718.221890@z14g2000cwz.googlegroups.com> Here's my trove of FAQ/Gotcha lists http://www.ferg.org/projects/python_gotchas.html http://zephyrfalcon.org/labs/python_pitfalls.html http://zephyrfalcon.org/labs/beginners_mistakes.html http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html http://www.norvig.com/python-iaq.html http://www.faqts.com/knowledge_base/index.phtml/fid/245 http://amk.ca/python/writing/warts From supercomputer at gmail.com Tue Jul 12 09:21:11 2005 From: supercomputer at gmail.com (supercomputer at gmail.com) Date: 12 Jul 2005 06:21:11 -0700 Subject: Parsing Data, Storing into an array, Infinite Backslashes References: <1121114842.623294.156790@g44g2000cwa.googlegroups.com> Message-ID: <1121174471.662146.216900@z14g2000cwz.googlegroups.com> Thanks for all the help, I'm not sure what approach I'm going to try but I think I'll try all of your suggestions and see which one fits best. The variable "i" held the following array: [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed', 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0', 'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0', 'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory', '1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'], ['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'], ['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary', '0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2', 'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2', 'Slot', 'DIMM2/J13'], > Where is the fetch object defined? And what is it supposed to be > returning? Fetch is declared a few lines up in the program with this fetch=iter(ed) it just goes through the array and returns the next part of it. >> query[count]=qval+i[2]+"="+i[3]+", " >Impossible to know what this does since we don't know what i is. Hint: it >is easier to read and parse expressions by adding a small amount of >whitespace: I am trying to assign each new memory slot to a new part in the array. So when memory is either 0,1,2,3 it will assign it to query[0], query[1], query[2], query[3] From sklass at pointcircle.com Wed Jul 13 21:26:03 2005 From: sklass at pointcircle.com (rh0dium) Date: 13 Jul 2005 18:26:03 -0700 Subject: Help - Classes and attributes Message-ID: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> Hi all, I believe I am having a fundamental problem with my class and I can't seem to figure out what I am doing wrong. Basically I want a class which can do several specific ldap queries. So in my code I would have multiple searches. But I can't figure out how to do it without it barfing.. The error is straightforward .. LDAP Version 2.0.8 Traceback (most recent call last): File "./ldap-nsc.py", line 62, in ? l.search() File "./ldap-nsc.py", line 40, in search ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, retrieveAttrs) AttributeError: NSCLdap instance has no attribute 'search_s' The code is also I believe straight forward.. import ldap class NSCLdap: def __init__(self,server="sc-ldap.nsc.com"): who=""; cred="" self.server=server try: print "LDAP Version", ldap.__version__ l=ldap.open(server) l.simple_bind_s(who, cred) l.protocol_version=ldap.VERSION3 except ldap.LDAPError, error_message: print "Couldn't Connect to %s %s " % (server,error_message) def search(self, baseDN="o=nsc.com", retrieveAttrs=None,searchAttrs="cn=*klass*" ): searchScope = ldap.SCOPE_SUBTREE try: ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, retrieveAttrs) result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: ## here you don't have to append to a list ## you could do whatever you want with the individual entry ## The appending to list is just for illustration. if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) print result_set except ldap.LDAPError, error_message: print "Errors on Search %s " % error_message def setBaseDN(self, baseDN="o=nsc.com"): return baseDN if __name__ == '__main__': l = NSCLdap() l.search() I would love some pointers - clearly my code thinks that search_s is an attribute of my class but it's not.. TIA From steve at REMOVETHIScyber.com.au Mon Jul 18 18:58:46 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 19 Jul 2005 08:58:46 +1000 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: On Mon, 18 Jul 2005 16:37:57 -0400, rbt wrote: > Shouldn't that be "to the horror of all your goto-snob friends." > > IMO, most of the people who deride goto do so because they heard or read > where someone else did. Or because they actually programmed in languages that used goto for flow control. Some of us have even programmed in versions of BASIC that didn't have FOR or WHILE loops, you had to roll your own out of gotos. How about you? How many times have you had to maintain and debug spaghetti code sprinkled with gotos all over the place? > Many of the world's most profitable software companies (MS for example) > have thousands of goto statements in their code... oh the horror of it > all. Why aren't these enlightened-by-the-gods know-it-alls as profitable > as these obviously ignorant companies? You know, I agree with you here. Why, just the other day I was discussing computer systems with my Aunt Tilly, who wanted to buy a computer so she could send emails to her friends and relatives. I suggested she buy a Mac, and she said "Well, I thought about buying a Mac, but I'm afraid I can't possibly use any software that wasn't written using goto. So I'm going to buy a Windows machine. Do you recommend any anti-virus and anti-spyware software that's easy to use?" -- Steven. From fuzzyman at gmail.com Wed Jul 6 08:59:13 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jul 2005 05:59:13 -0700 Subject: Python exception hook simple example needed In-Reply-To: References: Message-ID: <1120654753.122331.109950@g43g2000cwa.googlegroups.com> Wax has a brilliant prebuilt dialog/handler. It's a wrapper over wxPython - so you still use wxPython objects, it's jsut all a lot easier. http://zephyrfalcon.org/labs Best Regards, Fuzzy http://www.voidspace.org.uk/python From renmybiru at libero.it Mon Jul 4 05:38:28 2005 From: renmybiru at libero.it (Vittorio) Date: Mon, 4 Jul 2005 09:38:28 +0000 (UTC) Subject: email link and foreign accent References: <6f-dnTSTQazBSlvfRVn-jQ@powergate.ca> Message-ID: Vittorio wrote in news:Xns96896D46D9DCCSoToSpeak@ 195.110.128.18: > Thanks Peter for replying. > This is an example of the output of repr(x) as you requested: > > 'carr\xe0 at pluto.it' > > Results: > link opened from IE6->Outlook: it works > link opened from IE6->Pocomail: it works > link opened from Firefox->Outlook: characters with accent fail > link opened from Firefox->Pocomail: characters with accent fail adjournment: link opened from Firefox->Thunderbird:it works link opened from IE6->Thunderbird:it works From cam.ac.uk at mh391.invalid Sun Jul 24 04:41:28 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jul 2005 09:41:28 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> Message-ID: Peter Hansen wrote: > Point taken. What about ditching the "file" part, since it is redundant > and obvious that a file is in fact what is being accessed. Thus: > .read_bytes(), .read_text(), .write_lines() etc. +1. Although I've always been somewhat -0 on these methods to start with. -- Michael Hoffman From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 08:54:07 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 14:54:07 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e38876$0$6807$636a15ce@news.free.fr> Steven D'Aprano a ?crit : > On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote: > > (snip) > > Are you telling me that the ONLY thing you use dictobj objects for is to > print them? > > I don't think so. I do know how to print an object, amazingly. > > Perhaps you would like to explain how you use the rest of the > functionality of the dictobj, instead of taking my words out of context > and giving an inane answer. > > Why jump through all those hoops to get attributes when Python already > provides indexing and attribute grabbing machinery that work well? Why do > you bother to subclass dict, only to mangle the dict __getitem__ method so > that you can no longer retrieve items from the dict? > The idea of the OP is not to use the dictobj as a full fledged dict, just to wrap the obj in something that is dict-like enough to be used for "%(attname)s" formatting. I also assume that he doesn't want to manually alter the code of each and every class to achieve this !-) So we can certainly agree that subclassing dict here is overkill and a bit misleading, but there are probably better ways to express this feeling. Of course, it would have been simpler if the OP had tell us from the start what was it's use case, but what... One could of course use metaclass tricks and the like to customize the objects __str__ or __repr__ (as in David Mertz's gnosis.magic package), but that would be overkill too IMHO. The plain old Decorator[1] pattern is probably enough in this case, since it's quite easy to implement a generic Decorator in Python. Another solution could be to dynamically modify the to-be-wrapped object's class to add a __getitem__ method. From devnull at joreybump.com Wed Jul 13 00:16:10 2005 From: devnull at joreybump.com (Jorey Bump) Date: Wed, 13 Jul 2005 04:16:10 GMT Subject: Defending Python References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> <42d17b1f$0$19917$636a15ce@news.free.fr> Message-ID: >> Jorey Bump wrote: >> >>> Bruno Desthuilliers wrote: >>> >>>> it's. ^^^^ >>> +1 for this becoming the official name of Python 3000. ;) Monty Python's Flying Circus used to begin with "It's..." I had read at one time that "It's" was one of the original names proposed for the troupe/show, although I can't seem to find verification. Of course, based on some of the concerns voiced about Python 3000, maybe "It's Only A Flesh Wound" would be better. :) This was simply a nonsequitur: >>> And now for something completely different... >>> >>> The larch! IT'S A TREE From could.net at gmail.com Thu Jul 14 22:43:35 2005 From: could.net at gmail.com (could ildg) Date: Fri, 15 Jul 2005 10:43:35 +0800 Subject: How can I import a py script by its absolute path name? In-Reply-To: <4222a849050714074264811bbd@mail.gmail.com> References: <311b5ce105071404412d4bf318@mail.gmail.com> <4222a849050714074264811bbd@mail.gmail.com> Message-ID: <311b5ce105071419436e6f012e@mail.gmail.com> for f in os.listdir(os.path.abspath(libdir)): module_name = f.strip('.py') __import__(module_name, globals(), locals(), []) On 7/14/05, Jesse Noller wrote: > A question in a similiar vein: > > I have appended 2 different directories to my path (via > sys.path.append) now - without knowing the names of the files in those > directories, I want to force an import of the libraries ala: > > for f in os.listdir(os.path.abspath(libdir)): > module_name = f.strip('.py') > import module_name > > Obviously, this throws: > > ImportError: No module named module_name > > Is there some way to do this? > > thanks > -jesse > From twic at urchin.earth.li Sat Jul 16 20:16:43 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 17 Jul 2005 01:16:43 +0100 Subject: Python Programming Contest In-Reply-To: <1121527459.6b60aac30aa1215f6bad5d994664520f@teranews> References: <42D780EF.6020809@sweetapp.com> <1121527459.6b60aac30aa1215f6bad5d994664520f@teranews> Message-ID: On Sat, 16 Jul 2005, George Sakkis wrote: > "Tom Anderson" wrote: > >> On Sat, 16 Jul 2005, Joseph Garvin wrote: >> >>> Someone correct me if I'm wrong -- but isn't this the Shortest Path >>> problem? >> >> Dang! I was just about to point that out. >> >> [snipped] >> >> But yes, this is basically about who can write the fastest >> implementation of Dijkstra's algorithm. I've got one somewhere - i have >> a half-finished journey planner for the London Underground! - so maybe >> i should enter ... >> >> Hmm. Actually, Dijkstra's algorithm isn't always the fastest way to >> find the shortest path. The thing is, it's fully general, so it works >> on absolutely any graph; if the graph you're traversing has particular >> properties, you might be able to leverage those to find a solution >> faster. [snipped] > > Yes, that's right. Moreover, Dijkstra's computes the shortest path from > a given start to *all* nodes in the network, which is usually an > overkill if all you want is the shortest path to one (or a few) node(s). Actually, it only computes shortest paths from the source to every node which is closer than the destination. Unless you keep computing after you've found your route! >> I can't immediately see any properties of this network that could be >> exploited, but that doesn't mean there aren't any. > > Hints: > > - You have to take exactly one decision (flight or stop) every single > day until you reach the destination; no more, no less. > > - There is no time machine; days pass in one direction only, one at a time. Ah, but in my approach, those rules are encoded in the structure of the graph; i don't think they leave you with a graph with any obvious exploitable properties. To expand on that, rather than making a graph in which vertices are cities and edges are services, which then leaves me with the headache of finding a route in the face of shifting availability and weight of edges, i make each vertex a spacetime, rather than a purely spatial, location - 'Frankfurt on friday', for example, would be a different vertex to 'Frankfurt on monday'. Flights are then simply edges which link the origin city on the day they depart to the destination city on the next day; their weight is the cost of the flight. City X on day N is always linked to City X on day N+1 by an edge representing the option of staying in a hostel. Vertices corresponding to the destination city on any day are all linked to a special goal vertex by length-0 edges, so if you can make it to the destination at any time, you win. You could put nonzero weights on those edges if you liked, to capture your preferences about when you wanted to arrive (if you were willing to pay 15 pounds more to get there on tuesday, you'd set the weight of links from tuesday to the goal to -15, for example). You'd probably also want a special start node linked to your home airport on every day by length-0 edges. I can't see any properties of the resulting graph that are particularly interesting. The fact that flight prices are not correlated with physical distance makes an A*-like approach impossible. Actually, there is one thing - the number of edges you need to traverse to get from any vertex to any other (apart from the start and goal vertices) is always the same, regardless of the route taken, since each edge corresponds to one day's actions, and any given pair of vertices are a certain number of days apart. Ah, is that what you were hinting at? I'm still not sure how you could use this, though! tom -- I do not think we will have to wait for very long. From noreply at python.org Thu Jul 14 07:08:08 2005 From: noreply at python.org (Mail Administrator) Date: Thu, 14 Jul 2005 14:08:08 +0300 Subject: Mail System Error - Returned Mail Message-ID: <20050714110843.EED121E4003@bag.python.org> The original message was received at Thu, 14 Jul 2005 14:08:08 +0300 from python.org [157.76.199.159] ----- The following addresses had permanent fatal errors ----- From luis_XX at XXiname.com Sat Jul 23 15:24:08 2005 From: luis_XX at XXiname.com (Luis P. Mendes) Date: Sat, 23 Jul 2005 20:24:08 +0100 Subject: PostgreSQL & Python vs PHP References: <3kfaucFu3tlfU1@individual.net> <1122139628.703635.48610@g14g2000cwa.googlegroups.com> <1122141147.604862.54030@g49g2000cwa.googlegroups.com> Message-ID: <3kffubFtnab6U1@individual.net> gene tani wrote: > ok, to make this less open-ended, you should mention what O/S and web > server you have in mind, whether the web and DB servers will be under > your admin (big diff betw python and PHP, as far as finding shared > server accounts at web hosts), what kinds of queries, concurrent > read/write volumes, transactions, dirtiness, etc. etc Also if you > build your questions to this newsgroup on past threads you've read, you > will get absolute superb information, I guarantee it. I'll be using Apache, under Linux. The db server will be under my admin. A dozen clients acessing the db. For the first project: Three or four of them will be using queries mainly from three tables with: table 1: 3500000 lines x 20 cols table 2: 3500000 lines x 6 cols table 3: 42000000 lines x 5 cols as an estimate. Other clients will be very light users but need easy web interface for mouse clicks only. Thank you for your support and excuse me for my ignorance, but I'm starting the project and would like to start it in the right direction. Luis From rtw at freenet.co.uk Sun Jul 31 07:16:38 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 31 Jul 2005 06:16:38 -0500 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: deelan wrote in news:ve1He.29121$TR5.13328 at news.edisontel.com in comp.lang.python: > Paolino wrote: > (...) >> What I'm needing as a global (in globals() or at the module level or >> in the module namespace) is 'translate'.The rest of bindings >> (all,badcars and table) is something which is 'polluting' the module >> namespace. > > try this: > > ## yourmodule.py ## > > def _setup_table(): > import string > all=string.maketrans('','') > badcars=all.translate(all,string.letters+string.digits) > return string.maketrans(badcars,'_'*len(badcars)) > > TABLE = _setup_table() > > # optional, get rid of _setup_table symbol > del _setup_table() > > def translate(text): > return text.translate(TABLE) > After 3 or 4 iterations I refactored you code to this: def translate( text ) import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) TABLE = string.maketrans(badcars,'_'*len(badcars)) global translate def translate( text ): return text.translate(TABLE) print "First Call! ", # -- Just for demonstration -- return translate( text ) print translate("If I was ...") print translate("If I was ...") Rob. -- http://www.victim-prime.dsl.pipex.com/ From fuzzyman at gmail.com Tue Jul 12 10:41:18 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 12 Jul 2005 07:41:18 -0700 Subject: breaking out of nested loop In-Reply-To: References: Message-ID: <1121179278.560899.232480@z14g2000cwz.googlegroups.com> You either need to set a marker flag with multiple breaks - *or* (probably more pythonic) wrap it in a try..except and raise an exception. Define your own exception class and just trap for that if you want to avoid catching other exceptions. There is no single command to break out of multiple loops. Regards, Fuzzy http://www.voidspace.org.uk/python From mwm at mired.org Thu Jul 21 19:43:24 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 21 Jul 2005 19:43:24 -0400 Subject: Web-Forms References: Message-ID: <86ek9rrahv.fsf@bhuda.mired.org> Mathias Waack writes: > Hi, > > I need to access some information from a web site which are only accessible > through a form. Thus for each bucket of data you have to fill out the form, > submit it and wait for an answer. Very easy - if you don't have to check > some hundred times. Of course this site requires cookies, it is not > directly accessible by URL and so on. All that nice stuff used to make a > web site more professional;) > > But now the question: how can this be solved by using Python? urllib2 (in the standard library) for reading the data from the website. BeautifulSoup for extracting data from the pages. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From thanos at sians.org Mon Jul 25 14:58:57 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Mon, 25 Jul 2005 21:58:57 +0300 Subject: psp & php integration In-Reply-To: <20050725185152.1B9D81E4007@bag.python.org> References: <20050725185152.1B9D81E4007@bag.python.org> Message-ID: <20050725185857.GA15667@zermelo.sians.org> On Mon, Jul 25, 2005 at 07:53:19PM +0100, Jon Hewer wrote: > Hello, > > I am upgrading a PHP based site and want to use Python (using mod_python and > psp file) to achieve what is required. However, I do not want to recode the > navigation part of the site which is currently coded using PHP. Somehow I > need to merge the outputs of the PHP file and my PSP file to create the HTML > output which is sent to the browser. Can this be done inside my PSP file? > If not, is there any other way in Python (or PHP) to achieve this? I have never used PSP, (I prefer old-time cgi's) but one *BAD* solution is that you can open a local connection to your server asking for the .php file through the psp file which should do the extra functionality, or vice versa. I _REALLY_ don't like that though... -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From gustavo at niemeyer.net Thu Jul 7 16:47:33 2005 From: gustavo at niemeyer.net (Gustavo Niemeyer) Date: Thu, 7 Jul 2005 17:47:33 -0300 Subject: ANN: python-constraint 1.0 In-Reply-To: <20050707191912.GE17474@logilab.fr> References: <20050707064010.GA7979@burma.localdomain> <20050707191912.GE17474@logilab.fr> Message-ID: <20050707204733.GA6533@burma.localdomain> Hello Alexandre, > People interested in CSP and python may also want to check Logilab's > constraint module which has been available from some time at: > > http://www.logilab.org/projects/constraint/ Indeed! And please send us some notes comparing both. :-) The AIMA book inspired me to write that module. IIRC, there's also some kind of constraint code in Python by one of the book authors (Peter Norvig). For those who are interested, chapter 5, which talks about CSPs, may be found in the web site. > Gustavo, maybe we should coordinate and merge our efforts? Probably. I confess that even though I'm using CSP logic on other real world projects, I wrote that module completely for fun, and was not really caring if I was reinventing the wheel or not. > Alexandre Fayolle LOGILAB, Paris (France). I'm currently in Paris, btw. -- Gustavo Niemeyer http://niemeyer.net From cjw at sympatico.ca Sat Jul 2 09:51:04 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 02 Jul 2005 09:51:04 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> Message-ID: <9Zwxe.7122$Ai.782833@news20.bellglobal.com> Steven Bethard wrote: > Fredrik Johansson wrote: > >> On 6/27/05, Reinhold Birkenfeld >> wrote: >> >>> Do you have any other good and valued Python modules that you would >>> think are >>> bug-free, mature (that includes a long release distance) and useful >>> enough to >>> be granted a place in the stdlib? >> >> >> First of all, numeric/numarray, obviously! > > > There has been recent discussion about this. Check the python-dev list > archives I think. It's unlikely that all of numeric/numarray could go > into the Python stdlib because there still is disagreement between the > two camps as to the module architecture. However, there does seem to be > some agreement at the level of the basic array object, so it may be > possible that at least the array object itself might join the stdlib in > the not too distant future. I suspect there's more detailed discussion > of this in the numeric/numarray lists. There was a flurry of exchanges about three months ago but it soon died. One thing which needs to be sorted out is the silent truncation of complex values: http://sourceforge.net/tracker/index.php?func=detail&aid=1216688&group_id=1369&atid=450446 Colin W. > > STeVe From amit at digitalpeers.com Mon Jul 4 02:23:31 2005 From: amit at digitalpeers.com (amit) Date: Mon, 04 Jul 2005 08:23:31 +0200 Subject: Embedding performance. Message-ID: <42C8D5E3.70106@digitalpeers.com> Hello, Is there any kind of performance differences to the different ways of embedding python? PyEval_EvalCode() PyRun_SimpleFile() PyObject_CallObject() Thanks Amit From mwh at python.net Thu Jul 21 11:50:49 2005 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Jul 2005 15:50:49 GMT Subject: goto References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: skip at pobox.com writes: > >>> what is the equivalent of C languages' goto statement in python? > > >> You really shouldn't use goto. > >> Fortunately you can't. > > Steven> Of course you can :-) > > Steven> You can write your own Python interpreter, in Python, and add a > Steven> goto to it. > > Maybe easier would be to write a Python assembler (there's probably already > one out there) and just write to Python's virtual machine... The blockstack gets in the way. Really, I think Richie's goto module is about as "good" as it can get without vm surgery (apart from the performance, I'd guess). Cheers, mwh -- Reading Slashdot can [...] often be worse than useless, especially to young and budding programmers: it can give you exactly the wrong idea about the technical issues it raises. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#reasons From peter at engcorp.com Tue Jul 26 11:06:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Jul 2005 11:06:51 -0400 Subject: Packages and modules In-Reply-To: References: Message-ID: Dan Richter wrote: > I'm trying to create a package+module structure, specifically a "test" > package with all the unit tests. I'd like to have a package (directory) > "test" that has various test modules, and I'd also like "test" itself to > be a module that runs all the tests. Is this not possible? > > I created a directory called "test" with an __init__.py file that > defines a variable __all__. That works, but no executable code in > __init__.py is executed, even though "import test" seems to succeed. I > have confirmed that it's not a naming conflict (i.e., there's not some > other Python module also named "test"). Are you certain? The way to check is with "test.__file__" after importing test. There _is_ a standard library package called test, and when I import test here and do this test I get: >>> test.__file__ 'c:\\python24\\lib\\test\\__init__.pyc' -Peter From peterbe at gmail.com Tue Jul 19 07:35:02 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 19 Jul 2005 04:35:02 -0700 Subject: Finding # prefixing numbers Message-ID: <1121772902.193765.258700@g49g2000cwa.googlegroups.com> In a text that contains references to numbers like this: #583 I want to find them with a regular expression but I'm having problems with the hash. Hopefully this code explains where I'm stuck: >>> import re >>> re.compile(r'\b(\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') ['123', '234', '456'] >>> re.compile(r'\b(X\d\d\d)\b').findall('X123 x (X234) or:X456 X6789') ['X123', 'X234', 'X456'] >>> re.compile(r'\b(#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') [] >>> re.compile(r'\b(\#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') [] As you can guess, I'm trying to find a hash followed by 3 digits word bounded. As in the example above, it wouldn't have been a problem if the prefix was an 'X' but that's not the case here. From sp1d3rx at gmail.com Tue Jul 19 18:52:14 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 19 Jul 2005 15:52:14 -0700 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? References: Message-ID: <1121813534.868644.30590@g47g2000cwa.googlegroups.com> Chris, How would a wireless router show a signal to noise ratio? Especially if it's providing the signal? From fuzzyman at gmail.com Thu Jul 21 03:37:21 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Jul 2005 00:37:21 -0700 Subject: How to limit the uploading file size in python? In-Reply-To: References: <20050720074406.10046.qmail@web8402.mail.in.yahoo.com> Message-ID: <1121931440.953486.107410@f14g2000cwb.googlegroups.com> Hello Prabahar, It entirely depends on the mechanism you are using to receive the file (there is no generic solution). Is it within a CGI ? The normal way would be to check the file sized and discard if it's too big. You'll have to do it within your code - but it's probably a one line check ! Best Regards, Fuzzy http://www.voidspace.org.uk/python From steven.bethard at gmail.com Mon Jul 4 14:16:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 04 Jul 2005 12:16:47 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: Erik Max Francis wrote: > Ron Adam wrote: > >> In this case sum and product fulfill 90% (estimate of course) of >> reduces use cases. It may actually be as high as 99% for all I know. >> Or it may be less. Anyone care to try and put a real measurement on it? > > Well, reduce covers 100% of them, and it's one function, and it's > already there. And it's almost two times slower: $ python -m timeit -s "x = xrange(1000)" "sum(x)" 10000 loops, best of 3: 92.5 usec per loop $ python -m timeit -s "from operator import add; x = xrange(1000)" "reduce(add, x)" 10000 loops, best of 3: 157 usec per loop And that's only if I have the sense to import from operator: $ python -m timeit -s "x = xrange(1000); add = lambda x, y: x + y" "reduce(add, x)" 1000 loops, best of 3: 587 usec per loop Note that the simple for-loop beats the case where you define your own function because it doesn't have the repeated overhead of function calls (which are expensive in Python): $ python -m timeit -s "sum = 0; x = xrange(1000)" "for i in x: sum += i" 10000 loops, best of 3: 291 usec per loop What would really help here is if you could identify the cases where you think reduce is really a gain. A lot of them are actually not good practice in Python because of the function-call overhead. However, I'm willing to be convinced otherwise with a few good examples. STeVe From sybrenUSE at YOURthirdtower.com.imagination Sun Jul 17 18:15:49 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 18 Jul 2005 00:15:49 +0200 Subject: What is your favorite Python web framework? References: Message-ID: Admin enlightened us with: > But I'd like to know your opinion on what you think is best. The > Python framework I'll use will be to build an e-commerce > application looking like Amazon.com I'm greatly in favour of Cheetah. Also see http://www.unrealtower.org/mycheetah. I need to put up way more documentation & examples, but the basics are there. Let me know what you think! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From stefan.rank at ofai.at Sat Jul 30 05:08:28 2005 From: stefan.rank at ofai.at (Stefan Rank) Date: Sat, 30 Jul 2005 11:08:28 +0200 Subject: A replacement for lambda In-Reply-To: <42EB3854.5000006@tiscali.it> References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> Message-ID: <42EB438C.20209@ofai.at> on 30.07.2005 10:20 Paolino said the following: > why (x**2 with(x))<(x**3 with(x)) is not taken in consideration? > > If 'with' must be there (and substitue 'lambda:') then at least the > syntax is clear.IMO Ruby syntax is also clear. > I am sorry if this has already been proposed (I am sure it has). Why not substitue python-lambdas with degenerated generator expressions:: (lambda x: func(x)) == (func(x) for x) i.e. a one time callable generator expression (missing the `in` part). The arguments get passed into the generator, I am sure that can be combined with the PEP about passing args and Exceptions into a generator. From gsakkis at rutgers.edu Fri Jul 1 02:06:56 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 23:06:56 -0700 Subject: Splitting string into dictionary References: <1120195999.101197.135740@z14g2000cwz.googlegroups.com> Message-ID: <1120198016.500241.184700@g44g2000cwa.googlegroups.com> "David Pratt" > Thanks George! You guys are great! I am always learning. Python is > awesome!! Yeap, that was the reaction of many/most of us when we stumbled upon python. Welcome aboard ! George From jepler at unpythonic.net Tue Jul 26 21:22:30 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 26 Jul 2005 20:22:30 -0500 Subject: Tkinter - Resizing a canvas with a window In-Reply-To: References: Message-ID: <20050727012227.GA4233@unpythonic.net> You should just use 'pack' properly. Namely, the fill= and expand= parameters. In this case, you want to pack(fill=BOTH, expand=YES). For the button, you may want to use pack(anchor=E) or anchor=W to make it stick to one side of the window. The additional parameters for the button (both creation and packing) give a geometry that is closer to the standard buttons in Windows 95 / Windows 2000. Use those or not, as you see fit. Here's the new program: from Tkinter import * class testApp2: def __init__( self, master ): self.ma = master self.f = Frame( self.ma ) self.f.pack(fill=BOTH, expand=YES) self.cv = Canvas(self.f, width=25, height=25, bg='red') self.cv.pack(fill=BOTH, expand=YES) self.b1 = Button( self.f, text='Hello', height=1, width=10, padx=0, pady=1) self.b1.pack(side=BOTTOM, anchor=E, padx=4, pady=4) root = Tk() app = testApp2(root) root.mainloop() Jeff PS thanks for including a full, runnable program in your post! -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From pythonmailing at web.de Sun Jul 24 15:18:21 2005 From: pythonmailing at web.de (Marek Kubica) Date: Sun, 24 Jul 2005 21:18:21 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> Message-ID: <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> Hi! Am Sun, 24 Jul 2005 19:47:30 +0200 schrieb Torsten Bronger: > Is PyGTK more Pythonic by the way? I had a look at wxPython > yesterday and didn't like that it has been brought into the Python > world nearly unchanged. You can see its non-Python origin clearly. > How does PyGTK feel in this respect? Well.. I'd say, PyGTK is still quite like GTK in C. There are some nice features like iterators in treeviews but some things are IMHO unneccesary difficult and much more elegant in wx. I have started GUIs in Python with wx, but after a short time I was annoyed how many things were buggy. I don't know why, but I fell from one bug to the other while programming one application. Then, I tried GTK on Windows, because I know GTK+ 2 a bit liked it. First I was very impressed, the documentation (Tutorial + Reference + FAQ) was after wxPy 2.4.x _very_ impressive and things which were difficult in wxPy were easy in PyGTK. But after some time I realized some other things were complicated in PyGTK. You see, there is no non-plus-ultra GUI library and my best advice is to test it yourself to see which one fits your needs best. I hope a Qt4 compatible PyQt will be released soon, I'm curious about the new Qt4, which is free for GPL-only software on Windows. greets, Marek From peter at engcorp.com Fri Jul 29 08:21:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 08:21:24 -0400 Subject: os._exit vs. sys.exit In-Reply-To: <48GdnfrcP_Z2g3ffRVn-hg@comcast.com> References: <7a2dnSer5eC2BnTfRVn-sQ@comcast.com> <48GdnfrcP_Z2g3ffRVn-hg@comcast.com> Message-ID: Bryan wrote: > Thanks for the clarifications. One more question, can I catch this > exception in my main thread and then do another sys.exit() to kill the whole > process? Not as such. Exceptions can be caught only in the thread in which they are raised. There are tricky techniques to change this, but they would have to rely on things which are themselves sufficient for what you are trying to do. > Apparently sys.exit() allows the program to clean up resources and exit > gracefully, while os._exit() is rather abrupt. What does the main thread do while the other thread is running? If it's just waiting for it and other threads to finish/fail, then you need to have some kind of loop that waits for all other threads to not respond True to .isAlive(), and/or you need to add a threading.Event or something like it which the main thread can wait on or poll to see whether a thread has caught an exception, *and* you need to make all those other threads catch their own exceptions at the top levels of their run() method, and to set that Event object if SystemExit is caught. Or related techniques. If that's not enough ideas for you to figure something out, please provide more detail and we can come up with something more specific and appropriate. For example, do you want to exit the app only if a thread raises SystemExit, or would other exceptions result in the same effect? -Peter From simon.brunning at gmail.com Wed Jul 6 05:16:59 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 6 Jul 2005 10:16:59 +0100 Subject: f*cking re module In-Reply-To: <1120636894.567642.54380@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <1120636894.567642.54380@g47g2000cwa.googlegroups.com> Message-ID: <8c7f10c6050706021657f2300a@mail.gmail.com> On 6 Jul 2005 01:01:34 -0700, Raymond Hettinger wrote: > With * being a greedy operator, your post's subject line matches, > "firetrucking" Nope: >>> print re.match('f*cking', 'firetrucking') None The OP was clearly showing his lack of regex nouce here. Clearly he wanted 'f.*cking': >>> print re.match('f.*cking', 'firetrucking') <_sre.SRE_Match object at 0x01196058> ;-) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From mage at mage.hu Mon Jul 18 10:14:51 2005 From: mage at mage.hu (Mage) Date: Mon, 18 Jul 2005 16:14:51 +0200 Subject: goto In-Reply-To: <17115.43253.567942.405579@montanaro.dyndns.org> References: <261d32a705071804483ef68021@mail.gmail.com> <17115.43253.567942.405579@montanaro.dyndns.org> Message-ID: <42DBB95B.5050208@mage.hu> skip at pobox.com wrote: > >>> what is the equivalent of C languages' goto statement in python? > > >> You really shouldn't use goto. > >> Fortunately you can't. > > Steven> Of course you can :-) > > Steven> You can write your own Python interpreter, in Python, and add a > Steven> goto to it. > >Maybe easier would be to write a Python assembler (there's probably already >one out there) and just write to Python's virtual machine... > > > Even easier to buy a book about programming. Note that python.org is second in google if you search "programming". So we need a little more work. Mage From ms at cerenity.org Fri Jul 29 15:59:14 2005 From: ms at cerenity.org (Michael Sparks) Date: Fri, 29 Jul 2005 21:59:14 +0200 Subject: Advanced concurrancy References: Message-ID: <42ea98a2$0$1185$ed2619ec@ptn-nntp-reader01.plus.net> Peter Tillotson wrote: > Hi, > > I'm looking for an advanced concurrency module for python and don't seem > to be able to find anything suitable. Does anyone know where I might > find one? I know that there is CSP like functionality built into > Stackless but i'd like students to be able to use a standard python build. Please take a look at Kamaelia* - it /probably/ has what you're after by the sounds of things. Currently the unit for sequential process can be either generators or threads, and is single CPU, single process, however we do expect to make the system multi-process and multi-system. * http://kamaelia.sourceforge.net/ Currently it runs on Linux, Mac OS X, Windows and a subset works nicely on Series 60 mobiles. (That has separate packaging) It works with standard Python versions 2.2 and upwards. The basic idea in Kamaelia is you have a class that represents a concurrent unit that communicates with local interfaces only which are essentially queues. The specific metaphor we use is that of an office worker with inboxes and outboxes with deliveries made between outboxes to inboxes. There also exists a simple environmental/service lookup facility which acts like an assistant in the above metaphor, and has natural similarities to a Linda type system. (The actual rationale for the assistant facility though is based on biological systems. We have communicating linked concurrent components - which is much like many biological systems. However in addition to that most biological systems also have a hormonal system - which is part of the thinking behind the assistant system) Generators (when embedded in a class) lend themselves very nicely to this sort of model in our experience /because/ they are limited to a single level (with regard to yield). It's probably suitable for your students because we've tested the system on pre-university trainees, and vacation trainees, and found they're able to pick up the system, learn the basic ideas within a week or so (I have some exercises on how to build a mini- version if that helps), and build interesting systems. For example we had a pre-university trainee start with us at the beginning of the year, learn python, Kamaelia, and build a simple streaming system taking a video file, taking snapshots and sending those to mobile phones and PC's - this was over a period of 3 months. He'd only done a little bit of access in the past, and a little bit of VB. Well that as well as a simple learning system simulating a digital TV decode chain, but taking a script instead of a transport stream. We recently made a 0.2.0 release of the system (not announced on c.l.p yet) that includes (basic) support for a wide range of multimedia/networked apps which might help people getting started. Some interesting new additions in the release are an IPython integration - allowing you to build Kamaelia systems on the fly using a shell, much like you can build unix pipelines, as well as a visual introspection tool (and network graph visualiser) which allows you to see inside systems as they are running. (This has turned out to be extremely useful - as you can expect with any CSP-type system) The specific use cases you mention are also very closed aligned with our aims for the project. We're essentially working on making concurrency easy and natural to use, (starting from the domain of networked multimedia). You can do incremental development and transformation in exactly the way it sounds like you want, and build interesting systems. We're also working on the assumption that if you do that you can get performance later by specific optimisations (eg more CPUs). * Example of incremental component development here: http://tinyurl.com/dp8n7 By the time we reach a 1.0 release (of Kamaelia) we're also aiming to be able to integrate cleanly with Twisted (on Twisted's grounds), but it is highly usable already - especially in your area. (In CVS we have tools for building game type systems easily & Tk integration as well. Tk based CSP systems are particularly fun to work with (as in fun, not "fun" :). One project we are seriously looking at is a visual editor for these CSP-type systems, since that appears now to be low hanging fruit. We've got a white paper about Kamaelia here: * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml This is "textualisation" of a presentation I gave at ACCU earlier in the year and is an overview of the core areas of the system - hopefully enough to let you know whether to look further! I also gave an updated talk at Europython - the presentation for which can be downloaded from here: * http://www.python-in-business.org/ep2005/talk.chtml?talk=2589&track=692 Last week I also gave a more pragmatic, shorter talk at Open Tech which is an introduction to Kamaelia, it's goals, and several examples of CSP type systems ranging from simple audio clients/servers through to presentation tools. That presentation can be downloaded from here: * http://kamaelia.sourceforge.net/Kamaelia_OT2005.tgz Both the Europython & Open tech bundles actually include the core concurrency systems (called Axon), and the component modules (Kamaelia) in the bundle, in addition to the slides and install docs. The presentation tools included in the bundles are written in python using Kamaelia. The project website is here: http://kamaelia.sourceforge.net/ > I'm trying to develop distributed / Grid computing modules based on > python. The aim is to be able to use barriers for synchronisation and > channels for communication between processes running on a single box. > Then the jump to multiple processes on multiple boxes and eventually to > MPI implementations. Hopefully, each jump should not be that big a leap. > > Of course it would be nice if there was a robust way of managing > concurrency in python aswell ;-) It's getting there - the recent PEP regarding the ability to cause a generator to have an exception thrown inside it provides very similar to Unix signals as provided via "kill", which will be nice when 2.5 is released. Hopefully you find the system useful, Best Regards, Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. From ramon at conexus.net Sun Jul 10 21:08:40 2005 From: ramon at conexus.net (Ramon F Herrera) Date: 10 Jul 2005 18:08:40 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: <1121044120.904683.266560@g14g2000cwa.googlegroups.com> [Peter Barret wrote:] > It may just be me, but I tend to think of a computer language as a > tool for directing computers to perform specific actions. Do we talk > about the expressiveness of a spade? yes, it is just you. :-) Your comparison is a very poor match. How can you even begin to compare a hammer or a screwdriver with a computer language? A more apt comparison would be a Roman general with his spade directing his troops to attack. Some generals have more expresiveness than others. The barbar generals will just grunt while the French generals will inspire with some poetic invocation. -Ramon From tjreedy at udel.edu Mon Jul 18 01:02:39 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 18 Jul 2005 01:02:39 -0400 Subject: list implementation References: <1121655435.153214.292520@o13g2000cwo.googlegroups.com> Message-ID: "sj" wrote in message news:1121655435.153214.292520 at o13g2000cwo.googlegroups.com... >I believe the type "list" is implemented as an array of pointers. A Python list is sematically/behaviorally defined as a mutable extensible sequence of references to Python objects. For the CPython reference implementation, the references are arrays of C pointers. Since, on balance, this works well, I presume the other four active computer language implementations do something equivalent. (How we humans execute Python code is a different question!) > Thus, random access is an O(1) operation Yes > while insertion/deletion is an O(n) operation. At the front, yes. (But modern CPUs with a one-instruction block mem move make the hidden multiplier relatively small.) At the end of the list, no; it is O(1). Making front insertion/deletion (but not in the middle) also O(1) has been considered but so far rejected. (For apps that need the symmetry, there is collections.deque.) > 2. Implementing list as an array is part of language specification or > implementation-dependent? While I believe I have answered this, I recommend reading the relevant parts of the language and library manuals (see chapter 2 of the latter). > 3. What if I actually need a doubly-linked list for constant-time > insertion/deletion? Is there a built-in type or a standard class? I believe it is roll-your-own to your specific needs. Of course, scanning thru such a list is still O(n). Terry J. Reedy From dvanvliet at 3dna.net Mon Jul 4 09:37:59 2005 From: dvanvliet at 3dna.net (Derek van Vliet) Date: 4 Jul 2005 06:37:59 -0700 Subject: importing pyc from memory? Message-ID: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Using the Python/C API, is there a way I can import a pyc file that I have in memory (as opposed to loading from disk)? I'm trying to save compiled python code in a proprietary file format to cut reduce the overhead of compiling all my scripts when my app starts up. Derek From cliff at develix.com Sat Jul 30 17:13:14 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 14:13:14 -0700 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: <7xmzo4nmf0.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> <7xmzo4nmf0.fsf@ruckus.brouhaha.com> Message-ID: <1122757994.19618.33.camel@localhost.localdomain> On Sat, 2005-07-30 at 12:06 -0700, Paul Rubin wrote: > Peter Hansen writes: > > The last time I checked (as I recall), at least Wax and possibly Dabo > > both either lagged well behind recent wxPython developments of provide > > relatively limited support, leaving out a sizable and (to me) > > important number of features from what they wrapped. > > wxPython also depends on wxWidgets which lags behind GTK. But how stable is GTK on systems such as Windows and OS/X? That has been what has kept me from using it. Most GTK apps I've used on Windows (including the venerable GIMP) are nowhere near as stable as their Linux counterparts (although this may not be entirely the fault of GTK). Also, GTK on OS/X requires Fink, which is a pretty hefty requirement to place on an end user. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From steven.bethard at gmail.com Sun Jul 10 00:32:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 09 Jul 2005 22:32:22 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120963325.227725.123030@g43g2000cwa.googlegroups.com> References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> <1120963325.227725.123030@g43g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [Steven Bethard] > >>I would hope that in Python 3.0 list comprehensions and generator >>expressions would be able to share a large amount of implementation, and >>thus that the speed differences would be much smaller. But maybe not... > > Looking under the hood, you would see that the implementations are > necessarily as different as night and day. Only the API is similar. Necessarily? It seems like list comprehensions *could* be implemented as a generator expression passed to the list constructor. They're not now, and at the moment, changing them to work this way seems like a bad idea because list comprehensions would take a performance hit. But I don't understand why the implementations are *necessarily* different. Could you explain? STeVe P.S. The dis.dis output for list comprehensions makes what they're doing pretty clear. But dis.dis doesn't seem to give me as much information when looking at a generator expression: py> def ge(items): ... return (item for item in items if item) ... py> dis.dis(ge) 2 0 LOAD_CONST 1 ( at 0116FD20, file "", line 2>) 3 MAKE_FUNCTION 0 6 LOAD_FAST 0 (items) 9 GET_ITER 10 CALL_FUNCTION 1 13 RETURN_VALUE I tried to grep through the dist\src directories for what a generator expression code object looks like, but without any luck. Any chance you could point me in the right direction? From henryho at NO__SPAMM_.telus.net Thu Jul 28 20:19:50 2005 From: henryho at NO__SPAMM_.telus.net (fanbanlo) Date: Fri, 29 Jul 2005 00:19:50 GMT Subject: monitor a folder for file creation, how? Message-ID: How do I monitor a folder for new file(s) creation? How to use thread to do a wait until a new file is 'detected'? Thank you! From cam.ac.uk at mh391.invalid Tue Jul 26 14:52:50 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 26 Jul 2005 19:52:50 +0100 Subject: Emacs skeletons In-Reply-To: References: Message-ID: George Flaherty wrote: > Since you are on this topic, do you (or anyone else) have any > type of "code-completion" mode for python in emacs? I have this in my .emacs: (global-set-key "\M-/" 'hippie-expand) This means that M-/ will do dumb code completion based on stuff that is already in an open buffer, which can be helpful, and is certainly better than nothing. Try it; you'll probably like it. I also have this in .emacs: (setq abbrev-file-name "~/etc/emacs/abbrev_defs") (quietly-read-abbrev-file) and this in ~/etc/emacs/abbrev_defs: (define-abbrev-table 'python-mode-abbrev-table '( ("pdb" "import pdb; pdb.set_trace()" nil 0) )) Together, those mean that if I type pdb, M-/, then I get import pdb; pdb.set_trace(), which can save me a lot of time while debugging. To be honest, I usually use pdb from the commandline instead these days, with 'alias pdb="python -m pdb"' in my .bashrc. -- Michael Hoffman From me at privacy.net Mon Jul 25 16:49:46 2005 From: me at privacy.net (Dan Sommers) Date: Mon, 25 Jul 2005 16:49:46 -0400 Subject: how to write a line in a text file References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> <1122321475.234274.180140@g47g2000cwa.googlegroups.com> Message-ID: On 25 Jul 2005 12:57:55 -0700, "wittempj at hotmail.com" wrote: > A recipe is > * open your file for reading: f = open('filename.txt', 'r') > * read all lines in a list: content = f.readlines() > * close the file: f.close() > * set the third element in the list to something else: content[2] = > 'Blahdiblah' Better make that ''Blahdiblah\n' (note the trailing newline) because: - readlines leaves the newlines at the ends of the lines - writelines assumes that each line (still) contains a newline > * re-open the file for writing: f = open('filename.txt', 'w') > * write the list to the file: f.writelines(content) > * close the file: f.close() HTH, Dan -- Dan Sommers From lambacck at computer.org Sun Jul 17 11:48:27 2005 From: lambacck at computer.org (Chris Lambacher) Date: Sun, 17 Jul 2005 11:48:27 -0400 Subject: Python vs. Access VBA In-Reply-To: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> Message-ID: <20050717154827.GA13128@computer.org> If you are going to go with Python, don't include Access in the mix at all. If you want a small light-weight, serverless database back-end, you would be better to go with SQLite. Its cross platform and well proven. I think Firebird will give you that too, though I have never used it. Most people who use Oracle don't need it. Unless you REALLY need it (Think terabytes of data), Oracle is like cracking a nut with a sledge hammer. You can do it. But you have to slug around a lot more weight in order to do what you can accomplish with a nut cracker. In other words its overly complicated. -Chris On Sun, Jul 17, 2005 at 08:06:22AM -0400, Ed Leafe wrote: > On Jul 15, 2005, at 11:19 PM, William Lodge wrote: > > > Finally, does anybody know of any Web sites having examples of > > database apps > > in Python? > > You might want to look at Dabo, which is a database application > framework for Python. In about 30 seconds you can create an application > that queries a database, displays the results, and allows for > editing/updating/inserting/deleting records. > > Currently we do not have an ODBC interface, which is what you'd need > if the data is in Access, since no one involved has written that > module. However, if you are interested in developing your app in Dabo, > we'd be glad to add that module as long as you're willing to give us > the feedback we need to get it working smoothly. > > BTW, I wouldn't suggest scaling up to Oracle - why get involved with > all that licensing? There are many open-source databases, such as > PostgreSQL, MySQL and Firebird that can handle large data sets without > getting stuck with huge license fees. > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list From jasondrew72 at gmail.com Thu Jul 14 17:00:27 2005 From: jasondrew72 at gmail.com (Jason Drew) Date: 14 Jul 2005 14:00:27 -0700 Subject: Changing size of Win2k/XP console? In-Reply-To: <42d6cf32$0$16170$39db0f71@news.song.fi> References: <42d6bdd2$0$16170$39db0f71@news.song.fi> <42d6cf32$0$16170$39db0f71@news.song.fi> Message-ID: <1121374827.754019.188800@z14g2000cwz.googlegroups.com> SetConsoleWindowInfo looks like a better candidate. See http://tinyurl.com/budzk (I.e. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/setconsolewindowinfo.asp) Haven't tried it though. Good luck! From rtw at freenet.co.uk Sun Jul 31 09:16:46 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 31 Jul 2005 08:16:46 -0500 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: Paolino wrote in news:mailman.2453.1122812091.10512.python- list at python.org in comp.lang.python: > Rob Williscroft wrote: > > > After 3 or 4 iterations I refactored you code to this: > > > > def translate( text ) > > import string > > all=string.maketrans('','') > > badcars=all.translate(all,string.letters+string.digits) > > TABLE = string.maketrans(badcars,'_'*len(badcars)) > > > > global translate > > def translate( text ): > > return text.translate(TABLE) > > > > return translate( text ) > > There is a way to access 'all' and 'badcars' here? > > In my trial translate.all and translate.badcars can be accessed easily > and maybe coherently. I had to do this inorder to access them: def translate( text ): import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) TABLE = string.maketrans(badcars,'_'*len(badcars)) global translate def translate( text ): return text.translate(TABLE) print "First Call! ", # -- Just to showoff -- translate.all = all translate.badcars = badcars return translate( text ) print translate("If I was ...") print translate("If I was ...") print "badcars:", len(translate.badcars) CPython 2.4 on windows XP. But maybe you mean something else ? > > Thanks a lot, and don't tell me 'the dictator has marked the trail' ;) > I got the idea from Hung Jung Lu, here: http://groups.google.co.uk/group/comp.lang.python/msg/1e63e07c7d83cc7d How the trail got there I've no idea ;-) Rob. -- http://www.victim-prime.dsl.pipex.com/ From rwgk at yahoo.com Mon Jul 11 15:35:20 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 11 Jul 2005 12:35:20 -0700 (PDT) Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <42d295eb.389670396@news.oz.net> Message-ID: <20050711193520.99610.qmail@web31502.mail.mud.yahoo.com> --- Bengt Richter wrote: > >I still think it's too specialized. What would, hypothetically, this do? > > > >class Bar: pass > > > >class Foo: > > x = Bar() > > def method_1(self, x.y): > > pass > > > >It's hard to explain that you can autoassign self.y but not x.y. > > > No, that limitation wouldn't exist, so you wouldn't have to explain it ;-) > I.e., the above would act like > > class Foo: > x = Bar() > def method_1(self, _anonymous_arg_1): > x.y = _anonymous_arg_1 > > and would do whatever it would do now (probably look for a global x or a > closure cell x, but > it wouldn't find the class variable in a normal method call) I am a bit afraid of opening a door for weird side effects. E.g. class unrelated: pass u = unrelated() class grouping: def __init__(self, self.x, u.y, self.z): pass Is this really a good thing to allow? I am afraid it will be abused. My prime concern was to provide a good solution for a very common problem. If we stray too far from this most important goal we may get nothing in the end. "self" (or whatever people prefer as a name for the first argument of a bound function) *is* special. I think therefore it deserves special support. I think it would be fantastic if we could push through the def __init__(self, self.x, y, self.y) syntax, with the explicit limitation that only the first argument can be used on the left side of the dot. I'd also happily settle for a decorator approach, __autoinit__ or over variations, as long as they are built-in and easy to remember/use/explain to a novice. However, to me the self.x approach seems to be "just right" because: 1. It is a good compromise between "redundant" and "explicit"; i.e.: too redundant: def __init__(self, x, y, z): self.x = x self.y = y self.z = z middle ground: def __init__(self, self.x, self.y, self.z): pass the other extreme: def __init__(self, .x, .y, .z): pass I am thinking people can understand the "middle ground" approach even without looking at release notes and will not be surprised if unrelated.y doesn't work. 2. This approach is open to full optimization for runtime performance and should therefore be faster than the redundant conventional approach. I.e. the arguments can directly be inserted into the desired dictionary (or slot), without ever being added to locals(). 3. The user can always write "grouping(x=1,y=2,z=3)". I.e. how the arguments are used is strictly an implementation detail, as it should be. Cheers, Ralf ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ From hancock at anansispaceworks.com Thu Jul 21 22:25:12 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 21 Jul 2005 21:25:12 -0500 Subject: Copying attributes In-Reply-To: <200507212017.28766.hancock@anansispaceworks.com> References: <200507212017.28766.hancock@anansispaceworks.com> Message-ID: <200507212125.12967.hancock@anansispaceworks.com> On Thursday 21 July 2005 08:17 pm, Terry Hancock wrote: > But is "faces" a list, > dictionary, or tuple (or something more obscure)? Lest it be unclear why this matters: >>> da = {'a':1, 'b':2, 'c':3} >>> for d in da: ... print d ... a c b >>> la = [1,2,3] >>> for d in la: ... print d ... 1 2 3 As you can see, looping through a dictionary gives you its keys, not its values. It is possible to define even more bizarre behavior for user-defined collection classes, and "mesh" is probably a C extension type. I've been wanting to learn the Blender API, too. But I haven't done so yet, so I'm not really sure what "mesh" will be. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Sat Jul 30 11:50:50 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 01:50:50 +1000 Subject: [path-PEP] Path inherits from basestring again References: <3l192cF109df7U1@individual.net> Message-ID: On Sat, 30 Jul 2005 14:10:52 +0200, Reinhold Birkenfeld wrote: > Above all, nobody can tell me that there's any programmer who doesn't > instantly recognize '/' as a directory separator. Is classic Macintosh OS still supported on Python? Because Mac programmers who haven't made the jump to OS X will probably instantly recognise ':' as the directory separator, not '/'. Acorn RISC OS developers may also instantly recognise '.' as the directory separator. And presumably mathematicians and numeric programmers who do very little file input/output will probably instantly recognise '/' as the division operator. And I have no idea what directory separators are in use under file systems that don't use ASCII or any extension to ASCII, eg the OS which has been described as the most common operating system in the world, the Japanese "Real-time Operating System Nucleus", TRON. (Chances are you have at least half a dozen devices in your home with embedded TRON.) Still, your (modified) point that most Western programmers will quickly recognise '/' as a directory separator is surely true. Even given that, I'm not convinced that it is a good idea to turn '/' into a join-path operator. I don't have any good reasons for objecting either, just a funny little feeling in the back of my head that says that no good can ever come from allowing Path("C:\Windows")/"cmd.com". -- Steven. From Gov at mailinator.com Fri Jul 8 14:31:14 2005 From: Gov at mailinator.com (gov) Date: 8 Jul 2005 11:31:14 -0700 Subject: Legacy data parsing Message-ID: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Hi, I've just started to learn programming and was told this was a good place to ask questions :) Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. I've been reading up on the Regular Expression module and ways in which to manipulate strings however it has been difficult to think of a way in which to extract an address. Here's an example of the raw text that I have to work with: ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: **************************** FOR/POUR AL/LA: 20 CORR TYP: A1B 2C3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ####### MRS XXX X XXXXXXX ### XXXXXXXXX ST DD TYP: P:6 CHNGD/CHANG MONCTON NB LANG: E CONS/REGR: ####### MRS XXX X XXXXXXX ##### #### ###-###-# ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: **************************** FOR/POUR AL/LA: 30 BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ####### MISS XXXX XXXXX ### XXXXXXXX ST MONCTON NB EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: *********** (the # = any number, and the X's are just regular text) I would like to extract the address information, but the two different text objects on the right hand side are difficult to remove. I think it would be easier if I could just extract a fixed square of information, but I don't have a clue as to how to go about it. If anyone could give me suggestions as to methods in sorting this type of data, it would be appreciated. From godoy at ieee.org Fri Jul 29 16:13:26 2005 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 29 Jul 2005 17:13:26 -0300 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Michael Hoffman wrote: > True, but a lot of his point *is* parsing input from the command line. > Consider the following points paraphrased from his article: > > * Don't mix multiple ways of specifying options. (Solved by optparse) > * If a flag expects an associated value, allow an optional = between the > flag and the value. (Solved by optparse) > * Allow single-letter options to be "bundled" after a single dash. > (Solved by optparse) > * Always allow -- as a file list marker. (Solved by optparse) > > And a lot of the other points are things that are made much, much, > simpler by optparse, to the point that they become somewhat obvious. Take a look at the Perl module, then. You'll see that all of these are also solved there "automagically". I've stoped coding Perl almost 3 years ago, and even then I never had to write anything to parse command line input by hand. I suggest you take a look at Getopt::Long, at CPAN. http://search.cpan.org/~jv/Getopt-Long-2.34/ http://search.cpan.org/src/JV/Getopt-Long-2.34/README Be seeing you, -- Jorge Godoy From daniel.dittmar at sap.corp Fri Jul 1 11:30:52 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 01 Jul 2005 17:30:52 +0200 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> Message-ID: Rocco Moretti wrote: >>> Except that (please correct me if I'm wrong) there is somewhat of a >>> policy for not including interface code for third party programs which >>> are not part of the operating system. (I.e. the modules in the >>> standard libary should all be usable for anyone with a default OS + >>> Python install.) There are several degrees of std-ness for Python Modules: Example expat: The sources for this extension module are contained in the Python tarball, so this module is guaranteed to be part of a Python distribution Example zlib: If the include files and libs can be found, this extension will be built. So it's part of std-Python (the source), but not part of std-Python (installed). See others in Modules/Setup Binary distributions may choose additional modules which appear to be standard. Example: zlib is part of all Python-Installations on Windows and most Linux-distribution will have readlines as 'standard'. There seems to be a great reluctance by the Python developers to add modules of the expat kind, as this means responsibilities for additional source modules. There's also the problem with incompatible licenses, integrating a second configure, deciding when to update to the latest version of the library etc. Another problem is that there are often several modules for a specific problem (e.g. several modules interfacing to PostgreSQL), so there's always a chance to make an anemy for life, no matter which you pick. And module authors might not be interested as they'd be then bound by the Python release cycle. Daniel From martin.witte at gmail.com Sun Jul 3 08:05:36 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 3 Jul 2005 05:05:36 -0700 Subject: website catcher In-Reply-To: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> Message-ID: <1120392336.609911.76850@g14g2000cwa.googlegroups.com> You can catch the content of an url like this: http://www.python.org/doc/current/lib/node478.html, from here you can parse it, and the store the result e.g. in dictionary, you will have a very well performing solution like this. From steve at REMOVETHIScyber.com.au Thu Jul 28 09:10:22 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 28 Jul 2005 23:10:22 +1000 Subject: all possible combinations References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> <42d6de96@news.eftel.com> <1122547119.104995.43340@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 28 Jul 2005 12:30:23 +0100, Steve Holden wrote: >> This makes me wonder why we still don't have something like the unint >> function above in the standard distribution. >> > Because it's not what you'd call (or, at least, it's not what I'd call) > universally required. As you have shown it is relatively easy to hack > something supp when it's needed, so since it isn't something that's > required by the majority it hasn't been added to the library. Have you looked at what's in the standard Python library? aifc.py => Stuff to parse AIFF-C and AIFF files. imghdr.py => Recognize image file formats based on their first few bytes. gopher.py => Gopher protocol client interface. token.py => Token constants (from "token.h"). I'm sure they are useful to somebody, but do you really think that the majority of Python users need to parse AIFF files? Converting base-19 strings into integers is a rather niche need, but if somebody bothered to write, document and provide unittests for such a module, I'm sure it could be added to the standard library. It isn't as if there is any policy of prohibiting specialist modules just because they don't have universal need. And no, I'm not volunteering. I may, if I get an itch, but at this moment in my life I'm not that fussed one way or another. -- Steven. From __peter__ at web.de Fri Jul 29 14:27:18 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Jul 2005 20:27:18 +0200 Subject: can list comprehensions replace map? References: <42ea596d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Can I play too? Not unless you buy the expensive but good-looking c.l.py gaming license which is only available trough me :) > How about: > import itertools > > def fillzip(*seqs): > def Nones(countactive=[len(seqs)]): > countactive[0] -= 1 > while countactive[0]: > yield None > seqs = [itertools.chain(seq, Nones()) for seq in seqs] > return itertools.izip(*seqs) You may be introducing a lot of extra tests in the while loop with the non-constant condition -- which in practice is fairly cheap, though. I'm willing to take the performance hit for the introduction of sane variable names alone... Peter From no at spam Sat Jul 16 00:42:31 2005 From: no at spam (D H) Date: Fri, 15 Jul 2005 23:42:31 -0500 Subject: HTML expect in python In-Reply-To: References: Message-ID: <7uWdnWpzxZCnDUXfRVn-vQ@comcast.com> WGW wrote: > I would like to automate some simple browser navigating using python. > Ideally, I would like a package like pyexpect, but that can handle a > browser in much the same way as pyexpect handles a terminal (tall > order!). In short, I want a macro language for a browser (I know about > the commercial packages such as Easy Bee and Internet macros, but I want > more programmability and less cost!) See the mechanize module: http://wwwsearch.sourceforge.net/mechanize/ Or else you can use win32com stuff to automate internet explorer if you really need to do it that way. From Stephan.Popp at iisb.fraunhofer.de Mon Jul 18 04:25:12 2005 From: Stephan.Popp at iisb.fraunhofer.de (Stephan Popp) Date: Mon, 18 Jul 2005 10:25:12 +0200 Subject: Problem with threads Message-ID: <200507181025.12909.Stephan.Popp@iisb.fraunhofer.de> Hi all, I've got a problem with stopping python-threads. I'm starting a thread with twisteds reactor.deferToThread which start a methodcall in a seperate thread. In this thread a swig-wrapped c++ module is running. Now I want to stop the running thread from the main thread or another one, and have no idea how to do it. I hope it has become clear what I want to do, if not feel free to ask. I'm running python 2.4 Thanks in advance, Stephan From news4mat at gmx.de Wed Jul 6 13:47:23 2005 From: news4mat at gmx.de (fortuneteller) Date: Wed, 06 Jul 2005 19:47:23 +0200 Subject: Scipy - Latex Annotations in plots Message-ID: Hello, I'm quite new to python and Scipy. Anyway I want to use it to plot graphs. Does anybody know if there is the possibility to use Latex in SciPy's plotting functions like gplt? Thanks for your help, Matthias From flupke at nonexistingdomain.com Wed Jul 20 11:15:40 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 20 Jul 2005 15:15:40 GMT Subject: getting the class name of a subclass In-Reply-To: <1121872256.a32dca1a4e415c43dc250b9e956574bb@teranews> References: <5UsDe.149277$Yz5.7850081@phobos.telenet-ops.be> <1121872256.a32dca1a4e415c43dc250b9e956574bb@teranews> Message-ID: George Sakkis wrote: > Make printclass a class method: > > class A(object): > def __init__(self): > print "I'm A" > > # for python 2.4 > @classmethod > def printclass(cls): > print "Module", cls.__module__ > print "Class", cls.__name__ > # for 2.3 or older > printclass = classmethod(printclass) > > > Regards, > George George, it works like a charm. Thanks! Benedict From fake at doesntexist.dud Fri Jul 15 17:56:16 2005 From: fake at doesntexist.dud (MrEntropy) Date: Fri, 15 Jul 2005 21:56:16 +0000 Subject: Reading variables from a forked child (Python C/API) Message-ID: <42d7ab64@duster.adelaide.on.net> Greetings, I'm having a little trouble getting an idea running. I am writing a C program which is really a frontend to a Python program. Now, my C program starts up, does some initialisation like initialisation of it's variables and Py_Initialize() and then it fork()s. After forking the child launches the python program with Py_Main() and with the parent I want to be able to read the variables of the Python program. I have tried many ways but cannot find a solution to do this. The ONLY testcase in fact that I could get working is this: #include #include int main(){ char* buffer; PyObject* mod; PyObject* dict; PyObject* obj; Py_Initialize(); PyRun_SimpleString("foo = 'bar'"); mod = PyImport_AddModule("__main__"); dict = PyModule_GetDict(mod); obj = PyMapping_GetItemString(dict, "foo"); buffer = PyString_AsString(obj); printf(buffer); Py_Finalize(); return 0; } And that only proves to me that I can get the variables out of python, nothing to do with forking. When i try doing very much the same thing to a forked child I get sedfaults. In other words the child gets Py_Main()'d and executes the child, while in the parent i do much the same as the above with the exception of PyImport_AddModule() being changed to PyImport_ImportModule() because main is already preset i gather. So my questions are these: Does the fact that I initialise before the fork have anything to do with my failure? And if so, is it because some pointers are invalidated? Is the problem to do with the inability to perform operations on a python environment initialised through C while it's executing? Because i'm technically executing operations on it from the parent while the child in the same environment is running the program. In the program that the child is running, i need to access some variables it has in __main__. main also has an instantiated object 'd' which i also need some variables from, i.e. __main__.d.foo. How can I access these? Overall, I would REALLY appreciate an example of how to do what I want to achieve, examples help me a lot so if you wouldn't mind typing one up or pointing me to some relevant documentation i'd appreciate it. Thankyou. From martin at v.loewis.de Thu Jul 14 17:44:38 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 14 Jul 2005 23:44:38 +0200 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? In-Reply-To: <11ddfgsg4nlch86@corp.supernews.com> References: <11ddckucctde603@corp.supernews.com> <11ddfgsg4nlch86@corp.supernews.com> Message-ID: <42d6dcc7$0$11014$9b622d9e@news.freenet.de> Grant Edwards wrote: > I often foget how old Python is. Still, I've been using IEEE > floating point in C programs (and depending on the proper > production and handling of infinities and NaNs) for more than > 20 years now. I had thought that Python might have caught up. As should be clear by now, it hasn't. What made you think it would have? As Tim says, there are very strong reasons why Python *doesn't* support IEEE 754, the primary one being lack of contributors that improve it. I, for example, care much more about integer arithmetic than floating point. Regards, Martin From reinhold-birkenfeld-nospam at wolke7.net Sun Jul 24 11:49:39 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 24 Jul 2005 17:49:39 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kehbmFtv6lpU1@individual.net> <3khgn6Fu8nm8U1@individual.net> Message-ID: <3khrkkFuhpimU1@individual.net> Michael Hoffman wrote: > Reinhold Birkenfeld wrote: > >> * __iter__() iterates over the parts(). >> * the following methods raise NotImplemented: >> capitalize, expandtabs, join, splitlines, title, zfill > > Why? They *are* implemented. I do not understand this desire to wantonly > break basestring compatiblity for the sake of breaking compatibility. > > Once you break compatibility with basestring you can no longer use a > path anywhere that you could have used a str or unicode before. With > compatibility broken, the only possible supported way of passing paths > to third-party functions will be to cast the path with > path.__bases__[0](mypath) before passing it anywhere else. You can't > even use str() because you don't know what the base class of the path > is. What a pain. > > From the original path.py documentation: > > """ > os.path.join doesn't map to path.join(), because there's a string method > with that name. Instead it's path.joinpath(). This is a nuisance, but > changing the semantics of base class methods is worse. (I know, I tried > it.) The same goes for split(). > """ > > It ain't broke. Please stop breaking it. Okay. While a path has its clear use cases and those don't need above methods, it may be that some brain-dead functions needs them. Reinhold From usenet.20.evilspam at spamgourmet.com Wed Jul 27 19:14:40 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Wed, 27 Jul 2005 23:14:40 GMT Subject: Rich Graphics? Message-ID: I'm trying to write a Gui in Python for manipulating rich graphical representations, similar to something like Inkscape. I've tried tkinter, wxPython, pyGtk, and while they all do traditional widgets well enough, none of them really handle anti-aliased, transparent, transformed shapes typical of vector based displays. I've noticed tkZinc, which seems to better handle vector graphics through the use of openGL, but it's traditional widget set is still limited and based on tkinter. Ideally, what I'm looking for is something like wxWidgets which can display SVG along side standard widgets and allow there manipulation through Python. I was thinking of a web-based route, by accessing the SVG capabilities in Mozilla's Deer Park browser through Twisted+Livepage, but this has been extremely complicated and limiting. Are there any other options I haven't considered? Sincerely, Chris From supercomputer at gmail.com Fri Jul 15 15:27:28 2005 From: supercomputer at gmail.com (supercomputer at gmail.com) Date: 15 Jul 2005 12:27:28 -0700 Subject: ssh popen stalling on password redirect output? Message-ID: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> I have a script that I cycle through nodes connect to them and run uptime to get some information. I run the script as root so it doesn't require a password on the rest of the nodes. It does however barf on the nodes that are having trouble and require a different password. Is there an easy way to skip these nodes? Maybe redirect the password prompt to stdout or stderr or even skip them? Thanks in advance here is the current script. info=os.popen('ssh node208 uptime') sys.stderr=info sys.stderr.write(info) I'm very new to python if you could give me a link to an article that would also be helpful. The documentation on python is very hard to find as compared with php.net's php documentation. From rkern at ucsd.edu Wed Jul 13 09:16:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 13 Jul 2005 06:16:54 -0700 Subject: Building a function call? In-Reply-To: References: Message-ID: Duncan Booth wrote: > Francois De Serres wrote: > >>Having a string: "dothat" >>and a tuple: (x, y) >>1. What's the best way to build a function call like: dothat(x,y)? >> >>Assuming dothat is def'd in the same module, >>2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) >>the right way to have it executed? >> >>If dothat is def'd in another module: >>3. what would be the right way to initialize the globals to pass to >>eval ? > > No, none of this is a good place to use eval. > > aString = "dothat" > atuple = (x, y) > > If aString is the name of a function in the current module: > > globals()[aString](*aTuple) > > If aString is a function in another module: > > import otherModule > vars(otherModule)[aString](*aTuple) Ick! Please: getattr(otherModule, aString)(*aTuple) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gsakkis at rutgers.edu Fri Jul 1 01:06:58 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 22:06:58 -0700 Subject: Speaking of list-comprehension? References: Message-ID: <1120194418.531045.257500@g47g2000cwa.googlegroups.com> "Chinook" wrote: > I'm probably just getting languages mixed up, but I thought in my Python > readings over the last couple months that I had noticed an either/or > expression (as opposed to a bitwise or, or truth test). Being a curious > sort, I tried several variations of how a list comprehension *might* be > constructed and got the results expected relative to the operators, but > not the results I was trying to achieve. > > So, is it possible to achieve what the "for loop" (below) does in a > single list comprehension? I don't even see a way to accomplish such in > two list comprehensions with an intermediate result unless an index > pattern was the criterion. > > Just wondering, > Lee C > > PS I'm not suggesting it be added to the language :~) Beyond the new > classes and decorators (simply a convienence), I'm for KISS even to the > extent of the much abused Case statement. > > >>> ta = [5, 15, 12, 10, 9] > >>> for i in range(len(ta)): > ... if ta[i] >= 10: > ... ta[i] -= 10 > ... else: > ... ta[i] += 10 > ... > >>> ta > [15, 5, 2, 0, 19] The following works, although its readability is debatable, to say the least, let alone performance in the general worst case: >>> ta = [5, 15, 12, 10, 9] >>> ta = [(x+10,x-10)[x>=10] for x in ta] >>> ta > [15, 5, 2, 0, 19] The lack of a ternary if?then:else operator manifests itself in such examples, but alas, there isn't much hope that even python 3K will have one... Would-go-with-ugly-syntax-than-no-syntax-any-day'ly yrs, George From luca.tavoletti at gmail.com Wed Jul 20 10:46:47 2005 From: luca.tavoletti at gmail.com (lux) Date: 20 Jul 2005 07:46:47 -0700 Subject: wxPython field validation Message-ID: <1121870807.661993.27740@f14g2000cwb.googlegroups.com> Hi all, I'm using wxPython and I need to block the cursor (focus) in a TextCtrl until the field value is valid. I've look EVT_KILL_FOCUS but I can't stop the focus beavoir (no focus to next field) Any ideas? Tanks a lot and sorry for my english. From pinard at iro.umontreal.ca Fri Jul 8 12:20:38 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 8 Jul 2005 12:20:38 -0400 Subject: Compiler error recovery [was: Re: f*cking re module] In-Reply-To: References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> <86oe9dvs6d.fsf@bhuda.mired.org> Message-ID: <20050708162038.GA13998@phenix.progiciels-bpi.ca> [Rocco Moretti] > Fran?ois Pinard wrote: > > I once worked with a PL/I compiler (on a big IBM mainframe), which was > > trying to be helpful by spitting pages of: > > Error SUCH AND SUCH, assuming that THIS AND THIS was meant. > > and continuing compilation nevertheless. It was a common joke to say > > that PL/I would compile some random valid program out of any garbage! > We may laugh now (and then), but it was likely a valid design decision > at the time. [...] Error-checking-by-compiling only "works" if you > have cheap computing power you can run attended. (Can you imagine what > TDD would be like if you had to wait 24+ hrs between code executions?) Of course, all granted.[1] The only way to be really productive, in those times, was to round-robin oneself between a dozen simultaneous projects, or so, pushing on each one in turn while concentrating hard to avoid spoiling one run, before resubmitting that project and moving to the next. This kind of seek for productivity was somehow exhausting for the mind. Nowadays, things are infinitely easier. Even if easier, Python is sadly "original" in stopping at the first syntax error, probably for avoiding all concerns about error recovery, which is not always an easy matter. I suspect it might be easier with Python than with many other languages. -------------------- [1] PL/I was aggressively aiming both syntactic and semantic recovery. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From miki.tebeka at zoran.com Tue Jul 26 02:38:34 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 26 Jul 2005 09:38:34 +0300 Subject: Reading binary with header In-Reply-To: <0DF798CBF125BF4AA1227F26431C29BD01A32F31@pnlmse27.pnl.gov> References: <0DF798CBF125BF4AA1227F26431C29BD01A32F31@pnlmse27.pnl.gov> Message-ID: <20050726063834.GA3100@zoran.com> Hello Dan, > I am trying to head in a binary file that has a header and different > character types. The array module apparently expects the typecode to > be the same throughout. Here's what the file looks like: > > Byte number: type: value: purpose: > 1-4 char "ver." > 5-8 char "0001" version number > 9-12 int 1, 2, 3, or 4 data type: 1=unsigned byte > 2=unsigned short 3=32-bit integer 4=32-bit floating point > > 13-16 int x dimension, xdim > 7-20 int y dimension, ydim > 20-24 int z dimension, zdim > 25-28 int xdim*ydim*zdim > > The rest of the file contains the data array of type in indicated in > bytes 9-12. > > I have tried: > import Numeric as N > import array > fileobj = open(myfile, mode='rb') > s = array.array('f') > s.read(fileobj, size) > data = N.array(s, typecode=N.Int) > fileobj.close() > > But the header must confuse things because I do get what I expect. I'd use the struct module to read the header and then create an array according to type. Note: The code below is untested and without error checking. from struct import struct from array import array from os.path import getsize TYPES = { # Type of array 1 : "c", 2 : "H", 3 : "i", 4 : "f" } filesize = getsize(filename) # File size fo = open(filename, "rb") header = fo.read(12) # Read interesting header information fields = unpack("ssssssssi", header) fo.read(15) # Skip non-data header a = array(TYPES[fields[-1]) # Create array size = (filesize - 28) / a.itemsize # Size to read a.read(fo, size) # Read to array Also check that you don't have little/big endien problems. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 08:44:44 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 14:44:44 +0200 Subject: Path inherits from basestring again In-Reply-To: <1122683709.934081.273730@o13g2000cwo.googlegroups.com> References: <3kehbmFtv6lpU1@individual.net><3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> <3kkj5tFv0el1U1@individual.net> <1122683709.934081.273730@o13g2000cwo.googlegroups.com> Message-ID: <3l1b1sF10i4kgU2@individual.net> NickC wrote: > [Re: how to get at the base class] > > Do you really want to have a "only works for Path" way to get at the > base class, rather than using the canonical Path.__bases__[0]? > > How about a new property in the os.path module instead? Something like > os.path.path_type. > > Then os.path.path_type is unicode if and only if > os.path.supports_unicode_filenames is True. Otherwise, > os.path.path_type is str. > > Then converting a Path to str or unicode is possible using: > > as_str_or_unicode = os.path.path_type(some_path) > > The other thing is that you can simply make Path inherit from > os.path.path_type. That's what I suggested with Path.Base. It has the advantage that you don't have to import os.path to get at it (Path is meant so that you can avoid os.path). Reinhold From pythonmailing at web.de Sat Jul 23 19:48:20 2005 From: pythonmailing at web.de (Marek Kubica) Date: Sun, 24 Jul 2005 01:48:20 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <1n6sneaka8uxf.1oj2fdat4sfzp$.dlg@40tude.net> Hello! > How well does PyGTK run on Windows (98, 2K, XP)? How stable is it? Will > I be able to make an executable (using Py2Exe) of an application that > uses PyGTK? I _do_ like PyGTK on Windows. It works without problems. You can find a ready to use py2exe script on http://www.pythonwiki.de/PyGtk. You could also bundle the runtime DLLs with your py2exe'd application, but I have never done this. You could try doing this like described here: http://aspn.activestate.com/ASPN/Mail/Message/py2exe-users/2476686 (use the setup.py script from the wiki and start at (2) in the mail). HTH. greets, Marek PS: Yes, I admit it is harder than py2exe + wxPython but I still like PyGTK. From claird at lairds.us Sun Jul 17 11:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 17 Jul 2005 15:08:02 GMT Subject: Environment Variable References: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> <1121189578.883915.50620@o13g2000cwo.googlegroups.com> Message-ID: <3c5qq2-9p7.ln1@lairds.us> In article , Sybren Stuvel wrote: >tuxlover enlightened us with: >> No, the replies from Grant's and Sybren's do answer my question. > >It would be a lot more polite to actually thank the people helping >you. . . . Expressing gratitude is indeed a courtesy. As an old-time Usenetter, I also have a high regard for economy or brevity; I generally communicate my thanks in private e-mail, unless I can embed them in a comment which I think is likely to interest a wider audience. I have in mind something on the order of, "Thanks, timbot! I notice that not only does that solution conform to IEEE 754, as requested, but it's compatible with the Rayleigh-Ritz implementation found in ..." I'm certain neither of Mr. Stuvel's point, nor of whether it applied to tuxlover's actual behavior. I wouldn't want readers to think, though, that every well-formed clp thread must necessarily terminate in a follow-up whose content is limited to "Thx." From rem642b at Yahoo.Com Wed Jul 27 01:11:12 2005 From: rem642b at Yahoo.Com (Robert Maas, see http://tinyurl.com/uh3t) Date: Tue, 26 Jul 2005 22:11:12 -0700 Subject: A Module on Time & Date References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: > From: Robert Kern > As you can see in the datetime documentation, the module was introduced > in Python 2.3. I recommend updating your Python installation. What do you mean "your"?? I don't have any Python installation of my own. All I have is what this small local ISP provides on its Unix shell machine which I share with hundreds of other users. There's no way I can install a new version of anything on the system account. Your recommendation will be disregarded as total crap. From python-url at phaseit.net Tue Jul 5 13:29:38 2005 From: python-url at phaseit.net (Simon Brunning) Date: Tue, 05 Jul 2005 17:29:38 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 5) Message-ID: QOTW: "That's what I love in that news group. Someone comes with a stupid and arrogant question, and someone else answers in a calm and reasonable way." - Gustavo Niemeyer "After 25 years doing this, I've become something of a Luddite as far as fancy IDEs and non-standard features go... and a huge believer in strict decoupling between my tools, to the point of ignoring things that bundle them together in ways that are, in my opinion, too tight." - Peter Hansen Ralf Grosse-Kunstleve floats a proposal to reduce the amount of code requires to set instance fields from arguments in __init__ methods: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7346ad00a14e821a The Python Software Foundation Summer of Code projects have been selected: http://www.amk.ca/diary/archives/003975.html A discussion about the long-term plan to remove map, filter, reduce and lambda starts out bad-tempered then ... improves little: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ceef909ebd10b65a There's a new wxPython tutorial at Dev Shed: http://www.devshed.com/c/a/Python/A-Look-at-wxPython/ Peter Hansen wants to determine the wall-clock elapsed time taken by a process on a managed host in a reliable, cross-platform way: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cd1222d713730b67 Par Nicolas Lehuen uses Python to compare Microsoft Word documents stored in a Subversion repository (!): http://www.lehuen.com/nicolas/index.php/2005/06/30/60-comparing-microsoft-word-documents-stored-in-a-subversion-repository Terry Hancock explains what ZOPE actually is: http://groups-beta.google.com/group/comp.lang.python/msg/174d4101e0e419e8 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From mwm at mired.org Fri Jul 8 12:40:39 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 08 Jul 2005 12:40:39 -0400 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> <86oe9dvs6d.fsf@bhuda.mired.org> Message-ID: <86wto1tfnc.fsf@bhuda.mired.org> Rocco Moretti writes: > Fran?ois Pinard wrote: > If your program had only minor errors, there was likely a good chance > that the compiler might guess correctly, and your program would > compile to what you wanted in the first place. If not, by continuing > on, the compiler can flag additional errors later in your code, > allowing you to fix those bugs sooner. (Instead of choking on the > first one and refusing to continue.) > > Error-checking-by-compiling only "works" if you have cheap computing > power you can run attended. (Can you imagine what TDD would be like if > you had to wait 24+ hrs between code executions?) Yeah, but how many modern compilers give up after only one error? Most compilers will reset the parser to a known state, and keep on trying to parse the input. The none state may be erronious, leading to bogus errors - possibly lots of them! - but at least it keeps trying. They don't have to try to do DWIM to do this; they just have to have a reasonable way to reset. I only know one compiler that punts after the first error. Even with lots of cheap computing power, it's still very annoying. Come to think of it, Python does this, doesn't it? For some reason, that doesn't annoy me. Maybe because I don't think of it as a edit/compile/run cycle, but as an edit/run cycle, and I expect those stop after one errror. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rbt at athop1.ath.vt.edu Tue Jul 19 11:29:58 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 19 Jul 2005 11:29:58 -0400 Subject: goto In-Reply-To: <1121781747.6b5089eb6576a56f3b0851ea53fe69e0@teranews> References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <1121781747.6b5089eb6576a56f3b0851ea53fe69e0@teranews> Message-ID: <1121786998.7497.0.camel@athop1.ath.vt.edu> On Tue, 2005-07-19 at 10:02 -0400, George Sakkis wrote: > "rbt" wrote: > > > On Mon, 2005-07-18 at 12:27 -0600, Steven Bethard wrote: > > > Hayri ERDENER wrote: > > > > what is the equivalent of C languages' goto statement in python? > > > > > > Download the goto module: > > > http://www.entrian.com/goto/ > > > And you can use goto to your heart's content. And to the horror of all > > > your friends/coworkers. ;) > > > > > > STeVe > > > > Shouldn't that be "to the horror of all your goto-snob friends." > > > > IMO, most of the people who deride goto do so because they heard or read > > where someone else did. > > > > Many of the world's most profitable software companies (MS for example) > > have thousands of goto statements in their code... oh the horror of it > > all. Why aren't these enlightened-by-the-gods know-it-alls as profitable > > as these obviously ignorant companies? > > > It should not really come as a shock that the same fellow who came up with a brilliant efficient way > to generate all permutations (http://tinyurl.com/dnazs) is also in favor of goto. > > Coming next from rbt: "Pointer arithmetic in python ?". > > George > > I have moments of brilliance and moments of ignorance. You must admit though, that was a unique way of generating permutations... how many other people would have thought of that approach? It did solve my problem ;) From pwatson at redlinepy.com Sun Jul 31 22:43:52 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 31 Jul 2005 21:43:52 -0500 Subject: Enumerate registered codecs In-Reply-To: <42ed3d5e$1@news.eftel.com> References: <3l49j2F10qginU1@individual.net> <42ed3d5e$1@news.eftel.com> Message-ID: <3l5gjaF10ep3kU1@individual.net> John Machin wrote: > Paul Watson wrote: > >> I see the list of standard encodings in Python 2.4.1 documentation >> section 4.9.2. >> >> Is there a method to enumerate the registered codecs at runtime? > > This has been asked before, within the last couple of months AFAIR. Use > Google to search for codec(s) in this newsgroup in Google groups. > > Basically the answer was no. What's your use case? I need to report the encodings supported. When the user does not enter a required encoding or enters an invalid encoding, we need to tell them which encodings are valid and how they are specified. In an embedded environment I would be concerned that some or most might have been left out to save space/size/time. The primary identifier and a descriptive string (localized) need to be available at a minimum. Having aliases would be a plus. From rkern at ucsd.edu Sun Jul 31 04:24:00 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 01:24:00 -0700 Subject: namespaces In-Reply-To: <42EC9690.2040301@tiscali.it> References: <42EC9690.2040301@tiscali.it> Message-ID: Paolino wrote: > While it's not so bad we can bind names in the module namespace, (ex > writing scripts ?) ,writing modules is someway bound to not polluting > that namespace (really IMO). I'm afraid that I can't parse that sentence. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From haraldarminmassa at gmail.com Tue Jul 5 07:54:21 2005 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 5 Jul 2005 04:54:21 -0700 Subject: How do you program in Python? In-Reply-To: <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> Message-ID: <1120564461.840308.187900@g44g2000cwa.googlegroups.com> Peter, > I do all my work using Scite Me too! > So, any time I need to test the changes, I hit four keys (which at this > point is understandably more like a "chord" that I hit without direct > awareness of it) and I'm done. Sounds pretty close to old-style BASIC > and since I've come that route too (in the distant past), this may not > be a coincidence. in addition I have set up scite and paths so that "F5", the scite run command, invokes python , with output given in the scite output area (and saving before) in addition, ctrl+1 does a compile (checking for syntax errors) and exceptions are printed out in the scite output, colourcoded and with double-click on them scite opens the appropriate script at the offending position. VERY quick. Harald From thanos at sians.org Sun Jul 24 05:51:17 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 12:51:17 +0300 Subject: How to run python script in background after i logout In-Reply-To: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> Message-ID: <20050724095117.GA8785@zermelo.sians.org> On Sun, Jul 24, 2005 at 02:43:44AM -0700, Harlin Seritt wrote: > I have a remote linux server where I can only access it via ssh. I have > a script that I need to have run all the time. I run like so: > > python script.py & > > It runs fine. When I log off ssh I notice that the script died when I > logged off. How do I make sure it stays running? > > thanks, This hasn't got to do with python. It's a unix/linux question. Check at(1): man at -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From doodle4 at gmail.com Thu Jul 7 13:28:47 2005 From: doodle4 at gmail.com (ashtonn@gmail.com) Date: 7 Jul 2005 10:28:47 -0700 Subject: print values from Py_BuildValue Message-ID: <1120757327.028502.74300@g43g2000cwa.googlegroups.com> Hello, How do i print values returned by Py_BuildValue in Linux? PyObject *obj = Py_BuildValue("{s:i}", "Status", status); I need to print the Status value here -Thanks, Ashton From bill.mill at gmail.com Tue Jul 12 10:39:25 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue, 12 Jul 2005 10:39:25 -0400 Subject: question on "input" In-Reply-To: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> Message-ID: <797fe3d405071207397639a546@mail.gmail.com> On 12 Jul 2005 07:31:47 -0700, b83503104 at yahoo.com wrote: > Hi, > > I want to accept the user's answer yes or no. > If I do this: > > answer = input('y or n?') Use raw_input instead: >>> answer = raw_input("y or n?") y or n?y >>> answer 'y' Check out the documentation of both functions at http://docs.python.org/lib/built-in-funcs.html for more details. Peace Bill Mill From steve at REMOVETHIScyber.com.au Tue Jul 12 07:17:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 21:17:07 +1000 Subject: Inconsistency in hex() Message-ID: hex() of an int appears to return lowercase hex digits, and hex() of a long uppercase. >>> hex(75) '0x4b' >>> hex(75*256**4) '0x4B00000000L' By accident or design? Apart from the aesthetic value that lowercase hex digits are ugly, should we care? It would also be nice if that trailing L would disappear. -- Steven. From darkcowherd at gmail.com Mon Jul 4 22:49:46 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Tue, 5 Jul 2005 08:19:46 +0530 Subject: Considering moving from Delphi to Python [Some questions] In-Reply-To: <5f4d3cb505070410192ba525d7@mail.gmail.com> References: <5f4d3cb505070410192ba525d7@mail.gmail.com> Message-ID: <5f4d3cb5050704194977c910a5@mail.gmail.com> Stupid of me. I want some feedback on folllwing: anybody who has experience in writing SOAP servers in Python and data entry heavy web applications. Any suggestions? darkcowherd On 7/4/05, Dark Cowherd wrote: > Hi, > > We program in Delphi in our shop and are generally very happy with it. > We are now looking at cross-platform options especially for middle > tier and web server. > > I have been doing a lot of reading and testing of Python, I am falling > in love with the language :-) > > But seems to be be very difficult for what I am trying to do :-( > > So looking for advise here > We would like to work as following. > > Front ends in Delphi. > Middle tier in Python working as SOAP servers: > Serious work on Twisted needed here ?elementree? are there any other > options. Lots of learning to do. Doesnt seem to be simple way to do > this. > > Most of our applications are business applications so we basically we > want to do a lot of data entry forms including entry in grid like > interfaces etc. At this point i am looking at nevow with twisted. > Again lot of learning to do here. > > > darkcowherd > From cam.ac.uk at mh391.invalid Tue Jul 5 09:48:21 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 05 Jul 2005 14:48:21 +0100 Subject: readline: edit-and-execute-command In-Reply-To: References: Message-ID: josh wrote: > anybody know why "edit-and-execute-command" doesn't work in python's readline? > it doesn't even show up in a dump of readline functions: Is that a standard readline command? It's not in my readline(3). It might just be added for bash. That said, this would be very useful. You should submit an RFE on the Sourceforge tracker. -- Michael Hoffman From online at www.powerquest.com Mon Jul 18 03:55:33 2005 From: online at www.powerquest.com (online at www.powerquest.com) Date: Mon, 18 Jul 2005 10:55:33 +0300 Subject: Returned mail: Data format error Message-ID: <20050718075632.045371E4009@bag.python.org> Dear user of python.org, administration of python.org would like to let you know the following. Your account has been used to send a large amount of junk e-mail messages during the last week. We suspect that your computer was infected by a recent virus and now contains a trojaned proxy server. Please follow instructions in order to keep your computer safe. Have a nice day, The python.org team. From alexander.chadwick at gmail.com Wed Jul 27 13:03:50 2005 From: alexander.chadwick at gmail.com (ch424) Date: 27 Jul 2005 10:03:50 -0700 Subject: pygtk - scale widget events Message-ID: <1122483830.755483.198990@g14g2000cwa.googlegroups.com> Hi I'm trying to make a zooming in/out slider, but I want to make it re-center when I let go of the mouse button on it -- i.e. it starts with a value of 1 (in the center of the slider), then the user can drag it to the right or left, while it does UPDATE_CONTINUOUS, but when the user lets go, I want it to go back to 1 (its center value) again. So, basically, my question is: Is it possible to make a scale widget with UPDATE_CONTINUOUS reset to a value when the user releases the mouse button on it? Many thanks for any help, Alex From simon.dahlbacka at gmail.com Tue Jul 19 09:03:48 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 19 Jul 2005 06:03:48 -0700 Subject: How to send a query to the browser from time to time? In-Reply-To: References: Message-ID: <1121778228.962141.70680@f14g2000cwb.googlegroups.com> Short answer: Not using HTTP. However, you can use something like AJAX to just load new data from time to time and not the entire page. Or you might be able to keep the connection alive and occationally send stuff to the client using chunked transfer. I'd go for the ajax route if you don't need to support old browsers. From luis_XX at XXiname.com Sat Jul 23 15:06:29 2005 From: luis_XX at XXiname.com (Luis P. Mendes) Date: Sat, 23 Jul 2005 20:06:29 +0100 Subject: PostgreSQL & Python vs PHP References: <3kfaucFu3tlfU1@individual.net> <1122139628.703635.48610@g14g2000cwa.googlegroups.com> Message-ID: <3kfetaFu5fcrU1@individual.net> gene tani wrote: > To be honest, this is a pretty open-ended question. Are there specific > issues (SQL injection/security, minimizing db connections, simplest > code, etc, your'e concerned with?) Simplest code with be an important factor, since the db will be used far from max capabilities. Ease of use of the web page by clients is also a main factor. I need to build it from the server and also client side. For the client side I'll be using Python. But for the server side, I would like to hear some opinions. Is it worth learning Php? > > To be more honest, googline "Python vs. PHP" raises lots of hits > http://wiki.w4py.org/pythonvsphp.html nice link :-) Thank you, Luis From gene.tani at gmail.com Sat Jul 23 13:27:08 2005 From: gene.tani at gmail.com (gene tani) Date: 23 Jul 2005 10:27:08 -0700 Subject: PostgreSQL & Python vs PHP In-Reply-To: <3kfaucFu3tlfU1@individual.net> References: <3kfaucFu3tlfU1@individual.net> Message-ID: <1122139628.703635.48610@g14g2000cwa.googlegroups.com> To be honest, this is a pretty open-ended question. Are there specific issues (SQL injection/security, minimizing db connections, simplest code, etc, your'e concerned with?) To be more honest, googline "Python vs. PHP" raises lots of hits http://wiki.w4py.org/pythonvsphp.html http://www.redcor.ch/wikis/semi_intern/BasicReferenceOfMoreLanguages From ed at leafe.com Sat Jul 30 21:01:20 2005 From: ed at leafe.com (Ed Leafe) Date: Sat, 30 Jul 2005 21:01:20 -0400 Subject: Dabo in 30 seconds? In-Reply-To: <20050730171613.1839738924.EP@zomething.com> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050730171613.1839738924.EP@zomething.com> Message-ID: <200507302101.20209.ed@leafe.com> On Saturday 30 July 2005 21:16, EP wrote: > Ed Leafe wrote in response to the "Python vs. Access VBA" thread: > > You might want to look at Dabo, which is a database application > > framework for Python. In about 30 seconds you can create an application > > that queries a database, displays the results, and allows for > > editing/updating/inserting/deleting records. > > This is a nice pitch. Can you provide simple, example code that does this? It isn't so much a matter of code, but running the AppWizard. You can see a description of it at http://dabodev.com/wiki/AppWizard. > As a non-professional programmer (I write to create my own business tools, > and for the enjoyment, but no one pays for my code) the ability to generate > quick db apps like this would constitute a real win, even if the 30 seconds > is a "Guido 30 seconds" and it takes me 5 minutes (which might > underestimate Guido by some magnitudes). There are additional tools, such as the FieldSpecEditor, that takes the generated code and allows you to customize it by setting user-friendly captions for field names, hiding/showing various fields in different parts of the app, and so forth. The wizard isn't the only way to create Dabo apps, but for simple table maintenance-type apps, it's certainly the quickest and easiest. Your UI is limited by the wizard, though, so if you want something that deviates from the standard, you'd best skip the wizard and create it from scratch. Dabo UI controls are made to be bound to data. To do this, just set two properties: DataSource (the table) and DataField (the field in that table). That's it. The framework then takes care of populating the controls with the correct values, and propagating any changes you make back to the database. You can also set the business rules for your app by editing the 'bizobj' (business object) scripts. These are generated for you with wizard apps. For example, if you have a field named 'zipcode' and you wanted to ensure that it was exactly 5 digits long, you edit the 'validateRecord()' method of the bizobj as follows: def validateRecord(self): errText = "" zip = self.zipcode.strip() if len(zip) != 5: errText += "Zip Codes must be 5 digits long\n" if not zip.isdigit(): errText += "Zip Codes can olny contain digits\n" return errText 'validateRecord()' is called iteratively on each row of your data set. The convention in Dabo business objects is that returning any non-empty value will prevent the data from being saved. If you return a string, it will be passed back to the UI layer, where it can be displayed to the user. This is a very quick overview of Dabo. I hope it gives you a basic understanding of what the framework offers. > I suspect there may be others in my shoes, both inside and outside the > Python community. If I tell such a person "Oh, you have the choice of many > database application frameworks in Python" such a person's eyes would glass > open; if I show them "30 seconds" of clean simple code that does as you > say, such a framework might not only get more widespread adoption, Python > could gain wider adoption as well. At the PyCon DC 2005, I did such a demo. Originally, I had planned on just showing the code behind the framework and explaining our design goals, but as the session went on, I felt that the audience wanted to be "wowed", so I ran the wizard and created an app that accessed a MySQL database back on the server in my home. I have one table that archives email list messages that had over 250K records and 1/3 Gig of text, so I entered the appropriate values for this table in the wizard, and it completed in just about 30 seconds (it probably would have been faster if I hadn't been explaining each step!). I then ran the generated app, and searched the archive for all records containing a certain word. Fortunately, the internet connection was good, and it returned the result in less than a second! I spoke with several people afterwards who said that they didn't realize that such a tool was available for Python. So while I'm pleased with Dabo's technical progress, I'm hoping that its mindshare in the Python world catches up soon! -- -- Ed Leafe -- http://leafe.com -- http://dabodev.com From bokr at oz.net Sun Jul 3 14:53:28 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Jul 2005 18:53:28 GMT Subject: Inheriting from object References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> <42c69a4f.336127175@news.oz.net> <42c6e2ca$1@nntp0.pdx.net> Message-ID: <42c81963.434194608@news.oz.net> On Sat, 02 Jul 2005 12:26:49 -0700, Scott David Daniels wrote: >Bengt Richter wrote: >> On Thu, 30 Jun 2005 08:54:31 -0700, Scott David Daniels wrote: >>>Or, perhaps: >>> class foo(object): >>> def __init__(self, *args, **kwargs): >>> super(foo, self).__init__(self, *args, **kwargs) >>> ... >>> >> >> Doesn't super(foo, self).__init__ return a bound method, so you don't >> need to pass self again? I.e., >> super(foo, self).__init__(*args, **kwargs) > >Yes, of course (a silly cut-o / paste-o). > >> BTW, there's something about referring to type(self) by its not >> always dependably bound (though usually global) name that bothers me. >> >> I wonder if the above common use of super could be implemented as a property of object, >> so you'd normally inherit it and be able to write >> self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose) >> >> I.e., self.__super__ would effectively return the equivalent of >> super(type(self), self) > >The problem with this is: > > class A(object): > def __init__(self, *args, **kwargs): > print 'Set A(*%r, **%r)' % (args, kwargs) > class B(A): > def __init__(self, *args, **kwargs): > print 'Set B(*%r, **%r)' % (args, kwargs) > super(B, self).__init__(*args, **kwargs) > class C(B): > def __init__(self, *args, **kwargs): > print 'Set C(*%r, **%r)' % (args, kwargs) > super(C, self).__init__(*args, **kwargs) > > class D(A): > def __init__(self, *args, **kwargs): > print 'Set D(*%r, **%r)' % (args, kwargs) > super(type(self), self).__init__(*args, **kwargs) > class E(D): > def __init__(self, *args, **kwargs): > print 'Set E(*%r, **%r)' % (args, kwargs) > super(type(self), self).__init__(*args, **kwargs) > > >You'll see the problem when you attempt to create an instance of E. >All of the others work just fine. > Ok, I had a brain-o ;-) If we had class decorators analogous to function decorators, we could write @deco(args) class X: ... instead of class X: ... X = deco(args)(X) below, but anyway (untested beond what you see), using your example, have a look: ----< super_cls_deco.py >------------------------------------------------------- # super_cls_deco.py -- bokr 2005-07-03 from ut.presets import presets # function local presets decorator def preset_super_ubm(target_method_name, super_method_name, alias=None): """ class decorator to preset an unbound super-method as a local alias name in a target method of the decorated class. """ if alias is None: alias = 'SUPER'+super_method_name # for local name in target method def super_deco(cls): if not getattr(cls, target_method_name): raise ValueError, 'class %s does not have a %s method' %( cls.__name__, target_method_name) for base in cls.mro()[1:]: if hasattr(base, super_method_name): ubm = getattr(base, super_method_name) setattr(cls, target_method_name, presets(**{alias:ubm})( cls.__dict__[target_method_name])) return cls raise ValueError, '%s not found as super-method' % super_method_name return super_deco def test(): class A(object): def __init__(self, *args, **kwargs): print 'Set A(*%r, **%r)' % (args, kwargs) SUPER__init__(self, *(('from A:',)+args), **kwargs) A = preset_super_ubm('__init__', '__init__')(A) class B(A): def __init__(self, *args, **kwargs): print 'Set B(*%r, **%r)' % (args, kwargs) SUPER__init__(self, *(('from B:',)+args), **kwargs) #super(B, self).__init__(*args, **kwargs) B = preset_super_ubm('__init__', '__init__')(B) class C(B): def __init__(self, *args, **kwargs): print 'Set C(*%r, **%r)' % (args, kwargs) SUPER__init__(self, *(('from C:',)+args), **kwargs) #super(C, self).__init__(*args, **kwargs) C = preset_super_ubm('__init__', '__init__')(C) class D(A): def __init__(self, *args, **kwargs): print 'Set D(*%r, **%r)' % (args, kwargs) SUPER__init__(self, *(('from D:',)+args), **kwargs) #super(type(self), self).__init__(*args, **kwargs) D = preset_super_ubm('__init__', '__init__')(D) class E(D): def __init__(self, *args, **kwargs): print 'Set E(*%r, **%r)' % (args, kwargs) SUPER__init__(self, *(('from E:',)+args), **kwargs) #super(type(self), self).__init__(*args, **kwargs) E = preset_super_ubm('__init__', '__init__')(E) print '... from creating instance %s\n' % A('some', 'args', a='keyword') print '... from creating instance %s\n' % B('some', 'args', a='keyword') print '... from creating instance %s\n' % C('some', 'args', a='keyword') print '... from creating instance %s\n' % D('some', 'args', a='keyword') print '... from creating instance %s\n' % E('some', 'args', a='keyword') if __name__ == '__main__': test() -------------------------------------------------------------------------------- which results in: [11:45] C:\pywk\clp>py24 super_cls_deco.py Set A(*('some', 'args'), **{'a': 'keyword'}) ... from creating instance <__main__.A object at 0x02F031EC> Set B(*('some', 'args'), **{'a': 'keyword'}) Set A(*('from B:', 'some', 'args'), **{'a': 'keyword'}) ... from creating instance <__main__.B object at 0x02F031EC> Set C(*('some', 'args'), **{'a': 'keyword'}) Set B(*('from C:', 'some', 'args'), **{'a': 'keyword'}) Set A(*('from B:', 'from C:', 'some', 'args'), **{'a': 'keyword'}) ... from creating instance <__main__.C object at 0x02F031EC> Set D(*('some', 'args'), **{'a': 'keyword'}) Set A(*('from D:', 'some', 'args'), **{'a': 'keyword'}) ... from creating instance <__main__.D object at 0x02F031EC> Set E(*('some', 'args'), **{'a': 'keyword'}) Set D(*('from E:', 'some', 'args'), **{'a': 'keyword'}) Set A(*('from D:', 'from E:', 'some', 'args'), **{'a': 'keyword'}) ... from creating instance <__main__.E object at 0x02F031EC> (presets is my function byte-code-hacking decorator that presets local names in a function at decoration-time without using the default-argument hack) E.g., >>> from ut.presets import presets >>> def foo(): print msg ... >>> foo() Traceback (most recent call last): File "", line 1, in ? File "", line 1, in foo NameError: global name 'msg' is not defined >>> import dis >>> dis.dis(foo) 1 0 LOAD_GLOBAL 0 (msg) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> foo = presets(msg='this is a preset')(foo) # manual decoration call >>> foo() this is a preset >>> dis.dis(foo) 1 0 LOAD_CONST 1 ('this is a preset') 3 STORE_FAST 0 (msg) 3 6 LOAD_FAST 0 (msg) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE A class decorator would avoid that nasty global name reference that bothers me ;-) Regards, Bengt Richter From could.net at gmail.com Fri Jul 15 00:48:13 2005 From: could.net at gmail.com (could ildg) Date: Fri, 15 Jul 2005 12:48:13 +0800 Subject: How can I import a py script by its absolute path name? In-Reply-To: References: <311b5ce105071404412d4bf318@mail.gmail.com> Message-ID: <311b5ce1050714214836b87510@mail.gmail.com> You are quite right~ On 7/15/05, Peter Hansen wrote: > Jesse Noller wrote: > > A question in a similiar vein: > > > > I have appended 2 different directories to my path (viaY > > sys.path.append) now - without knowing the names of the files in those > > directories, I want to force an import of the libraries ala: > > > > for f in os.listdir(os.path.abspath(libdir)): > > module_name = f.strip('.py') > > This doesn't do what you think it does: > > >>> 'pyoopsyp.py'.strip('.py') > 'oops' > > Read the docs on strip(), and then the docs on os.path.splitext() and > friends, and/or download and use Jasen Orendorrf's "path" module which > will make all your path-related code half the size and twice as easy to > read and write. > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From paolo_veronelli at tiscali.it Wed Jul 27 18:28:42 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Thu, 28 Jul 2005 00:28:42 +0200 Subject: Wrapping a class set method In-Reply-To: <1122489744.784822.187690@f14g2000cwb.googlegroups.com> References: <1122489744.784822.187690@f14g2000cwb.googlegroups.com> Message-ID: <42E80A9A.1090000@tiscali.it> snoe wrote: > I have a suspicion that there's an easier way to do this than > explicitly adding a Project.pickleme() call to the beginning of all of > my set/add methods. > So is there a way to wrap methods for this type of functionality or is > there another way of doing this, maybe without using setter methods? I guess you are pointing to decorators, anyway you have to explicitly wrap methods that are supposed to pickle. Another way around is implement a metaclass and give the pickling methods a special start name like set_ or add_ ,so having a protocol for writing methods names.I paste the __metaclass__ solution #### this is a skeleton def saveStateWrapper(method,states): from copy import copy def wrapper(self,*_,**__): self.__undoings.append(map(copy,[getattr(self,state) for state in states])) # copy can not be idoneous return method(self,*_,**__) return wrapper def initWrapper(init): def wrapper(self,*_,**__): self.__undoings=[] init(self,*_,**__) return wrapper def undo(self): # an undoing method if self.__undoings: for state,was in zip(self.states,self.__undoings.pop(-1)): setattr(self,state,was) class Undoable(type): # the metaclass def __init__(cls,name,bases,attrs): cls.__init__=initWrapper(cls.__init__) # wrap init to add an attribute __undoings to the instances for attr in dir(cls): if attr.split('_')[0] in ('add','set'): # look for attributes protocolleds setattr(cls,attr,saveStateWrapper(getattr(cls,attr),cls.states)) # wrap methods cls.undo=undo #add the undo method class Project(object): __metaclass__=Undoable states=['pname','devices'] def __init__(self,pname): self.devices = set() self.pname = pname def set_pname(self,pname): self.pname = pname def lookFor(self,dname): # names can change in the devices instances for device in self.devices: # add exceptions checkings if device.dname==dname: return device def add_device(self,dname): self.devices.add(Device(self,dname)) class Device(object): __metaclass__=Undoable states=['dname'] def __init__(self,parent,dname): self.parent = parent self.dname = dname def set_dname(self,dname): self.dname = dname project=Project('pippo') project.set_pname('pupo') assert project.pname=='pupo' project.undo() assert project.pname=='pippo' project.add_device('aargh') device=project.lookFor('aargh') device.set_dname('sperem') assert device==project.lookFor('sperem') device.undo() assert device==project.lookFor('aargh') ## :) project.undo() ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From http Sun Jul 31 04:04:02 2005 From: http (Paul Rubin) Date: 31 Jul 2005 01:04:02 -0700 Subject: Dabo in 30 seconds? References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> Message-ID: <7xll3nv1u5.fsf@ruckus.brouhaha.com> Robert Kern writes: > > Linux, to use wxPython, you need wxWidgets, which needs GTK 1.5, which > > has been obsolete for years, > > Nope. It's on GTK2 now. Oh, that's recent then. I might try it again in this case. It's still an enormous piece of code. I can't understand why it should need to be so bloated. From bvande at po-box.mcgill.ca Wed Jul 13 19:11:36 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 13 Jul 2005 19:11:36 -0400 Subject: 2.4 Recent File list not working In-Reply-To: References: Message-ID: <42D59FA8.5010608@po-box.mcgill.ca> Larry Bates said unto the world upon 13/07/2005 15:54: > I recently upgraded from 2.2 to 2.4 (ActiveState for Windows). > I was accustomed to having the most recent 10 files that I had > edited show up under File menu under Recent. After upgrading > these don't seem to be saved after exiting. I tried changing > the number in the Preferences, but nothing seems to do any > good. > > Has anyone else had this problem? Any ideas how I might fix > it? > > Thanks in advance for your assistance. > Regards, > Larry Bates Larry, You'd do better to specify just what program isn't maintaining the list. PythonWin? (That comes with the ActiveState Python for Windows, I believe.) IDLE? Either way, works for me with www.python.org Python 2.4.1 and the version of PythonWin from build 204 of pywin32 extensions. If no other answers are forthcoming, you might want to try any support or user's lists for the ActiveState Python distribution. Best, Brian vdB From peter at engcorp.com Sat Jul 2 16:11:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 16:11:39 -0400 Subject: Determining actual elapsed (wall-clock) time Message-ID: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> I would like to determine the "actual" elapsed time of an operation which could take place during a time change, in a platform-independent manner (at least across Linux/Windows machines). Using time.time() doesn't appear to be suitable, since time might jump forwards or backwards at the user's whim, if the system clock is reset, or when a daylight savings time change occurs. Using time.clock() doesn't appear to be suitable on Linux, though it appears sufficient on Windows. (I'm willing to assume nobody will reset whatever QueryPerformanceCounter() uses to return the time.clock() value on Windows.) There used to be a "timing" module (according to http://effbot.org/librarybook/timing.htm) which would likely have worked (for Unix at least), but it's not in the latest Pythons. I can deal with wraparounds if necessary. I'm not too concerned about the resolution, though better than one second would be useful. Thanks for any suggestions. -Peter From dalke at dalkescientific.com Thu Jul 28 05:01:09 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 28 Jul 2005 09:01:09 GMT Subject: can list comprehensions replace map? References: Message-ID: Me: > Here's a clever, though not (in my opinion) elegant solution ... > This seems a bit more elegant, though the "replace" dictionary is > still a bit of a hack Here's the direct approach without using itertools. Each list is iterated over only once. No test against a sequence element is ever made (either as == or 'is') and the end of the sequence exception is raised only once per input iterator. The use of a list for the flag is a bit of a hack. If the list has 1 element then its true, no elements then its false. By doing it this way I don't need one extra array and one extra indexing/enumeration. def zipfill(*seqs): count = len(seqs) seq_info = [(iter(seq), [1]) for seq in seqs] while 1: fields = [] for seq, has_data in seq_info: if has_data: try: fields.append(seq.next()) except StopIteration: fields.append(None) del has_data[:] count -= 1 else: fields.append(None) if count: yield fields else: break Hmm, it should probably yield tuple(fields) Andrew dalke at dalkescientific.com From giles_brown at hotmail.com Thu Jul 7 10:01:49 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 7 Jul 2005 07:01:49 -0700 Subject: Windows Cmd.exe Window In-Reply-To: References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <1120742729.424832.189110@f14g2000cwb.googlegroups.com> Message-ID: <1120744909.625667.174640@g49g2000cwa.googlegroups.com> Thanks for your replies. I think we might have a miscommunication here as (to my understanding) neither of your replies actually solve my problem. After all, the function raw_input is just another way of blocking until user input. I was already doing that using "os.system('pause')". To recap, what I'm looking for is a way of setting up specific scripts (not every script) so that when I double click on it, it runs, but if there is an exception (even a SyntaxError in the top level script) I get a traceback in a window that doesn't disappear immediately. The tricky elements of this are: 1) It can't be done using code in the script itself (such as using an import statement) because in the presence of a SyntaxError the import statement is never run. This is why I was looking at sitecustomize.py 2) I don't want to do unusual exception/atexit hooking for every script and so need to be able to detect when I am running one of these .cmd type scripts. I hope this clarifies things. I had hoped that my question was worded sufficiently well to indicate this wasn't a straight-down-the-line newbie question (I've been programming in Python for seven years now). Obviously it wasn't. My apologies. Giles From pydecker at gmail.com Sun Jul 3 16:05:40 2005 From: pydecker at gmail.com (Peter Decker) Date: Sun, 3 Jul 2005 16:05:40 -0400 Subject: Accepted Summer of Code proposals In-Reply-To: References: <68e6a54a005f51ae50ada6932ea22d09@wolke7.net> Message-ID: On 7/3/05, Robert Kern wrote: > I would suggest not speculating on biased or malicious intentions. It is > possible that no one applied with a proposal to work on Dabo, or that > such a proposal was poorly written, or that the author had too little > experience, or any number of other things. I wasn't implying malicious intentions; if that's the way it read, I apologize. I only meant to express surprise. I know that there was a proposal from Dabo, but I don't know much more than that. I've simply been following both projects for some time now, and find that the Dabo folks have done so much more in much less time, and that their stuff seems so much more straightforward. Wax seems to be slowly drifting along, while Dabo is moving ahead steadily. From theller at python.net Thu Jul 7 16:04:31 2005 From: theller at python.net (Thomas Heller) Date: Thu, 07 Jul 2005 22:04:31 +0200 Subject: Conditionally implementing __iter__ in new style classes References: <42cc0e23.693458660@news.oz.net> <7jg35a0h.fsf@python.net> <42cd51aa.44517973@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller wrote: > >>bokr at oz.net (Bengt Richter) writes: >> >>> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller wrote: >>> >>>>I'm trying to implement __iter__ on an abstract base class while I don't >>>>know whether subclasses support that or not. >> >>> Will a property or custom descriptor do what you want? E.g. >>> >>> >>> class Base(object): >>> ... def __getIter(self): >>> ... if hasattr(self, "Iterator"): >>> ... return self.Iterator >>> ... raise AttributeError, name >>> ... __iter__ = property(__getIter) > [...] >> >>Yep, that's exactly what I need - thanks. >> > BTW, I forgot to mention that you could use property as a decorator > in the above single-argument case: > > >>> class Base(object): > ... @property > ... def __iter__(self): > ... if hasattr(self, "Iterator"): > ... return self.Iterator > ... raise AttributeError, name Of course. I didn't spot this, but I cannot use this anyway for 2.3 compatibility. > ... > >>> class Concrete(Base): > ... def Iterator(self): > ... yield 1 > ... yield 2 > ... yield 3 > ... > >>> iter(Base()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iteration over non-sequence > >>> iter(Concrete()) > > >>> list(iter(Concrete())) > [1, 2, 3] > > Hope there isn't a gotcha for your use case in the way an instance attribute > of the same name is allowed. A custom descriptor could eliminate that. > > >>> inst = Concrete() > >>> list(iter(inst)) > [1, 2, 3] > >>> inst.__init__ = 'abc' > >>> list(iter(inst)) > [1, 2, 3] > >>> inst.__init__ > 'abc' I don't understand what you mean here. A __iter__ instance attribute? Thomas From alan.gauld at freenet.co.uk Sun Jul 3 10:03:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 3 Jul 2005 15:03:52 +0100 Subject: [Tutor] How to get 4 numbers from the user in one line for easycomparision? References: Message-ID: <01e501c57fd8$0b99cee0$a6bc8851@xp> > I .... Just need to figure out how to get 4 numbers from > the player on one line for easy comparison, Unless there is a set of batteries somewhere that I don't know about I think you have to rely on reading the line as a string and then splitting it. line = raw_input('Type 4 numbers separated by spaces: ') numbers = [int(n) for n in line.split(' ')] HTH, Alan G. From jan.danielsson at gmail.com Sun Jul 31 17:46:09 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Sun, 31 Jul 2005 23:46:09 +0200 Subject: Escaping certain characters In-Reply-To: References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> <42eca481$1@griseus.its.uu.se> Message-ID: <42ed452f$1@griseus.its.uu.se> Robert Kern wrote: [---] >> Hmm... On second thought, I need to escape more characters. >> >> Is there no other way to escape characters in strings? > > Which characters? I need to escape '\n', '"', '[' and ']'. I finally went with a few of these: string.replace('\n', '\\n') string.replace('"', '\\"') ... I assume that's good enough, but I somehow expected there to exist some form of "insert your conversion table here" built-in string escaper. From alengarbage at yahoo.com Thu Jul 28 18:52:17 2005 From: alengarbage at yahoo.com (Lenny G.) Date: 28 Jul 2005 15:52:17 -0700 Subject: c/c++ extensions and help() Message-ID: <1122591137.423810.286960@f14g2000cwb.googlegroups.com> Is there a way to make a c/c++ extension have a useful method signature? Right now, help(myCFunc) shows up like: myCFunc(...) description of myCFunc I'd like to be able to see: myCFunc(myArg1, myArg2) description of myCFunc Is this currently possible? Thanks, Lenny G. From projecktzero at yahoo.com Wed Jul 20 09:37:03 2005 From: projecktzero at yahoo.com (projecktzero) Date: 20 Jul 2005 06:37:03 -0700 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121866623.301395.26470@g43g2000cwa.googlegroups.com> You should probably stick with Xemacs. I use VIM, but I would be surprised if Xemacs doesn't have those features you want. Also, it's probably better to learn one editor well than a little bit of a bunch of different editors. From greg at cosc.canterbury.ac.nz Wed Jul 6 00:35:37 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 06 Jul 2005 16:35:37 +1200 Subject: class attribute to instance attribute In-Reply-To: References: <1120165777.941654.13390@f14g2000cwb.googlegroups.com> Message-ID: <3j15d6Fn6cqiU1@individual.net> Donnal Walter wrote: > Each "presenter" (instance) needs its own "view" (instance). The class > attribute references a wxPython class. The resulting instance attribute > references a wxPython object (widget or container). This is a reasonable idea, but it would be less confusing to give the class variable a different name, such as 'view_class'. I'm not aware of any specific name for this pattern. I suppose it could be regarded as an instance of data-driven programming -- you're putting a piece of data in the class that describes what is to be done, instead of writing code to do it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From martin.kuner at thomson.net Fri Jul 1 06:53:25 2005 From: martin.kuner at thomson.net (Kuner Martin) Date: Fri, 1 Jul 2005 12:53:25 +0200 Subject: Problem with struct.unpack Message-ID: <5FBC042194FEC54C9EFEA97D1EA8B3680140E699@villsmail01.eu.thmulti.com> Hi all, I have the following question/problem: >>> import struct >>> strBuffer = u'\x00\xf0\x00\x00\x00\x00\x00\x00' >>> print "%r" % strBuffer u'\x00\xf0\x00\x00\x00\x00\x00\x00' >>> (doorOpen,) = struct.unpack("1x1B6x", strBuffer) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf0' in position 1: ordinal not in range(128) Why is that not working with an "u" string ? If there is a 0x70 on the second byte, it works. Any ideas ? Thanks in advance Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From mahs at telcopartners.com Mon Jul 11 00:10:36 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 10 Jul 2005 21:10:36 -0700 Subject: Read-only class properties In-Reply-To: <42d1b2af.331498399@news.oz.net> References: <1121027902.719545.103860@g14g2000cwa.googlegroups.com> <42d1b2af.331498399@news.oz.net> Message-ID: Bengt Richter wrote: ... > > class Foo(object): > class __metaclass__(type): > def __setattr__(cls, name, value): > if type(cls.__dict__.get(name)).__name__ == 'Descriptor': > raise AttributeError, 'setting Foo.%s to %r is not allowed' %(name, value) > type.__setattr__(cls, name, value) > @classproperty > def TheAnswer(cls): > return "The Answer according to %s is 42" % cls.__name__ > @classproperty > def AnotherAnswer(cls): > return "Another Answer according to %s is 43" % cls.__name__ > or, simply put the read-only descriptor in the metaclass: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def classproperty(function): ... class Descriptor(object): ... def __get__(self, obj, objtype): ... return function(objtype) ... def __set__(self, obj, value): ... raise AttributeError, "can't set class attribute" ... return Descriptor() ... >>> class A(object): ... class __metaclass__(type): ... @classproperty ... def TheAnswer(cls): ... return "The Answer according to %s is 42" % cls.__name__ ... >>> A.TheAnswer 'The Answer according to __metaclass__ is 42' >>> A.TheAnswer = 3 Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __set__ AttributeError: can't set class attribute >>> class B(A): pass ... >>> B.TheAnswer 'The Answer according to __metaclass__ is 42' >>> this means that the getter doesn't automatically get a reference to the class (since it is a method of metaclass), which may or may not matter, depending on the application Michael From python at rcn.com Sat Jul 9 10:53:21 2005 From: python at rcn.com (Raymond Hettinger) Date: 9 Jul 2005 07:53:21 -0700 Subject: Defending Python In-Reply-To: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> Message-ID: <1120920801.730115.9410@g43g2000cwa.googlegroups.com> The posts do share an erroneous, implied assumption that the investment in learning each language is equal. Python has a strong competitive advantage over Java and C++ in terms of learnability. A person can get up to speed in a few days with Python. That certainly is not true for C++ which is more of a lifetime learning project. The negative reaction is likely due to the phrasing of the question in choosing popular language X over language Y. But if Y is easy to learn, there is no reason for it to preclude X. As a career builder, it is better to be able to work with multiple languages. So, I would recommend Python to these folks as an easily acquired extra skill. Raymond Hettinger From onurb at xiludom.gro Thu Jul 28 12:22:57 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 28 Jul 2005 18:22:57 +0200 Subject: functions without parentheses In-Reply-To: References: Message-ID: <42e90662$0$4566$636a15ce@news.free.fr> Jerry He wrote: > Hi, > Is it possible to create a function that you can use > without parenthesizing the arguments? for example, for > > def examine(str): > ..... > ..... > > Is there some way to define it so that I can call it > like > > examine "string" > instead of examine("string")? No. The reason (well, one of the reasons) is that, given a function my_func def my_func(*args, **kwargs): print "in my_func:" print "+ args : %s" % ", ".join(args) print "+ kwargs %s" % ", ".join(["%s=%s" % keyval \ for keyval in kwargs.items()]) return True the expressions my_func and my_func() have very different semantics. (hint: copy/paste this code in your python interactive interpreter). The first expression has exactly the same semantic as it would have with any other object[1] : it returns a reference to the function object referenced by the name 'my_func' according to namespace rules. [1] remember, in Python, functions are objects too. The second expression has the usual 'function call' semantic. The first expression allow to write code like: my_func_alias = my_func my_func_alias() or def my_caller_func(any_func, *args, **kwargs): print "calling %s with *args %s and **kwargs %s" \ % (any_func, ", ".join(args), ", ".join(["%s=%s" % keyval for keyval in kwargs.items()]) result = any_func(*args, **kwargs) print "result :%s" % result return result my_caller_func(my_func) In fact, '()' is the 'call' operator, that is then applied to the callable object[2] referenced by 'my_func'. So a function call like my_func() is in fact made in two steps: - retrieving the object referenced by the name 'my_func' - trying to apply the '()' call operator on it. [2] Functions are just one special case of callable object. Lambda are another, as any instance of a class defining the __call__ method. the call operator could be implemented like this: def __call_op__(func_name, *args, **kwargs): if hasattr(func_name, __call__): return func_name.__call__(*args, **kwargs) else: raise TypeError("%s object is not callable" % type(func_name)) Ok. Now that you know this, if Python was to support the result = my_func "arg1", "arg2" syntax, how should the expression result = my_func be interpreted ?-) (hint: remember that the prototype of my_func allow us to call it with no args at all) There are good reasons for trying to have a clear and unambigous syntax. functions-being-objects (as wall as 'other-objects-being-callable) is one of the strength of Python, and it's a common idiom in Python to pass functions (or any other callable) around. BTW, note that there are few languages that doesn't inforce one (and only one) unambigous syntax for function calls (even VB has a defined and mandatory syntax for function calls, which is the same as Python's. What VB has that Python has not is the semantic difference between functions and procedures, and different syntaxes for both). HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at REMOVETHIScyber.com.au Sun Jul 3 13:25:13 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 03:25:13 +1000 Subject: math.nroot [was Re: A brief question.] References: Message-ID: On Sun, 03 Jul 2005 15:46:35 +0100, Tom Anderson wrote: > I think there would be a lot less confusion over the alleged inaccuracy of > floating point if everyone wrote in hex - indeed, i believe that C99 has > hex floating-point literals. C has always been such a forward-thinking > language! No, all that would do is shift the complaint from "Python has a bug when you divide 10 into 1.0" to "Python has a bug when you convert 0.1 into hex". [snip] >> But this works: >> >> py> inf = float("inf") >> py> inf >> inf > > True. Still, i'd rather not have to rely on string parsing to generate a > fairly fundamental arithmetic quantity. What happens when your Python script is running on a platform that can deal with 1e300*1e300 giving 1e600 without overflow? Okay, maybe no such platform exists today (or does it?), but it could exist, and your code will fail on those systems. I believe that the IEEE standard specifies that float("inf") should give an infinity, just as float("0.0") should give a zero. For production code, I'd wrap float("inf") in a try...except and only fall back on your method if it raised an exception, and then I'd actually test that your result was a real inf (eg by testing that inf+inf=inf). [snip] >>> The IEEE spec actually says that (x == nan) should be *false* for every x, >>> including nan. I'm not sure if this is more or less stupid than what >>> python does! >> >> Well, no, the IEEE standard is correct. NaNs aren't equal to anything, >> including themselves, since they aren't numbers. > > I don't buy that. Just because something isn't a number doesn't mean it > can't be equal to something else, does it? I mean, we even say x == None > if x is indeed None. Yes, but None does equal None, since there is only one None, and by definition, a thing is equal to itself. But NaNs are _not_ things. That is the whole point! Yes, we _represent_ INF-INF as a particular bit-pattern and call it NaN, but mathematically subtracting infinity from infinity is not defined. There is no answer to the question "what is infinity subtracted from infinity?". We pretend that the answer is NaN, but that isn't right. The NaN is just there as a placeholder for "there is no answer", so that we don't have to sprinkle our code with a thousand and one tests. Since INF-INF doesn't have an answer, we can't do this: x = inf - inf y = inf - inf and expect that x == y. > Moreover, this freaky rule about NaNs means that this > is an exception to the otherwise absolutely inviolate law that x == x. Yes. So what? Remove the NaN shorthand: "The non-existent answer to this question is the same non-existent answer to this other question." It doesn't make sense to say that a non-thing is equal to anything -- even to itself, since itself doesn't exist. (Remember, a NaN is just an illusionary placeholder, not a number.) > I'd rather have that simple, fundamental logical consistency than some IEEE > rocket scientist's practical-value-free idea of mathematical consistency. Ah, from a _programmer's_ perspective, there is an argument that the simplicity of just testing NaNs with equality outweighs the logical silliness of doing such a thing. But, apart from testing whether a float is a NaN, why would you ever want to do an equality test? The only usage case I can think of is would be something like this: def isNaN(x): return x == SOME_KNOWN_NAN But that won't work, because there are lots of different NaNs. 254 of them, or twice that if you include signed NaNs (which you shouldn't, but you do have to allow for them in equality testing). Any good IEEE compliant system should already have a built-in function that tests for NaNs. [snip] >>> And while i'm ranting, how come these expressions aren't the same: >>> >>> 1e300 * 1e300 >>> 1e300 ** 2 >> >> Because this is floating point, not real maths :-) >> >> I get inf and Overflow respectively. What do you get? > > The same. They really ought to give the same answer. In real numbers, yes they should. In floating point, that is too much to expect. In mathematics, the order you do your calculation shouldn't matter. But in floating point, where there is rounding errors and finite precision issues, it does. The aim of the High Level Language designer is to insulate the programmer from the ickiness of actual hardware implementation. Unfortunately, in the case of floating point, you can't get away from the hardware limitations. >>> And finally, does Guido know something about arithmetic that i don't, >>> or is this expression: >>> >>> -1.0 ** 0.5 >>> >>> Evaluated wrongly? >> >> No, it is evaluated according to the rules of precedence. It is >> equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which >> fails as expected. > > Ah. My mistake. I submit that this is also a bug in python's grammar. > There's probably some terribly good reason for it, though. Yes. You generally want exponentiation to have the highest precedence. 2*3**4 should give 162, not 1296. Think about how you would write that mathematically, with pencil and paper: the 4 is written as a superscript over the 3, and is applied to that before multiplying by the 2. Unary minus is equivalent to multiplying by -1, so -3**4 is equivalent to -1*3**4. These are the rules of precedence mathematicians have worked out over many centuries. Yes, some of them are arbitrary choices, but they do work, and changing them for another arbitrary choice doesn't give us any benefit. -- Steven. From peter at engcorp.com Mon Jul 25 15:26:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 15:26:22 -0400 Subject: Run batch files in Windows XP In-Reply-To: <1122318744.969547.113640@g43g2000cwa.googlegroups.com> References: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> <1122318744.969547.113640@g43g2000cwa.googlegroups.com> Message-ID: <9v2dnYY1NvZtoXjfRVn-ug@powergate.ca> Ernesto wrote: > The issue is I haven't done very much batch programming. I need to > prompt the user for input and each batch file is in a different > directory. How do I change directories and prompt for user input? Ah, now you're talking things where Python, while not strictly required, can start to make things easier. :-) To run external things like batch files, you import the "os" module and use the system() function: import os os.system('somebatchfile.bat') Since you're prompting the user for input first, presumably the input is passed to the batch file in some way, like so: input = raw_input('Enter your incredibly useful info now:') ("raw_input" is a builtin... good to learn about as many of those as you can handle by reading the docs here: http://docs.python.org/lib/built-in-funcs.html . Some of those are absolutely not important to you at this early stage, others are.) Then with the input you've collected, you could pass it to the batch file like so: os.system('myfile.bat %s' % input) The %s and % together result in whatever text the user entered being added on the command line for the call to myfile.bat, exactly as though it had been executed manually with the same input. -Peter From j-integra_support at intrinsyc.com Mon Jul 18 16:39:41 2005 From: j-integra_support at intrinsyc.com (j-integra_support at intrinsyc.com) Date: 18 Jul 2005 13:39:41 -0700 Subject: J-Integra for COM (Java COM interoperability) Message-ID: <1121719181.408096.190110@g43g2000cwa.googlegroups.com> Looking for Java/COM interoperability tools? Thousands of companies world-wide are using J-Integra for COM for interoperability between Java and Microsoft COM applications. J-Integra for COM is a pure Java implementation of the DCOM protocol, making it several times faster than Web Services. J-Integra for COM Features: * Access J2EE components from VB, C++, ASPs, etc... * Access COM components from EJBs, Servlets, JSPs, Applets, etc... * Pure Java implementation, 100% managed code (no native code required) * Bi-directional: "Java to COM" and "COM to Java" * One-sided deployment (no touch on Microsoft client/server side) * Supports any JVM running on any platform (Windows, Unix, Linux, etc...) * Optional high-speed native mode for Windows platforms * Allows Java clients to subscribe to COM events using standard Java semantics, and COM clients to subscribe to Java events using standard COM semantics * Supports both early binding and late binding access to Java/COM components * Supports the full range of COM Oleautomation types For a free evaluation, visit our website at http://j-integra.intrinsyc.com/ Regards, Shane Sauer Intrinsyc Software International, Inc. J-Integra Interoperability Solutions http://j-integra.intrinsyc.com/ When Web Services are not enough From jeffm at rivernet.com.au Sun Jul 10 12:37:21 2005 From: jeffm at rivernet.com.au (Jeff Melvaine) Date: Mon, 11 Jul 2005 02:37:21 +1000 Subject: Efficiency of using long integers to hold bitmaps Message-ID: <42d14ec3@news.rivernet.com.au> I note that I can write expressions like "1 << 100" and the result is stored as a long integer, which means it is stored as an integer of arbitrary length. I may need to use a large number of these, and am interested to know whether the storage efficiency of long integers is in danger of breaking my code if I use too many. Would I do better to write a class that defines bitwise operations on arrays of integers, each integer being assumed to contain at most 32 bits? I cannot find information in the Python manuals for 2.4.1 that would allow me to resolve this question; perhaps the intention is that programmers should not rely on implementation details. Thanks in advance, Jeff From steve at REMOVETHIScyber.com.au Sat Jul 23 04:14:10 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 23 Jul 2005 18:14:10 +1000 Subject: tuple to string? References: <42E0EED4.4020001@gmx.net> Message-ID: On Fri, 22 Jul 2005 06:07:28 -0700, Robert Kern wrote: > Francois De Serres wrote: >> hiho, >> >> what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to >> the string 'spam'? > > In [1]: t = (0x73, 0x70, 0x61, 0x6D) > > In [2]: ''.join(chr(x) for x in t) > Out[2]: 'spam' I get a syntax error when I try that. I guess anyone who hasn't started using Python 2.4 will also get the same error. Since t is just a tuple, there isn't a big advantage as far as I can see to build up and dispose of the generator machinery just for grabbing the next item in a tuple. So a list comprehension will work just as well, and in older versions of Python: ''.join([chr(x) for x in (0x73, 0x70, 0x61, 0x6D)]) For an even more version-independent method: L = [] for n in (0x73, 0x70, 0x61, 0x6D): L.append(chr(n)) print ''.join(L) or even: >>> ''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D))) 'spam' -- Steven. From cyril.bazin at gmail.com Tue Jul 12 04:58:19 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Tue, 12 Jul 2005 10:58:19 +0200 Subject: Trying to come to grips with static methods In-Reply-To: References: Message-ID: Im my opinion, class method are used to store some "functions" related to a class in the scope of the class. For example, I often use static methods like that: class Foo: On 7/12/05, Steven D'Aprano wrote: > > I've been doing a lot of reading about static methods in Python, and I'm > not exactly sure what they are useful for or why they were introduced. > > Here is a typical description of them, this one from Guido: > > "The new descriptor API makes it possible to add static methods and class > methods. Static methods are easy to describe: they behave pretty much like > static methods in C++ or Java." > http://www.python.org/2.2.3/descrintro.html > > Great. So I have learn an entire new language to understand static > methods. Perhaps not -- hence this cry for help. > > As near as I can see it, static methods are object methods that act just > like functions. Er. I always thought that object methods *were* functions, > except they had some runtime magic that passed the object itself as the > first argument. > > >From Guido's example: > > >>> class C: > ... def foo(x, y): > ... print "staticmethod", x, y > ... foo = staticmethod(foo) > ... > >>> C.foo(1, 2) > staticmethod 1 2 > >>> c = C() > >>> c.foo(1, 2) > staticmethod 1 2 > > So I compare with an ordinary class function, er, method: > > >>> class D: > ... def foo(self, x, y): > ... print "method", x, y > ... > >>> D.foo(1, 2) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unbound method foo() must be called with D instance as first > argument (got int instance instead) > > Okay, that is to be expected. Actually, I expected an exception that I > hadn't passed enough arguments (2 arguments when foo expects 3), but in > hindsight it is obvious enough. > > First point of confusion. In the above exception, foo is called an unbound > method. But type(D.foo) returns even though foo is > being access through the class, not an instance. And type(D().foo) returns > the same. > > Can I assume that in Python "unbound method" is just another way of saying > "a method of a class that expects to be called via an instance"? > > > > I next tried this: > > >>> D.foo(D(), 1, 2) > method 1 2 > >>> D().foo(1, 2) > method 1 2 > > Clear as mud. An ordinary method called from an instance is the same as a > static method called from anywhere, provided you don't -- or rather, can't > -- try to access self from the static method. > > When would you use a static method instead of an ordinary method? It has > been suggested that you might use it for functions that don't need to > access self. But that doesn't seem very convincing to me, because there is > already a perfectly good idiom for that: > > >>> class E: > ... def foo(): # returns calculated value > ... return 1 > ... foo = staticmethod(foo) > ... def bar(self): > ... return 1 # just ignore the value of self > ... > >>> E.foo() > 1 > >>> e = E() > >>> e.bar() > 1 > > What are some usage cases for using Class.StaticMethod() instead of > instance.method()? Everything I've read seems to just assume that the > benefits of static methods are so obvious that they don't need explaining. > Unfortunately, I haven't come from a background in OO and I'm easily > confused, hence this post. > > > -- > Steven. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggg at zzz.it Fri Jul 8 06:40:21 2005 From: ggg at zzz.it (deelan) Date: Fri, 08 Jul 2005 12:40:21 +0200 Subject: urllib2 - basic authentication and the put and delete methods In-Reply-To: <64oze.2034$S17.395743@monger.newsread.com> References: <64oze.2034$S17.395743@monger.newsread.com> Message-ID: news.corp.adobe.com wrote: (...) > > But despite much searching, I have yet to discover how to then use PUT and > DELETE to copy files / delete files on the server. i believe you have to use httplib for that: examples here: basically you pass auth headers whie using PUT/DELETE verbs: ## untested! ## headers = { "Authorization": authheader # your base 64 str } conn.request("PUT", "/your/url/here", body, headers) HTH, deelan. -- deelan, #1 fan of adriana lima! From sjuranic at gmail.com Sat Jul 9 14:21:07 2005 From: sjuranic at gmail.com (Steve Juranich) Date: Sat, 9 Jul 2005 11:21:07 -0700 Subject: Should I use "if" or "try" (as a matter of speed)? Message-ID: <56190b6c05070911213409433e@mail.gmail.com> I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution model (specifically, exceptions). Without fail, when I start talking with some of the "old-timers" (people who have written code in ADA or Fortran), I hear the same arguments that using "if" is "better" than using "try". I think that the argument goes something like, "When you set up a 'try' block, you have to set up a lot of extra machinery than is necessary just executing a simple conditional." I was wondering how true this holds for Python, where exceptions are such an integral part of the execution model. It seems to me, that if I'm executing a loop over a bunch of items, and I expect some condition to hold for a majority of the cases, then a "try" block would be in order, since I could eliminate a bunch of potentially costly comparisons for each item. But in cases where I'm only trying a single getattr (for example), using "if" might be a cheaper way to go. What do I mean by "cheaper"? I'm basically talking about the number of instructions that are necessary to set up and execute a try block as opposed to an if block. Could you please tell me if I'm even remotely close to understanding this correctly? -- Steve Juranich Tucson, AZ USA From jeanphilippe.aumasson at gmail.com Mon Jul 4 03:30:28 2005 From: jeanphilippe.aumasson at gmail.com (jeanphilippe.aumasson at gmail.com) Date: 4 Jul 2005 00:30:28 -0700 Subject: 'Deep' pickling Message-ID: <1120462227.921646.274480@g43g2000cwa.googlegroups.com> Hi, I have some problems when pickling an instance of a class, i don't retrieve all its attributes instances after loading. I'm quite a beginner in Python, so it may be a stupid error... Here the full description : I have a class Test, having an attribute self.problem, as an instance of Problem class, defined in the same module. Problem as an attribute self.optimum, that is a list of Point instances, also defined in the same module. So i use to write self.problem.optimum[i] to get some Points of my Test... I pickle a Test with the following lines : import copy cPickle.dump( copy.deepcopy(self), open('TEST', 'w')) and unpickle in another module with : fd = open( os.path.join(p, 'TEST'), 'r' ) s = cPickle.load( fd ) But the problem is, when i try to access the self.problem.optimum field, i get an empty list, instead of having a list full of Points. I can access string, int, or even Point attributes of Problem. This only happens when i load AFTER restarting Python interpreter. I thought that pickling self from my Test wasn't enought to get instances of attributes copied to, that's why i used a deepcopy(self) instead, but it didn't resolve my problem... I tryed to define a __getState__() method, but didn't help... Can someone help ? Thx From donn at drizzle.com Sat Jul 9 11:47:44 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 09 Jul 2005 15:47:44 -0000 Subject: Defending Python References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> Message-ID: <1120924063.362692@yasure> Quoth Dave Cook : | On 2005-07-08, Charlie Calvert wrote: | |> I perhaps rather foolishly wrote two article that mentioned Python as a |> good alternative language to more popular tools such as C# or Java. I | | Sounds like a really hidebound bunch over there. Good luck. Nah, just normal. Evangelism is always wasted on the majority of listeners, but to the small extent it may succeed it depends on really acute delineation of the pitch. It's very hard for people to hear about something without trying to apply it directly to the nearest equivalent thing in their own familiar context. Say good things about language X, and people will hear you saying "give up using language Y and rewrite everything in language X." Then they will conclude that if you would say that, you don't know very much about their environment. Donn Cave, donn at drizzle.com From sjmachin at lexicon.net Thu Jul 21 07:13:53 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 21 Jul 2005 21:13:53 +1000 Subject: is a file open ? In-Reply-To: References: <42de3b80$1@news.eftel.com> Message-ID: <42df8370$1@news.eftel.com> luis wrote: > John Machin wrote: > >> Daniel Dittmar wrote: >> >>> luis wrote: >>> >>>> for root, dirs, files in os.walk(path): >>>> for file in files: >>>> # ? is opened ? >>> >>> >>> >>> >>> On Linux and some other Unixes, you can probably read the /proc >>> filesystem. >>> >>> On Windows, you'll probably get the quickest result by running >>> handle.exe (http://www.sysinternals.com/Utilities/Handle.html). >>> >>> Either way, the information you'll get is restricted by your >>> permissions. >>> >>> Either information will get stale really fast, so it's not suitable >>> if your task is something like 'can I backup this directory or is >>> someone writing to a file?' >> >> >> >> If that's what the OP had in mind, the question might have been better >> phrased as "given the path to a file, how can I tell if it is >> currently opened by another process/thread", and better directed to >> OS-specifc newsgroup(s). >> > there is a specific python function ? If you mean "is there a Python function that given a filename, returns an indication of whether that file has been opened by another process/thread, portably across different operating systems?" then the answer is NO. This is what I meant by "the question might have been ... better directed to OS-specifc newsgroup(s)". That is what you should have inferred from Daniel's reply "On Linux ... probably ... On Windows ... probably...". If you mean something else, you might like to try rephrasing your question. From fumanchu at amor.org Sun Jul 10 16:21:32 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 10 Jul 2005 13:21:32 -0700 Subject: Yet Another Python Web Programming Question Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3772520@exchange.hqamor.amorhq.net> Paul Boddie wrote: > "Robert Brewer" wrote in message > news:... > > Daniel Bickett wrote: > > > I neglected to mention an important fact, and that is the > > > fact that I am limited to Apache, which elminates several > > > suggestions (that are appreciated none-the-less). > > > > Do you have access to mod_python, mod_rewrite, FastCGI, or > > SCGI? Then CherryPy 2.1 is still a great option for you with > > Apache: > > http://www.cherrypy.org/wiki/WSGIServers > > http://www.cherrypy.org/wiki/BehindApache > > According to the "quick facts" page "CherryPy powered web > applications are in fact stand-alone Python applications embedding > their own multi-threaded web server", suggesting that if the hosting > environment is "limited to Apache" and if this can also be taken to > mean that the environment doesn't permit long-running server processes > apart from Apache, then CherryPy isn't likely to be suitable. Thanks for pointing that out; that page was out of date, and has now been corrected: http://www.cherrypy.org/wiki/CherryPyQuickFacts . CherryPy 2.1 apps can be deployed using Apache (via mod_python) or IIS (via ASP) as the webserver *without* running the webserver built into CherryPy. In fact, CherryPy should work with any WSGI-capable webserver, and be deployable in a wide variety of hosting environments with no changes to your application code. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From spam.csubich+block at block.subich.spam.com Wed Jul 13 12:19:47 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 13 Jul 2005 12:19:47 -0400 Subject: all possible combinations In-Reply-To: <1121267364.28617.4.camel@athop1.ath.vt.edu> References: <1121267364.28617.4.camel@athop1.ath.vt.edu> Message-ID: rbt wrote: > Expanding this to 4^4 (256) to test the random.sample function produces > interesting results. It never finds more than 24 combinations out of the > possible 256. This leads to the question... how 'random' is sample ;) sample(population,k): Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. New in version 2.3. Working as designed, I'd say. 4! = 24. From bogus@does.not.exist.com Fri Jul 1 10:05:02 2005 From: bogus@does.not.exist.com () Date: Fri, 01 Jul 2005 14:05:02 -0000 Subject: No subject Message-ID: #! rnews 1856 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!tiscali!transit0.news.tiscali.nl!tudelft.nl!txtfeed1.tudelft.nl!feeder1.cambrium.nl!feed.tweaknews.nl!news2.euro.net!newsfeed.freenet.de!newspeer1.nwr.nac.net!in.100proofnews.com!in.100proofnews.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Modules for inclusion in standard library? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 26 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <3ian37Fkjle0U1 at individual.net> <11c343ho6i6hv17 at news.supernews.com> <1x6lpi6z.fsf at python.net> <7xwtodvzsv.fsf at ruckus.brouhaha.com> <7x3br1ger1.fsf at ruckus.brouhaha.com> <86slyza5hn.fsf at bhuda.mired.org> Mime-Version: 1.0 Date: Fri, 1 Jul 2005 13:46:28 GMT Xref: news.xs4all.nl comp.lang.python:384359 Mike Meyer writes: > Harry George writes: > > > b) Installing distutils-aware python packages is trivial. I'd rather > > the energy which might go into a bigger std library go instead into > > helping projects which don't have distutils-style builds. > > How about integrating distutils and PyPI, so that distutils can > automatically download and install packages that are required by the > package it's currently installing? In other words, C-Python-AN. > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. I personally don't do auto download/installs, preferring instead to scan the code before build/install. However, getting a list of dependencies would be nice. Maybe a setup.py --requires flag. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From jaymail at gawab.com Sat Jul 30 04:11:32 2005 From: jaymail at gawab.com (Jay) Date: 30 Jul 2005 01:11:32 -0700 Subject: keylogger in Python Message-ID: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> ok, i thought for 2 seconds i might have created a Keylogger in python but i still have one major think stopping me... PYTHON. when i run the program i have python create a file named keylog2.log and it then logs all keys pressed/typed in the python IDE into that file. All i want to know now is how do i hide or background python so that it will log all the keys pressed outside of Python. feel free to play around with my program... but please post ur findings on my post... ##################################################### class keylogger: pass keylogging = keylogger() keylog = open("keylog2.log", "w") text = raw_input() keylog.write(text) keylog.close keylog = open("keylog2.log", "r") keylog.read From Scott.Daniels at Acm.Org Wed Jul 6 17:14:58 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 06 Jul 2005 14:14:58 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> Message-ID: <42cc420b$1@nntp0.pdx.net> Fran?ois Pinard wrote: > My feeling at the time was that Scheme is a very fast language to write > into, and in which one can implement new concepts cleanly and compactly. > Maybe Python is a bit slower to write, but this is compensated by the > fact Python is more legible when it comes to later maintenance, or when > many people have to share work on a big set of sources. > > There is some heaviness and complexity in Python internals, Scheme are > purer and simpler by comparison. On its bright side, Python has a nice > and comprehensive library, and an interesting community of users. These > probably make most of the difference. Well said. Writing speed is not everything; if it is, APL and Scheme win (and the evil Perl for string processing). --Scott David Daniels Scott.Daniels at Acm.Org From nothingcanfulfill at gmail.com Sat Jul 9 14:44:34 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 9 Jul 2005 11:44:34 -0700 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: <1120934674.774605.184080@g44g2000cwa.googlegroups.com> Honestly, I'm rather new to python, but my best bet would be to create some test code and time it. From williams13 at llnl.gov Mon Jul 25 08:55:39 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Mon, 25 Jul 2005 05:55:39 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050722164442.GB1912@tishler.net> References: <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> Message-ID: <42E4E14B.2030905@llnl.gov> Jason, > >>Is there anyway for me to get back to an older version of Cygwin? >> >> > >What do you mean by the above? An older Cygwin? An older Cygwin >Python? An older rebase? > I installed Cygwin back in February on my laptop. (Call this Cygwin A.) I have not updated it (i.e., Cygwin A) since getting Python to run. Last week, I obtained another laptop, which I installed Cygwin (from the Internet) on last Thursday. (Call this Cygwin B.) Cygwin Versions: Cygwin A = the February 2005, version Cygwin B = Thursday's, July 21, 2005 version Last Friday, I built Python2.4 on Cygwin A with no errors. (The socketmodule worked and I can import socket.) I also built Python2.4 on newer version of Cygwin (i.e., Cygwin B), but the socketmodule doesn't work. I get an error message when importing socket. The Python2.4 is the same for both. The only difference is in the Cygwin version. That is, the version I installed from the internet in February and the version I installed last Thursday. When installing from the internet, there is no way to specify which version (or date) of Cygwin to download. I was wondering if you kept version controls, so I could go back to the February version of Cygwin since I know the Python Socket Module works. > > > >>In my Python2.4 log file, I tracked it down to the file >>Python2.4/Modules/socketmodule.c file: 3350 INET_ADDSTRLEN, which >>says "INET_ADDSTRLEN" is undeclared. I know this has something to do >>with the _ssl extension. >> >> > >Is the above from building Python or CDAT? > The above is building Python. > > > >>Also in my Python2.4 log file, I see DB_LSTAT_ERR is undeclared. Has >>something to do with the building of the gdbm extension. >> >> > >Ditto. > Yeap. The is from the Python build. > > > >>Also when I tryed "rebaseall" it no longer worked. When I went to >>"Start/run..." and tried to run "ash", I got the error stating it >>didn't know what "ash" was. Any help on this is appreciated. >> >> > >If Cygwin's bin is not in your Windows PATH, then give the full path to >ash. For example: > > C:\Cygwin\bin\ash.exe > >Then start rebaseall is follows: > > $ PATH=/bin rebaseall > Thanks. I will try this and see if this gets around my problem. Thanks again for any help on this Best regards, Dean From cell2005 at pchome.net Sat Jul 23 13:25:58 2005 From: cell2005 at pchome.net (=?gb2312?q?=B8=D5=20=CD=F5?=) Date: Sun, 24 Jul 2005 01:25:58 +0800 (CST) Subject: How to realize ssh & scp by Python Message-ID: <20050723172558.21838.qmail@web15407.mail.cnb.yahoo.com> I would like to write a Python code like this: It can login a host by SSH after login the host, use SCP to get a remote file, so it can deliver file to the host. then execute the program then leave the host For example : STEP 1. ssh xxxx_yyy at 123.45.67.89 STEP 2. Enter the password automatically STEP 3. run " scp -r zzz at 123.45.67.90:/home/xxx/program ." STEP 4. Enter the password for SCP automatically STEP 5. run "./program" STEP 6. run " exit" I know telnetlib can help us with telnet, and how to deal with this SSH situation in Python? Thanks a lot for your help :) __________________________________________________ ??????????????? http://cn.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gyromagnetic at gmail.com Thu Jul 28 15:08:44 2005 From: gyromagnetic at gmail.com (gyromagnetic at gmail.com) Date: 28 Jul 2005 12:08:44 -0700 Subject: Ten Essential Development Practices Message-ID: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> The following url points to an article written by Damian Conway entitled "Ten Essential Development Practices": http://www.perl.com/pub/a/2005/07/14/bestpractices.html Althought the article has Perl as a focus, I thought that some of the general points made might be of interest to the Python community. It would certainly be interesting to put together an analogous version of this article that centers on Python. Best Regards, g From steve at REMOVETHIScyber.com.au Sun Jul 3 00:46:20 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 14:46:20 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 02 Jul 2005 20:26:31 -0700, Devan L wrote: > Claiming that sum etc. do the same job is the whimper of > someone who doesn't want to openly disagree with Guido. > > Could you give an example where sum cannot do the job(besides the > previously mentioned product situation? There is an infinite number of potential lambdas, and therefore an infinite number of uses for reduce. sum only handles a single case, lambda x,y: x+y product adds a second case: lambda x,y: x*y So sum and product together cover precisely 2/infinity, or zero percent, of all possible uses of reduce. > Also, map is easily replaced. > map(f1, sequence) == [f1(element) for element in sequence] Three mental tokens ( map, f1, sequence ) versus seven ( [], f1, element, for, element, in, sequence ). Also, map can take any number of sequences: map(f1, seq1, seq2, seq3, seq4, ...) -- Steven. From avera at coes.org.pe Fri Jul 22 11:58:24 2005 From: avera at coes.org.pe (Alberto Vera) Date: Fri, 22 Jul 2005 10:58:24 -0500 Subject: use libs from one of two releases Message-ID: <001c01c58ed6$30dd9260$1603a8c0@avc> Hello. I have two versions of Python. They were intalled in two different folders. (python22 and python23) I have an old py that works in an older version. How can I change my old py to use libs of python22? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Jul 31 22:34:57 2005 From: http (Paul Rubin) Date: 31 Jul 2005 19:34:57 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <7xvf2rync2.fsf@ruckus.brouhaha.com> Message-ID: <7xd5oyxu3y.fsf@ruckus.brouhaha.com> Ed Leafe writes: > Because Tkinter looked like crap on OS X. Yes, it's cross-platform, it looks like crap everywhere ;-). > There are step-by-step instructions on the wxPython site for building it If I need step by step instructions beyond ./configure make make install then I'd say it's unfinished software and I'll be more interested in it after it's done. From peter at engcorp.com Fri Jul 29 17:32:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 17:32:09 -0400 Subject: Async PySerial (was Re: pySerial Windows write problem) In-Reply-To: References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: <6OmdnVb916I-PHffRVn-1g@powergate.ca> phil wrote: > I use PySerial in a 16 line data collection system > with LOTS of threads, and yes am frustrated by read(). > This sounds excellent, keep us updated. > > BTW, haven't done any event driven Python except Tkinter. > Would this a class library which would let you > define an event and a handler? Roughly speaking, yes. The primary parent class happens to be called Handler, and is a threading.Thread subclass which in its run() method basically sits in a win32 WaitForMultipleObjects() call for various things to happen, then calls handler routines based on which event fires. > Do you have a one line code example? One line? No way... this isn't Perl. ;-) from bent.serial import Driver class MyDriver(Driver): def __init__(self, port, baud=9600): Driver.__init__(self, port, baud=baud, name='iodriver') self.start() # start the thread def handleSerialRead(self, data): print 'read %r' % data def handleSerialDsr(self, level): print 'DSR', level def handleSerialBreak(self): print 'break detected, ho hum' Usage for this would be simply: d = MyDriver('COM3') and then sit back and watch the, uh, fireworks... or at least the print statements. Anything interesting represents a much more sophisticated subclass which parses the data as it arrives, of course, and at least in my case then calls a handlePacket() routine where the fun really begins. -Peter From steve at REMOVETHIScyber.com.au Sat Jul 23 09:22:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 23 Jul 2005 23:22:21 +1000 Subject: Getting a dictionary from an object References: Message-ID: On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote: > Hello. > > I would like to have a quick way to create dicts from object, so that a > call to foo['bar'] would return obj.bar. That looks rather confusing to me. Why not just call obj.bar, since it doesn't look like you are actually using the dictionary at all? > The following works, but I would prefer to use a built-in way if one > exists. Is there one? > > Thanks in advance. > > class dictobj(dict): > """ > class dictobj(dict): > A dictionary d with an object attached to it, > which treats d['foo'] as d.obj.foo. > """ > def __init__(self, obj): > self.obj = obj > def __getitem__(self, key): > return self.obj.__getattribute__(key) I don't think this is particularly useful behaviour. How do you use it? py> D = dictobj("hello world") py> D {} py> D.obj 'hello world' py> D["food"] = "spam" py> D {'food': 'spam'} py> D["food"] Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __getitem__ AttributeError: 'str' object has no attribute 'food' -- Steven. From pydecker at gmail.com Sun Jul 24 21:21:32 2005 From: pydecker at gmail.com (Peter Decker) Date: Sun, 24 Jul 2005 21:21:32 -0400 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <87ek9occzx.fsf@wilson.rwth-aachen.de> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> Message-ID: On 7/24/05, Torsten Bronger wrote: > Is PyGTK more Pythonic by the way? I had a look at wxPython > yesterday and didn't like that it has been brought into the Python > world nearly unchanged. You can see its non-Python origin clearly. > How does PyGTK feel in this respect? There are several projects that have as their goal to wrap wxPython and make it more Pythonic. IMO, the best choice now is Dabo, which is being actively developed and improved. There is also Wax, which I got interested a while ago, but it seems to be the work of a single author who only works on it when he has a personal need. I've been doing some development work in Dabo, even though I don't currently need their database integration. The UI layer is very Pythonic, and I much prefer writing code in Dabo than plain wxPython. -- # p.d. From fowlertrainer at anonym.hu Tue Jul 5 10:00:09 2005 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 05 Jul 2005 16:00:09 +0200 Subject: Py2Exe and the log file... Message-ID: <42CA9269.6030503@anonym.hu> Hi ! 1. Thanx for your answer in the theme of Unicode, and other things. 2. The problem: I need to create an application that not need Python libs to install. Py2Exe is good for that, but I need to copy the "dist" to the network drive what mapped readonly. This is a protection. So: in this time I have been use same applications, but they are created by Delphi. These apps make logs into user's temp to avoid the log merging, and log creation problems (in readonly drive). Py2Exe have an exception catcher "module", that log the errors in the log file that created in app dir. This is problem, because the log file creation have been failed in RO drive. How to I redirect this log file, or can I do anything to aviod the log file creation error ? Thanx for your help: ft From duncan.booth at invalid.invalid Wed Jul 13 08:56:26 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jul 2005 12:56:26 GMT Subject: Building a function call? References: Message-ID: Francois De Serres wrote: > Having a string: "dothat" > and a tuple: (x, y) > 1. What's the best way to build a function call like: dothat(x,y)? > > Assuming dothat is def'd in the same module, > 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) > the right way to have it executed? > > If dothat is def'd in another module: > 3. what would be the right way to initialize the globals to pass to > eval ? > No, none of this is a good place to use eval. aString = "dothat" atuple = (x, y) If aString is the name of a function in the current module: globals()[aString](*aTuple) If aString is a function in another module: import otherModule vars(otherModule)[aString](*aTuple) and if you don't know the name of the module in advance: otherModule = __import__(nameOfOtherModule) vars(otherModule)[aString](*aTuple) Better still, collect all the functions you expect to be callable in this way together in a dictionary and then you can be sure that you only call something you intended to be callable. From paul at boddie.org.uk Sat Jul 23 09:23:02 2005 From: paul at boddie.org.uk (paul at boddie.org.uk) Date: 23 Jul 2005 06:23:02 -0700 Subject: PEP on path module for standard library References: <3kacleFslj6sU1@individual.net> <3kajr8FtfejbU1@individual.net> Message-ID: <1122124982.120316.257310@g47g2000cwa.googlegroups.com> Michael Hoffman wrote: > Reinhold Birkenfeld wrote: > > Probably as Terry said: a path is both a list and a string. [...] > One way to divide this is solely based on path separators: > > ['c:', 'windows', 'system32:altstream', 'test.dir', > 'myfile.txt.zip:altstream'] I would argue that any proposed solution has to work with VMS pathnames. ;-) > The current stdlib solution, os.path.splitext(os.path.splitext(filename) > [0])[0] is extremely clunky, and I have long desired something better. > (OK, using filename.split(os.extsep) works a little better, but you get > the idea.) And also with unusual (eg. RISC OS) filename extensions. To do any justice to the existing solutions, any PEP should review at least the following projects: * The path module (of course): http://www.jorendorff.com/articles/python/path/ * The py.path module (or at least the ideas for it): http://codespeak.net/py/current/doc/future.html * itools.uri http://www.ikaaro.org/itools * Results from the "Object-Oriented File System Virtualisation" project in the "Summer of Code" programme: http://wiki.python.org/moin/SummerOfCode And I hope that the latter project is reviewing some of the other work, if only to avoid the "framework proliferation" that people keep complaining about. Paul From tlesher at gmail.com Sun Jul 24 23:04:50 2005 From: tlesher at gmail.com (Tim Lesher) Date: 24 Jul 2005 20:04:50 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <1122260690.239957.227150@f14g2000cwb.googlegroups.com> Yes, it's not that hard to get the native file dialogs, as described in the FAQ: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq21.013.htp It would be nice if PyGTK had a knob for making it use win32 dialogs by default, though. From sjmachin at lexicon.net Fri Jul 1 09:45:57 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 01 Jul 2005 23:45:57 +1000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) In-Reply-To: References: Message-ID: <42C54915.3020501@lexicon.net> Simon Brunning wrote: > On 7/1/05, Peter Maas wrote: > >>Simon Brunning schrieb: >> >>> Sibylle Koczian needs to sort part of a list. His first attempt made >>> the natural mistake - sorting a *copy* of part of the list: >> >>I think it was _her_ first attempt. > > > Ooops! Sorry, Sibylle. > Obviously haven't spent enough time watching Fawlty Towers :-) From rrr at ronadam.com Wed Jul 6 12:30:49 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 16:30:49 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120665674.114022.180500@g44g2000cwa.googlegroups.com> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1120621580.107813.47100@g43g2000cwa.googlegroups.com> <1120665674.114022.180500@g44g2000cwa.googlegroups.com> Message-ID: Devan L wrote: >># from a custom numeric class >># converts a tuple of digits into a number >>mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) > > > I'll admit I can't figure out a way to replace reduce without writing > some ugly code here, but I doubt these sorts of things appear often. It's not ugly or difficult to define a named function. def digits_to_value(seq): v = 0 for d in seq: v = v*10+d return v Then where you need it. mantissa = sign * digits_to_value(mantissa) One of the motivations is the reduce-lambda expressions are a lot harder to read than a properly named function. And a function will often work faster than the reduce-lambda version as well. Cheers, Ron From nephish at xit.net Wed Jul 27 08:46:23 2005 From: nephish at xit.net (nephish) Date: Wed, 27 Jul 2005 12:46:23 +0000 Subject: question about deleting records from mysql In-Reply-To: <42E7816C.5080501@fielden.com.au> (from david@fielden.com.au on Wed Jul 27 07:43:24 2005) References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> <42E7720E.90307@xit.net> <1122466366.005107.303840@z14g2000cwz.googlegroups.com> <42E7816C.5080501@fielden.com.au> Message-ID: <1122468383l.15818l.0l@texaspivot.texaspivot.com> Man, thanks for the link. and the tip. i am testing the db.commit() and printing the doc right now. thanks again. On 07/27/2005 07:43:24 AM, Rowdy wrote: > nephish at xit.net wrote: >> ok. did this >> >> >>>>> cursor.execute("DELETE FROM table WHERE autoinc > 1000") >> >> 245L >> >>>>> cursor.commit() >> >> >> i got an AttributeError 'Cursor' object has no attribute 'commit' >> >> hmm. what should i do now? >> the stuff about writing a lightweight layer between the dbapi and the >> program shot right over my head. sorry, but thanks >> > > IIRC it is the connection that can commit(), not the cursor. > > Rowdy > From peter at engcorp.com Mon Jul 25 12:02:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 12:02:50 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kkf2vFv0mngU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> Message-ID: <8dKdnaBmHKO2kHjfRVn-uQ@powergate.ca> Reinhold Birkenfeld wrote: > Peter Hansen wrote: >> Would basestring() be a better name? > "tobase"? > "tostring"? > "tobasestring"? Of these choices, the latter would be preferable. > Alternative is to set a class attribute "Base" of the > Path class. Or export PathBase as a name from the module > (but that's not quite useful, because I > expect Path to be imported via "from os.path import Path"). I don't understand how that would work. An attribute on the *class*? What would it be, a callable? So mypath.Base(mypath) or something? Please elaborate... What about just .basestring, as a read-only attribute on the Path object? -Peter From go2len at TRALALALAhotmail.com Tue Jul 5 11:32:55 2005 From: go2len at TRALALALAhotmail.com (Lennart) Date: Tue, 5 Jul 2005 17:32:55 +0200 Subject: Good starterbook for learning Python? Message-ID: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Hi everybody, Can someone advice me with the following issue: i want to learn python in my summer vacation (i try to ...:-) So, a good start is buying a good book. But wich? There are many ... I'm living in the Netherlands and I prefer a book from bol.com (see link) because i've to order more books by them. I'm familiar with html & php and basic (in the good old days). It has to be a newbie book, but not a book what i don't need anymore when i've got some skills. I.e. the learning curve of the book should be linear. A kind of book wich i could use as a novice. Search here for python (sorry, there's no short link) http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_BrowseCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&CategoryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb&CategoryLeftpanel=BOOK_EN%2eCATEGORY00000000&Secondary=YES&Template=BOL_subcat_BOOK_EN_1476 From steven.bethard at gmail.com Tue Jul 26 13:03:33 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 26 Jul 2005 11:03:33 -0600 Subject: Bug Report / Patch (1159139 cgi.py invalid REQUEST_METHOD set) In-Reply-To: <_ICdnT-Tg-3_ynvfRVn-qw@comcast.com> References: <_ICdnT-Tg-3_ynvfRVn-qw@comcast.com> Message-ID: Joe wrote: > Back in March I submitted a patch for cgi.py to sourceforge to fix a problem > with the handling of an invalid REQUEST_METHOD. > > I thought I followed all the steps to properly submit the bug and patch but > the patch is still sitting there in limbo. Patches get processed when people have the time to review them. If you'd like to speed up the process, a few people on the python-dev list have promised to review a patch if the requester reviews 5 other patches. So if you want to get your patch looked at: (1) pick 5 other patches (2) try them on your system (3) make a helpful comment on each of the patch trackers (4) send a summary of your reviews to the python-dev list, along with a link to the patch you'd like reviewed. HTH, STeVe From smcg4191zz at friizz.RimoovAllZZs.com Wed Jul 13 17:04:31 2005 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Wed, 13 Jul 2005 15:04:31 -0600 Subject: Tix example code? Message-ID: <11db0f02gdquvfb@corp.supernews.com> I am having trouble trying to figure out how to use Tix widgets in a Python program. The documentation is scanty and in TCL syntax with no examples. Specifically, I'm trying to use a Tix ComboBox widget and haven't been able to figure out how to initialize the set of values in the widget's list. Does anyone have some (or a pointer to) simple example python code that uses TIX widgets (especially the ComboBox) including subwidgets? Thanks!... (And, yes, I looked at the "Mapping Basic Tk into Tkinter " rosetta stone web page but it did not provide much enlightenment.) From peter at engcorp.com Wed Jul 27 08:02:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Jul 2005 08:02:06 -0400 Subject: how to write a line in a text file In-Reply-To: References: <42E5B0F0.6020206@REMOVEMEcyber.com.au> <42E5ED91.10402@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > On Wed, 27 Jul 2005 04:26:31 +0000, Andrew Dalke wrote: >>This isn't 1970. Why does your app code work directly with >>files? Use a in-process database library (ZODB, SQLLite, >>BerkeleyDB, etc.) to maintain your system state and let the >>library handle transactions for you. > > And when users are happy to install a relational database system in order > for their editor to save their letter to grandma, I'm sure your scheme > will work well for them. Given that ZODB and PySQLite are simply Python extension modules, which get bundled by your builder tool and are therefore installed transparently along with your app by your installer, this is a total non-issue at least with those packages. After all, it's not 1970 any more. ;-) -Peter From rkern at ucsd.edu Mon Jul 11 21:41:53 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Jul 2005 18:41:53 -0700 Subject: tuple.index(item) In-Reply-To: <2357634.ngsvs5RTyu@knode.kde> References: <2357634.ngsvs5RTyu@knode.kde> Message-ID: Jules Dubois wrote: > On Monday 11 July 2005 15:23, David Isaac > () wrote: > >>Why don't tuples support an index method? > > 19:27:32:~ $ python > Python 2.3.5 (#2, Jun 19 2005, 13:28:00) > [GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> > >>> t = ('a', 'b', 'c') > >>> t[1] > 'b' > >>> He means, rather t.index('b') == 1 as it works for lists. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kay.schluehr at gmx.net Fri Jul 8 11:33:11 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Jul 2005 08:33:11 -0700 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <1120836791.706613.116500@g14g2000cwa.googlegroups.com> jwaixs schrieb: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. 1.5 hours are not enough for understanding regular expressions. But to be honest: I never had the patience to learn them accurately and I guess I will never do so as well as I don't ever learn sed or awk or Perl. When my brain hit regexp syntax the first time I thought about writing a little language that translates readable Python expressions in awkward regexps as an intermediary language which gets finally compiled into a finite state-machine descriptions. Fortunately I was not the first one who considered his mental weakness/aesthetic repulsion as a virtue: http://home.earthlink.net/~jasonrandharper/reverb.py I never took time for a critical review. The module just worked for my purposes. Kay From erniedude at gmail.com Mon Jul 25 14:17:37 2005 From: erniedude at gmail.com (erniedude at gmail.com) Date: 25 Jul 2005 11:17:37 -0700 Subject: Run batch files in Windows XP Message-ID: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> Hi, I'm a newbie and I was wondering if anyone knew a (Python) script to run 4 batch files, one after the other (assuming the directories are known). It would be better if all 4 batch files could run simultaneously, but that might break Windows... ;) The problem I had was I couldn't get the files to RUN, only to OPEN. Thanks for the help!!! pseudo-code looks like this > Get directory > Run batch1 > Run batch2 > Run batch3 > Run batch4 From caseyhHAMMER_TIME at istar.ca Tue Jul 19 13:24:21 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Tue, 19 Jul 2005 17:24:21 GMT Subject: Strange os.path.exists() behaviour References: <42cc3613$0$22287$8fcfb975@news.wanadoo.fr> Message-ID: Does this work differently under other platforms? Pierre Quentel wrote: >os.path.exists(path) returns True if "path" exists > >But on Windows it also returns True for "path" followed by any number of >dots : > >Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> os.path.exists('Lib/os.py') >True # expected > >>> os.path.exists('Lib/os.py.') >True # unexpected > >>> os.path.exists('Lib/os.py.....') >True # unexpected > >>> > >Is there a reason for this ? Is there a test that returns True only for >the really existing path ? > >Pierre -- Regards, Casey From ntv1534 at gmail.com Tue Jul 5 19:11:45 2005 From: ntv1534 at gmail.com (MooMaster) Date: 5 Jul 2005 16:11:45 -0700 Subject: multiple checkboxes highlighted when one clicked = not good Message-ID: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> I've been reading Deitel's Introducing Python, and Fredrik Lundh's Introduction to Tkinter, trying to familiarize myself with Python and GUI design in Tk, and I've run into a puzzling problem. I'm trying to draw a column of 10 checkboxes, each with a separate variables and commands. The easy way to do this is to hardcode it, but I was trying to do something a little more elegant: self.InUse =[BooleanVar(), BooleanVar(), BooleanVar(), BooleanVar(), BooleanVar(), BooleanVar(), BooleanVar()] for i in range(1,11): for t in range(7): if(t==0): Checkbutton(self.frame2, variable = self.InUse[t]).grid(row= i, column = t) I figure since I create a separate variable for each checkbutton, the should be independent of one another. Unfortunately, they are not, and when I click on one, all become selected/deselected. What am I missing? Thanks! From sjmachin at lexicon.net Thu Jul 14 17:52:22 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 15 Jul 2005 07:52:22 +1000 Subject: all possible combinations In-Reply-To: <1121362739.24407.4.camel@athop1.ath.vt.edu> References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> Message-ID: <42d6de96@news.eftel.com> rbt wrote: > Thanks to all who were helpful... some of you guys are too harsh and > cynical. Reality check: wander down to your nearest military establishment, ask a drill sergeant to demonstrate "harsh and cynical". > Here's what I came up with. I believe it's a proper > combination, but I'm sure someone will point out that I'm wrong ;) > > groups = [list('abc'),list('abc'),list('abc'),list('abc')] > > already = [] In general, a set would be better than a list (1) conceptually (2) when the number of elements is large. > > while 1: > > LIST = [] Read the style guide -- http://www.python.org/peps/pep-0008.html > > for g in groups: > sample = random.sample(g, 1) > LIST.append(sample[0]) > > STRING = ''.join(LIST) > if STRING not in already: > print STRING > already.append(STRING) > if len(already) == 81: > break > You don't need to use random sampling. Paul Rubin has shown how it can be done deterministically. The following is a generalisation of his code; it generates all possible assemblies of size n from a list of parts. Is this helpful? def all_size_n_knickers(rqd_size, pieces): npieces = len(pieces) knicker_count = npieces ** rqd_size austen = [npieces ** (rqd_size-k-1) for k in xrange(rqd_size)] for i in xrange(knicker_count): knicker = [pieces[j] for j in [(i // d) % npieces for d in austen]] yield knicker for alist in all_size_n_knickers(4, 'abc'): print ''.join(alist) print print list(all_size_n_knickers(2, [1, 42, 666])) From saint.infidel at gmail.com Wed Jul 6 12:17:23 2005 From: saint.infidel at gmail.com (infidel) Date: 6 Jul 2005 09:17:23 -0700 Subject: Conditionally implementing __iter__ in new style classes In-Reply-To: References: Message-ID: <1120666643.702285.206670@f14g2000cwb.googlegroups.com> Why not define an Iterator method in your Base class that does the iteration using __getitem__, and any subclass that wants to do something else just defines its own Iterator method? For that matter, you could just use the __iter__ methods of Base and Concrete instead of a separate method. From A.Lloyd.Flanagan at gmail.com Wed Jul 20 16:45:38 2005 From: A.Lloyd.Flanagan at gmail.com (Adrian Flanagan) Date: 20 Jul 2005 13:45:38 -0700 Subject: python certification References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> Message-ID: <1121892337.873335.68010@g47g2000cwa.googlegroups.com> lordverminard at gmail.com wrote: > i want to get a small certificate or diploma in python. I can recommend brainbench.com (http://www.brainbench.com, of course) for certifications that are both respected and reasonably priced. Only drawback: their Python certification is for version 1.5! They have got to update that. Lloyd Flanagan (Brainbench Master Certified in Python) From nicolas.riesch at genevoise.ch Fri Jul 29 05:25:08 2005 From: nicolas.riesch at genevoise.ch (nicolas_riesch) Date: 29 Jul 2005 02:25:08 -0700 Subject: codecs.getencoder encodes entire string ? References: <1122565377.433764.274280@f14g2000cwb.googlegroups.com> <42E93CFE.3090903@v.loewis.de> Message-ID: <1122629108.013105.322850@g49g2000cwa.googlegroups.com> Thank you very much ! Nicolas From nethawg1 at verizon.net Mon Jul 18 12:12:18 2005 From: nethawg1 at verizon.net (windozbloz) Date: Mon, 18 Jul 2005 16:12:18 GMT Subject: Python scripts wont run - HELP Message-ID: Bye Bye Billy Bob... Hello All, I'm a fairly literate windoz amateur programmer mostly in visual basic. I have switched to SuSE 9.2 Pro and am trying to quickly come up to speed with Python 2.3.4. I can run three or four line scripts from the command line but have not been able to execute a script from a file. I have used EMACS and JEDIT to create small test routines. I would right click the file and set properties to executable. I would then click the icon, the bouncy ball would do its thing then a dialog box would flash on the screen for a fraction of a second. I could tell it had a progress bar on it but could not catch anything else on it. Then nothing else would happen. If I could execute a script the world would once again be my playground... PLEASE HELP. -- LINUX protects me from the GATES of hell !!! From peter at engcorp.com Sat Jul 2 19:16:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 19:16:08 -0400 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: Roy Smith wrote: > Peter Hansen wrote: >>Using time.time() doesn't appear to be suitable, since time might jump >>forwards or backwards at the user's whim, if the system clock is reset, >>or when a daylight savings time change occurs. > > If you get the UTC time, daylight savings time doesn't enter the equation. Hmmm... not only that, but at least under XP the return value of time.time() _is_ UTC. At least, it's entirely unaffected by the daylight savings time change, or (apparently) by changes in time zone. Looks like time.time() might be sufficient. (That might be what Roy intended, but I initially thought he meant time.gmtime(time.time()), which could have resulted in a race condition if time.time() jumped ahead or back separately from some internal daylight savings time flag, and the value was read between the two operations.) -Peter From lsolis at mu.intecsa-inarsa.es Thu Jul 21 06:17:04 2005 From: lsolis at mu.intecsa-inarsa.es (luis) Date: Thu, 21 Jul 2005 10:17:04 GMT Subject: is a file open ? In-Reply-To: <42de3b80$1@news.eftel.com> References: <42de3b80$1@news.eftel.com> Message-ID: John Machin wrote: > Daniel Dittmar wrote: > >> luis wrote: >> >>> for root, dirs, files in os.walk(path): >>> for file in files: >>> # ? is opened ? >> >> >> >> On Linux and some other Unixes, you can probably read the /proc >> filesystem. >> >> On Windows, you'll probably get the quickest result by running >> handle.exe (http://www.sysinternals.com/Utilities/Handle.html). >> >> Either way, the information you'll get is restricted by your permissions. >> >> Either information will get stale really fast, so it's not suitable if >> your task is something like 'can I backup this directory or is someone >> writing to a file?' > > > If that's what the OP had in mind, the question might have been better > phrased as "given the path to a file, how can I tell if it is currently > opened by another process/thread", and better directed to OS-specifc > newsgroup(s). > there is a specific python function ? From travislspencer at gmail.com Wed Jul 20 16:02:29 2005 From: travislspencer at gmail.com (travislspencer at gmail.com) Date: 20 Jul 2005 13:02:29 -0700 Subject: Printing a variable's name not its value In-Reply-To: <1121886771.309517.156380@g47g2000cwa.googlegroups.com> References: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> <1121886771.309517.156380@g47g2000cwa.googlegroups.com> Message-ID: <1121889749.338401.294160@o13g2000cwo.googlegroups.com> Simon Dahlbacka wrote: > as you have been told, there is no way to get a variable's name, take a > look at http://effbot.org/zone/python-objects.htm to find out why this > is so. Thanks, Simon, for the link. -- Regards, Travis Spencer From llgloul at yahoo.fr Mon Jul 18 03:52:40 2005 From: llgloul at yahoo.fr (laurent) Date: 18 Jul 2005 00:52:40 -0700 Subject: What is your favorite Python web framework? In-Reply-To: References: Message-ID: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> hello, I follow somes projects that have a pythonic way to make web site. there's thats projects : http://www.cherrypy.org/ and http://subway.python-hosting.com/ subway aim to be like ruby on rails frameworks , simple and fast developpment. It uses cherrypy and other project like : * http://www.cheetahtemplate.org/ * http://www.formencode.org/ * http://www.sqlobject.org/ From jeff.maitland at gmail.com Tue Jul 5 12:01:14 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Tue, 5 Jul 2005 12:01:14 -0400 Subject: threads and sleep? In-Reply-To: <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> Message-ID: <6829832e05070509012aa8dcf8@mail.gmail.com> Thanks. I was hoping that python would allow for the cpu threading such in Java etc.. but I guess not. (from the answers,and other findings) I guess I will have to write this part of the code in something such as java or c or something that allows for it then I can either wrap it in python or avoid python for this part of the app. Thanks for all the help. From Scott.Daniels at Acm.Org Thu Jul 28 12:11:02 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 28 Jul 2005 09:11:02 -0700 Subject: baffling error-handling problem In-Reply-To: References: Message-ID: <42e8fb33$1@nntp0.pdx.net> Chris Fonnesbeck wrote: > I thought I knew how to do error handling in python, but apparently I > dont. I have a bunch of code to calculate statistical likelihoods, and > use error handling to catch invalid parameters. For example, for the > bernoulli distribution, I have: > > def bernoulli_like(self, x, p, name='bernoulli'): > ... if sum(p>=1 or p<=0): raise LikelihoodError ... > > where LikelihoodError is simply a subclass of ValueError that I created: > > class LikelihoodError(ValueError): > "Log-likelihood is invalid or negative infinite" > > I catch these errors with the following: > > try: like = self.calculate_likelihood() > except LikelihoodError: > return 0 > > ... [when using] ... > like=self.bernoulli_like(x,p) > > I get the following when an invalid parameter is passed: > > Traceback (most recent call last): > File "...\model_000.py", line 381, in ? > model.sample(iterations=iter, burn=burn,plot=False) > File "...\PyMC\MCMC.py", line 1691, in sample > self._like = self.calculate_likelihood() > File "...\model_000.py", line 194, in calculate_likelihood > like+=self.bernoulli_like(x,p) > File "...\MCMC.py", line 868, in bernoulli_like > if sum(p>=1 or p<=0): raise LikelihoodError > LikelihoodError > > I have no idea how this can happen, given how I have coded this. Might you be referring to a different LikelihoodError in the try: ... except ... part of your code than in the ... raise ... part? Similarly defined classes are not the same class. If you didn't get LikelihoodError in mode4l_000.py with the moral equivalent of from MCMC import LikelihoodError then this is what is going wrong. By the way, if it were I, I'd: raise LikelihoodError(p) just so I could discover a bit of what went wrong. --Scott David Daniels Scott.Daniels at Acm.Org From rupole at hotmail.com Wed Jul 20 13:49:43 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 20 Jul 2005 13:49:43 -0400 Subject: Using SHFileOperation References: <1121843013.558480.43380@g43g2000cwa.googlegroups.com> Message-ID: <42de8fe8$1_1@spool9-west.superfeed.net> SHFILEOPSTRUCT is just a tuple, with the elements listed in docs. from win32com.shell import shell, shellcon shell.SHFileOperation((0, shellcon.FO_DELETE, 'somefilename', None, shellcon.FOF_ALLOWUNDO|shellcon.FOF_NOCONFIRMATION)) hth Roger "avishay" wrote in message news:1121843013.558480.43380 at g43g2000cwa.googlegroups.com... > Hi All, > I want to use SHFileOperation using Python and Win32 extentions, in > order to move a file to the trash can. The function itself can be > accessed by importing win32com.shell.shell. However, I cannot find > anywhere the SHFILEOPSTRUCT. This structure is mentioned in the > documentation of the Win32 extentions, but I can't find a way to access > it. > I would appreciate your help. If there's an alternative way to send a > file to the trash can, that can also help. > > Best Regards > Avishay > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From pydecker at gmail.com Sat Jul 30 14:12:14 2005 From: pydecker at gmail.com (Peter Decker) Date: Sat, 30 Jul 2005 14:12:14 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <87oe8kqjhw.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <871x5gs6oy.fsf@wilson.rwth-aachen.de> <87slxwqp32.fsf@wilson.rwth-aachen.de> <87oe8kqjhw.fsf@wilson.rwth-aachen.de> Message-ID: On 7/30/05, Torsten Bronger wrote: > You found a solution for you, which is a good thing. I don't want > to rule out to use Dabo myself. But in my institute I'd like to > present Python as a viable alternative to Delphi. In order to > convince people who are used to a homogeneous rock-solid system, you > must present something equivalent. Of course an open-source project > can never be as homogeneous, but I can't make the whole team switch > to a niche project, ignoring all other GUI alternatives about which > you can even buy books in German! They'll think "strange, that > Python" (or maybe "strange that Torsten" ;). I understand the difficulty of convincing your bosses to use something that isn't the 'most popular'. I have had many disagreements with management who insisted that development be done in Visual Basic instead of Python, because it was the 'standard'. Ugh. But with any luck, enough people will discover the combination of Python, wxPython and Dabo to reach that 'critical mass' that you mentioned earlier. That can only make things better than they are now! -- # p.d. From sjmachin at lexicon.net Sat Jul 9 07:58:04 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 09 Jul 2005 21:58:04 +1000 Subject: Formatting data to output in web browser from web form In-Reply-To: <1120909105.049621.210020@z14g2000cwz.googlegroups.com> References: <1120909105.049621.210020@z14g2000cwz.googlegroups.com> Message-ID: <42CFBBCC.9030700@lexicon.net> Harlin Seritt wrote: > Hi, > > I am using CherryPy to make a very small Blog web app. > > Of course I use a textarea input on a page to get some information. > Most of the time when text is entered into it, there will be carriage > returns. > > When I take the text and then try to re-write it out to output (in html > on a web page), I notice the Python strings don't translate these > special characters (carriage returns) to a "

" so that these > paragraphs show up properly in html for output. I tried doing something > like StringData.replace('\n', '

'). Of course this doesnt work > because it appears that '\n' is not being used. > > Is there anything I can do to make sure paragraphs show up properly? > The ASCII carriage return (CR) is represented in Python as "\x0d" or "\r". The line feed (LF) is "\x0a" or "\n". Does this info help you with your problem? If, not perhaps you might like to print repr(StringData) so that we can see what you are calling "carriage returns". HTH, John From ssweber at gmail.com Sat Jul 16 15:02:53 2005 From: ssweber at gmail.com (samuels) Date: 16 Jul 2005 12:02:53 -0700 Subject: Parsing html :: output to comma delimited Message-ID: <1121540573.555193.243760@g49g2000cwa.googlegroups.com> Hello All, I am a total python newbie, and I need help writing a script. This is what I want to do: There is a list of links at http://www.rentalhq.com/fulllist.asp. Each link goes to a page like, http://www.rentalhq.com/store.asp?id=907%2F272%2D4425, that contains a company name, address, phone, and fax. I want extract each page, parse this information, and export it to a comma delimited text file, or tab delimited. The important information in each page is: from the first line you can see that submitting the result will request the page "busquedas_b.html" -- so your script has to request this site directly with the form parameters given as additional data (method="POST"). which form parameters to pass can be seen in the name attributes of the input-tags, e.g. . urllib provides the methods urlopen and urlencode to setup the query string and fetch the result: from urllib import urlopen,urlencode form_data = { 'byDay' : '12' , 'byMonth' : '07' , 'byYear' : '2005' } html_data = urlopen( "http://www.los40.com/actualidad/listas/busquedas_b.html", urlencode(form_data) ).read() print html_data - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman From grante at visi.com Fri Jul 1 11:10:13 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jul 2005 15:10:13 -0000 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: <11can6l9ldmdeaa@corp.supernews.com> On 2005-06-30, xeys_00 at yahoo.com wrote: > I have read in the old days that C was used for everything. It > was a systems programming language, and also did a lot of the > same stuff Bash scripts and perl do now. Not really. C was used for a lot of stuff (mostly just under Unix), but there was still tons of COBOL, FORTRAN, Lisp, and a bunch of other languages. Under Unix bourne shell (from which bash evolved) has always been popular for scripting. Sed and awk scripts have been popular for ages as well. Other OSes have various JCL and batch scripting languages. C was only popular under Unix OSes -- under most other OSes, C wasn't popular at all. MacOS and Windows APIs were originally designed for use by Pascal, VAX/VMS was apparently intended to be used via FORTRAN and BLISS-32. C was later made available on those platforms but you could tell it didn't really "fit" well with the OS. > So, in that era, C did it all, from short to tall. My memory only goes back about 25 years, but that was never true in my experience. > My question is, can Python "do it all"? I am wondering what to > learn as my scripting language. First, stop thinking in the singular. For starters I'd recommend bash, Python, and awk. Add perl if you like, but I think it's syntax/semantics are extraordinarily nasty (I even find the Lisp family of languages far easier to read). > I have read that perl is good up to about 250 lines, and after > that it gets kind of hairy. In my experience it get's hairy a lot faster than that. :) > However, from what little I have heard about Python, it's very > well suited for readability due to the whitespace requirements > of the language, and very good for large projects due to it's > large amount of modules and it's object oriented structure. True. > I would like opinions as to the suitability of Python as a > general purpose language for programming unix, everything from > short scripts to muds. I use Python for all sorts of programs under from a couple lines for a normal text filter to thousands of lines with a complex GUI. [Why are Python programs referred to as "scripts". Python no more a "scripting" language than Java, Pascal, Smalltalk, Objective C.] -- Grant Edwards grante Yow! Yow! We're going to at a new disco! visi.com From tjreedy at udel.edu Tue Jul 19 13:52:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 19 Jul 2005 13:52:01 -0400 Subject: Dictionary, keys and alias References: <42D780EF.6020809@sweetapp.com><20050717210438.GA17650@gate2.hazen.net><5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: "Steven D'Aprano" wrote in message news:pan.2005.07.19.13.56.18.857714 at REMOVETHIScyber.com.au... > On Tue, 19 Jul 2005 10:20:04 +0200, Glauco wrote: > >>> The only niggly worry I have is I'm not sure when hash can be used, >>> when >>> it is unique, or even if is it guaranteed to be unique. >>> >> >> Thank Steve, the idea was the same... >> but yours using hash is much elegant. > > I'm still worried about hash of two unrelated objects returning the same > value. > > Another implementation is to keep a hidden attribute of the object, and > initialise it to the integer 0. Instead of using hash(key), you use the > current value of the integer, then increment the integer by one. > > This is guaranteed to be unique, no matter what. id(ob) is already guaranteed to be a unique integer while ob exists. So, if I understand the goal, map possibly-multiple-keys each to id and id to ob. Terry J. Reedy From http Sun Jul 31 20:45:07 2005 From: http (Paul Rubin) Date: 31 Jul 2005 17:45:07 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <8664uqhkfj.fsf@bhuda.mired.org> <7xu0iale9x.fsf@ruckus.brouhaha.com> Message-ID: <7x4qaa32p8.fsf@ruckus.brouhaha.com> Cliff Wells writes: > > The usual way to do that is with a web GUI, but nothing stops you from > > running Tkinter on a Unix server through a remote X connection. > > Of course not, but unless the servers are on a trusted network and use > an authentication scheme such as kerberos, you are asking for trouble. If it's for sensitive stuff normally you'd use https. From skip at pobox.com Thu Jul 14 14:14:38 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 14 Jul 2005 13:14:38 -0500 Subject: Python Installation error on Solaris-9-SPARC In-Reply-To: <1121363416.498522.138420@g43g2000cwa.googlegroups.com> References: <1121362775.799428.239840@g47g2000cwa.googlegroups.com> <1121363416.498522.138420@g43g2000cwa.googlegroups.com> Message-ID: <17110.43918.136947.522919@montanaro.dyndns.org> Madhu> I did... Madhu> 1. wget http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz Madhu> 2. gunzip -c Python-2.4.1.tgz | tar xvf - Madhu> the above step errors: Madhu> -------- Madhu> tar: directory checksum error Madhu> gunzip: stdout: Broken pipe Madhu> -------- You can't use Sun's tar to unpack the tarfile. The directory structure is too deep. Get ahold of GNU tar instead. Skip From ric at next-level.com.au Mon Jul 11 13:54:07 2005 From: ric at next-level.com.au (Ric Da Force) Date: Tue, 12 Jul 2005 01:54:07 +0800 Subject: Tricky Dictionary Question from newbie Message-ID: Hi all, I have a dictionary containing about 300 items, some of the values being repeated. Both keys and values are strings. How can I turn this thing on its head so that we create a key based on each unique value and build the values based on the keys corresponding to the repeated values? It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} I am still learning Python and have struggled with this for hours before deciding to go for help. Unfortunately, I didn't really know how to search for this in google and decided to post it here. I apologise if this is too basic for this newsgroup... Ric From paul at boddie.org.uk Wed Jul 6 09:54:44 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Jul 2005 06:54:44 -0700 Subject: best options for oracle/python? References: <6wAye.1255$Tc6.1131@newssvr13.news.prodigy.com> Message-ID: <5339b60d.0507060554.583f4f4f@posting.google.com> Mark Harrison wrote in message news:<6wAye.1255$Tc6.1131 at newssvr13.news.prodigy.com>... > Any recommendations for Oracle bindings for the > DB-API 2.0 specification? This is for Oracle 10g > if that makes any difference. > > Also, any other Oracle related goodies that might > be useful? You might want to check out the database topic guide for Python... http://www.python.org/topics/database/modules.html ...as well as the DB-SIG resources and mailing list: http://www.python.org/sigs/db-sig/ http://mail.python.org/pipermail/db-sig/ Paul From peter at engcorp.com Mon Jul 4 09:48:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Jul 2005 09:48:12 -0400 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: Message-ID: Coates, Steve (ACHE) wrote: > > There is already an NTP client in the ASPN cookbook :- > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117211 Thanks Steve. As it turns out, Windows XP already has support (via NTP I presume, though of course since this is Microsoft they try to keep the user base ignorant by making no mention of that even in the help page) for keeping the clock accurate, right on the last tab (labelled "Internet Time") of the Date and Time Properties dialog. And on Linux, of course, this is already a trivial matter. With what Tim clarified about time.time(), it will be quite sufficient when used in conjunction with a threatened slap on the wrist (or a label on the side of the monitor) for any user who tries to change the clock... (Thanks, Tim! time.time() makes sense finally.) -Peter From velocity.travlr at gmail.com Thu Jul 21 04:13:22 2005 From: velocity.travlr at gmail.com (travlr) Date: 21 Jul 2005 01:13:22 -0700 Subject: How to use octave in python References: <1121905932.531027.154080@g49g2000cwa.googlegroups.com> Message-ID: <1121933601.901690.4630@g49g2000cwa.googlegroups.com> And or numarray :) http://www.stsci.edu/resources/software_hardware/numarray From gsakkis at rutgers.edu Fri Jul 1 11:56:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 08:56:08 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> Message-ID: <1120233368.942731.307230@g44g2000cwa.googlegroups.com> > Seems like he wants python programmers to solve their problems all in the > same way. While that is great for corporate slaves it is terrible for the > creative programmer. > Python is quickly becoming the visual basic of the 21 century. If you want > to have fun while getting some work done you need to look elsewhere. It's a > shame... What do we have here, a perl troll ? Perhaps you need to post elsewhere "to have fun". George From noreply at python.org Tue Jul 12 01:41:48 2005 From: noreply at python.org (Post Office) Date: Tue, 12 Jul 2005 08:41:48 +0300 Subject: Returned mail: see transcript for details Message-ID: <20050712054227.033511E4002@bag.python.org> ?8G????????X??9Z??4??Y??4??!???u?x?? {???Yt8??Y2f?? L???kUp?}R?>????t???????c?????hL????wU??m?^?R&??i5??5??*?7?Li)'?tY??j?f2J\?w?C?}wW'????`;?> From zanesdad at bellsouth.net Fri Jul 8 12:51:22 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 08 Jul 2005 12:51:22 -0400 Subject: file handling in a server (.py) file using xmlrpc In-Reply-To: References: Message-ID: <42CEAF0A.600@bellsouth.net> uwb wrote: >I've got a call to glob in a .py file sitting in an apache cgi-bin directory >which refuses to work while the exact same code works from a python console >session. > >I'm guessing that in order to read or write files from any sort of a script >file sitting in the cgi-bin directory on a server, something has to be set >to allow such activity. I'd appreciate it if anybody with as clue as to >what that was could tell me about it. > > > > > So, what do you mean "refuses to work"? Is the cgi script not executing at all? Spitting out an error? If so, what error? (And is it an error to the browser calling the cgi script, or in your apache logs?) Jeremy Jones From alexander.chadwick at gmail.com Thu Jul 28 05:52:22 2005 From: alexander.chadwick at gmail.com (ch424) Date: 28 Jul 2005 02:52:22 -0700 Subject: Trigger pygtk drawingarea redraw Message-ID: <1122544342.581358.274980@g43g2000cwa.googlegroups.com> Hi, Does anybody know the fastest way to trigger a DrawingArea redaw in pygtk? At the moment, I'm using a bit of a hack: def redraw(self): self.area.hide() self.area.show() Is there a better way to trigger a redraw? This causes flickering when the window gets bigger than 400x400 pixels, which is a nuisance... there must be a better way of clearing the area and letting it redraw itself? Many thanks for any help, Alex From dalke at dalkescientific.com Sat Jul 23 03:56:39 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 23 Jul 2005 07:56:39 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> <1122074127.098fda4a2097406639f8c6b7f8b523ed@teranews> <1122103716.047d4c80bde51f39c1c9b5251fd07bfc@teranews> Message-ID: George Sakkis wrote: > That's why phone numbers would be a subset of integers, i.e. not every > integer would correspond to a valid number, but with the exception of > numbers starting with zeros, all valid numbers would be an integers. But it's that exception which violates the LSP. With numbers, if x==y then (x,y) = (y,x) makes no difference. If phone numbers are integers then 001... == 01... but swapping those two numbers makes a difference. Hence they cannot be modeled as integers. > Regardless, this was not my point; the point was that adding > two phone numbers or subtracting them never makes sense semantically. I agree. But modeling them as integers doesn't make sense either. Your example of adding phone numbers depends on them being represented as integers. Since that representation doesn't work, it makes sense that addition of phone number is suspect. > There are (at least) two frequently used path string representations, > the absolute and the relative to the working directory. Which one *is* > the path ? Depending on the application, one of them woud be more > natural choice than the other. Both. I don't know why one is more natural than the other. >> I trust my intuition on this, I just don't know how to justify it, or >> correct it if I'm wrong. > > My intuition also happens to support subclassing string, but for > practical reasons rather than conceptual. As you may have read elsewhere in this thread, I give some examples of why subclassing from string fits best with existing code. Even if there was no code base, I think deriving from string is the right approach. I have a hard time figuring out why though. I think if the lowest level Python/C interface used a "get the filename" interface then perhaps it wouldn't make a difference. Which means I'm also more guided by practical reasons than conceptual. Andrew dalke at dalkescientific.com From sjmachin at lexicon.net Wed Jul 20 06:57:06 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Jul 2005 20:57:06 +1000 Subject: is a file open ? In-Reply-To: References: Message-ID: <42de2e02@news.eftel.com> luis wrote: > for root, dirs, files in os.walk(path): > for file in files: > # ? is opened ? > ? rtfm ! "files" is a list of fileNAMEs -- i.e. strings. ? How could you possibly imagine that your sample code would open a file? What a design-nonsense that would be: instant complaints from folk who wanted to do some further selection before opening (if they ever wanted to open the files at all). ? Did you contemplate *trying* this code to see what happened ? ? Don't use "file" as a name; it shadows the built-in file function ! From gregpinero at gmail.com Tue Jul 12 15:20:52 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 12 Jul 2005 15:20:52 -0400 Subject: Web client, https and session management In-Reply-To: <11d7oqmr47jc53@corp.supernews.com> References: <1121182118.684389.182950@g14g2000cwa.googlegroups.com> <11d7oqmr47jc53@corp.supernews.com> Message-ID: <312cfe2b050712122024dd16bc@mail.gmail.com> How's this for an answer, it even uses yahoo in the example! http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/391929 Greg From thomasbartkus at comcast.net Mon Jul 18 14:04:33 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 18 Jul 2005 13:04:33 -0500 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: > Jeff Epler wrote: > > > I honestly don't know why anyone would spend money for a development > > environment, no matter how fancy. I don't knowdefinitelye would develop > > software in a language that doesn't have at least one open > > implementation. It's called (ROI) Return On Investment. If you can get that to a positive number, then spending money on the tool is a no brainer. Given that one caveat, a sane person will just do it! If I can create something that earns $10,000 or more in profit, then the difference between a tool that costs $500 and one that is free amounts to small beer. IOW - it hardly matters! The only decision one needs be concerned with is which tool is most effective. > > It's a great way to get screwed when Borland goes under or decides > > they only want to sell a new, incompatible product. What do you do with > > your existing product when that happens? Your existing products are not affected. The compiler tools you have will work just as well as the day you bought it. Your ownership of the product does not get revoked just because Borland dissapears. > > Re-train on a new platform, > > and re-write from scratch? What do you do when an open source project you were using gets abandoned? Hard to see much difference here. Thomas Bartkus From thanos at sians.org Sun Jul 24 05:07:02 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 12:07:02 +0300 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <20050724090702.GB9121@zermelo.sians.org> On Sat, Jul 23, 2005 at 06:59:43PM -0600, Steven Bethard wrote: > Thanos Tsouanas wrote: > > I would like to have a quick way to create dicts from object, so that a > > call to foo['bar'] would return obj.bar. > > > > The following works, but I would prefer to use a built-in way if one > > exists. Is there one? > > Maybe I'm not understanding your problem, but have you looked at the > builtin "vars()"? I didn't know about it, but I knew about object.__dict__ which is, as I see equivalent with vars(object). But it doesn't do the job for me, since it fails to grab all obj.foo's, some of them being properties, etc. vars() is good to know though, Thanks! -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From sjmachin at lexicon.net Fri Jul 22 18:14:49 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 08:14:49 +1000 Subject: Extending python - undefined symbol error on import In-Reply-To: <1122047378.752186.6840@z14g2000cwz.googlegroups.com> References: <1122047378.752186.6840@z14g2000cwz.googlegroups.com> Message-ID: <42e16fd9$1@news.eftel.com> ch424 wrote: [snip] > However, when I open up the python command line, and type "from gpib > import *" or "import gpib" I get "ImportError: /usr/.../gpibmodule.so: > undefined symbol: ibdev" -- but I know it's defined in the ni488.h > file, especially as I can use this code from actual C programs without > problems. The ni488.h file in in the right place to be used for C > compilation. > > So, the question is, what did I type wrong? Why is python examining > that c function embedded in another, surely it should only be > interested in providing arguments and getting returned values, and what > the c function does is its own bussiness? > Daniel has already given you what to do to get over your immediate problem. I'd just like to add a couple of mindset adjustments to get you over the next few stiles. The message ".... gpibmodule.so: undefined symbol: ibdev" is being reported by Python, but this problem is detected by an operating-system specific loader. What it is trying to tell you is that gpibmodule.so contains a call to a function named ibdev, but the loader can't find ibdev. This is nothing to do with extending Python; if you had written a stand-alone program in C, and made the same mistake [not providing the name of the library containing ibdev], you would have got a similar message either from the linker or later from the loader. Neither Python nor the loader is "examining" ibdev, the loader can't even find it, and Python has no way of knowing that it exists (and doesn't and shouldn't care) even if the loader could find it! It is the job of *your* code to interface with the ibdev routine. Another slant on all this: the problem doesn't exist on the boundary between Python and your extension module; it exists on the boundary between your module and a 3rd party function called by your module. HTH, John From gsakkis at rutgers.edu Tue Jul 5 15:59:28 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jul 2005 12:59:28 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> <1120592778.753940.162280@z14g2000cwz.googlegroups.com> Message-ID: <1120593568.781202.114580@g44g2000cwa.googlegroups.com> "Devan L" wrote: > def flatten(iterable): > if not hasattr(iterable, '__iter__'): > return [iterable] > return sum([flatten(element) for element in iterable],[]) > Recursion makes things so much shorter. The last line can faster and more compact by: from itertools import imap def flatten(iterable): if not hasattr(iterable, '__iter__'): return [iterable] return sum(imap(flatten,iterable),[]) George From LISTSERV at LISTSERV.UARK.EDU Mon Jul 25 08:30:38 2005 From: LISTSERV at LISTSERV.UARK.EDU (University of Arkansas LISTSERV Server (14.3)) Date: Mon, 25 Jul 2005 07:30:38 -0500 Subject: Message ("Your message dated Mon, 25 Jul 2005 14:21:50...") Message-ID: Your message dated Mon, 25 Jul 2005 14:21:50 +0200 with subject "Status" has been submitted to the moderator of the VMESA-L list: moderator at GIZMOWORKS.COM. From caleb1 at telkomsa.net Wed Jul 20 16:13:25 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Wed, 20 Jul 2005 22:13:25 +0200 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu> Message-ID: Wow, I didn't know about enumerate. Many thanks Caleb On Wed, 20 Jul 2005 15:19:50 +0200, Simon Brunning wrote: > On 7/20/05, Mage wrote: >> Or is there better way? >> >> for (i, url) in [(i,links[i]) for i in range(len(links))]: > > for i, url in enumerate(links): > From gh at ghaering.de Tue Jul 19 13:00:10 2005 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 19 Jul 2005 19:00:10 +0200 Subject: dictionary as property In-Reply-To: <20050719165620.GA4136@zermelo.sians.org> References: <20050719165620.GA4136@zermelo.sians.org> Message-ID: <20050719170010.GA28430@mylene.ghaering.de> On Tue, Jul 19, 2005 at 07:56:20PM +0300, Thanos Tsouanas wrote: > Hello. > > (How) can I have a class property d, such that d['foo'] = 'bar' will run > a certain function of the class with 'foo' and 'bar' as it's arguments? You could implement a custom container type that will do what you want. See http://docs.python.org/ref/sequence-types.html for __setitem__. Quick hack: >>> class Foo: ... def __init__(self): ... self.d = self ... def __setitem__(self, key, value): ... getattr(self, key)(value) ... def bar(self, param): ... print "bar got called with", param ... >>> foo = Foo() >>> foo.d["bar"] = 42 bar got called with 42 >>> -- Gerhard -- Gerhard H?ring - gh at ghaering.de - Python, web & database development -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 03:59:15 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 09:59:15 +0200 Subject: Detecting computers on network References: <1122006490.221581.239840@z14g2000cwz.googlegroups.com> Message-ID: linuxfreak enlightened us with: > How about sending an ICMP echo packet to your broadcast address and > checking which hosts send a reply Won't work on all boxes. Windows boxes ignore broadcast pings, for example. I'd go for a call to "nmap -sP" instead, and filter it's output. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From Scott.Daniels at Acm.Org Thu Jul 28 11:56:20 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 28 Jul 2005 08:56:20 -0700 Subject: functions without parentheses In-Reply-To: References: Message-ID: <42e8f7c2$1@nntp0.pdx.net> Jerry He wrote: > ... Is there some way to define [examine] so I can call it like > examine "string" > instead of examine("string")? Perhaps you are looking for ipython (google for it) if all you are looking for is ease of interactive entry. --Scott David Daniels Scott.Daniels at Acm.Org From mwm at mired.org Fri Jul 8 00:48:55 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 08 Jul 2005 00:48:55 -0400 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <42oiad.vg8.ln@lightning.itga.com.au> Message-ID: <86d5ptvr60.fsf@bhuda.mired.org> Jorgen Grahn writes: > Hey, it's not fair to make fun of emacs now that I've mentioned vim > favourably so many times ;-) > > Seriously, nothing about emacs seems big or slow today. It has been > outbloated by pretty much everything else. Who could have imagined /that/ > ten years ago? Actually, it hasn't. Then again, maybe it depends on how you use it. I start an xemacs at login, and leave it running forever. Just like I do a shell. It slowly accretes buffers as time goes by, many of them useless (why do I need to keep traces of 14 POP sessions around?). As a result, xemacs is usually the second biggest thing on my system I treat most programs that way. I never exit them, just unmap them. My WM is configured to map a single existing window, launch the application if there is no existing window, or offer a menu of windows if there's more than one existing window when I ask for an application. So I tend to have a lot of old, big processes on the system. And xemacs is usually bigger than everything but X. And people wondered when I complained that Mac OS 9 and Windows 98 crashed a lot :-). http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rkern at ucsd.edu Sat Jul 2 00:03:30 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 01 Jul 2005 21:03:30 -0700 Subject: Bad Math In-Reply-To: References: Message-ID: Patrick Rutkowski wrote: > I started reading a python book today, one example was: > >>>>4 / (2.0 + 3) > > 0.8 Must be an old book. > My input/output was: > >>>>4 (2.0 + 3) > > 0.80000000000000004 This is correct. > Something smells fishy here... whats up? > > --python 2.4.1 http://docs.python.org/tut/node16.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sjmachin at lexicon.net Wed Jul 13 19:16:10 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Jul 2005 09:16:10 +1000 Subject: 2.4 Recent File list not working In-Reply-To: References: Message-ID: <42d5a0ba$1@news.eftel.com> Larry Bates wrote: > I recently upgraded from 2.2 to 2.4 (ActiveState for Windows). > I was accustomed to having the most recent 10 files that I had > edited show up under File menu under Recent. "File menu" of what? Let's guess that you mean Pythonwin. The problem is now fixed. It is possible that you need to get the latest pywin32 or get the latest ActiveState distribution ... go look. From kirk at jobsluder.net Fri Jul 8 14:02:33 2005 From: kirk at jobsluder.net (Kirk Job Sluder) Date: Fri, 08 Jul 2005 18:02:33 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120834070.272672.143850@f14g2000cwb.googlegroups.com> Message-ID: <87br5d2n0a.fsf@debian.kirkjobsluder.is-a-geek.net> "Kay Schluehr" writes: > This might be a great self experience for some "great hackers" but just > annoying for others who used to work with modular standard librarys and > think that the border of the language and an application should be > somehow fixed to enable those. In what way do lisp macros prevent the creation of modular libraries? Common Lisp does does have mechanisms for library namespaces, and in practice a macro contained within a library is not that much different from a function contained in a library or a class contained in a library. Macros just provide another mechanism for creating useful domain-specific abstractions. The primary advantage to macros is that you can create abstractions with functionality that is not easily described as either a function or a class definition. > Kay -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From jstier at cs.uvic.ca Sun Jul 10 17:33:28 2005 From: jstier at cs.uvic.ca (J) Date: 10 Jul 2005 14:33:28 -0700 Subject: inheritance Message-ID: <1121031208.829250.82160@g44g2000cwa.googlegroups.com> Hi I am trying to make a C++ class hierarchy accessible to python scripts. Am I right to assume that the type structure of a derived class must have all the members of its base class declared as well ? For example, typedef struct { PyObject_HEAD int somebaseclassmember; } PyStructBaseClass is the structure for a base class. In this case, the structure for a derived class would have to look like typedef struct { PyObject_HEAD ScnNode* mObject; int somebaseclassmember; float somederivedclassmember } PyStructDerivedClass; Is this true ? I have linked the derived class type to the base class type via tp_base. I don't think that when I instantiate a derived class, a PyStructBaseClass is being created. I believe that if PyStructDerivedClass was missing the "int somebaseclassmember;" then the offset for that memory would point into the float during base class member lookups .... ??? Any thoughts ? Cheers Jochen From tdelaney at avaya.com Sun Jul 31 21:52:32 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 1 Aug 2005 11:52:32 +1000 Subject: [path-PEP] Path inherits from basestring again Message-ID: <2773CAC687FD5F4689F526998C7E4E5F0742A3@au3010avexu1.global.avaya.com> I have to say, the examples of using / don't really suggest path concatenation to me. However, I think the problem is the use of whitespace. Specifically:: path = Path() subdir = "subdir" f = "filname" path = path / subdir / f looks more like division (even with the obvious names I've used). OTOH: path = path/subdir/f *does* look a lot more like path concatenation. So for some people it may be how it is used. On the gripping hand, the second example reads more like a regex to me ... ;) OK - now for the silly suggestions ... I'm feeling tired ... methinks Guido would not be happy if I suggested the following on python-dev ;) For a relative path: path = ./subdir/f path = ../subdir/f For an absolute path: path = /dir/f Both of these are currently syntax errors. Introduce the . and .. syntax which map to calls to Path() and Path(os.path.dirname(os.cwd()) respectively, and the unary division operator (which can either preceed or follow the object). Hey - paths are special enough to warrant additional syntax, aren't they? Tim Delaney From http Sun Jul 31 22:38:03 2005 From: http (Paul Rubin) Date: 31 Jul 2005 19:38:03 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <8664uqhkfj.fsf@bhuda.mired.org> <7xu0iale9x.fsf@ruckus.brouhaha.com> <7x4qaa32p8.fsf@ruckus.brouhaha.com> Message-ID: <7x7jf6xtys.fsf@ruckus.brouhaha.com> Cliff Wells writes: > > If it's for sensitive stuff normally you'd use https. > > Hm, I haven't tried piping X over https... I wasn't even aware it was > possible... do you have a link I can check this out on? I meant https for web interfaces. For other protocols it's simplest to use stunnel or ssh (stunnel is probably a better choice), or run your whole net connection through ipsec or whatever. From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 08:09:51 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 14:09:51 +0200 Subject: Detecting computers on network References: Message-ID: Peter Tillotson enlightened us with: > You could use a sniffer in promiscuous mode. pypcap -- or something > like. This will record every packet seen by your network card. > Whether is will work depends on whether you are on a true braodcast > network. That's not going to work on a switched network, which most modern networks are. > Windows boxes positively shout about there presence :-) Definitely true. > baically this is pasive nmap, nmap will try to open a tcp or udp > connection on every machine. your going to generat a lot of > traffic. Not if you tell it to use ICMP pings only. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From sbassi at gmail.com Wed Jul 20 14:47:13 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Wed, 20 Jul 2005 15:47:13 -0300 Subject: How to store "3D" data? (data structure question) In-Reply-To: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> References: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> Message-ID: On 20 Jul 2005 10:47:50 -0700, Graham Fawcett wrote: > # zip is your friend here. It lets you iterate > # across your line names and corresponding values > # in parallel. This zip function is new to me, the only zip I knew was pkzip :). So will read about it. -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From grante at visi.com Tue Jul 12 11:13:53 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Jul 2005 15:13:53 -0000 Subject: append one file to another References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> <1121179119.788276.92280@f14g2000cwb.googlegroups.com> Message-ID: <11d7nhhhrmgrd22@corp.supernews.com> On 2005-07-12, b83503104 at yahoo.com wrote: > As a side question, you mentioned opening files in binary > mode, in case the code needs to run under Windows or > cross-platform. What would happen otherwise? Is it an issue > of big little endian or some other issue? The end-of-line characters might get converted -- even if they're not really "end-of-line" characters in the file in question. -- Grant Edwards grante Yow! My mind is a potato at field... visi.com From jaymail at gawab.com Fri Jul 29 13:50:43 2005 From: jaymail at gawab.com (Jay) Date: 29 Jul 2005 10:50:43 -0700 Subject: writing a web client In-Reply-To: <1122642828.810852.146650@g14g2000cwa.googlegroups.com> References: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> <1122642828.810852.146650@g14g2000cwa.googlegroups.com> Message-ID: <1122659443.714192.253690@o13g2000cwo.googlegroups.com> thats pretty cool, could someone post a example program of a python web-based program? From albert at compuscan.co.za Thu Jul 28 02:57:36 2005 From: albert at compuscan.co.za (Albert Leibbrandt) Date: Thu, 28 Jul 2005 08:57:36 +0200 Subject: trying to access Oracle In-Reply-To: <000901c592ca$9ea61220$8235a8c0@co.montezuma.co.us> Message-ID: <20050728065751.A29F01E4002@bag.python.org> >> I am trying to access Oracle using the cx_Oracle module. I can login to Oracle OK, but I >> am at a loss as to how I should then access the specific table I need so that I can join it to >> our county parcel layer using the "make table view" tool. I have scoured the internet looking >> for any examples and have found little that makes sense (to me). Can anyone help? The >> table I need is called ASR.TEMP_OWNERSHIP. The password, username, and TNS is all >> "asr". >> I'm not quite to the point where I can think for myself and improvise with python. Import cx_Oracle conn = cx_Oracle.connect('username','password','tns') cursor = conn.cursor() cursor.execute("whatever you feel like executing") Hope it helps cheers Albert -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftset at gmail.com Sat Jul 9 18:17:33 2005 From: swiftset at gmail.com (Alex Gittens) Date: Sat, 9 Jul 2005 17:17:33 -0500 Subject: already written optparse callback for range and list arguments? Message-ID: I would like my program to accept a list of range values on the command line, like -a 1 -a 1-10 -a 4,5,2 In the interest of avoiding reinventing the wheel, is there already available code for a callback that would enable optparse to parse these as arguments? Thanks, Alex -- ChapterZero: http://tangentspace.net/cz/ From jaymail at gawab.com Fri Jul 29 23:05:13 2005 From: jaymail at gawab.com (Jay) Date: 29 Jul 2005 20:05:13 -0700 Subject: Hiding In-Reply-To: References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> <1122662993.207041.89630@f14g2000cwb.googlegroups.com> Message-ID: <1122692712.976074.48870@g49g2000cwa.googlegroups.com> thanks for the great info and urls, i have downloaded the pymedia module and playing around with it now. Thx alot From mage at mage.hu Tue Jul 12 08:07:57 2005 From: mage at mage.hu (Mage) Date: Tue, 12 Jul 2005 14:07:57 +0200 Subject: cursor positioning In-Reply-To: <1121105408.19900@news.liwest.at> References: <1121105408.19900@news.liwest.at> Message-ID: <42D3B29D.90307@mage.hu> Danny Milosavljevic wrote: >Hi, > > > >Examples > ESC[2JESC[H same as "clear", clear screen, go home > \rESC[Kprogress %d probably what you want :) > > Well, like the good old Commodore times :) Thank you. Mage From chris.kang.83 at gmail.com Sat Jul 2 18:49:20 2005 From: chris.kang.83 at gmail.com (Christopher Kang) Date: Sat, 2 Jul 2005 18:49:20 -0400 Subject: Python, mysql, floating point values question In-Reply-To: <43b72594050701154055297e73@mail.gmail.com> References: <43b72594050701154055297e73@mail.gmail.com> Message-ID: <43b7259405070215493a967a1b@mail.gmail.com> Thanx all for responding. I've been doing the epsilon comparisons, i had just hoped that to be a temporary solution. anyway, thanx for the responses From ed at leafe.com Thu Jul 7 06:55:18 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 7 Jul 2005 06:55:18 -0400 Subject: Do a "Python beginners e-mail list" exist? In-Reply-To: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> References: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> Message-ID: <9437f8a9c51d0361ed3e388f2c2974e4@leafe.com> On Jul 7, 2005, at 3:24 AM, Alessandro Brollo wrote: > 1. I don't want to post banal questions about Python > to main Python list. Does a "banal Python questions > list" or a "Python beginners list" exist? > > 2. There is somewhere a very patient fellow willing to > be my free "python tutor" by personal e-mailing > outside the mail list? . The ideal candidate would be > someone, sharing with me some other fields of interest > (I'm a middle-aged Italian pathologist, with some > dBase III and dBase IV past programming experience, > and I like nature and mainly horses). There is an email list called ProPython (http://leafe.com/mailman/listinfo/propython) that was started by a group of Visual FoxPro developers who are taking up Python. So it is definitely newbie-friendly, and has many people willing to help walk you through the learning process. And with your database programming background, you're sure to fit in with a Fox-flavored crowd! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From gene.tani at gmail.com Sat Jul 23 11:00:00 2005 From: gene.tani at gmail.com (gene tani) Date: 23 Jul 2005 08:00:00 -0700 Subject: Using python to runother programs In-Reply-To: <1122054694.450950.216900@g44g2000cwa.googlegroups.com> References: <1122054694.450950.216900@g44g2000cwa.googlegroups.com> Message-ID: <1122130800.453925.82690@g47g2000cwa.googlegroups.com> this isn't really enough data to go on. What operating system (sounds like win2k/XP), does Crystal reports and unnamed accounting software have COM hooks? Look at Simon Brunning posts: http://www.brunningonline.net/simon/blog/archives/000652.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003 From matt.schinckel at gmail.com Sat Jul 30 06:34:10 2005 From: matt.schinckel at gmail.com (matt.schinckel at gmail.com) Date: 30 Jul 2005 03:34:10 -0700 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> Message-ID: <1122719650.847969.200750@f14g2000cwb.googlegroups.com> Dark Cowherd wrote: >> GUI, Web development, Application Framework - it is shambles. >Yeah, I agree. When I finally make that GUI application I still don't >know whether I am going to use wx or PyGTK. I was part of the anygui development team, back when it was still active (I think I technically am still part of the team, we just haven't checked in any new code since I left BeOS!). It was a plan to allow GUI access to be as simple and 'once' as anydb does for accessing the database systems it does. We failed. Although we did actually have some code that was working really well, across several platforms and GUI systems. From mrmaple at gmail.com Tue Jul 12 10:09:52 2005 From: mrmaple at gmail.com (James Carroll) Date: Tue, 12 Jul 2005 10:09:52 -0400 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: <3jftckFpvhv2U2@individual.net> Message-ID: Oops.. Gmail just normally puts the reply to at the bottom of the discussion... so by default I reply to the list, and the last person to post. My comment was not directed at you. I just posted the contents of an interactive session that I did to better understand setdefault myself. I've got to remind myself to change the reply-to address to the list. (other lists do this by default, why not this one?) I agree that the name doesn't ring quite right to me either. I kind of understand what the creator of the function was getting at... it's kind of like when you want to retrieve a configuration variable from a container, but if it's not there, then you want to use a default: storedWidth = container.GetConfigurationValue(name = "width", default=500) If there is a width stored, it will retrieve that, otherwise it will give you the default that you specified in the second parameter. It makes it easier than checking for existance, then retrieving or assigning a default. Setdefault, in my mind is really a _get_ kind of operation. It retrieves from the dictionary most of the time, and only does anything different when the key doesn't exist, and then does an assignment... so my next guess at a better name for setdefault would be: value = container.GetOrAddDefault(key="a", default=[]) value.append(listvalue) but that's kind of confusing too, but it better describes what is happening. -Jim On 7/12/05, Peter Hansen wrote: > (Fixed top-posting) > > James Carroll wrote: > > On 7/11/05, Peter Hansen wrote: > >>(I always have to ignore the name to think about how it works, or it > >>gets in the way of my understanding it. The name makes fairly little > >>sense to me.) > > > Notice the dictionary is only changed if the key was missing. > > James, I'll assume your reply was intended to address my comment above. > From paddy3118 at netscape.net Sun Jul 31 14:17:42 2005 From: paddy3118 at netscape.net (Paddy) Date: 31 Jul 2005 11:17:42 -0700 Subject: Thaughts from an (almost) Lurker. In-Reply-To: References: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Message-ID: <1122833862.936009.130890@o13g2000cwo.googlegroups.com> L.OL :-) From python-ml at nn7.de Sun Jul 24 10:30:19 2005 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Sun, 24 Jul 2005 16:30:19 +0200 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: <1122175536.959648.101230@z14g2000cwz.googlegroups.com> References: <1122175536.959648.101230@z14g2000cwz.googlegroups.com> Message-ID: <1122215419.30698.46.camel@localhost> On Sat, 2005-07-23 at 20:25 -0700, Dan Bishop wrote: > Soeren Sonnenburg wrote: > > Hi all, > > > > Just having started with python, I feel that simple array operations '*' > > and '+' don't do multiplication/addition but instead extend/join an > > array: > > > > a=[1,2,3] > > >>> b=[4,5,6] > > >>> a+b > > [1, 2, 3, 4, 5, 6] > > > > instead of what I would have expected: > > [5,7,9] > > To get what you expected, use > > [x + y for (x, y) in zip(a, b)] Thanks for this suggestion, however I am interested in understanding the design decision here... I could aswell just use numarray and get the wanted a+b by: from numarray import * a=array([1,2,3]) b=array([1,2,3]) a+b array([2, 4, 6]) Soeren From rutski89 at gmail.com Tue Jul 5 11:46:16 2005 From: rutski89 at gmail.com (Patrick Rutkowski) Date: Tue, 5 Jul 2005 11:46:16 -0400 Subject: Good starterbook for learning Python? In-Reply-To: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: <200507051146.17146.rutski89@gmail.com> On Tuesday 05 July 2005 11:32, Lennart wrote: > Hi everybody, > > Can someone advice me with the following issue: i want to learn python in > my summer vacation (i try to ...:-) So, a good start is buying a good book. > But wich? There are many ... > > I'm living in the Netherlands and I prefer a book from bol.com (see link) > because i've to order more books by them. I'm familiar with html & php and > basic (in the good old days). It has to be a newbie book, but not a book > what i don't need anymore when i've got some skills. I.e. the learning > curve of the book should be linear. A kind of book wich i could use as a > novice. > > Search here for python (sorry, there's no short link) > http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_Brow >seCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&Cate >goryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb >&CategoryLeftpanel=BOOK_EN%2eCATEGORY00000000&Secondary=YES&Template=BOL_sub >cat_BOOK_EN_1476 I've taken up learning python over the summer as well. http://safari.oreilly.com/ is a website which sells IT books for on-line viewing. They charge $20 per month and you get 10 "slots" on your books shelf. You can get anybook you want, some books take 2 slots, some 1 slot, and some are even half of a slot. They have a 14 day free trial as well, its really worth giving it a whirl (free books!!). It's totally 100% over the internet (or in downloadable PDF format), its so great. From b83503104 at yahoo.com Wed Jul 20 20:32:12 2005 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 20 Jul 2005 17:32:12 -0700 Subject: How to use octave in python Message-ID: <1121905932.531027.154080@g49g2000cwa.googlegroups.com> Hi, I want to use octave to read a file and do some matrix operation. My question is, how do I do it inside my python script? Also, can I write octave line by line in python without having to write the octave code in another script and then call it in the python script? Thanks in advance From solafidefarms at gmail.com Fri Jul 15 18:02:03 2005 From: solafidefarms at gmail.com (SolaFide) Date: 15 Jul 2005 15:02:03 -0700 Subject: What module to use to get a file from a website? In-Reply-To: References: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> Message-ID: <1121464923.522948.46080@f14g2000cwb.googlegroups.com> Thanks! From edgrsprj at ix.netcom.com Tue Jul 12 18:20:05 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Tue, 12 Jul 2005 22:20:05 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> Message-ID: "Hank Oredson" wrote in message news:7%UAe.4148$BK1.174 at newsread3.news.pas.earthlink.net... > "edgrsprj" wrote in message > news:upBAe.1915$oZ.930 at newsread2.news.atl.earthlink.net... > > "edgrsprj" wrote in message > > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... > >> PROPOSED EARTHQUAKE FORECASTING > >> COMPUTER PROGRAM DEVELOPMENT EFFORT > What observational data are used? > What are the sources of that observational data? > How are those sources accessed? > Is there a database to hold historical plus current data? > If so, is it centralized or distributed? > > The project might be of interest if the data sources are > rich enough, complete enough, and current enough. > July 12, 2005 Thanks for the response and questions. The following are my personal opinions on this. Briefly, the amount of data available for this type of effort is virtually limitless. And more of those data than most people could even deal with can be obtained for free. You don't have to build a new laboratory filled with expensive equipment. A reasonably powerful computer, Access to the Internet, At least some knowledge of science Some computer programming ability And a little imagination Are all that are required. Researchers have been attempting to do this type of work for probably as far back as we have historical records. The reason that previous efforts that I am aware of have not been successful is because two key discoveries needed to be made. They are referred to on my 90-05.html Web page as the "Gravity Point" and "Earthquake Triggering Symmetry." Now that those discoveries have been made the door should be open to tremendously rapid advances in our understanding of how and why earthquakes occur and how to forecast them. Much of this research could be easily done by computer programmers. You don't need to be a geophysicist. If the data you are generating look statistically significant then they are probably important whether or not you actually understand the geophysical theories behind them. To actually forecast earthquakes using the procedure I have developed you need both warning signal data and earthquake data along with some ocean tide and Solid Earth Tide data. But one of the really great parts of this particular research project is the fact that many of the basic discoveries can be made by simply comparing earthquakes with one another. You don't need any warning signal data at all. And there is certainly no shortage of earthquake data! At my Web site there is a discussion of a concept called "Earthquake Pairs." They are two or more earthquakes which were apparently triggered in the same manner. My data indicate that the two highly destructive 1998 earthquakes in Afghanistan would represent an Earthquake Pair. And the two highly destructive 1999 earthquakes in Turkey would represent another pair. Important discoveries can be made by determining what the similarities are between the two or more earthquakes in an Earthquake Pair and how they differ from other earthquakes. And since the group of earthquake warning signals that I am presently working with is being controlled by the same forces that are responsible for earthquake triggering, significant discoveries regarding earthquake triggering processes could be immediately applied to forecasting efforts. One of the reasons that geologists have not yet taken an interest in this particular effort could be because it is heavily reliant on celestial mechanics. And most geology researchers appear to me to prefer to focus on measuring forces within the ground. I presently suspect that astronomers would be a more likely group to take an interest in this science at first. And I am planning to contact some of them about that. From majromax at gmail.com Fri Jul 22 09:21:02 2005 From: majromax at gmail.com (Christopher Subich) Date: 22 Jul 2005 06:21:02 -0700 Subject: find a specified dictionary in a list In-Reply-To: References: <42e0dc25$1@news.eftel.com> Message-ID: <1122038462.935084.20820@g49g2000cwa.googlegroups.com> Odd-R. wrote: > On 2005-07-22, John Machin wrote: > > Odd-R. wrote: > >> I have this list: > >> > >> [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] > >> > >> All the dictionaries of this list are of the same form, and all the oids > >> are distinct. If I have an oid and the list, how is the simplest way of > >> getting the dictionary that holds this oid? > >> > > > > Something like this: > > > > def oidfinder(an_oid, the_list): > > for d in the_list: > > if d['oid'] == an_oid: > > return d > > return None > > # These are not the oids you are looking for. > > Thank you for your help, but I was hoping for an even simpler > solution, as I am suppose to use it in a > References: <1121101669.752932.217380@g14g2000cwa.googlegroups.com> <42D2F687.3040003@v.loewis.de> <1121176236.090606.287860@g49g2000cwa.googlegroups.com> Message-ID: <42D4B5FA.3090608@v.loewis.de> Hugh Macdonald wrote: > PyMethodDef *callbackFunctionDef = new PyMethodDef; > callbackFunctionDef->ml_name = "doLoadCallback"; > callbackFunctionDef->ml_meth = &myPython_doLoadCallback; > callbackFunctionDef->ml_flags = 1; I think this gives a memory leak. I was rather thinking of static PyMethodDef doLoadCallback = { "doLoadCallback", &myPython_doLoadCallback, 1 }; PyObject *pyCallbackFunc = PyCFunction_New(&doLoadCallback, NULL); Since you have to write the C(++) functions statically, you can also provide the PyMethodDef objects statically. Regards, Martin From tjreedy at udel.edu Thu Jul 28 10:22:22 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 28 Jul 2005 10:22:22 -0400 Subject: easy float question just eludes me References: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> Message-ID: wrote in message news:1122557972.833617.157360 at o13g2000cwo.googlegroups.com... > Hullo all ! > > i have a real easy one here that isn't in my book. > i have a int number that i want to divide by 100 and display to two > decimal places. > > like this float(int(Var)/100) At present, int/int truncates, so this won't do what you want. Use int/100.0 to get float you want. For output, use % formating operator with f specification. >>> '%7.2f' % (50/100.0) ' 0.50' Terry J. Reedy From jeremy+complangpython at jeremysanders.net Tue Jul 12 06:41:22 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 12 Jul 2005 11:41:22 +0100 Subject: Sort files by date References: <42d39273$0$12593$636a15ce@news.free.fr> Message-ID: fargo wrote: > I'm looking for some way to sort files by date. you could do something like: l = [(os.stat(i).st_mtime, i) for i in glob.glob('*')] l.sort() files = [i[1] for i in l] Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From reinhold-birkenfeld-nospam at wolke7.net Thu Jul 7 02:27:35 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 07 Jul 2005 08:27:35 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <3j40aoFocvh4U1@individual.net> Ron Adam wrote: > Given the statement: > > a = None > > And the following are all true: > > a == None Okay. > (a) == (None) Okay. > (a) == () Whoops! a (which is None) is equal to the empty tuple (which is not None)? > (None) == () > > Then this "conceptual" comparison should also be true: > > if (None): == if (): > if (): == if: I can't really see any coherent concept here. Reinhold From bdesth.quelquechose at free.quelquepart.fr Sat Jul 23 05:49:42 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 23 Jul 2005 11:49:42 +0200 Subject: Separation of Code in CGI App In-Reply-To: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> References: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> Message-ID: <42e20bc1$0$7047$636a15ce@news.free.fr> Rob Cowie a ?crit : > Hi, > > I need to create a planner/calendar system using python cgi scripts. It > is my first CGI app (beyond a few tutorial examples). > (snip) You may want to have a look at the cgi_app mini-framework: -> http://thraxil.org/code/cgi_app/ It's a port of a Perl framework, and it has some unpythonic flavour in some points (but that can be easily corrected), and it can work with CGI and mod_python. It's quite easy to get started with, and the source being really small (about 1kloc IIRC), it's quite easy to customize to your own needs (I rolled my own mod_python-only/SimpleTAL-only version in half a day...). You also have the choice between 2 template systems, one that's dirty as can be IMHO (htmltmpl) and one that is quite nice (SimpleTAL). The only wart with SimpleTAL is that it requires every input to be unicode, but that's easy to solve also (I wrote a wrapper class that handle this quite transparently - it's still Q&D but works well so far, I can publish it if anyone is interested). My 2 cents From roy at panix.com Mon Jul 4 20:25:11 2005 From: roy at panix.com (Roy Smith) Date: Mon, 04 Jul 2005 20:25:11 -0400 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> <42c98b40$0$29947$626a14ce@news.free.fr> Message-ID: Steven D'Aprano wrote: > Should we *really* be encouraging newbies to mess with globals() and > locals()? Isn't that giving them the tools to shoot their foot off before > teaching them how to put shoes on? Why risk damaging perfectly good footwear? But, seriously, I agree with you. The cannonical way to tell if a variable exists in Python is to try to access it and catch any resulting NameError. From simon.brunning at gmail.com Tue Jul 5 04:49:45 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 5 Jul 2005 09:49:45 +0100 Subject: what is __init__.py used for? In-Reply-To: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> References: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> Message-ID: <8c7f10c6050705014942e7d86f@mail.gmail.com> On 5 Jul 2005 01:31:09 -0700, zelzel.zsu at gmail.com wrote: > I am a new learner of Python Programming Language. Welcome! > I was wonderring ... what is the __init__.py used for ? > This question may seems to be stupid for an expert. > But, if you can give the answer, it will be helpful for me. The __init__.py files make Python treat the directories as packages - see http://docs.python.org/tut/node8.html#SECTION008400000000000000000. We have to do something about those URLs! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 13:06:37 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 19:06:37 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3l192cF109df7U1@individual.net> Message-ID: <3l1qcuF1060r2U1@individual.net> Steven D'Aprano wrote: > On Sat, 30 Jul 2005 14:10:52 +0200, Reinhold Birkenfeld wrote: > >> Above all, nobody can tell me that there's any programmer who doesn't >> instantly recognize '/' as a directory separator. > > Is classic Macintosh OS still supported on Python? Because Mac programmers > who haven't made the jump to OS X will probably instantly recognise ':' as > the directory separator, not '/'. > > Acorn RISC OS developers may also instantly recognise '.' as the directory > separator. I didn't say that '/' is the native directory separator on every platform. But other than ':' or '.', '/' is used as widely as URLs are, so it _will_ be recognizable as a directory separator. > And presumably mathematicians and numeric programmers who do very little > file input/output will probably instantly recognise '/' as the division > operator. Yes, they will. But they presumably will read the documentation of the path module when using it (and, given that most operands will be strings, they won't suspect division going on). > And I have no idea what directory separators are in use under file systems > that don't use ASCII or any extension to ASCII, eg the OS which has been > described as the most common operating system in the world, the Japanese > "Real-time Operating System Nucleus", TRON. (Chances are you have at least > half a dozen devices in your home with embedded TRON.) Well, as long as Python doesn't run under TRON, that's not much of a point here. > Still, your (modified) point that most Western programmers will quickly > recognise '/' as a directory separator is surely true. > > Even given that, I'm not convinced that it is a good idea to turn '/' into > a join-path operator. I don't have any good reasons for objecting > either, just a funny little feeling in the back of my head that says > that no good can ever come from allowing Path("C:\Windows")/"cmd.com". Well, if you want to do such things, you surely don't need a path join anyway. Just write "C:\\Windows\\" + something in this case. The path join is there for platform independence, and you will most certainly not write a Windows path directly into the source if you want to be XP compatible. Reinhold From __peter__ at web.de Mon Jul 25 02:30:29 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Jul 2005 08:30:29 +0200 Subject: Problem loading a file of words References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> Message-ID: teoryn wrote: > I've been spending today learning python and as an exercise I've ported > a program I wrote in java that unscrambles a word. Before describing > the problem, here's the code: > line = str.lower(line[:-1]) # convert to lowercase just in case > have to add exceptions later). The problem is when using a large > dictionary.txt file (2.9 MB is the size of the dictionary I tested) it > always gives an error, specifically: > (Note: ccehimnostyz is for zymotechnics, which is in the large > dictionary) > > > *--beginning of example--* > Enter a scrambled word : ccehimnostyz > Traceback (most recent call last): > File "unscram.py", line 62, in ? > results = dictionary[sort_string(lookup)] > KeyError: 'ccehimnostyz' > *--end of example--* If 'zymotechnics' is the last line and that line is missing a trailing newline line[:-1] mutilates 'zymotechnics' to 'zymotechnic'. In that case the dictionary would contain the key 'ccehimnotyz'. Another potential problem could be leading/trailing whitespace. Both problems can be fixed by using line.strip() instead of line[:-1] as in Robert Kern's code. Peter From jepler at unpythonic.net Fri Jul 1 10:06:47 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 1 Jul 2005 09:06:47 -0500 Subject: It seems that ZipFile().write() can only write files, how can empty directories be put into it? In-Reply-To: <311b5ce10506301850643872d6@mail.gmail.com> References: <311b5ce10506301850643872d6@mail.gmail.com> Message-ID: <20050701140644.GD7252@unpythonic.net> This has been discussed before. One thread I found was http://mail.python.org/pipermail/python-list/2003-June/170526.html The advice in that message might work for you. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From adurdin at gmail.com Wed Jul 6 05:55:00 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 6 Jul 2005 19:55:00 +1000 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120635034.080123.218060@g47g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> Message-ID: <59e9fd3a0507060255601b50a4@mail.gmail.com> On 6 Jul 2005 00:30:34 -0700, Raymond Hettinger wrote: > > With Lisp or Forth, a master programmer has unlimited power and > expressiveness. With Python, even a regular guy can reach for the > stars. +1 QOTW From rkern at ucsd.edu Wed Jul 20 21:06:43 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 18:06:43 -0700 Subject: How to use octave in python In-Reply-To: <1121905932.531027.154080@g49g2000cwa.googlegroups.com> References: <1121905932.531027.154080@g49g2000cwa.googlegroups.com> Message-ID: b83503104 at yahoo.com wrote: > Hi, > > I want to use octave to read a file and do some matrix operation. My > question is, how do I do it inside my python script? Also, can I write > octave line by line in python without having to write the octave code > in another script and then call it in the python script? You could try communicating with an octave instance using the subprocess module in the standard library. Depending on what that matrix operation is, though, you might want to consider doing it all in Python using Numeric and possibly Scipy. http://numeric.scipy.org http://www.scipy.org -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steven.bethard at gmail.com Mon Jul 18 18:17:37 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 18 Jul 2005 16:17:37 -0600 Subject: goto In-Reply-To: <1121719077.19216.10.camel@athop1.ath.vt.edu> References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: <_OKdnRi4hYUdt0HfRVn-jg@comcast.com> rbt wrote: > Steven Bethard wrote: > >>Download the goto module: >> http://www.entrian.com/goto/ >>And you can use goto to your heart's content. And to the horror of all >>your friends/coworkers. ;) > > Shouldn't that be "to the horror of all your goto-snob friends." > > IMO, most of the people who deride goto do so because they heard or read > where someone else did. > > Many of the world's most profitable software companies (MS for example) > have thousands of goto statements in their code... oh the horror of it > all. Why aren't these enlightened-by-the-gods know-it-alls as profitable > as these obviously ignorant companies? Perhaps I should reiterate: ;) Oh, and ;) The CPython source code is filled with gotos -- with a rough grep count, I found over 2000. And, while I wouldn't care to inspect them all, I'd guess that they're mostly quite appropriate. A lot of them look like "goto fail", "goto finally", etc. and are used to handle error conditions. Heck, the patch I wrote to add key= arguments to min() and max() in Python 2.5 uses goto for exactly this purpose. That said, I don't think my joke was really that inaccurate -- I have yet to see a good use case for gotos in Python. Why use gotos when you have an efficient exception handling mechanism? STeVe From tprimke at interia.pl Sun Jul 24 08:57:30 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jul 2005 05:57:30 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <1122209850.126276.266650@g43g2000cwa.googlegroups.com> > I've used pygtk with success on windows. (...) > > [will] I be able to make an executable (using Py2Exe) of an application > > that uses PyGTK? > > Yes. So PyGTK is now my favourite. Better documentation, runs on Linux and Windows, the possibility to make an executable program with Py2Exe. It's enough for me. > One point against: requires X11 on a Mac; definitely not native there, > though that's where I do a lot of my pygtk development. I suppose that 95% of my application's users will work on Win. The rest will work on *nix. So my primary concern is PC world. AFAIK PyGTK doesn't look native on Win as well, but I don't care. From gene.tani at gmail.com Fri Jul 29 22:20:33 2005 From: gene.tani at gmail.com (gene tani) Date: 29 Jul 2005 19:20:33 -0700 Subject: writing a web client In-Reply-To: <1122659443.714192.253690@o13g2000cwo.googlegroups.com> References: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> <1122642828.810852.146650@g14g2000cwa.googlegroups.com> <1122659443.714192.253690@o13g2000cwo.googlegroups.com> Message-ID: <1122690033.394859.234030@g49g2000cwa.googlegroups.com> Here: http://diveintopython.org/http_web_services/index.html#oa.divein Here: Cookbook rel 2, and: http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Web Here:other really good py intros which cover 2.2 / urllib (maybe 2.3, I don't have them with me), but examples should all not give deprecation warnings: Practical Py (Hetland), Text Processing (Mertz). From gsakkis at rutgers.edu Wed Jul 20 11:10:33 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 20 Jul 2005 11:10:33 -0400 Subject: getting the class name of a subclass References: <5UsDe.149277$Yz5.7850081@phobos.telenet-ops.be> Message-ID: <1121872256.a32dca1a4e415c43dc250b9e956574bb@teranews> "flupke" wrote: > I have the following test code setup, trying to get the class name of a > subclass in the super class. (Reason why i want this is described below) > > file class_name_start.py > ======================== > import class_name as cn > > obj = cn.B() > obj.printclass() > ======================== > > > file class_name.py > ======================== > class A(object): > def __init__(self): > print "I'm A" > > def printclass(self): > print "Name ",__name__ > print "Class ",A.__name__ > > class B(A): > def __init__(self): > super(B,self).__init__() > print "I'm B" > ======================== > > Output: > I'm A > I'm B > Name class_name > Class A > > I would want the last line to be Class B > The reason i want this is since i have a number of dialogs all deriving > from the same super class. In the superclass i have a save function and > i thought it would be easy to get the classname and write the properties > in a filename with the classes name as the filename. > However it turns out i get the class name of the superclass for all. > All the different dialogs are in seperate files. > > Is there a way to get the name of the subclass. If not i could always > pass a param to the init function but in my real life code i already > have several params shipped to the init so i wanted to solve it slightly > more elegant. > > Regards, > Benedict Make printclass a class method: class A(object): def __init__(self): print "I'm A" # for python 2.4 @classmethod def printclass(cls): print "Module", cls.__module__ print "Class", cls.__name__ # for 2.3 or older printclass = classmethod(printclass) Regards, George From joe.woodward at padtinc.com Wed Jul 13 18:49:33 2005 From: joe.woodward at padtinc.com (Joe) Date: 13 Jul 2005 15:49:33 -0700 Subject: PY2EXE => Is there a way to go backwards? EXE2PY In-Reply-To: References: <1121277611.573163.318250@g49g2000cwa.googlegroups.com> Message-ID: <1121294973.617903.268050@f14g2000cwb.googlegroups.com> Thank you, Peter. Your point is well taken. We a control system, but I just never got around to using it. I think now I'll get a round to it. :) Thanks again, Joe From grig.gheorghiu at gmail.com Mon Jul 4 15:33:25 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 4 Jul 2005 12:33:25 -0700 Subject: Connecting to Firebird database using Kinterbasdb+Python References: Message-ID: <1120505605.805450.76840@z14g2000cwz.googlegroups.com> How is your Firebird database configured -- Classic Server or Super Server? If it's in classic server mode, you don't need to worry about the host portion. You do need to worry about permissions on the database file. I got it to work by making it 664 and owner + group firebird. Grig From Sebastien.Boisgerault at gmail.com Sat Jul 2 13:47:06 2005 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 2 Jul 2005 10:47:06 -0700 Subject: What's wrong with this code? In-Reply-To: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> References: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> Message-ID: <1120326425.950215.309250@z14g2000cwz.googlegroups.com> Nathan Pinno a ?crit : > Hi all, > > What's wrong with the following code? It says there is name error, that > random is not defined. How do I fix it? Add "import random" at the top of your file Cheers, SB > # Plays the guessing game higher or lower. > # Originally written by Josh Cogliati, improved first by Quique, then by > Nathan Pinno. > print "Higher or Lower" > print > number = random.choice(range(100)) > guess = 0 > while guess != number: > guess = input("Guess a number: ") > if guess > number: > print "Too high" > guess = input("Guess a number: ") > elif guess < number: > print "Too low" > guess = input("Guess a number: ") > print "Just right" > > Thanks. > Nathan Pinno > http://www.npinnowebsite.ca/ > > > > -- > > > ---------------------------------------------------------------- > Posted via UsenetRevolution.com - Revolutionary Usenet > ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** > http://www.UsenetRevolution.com From python at rcn.com Wed Jul 6 03:30:34 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jul 2005 00:30:34 -0700 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <1120635034.080123.218060@g47g2000cwa.googlegroups.com> seberino at spawar.navy.mil wrote: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. > > It got me curious if Lisp > is inherently faster to develop complex apps in. With Lisp or Forth, a master programmer has unlimited power and expressiveness. With Python, even a regular guy can reach for the stars. Raymond From hancock at anansispaceworks.com Wed Jul 6 02:58:14 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 6 Jul 2005 01:58:14 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <200507060158.14822.hancock@anansispaceworks.com> On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote: > I understand that the backslash is popular in some ivory-tower functional > languages. Currently, a backslash can be used for explicit line joining, > and is illegal elsewhere on a line outside a string literal, so i think > it's available for this. It would be utterly unpythonic to use puntuation > instead of a keyword, and it would make no sense to novices, but it would > scare the crap out of C programmers, which has to be worth something. With list comprehensions and generators becoming so integral, I'm not sure about "unpythonic". And a syntax just occured to me -- what about this: [y*x for x,y] ? (that is: [ for ] It's just like the beginning of a list comprehension or generator, but without the iterator. That implies that one must be given, and the result is therefore a callable object. Wouldn't do anything more or less than present day "lambda", but gets rid of the weird keyword, and integrates nicely with list comps and generators. It's currently a syntax error, and it requires no special delimiter -- it's really just an extension of list comp syntax. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tiissa at nonfree.fr Sat Jul 30 11:26:54 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 30 Jul 2005 17:26:54 +0200 Subject: string methods In-Reply-To: <3l1js6F10d0leU1@individual.net> References: <3l1js6F10d0leU1@individual.net> Message-ID: <42eb9c3c$0$28242$626a14ce@news.free.fr> anthonyberet wrote: > I know this touches on immutability etc, but I can't find string methods > to return the first 3 characters, and then the last 2 characters, which > I could concatenate with newchar to make a new string. > > I know the string methods are there, but can't find it in any docs, and > just want to check the syntax, unless there is an easier way. Strings [1] are sequences [2], and therefore support slicing, which is what you are looking for. [1] http://docs.python.org/lib/string-methods.html [2] http://docs.python.org/lib/typesseq.html From caleb1 at telkomsa.net Tue Jul 26 16:08:25 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 26 Jul 2005 22:08:25 +0200 Subject: Emacs skeletons References: Message-ID: > Since you are on this topic, do you (or anyone else) have any type of > "code-completion" mode for python in emacs? > > Thanks > -george For what its worth, Vim has a generic type of "code-completion" that uses the file being edited to check for completion options within a word. It's not true completion (using valid completions for class hierarchies, a la Delphi/VB), but I get a lot of mileage out of it with my python coding. I fully expect Emacs has something similar, though I can't tell you how (I hardly know emacs at all). rgds Caleb From peter at engcorp.com Sun Jul 3 13:41:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 13:41:52 -0400 Subject: How execute a .py in this way? In-Reply-To: References: Message-ID: <_N2dnQA0rKatvlXfRVn-tA@powergate.ca> Peter Cai wrote: > Thus, you > can execute you "py" program anywhere by using the command "xxx.py", > but when you want to use an exsiting file as it's input, you have to > use something like "pythong xxx.py < input.txt". This is apparently a bug or limitation of Windows command prompts and may not be fixed any time soon. Past threads have discussed it and a recent one even gave pointers to some web pages that explain it further. -Peter From pinard at iro.umontreal.ca Fri Jul 1 12:59:20 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 1 Jul 2005 12:59:20 -0400 Subject: Assigning to None (was Re: Question about Python) In-Reply-To: References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> Message-ID: <20050701165920.GA11908@phenix.progiciels-bpi.ca> [Peter Hansen] > Mike Meyer wrote: > > Yes. I once grabbed an old program that did assignments to None. But > > that's always been a bad idea. > What was the use case!? People used to assign None to itself as a keyword argument in function headers. The goal was to make a local copy of the reference, which was then accessed faster than the global thing. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From reinhold-birkenfeld-nospam at wolke7.net Tue Jul 12 03:45:14 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 12 Jul 2005 09:45:14 +0200 Subject: set and frozenset unit tests? In-Reply-To: References: Message-ID: <3jhaoaFq2kajU1@individual.net> Jacob Page wrote: > I have released interval-0.2.1 at > http://members.cox.net/apoco/interval/. IntervalSet and > FrozenIntervalSet objects are now (as far as I can tell) functionality > equivalent to set and frozenset objects, except they can contain > intervals as well as discrete values. > > Though I have my own unit tests for verifying this claim, I'd like to > run my code through actual set and frozenset unit tests. Does any such > code exist? Is it in pure Python? If so, where can it be obtained? > > Oh, and again, I'd really appreciate additional feedback on the module, > especially related to design, if you've got any. My goal for this > project is to make the classes built-in-data-type quality. Look at /usr/lib/python2.x/test/ (on unix platforms). Reinhold From steve at REMOVETHIScyber.com.au Tue Jul 12 10:53:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 00:53:21 +1000 Subject: append one file to another References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Message-ID: Dear me, replying to myself twice in one day... On Wed, 13 Jul 2005 00:39:14 +1000, Steven D'Aprano wrote: > Then, if you are concerned that the files really are huge, that is, as big > or bigger than the free memory your computer has, read and write them in > chunks: > > data = infile.read(64) # 64 bytes at a time is a bit small... > outfile.write(data) Sorry, that should be in a loop: data = "anything" while data: data = infile.read(64) # data will be empty when the file is read outfile.write(data) -- Steven. From bokr at oz.net Sat Jul 2 23:09:28 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Jul 2005 03:09:28 GMT Subject: Inheriting from object References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> <42c69a4f.336127175@news.oz.net> Message-ID: <42c6ea79.356649284@news.oz.net> On Sat, 02 Jul 2005 14:17:32 -0400, Peter Hansen wrote: >Bengt Richter wrote: >> BTW, there's something about referring to type(self) by its not >> always dependably bound (though usually global) name that bothers me. >> >> I wonder if the above common use of super could be implemented as a property of object, >> so you'd normally inherit it and be able to write >> self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose) >> >> I.e., self.__super__ would effectively return the equivalent of >> super(type(self), self) > >This doesn't work: type(self) is always the type of the instantiated >(child) class, not the type of the class at whatever level of the class >hierarchy the __init__() calls currently have reached. > D'oh, you're right, that was too easy a property definition ;-/ I still don't like having to use a global name to get access to the current lexical scope object though. But I can't think of a decent hack right now to get around all that, and I can't spend too much time ;-/ >In other words, with these definitions: > >class A(object): > def __init__(self): > super(type(self), self).__init__() # does not do what you want > >class B(A): > def __init__(self): > super(type(self), self).__init__() # works okay here > >if you do "b = B()", the first __init__ will work (i.e. B's __init__ >will find and call A.__init__), but the next one won't (i.e. A.__init__ >will now try calling A.__init__ recursively, giving you an eventual >stack overflow). > >-correcting-bengt-richter-on-such-arcana-is-always-dangerously y'rs, > Peter No danger at all, I'm grateful ;-) Regards, Bengt Richter From mwh at python.net Tue Jul 12 08:14:18 2005 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Jul 2005 12:14:18 GMT Subject: math.nroot [was Re: A brief question.] References: Message-ID: I doubt anyone else is reading this by now, so I've trimmed quotes fairly ruthlessly :) Tim Peters writes: > > Actually, I think I'm confused about when Underflow is signalled -- is it > > when a denormalized result is about to be returned or when a genuine > > zero is about to be returned? > > Underflow in 754 is involved -- indeed, the definition is different > depending on whether the underflow trap is or is not enabled(!). ! > > Sure, but we already have a conforming implementation of 854 with > > settable traps and flags and rounding modes and all that jazz. > > No, we don't, but I assume you're talking about the decimal module. Uh, yes. Apologies for the lack of precision. > If so, the decimal module enables traps on overflow, invalid > operation, and divide-by-0 by default. A conforming implementation > would have to disable them by default. > > Apart from that difference in defaults, the decimal module does intend > to conform fully to the proposed decimal FP standard. Right, that's what I meant. > > Maybe we should just implement floats in Python. > > Certainly the easiest way to get 754 semantics across boxes! Been > there, done that, BTW -- it's mondo slow. No doubt. > >>> (In the mean time can we just kill fpectl, please?) > > >> Has it been marked as deprecated yet (entered into the PEP for > >> deprecated modules, raises deprecation warnings, etc)? I don't know. > >> IMO it should become deprecated, but I don't have time to push that. > > > A bit of googling suggests that more people pass --with-fpectl to > > configure than I expected, but I doubt more than 1% of those actually > > use the features thus provided (of course, this is a guess). > > I expect 1% is way high. Before we stopped building fpectl by > default, Guido asked and heard back that there were no known users > even at LLNL anymore (the organization that contributed the code). Interesting. > >>>> You're seeing native HW fp behavior then. > > >>> But anyway, shouldn't we try to raise exceptions in these cases? > > Note that the only cases you could have been talking about here were > the plain * and / examples above. Ah, OK, this distinction passed me by. > >> Why doesn't Python already supply a fully 754-conforming arithmetic > >> on 754 boxes? It's got almost everything to do with implementation > >> headaches, and very little to do with what users care about. > >> Because all the C facilities are a x-platform mess, the difference > >> between calling and not calling libm can be the difference between > >> using the platform libm or Python needing to write its own libm. > >> For example, there's no guarantee that math.sqrt(-1) will raise > >> ValueError in Python, because Python currently relies on the > >> platform libm sqrt to detect _and report_ errors. The C standards > >> don't require much of anything there. > > > Can't we use the stuff defined in Appendix F and header of > > C99 to help here? I know this stuff is somewhat optional, but it's > > available AFAICT on the platforms I actually use (doesn't mean it > > works, of course). > > It's entirely optional part of C99. Hmm, is optional? I'm not finding those words. I know Appendix F is. > Python doesn't require C99. Sure. But it would be possible to, say, detect C99 floating point facilities at ./configure time and use them if available. > The most important example of a compiler that doesn't support any of > that stuff is Microsoft's, although they have their own MS-specific > ways to spell most of it. OK, *that's* a serious issue. If you had to guess, do you think it likely that MS would ship fenv.h in the next interation of VC++? > > I'm thinking something like this: > > > > fexcept_t flags; > > > > feclearexcept(FE_ALL_EXCEPT); > > > > /* stuff, e.g. r = exp(PyFloat_AS_DOUBLE(x)) */ > > > > fegetexceptflag(&flags, FE_ALL_EXCEPT) > > > > /* inspect flags to see if any of the flags we're currently trapping > > are set */ > > Assuming the platform libm sets 754 flags appropriately, that's a fine > way to proceed on platforms that also support that specific spelling. It even seems to work, on darwin/ppc (so, with GCC) at least. > ... > > >>> Well, you can at least be pretty sure that an infinite result is the > >>> result of an overflow condition, I guess. > > > > There are at least two other causes: some cases of divide-by-0 (like > > > 1/0 returns +Inf), and non-exceptional production of an infinite > > > result from infinite operands (like sqrt(+Inf) should return +Inf, and > > > there's nothing exceptional about that). > > > Yeah, but I think those can be dealt with (if we really wanted to). > > They certainly could be. The more I think about it, the less wise I think detecting stuff this was is sane. > >> BTW, since there's so little the HW can help us with here in reality > >> (since there's no portable way to get at it), > > > In what way does C99's fenv.h fail? Is it just insufficiently > > available, or is there some conceptual lack? > > Just that it's not universally supported. Look at fpectlmodule.c for > a sample of the wildly different ways it _is_ spelled across some > platforms. C'mon, fpectlmodule.c is _old_. Maybe I'm stupidly optimistic, but perhaps in the last near-decade things have got a little better here. > A maze of #ifdefs could work too, provided we defined a > PyWhatever_XYZ API to hide platform spelling details. Hopefully it wouldn't be that bad a maze; frankly GCC & MSVC++ covers more than all the cases I care about. > > Another question: where can I find these experts? > > I'm one. I'd expect to find others on the numerical Python lists, not > on c.l.py. The folks at Enthought would be good to talk with. OK. > > How come they haven't tried to reduce the mess before? > > It's tedious, exacting, time-consuming, and an endless source of > x-platform problems. I'd much rather work on the Python Challenge > riddles now <0.5 wink>, speaking of which ... Heh. Cheers, mwh -- For every complex problem, there is a solution that is simple, neat, and wrong. -- H. L. Mencken From ptmcg at austin.rr.com Tue Jul 5 13:06:28 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 5 Jul 2005 10:06:28 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <1120473422.864033.36350@o13g2000cwo.googlegroups.com> Message-ID: <1120583188.805750.310670@g43g2000cwa.googlegroups.com> Your elaboration on what problem you are actually trying to solve gave me some additional insights into your question. It looks like you are writing a Python-HTML templating system, by embedding Python within HTML using ... tags. As many may have already guessed, I worked up a pyparsing treatment of your problem. As part of the implementation, I reinterpreted your transformations slightly. You said: >>>I want to replace the with " ", >>>with "\n" and every thing that's not between the two >>>python tags must begin with "\nprint \"\"\"" and >>>end with "\"\"\"\n" If this were an HTML page with tags, it might look like: x = 1 The corresponding CGI python code would then read: print """\n""" x = 1 print """\n""" So we can reinterpret your transformation as: 1. From start of file to first tag, enclose in print """\n""" 2. From tag to tag to next tag, enclose in print """\n""" 4. From last tag to end of file, enclose in print """\n""" Or more formally: -> 'print r"""' -> '"""\n' <\python> -> 'print r"""' -> '"""\n' Now that we have this defined, we can consider adding some standard imports to the transformation, such as "import sys", etc. Here is a working implementation. The grammar itself is only about 10 lines of code, mostly in defining the replacement transforms. The last 18 lines are the test case itself, printing the transformed string, and then eval'ing the transformed string. ======================== # Take HTML that has tags interspersed, with python code # between the tags. Convert to running python cgi program. # replace with r'"""\n' and with r'\nprint """' # also put 'print """\ \n' at the beginning and '"""\n' at the end from pyparsing import * class OnlyOnce(object): def __init__(self, methodCall): self.callable = methodCall self.called = False def __call__(self,s,l,t): if not self.called: self.called = True return self.callable(s,l,t) raise ParseException(s,l,"") stringStartText = """import sys print "Content-Type: text/html\\n" print r\"\"\"""" stringEndText = '"""\n' startPythonText = '"""\n' endPythonText = '\nprint r"""\n' # define grammar pythonStart = CaselessLiteral("") pythonEnd = CaselessLiteral("") sStart = StringStart() sEnd = StringEnd() sStart.setParseAction( OnlyOnce( replaceWith(stringStartText) ) ) sEnd.setParseAction( replaceWith(stringEndText) ) pythonStart.setParseAction( replaceWith(startPythonText) ) pythonEnd.setParseAction( replaceWith(endPythonText) ) xform = sStart | sEnd | pythonStart | pythonEnd # run test case htmlWithPython = r""" Sample Page Created from Python

Sample Page Created from Python

for i in range(10): print "This is line %d
" % i
""" generatedPythonCode = xform.transformString( htmlWithPython ) print generatedPythonCode print exec(generatedPythonCode) ======================== Here is the output: import sys print "Content-Type: text/html\n" print r""" Sample Page Created from Python

Sample Page Created from Python

""" for i in range(10): print "This is line %d
" % i print r""" """ Content-Type: text/html Sample Page Created from Python

Sample Page Created from Python

This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
======================== This exercise was interesting to me in that it uncovered some unexpected behavior in pyparsing when matching on positional tokens (in this case StringStart and StringEnd). I learned that: 1. Since StringStart does not advance the parsing position in the string, it is necessary to ensure that the parse action get run only once, and then raise a ParseException on subsequent calls. The little class OnlyOnce takes care of this (I will probably fold OnlyOnce into the next point release of pyparsing). 2. StringEnd is not well matched during scanString or transformString if there is no trailing whitespace at the end of the input. Even a trailing \n is sufficient. My first example of testdata ended with the closing tag, with no carriage return, and scanString/transformString failed to match. If I added a newline to close the tag, then scanString could find the StringEnd. This is not a terrible workaround, but it's another loose end to tie up in the next release. Enjoy! -- Paul From kbiswal at gmail.com Thu Jul 14 14:02:34 2005 From: kbiswal at gmail.com (Krutibas Biswal) Date: 14 Jul 2005 11:02:34 -0700 Subject: unbuffer script using pexpect Message-ID: <1121364154.924841.277380@z14g2000cwz.googlegroups.com> Hi, I am using a script 'unbuffer' for unbuffering my outputs when using pipes. This script is based on expect and looks like this : ---------------------------------------------- #!/usr/bin/expect -- # Description: unbuffer stdout of a program # Author: Don Libes, NIST eval spawn -noecho $argv set timeout -1 expect ---------------------------------------------- Now if you do % unbuffer it works fine. I am trying to write a similar similar script in python (pexpect) and it looks like this : ------------------------------------------------------------ #!/usr/bin/env python # Description: unbuffer stdout of a program and return program's error code import pexpect import sys child = pexpect.spawn(' '.join(sys.argv[1:])) child.expect('(.+\n)+') sys.stdout.flush() child.interact() # Escape character defaults to ^] sys.exit(child.exitstatus) ------------------------------------------------------------ This script works fine except that after the output is displayed on the screen, it expects me to press to comeback to the prompt. What is wrong here ? (I am a newbie) Thanks, Krutibas From qwweeeit at yahoo.it Sat Jul 2 06:50:47 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 2 Jul 2005 03:50:47 -0700 Subject: Python, mysql, floating point values question References: Message-ID: <1120301447.012340.16500@g14g2000cwa.googlegroups.com> Hi Christopher, if you have to make calculations or comparing operations, the only "safe" method is to save and use only integer values. Of course there must be a preventive agreement on the precision you want to have (2, 3 4 ... decimals). The sw part is straigthforward: - to save in the database you must multiply every float by 10**(precision) - to use the "integers" and, for example, display them as float, you must of course make the opposit operation (dividing). There are drawbacks: - the queries (from the point of view of the user) are much more complicate - the integer takes generally more place than the corresponding float - the integer divide needs particular attention. If the disk space occupied by the database is a concern, you can evaluate the possibility to save the floats as string representation as, for example, "1.5632" (coming out from "%.4f" % 1.5631999999999999). Sorry if the above considerations are not at the same level of those of the experts, but I definitely am not an "expert". I encountered the same problems many years ago (when the size of disks was at maximum 200 Mb). Bye. From nothingcanfulfill at gmail.com Wed Jul 13 20:36:02 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 13 Jul 2005 17:36:02 -0700 Subject: Odd behaviour of regexp module In-Reply-To: <1121288737.882813.244540@f14g2000cwb.googlegroups.com> References: <1121288737.882813.244540@f14g2000cwb.googlegroups.com> Message-ID: <1121301362.363992.83330@g44g2000cwa.googlegroups.com> To possibly clearify what the others have said, group() is the same as saying group(0). Group is, if I recall correctly, supposed to return the n-th subpattern from the regular expression (subpatterns, as you know, being indicated by parenthises). Hope that helps :) -Wes From andre.roberge at gmail.com Sun Jul 31 19:51:44 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Sun, 31 Jul 2005 20:51:44 -0300 Subject: Wheel-reinvention with Python In-Reply-To: <42ED5652.9080909@ulmcnett.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> <42ED5652.9080909@ulmcnett.com> Message-ID: Paul McNett wrote: [snip] >>Terry Hancock writes: > >>>I know I'm diving into this conversation late, and I haven't read >>>the whole thread, but has someone yet mentioned the "anygui" >>>project? This has stalled, but it was IMHO a good idea. Well, it appears to be more than stalled! From http://anygui.sourceforge.net/: Note: Anygui is no longer being actively developed or supported. These pages are not up to date. [snip] > > Now, that was only one part of the original Dabo vision, and the other > parts of the vision may actually add too much baggage and bloat for > people just interested in the UI aspect. Dabo also provides an > Application object, a database layer, and a business object layer. Ed > and I have discussed the possibility of ripping out the UI layer and > putting it into a completely separate project for the purpose of getting > more wxPython users interested. It wouldn't be all that hard to do, > because we've kept all the UI code separate from the the other stuff by > design. > Please do! On a somewhat unrelated note: is there any "overlap"/"possibility of collaboration" between Dabo-UI and Wax? (I have use neither, sticking to pure wxPython so far.) Andr? From cpl.19.ghum at spamgourmet.com Mon Jul 18 04:02:06 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 18 Jul 2005 08:02:06 +0000 (UTC) Subject: Java RMI-like services in Python References: Message-ID: Maurice LING wrote in news:dbfmbq$e49$1 @domitilla.aioe.org: > I am wondering if Python has services or frameworks that does the same > as Java RMI? google for pyro Harald From hancock at anansispaceworks.com Sun Jul 3 01:31:49 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 3 Jul 2005 00:31:49 -0500 Subject: Python, mysql, floating point values question In-Reply-To: References: <43b72594050701154055297e73@mail.gmail.com> Message-ID: <200507030031.49813.hancock@anansispaceworks.com> On Saturday 02 July 2005 10:50 pm, Peter Hansen wrote: > Terry Hancock wrote: > > On Saturday 02 July 2005 08:53 pm, Dennis Lee Bieber wrote: > > And for that matter, some of the posters here have *been* 14. > > Terry, almost every single one of the posters here have been 14. > At some time. :-) Uh, yeah. I meant when they posted. ;-D I like the "almost". I guess that's for the 12 year-olds. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From sjmachin at lexicon.net Sat Jul 2 20:11:20 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 03 Jul 2005 10:11:20 +1000 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: <42c72d27@news.eftel.com> Roy Smith wrote: > Peter Hansen wrote: > >>I guess as long as the NTP client is set up to ensure the time >>adjustments are smaller than some value X, it would be acceptable. > > > NTP is generally capable of keeping the various system clocks on a LAN > within a few ms of each other, and within a few 10's of ms over the > Internet from GPS, WWV, or similar international time references. > > >>I'll have to look into how to set up Windows XP to prevent users from >>changing the time on their own, assuming that's possible. > > > On a single-user system like Windows, you pretty much have to assume the > user can do anything. They can turn off NTP, reset the clock, reboot the > system, uninstall your software, whatever. > > If you could check to see that NTP is running, it doesn't prove anything. > A malicious and determined user could set up another machine as a NTP > server to synch against, and even configure that machine to look like it > was a stratum-1 reference (i.e. an atomic clock). > > At some point, you need to decide if you trust the system administrator to > supply you with an accurate system clock or not. If you don't, and it's > really important that you have an accurate time reference, you've got an > interesting engineering problem on your hands. A couple of quick thoughts: (1) stupidity is much more prevalent than malice in that environment. (2) Peter, if your app has something else to measure e.g. it is processing zillions of rows from a database, grab the [UTC] wall time every N things, and apply plausibility checks to the speed N/delta(wall) -- if it goes negative or "too high" or "too slow", holler fer a mountie. From helge at aksdal.net Tue Jul 19 14:42:05 2005 From: helge at aksdal.net (Helge Aksdal) Date: Tue, 19 Jul 2005 20:42:05 +0200 Subject: socket programming Message-ID: <20050719184205.GA24773@mail.smule.com> i've recently made my very first socket program in python, however i've stumbled upon a problem. this program connects to a server serveral hundred time while it's executed (it's not possible to let connection stay up, because the server closes it), and after a time my program dies with the error: "socket.error: (134, 'Transport endpoint is not connected')" if i then change to a console window, and telnet to this server it sends me to another one. That's probably why my program dies, how can i get my code to handle this? Trying xxx.xxx.xxx.xxx telnet: connect to address xxx.xxx.xxx.xxx: Connection refused Trying xxx.xxx.xxx.xxx Connected to xxxxxx.xxxxx. Escape character is '^]'. here is my current connection code: def connect(self, server, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setblocking(0) self.sock.connect((server, port)) (sread, swrite, serror) = select.select([], [self.sock], [], 10) if swrite.count(self.sock) > 0: i = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if 0 == i: self.sock.setblocking(1) -- Helge Aksdal From rrr at ronadam.com Wed Jul 6 00:34:46 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 04:34:46 GMT Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > "George Sakkis" wrote in message >>So, who would object the full-word versions for python 3K ? >>def -> define >>del -> delete >>exec -> execute > > > These three I might prefer to keep. > > >>elif -> else if > > > This one I dislike and would prefer to write out. I never liked it in > whatever else language I first encountered it and still don't. > > Terry J. Reedy Interesting, the exact opposite of what I was thinking. I don't use del and exec that often, so the long versions are fine to me. Define is ok for me too because it's usually done only once for each function or method so I'm not apt to have a lot of defines repeated in a short space like you would in C declarations. elif... I was thinking we should keep that one because it's used fairly often and having two keywords in sequence doesn't seem like it's the beat way to do it. Although it could be replaced with an 'andif' and 'orif' pair. The 'andif' would fall though like a C 'case', and the 'orif' would act just like the 'elif'. Actually this is a completely differnt subject reguarding flow testing verses value testing. Else and also would be the coorisponding end pair, but it seemed nobody really liked that idea when I suggested it a while back. Cheers, Ron From apardon at forel.vub.ac.be Wed Jul 6 09:18:22 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Jul 2005 13:18:22 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> <1120636418.166800.42290@o13g2000cwo.googlegroups.com> <1120642040.109796.212450@o13g2000cwo.googlegroups.com> Message-ID: Op 2005-07-06, Michele Simionato schreef : > Fuzzyman: >> So Lisp is for really good programmers, and Python is for >> mediocre programmers ? > > > Python is *also* for mediocre programmers. I see this as a > strength, not as a weakness. But sometimes I get the impression people want it to evolve so it is only for mediocre programmers. -- Antoon Pardon From gregm at taming-tech.com Thu Jul 7 18:50:38 2005 From: gregm at taming-tech.com (GregM) Date: 7 Jul 2005 15:50:38 -0700 Subject: import Help Needed - Newbie References: Message-ID: <1120776638.876867.4730@g14g2000cwa.googlegroups.com> A search on google for odbchelper resulted in: http://linux.duke.edu/~mstenner/free-docs/diveintopython-3.9-1/py/odbchelper.py I think this will help you. Greg. From roccomoretti at hotpop.com Sun Jul 3 12:39:02 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Sun, 03 Jul 2005 11:39:02 -0500 Subject: Assigning to None In-Reply-To: References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <86ekai5sk7.fsf@bhuda.mired.org> Message-ID: Fran?ois Pinard wrote: > [Rocco Moretti] > > >>foo, bar, _ = gen_tuple(stuff) > > >>as '_' is already special cased (last result in interactive mode), and >>is already used for "don't care" sematics in Prolog. > > > `_' is also the `gettext' function in internationalised programs. It so > seems that `_' is in great demand! :-) Hm, then assigning to '_' might not be the best idea in internationalized programs, then. Well, you still have '_'*2, '_'*3, '_'*4, etc. From jeffm at rivernet.com.au Tue Jul 12 06:23:57 2005 From: jeffm at rivernet.com.au (Jeff Melvaine) Date: Tue, 12 Jul 2005 20:23:57 +1000 Subject: Efficiency of using long integers to hold bitmaps References: <42d14ec3@news.rivernet.com.au> <1121017410.949244.288220@g44g2000cwa.googlegroups.com> Message-ID: <42d39a49@news.rivernet.com.au> Raymond, Thanks for your answers, which even covered the question that I didn't ask but should have. "A Python list is not an array()\n" * 100 :) Jeff "Raymond Hettinger" wrote in message news:1121017410.949244.288220 at g44g2000cwa.googlegroups.com... > [Jeff Melvaine] >> I note that I can write expressions like "1 << 100" and the result is >> stored >> as a long integer, which means it is stored as an integer of arbitrary >> length. I may need to use a large number of these, and am interested to >> know whether the storage efficiency of long integers is in danger of >> breaking my code if I use too many. Would I do better to write a class >> that >> defines bitwise operations on arrays of integers, each integer being >> assumed >> to contain at most 32 bits? > > > Both array() objects and long integers are equally space efficient. > In contrast, a list of integers takes up a lot of space (the list is > stored as an array of pointers to individual integer objects). > > Raymond > From lee at example.com Fri Jul 8 09:14:29 2005 From: lee at example.com (Lee Harr) Date: Fri, 08 Jul 2005 13:14:29 GMT Subject: Ann: The first PyWeek Python Game Programming Competition References: Message-ID: > See the competition timetable (including competition dates in various > timezones), rules, sign-up (commencing 6th August) at: > > http://www.mechanicalcat.net/tech/PyWeek > Sounds like fun. One thing. From the website ... > Clip Art > note: > more links welcome How about: http://www.openclipart.org/ From mwh at python.net Tue Jul 5 13:16:15 2005 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Jul 2005 17:16:15 GMT Subject: math.nroot [was Re: A brief question.] References: Message-ID: Tim Peters writes: > [Tim Peters] > >> All Python behavior in the presence of infinities, NaNs, and signed > >> zeroes is a platform-dependent accident, mostly inherited from that > >> all C89 behavior in the presence of infinities, NaNs, and signed > >> zeroes is a platform-dependent crapshoot. > > [Michael Hudson] > > As you may have noticed by now, I'd kind of like to stop you saying > > this :) -- at least on platforms where doubles are good old-fashioned > > 754 8-byte values. > > Nope, I hadn't noticed! I'll stop saying it when it stops being true, > though . Note that since there's not even an alpha out for 2.5 > yet, none of the good stuff you did in CVS counts for users yet. Well, obviously. OTOH, there's nothing I CAN do that will be useful for users until 2.5 actually comes out. > > But first, I'm going to whinge a bit, and lay out some stuff that Tim > > at least already knows (and maybe get some stuff wrong, we'll see). > > > > Floating point standards lay out a number of "conditions": Overflow > > (number too large in magnitude to represent), Underflow (non-zero > > number to small in magnitude to represent), Subnormal (non-zero number > > to small in magnitude to represent in a normalized way), ... > > The 754 standard has five of them: underflow, overflow, invalid > operation, inexact, and "divide by 0" (which should be understood more > generally as a singularity; e.g., divide-by-0 is also appropriate for > log(0)). OK, the decimal standard has more, which confused me for a bit (presumably it has more because it doesn't normalize after each operation). > > For each condition, it should (at some level) is possible to trap each > > condition, or continue in some standard-mandated way (e.g. return 0 > > for Underflow). > > 754 requires that, yes. > > > While ignoring the issue of allowing the user to control this, I do > > wish sometimes that Python would make up it's mind about what it does > > for each condition. > > Guido and I agreed long ago that Python "should", by default, raise an > exception on overflow, invalid operation, and divide by 0, and "should > not", by default, raise an exception on underflow or inexact. OK. > Such defaults favor non-expert use. Experts may or may not be happy > with them, so Python "should" also allow changing the set. Later :) (In the mean time can we just kill fpectl, please?) > > There are a bunch of conditions which we shouldn't and don't trap by > > default -- Underflow for example. For the conditions that probably should > > result in an exception, there are inconsistencies galore: > > > >>> inf = 1e300 * 1e300 # <- Overflow, no exception > > >>> nan = inf/inf # <- InvalidOperation, no exception > > Meaning you're running on a 754 platform whose C runtime arranged to > disable the overflow and invalid operation traps. Isn't that the standard-mandated start up environment? > You're seeing native HW fp behavior then. But anyway, shouldn't we try to raise exceptions in these cases? I don't think it's a particularly good idea to try to utilize the fp hardware's ability to do this at this stage, btw, but to add some kind of check after each operation. > > >>> pow(1e100, 100) <- Overflow, exception > > Traceback (most recent call last): > > File "", line 1, in ? > > OverflowError: (34, 'Numerical result out of range') > > >>> math.sqrt(-1) # <- InvalidOperation, exception > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: math domain error > > Unlike the first two examples, these call libm functions. And the user cares about this why? > Then it's a x-platform crapshoot whether and when the libm functions > set errno to ERANGE or EDOM, and somewhat of a mystery whether it's > better to reproduce what the native libm considers to be "an error", > or try to give the same results across platforms. Python makes a > weak attempt at the latter. Well, you can at least be pretty sure that an infinite result is the result of an overflow condition, I guess. > > At least we're fairly consistent on DivisionByZero... > > When it's a division by 0, yes. It's cheap and easy to test for that. > However, many expert uses strongly favor getting back an infinity > then instead, so it's not good that Python doesn't support a choice > about x/0. Indeed. But I'd rather work on non-settable predictability first. > > If we're going to trap Overflow consistently, we really need a way of > > getting the special values reliably -- which is what pep 754 is about, > > and its implementation may actually work more reliably in 2.5 since my > > recent work... > > I don't know what you have in mind. Well, the reason I headbutted into this stuff again recently was writing (grotty) string to float parsing code for PyPy. If you write (where 'e' is the exponent parsed from, say '1e309'): while e > 0: result *= 10 e -= 1 you get an infinite result in the large e case. If instead you write the seemingly much more sensible: result *= pow(10, e) you don't, you get an overflow error instead. This make me sad. Whether my code should have returned an infinite value or raised an exception for "1e1000" is an open question, but I'd like the answer to be less accidental. > For example, checking the result of x*y to see whether it's an > infinity is not a reliable way to detect overflow, and it fails in > more than one way (e.g., one of the inputs may have been an infinity > (in which case OverflowError is inappropriate), Well, yeah. What other ways can it fail? > and overflow doesn't always result in an infinity either (depends on > the rounding mode in effect)). If we're allowing the user to alter rounding mode, I imagine we'll have a much better idea about this sort of thing. For now, I think we can assume a default rounding that doesn't do that, and someone who has a platform like where it has his or her own problem. > > On the issue of platforms that start up processes with traps enabled, > > I think the correct solution is to find the incantation to turn them > > off again and use that in Py_Initialize(), though that might upset > > embedders. > > Hard to know. Python currently has a hack to disable traps on > FreeBSD, in python.c's main(). Oh, right. Well, I don't much care about embedding, anyway. Cheers, mwh -- MARVIN: Oh dear, I think you'll find reality's on the blink again. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From falcon3166 at hotmail.com Sat Jul 2 13:43:46 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 2 Jul 2005 11:43:46 -0600 Subject: What's wrong with this code? Message-ID: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> Hi all, What's wrong with the following code? It says there is name error, that random is not defined. How do I fix it? # Plays the guessing game higher or lower. # Originally written by Josh Cogliati, improved first by Quique, then by Nathan Pinno. print "Higher or Lower" print number = random.choice(range(100)) guess = 0 while guess != number: guess = input("Guess a number: ") if guess > number: print "Too high" guess = input("Guess a number: ") elif guess < number: print "Too low" guess = input("Guess a number: ") print "Just right" Thanks. Nathan Pinno http://www.npinnowebsite.ca/ -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From nethawg1 at verizon.net Mon Jul 18 12:24:44 2005 From: nethawg1 at verizon.net (windozbloz) Date: Mon, 18 Jul 2005 16:24:44 GMT Subject: Opinions on KYLIX 3 (Delphi 4 Linux) Message-ID: Bye Bye Billy Bob... I'm back with one more question, then I'll chill. I have scoured the news and net for info about Borlands KYLIX 3 and have found little technical info about it. Their screen shots are very impressive, similar to Visual Basic. I have sent several emails to Borlands Sales and Pre-Sales departments. Pre-Sales bounces and Sales won't answer. I'm sitting here with money in hand ready to buy but not from a company that won't give me the time of day. Does anyone of you have experiance with KYLIX 3 and do you think I should consider buying it? Thank You, I'll go oil my keyboard now. Doug -- LINUX protects me from the GATES of hell !!! From dan at cellectivity.com Wed Jul 27 04:53:54 2005 From: dan at cellectivity.com (Dan) Date: Wed, 27 Jul 2005 09:53:54 +0100 Subject: [OT] Problems with permissions etc In-Reply-To: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: <1122454441.27936.8.camel@localhost.localdomain> > 2. I am using wxPython, which was compiled from source. Maybe you had a good reason to install from source. But if you didn't, I suggest using a sys-admin's convenience tool, such as "apt". Both will probably succeed, a sys-admin tool will manage dependencies for you and will be easier to upgrade. -- I'm actually hoping that [Linux] won't take more than 25 or 30% of the market. If Linux owned 95% of the market it would be ... as sick [as Windows]. There is some need for competition. - Linus Torvalds From sjmachin at lexicon.net Sat Jul 9 07:05:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 09 Jul 2005 21:05:56 +1000 Subject: directory traverser In-Reply-To: References: Message-ID: <42CFAF94.4090902@lexicon.net> Florian Lindner wrote: > Hello, > IIRC there is a directory traverser for walking recursively through > subdirectories in the standard library. But I can't remember the name and > was unable to find in the docs. Where did you look? How did you look? > Anyone can point me to it? Did you try Googling in this newsgroup for "directory traverser"? I did: Do you mean "traversal"? -- Hmmm, the allegedly most relevant article is 5 years old -- Hit the "date order" link -- what do we find? The timbot discussing a function called os.walk ... From grante at visi.com Tue Jul 5 12:07:27 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Jul 2005 16:07:27 -0000 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> Message-ID: <11clc1v4el6no7d@corp.supernews.com> On 2005-07-05, Grant Edwards wrote: >> Don't think you can do that with Python... The Python runtime >> interpreter itself is running on a single processor. > > I don't see how that can be. Under Linux at least, the Python > threading module uses "real" OS threads, so there are multiple > instances of the interpreter, right? Generally all but one of > them will be blocked on the GIL, but there are still multiple > interpreter threads (which can be on multiple different CPUs). > > Or is the Python interpreter actually doing the context > switches itself? Upon further thought, that just can't be the case. There has to be multiple instances of the intepreter because the interpreter can make C system calls that block (thus blocking that instance of the interpreter). Other Python threads within the program continue to run, so there must be multiple Python intepreters. -- Grant Edwards grante Yow! I'm wearing PAMPERS!! at visi.com From rkern at ucsd.edu Tue Jul 12 05:06:41 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 02:06:41 -0700 Subject: Trying to come to grips with static methods In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I've been doing a lot of reading about static methods in Python, and I'm > not exactly sure what they are useful for or why they were introduced. > > Here is a typical description of them, this one from Guido: > > "The new descriptor API makes it possible to add static methods and class > methods. Static methods are easy to describe: they behave pretty much like > static methods in C++ or Java." > http://www.python.org/2.2.3/descrintro.html > > Great. So I have learn an entire new language to understand static > methods. Perhaps not -- hence this cry for help. > > As near as I can see it, static methods are object methods that act just > like functions. Er. I always thought that object methods *were* functions, > except they had some runtime magic that passed the object itself as the > first argument. [snip] > What are some usage cases for using Class.StaticMethod() instead of > instance.method()? Everything I've read seems to just assume that the > benefits of static methods are so obvious that they don't need explaining. > Unfortunately, I haven't come from a background in OO and I'm easily > confused, hence this post. staticmethods don't see a whole lot of use in Python. They see use in Java because everything has to be stuck in a class, even if they don't actually require an instance of the class to work. In Python, you usually just define a function. I think staticmethod was implemented along with classmethod primarily for completeness than anything else. OTOH, I do find myself using them occasionally to group such functions appropriately. I'll be writing a utility method that doesn't actually need an instance or the class to be passed in, so I make it a staticmethod. It *could* just as well be a module-level function, but sometimes it really belongs tucked in with the class. It could also be a regular method, but then I can't call it from the outside without actually having an instance which isn't actually needed. It could also be a classmethod, but since it doesn't actually need any information from the class to do its work, I find that the extra reminder of staticmethod helps my brain understand what it's doing. All told, I'd probably vote -0.5 on a builtin staticmethod if it came up today. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mwm at mired.org Sun Jul 31 15:05:03 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 15:05:03 -0400 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: <861x5ehk4g.fsf@bhuda.mired.org> Jorge Godoy writes: > Mike Meyer wrote: > > [ Having GUI stuff included on a standard installation of Python ] > >> However, you can get compilers for both that come bundled with a good >> GUI library. Could it be that that's what you really want - someone to >> distribute Python bundled with an enterprise-class GUI library and >> IDE? > > And then you are going to have three or four different distributors of > Python using three or four different GUI toolkits and also python.org > distributing Python for free without any (or with TKinter)... Which one > will be the "standard" distributor so that it gets documented and adopted? We already have multiple distributions of Python: CPython, IronPython, and Jython (and there's at least one more). We even have multiple distributions of CPython, what with Active State doing their own and the MacPython distribution. I'm not proposing a fundamental change in the world, I'm suggesting an addition that would satisify the OPs needs. The "standard" distributor is whichever one your organization settles on when it comes time to choose a Python distribution. > In an international project I see othe problems as well -- cost, logistics, > S&H, customs, etc. None of which has stopped linux from following this path. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gene.tani at gmail.com Tue Jul 19 09:17:44 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jul 2005 06:17:44 -0700 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? In-Reply-To: <-I2dnSRstZxiekHfRVn-rA@powergate.ca> References: <-I2dnSRstZxiekHfRVn-rA@powergate.ca> Message-ID: <1121779064.088577.77130@g43g2000cwa.googlegroups.com> ok, i don't see URL and password here, so try: urllib2 (maybe mechanize), then beautiful soup. maybe another HTML parser ... From peter at engcorp.com Fri Jul 8 21:58:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 08 Jul 2005 21:58:09 -0400 Subject: can't start new thread In-Reply-To: <1120842854.694743.216930@o13g2000cwo.googlegroups.com> References: <1120842854.694743.216930@o13g2000cwo.googlegroups.com> Message-ID: jdonnell wrote: > I'm at a loss on this one. I have a multithreaded script that gets > 'thread.error: can't start new thread' errors seemingly randomly. I > just got it right after starting the script when it was trying to > create the 5th thread. Usually the script will run for a while before > throwing this error, but sometimes it throws it right away. Often posting the actual traceback, cut and pasted without editing, is highly effective at helping us provide a useful answer... -Peter From max at alcyone.com Sun Jul 3 23:54:22 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 03 Jul 2005 20:54:22 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: Ron Adam wrote: > So you are saying that anything that has a 1% use case should be > included as a builtin function? > > I think I can find a few hundred other functions in the library that are > used more than ten times as often as reduce. Should those be builtins too? > > This is a practical over purity issue, so what are the practical reasons > for keeping it. "It's already there" isn't a practical reason. And it > covers 100% of it's own potential use cases, is circular logic without a > real underlying basis. But the Python 3000 plan, at least what we've heard of it so far, isn't to move it to a standard library module. It's to remove it altogether, replacing it with sum and product. Since sum and product don't cover all the uses cases for reduce, this is a case of taking one function that handles all the required use cases and replacing it with _two_ functions that don't. Since it's doubling the footprint of the reduce functionality, arguments about avoiding pollution are red herrings. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Every astronaut who goes up knows the risks he or she faces. -- Sally Ride From john at castleamber.com Mon Jul 18 18:40:10 2005 From: john at castleamber.com (John Bokma) Date: 18 Jul 2005 22:40:10 GMT Subject: Xah's edu corner: on Microsoft hatred References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: Steve Sobol wrote: > Xah Lee wrote: >> Dear Joe, >> >> It is well known that you are an avid hater of Microsoft, from their >> technologies to their leader to their business practices. I have now >> and then seen your impassioned expression of this hatred, scattered >> among your newsgroup posts. > > This has ZERO to do with any of the groups you posted to. Go post to > some advocacy groups where you *might* be on-topic. A typical Xah Lee posting... wake me up when he is able to write a single post that makes and sense, and doesn't contain fuck or similar words. -- John Small Perl scripts: http://johnbokma.com/perl/ Perl programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From cam.ac.uk at mh391.invalid Sun Jul 31 07:55:15 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 31 Jul 2005 12:55:15 +0100 Subject: Passing a log handle to a module? Help needed with logging module and In-Reply-To: <1122784140.800331.86740@z14g2000cwz.googlegroups.com> References: <1122784140.800331.86740@z14g2000cwz.googlegroups.com> Message-ID: rh0dium wrote: > But I can't figure out how to pass the d$!@# logging handle to the > called module - I'm sorry, but what have you tried? It seems like it should be a simple matter of calling module.main(log). > much less change the getLogger name to "module". Why do you want to do this? -- Michael Hoffman From seberino at spawar.navy.mil Sun Jul 3 01:17:23 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 2 Jul 2005 22:17:23 -0700 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? Message-ID: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> Guido gave a nice "Python Regrets" Power Point talk at OSCON few years ago. I was wondering if the plan is to ever implement these ideas. e.g. Guido said he'd prefer 'print' to be a *function* with perhaps a 'println' version IIRC. He also had a ton of stuff he'd rather see become iterators. Chris From st at realU.de Fri Jul 1 11:31:27 2005 From: st at realU.de (Stefan Tietke) Date: Fri, 01 Jul 2005 17:31:27 +0200 Subject: getting Quicktime video into Python Message-ID: <42C561CF.9060005@realU.de> Hi all, for a realtime simulation of a video installation we want to use Quicktime to read video data from a file or stream and process the data in a realtime Gameblender model. We are trying to simulate a large-scale, low resolution media facade using individuell video pixels to control lamps mounted into the facade. For a related, earlier project, please see http://www.bix.at/ where you can also find images of this project and a software simulator created using MAX/MSP and Jitter. Now we plan to create a new simulator using Quicktime and Gameblender. Alternativly we think of using Jitter for preprocessing and Blender for visualisation. What we need are hints and information how to connect Quicktime and Blender, or Jitter and Blender. If neccessary we could spend a (limited, this is an art project) amount of money for somebody programming a custom solution. Essentially what we need is a either a Quicktime->Python module or a Quicktime->Blender module, providing pixel level access to the video data. We need a solution for both Macintosh and Windows OS. Solution 1) A pure Quicktime + PYthon + Blender solution. I noticed there is a python module called Carbon.QT availlable for MacOS. -- Is this what we need for our purpose? -- I could not find a version of this module for windows. Is there any port? -- How difficult would it be to port the Mactintosh module to Quicktime/Windows? -- Is there somebody who could do a port for us? -- Are there any other Quicktime modules availlable (Macintosh/ Windows) ? Solution 2) A mixed solution using Quicktime on Mactinosh, and another module on Windows. I noticed there are two related modules called pyVideo and pyMedia. -- Is anybody using those modules and could give us any advice? Solution 3) A solution consisting of Jitter + Python + Blender. -- How could we transmit the video data from Jitter into either Gameblender or Python, e.g. streaming into an UDP port? Solution 4) A solution using vlc/ mplayer + Python + Blender. -- How could we stream the decoded, uncompressed video data from programs like vlc or mplayer in realtime into Blender or Python? Any hints or recommendations? Thanks in advance for all your help and advice + all the best, Stefan Tietke -- stefan tietke / st at realU.de realities:united leipziger strasse 50 (ebbinghaus) d-10117 berlin tel +49. 30. 20 64 66 -30 fax +49. 30. 20 64 66 -39 _________________________________ http://www.realities-united.de From jitendran at productdossier.com Tue Jul 26 01:56:57 2005 From: jitendran at productdossier.com (jitu) Date: 25 Jul 2005 22:56:57 -0700 Subject: Something that Perl can do that Python can't? References: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> Message-ID: <1122357417.596068.12320@g44g2000cwa.googlegroups.com> Donn Cave wrote: > In article <1122064588.174698.153220 at g43g2000cwa.googlegroups.com>, > "Dr. Who" wrote: > > So here it is: handle unbuffered output from a child process. > > Your Perl program works the same for me, on MacOS X, > as your Python program. That's what we would expect, > of course, because the problem is with the (Python) > program on the other end - it's buffering output, > because the output device is not a terminal. > > Donn Cave, donn at u.washington.edu Yes Donn's right , works the same for me , bufcallee.py may be should look like this import time import sys sysout=sys.stdout sysout.write("START\n") sysout.flush() time.sleep(10) sysout.write("STOP\n") sysout.flush() regards jitu From http Fri Jul 29 20:34:54 2005 From: http (Paul Rubin) Date: 29 Jul 2005 17:34:54 -0700 Subject: Block-structured resource handling via decorators References: <8664uti1kr.fsf@bhuda.mired.org> Message-ID: <7xvf2t5dxt.fsf@ruckus.brouhaha.com> Mike Meyer writes: > > When handling resources in Python, where the scope of the resource is > > known, there seem to be two schools of thought: > > (1) Explicit: ... > > (2) Implicit: let the GC handle it. > > The only cases I see the first school of thought is when the resource > in question is "scarce" in some way. For example, most OS's place a > limit on the number of open files a process can have, some rather > tight. CPython's garbage collector will close an open file when it > leaves scope. Jython's GC will close it when the file is collected, > but you have no idea of when that will be, and an "open" failing won't > trigger a GC. So in this case, the first form is less likely to fail > unexpectedly. I thought there was a Zen thing somewhere saying that Python is not Perl. One of Perl's silliest tenets is that the implementation defines the language. There are already 4 different Python implementations (CPython, Jython, Pypy, IronPython) and probably more on the way. We should take the view that the manual, not the implementation, defines the language. The manual doesn't specify anything about reference counting or GC happening as soon as something goes out of scope. That is a GOOD thing since requiring CPython-like behavior would eliminate many good GC techniques, including some that are both more efficient and easier for extension writers to deal with. Since reference counting is not in the manual, it is not part of the language, it's subject to change at any time in any implementation, and non-throwaway Python apps should not depend on it. On the other hand, the try/finally explicit release is cumbersome and non-tasty. Therefore, the correct solution is a language extension along the lines of PEP 343. I haven't studied PEP 343 specifically enough to say that I think every detail of it is the right thing, but at least it is the right idea. From Holzmayer.Bernhard at deadspam.com Thu Jul 14 09:39:22 2005 From: Holzmayer.Bernhard at deadspam.com (Bernhard Holzmayer) Date: Thu, 14 Jul 2005 15:39:22 +0200 Subject: Splitting on a word References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> <1121344568.230244.214440@o13g2000cwo.googlegroups.com> Message-ID: qwweeeit at yahoo.it wrote: > Bernard... don't get angry, but I prefer the solution of Joe. Oh. If I got angry in such a case, I would have stopped responding to such posts long ago You know the background... and you'll have to bear the consequences. ;-) > ... > for me "pythonic" means simple and short (I may be wrong...). It's your definition, isn't it? One of the most important advantages of Python (for me!) besides its readability is that it comes with "Batteries included", which means, that I can benefit of the work others did before, and that I can rely on its quality. The solution which I proposed is nothing but the test code from htmllib, stripped down to the absolut minimum, enriched with the print command to show the anchor list. If I had to write production-level code of your sort, I'd take such an off-the-shelf solution, because it minimizes the risk of failures. Think only of such issues like these: - does your code find a tag like or references with/without " ...? - does it survive ill-coded html after all? I've made the experience that it's usually better to rely on such "library" code than to reinvent the wheel. There's often a reason to take another approach. I'd agree that a simple and short solution is fascinating. However, every simple and short solution should be readable. As a terrific example, here's a very tiny piece of code, which does nothing but calculate the prime numbers up to 1000: print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1), range(2,1000))) - simple (depends on your familiarity with stuff like map and lambda) - short (compared with different solutions) - and veeerrrryyy pythonic! Bernhard From exogen at gmail.com Sat Jul 30 12:31:49 2005 From: exogen at gmail.com (Brian Beck) Date: Sat, 30 Jul 2005 12:31:49 -0400 Subject: string methods In-Reply-To: <3l1js6F10d0leU1@individual.net> References: <3l1js6F10d0leU1@individual.net> Message-ID: anthonyberet wrote: > I know this touches on immutability etc, but I can't find string methods > to return the first 3 characters, and then the last 2 characters, which > I could concatenate with newchar to make a new string. As tiissa said, you want slicing: py> s = "foobar" py> s[:3] 'foo' py> s[:3] + "B" + s[4:] 'fooBar' py> -- Brian Beck Adventurer of the First Order From steve at REMOVETHIScyber.com.au Mon Jul 11 07:48:11 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 11 Jul 2005 21:48:11 +1000 Subject: __eq__ on a dict References: Message-ID: On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote: > Hello, > > I can't find the docs for __eq__ on a dict and I can't find > a description on what the eq does (strangely it does implement > and < > but I have no idea what that does). Does anyone know (definitively) > what the __eq__, __gt__, __lt__ methods do. > > BTW, google is not my friend - I invited it out for a drink last > week and it stood me up :-). It works for me. Google on "__eq__ Python" and the 5th and 6th sites are: http://python.active-venture.com/ref/customization.html http://www.network-theory.co.uk/docs/pylang/ref_32.html Normally, asking Python for help is a good way to read the docs, but in this particular case, it is a big let-down: py> help({}.__eq__) Help on method-wrapper: __eq__ = For any two objects x and y, when you call x == y Python calls x.__eq__(y). That includes dicts: py> dictA = {0: "spam"} py> dictB = {0: "sp" + "am"} py> dictC = {1: "ham"} py> py> dictA == dictB True py> dictA.__eq__(dictB) # same as dictA == dictB True py> dictB == dictC # calls dictB.__eq__(dictC) False Two dicts are equal if they have the same keys and the same values. In general, you should not call __eq__ directly, but use the == operator instead. Likewise: x > y becomes x.__gt__(y) x < y becomes x.__lt__(y) x >= y becomes x.__ge__(y) x <= y becomes x.__le__(y) x != y becomes x.__ne__(y) x <> y also becomes x.__ne__(y) -- Steven From onurb at xiludom.gro Thu Jul 21 14:09:47 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 21 Jul 2005 20:09:47 +0200 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <42dfb111@griseus.its.uu.se> References: <42dfb111@griseus.its.uu.se> Message-ID: <42dfe4f0$0$17086$626a14ce@news.free.fr> Jan Danielsson wrote: > Hello all, > > How do I make a python script actually a _python_ in unix:ish > environments? > > I know about adding: > #!/bin/sh > > ..as the first row in a shell script, but when I installed python on > a NetBSD system, I didn't get a "python" executable; only a "python2.4" > executable. > > Adding "#!/usr/pkg/bin/python2.4" as the first row in the script > would probably work, but that would be too specific for the system I'm > using, imho. What about: ln /usr/pkg/bin/python2.4 /usr/bin/python then #!/usr/bin/python in your script, and you should be done (dont forget to chmod +x your script of course) Or I'm I missing something specific to xxxBSD ? > I saw someone using "#!/usr/bin/env python", but that failed on the > system I'm using, How do you execute the python interpreter ? If you need to type "python2.4" (not just "python"), then obviously 'usr/bin/env python' syntax shouldn't work either. My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rootrot at govtabuse.com Sat Jul 30 00:49:47 2005 From: rootrot at govtabuse.com (James Richards) Date: Sat, 30 Jul 2005 04:49:47 GMT Subject: To thread or not to thread References: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> Message-ID: On 2005-07-28, Sidd wrote: > Hello, > I was recently reading an article on threading in python and I > came across Global Interpreter Lock,now as a novince in python I was > cusrious about > > 1.Is writing a threaded code in python going to perform well than a > normal python code.If so on what basis can it performance be measured. My last "real" experience with python threads was a while back, on a P-2. That experience suggested that creating "lots" of threads (a few hundred) caused some serious performance impacts. I determined, in that instance, that it was better to write my own implementation to simulate threads. I had set of classes that pretended to be threads. I had another class which actually did all the threading for them. It was pretty ugly. > > 2.Is writing a threaded code in python better than a code written in > C/C++ using PTHREADS. I agree with the earlier. Define "better." Do you really have a heavily multi-threaded app? Are these threads all CPU-intensive, or do you just have a bunch of threads which need some arbitrary scheduling? Is it really worth re-writing in PTHREADS? Or could you buy a new server and save a few months in development time by writing your own scheduling? It all depends on your situation. > > If someone can comment on these questions, it would be great. > Heh. You're on Usenet. *Anyone* can comment on these questions. :-) You should have asked for *useful* comments. ;-) -- Liberty means responsibility. That is why most men dread it. - George Bernard Shaw From agriff at tin.it Sun Jul 3 05:36:10 2005 From: agriff at tin.it (Andrea Griffini) Date: Sun, 03 Jul 2005 09:36:10 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: On Sat, 2 Jul 2005 03:04:09 -0700 (PDT), "Ralf W. Grosse-Kunstleve" wrote: >Hi fellow Python coders, > >I often find myself writing:: > > class grouping: > > def __init__(self, x, y, z): > self.x = x > self.y = y > self.z = z > # real code, finally > >This becomes a serious nuisance in complex applications with long >argument lists, especially if long variable names are essential for >managing the complexity. Therefore I propose that Python includes >built-in support for reducing the ``self.x=x`` clutter. With some help from new-style classes you can get more than just removing the "self.x = x" clutter. I'm not an expert of these low-level python tricks, but you can download from http://www.gripho.it/objs.py a small example that allows you to write class MyClass(Object): x = Float(default = 0.0, max = 1E20) y = Float(min = 1.0) and you can get in addition of redudancy removal also parameter checking. You can also have an __init__ method that gets called with attributes already set up. HTH Andrea From hancock at anansispaceworks.com Tue Jul 19 20:48:06 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 19 Jul 2005 19:48:06 -0500 Subject: I just wanna know about os.path module.. In-Reply-To: <1121622472.349346.182970@g49g2000cwa.googlegroups.com> References: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> <1121622472.349346.182970@g49g2000cwa.googlegroups.com> Message-ID: <200507191948.07155.hancock@anansispaceworks.com> On Sunday 17 July 2005 12:47 pm, kimes wrote: > Thanks for all you guys help.. > I'm still confused about that.. > When I just call import os.path without calling import os.. > In that case, you mean 'import os' is called implicitly? > Why? and How? > > how python knows it should call import when we call import os? > Please make me clear.. :) All you have to do is import os Python "knows" to import "os.path" because "os" tells it to. That is to say, somewhere in "os" is code (conceptually) like: import path The os.path module is a sub-module of os. What makes it particularly interesting is only that it is not always the *same* module -- the particular os.path module that is loaded is determined by your architecture. On a POSIX system (including Unix and Linux) it will actually be an alias for "posixpath", but it will be something else on Windows and Macintosh systems. OTOH, the same thing will happen if you say: import os.path since it must import "os" in order to get to "path". I don't think that Python is guaranteed to load the entire contents of such dotted imports, although it appears to do so for the case of "os" (I believe it depends on the code in the module). Occasionally you will find packages that require you to load subpackages explicitly: import mypackage import mypackage.subpackage but not with "os". Oh, and what Peter Otten meant by "module, or package, it doesn't matter here" is that the two terms are roughly equivalent, although there is an internal distinction -- a "module" is a single Python source file, whereas a "package" is a directory of source files which are set up to load like a single module. For the purposes of this discussion, the two terms are basically interchangeable (we really ought to have a single term that can mean either -- I usually speak loosely of "modules" regardless of which way they are actually defined). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From maxm at mxm.dk Fri Jul 8 04:35:15 2005 From: maxm at mxm.dk (Max M) Date: Fri, 08 Jul 2005 10:35:15 +0200 Subject: mail sending using telnet in python In-Reply-To: References: Message-ID: <42ce3aa1$0$255$edfadb0f@dread12.news.tele.dk> praba kar wrote: > Dear All, > Normally we can send mail using > telnet in linux. In the following way > Is it possible to run same thing same manner > in python? If possible kindly help me with > specimen code. Actually I gone through > telnetlib module documentation but I cann't > get solution for it. Why not just use the smtp module? It's a tad easier. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From rbt at athop1.ath.vt.edu Wed Jul 13 10:39:41 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 13 Jul 2005 10:39:41 -0400 Subject: all possible combinations In-Reply-To: References: Message-ID: <1121265581.28091.2.camel@athop1.ath.vt.edu> On Thu, 2005-07-14 at 00:47 +1000, Steven D'Aprano wrote: > On Wed, 13 Jul 2005 10:21:19 -0400, rbt wrote: > > > Say I have a list that has 3 letters in it: > > > > ['a', 'b', 'c'] > > > > I want to print all the possible 4 digit combinations of those 3 > > letters: > > > > 4^3 = 64 > > > > aaaa > > abaa > > aaba > > aaab > > acaa > > aaca > > aaac > > ... > > > > What is the most efficient way to do this? > > Efficient for who? The user? The programmer? The computer? Efficient use > of speed or memory or development time? The CPU > > If you want the fastest runtime efficiency, a lookup table of > pre-calculated values. That is an O(1) operation, and you don't get any > faster than that. > > If you expect to extend the program to arbitrary lists, pre-calculation > isn't practical, so you need an algorithm to calculate permutations (order > matters) or combinations (order doesn't matter). My list is not arbitrary. I'm looking for all 'combinations' as I originally posted. Order does not matter to me... just all possibilities. From draghuram at gmail.com Tue Jul 5 12:05:35 2005 From: draghuram at gmail.com (draghuram at gmail.com) Date: 5 Jul 2005 09:05:35 -0700 Subject: pexpect question.... In-Reply-To: <1120540304.656547.209800@g49g2000cwa.googlegroups.com> References: <1120236289.836018.234240@f14g2000cwb.googlegroups.com> <1120540304.656547.209800@g49g2000cwa.googlegroups.com> Message-ID: <1120579535.710741.184240@g44g2000cwa.googlegroups.com> Hi, While I continue to look at the problem, I thought I would post more details. In a sense, this is more of a UNIX issue. I have a python script that uses pexpect to spawn a child process (p1). The python script then goes ahead and does a "tail --pid=p1". Assuming that I do close(wait=0), P1 completes and gets stuck in zombie status. The python script is also stuck because "tail" will not return until zombie P1 goes away. So each is waiting for the other to go away resulting in a deadlock. Apparently, when close(wait=0) is done, all that pexpect does is that it wouldn't call wait() on the spawned process anymore. I was looking for a solution where pexpect also should be able to tell kernel that it doesn't care about child process's exit status. Note that this is different from not doing "wait". I think this can be achieved by ignoring SIGCLD on SVR4 systems but I am not sure what is the (expected) behaviour on posix/linux. Unfortunately, only parent process can control this behaviour. So my questions are two fold. 1) What is the best way (preferably a generic UNIX way) for a parent process to inform kernel that it is not interested in child process's exit status? 2) How can this be achieved in pexpect module since it is spawning the child process in my case. As I said, this is more of a UNIX question rather than python one. Thanks, Raghu. From peter at engcorp.com Thu Jul 14 23:02:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 23:02:24 -0400 Subject: How can I import a py script by its absolute path name? In-Reply-To: References: <311b5ce105071404412d4bf318@mail.gmail.com> Message-ID: Jesse Noller wrote: > A question in a similiar vein: > > I have appended 2 different directories to my path (via > sys.path.append) now - without knowing the names of the files in those > directories, I want to force an import of the libraries ala: > > for f in os.listdir(os.path.abspath(libdir)): > module_name = f.strip('.py') This doesn't do what you think it does: >>> 'pyoopsyp.py'.strip('.py') 'oops' Read the docs on strip(), and then the docs on os.path.splitext() and friends, and/or download and use Jasen Orendorrf's "path" module which will make all your path-related code half the size and twice as easy to read and write. -Peter From roy at panix.com Sun Jul 10 08:03:44 2005 From: roy at panix.com (Roy Smith) Date: Sun, 10 Jul 2005 08:03:44 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Thomas Lotze wrote: > Basically, I agree with the "make it run, make it right, make it fast" > attitude. However, FWIW, I sometimes can't resist optimizing routines that > probably don't strictly need it. Not only does the resulting code run > faster, but it is usually also shorter and more readable and expressive. Optimize for readability and maintainability first. Worry about speed later. From stian at soiland.no Wed Jul 6 14:49:19 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 6 Jul 2005 20:49:19 +0200 Subject: Use cases for del In-Reply-To: References: Message-ID: <20050706184919.GV12095@itea.ntnu.no> On 2005-07-06 18:10:16, Ron Adam wrote: > But what if assigning a name to None actually unbound it's name? > And accessing an undefined name returned None instead of a NameError? Yes, and we can make someunknownlist[] = 2 magically do someunknownlist = list() and append 2. Please. -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] From k33rni at gmail.com Mon Jul 4 05:44:49 2005 From: k33rni at gmail.com (k33rni at gmail.com) Date: 4 Jul 2005 02:44:49 -0700 Subject: Embedding performance. References: Message-ID: <1120470289.104568.6960@z14g2000cwz.googlegroups.com> amit wrote: > Is there any kind of performance differences to the different ways of > embedding python? > PyEval_EvalCode() > PyRun_SimpleFile() > PyObject_CallObject() > AFAIK, these are only different wrappers, while you're generally getting at the same functionality. I assume you're somewhat familiar with the Python API. What you're saving using the third one is parsing and compiling time, since the other two functions do it every time they're called, I believe. With PyObject_CallObject() you already have the PyObject, so it just goes straight to the interpreter core, and does not do any parsing and compiling. That said, you have to get the object from somewhere first, possibly using the other two :), which may not apply if you're calling something embedded (that is, written in C). A quick look in the Python sources brings up the following: PyRun_SimpleFile: adds __main__. sets __file__. looks for .pyc or .pyo files, loads the code object from them, or parses text, and finally calls PyEval_EvalCode with the code object. So there, you have the overhead. PyObject_CallObject: goes through some redirection to PyObject_Call, which calls obj->ob_type->tp_call directly. PyEval_EvalCode: checks for globals, checks for arguments, creates a frame with all the necessary stuff, checks for generators, calls PyEval_EvalFrame() which does all the dirty running of python code. So there, the least overhead seems to be in CallObject. Don't treat this as an authoritative answer, though.:) From gsakkis at rutgers.edu Mon Jul 4 07:36:34 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 4 Jul 2005 04:36:34 -0700 Subject: math.nroot [was Re: A brief question.] References: <1120432250.340056.237460@g44g2000cwa.googlegroups.com> <42C8AD20.30004@REMOVEMEcyber.com.au> Message-ID: <1120476994.515029.129260@g14g2000cwa.googlegroups.com> "Steven D'Aprano" wrote: > But it doesn't make sense to say that two flags are equal: > > keep_processing = True > more_reading_needed = True > while more_reading_needed and keep_processing: > get_more_records() > process_records() > if not keep_processing: > print "User clicked Cancel" > > What does it mean to say that the flag done_processing > is equal to the flag more_reading_needed? (That is not > the same question as asking if the two flags have the > same value.) Huh ? Equality *is* the answer to whether two "things" (flags or whatever) have the same value or not. What else could it be ? Certainly not whether they are *the same*; you have the 'is' operator for checking identity. In any case, "done_processing == more_reading_needed" is perfectly valid and most people would agree that if the result is True, "done_processing" and "more_reading_needed" are equal. > It gets worse. Consider this example of "logic": > > x = log(-5) # a NaN > y = log(-2) # the same NaN > x == y # you want this to be true for NaNs > > Then: > > # compare x and y directly > log(-5) == log(-2) > # if x == y then exp(x) == exp(y) for all x, y > exp(log(-5)) == exp(log(-2)) > -5 == -2 Such paradox cases can be avoided if the only operations defined for NaNs are equality/inequality; all others yield NaN too. That is, exp(NaN) is NaN, as it is log(NaN), 3**NaN / 5i and so on. Think of NaN as a black hole that absorbs and assimilates what falls into it, so log(-5) and log(-2) are just NaN, they lose their "identity" as two distinct things, "log(-5)" and "log(-2)". > > Similarly, if z=0/0, z would also be invalid, but > > different from x and y, since it is the result of a different invalid > > operation. This brings us to the many-NaN situation. > > The problem is, the many NaNs in the IEEE standard (or > at least Apple's implementation of it) refer to _kinds_ > of NaNs, not NaNs themselves. > > log(-2) is not the same "not a number" as log(-2.0001), > or log(-2.3). They might be the same "kind" of failure, > but that's it. That's absolutely fine; as long as two "things" are invalid and they're invalid for the same reason ("kind of failure"), they are equal to me. > Having given reasons why it is utterly bogus to be > comparing NaNs for equality, I will say this. > Practicality beats purity. If you can demonstrate a > good usage case for testing equality with NaNs, I will > accept that it is a good thing to do. > > if x in (SOME_NAN, SOME_OTHER_NAN, ANOTHER_NAN, \ > YET_ANOTHER_NAN, AND_ANOTHER_NAN, ..., \ > # 240+ more NaNs listed > ALMOST_FINISHED_NOW, LAST_NAN): > print "Calculation failed!" > > is _not_ a good usage case, since it is best handled with: > > if isNan(x): # handled by the floating point package > print "Calculation failed!" Agreed on that, if all you need to know is if the outcome of an expression is valid or not. But since a NaN can be thought of as "a flag representing the fact that an error occurred", as you mentioned, it makes sense in practice to ask whether two errors are of the same kind, e.g. for handling them differently. If I understood correctly, your objection is using the equality operator '==' with these semantics for NaNs. I would say that it's a reasonable choice for "practicality beats purity" reasons, if nothing else. George From s_t_a_n_i at gmx.net Wed Jul 13 13:34:28 2005 From: s_t_a_n_i at gmx.net (s_t_a_n_i at gmx.net) Date: 13 Jul 2005 10:34:28 -0700 Subject: SDXF 1.0 - Stani's DXF Library for Python Message-ID: <1121276068.648562.27480@z14g2000cwz.googlegroups.com> SDXF is a Python library to generate DXF files. DXF is an abbreviation of Data Exchange File, a vector graphics file format. It is supported by virtually all CAD products (such as AutoCAD, Blender, 3Dstudio, Maya,Vectorworks...) and vector drawing programs (such as Illustrator, Flash, ...). SDXF can generate complex CAD drawings (dxf format) with all kind of entities (such as 3DFace, Arc, Insert, Circle, Line, Mtext, Point, Polyline, Rectangle (can be filled), Solid & Text). They can be structured with Layers, Blocks, Linetypes, Text styles and Views. Example import sdxf d=sdxf.Drawing() d.append(sdxf.Text('Hello World!',point=(3,0,1))) d.append(sdxf.Line(points=[(0,0,0),(1,1,1)])) d.saveas('hello_world.dxf') For more info&downloads: http://www.stani.be/python/sdxf From twic at urchin.earth.li Tue Jul 5 09:01:04 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 5 Jul 2005 14:01:04 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120490609.134384.206840@g47g2000cwa.googlegroups.com> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: On Mon, 4 Jul 2005, George Sakkis wrote: > "Tom Anderson" wrote: > >> I'll just chip in and say i'd quite like a flatten(), too; at the moment, >> i have one like this: >> >> def flatten(ll): >> return reduce(lambda a, l: a.extend(l), ll, []) > > This doesn't work; a.extend() returns None, not the extended list a: Ah, no, very good, i was hoping someone would notice that. Well done. I think my lambda looks more like lambda a, b: a + b, but i realised the other day that extend could make it more efficient, and didn't think it through properly. tom -- The revolution will not be televised. The revolution will be live. From gregpinero at gmail.com Fri Jul 8 12:20:17 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Fri, 8 Jul 2005 12:20:17 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: <312cfe2b05070809197f03fd15@mail.gmail.com> References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> <42c1662d$0$26260$626a14ce@news.free.fr> <1119977801.449923.128330@o13g2000cwo.googlegroups.com> <1120739908.912266.256630@g14g2000cwa.googlegroups.com> <312cfe2b05070809197f03fd15@mail.gmail.com> Message-ID: <312cfe2b0507080920609a5088@mail.gmail.com> Has anyone recommended ftputil? Either add that to the library or make the existing ftp module more high level would be my suggestion. http://www.sschwarzer.net/python/python_software.html -Greg On 7 Jul 2005 05:38:28 -0700, awbarker at gmail.com wrote: > 1. LDAP module should be included in the base distro. > 2. DNS library really should be included in the base library, I emailed > Anthony Baxter and he replied, saying it was almost done. > 3. Ipython would be nice > > -- > http://mail.python.org/mailman/listinfo/python-list > From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 15 08:24:09 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 15 Jul 2005 14:24:09 +0200 Subject: Python Programming Contest References: <1121421762.826887.114880@g43g2000cwa.googlegroups.com> Message-ID: Brian Quinlan enlightened us with: > Also, it is easiest to protect my system against malicious code if > it is being run on an OS without a writeable filesystem. Even easier with User Mode Linux and a COW (copy on write) filesystem. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From devnull at joreybump.com Sun Jul 10 00:17:53 2005 From: devnull at joreybump.com (Jorey Bump) Date: Sun, 10 Jul 2005 04:17:53 GMT Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Steve Juranich wrote in news:mailman.1544.1120933273.10512.python-list at python.org: > I was wondering how true this holds for Python, where exceptions are > such an integral part of the execution model. It seems to me, that if > I'm executing a loop over a bunch of items, and I expect some > condition to hold for a majority of the cases, then a "try" block > would be in order, since I could eliminate a bunch of potentially > costly comparisons for each item. But in cases where I'm only trying > a single getattr (for example), using "if" might be a cheaper way to > go. > > What do I mean by "cheaper"? I'm basically talking about the number > of instructions that are necessary to set up and execute a try block > as opposed to an if block. > > Could you please tell me if I'm even remotely close to understanding > this correctly? *If* I'm not doing a lot of things once, I *try* to do one thing a lot. From prabapython at yahoo.co.in Wed Jul 20 03:44:06 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 20 Jul 2005 08:44:06 +0100 (BST) Subject: Reg file uploading In-Reply-To: Message-ID: <20050720074406.10046.qmail@web8402.mail.in.yahoo.com> Dear All, I have doubt regarding file uploading. When we upload a file to the remote server we can get file type through file extentions. How we can find out file type if a file doesn't have any extentions ? with regards PRabahar __________________________________________________________ Free antispam, antivirus and 1GB to save all your messages Only in Yahoo! Mail: http://in.mail.yahoo.com From python.leojay at gmail.com Thu Jul 14 05:09:10 2005 From: python.leojay at gmail.com (Leo Jay) Date: Thu, 14 Jul 2005 17:09:10 +0800 Subject: how to get rate of pop3 receiving progress? Message-ID: <4e307e0f0507140209a295e8a@mail.gmail.com> when i use POP3.retr() in poplib module, the retr() function will not return until the receiving progress is finished so, is there any way to get the rate of receiving progress? Thanks -- Best Regards, Leo Jay From SSchukat at dspace.de Thu Jul 21 05:55:03 2005 From: SSchukat at dspace.de (Stefan Schukat) Date: Thu, 21 Jul 2005 10:55:03 +0100 Subject: returning list of strings from Python COM to Visual basic 6 Message-ID: You have to wrap the python object with a COM object: def Get_Obj(self): return win32com.server.util.wrap(an_object) Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org]On Behalf Of > Philippe C. Martin > Sent: Thursday, July 21, 2005 1:42 AM > To: python-list at python.org > Subject: Re: returning list of strings from Python COM to > Visual basic 6 > > > I can now pass and return quite a few types except object > instances: my > python code gets to the point where I do: > > > def Get_Obj(self): > ..... > return an_object > > My VB code looks like > > Dim obj as Variant > > obj = acom.Get_Obj() > > > I get an "unexpected Python error ..... Objects of type > 'instance' can not > be converted to a COM VARIANT" > > Is there a way out ? > > Thanks, > > Philippe > > > > > > > Philippe C. Martin wrote: > > > Hi, > > > > Is it possible ? > > > > ex: return ['1','2'] > > > > If so which type should I use in VB ? > > > > dim res as ??????? > > > > Set testObj = CreateObject("xxxx") > > > > res = testObj.AMethodThatReturnsAListOfStrings() > > > > > > Thanks, > > > > Philippe > > -- > http://mail.python.org/mailman/listinfo/python-list > The "Leading Manufacturing Test Company of the Year 2005" http://www.dspace.de/goto?f_s_award From giles_brown at hotmail.com Thu Jul 7 10:14:03 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 7 Jul 2005 07:14:03 -0700 Subject: Windows Cmd.exe Window In-Reply-To: <42CD3124.2010202@syscononline.com> References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <42CD3124.2010202@syscononline.com> Message-ID: <1120745643.735880.59000@g44g2000cwa.googlegroups.com> Hi Larry, I mentioned how I am already using "sys.excepthook" in my initial posting. What I'm looking for is: 1) Is there any better way of solving the problem than setting sys.excepthook in sitecustomize.py? 2) Or is there a better way of detecting when I am running a .cmd based script than the method I proposed? Hope this clears up what I'm asking for. Thanks, Giles From skip at pobox.com Mon Jul 25 12:41:08 2005 From: skip at pobox.com (skip at pobox.com) Date: Mon, 25 Jul 2005 11:41:08 -0500 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kkf2vFv0mngU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> Message-ID: <17125.5668.976189.250466@montanaro.dyndns.org> Reinhold> Right, that was a concern of mine, too. Reinhold> "tobase"? Reinhold> "tostring"? Reinhold> "tobasestring"? If we're on a filesystem that understands unicode, would somepath.tostring() return a unicode object or a string object encoded with some to-be-determined encoding? Why not just add __str__ and __unicode__ methods to the class and let the user use str(somepath) or unicode(somepath) as needed? Or am I missing something fundamental about what the base() method is supposed to do? Skip From jdennett at acm.org Mon Jul 4 16:04:40 2005 From: jdennett at acm.org (James Dennett) Date: Mon, 04 Jul 2005 13:04:40 -0700 Subject: math.nroot [was Re: A brief question.] In-Reply-To: <42C8ADAF.1040708@REMOVEMEcyber.com.au> References: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> <8AXxe.3186$HV1.2814@fed1read07> <42C8ADAF.1040708@REMOVEMEcyber.com.au> Message-ID: <2Dgye.3434$HV1.2473@fed1read07> Steven D'Aprano wrote: > James Dennett wrote: > >> > Yes: 5^2 + -2^2 is 29, however you write it. >> >> *If* you take -2 as a number, but not if you take the number >> as 2 and the unary minus as an operator with lower precedence >> than exponentiation. > > > [snip] > >> Not in this respect. However, the question is whether that's >> a unary -, which binds lower than exponentiation in most systems, >> or part of the negative number minus 2. > > > In Python, all numbers are positive. -2 is a unary minus in front of 2. Indeed, as I hoped was clear from the rest of my post. When we're discussing what the rules of Python *should* be, however, it's necessary to step back and not assume that the rules of Python are "right", whatever we might mean by that. I was illustrating that the choice made by Python in this respect, i.e., of viewing "-2" as an expression where unary minus applies to the number 2, naturally leads to 5**2 + -2**2 being evaluated as 21 (because of the precedence of unary minus), whereas taking "-2" as a number would lead to the answer 29 (which is not what Python gives). That said, Python's choice is consistent with conventional mathematical notation, which is one reason not to lex -2 as a number in a language with an infix exponentiation operator. -- James From spam.csubich+block at block.subich.spam.com Sat Jul 30 22:27:20 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 30 Jul 2005 22:27:20 -0400 Subject: A replacement for lambda In-Reply-To: <1122713238.644818.171210@g49g2000cwa.googlegroups.com> References: <867jf9jmfw.fsf@bhuda.mired.org> <1122713238.644818.171210@g49g2000cwa.googlegroups.com> Message-ID: Paddy wrote: > Christopher Subich writes: > >>Basically, I'd rewrite the Python grammar such that: >>lambda_form ::= "<" expression "with" parameter_list ">" > > > I do prefer my parameter list to come before the expression. It would > remain consistant with simple function definitions. Stylistic choice; I can appreciate your sentiment, but remember that this isn't exactly a function definition. It's a form of 'delayed expression.' Also, <... with ...> is nearly identical (identical if you replace 'with' with 'for') to existing list and generator comprehensions, so we'd get to stretch that idiom. From benji at benjiyork.com Wed Jul 6 17:55:18 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 06 Jul 2005 17:55:18 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <42CC5346.8020009@benjiyork.com> Ron Adam wrote: > "if extraargs:" would evaluate to "if None:", which would evaluate to > "if:" which would give you an error. In what way is "if None:" equivalent to "if:"? -- Benji York From fabioz at esss.com.br Fri Jul 1 07:08:09 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Fri, 01 Jul 2005 08:08:09 -0300 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: Message-ID: <42C52419.3040801@esss.com.br> Ville Vainio wrote: >>>>>>"Timothy" == Delaney, Timothy (Tim) writes: >>>>>> >>>>>> > > Timothy> Absolutely. I've really tried to use Eclipse - it's the > Timothy> standard editor for my current project (Java - blegh!). I > Timothy> *hate* it. It's huge, bulky, slow ... I've gone back to > Timothy> my text editor. I'm a hell of a lot more > >Have you tried the recently released 3.1 version? It seems to be a tad >snappier than the old version. > > Timothy> The only IDE I've ever actually liked using was > Timothy> Metrowerks CodeWarrior (on MacOS classic). Simple, > Timothy> unobtrusive. Good project management, without trying to > Timothy> control every aspect of the development process. And > >The debugger in CodeWarrior is quite crappy IMHO. Unlike visual >studio, it doesn't show the return values of function calls. The >editor is also quite lacking, without the ability to create macros >etc. > >I agree about the project management part. Though I would still love >to use Eclipse instead, if it only was supported for my line of work >:-/. > > Timothy> it allowed me to use the entire screen for editing if I > Timothy> wished whilst still having everything readily available. > >Eclipse allows this as well. ctrl+m is maximize/unmaximize. > > > What line of work is not supported in eclipse? -- 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 From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 13:44:55 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 19:44:55 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> <3l1avfF10i4kgU1@individual.net> Message-ID: <3l1sknF10a9h2U1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: >> Mike Orr wrote: >>>- I saw in a thread that .name and .parent were removed. I use them >>>very frequently, along with .ext and .namebase. I don't want to call >>>methods for these. >> >> They are now named .basename and .directory. > > Reinhold, is ".parent" now ".directory"? Does that still make sense > when the Path contains a directory and not a file name? It seems to me > more general to have .parent in there where it makes sense for both cases. Hm. It was suggested on python-dev and among my first modifications. I didn't see objections till now, but as you're saying, parent is probably better. Reinhold From bvande at po-box.mcgill.ca Wed Jul 20 22:29:04 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 20 Jul 2005 22:29:04 -0400 Subject: interactive python session spool/save-log command? In-Reply-To: References: <1121907960.539100.146940@z14g2000cwz.googlegroups.com> Message-ID: <42DF0870.8010501@po-box.mcgill.ca> Robert Kern said unto the world upon 2005-07-20 21:15: > S. M. Tuttle wrote: > >>I'm going to be teaching an introductory course on Python >>in the Fall, so I am hurriedly trying to both learn >>Python and prepare the course during the next few weeks. >> >>I'm curious if there is a command that allows everything from >>that point on in a python interactive session to be >>saved/spooled/forked/logged into a text file of the user's choice. > > > IPython is an interactive interpreter that will log all input to a file. > > http://ipython.scipy.org/ > If your students are more likely to feel comfortable with an interface with things right there for the clicking, IDLE allows for the interactive prompt windows to be saved. IDLE's bundled with Python, so less to install to boot. Best, Brian vdB From wendell at meetro.com Thu Jul 14 00:10:33 2005 From: wendell at meetro.com (Wendell III) Date: Wed, 13 Jul 2005 23:10:33 -0500 Subject: Any Lua Coders About? Message-ID: <2005071323103316807%wendell@meetrocom> Hey, I'm looking for a few good Lua guys with some IM network experience. Anyone around fit that criteria? Bestest, -Wendell -- web: www.meetro.com phone: 312.275.7865 fax: 312.275.7865 icq: 12107743 skyp: wendell_iii msn: wadmoose at hotmail.com gg: 7116285 aim: wadm00se From duncan.booth at invalid.invalid Mon Jul 4 11:13:49 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Jul 2005 15:13:49 GMT Subject: OT: ^ in redirection (windows) References: <42c94383.510514691@news.oz.net> Message-ID: Bengt Richter wrote: > You'd think ^ would be mentioned in > http://www.microsoft.com/resources/documentation/windows/xp/all/pro > ddocs/en-us/redirection.mspx > but it seems not to be. > You mean you didn't think to look at http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx ? (or from Help & Support centre in Windows search on 'shell' to get to the same page). I think the point is that the ^ escape isn't part of the redirection syntax, it is only useful when you want to not redirect (or not have multiple commands on one line), so it isn't really obvious where it should be documented. That said, they have done a pretty good job of hiding it. From ypaami at gmail.com Sun Jul 3 03:19:45 2005 From: ypaami at gmail.com (Xinyue Ye) Date: Sun, 3 Jul 2005 03:19:45 -0400 Subject: a question Message-ID: when I type sys.ps2 after import sys, I got the message like: Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' why does it happen? From lashkariNO at SPAMworldviz.com Thu Jul 28 16:03:58 2005 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Thu, 28 Jul 2005 20:03:58 GMT Subject: Determine if object is a Bound or Unbound method In-Reply-To: References: Message-ID: Grazie! Paolino wrote: > Farshid Lashkari wrote: > >> Hi, >> >> I have an object and I want to check if it is a bound or unbound >> method, or neither. I tried using the types module, but it seems as >> though types.UnboundMethodType and types.MethodType are equal. How >> else can I determine this? BTW, I'm using Python 2.3 >> >> Thanks, >> >> Farshid > > Bound methods has an im_self attribute set to the instance binding them > > Ciao > > > ___________________________________ Yahoo! Messenger: chiamate gratuite > in tutto il mondo http://it.beta.messenger.yahoo.com From theller at python.net Fri Jul 1 05:32:33 2005 From: theller at python.net (Thomas Heller) Date: Fri, 01 Jul 2005 11:32:33 +0200 Subject: No subject References: Message-ID: "Adriaan Renting" writes: > I'm not a very experienced Python programmer yet, so I might be > mistaken, but there are a few things that would make me prefer C++ over > Python for large (over 500.000 LOC) projects. > - namespaces > - templates > - strong type checking > - data hiding > - more available libraries and more advanced developement tools. > > I'm talking about managing the code, not the programmers, the project or > schedules or what have you. Those are independent from the chosen > programming language. Just a single datapoint: Implementing a trivial COM object in Python requires, let's guess, about 10 or 20 lines of source code. When I do the same in MSVC6, the wizard creates 10 files, with nearly 400 lines of code. Sure, I didn't have to write these code lines, but I'm required to understand and manage them as well. Thomas From philippe at philippecmartin.com Thu Jul 21 08:36:37 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 21 Jul 2005 12:36:37 GMT Subject: returning list of strings from Python COM to Visual basic 6 References: Message-ID: I guess that also means (which makes sense) that the returned object has to be registered as a COM object. However, in my case, I just needed that object to pass it to yet another object, I did not need to use it from VB Regards, Philippe Philippe C. Martin wrote: > Thanks a bunch, > > I'll try this, This raises two questions: > 1) How do I declare the receiving VB variable ? > 2) Then, can I use the returned object as a COM object: call its public > methods (that would be hot)? > > > Dim newobj as ????? > newobj = acom.Get_Obj() > > newobj.A_Public() > > > Regards, > > Philippe > > > > > > On Thursday 21 July 2005 09:55 am, Stefan Schukat wrote: >> You have to wrap the python object with a COM object: >> >> def Get_Obj(self): >> return win32com.server.util.wrap(an_object) >> >> >> Stefan >> >> > -----Original Message----- >> > From: python-list-bounces+sschukat=dspace.de at python.org >> > [mailto:python-list-bounces+sschukat=dspace.de at python.org]On Behalf Of >> > Philippe C. Martin >> > Sent: Thursday, July 21, 2005 1:42 AM >> > To: python-list at python.org >> > Subject: Re: returning list of strings from Python COM to >> > Visual basic 6 >> > >> > >> > I can now pass and return quite a few types except object >> > instances: my >> > python code gets to the point where I do: >> > >> > >> > def Get_Obj(self): >> > ..... >> > return an_object >> > >> > My VB code looks like >> > >> > Dim obj as Variant >> > >> > obj = acom.Get_Obj() >> > >> > >> > I get an "unexpected Python error ..... Objects of type >> > 'instance' can not >> > be converted to a COM VARIANT" >> > >> > Is there a way out ? >> > >> > Thanks, >> > >> > Philippe >> > >> > Philippe C. Martin wrote: >> > > Hi, >> > > >> > > Is it possible ? >> > > >> > > ex: return ['1','2'] >> > > >> > > If so which type should I use in VB ? >> > > >> > > dim res as ??????? >> > > >> > > Set testObj = CreateObject("xxxx") >> > > >> > > res = testObj.AMethodThatReturnsAListOfStrings() >> > > >> > > >> > > Thanks, >> > > >> > > Philippe >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> >> The "Leading Manufacturing Test Company of the Year 2005" >> http://www.dspace.de/goto?f_s_award > From martin at v.loewis.de Thu Jul 14 17:47:37 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 14 Jul 2005 23:47:37 +0200 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? In-Reply-To: <11ddckucctde603@corp.supernews.com> References: <11ddckucctde603@corp.supernews.com> Message-ID: <42d6dd7a$0$11014$9b622d9e@news.freenet.de> Grant Edwards wrote: > 1/0 is defined by the standard as +Inf and 0/0 is NaN. I wonder why Tim hasn't protested here: I thought this was *not* the case. I thought IEEE 754 defined +Inf and NaN as only a possible outcome of these operations with other possible outcomes being exceptions... In that case, Python would comply to IEEE 754 in this respect (although in a different way than the C implementation on the same system). Regards, Martin From philippe at philippecmartin.com Wed Jul 6 11:29:31 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 06 Jul 2005 15:29:31 GMT Subject: adding a character to the last string element of a list References: <_WEye.1218$Ae.676@newssvr12.news.prodigy.com> Message-ID: Thanks, Philippe Peter Hansen wrote: > Philippe C. Martin wrote: >> I guess my slicing was wrong, l[-1] worked > > Note that that's _not_ a slice, however, but a reference to the last > element in the list. > > You'd have to subclass list to be able to do something with > "reference-slices". Probably returning a special object from > __getslice__ which itself has references back to the original list and > implements any changes back in the original instead of in itself. I > haven't tried to imagine if this is even feasible. > > Anything "indexing" with : in it is a slice, so a copy, while anything > with only a single index as you have in l[-1] is just a reference to one > element in the list. > > -Peter From kay.schluehr at gmx.net Sat Jul 30 12:48:27 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Jul 2005 09:48:27 -0700 Subject: Comparison of functions In-Reply-To: References: Message-ID: <1122742107.730908.107690@g44g2000cwa.googlegroups.com> Some indications: >>> for i in range(5): ... x = lambda x:x ... y = lambda y:y ... print x,y,x at 0x00EE83F0> at 0x00EE8FB0> True True at 0x00EE8AB0> at 0x00EE83F0> False False at 0x00EE8FB0> at 0x00EE8AB0> False False at 0x00EE83F0> at 0x00EE8FB0> True True at 0x00EE8AB0> at 0x00EE83F0> False False Regards, Kay From pinard at iro.umontreal.ca Wed Jul 6 10:32:12 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 6 Jul 2005 10:32:12 -0400 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120635034.080123.218060@g47g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> Message-ID: <20050706143212.GD28691@alcyon.progiciels-bpi.ca> [Raymond Hettinger] > seberino at spawar.navy.mil wrote: > > > It got me curious if Lisp is inherently faster to develop complex > > apps in. > With Lisp or Forth, a master programmer has unlimited power and > expressiveness. With Python, even a regular guy can reach for the > stars. A few years ago, I much hesitated between Scheme and Python as my next day-to-day programming language. My feeling at the time was that Scheme is a very fast language to write into, and in which one can implement new concepts cleanly and compactly. Maybe Python is a bit slower to write, but this is compensated by the fact Python is more legible when it comes to later maintenance, or when many people have to share work on a big set of sources. There is some heaviness and complexity in Python internals, Scheme are purer and simpler by comparison. On its bright side, Python has a nice and comprehensive library, and an interesting community of users. These probably make most of the difference. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From peter at engcorp.com Thu Jul 14 19:28:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 19:28:54 -0400 Subject: readlines() doesn't read entire file In-Reply-To: References: Message-ID: Jeremy wrote: > I have a most aggravating problem. I don't understand what is causing > readlines() not to read all the lines in the file. I have the following > syntax: > ... > self.xsdir = file(Datapath, 'r') # File object > > I can see all the lines in the list self.lines, but they are not all the > lines in the file. When I look at the file in Vim, I can see all the > lines, but Python cannot. Can someone help me with this one? What platform? What version of Python? You're opening the file in "text" mode. If you are on Windows and the file actually contains a ^Z (byte 26) it is treated as EOF. Is that the problem? If not, have you tried cutting parts out of the file, to produce the smallest file that still shows the problem? At that point you will likely resolve the issue on your own. Also, does the same thing happen if you use the interactive interpreter to read the file "manually"? These are all basic troubleshooting techniques you can use at any time on any problem... -Peter From cam.ac.uk at mh391.invalid Wed Jul 27 14:40:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 27 Jul 2005 19:40:42 +0100 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: Michael Hoffman wrote: > David Isaac wrote: > >> Newbie question: >> >> I have been generally open to the proposal that list comprehensions >> should replace 'map', but I ran into a need for something like >> map(None,x,y) >> when len(x)>len(y). I cannot it seems use 'zip' because I'll lose >> info from x. How do I do this as a list comprehension? (Or, >> more generally, what is the best way to do this without 'map'?) > > > It ain't broke so I'd stick with what you're doing. Even if map() is > removed as a builtin, it will surely stick around in a module. Addendum: I know this doesn't answer your question, so if you were asking out of purely academic interest, then someone else will probably post another answer. -- Michael Hoffman From hugh.macdonald at gmail.com Mon Jul 11 13:07:49 2005 From: hugh.macdonald at gmail.com (Hugh Macdonald) Date: 11 Jul 2005 10:07:49 -0700 Subject: C API : Creating a Py_Method object from a C function. Message-ID: <1121101669.752932.217380@g14g2000cwa.googlegroups.com> I've got a pure python module that parses a certain type of file. It has a load() function that allows a callback function to be passed for getting progress information. In straight python, this works fine. However, I'm now trying to use this from a C++ program. The current flow that I'm trying to get is as follows: C++ calls python interface function, passing a C++ function pointer Python interface function stores C++ function pointer Python interface function generates new Py_Object method pointer pointing to a different C python function. (This different function calls the stored C++ function pointer) Python interface function calls python function Python function calls the python method pointer it was passed C python function then calls the stored C++ function pointer. The problem in this workflow is taking the C python function that I've defined (using the standard "static PyObject *someFunction(PyObject *self, PyObject *args)" method) and converting this into a Py_Object. Any ideas? Py_Method doesn't seem to allow you to generate a new one with your own pointers inside... and I can't see anything else in the docs that might allow me to do this... Thanks for any advice! -- Hugh Macdonald From tchurm at gmail.com Tue Jul 12 04:11:44 2005 From: tchurm at gmail.com (tchurm at gmail.com) Date: 12 Jul 2005 01:11:44 -0700 Subject: Search & Replace with RegEx Message-ID: <1121155904.551248.102700@o13g2000cwo.googlegroups.com> Hi Pythonistas, Here's my problem: I'm using a version of MOOX Firefox (http://moox.ws/tech/mozilla/) that's been modified to run completely from a USB Stick. It works fine, except when I install or uninstall an extension, in which case I then have to physically edit the compreg.dat file in my profile directory, replacing all instances of Absolute Path links to relative ones. (And, yes, I have filed a Bugzilla report.) For example, after installing a new extension, I change in compreg.dat lines such as: abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{0538E3E3-7E9B-4d49-8831-A227C80A7AD3}\components\nsForecastfox.js,1111185900000 abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{c4dc572a-3295-40eb-b30f-b54aa4cdc4b7}\components\wml-service.js,1114705020000 to: rel:nsForecastfox.js,1111185900000 rel:wml-service.js,1114705020000 I started a Python script that searches compreg.dat and finds all the lines that I need to edit. I just need some help using RegEx to search and replace these lines (as in the examples above), so that I no longer need to edit compreg.dat manually. Here's the script that I started: ################################################ import os import re import fileinput theRegEx = '.*abs:.*\.*.js.*' p = re.compile(theRegEx, re.IGNORECASE) fileToSearch = 'compreg.dat' print "File to perfrom search-and-replace on: " + fileToSearch print "Using Regex: " + theRegEx print "" if os.path.isfile( fileToSearch ): tempFile = open( fileToSearch, 'r' ) for line in fileinput.input( fileToSearch ): if (p.match(line)!=None): print line tempFile.close() raw_input( '\n\nPress Enter to exit...' ) ################################################ I'd be very glad to get a helping hand here ;) Thanks, Tom From duncan.booth at invalid.invalid Tue Jul 19 08:05:28 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2005 12:05:28 GMT Subject: Finding # prefixing numbers References: <1121772902.193765.258700@g49g2000cwa.googlegroups.com> Message-ID: peterbe at gmail.com wrote: > In a text that contains references to numbers like this: #583 I want > to find them with a regular expression but I'm having problems with > the hash. Hopefully this code explains where I'm stuck: > >>>> import re >>>> re.compile(r'\b(\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > ['123', '234', '456'] >>>> re.compile(r'\b(X\d\d\d)\b').findall('X123 x (X234) or:X456 X6789') > ['X123', 'X234', 'X456'] >>>> re.compile(r'\b(#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > [] >>>> re.compile(r'\b(\#\d\d\d)\b').findall('#123 x (#234) or:#456 >>>> #6789') > [] > > As you can guess, I'm trying to find a hash followed by 3 digits word > bounded. As in the example above, it wouldn't have been a problem if > the prefix was an 'X' but that's not the case here. > > >From the re documentation: > \b > Matches the empty string, but only at the beginning or end of a word. > A word is defined as a sequence of alphanumeric or underscore > characters, so the end of a word is indicated by whitespace or a > non-alphanumeric, non-underscore character. Note that \b is defined as > the boundary between \w and \ W, so the precise set of characters > deemed to be alphanumeric depends on the values of the UNICODE and > LOCALE flags. Inside a character range, \b represents the backspace > character, for compatibility with Python's string literals. # is not a letter or digit, so \b# will match only if the # is directly preceded by a letter or digit which isn't the case in any of your examples. Use \B (which is the opposite of \b) instead: >>> re.compile(r'\B(#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') ['#123', '#234', '#456'] From M.Waack at gmx.de Tue Jul 5 02:39:20 2005 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 05 Jul 2005 06:39:20 GMT Subject: Connecting to Firebird database using Kinterbasdb+Python References: Message-ID: Maurice LING wrote: > What I am trying to do is "port" a workable program from my own machine > (Mac OSX) to a larger machine (Linux). So, the DB and the program are > also on the same Linux machine. > > On the Linux machine, I cannot use localhost, so I set host parameter in > kinterbasdb.connect() method to None, which is the default kinterbasdb > uses. On Linux machine, I get the error as posted. On my Mac OSX > machine, initiating host parameter to 'localhost' or None has no > difference, it works. How do you connect to the Linux-DB using tools like isql? Check you firebird config (most likely in /etc/firebird2/firebird.conf) for the parameters "RemoteServicePort" and "RemoteBindAddress". And at least try "netstat -alp | grep fbserv" (as root) to check if the firebird is running properly. If you're running the classic server you can simply follow Grig's advice and connect "directly" to the db files. Mathias From tjreedy at udel.edu Sun Jul 10 16:14:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jul 2005 16:14:44 -0400 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net><11cokv26rabdndf@corp.supernews.com><42CCE6DA.5020402@REMOVEMEcyber.com.au><42CE0E38.60305@REMOVEMEcyber.com.au><1120825627.498017.19370@g47g2000cwa.googlegroups.com><42d0529a$1@nntp0.pdx.net> Message-ID: "Ron Adam" wrote in message news:OI_ze.189063$IO.87173 at tornado.tampabay.rr.com... > To avoid that you either need to define the flag string as a global name > or use it strictly in the local scope it's defined in. Python will also > sometimes reuse strings as an optimization instead of creating a second > string if they are equal. Something else to be aware of. I believe CPython's string equality function first checks the two strings for identity. So one gets most of the benefit of 'is' testing anyway. (An I presume it next check for length equality.) tjr From exarkun at divmod.com Wed Jul 6 10:00:02 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 6 Jul 2005 10:00:02 -0400 Subject: Use cases for del In-Reply-To: Message-ID: <20050706140002.26278.269554290.divmod.quotient.6538@ohm> On Wed, 06 Jul 2005 09:45:56 -0400, Peter Hansen wrote: >Tom Anderson wrote: >> How about just getting rid of del? Removal from collections could be >> done with a method call, and i'm not convinced that deleting variables >> is something we really need to be able to do (most other languages >> manage without it). > >Arguing the case for del: how would I, in doing automated testing, >ensure that I've returned everything to a "clean" starting point in all >cases if I can't delete variables? Sometimes a global is the simplest >way to do something... how do I delete a global if not with "del"? > Unless you are actually relying on the global name not being defined, "someGlobal = None" would seem to do just fine. Relying on the global name not being defined seems like an edge case. Jp From sun.aries at gmail.com Thu Jul 14 03:17:49 2005 From: sun.aries at gmail.com (Aries Sun) Date: 14 Jul 2005 00:17:49 -0700 Subject: Consecutive Character Sequences References: <1121318559.d582247e6e25443e247191d29f60b3b0@teranews> Message-ID: <1121325469.494500.291730@z14g2000cwz.googlegroups.com> I have tested George's solutions, it seems not complete. When pass (s, 3) to the function hasConsequent(), it returns the wrong result. The following is my approach. The performence may be not so good. There must be better ones. >>> from re import findall >>> def hasConsequent(aString, minConsequent): for ch in aString: result = findall(ch*minConsequent, aString) if len(result) >= 1: return True return False >>> hasConsequent(s, 2) True >>> hasConsequent(s, 3) True >>> hasConsequent(s, 4) False Aries Sun From sjmachin at lexicon.net Thu Jul 7 03:38:07 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 07 Jul 2005 17:38:07 +1000 Subject: Do a "Python beginners e-mail list" exist? In-Reply-To: References: Message-ID: <42CCDBDF.1060904@lexicon.net> Alessandro Brollo wrote: > Far from a professional programmer, I'm simply a > newbie Python user. Two basic questions: > > 1. I don't want to post banal questions about Python > to main Python list. Does a "banal Python questions > list" or a "Python beginners list" exist? http://mail.python.org/mailman/listinfo/tutor > > 2. There is somewhere a very patient fellow willing to > be my free "python tutor" by personal e-mailing > outside the mail list? See above, where the possibility of one-on-one tutorials is canvassed. > The ideal candidate would be > someone, sharing with me some other fields of interest > (I'm a middle-aged Italian pathologist, with some > dBase III and dBase IV past programming experience, > and I like nature and mainly horses). There are other newsgroups that cater for your interests e.g. rec.equestrian -- check out Google groups. From thomasbartkus at comcast.net Fri Jul 8 16:03:45 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 8 Jul 2005 15:03:45 -0500 Subject: Legacy data parsing References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: "gov" wrote in message news:1120847474.604271.196220 at g49g2000cwa.googlegroups.com... > Hi, > > I've just started to learn programming and was told this was a good > place to ask questions :) > > Where I work, we receive large quantities of data which is currently > all printed on large, obsolete, dot matrix printers. This is a problem > because the replacement parts will not be available for much longer. > > So I'm trying to create a program which will capture the fixed width > text file data and convert as well as sort the data (there are several > different report types) into a different format which would allow it to > be printed normally, or viewed on a computer. Text file data has no concept of "fixed width". Somewhere in your system, text file data is being thrown at your dot matrix printer. It would seem a trivial exercise to simply plug in a newer and probably inexpensive replacement printer. What am I missing here? > I've been reading up on the Regular Expression module and ways in which > to manipulate strings however it has been difficult to think of a way > in which to extract an address. > > Here's an example of the raw text that I have to work with: > How are you intercepting this text data? Are you replacing your old printer with a Python speaking computer? How will you deliver this data to your Python program? > (the # = any number, and the X's are just regular text) > I would like to extract the address information, but the two different > text objects on the right hand side are difficult to remove. I think > it would be easier if I could just extract a fixed square of > information, but I don't have a clue as to how to go about it. Assuming you know how your Python code will "see" this data - You would need no more than standard Python string handling to perform these tasks. There is no concept of a "fixed square" here. This is a continuous stream of (probably ascii) characters. If you could pick the data up from a file, you would use readline() to build a list of individual lines. If you were picking the data from a serial port, you might assemble the whole thing into one big string and use split(/n) to build your list of lines. Once you had a full record (print page?) as a list of individual lines you could identify each line by it's position in the list *if*, as is likely, each item arrives at the same line position. If not, your code can read each line and test. For example: The line "#######" Seems to immediately precede several address lines " MRS XXX X XXXXXXX" " #####" " ####: " ###-###-#" If you can rely on this you would know that the line "#######" is immediately followed by several lines of an address - up until the empty line. And you can look at each of those address lines and use trim() to remove leading and trailing blanks. Similarly, the line that begins " LANG:" would seem to immediately precede another address. None of this is particularly difficult with standard Python. But then - if we are merely replacing an old printer - We are already working way too hard! Thomas Bartkus From rorra at rorra.com.ar Fri Jul 1 18:17:48 2005 From: rorra at rorra.com.ar (Rodrigo Dominguez) Date: Fri, 1 Jul 2005 19:17:48 -0300 Subject: web programming with mod_python Message-ID: <5xzm6obuegpo$.1u6l6qmydgi2v$.dlg@40tude.net> Actually I'm using php4 for web programming, but I don't like it, I know that manny hosting servers supports mod_python, so I want to start programming in python for web applications with mod_python. My question is: is there some kind of framework that works with mod_python? I just want some classes to manage some kind of themplates (for MVC), sessions, and if possible data persistence. I don't have root on these servers and the admins won't install any application if I ask them, I need to use just plain python files. Thank you -- Rodrigo Dom?nguez Consultor Av. Directorio 183 1? Piso Tel: 4921-1648 / 4926-1067 Cel: 15-5695-6027 rorra at rorra.com.ar www.rorra.com.ar From hancock at anansispaceworks.com Thu Jul 21 22:39:23 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 21 Jul 2005 21:39:23 -0500 Subject: Generating images with text in them In-Reply-To: References: Message-ID: <200507212139.23173.hancock@anansispaceworks.com> On Thursday 21 July 2005 11:29 am, phil hunt wrote: > On Thu, 21 Jul 2005 02:44:03 -0500, Terry Hancock wrote: > >On Wednesday 20 July 2005 11:59 pm, phil hunt wrote: > >> I am trying to generate some images (gifs or pngs) with text in > >> them. I can use the Python Imaging Library, but it only has access > >> to the default, rather crappy, font. > > > >On the fly, or just during development? > > Just during development. There are several free vector graphics programs. It would be fairly trivial to hack a Skencil file to change text in it. Could do the same with an SVG file from Inkscape. This would be a way to generate your graphics. I wrote a build utility for image resources based on Skencil which creates images as part of your build process. See: http://buildimage.narya.net That might be useful to you. > I'm runnnig a desktop environment. For example Tkinter works fine. Then Skencil is no problem if you want to use that. > >While bitmap font files are not copyrightable, there are license issues > >with most of the "nicer" fonts you are probably talking about. > > Oh? I can understand them being copyrighted; but if they are not > copywritable, what licnese issues are there? In any case, there > presumably are not license issues with the fonts that come with a > standard GNU/Linux distribution such as SuSE 9.1, which is what I am > using. *Bitmap* fonts are not copyrightable.* TrueType and Type 1 fonts are outline fonts and are copyrightable just like programs (indeed they technically are a kind of limited-domain program due to the coding of "hints"). I see that the new ability to use True Type fonts solved your problem, so I'll just leave it at that. Glad you found a solution. Cheers, Terry *In the US anyway -- they are regarded as too simple. This might not be true in other countries, it's clearly a judgement call. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From falcon3166 at hotmail.com Fri Jul 1 14:33:42 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 1 Jul 2005 12:33:42 -0600 Subject: I have a question. References: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Message-ID: <42c58c90$0$7001$b9fe7a78@news.usenetrevolution.com> Thanks all. I needed to ask because I'm writing a couple of programs which require the computer to choose numbers at random thanks. Nathan Pinno "Jeremy Jones" wrote in message news:mailman.1131.1120146826.10512.python-list at python.org... > Nathan Pinno wrote: > > > Hi all, > > > > Does Python have a random function? If so, can you show me an example > >using it? > > > > Thanks, > > Nathan Pinno > > http://www.npinnowebsite.ca/ > > > > > > > > > > > Take your pick: > > In [5]: import random > > In [6]: random.choice(range(10)) > Out[6]: 2 > > In [7]: random.choice(range(10)) > Out[7]: 7 > > In [8]: random.choice(range(10)) > Out[8]: 8 > > In [9]: random.choice(range(10)) > Out[9]: 8 > > > In [14]: random.random() > Out[14]: 0.56386154889489271 > > In [15]: random.random() > Out[15]: 0.47322827346926843 > > In [16]: random.random() > Out[16]: 0.39921336622176518 > > In [17]: random.random() > Out[17]: 0.65521407248459007 > > In [18]: random.random() > Out[18]: 0.74525381787627598 > In [20]: r = range(10) > > In [21]: random.shuffle(r) > > In [22]: r > Out[22]: [6, 4, 9, 7, 2, 0, 8, 3, 5, 1] > > > Jeremy Jones -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From fuzzyman at gmail.com Sat Jul 16 05:10:57 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Jul 2005 02:10:57 -0700 Subject: Snakespell In-Reply-To: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> References: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> Message-ID: <1121505056.996504.153010@z14g2000cwz.googlegroups.com> peterbe at gmail.com wrote: > I used to use Snakespell from scriptfoundry to do spellchecking on my > website (www.peterbe.com/search?q=pyton) but now that I've moved server > and wiped the old machine I forgot to take with me the Snakespell code. > > www.scriptfoundry.com where it used to live seems to have expired. > > Does anybody know where I can get hold of this? (or even send a tgz to > me) PyEnchant is maintained and easy to use.... jsut anotehr suggestion. Regards, Fuzzyman http://www.voidspace.org.uk/python From brian at mines.colorado.edu Thu Jul 28 21:30:09 2005 From: brian at mines.colorado.edu (brian at mines.colorado.edu) Date: Fri, 29 Jul 2005 07:00:09 +0530 Subject: Hello Message-ID: <200507290204.j6T24ml30926@cse.iitkgp.ernet.in> The message cannot be represented in 7-bit ASCII encoding and has been sent as a binary attachment. -------------- next part -------------- ------------------ Virus Warning Message (on cse.iitkgp.ernet.in) body.scr is removed from here because it contains a virus. --------------------------------------------------------- From benji at benjiyork.com Mon Jul 25 07:36:20 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 25 Jul 2005 07:36:20 -0400 Subject: Fire event when variable is Set/Get In-Reply-To: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> References: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> Message-ID: <42E4CEB4.4030407@benjiyork.com> tharaka wrote: > You are in luck because Python has "Properties" just like .NET. > class C(object): > def getx(self): return self.__x > def setx(self, value): self.__x = value > def delx(self): del self.__x > x = property(getx, setx, delx, "I'm the 'x' property.") Just for those that might have tastes like mine; here's the pattern I've been using for this (in 2.4, obviously): class C(object): @apply def x(): doc = "I'm the 'x' property." def fget(self): return self.__x def fset(self, value): self.__x = value def fdel(self): del self.__x return property(**locals()) You can remove any of fget, fset, fdel, or doc without changing any other lines, and there are no "extra" entries in the class's name space. -- season-to-taste-ly yours, Benji York From walter at livinglogic.de Tue Jul 5 06:25:28 2005 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 05 Jul 2005 12:25:28 +0200 Subject: what is __init__.py used for? In-Reply-To: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> References: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> Message-ID: <42CA6018.5050901@livinglogic.de> zelzel.zsu at gmail.com wrote: > I am a new learner of Python Programming Language. > Now. I am reading a book. > In the section relating to module, I see an example. > the directory tree looks like below: > root\ > system1\ > __init__.py > utilities.py > main.py > other.py > system2\ > __init__.py > utilities.py > main.py > other.py > system3\ # Here or elsewhere > __init__.py # Your new code here > myfile.py > > question > ========== > I was wonderring ... what is the __init__.py used for ? > This question may seems to be stupid for an expert. > But, if you can give the answer, it will be helpful for me. If the root directory is on the Python search path, you can do "import system2.other" or "from system2 import other", to import the other.py module. But you can also do "import system2". This means that the source code for the system2 module has to live somewhere. __init.py inside the directory with the same name is this "somewhere". Without this __init__.py inside the system2 directoy you couldn't import other.py because Python doesn't know where the source code for system2 lives and refuses to treat system2 as a package. Hope that helps, Walter D?rwald From kay.schluehr at gmx.net Mon Jul 18 01:31:04 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 17 Jul 2005 22:31:04 -0700 Subject: Ordering Products In-Reply-To: References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: <1121664664.911474.287840@o13g2000cwo.googlegroups.com> Ron Adam wrote: > Kay Schluehr wrote: > > Here might be an interesting puzzle for people who like sorting > > algorithms ( and no I'm not a student anymore and the problem is not a > > students 'homework' but a particular question associated with a > > computer algebra system in Python I'm currently developing in my > > sparetime ). > > > > >>>>x = 7*a*b*a*9 > >>>>x.factors.sort() > >>>>x > > > > a*a*b*7*9 > > > > -> (a**2)*b*63 > > > > Now lets drop the assumption that a and b commute. More general: let be > > M a set of expressions and X a subset of M where each element of X > > commutes with each element of M: how can a product with factors in M be > > evaluated/simplified under the condition of additional information X? > > > > It would be interesting to examine some sorting algorithms on factor > > lists with constrained item transpositions. Any suggestions? > > > > Regards, > > Kay > > Looks interesting Kay. I think so too :) And grouping by sorting may be interesting also for people who are not dealing with algebraic structures. > I think while the built in sort works as a convenience, you will need to > write your own more specialized methods, both an ordering (parser-sort), > and simplify method, and call them alternately until no further changes > are made. (You might be able to combine them in the sort process as an > optimization.) > > A constrained sort would be a combination of splitting (parsing) the > list into sortable sub lists and sorting each sub list, possibly in a > different manner, then reassembling it back. And doing that possibly > recursively till no further improvements are made or can be made. I think a comparison function which is passed into Pythons builtin sort() should be sufficient to solve the problem. I guess the comparison defines a total order on the set of elements defined by the list to sort. > On a more general note, I think a constrained sort algorithm is a good > idea and may have more general uses as well. > > Something I was thinking of is a sort where instead of giving a > function, you give it a sort key list. Then you can possibly sort > anything in any arbitrary order depending on the key list. > > sort(alist, [0,1,2,3,4,5,6,7,8,9]) # Sort numbers forward > sort(alist, [9,8,7,6,5,4,3,2,1,0]) # Reverse sort > sort(alist, [1,3,5,7,9,0,2,4,6,8]) # Odd-Even sort > sort(alist, [int,str,float]) # sort types Seems like you want to establish a total order of elements statically. Don't believe that this is necessary. > These are just suggestions, I haven't worked out the details. It could > probably be done currently with pythons built in sort by writing a > custom compare function that takes a key list. Exactly. > How fine grained the key > list is is also something that would need to be worked out. Could it > handle words and whole numbers instead of letters and digits? How does > one specify which? What about complex objects? In order to handle complex objects one needs more algebra ;) Since the class M only provides one operation I made the problem as simple as possible ( complex expressions do not exist in M because __mul__ is associative - this is already a reduction rule ). Kay From tjreedy at udel.edu Mon Jul 4 15:11:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jul 2005 15:11:38 -0400 Subject: Accepted Summer of Code proposals References: Message-ID: "A.M. Kuchling" wrote in message news:CIedncqF78Ft21TfRVn-2Q at speakeasy.net... > On Fri, 1 Jul 2005 14:22:51 -0400, > Terry Reedy wrote: >> Thanks for posting this and thanks for coordinating the PSF effort. > > I did little beyond writing up that wiki page. David Ascher > has been the primary coordinator for the PSF. Then I applaud him and the mentor volunteers and whoever else. 18 x $5000 = $90,000 invested in Python (with $9,000 to PSF). This is no small thing. While I fully expect Google to get their money's worth in publicity, payback satisfaction, and prospective-employeee testing, I also expect to benefit pretty directly from at least a few of the projects. Terry J. Reedy From paddy3118 at netscape.net Sun Jul 31 03:29:36 2005 From: paddy3118 at netscape.net (Paddy) Date: 31 Jul 2005 00:29:36 -0700 Subject: Thaughts from an (almost) Lurker. Message-ID: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Sometimes when reading c.l.p. I mentally stand off from what I have been reading and get an odd feeling that 'WE ARE BEING TESTED'. That someone else is purposefully posting a near repetitive post, or obvious flame bait etc - not for the usual reasons, but to track the dynamics af the replies. Rather like dropping a stone in the river and watching pythonistas return c.l.p. to its normal, helpful, and polite norm. Fascinating. I only hope that if thats the case, then they should post their findings here. - Paddy. From ramen at lackingtalent.com Tue Jul 19 13:56:00 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 19 Jul 2005 10:56:00 -0700 Subject: Jython Released In-Reply-To: References: <6NWdna8jsbEov0DfRVn-vA@comcast.com> Message-ID: Dave Benjamin wrote: > Ramza Brown wrote: > >> This is an update from Brian Zimmer of the Jython group, new release: > > Great news! > >> - new installer > > How do I use it? I figured it out. You might want to document this somewhere. ;) java -cp jython_Release_2_2alpha1.jar org.python.util.install.Installation Dave From dalke at dalkescientific.com Mon Jul 25 13:37:52 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 25 Jul 2005 17:37:52 GMT Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> Message-ID: > Reinhold Birkenfeld wrote: >> Current change: >> >> * Add base() method for converting to str/unicode. Now that [:] slicing works, and returns a string, another way to convert from path.Path to str/unicode is path[:] Andrew dalke at dalkescientific.com From lambacck at computer.org Wed Jul 13 15:22:35 2005 From: lambacck at computer.org (Chris Lambacher) Date: Wed, 13 Jul 2005 15:22:35 -0400 Subject: DNS access In-Reply-To: <1121265881.737855.284030@g44g2000cwa.googlegroups.com> References: <1121265881.737855.284030@g44g2000cwa.googlegroups.com> Message-ID: <20050713192235.GC32027@computer.org> reverse dns lookup is not really special compared to a regular dns lookup. you just need to look up a special name: http://www.dnsstuff.com/info/revdns.htm to format the ip address properly use something like: def rev_dns_string(ip_str): nums = ip_str.split('.').reverse() nums.extend(('in-addr', 'arpa')) return '.'.join(nums) -Chris On Wed, Jul 13, 2005 at 07:44:41AM -0700, laksh wrote: > im looking for some advice regarding DNS lookup using python > > is it possible to give parameters like the IP of a DNS server and the > DNS query to a python program and obtain the response from the DNS > server ? > > please reply if u hav some idea or interest > > laksh > > -- > http://mail.python.org/mailman/listinfo/python-list From fperez.net at gmail.com Tue Jul 19 14:06:48 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 19 Jul 2005 12:06:48 -0600 Subject: goto References: Message-ID: Steven Bethard wrote: > Fernando Perez wrote: >> Steven Bethard wrote: >> >>>Download the goto module: >>> http://www.entrian.com/goto/ >>>And you can use goto to your heart's content. And to the horror of all >>>your friends/coworkers. ;) >> >> That is actually a _really_ cool piece of code, in terms of showing off the >> kind of things which are possible in python if you're willing to be a little >> sneaky. > > Yeah, it's pretty slick. I think most people who see the link don't > realize that it's actually *working code* for gotos in Python. For a second I didn't think it was, but the page looked too serious to be just a mockup (regardless of the April's fool warning at the top). So I actually donwloaded the code to see how he did it, because it wasn't quite obvious to me after the standard 3 seconds of thought. It was quite fun the read how he got it to work. Cheers, f From Florian.Lindner at xgm.de Sat Jul 9 06:20:33 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sat, 09 Jul 2005 12:20:33 +0200 Subject: directory traverser Message-ID: Hello, IIRC there is a directory traverser for walking recursively through subdirectories in the standard library. But I can't remember the name and was unable to find in the docs. Anyone can point me to it? Thanks, Florian From peter at engcorp.com Wed Jul 13 10:19:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 10:19:18 -0400 Subject: reg php equivalent move_uploaded file function in python In-Reply-To: References: Message-ID: praba kar wrote: > Is there any php equivalent > move_uploaded_file($source_path, "$upload_dir/$name"); > function in python to > upload a file to server? As this is a Python forum, most will not know PHP. Perhaps describing what you want in plain English would be more effective in getting useful answers. (For example, what kind of server are you talking about?) -Peter From godoy at ieee.org Fri Jul 29 13:19:05 2005 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 29 Jul 2005 14:19:05 -0300 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Michael Hoffman wrote: > He spends so much space on "Create Consistent Command-Line Interfaces," > a section that, in Python, could be replaced with a simple "Use optparse." In Perl there's also the equivalent of optparse, but where does it guarantee that you'll use consistent name options and design a good interface? I think he's point is much broader than parsing input from the command line. -- Jorge Godoy From dalke at dalkescientific.com Sun Jul 31 03:28:13 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 31 Jul 2005 07:28:13 GMT Subject: PEP on path module for standard library References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> <3l1avfF10i4kgU1@individual.net> Message-ID: Peter Hansen wrote: > A scattered assortment of module-level global function names, and > builtins such as open(), make it extraordinarily difficult to do > effective and efficient automated testing with "mock" objects. I have been able to do this by inserting my own module-scope function that intercepts the lookup before it gets to builtins. A problem though is that a future (Python 3K?) Python may not allow that. For example, module.open = mock_open try: ... finally: module.open = open By looking at the call stack it is possible to replace the built-in open to have new behavior only when called from specific modules or functions, but that gets to be rather hairy. > Object-oriented solutions like Path make it near trivial to substitute a > mock or other specialized object which (duck typing) acts like a Path > except perhaps for actually writing the file to disk, or whatever other > difference you like. By analogy to the other builtins, another solution is to have a protocol by which open() dispatches to an instance defined method. > So, for the PEP, another justification for Path is that its use can > encourage better use of automated testing techniques and thereby improve > the quality of Python software, including in the standard library. But then what does the constructor for the file object take? I've also heard mention that a future (Py3K era) 'open' may allow URLs and not just a path string. Andrew dalke at dalkescientific.com From aahz at pythoncraft.com Mon Jul 4 14:56:51 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jul 2005 11:56:51 -0700 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Message-ID: In article , Peter Hansen wrote: > >After 25 years doing this, I've become something of a Luddite as far as >fancy IDEs and non-standard features go... and a huge believer in strict >decoupling between my tools, to the point of ignoring things that bundle >them together in ways that are, in my opinion, too tight. Sorry! :-) +1 QOTW -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From max at alcyone.com Thu Jul 7 23:48:05 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 07 Jul 2005 20:48:05 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <3j40aoFocvh4U1@individual.net> <6oadncSMIs0fclDfRVn-jg@speakeasy.net> Message-ID: Ron Adam wrote: > Well in my previous explanation I *mean* it to be empty parenthesis. > > Does that help? Maybe it might be beneficial to learn a little more of the language before proposing such wide-reaching (and un-Pythonic) reforms? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis But since when can wounded eyes see / If we weren't who we were -- Joi From exarkun at divmod.com Sun Jul 3 18:06:25 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 3 Jul 2005 18:06:25 -0400 Subject: looping over a big file In-Reply-To: <11cgnhp3j4th442@corp.supernews.com> Message-ID: <20050703220625.26278.539475330.divmod.quotient.5039@ohm> On Sun, 3 Jul 2005 23:52:12 +0200, martian wrote: >Hi, > >I've a couple of questions regarding the processing of a big text file >(16MB). > >1) how does python handle: > >> for line in big_file: > >is big_file all read into memory or one line is read at a time or a buffer >is used or ...? It uses an internal buffer to reach a happy medium between performance and memory usage. > >2) is it possible to advance lines within the loop? The following doesn't >work: > >> for line in big_file: > line_after = big_file.readline() > Yes, but you need to do it like this: fileIter = iter(big_file) for line in fileIter: line_after = fileIter.next() Don't mix iterating with any other file methods, since it will confuse the buffering scheme. Jp From mage at mage.hu Mon Jul 11 10:27:30 2005 From: mage at mage.hu (Mage) Date: Mon, 11 Jul 2005 16:27:30 +0200 Subject: cursor positioning In-Reply-To: <42D27E2E.3040904@syscononline.com> References: <42D27E2E.3040904@syscononline.com> Message-ID: <42D281D2.9060302@mage.hu> Larry Bates wrote: >While not "curses" based this class will update screen as you >want. You could use it as a basis upon which to do a curses >version with your cursor positioning. > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 > > > Thank you. This is good for displaying the percentage. However it fails to display this: 100 files read 200 files read 300 files read .... of course all in the same line and not under the last line. Mage From devlai at gmail.com Wed Jul 27 02:33:35 2005 From: devlai at gmail.com (Devan L) Date: 26 Jul 2005 23:33:35 -0700 Subject: [pygame]how to copy a surface to an other surface with alpha value? In-Reply-To: References: Message-ID: <1122446015.671035.245180@g49g2000cwa.googlegroups.com> flyaflya wrote: > I want to join some surfaces to a new big surface with alpha cannel, I want > the new surface has same pixels(inclue r,g,b and alpha value) as the pixels > on the source surfaces. > my code as follow: > > surf = pygame.Surface((200,200)) > surf.blit(surf1, (0,0)) > surf.blit(surf2, (0,100)) > ..... > > but these codes can't copy alpha value to the new surface.how can I deal > with it? Try the pygame mailing list or irc channel. http://www.pygame.org/info.shtml From NAV2_SMTP_Gateway at sunway.edu.my Wed Jul 13 00:27:10 2005 From: NAV2_SMTP_Gateway at sunway.edu.my (NAV2_SMTP_Gateway at sunway.edu.my) Date: Wed, 13 Jul 2005 12:27:10 +0800 Subject: Content violation Message-ID: <200507130400.j6D401g0021526@gate2a.sunway.edu.my> Content violation found in email message. From: python-list at python.org To: ateway at sunway.edu.my File(s): message.zip Matching filename: message.zip From tdelaney at avaya.com Wed Jul 6 19:40:03 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 7 Jul 2005 09:40:03 +1000 Subject: I am a Java Programmer Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CB3D@au3010avexu1.global.avaya.com> mjmrifai at gmail.com wrote: > I am a java programmer and I want to learn Python Please help me. My condolences. I am a programmer who is currently forced to program in Java. These two sites will help you a lot in learning to program in Python: http://www.catb.org/~esr/faqs/smart-questions.html http://www.python.org/ Tim Delaney From benji at benjiyork.com Thu Jul 21 22:47:29 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 21 Jul 2005 22:47:29 -0400 Subject: Difference between " and ' In-Reply-To: <42E05106.5060905@REMOVEMEcyber.com.au> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> Message-ID: <42E05E41.9050101@benjiyork.com> Steven D'Aprano wrote: > Michael Hoffman wrote: >>John Machin wrote: >>>b83503104 at yahoo.com wrote: >>>>Can someone tell me the difference between single quote and double >>>>quote? >>> >>> ord("'") - ord('"') >>>5 >>Very zen. > But unfortunately incorrect, since the original poster > didn't ask for the difference between the ordinal > values of the single quote and double quote characters Steven, your reply was one of the most subtle and hilarious things I've read in a long time. Unfortunately I couldn't tell if it was intentional or not. :) -- Benji York From M.Waack at gmx.de Thu Jul 21 04:01:28 2005 From: M.Waack at gmx.de (Mathias Waack) Date: Thu, 21 Jul 2005 08:01:28 GMT Subject: Web-Forms Message-ID: Hi, I need to access some information from a web site which are only accessible through a form. Thus for each bucket of data you have to fill out the form, submit it and wait for an answer. Very easy - if you don't have to check some hundred times. Of course this site requires cookies, it is not directly accessible by URL and so on. All that nice stuff used to make a web site more professional;) But now the question: how can this be solved by using Python? Mathias From news at NOwillmcguganSPAM.com Mon Jul 25 12:17:44 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Mon, 25 Jul 2005 17:17:44 +0100 Subject: First app, thanks people In-Reply-To: <42e4eff3$1@griseus.its.uu.se> References: <42e4eff3$1@griseus.its.uu.se> Message-ID: <42e510ab$0$31229$db0fefd9@news.zen.co.uk> Jan Danielsson wrote: . > > Oh, I do have one more question though. I'm using wxPython, and when > I check for keys I use the evt.GetKeyCode() call, and compare it with > integers which I have found by printing what event.GetKeyCode() returns. > I would prefer a more portable way, since I assume that F1 doesn't have > the same code on a Sparc Ultra10. (?) Is there a way to get "key codes" > in wxPython in a portable manner? Hi, You should use the keycode constants. http://www.wxwidgets.org/manuals/2.6.1/wx_keycodes.html#keycodes Will -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From elmo13 at jippii.fi Thu Jul 14 13:38:45 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Thu, 14 Jul 2005 20:38:45 +0300 Subject: Differences between RDFlib - 4RDF and Redfoot - 4Suite? Message-ID: I was wondering about the differences with the referred libs and servers. Since the documentation isn't so thorough(and a bit because of my laziness), I thought I'd make request for usage accounts etc. stating the pros and cons of the aforementioned. Any notes would be appreciated. From python-ml at nn7.de Sun Jul 24 10:21:05 2005 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Sun, 24 Jul 2005 16:21:05 +0200 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: Message-ID: <1122214865.30698.32.camel@localhost> On Sat, 2005-07-23 at 23:35 +0200, Marc 'BlackJack' Rintsch wrote: > In , Soeren > Sonnenburg wrote: > > > Just having started with python, I feel that simple array operations '*' > > and '+' don't do multiplication/addition but instead extend/join an > > array: > > > > a=[1,2,3] > >>>> b=[4,5,6] > >>>> a+b > > [1, 2, 3, 4, 5, 6] > > Both operate on the lists themselves and not on their contents. Quite > consistent if you ask me. But why ?? Why not have them operate on content, like is done on *arrays ? Soeren From sjmachin at lexicon.net Sun Jul 24 08:42:28 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 24 Jul 2005 22:42:28 +1000 Subject: tuple to string? In-Reply-To: References: <42E0EED4.4020001@gmx.net> Message-ID: <42e38cb3$1@news.eftel.com> Francois De Serres wrote: > Francois De Serres wrote: > >> hiho, >> >> what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) >> to the string 'spam'? >> >> TIA, >> Francois >> >> > thanks to all! > > I'll pick ('%c' * len(t)) % t, for it's readability and the fact that > join() is on the deprec'd list. I presume you mean "deprecated". AFAIK there is no such thing as a "deprecated list". Certain constructs cause a deprecation warning to be emitted at run time -- like passing a float argument where an int is expected. Other constructs could be loosely described as deprecated because there is now a better way to do it, but no messages are generated. This is so for almost all of the functions in the string module. One example of this is "join": instead of string.join(alist, sep) one now does sep.join(alist) Given a non-string sequence of single characters, the common/standard/well-known idiom for producing a string uses join; it is ''.join(seq) Backing up to readability, I wouldn't have picked "('%c' * len(t)) % t" (nor the version with 2 fewer parentheses!) as particulary readable -- mainly because %c is AFAIK relatively little used in Python and only someone familar with C etc would understand why it works, or why it even exists. OTOH something like "''.join(chr(x) for x in t)" is made up of well-known frequently-used components. Cheers, John From spam.csubich+block at block.subich.spam.com Thu Jul 7 18:33:37 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 07 Jul 2005 18:33:37 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <74ize.27369$ho.19404@bignews6.bellsouth.net> Terry Hancock wrote: > With list comprehensions and generators becoming so integral, I'm > not sure about "unpythonic". And a syntax just occured to me -- > what about this: > > [y*x for x,y] > > ? > > (that is: > > [ for ] > > It's just like the beginning of a list comprehension or generator, but > without the iterator. That implies that one must be given, and > the result is therefore a callable object. As others have mentioned, this looks too much like a list comprehension to be elegant, which also rules out () and {}... but I really do like the infix syntax. Perhaps using angle-brackets would be useful? These have no grouping-meaning in Python that I'm aware of. Example, I'd also prefer using 'with' rather than 'for' as the keyword -- 'with' doesn't suggest iteration. I also suggest parenthization of the argument list, since that makes a zero-argument lambda not look weird. To replicate the examples from http://wiki.python.org/moin/AlternateLambdaSyntax 1 lambda a, b, c:f(a) + o(b) - o(c) 2 lambda x: x * x 3 lambda : x 4 lambda *a, **k: x.bar(*a, **k) 5 ((lambda x=x, a=a, k=k: x(*a, **k)) for x, a, k in funcs_and_args_list) ( for x, a, k in funcs_and_args_list) From steve at REMOVETHIScyber.com.au Tue Jul 12 11:58:00 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 01:58:00 +1000 Subject: append one file to another References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> <1121179119.788276.92280@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 12 Jul 2005 07:38:39 -0700, b83503104 at yahoo.com wrote: > Thanks for the nice suggestions! > > As a side question, you mentioned opening files in binary mode, in case > the code needs to run under Windows or cross-platform. What would > happen otherwise? Is it an issue of big little endian or some other > issue? No, nothing to do with big and little endian issues. It is all to do with the line delimiter, and possibly the end-of-file marker. Windows uses '\r\n' as the line delimiter for text files. (Or is it '\n\r'? I always forget...) Old-style Macintosh used '\r', and (almost) everything else, including new Macs running OS X, uses '\n'. If you open files in text mode, there can be complications due to the different line endings. To be perfectly frank, I only use Python under Linux, so I don't have the foggiest idea of just what Bad Things can happen. I know it is a big problem when using some FTP programs, which have a tendency to destroy binary programs if you upload/download them in text mode. I just did some experiments here, and can't get anything bad to happen. But whatever the problem is, my grand-pappy always told me, open the danged file in binary mode and you can't go wrong. *wink* I have found some discussions here: http://python.active-venture.com/tut/node9.html "Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in JPEGs or .EXE files. Be very careful to use binary mode when reading and writing such files." and here: http://zephyrfalcon.org/labs/python_pitfalls.html This website recommends: "Solution: Use the correct flags -- 'r' for text mode (even on Unix), 'rb' for binary mode." but I've never had any problems using 'rb' for text files under Linux. I'm also told that Windows uses ctrl-Z as the end-of-file marker, and if it finds that character in the middle of a text file, it will assume the file has finished and stop reading. But only in text mode, not binary. I don't think that's a problem for Linux. -- Steven. From ahabib at engin.umich.edu Tue Jul 26 09:24:42 2005 From: ahabib at engin.umich.edu (Asad Habib) Date: Tue, 26 Jul 2005 09:24:42 -0400 (EDT) Subject: Compiling a Python File on Mac OS X Tiger Message-ID: Hello. I am working on Tiger and wanted to find out how to compile a Python (.py) file into a .pyc file and then into a .pyo file. Can the compilation be achieved within the interpreter? Also, I am new to Python and wanted to know the difference between .pyc and .pyo files. Is this comparison similar to C? Any help would be appreciated. Thanks. - Asad From rafi at free.fr Mon Jul 25 16:50:08 2005 From: rafi at free.fr (rafi) Date: Mon, 25 Jul 2005 22:50:08 +0200 Subject: OS X py2app confusion In-Reply-To: <1122320692.803298.231120@g49g2000cwa.googlegroups.com> References: <1122320692.803298.231120@g49g2000cwa.googlegroups.com> Message-ID: <42e55087$0$6479$636a15ce@news.free.fr> bex wrote: > Im baffled about this one... > I was confused about the packaging, so I tried moving all the folders > in py2app into /Library/Python/2.3/ and deleted the py2app.pth file, > but it still wouldn't load the module. that does not sound as a good idea... > Any insight into the voodoo magic required to get this working? How many pythons do you have on your OS X? I have four different ones: Python as a Mac OS X install (original and 2.4) Python as a Fink installation (2.3 and 2.4) If you have several ones are you sure that the one you are using is the same as the one used to isntall py2app? Have you tried to re-install the py2app (even version 0.17)? my 2 cents -- rafi "Imagination is more important than knowledge." (Albert Einstein) From bill.mill at gmail.com Sat Jul 16 12:00:41 2005 From: bill.mill at gmail.com (Bill Mill) Date: Sat, 16 Jul 2005 12:00:41 -0400 Subject: odd python/linux/cherrypy behavior Message-ID: <797fe3d405071609006d1cfcd9@mail.gmail.com> On my laptop, I have an NTFS partition for NT, a FAT partition for data as a dmz which both linux and NT can access, and an ext3 partition for linux. However, I've experienced some weirdness on the FAT partition, and I'm wondering if anybody can tell me why it's happening. Yesterday, I downloaded the new release of cherrypy, and stuck it on the dmz drive. I ran tutorial01, which opens up a server on port 8080 and waits for connections. All seemed well, initialization info printed out, and it said it was waiting for connections on port 8080. However, when I tried to connect to it (via firefox or telnet) it just didn't respond. Not immediately - the connection attempts timed out. I tried different ports, but that didn't change anything. A reboot into NT, run the same file, it works perfectly. Eventually, after thinking it's a hosts file problem, or a firewall problem, I figure out that if I move it to my ext3 drive, it again works perfectly. Prints out the same information, says it's waiting on 8080, but this time, I can access it. Can anybody posit a guess as to why it would behave this way? Peace Bill Mill bill.mill at gmail.com From rafi at free.fr Wed Jul 27 04:42:09 2005 From: rafi at free.fr (rafi) Date: Wed, 27 Jul 2005 10:42:09 +0200 Subject: multiple inheritance super() In-Reply-To: <42e6c629@nntp0.pdx.net> References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> Message-ID: <42e748e9$0$32207$626a14ce@news.free.fr> Scott David Daniels wrote: >> I do understand the lookup for foo: foo is provided by both classes A >> and B and I do not state which one I want to use, so it takes the >> first one in the list of inherited classes (order of the declaration). >> However >> I cannot find an explanation (I may have googled the wrong keywords) >> for the order of the __init__ calls from C. I was expecting (following >> the same order as the method lookup): > > > This should make it clear: > class A (object): > def __init__ (self): > print '', > super (A, self) .__init__ () > print '' > class B (object): > def __init__ (self): > print '', > super (B, self) .__init__ () > print '' > class C (A, B): > def __init__ (self): > print '', > super (C, self) .__init__ () > print '' > > C() > Gosh, based on your code I added an attribute foo on both A and B, and I now understand... The super goes through all the super classes init to find the attributes that may have name conflict and keep the value of the attribute baesd upon the order of the class declaration in the definition of C (here the value of foo in A). Am I right? I am mostly using old style (without type unification) init but this motivate the shift for the new style. Is there somewhere a document about this? Thanks a lot Scott -- rafi "Imagination is more important than knowledge." (Albert Einstein) From gsakkis at rutgers.edu Sun Jul 3 16:09:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 13:09:50 -0700 Subject: Python concurrent tasking frameworks? References: <2jacl3yge2.fsf@random-node.example.org> Message-ID: <1120421390.834549.252410@o13g2000cwo.googlegroups.com> "Chris Stiles" wrote: > Hi -- > > I was wondering if anyone had a list of the various (presuming more than one) > Python tasking frameworks? I know of Twisted already, but I'm really looking > for something along the lines of a task/thread pool type of arrangement. I > see that there was some discussion on this topic a while ago referencing a > Matt Welsh paper, but afaict no implementations were discussed. Hi Chris, I don't know if it's close to what you're looking for but I have a (stripped-down, incomplete and undocumented) python version of Doug Lea's PooledExecutor class (http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/PooledExecutor.html), which is now part of JDK1.5 in the java.util.concurrent package. It's by no means ready for prime time as I didn't really use it in the end, but it's better than starting from scratch. Let me know if you're interested and I'll send it over. Regards, George From spam.csubich+block at block.subich.spam.com Sat Jul 30 22:23:42 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 30 Jul 2005 22:23:42 -0400 Subject: A replacement for lambda In-Reply-To: <42ead151@nntp0.pdx.net> References: <867jf9jmfw.fsf@bhuda.mired.org> <42ead151@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > What kind of shenanigans must a parser go through to translate: > < > > this is the comparison of two functions, but it looks like a left- > shift on a function until the second with is encountered. Then > you need to backtrack to the shift and convert it to a pair of > less-thans before you can successfully translate it. I hadn't thought of that, but after much diving into the Python grammar, the grammar would still work with a greedy tokenizer if "<<" (and also ">>", for identical reasons) were replaced in 'shift_expr" with "<" "<" and ">" ">". That, of course, introduces some weirdness of '''a = 5 < < 3''' being valid. I'm not sure whether that is a wart big enough to justify a special-case rule regarding '>>' and '<<' tokens. We do allow 'def f () :' as-is, so I'm not sure this is too big of a problem. From cam.ac.uk at mh391.invalid Fri Jul 29 22:59:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 30 Jul 2005 03:59:42 +0100 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Jorge Godoy wrote: > Michael Hoffman wrote: > > >>True, but a lot of his point *is* parsing input from the command line. >>Consider the following points paraphrased from his article: >> >>* Don't mix multiple ways of specifying options. (Solved by optparse) >>* If a flag expects an associated value, allow an optional = between the >>flag and the value. (Solved by optparse) >>* Allow single-letter options to be "bundled" after a single dash. >>(Solved by optparse) >>* Always allow -- as a file list marker. (Solved by optparse) >> >>And a lot of the other points are things that are made much, much, >>simpler by optparse, to the point that they become somewhat obvious. > > Take a look at the Perl module, then. You'll see that all of these are also > solved there "automagically". In that case, I think he just wasted a lot of time in the article, and would have been better off saying "use Getopt::Long." -- Michael Hoffman From gsakkis at rutgers.edu Fri Jul 8 15:51:14 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Jul 2005 12:51:14 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <74ize.27369$ho.19404@bignews6.bellsouth.net> <9nmze.144208$VH2.52770@tornado.tampabay.rr.com> Message-ID: <1120852274.923521.211250@g43g2000cwa.googlegroups.com> "Steven Bethard" wrote: > Christopher Subich wrote: > > Ron Adam wrote: > >> I think the association of (lambda) to [list_comp] is a nice > >> distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) > > > > Yeah, dictionary comprehensions would be an interesting feature. :) > > Syntax might be a bit unwieldy, though, and I doubt they'd be used often > > enough to be worth implementing, but still neat. > > Dict comprehensions were recently rejected: > http://www.python.org/peps/pep-0274.html > The reason, of course, is that dict comprehensions don't gain you much > at all over the dict() constructor plus a generator expression, e.g.: > dict((i, chr(65+i)) for i in range(4)) Sure, but the same holds for list comprehensions: list(i*i for i in xrange(10)). The difference is historic I guess; list comprehensions preceded generator expressions and so they cannot be removed, at least not before 3.0. I wonder if they will/should be in the language when the constraint of backwards compatibility is lifted. IMO they should not (TIOOWTDI, uniformity among builtin data structures, not overwhelmingly more useful than set or dict comprehensions), but there's a long way till that day. George From diesch at spamfence.net Wed Jul 20 12:03:46 2005 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 20 Jul 2005 18:03:46 +0200 Subject: Python IDE References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <20050720160346.23B2.2.NOFFLE@dieschf.news.arcor.de> linuxfreak wrote: > Got going with python...and i must say its a pretty cool language. > Been using Xemacs to write me programs. But I want an IDE that would I'm using GNU emacs > give me auto-completion, Read the manual about tags and abbrevs Emacs Language Sensitive Editor (ELSE) looks interesting too. > online help python-mode has C-c C-h for py-help-at-point > and the like... Tried SPE and > Dr.Pyhton but the former crashes regulary and the latter is quite > unweildy and does not have a great many features. I quite like the UML > feature found in SPE but the damn thing crashes way too often. What are > you guys using and what do you think is the best IDE...or should i > stick with Xemacs/emacs??? I don't like specialized IDE's as I'm using different languages and don't want to switch my editor for them. Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From rkern at ucsd.edu Wed Jul 27 16:39:13 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Jul 2005 13:39:13 -0700 Subject: searching string url In-Reply-To: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> Message-ID: googlinggoogler at hotmail.com wrote: > Hiya, > > Im trying to find a method of searching a html file (ive grabbed it > with FancyURLopener), basically in the html file there is a series of > links in the following format - > > A HREF="../../company/11/13/820.htm">some name > so I want to search the file for "../../company/" and then get the 13 > charecters after it so that I can work it as a URL, if you see what I > mean? You want to use BeautifulSoup. http://www.crummy.com/software/BeautifulSoup/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rtw at freenet.co.uk Sun Jul 31 12:45:14 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 31 Jul 2005 11:45:14 -0500 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: Steven D'Aprano wrote in news:pan.2005.07.31.14.30.04.607118 at REMOVETHIScyber.com.au in comp.lang.python: > Quoting Rob Williscroft: > >> > def translate( text ) >> > import string all=string.maketrans('','') >> > badcars=all.translate(all,string.letters+string.digits) >> > TABLE = string.maketrans(badcars,'_'*len(badcars)) >> > >> > global translate >> > def translate( text ): >> > return text.translate(TABLE) >> > >> > return translate( text ) > > This is a difficult piece of code to understand and maintain. Its 8 lines, of self contained code. It does everyting its supposed to do and nothing its not. > You have > a function called translate, which in turn calls the string > translate() method. That's okay. But then you have a global variable > *also* called translate -- does that refer to the same function? This is how globals work in python, if you wish to (re)bind to a global before reading it at function scope, you need to say so. > Is > this self-modifying code? That is a dangerous, hard to debug, hard to > understand technique that is too-clever-by-half. > Maybe so, but if true, python as a language is too-clever-by-half. > Then you create a local variable, also called translate, also a No, that isn't how globals work in python, there is no local called translate above. > function, which simply calls the translate method of its argument. A > waste of a function, when all you need to do is call the pre-existing > translate method. If I have understood this code correctly, the > *local* translate is bound to the *global* translate, which is the > function being defined. Close but there isn't, and never was, a *local* translate function. > And lastly, just to complete the confusion, the original function > itself appears to call itself -- presumably the rebound copy that > points to what was the local copy -- recursively, with the same > argument. def f() global g def g(): return "something" return g() f() is a function that (re)creates a global function g() and calls it. Is it just that translate() rebinds itself that is too much, or do you object to f() too ? I do object to f() but only because its useless. > That's a nifty piece of code for showing how clever you are at writing > mildly obfuscated code. But for commercial use, where the code has to > be maintained and debugged, it is a terrible idea. 8 lines of self contained code are a terrible idea !, you have IMO a very strange idea of what is or isn't maintainable. Is using generators and decorators a terrible idea too ? Rob. -- http://www.victim-prime.dsl.pipex.com/ From pbagora at yahoo.com Tue Jul 19 13:52:03 2005 From: pbagora at yahoo.com (Pranav Bagora) Date: Tue, 19 Jul 2005 10:52:03 -0700 (PDT) Subject: Read only files Message-ID: <20050719175203.39701.qmail@web32409.mail.mud.yahoo.com> Hello, I am getting a permission Denied error when i am trying to make changes in some read only files in a directory. How do we check and change the read only attributes of files in python. Please Help, Pranav __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From gsakkis at rutgers.edu Sat Jul 16 11:24:04 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 16 Jul 2005 11:24:04 -0400 Subject: Python Programming Contest References: <42D780EF.6020809@sweetapp.com> Message-ID: <1121527459.6b60aac30aa1215f6bad5d994664520f@teranews> "Tom Anderson" wrote: > On Sat, 16 Jul 2005, Joseph Garvin wrote: > > > Someone correct me if I'm wrong -- but isn't this the Shortest Path problem? > > Dang! I was just about to point that out. > > [snipped] > > But yes, this is basically about who can write the fastest implementation > of Dijkstra's algorithm. I've got one somewhere - i have a half-finished > journey planner for the London Underground! - so maybe i should enter ... > > Hmm. Actually, Dijkstra's algorithm isn't always the fastest way to find > the shortest path. The thing is, it's fully general, so it works on > absolutely any graph; if the graph you're traversing has particular > properties, you might be able to leverage those to find a solution faster. > [snipped] Yes, that's right. Moreover, Dijkstra's computes the shortest path from a given start to *all* nodes in the network, which is usually an overkill if all you want is the shortest path to one (or a few) node(s). > I can't immediately see any properties of this network that could be > exploited, but that doesn't mean there aren't any. Hints: - You have to take exactly one decision (flight or stop) every single day until you reach the destination; no more, no less. - There is no time machine; days pass in one direction only, one at a time. George From George.Flaherty at marketmax.com Thu Jul 21 09:28:59 2005 From: George.Flaherty at marketmax.com (George Flaherty) Date: Thu, 21 Jul 2005 09:28:59 -0400 Subject: Listing Processes Running on Remote Machines Message-ID: <59CF9F456FAA9045B405C441EC916F3E02735022@MERC24.na.sas.com> Look into STAF http://staf.sourceforge.net/index.php -g -----Original Message----- From: python-list-bounces+george.flaherty=sas.com at python.org [mailto:python-list-bounces+george.flaherty=sas.com at python.org] On Behalf Of yoda Sent: Thursday, July 21, 2005 9:23 AM To: python-list at python.org Subject: Listing Processes Running on Remote Machines Hello Hackers, I'm developing a large scale distributed service and part of the requirement is that I be able to monitor clients in a very granular way. To this end, I'd like to know if there is any way to get a list of all the processes running on a remote client\machine. I need to be able to do this on demand. (i.e on user demand) Please note that the clients run heterogeneous operating systems mainly Linux and Windows2000\XP -- http://mail.python.org/mailman/listinfo/python-list From kbk at shore.net Tue Jul 12 00:11:56 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 12 Jul 2005 00:11:56 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200507120411.j6C4Bu9Y030858@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 349 open ( +1) / 2880 closed ( +1) / 3229 total ( +2) Bugs : 897 open ( -1) / 5119 closed (+16) / 6016 total (+15) RFE : 194 open ( +1) / 170 closed ( +0) / 364 total ( +1) New / Reopened Patches ______________________ PEP 343 draft documentation (2005-07-07) http://python.org/sf/1234057 opened by Nick Coghlan PEP 343 implementation (2005-07-11) http://python.org/sf/1235943 opened by Michael Hudson Patches Closed ______________ Allow weak referencing of classic classes (2005-04-03) http://python.org/sf/1175850 closed by glchapman New / Reopened Bugs ___________________ Pickle protocols 1, 2 can't handle "inf" floats. (2005-07-06) CLOSED http://python.org/sf/1233578 opened by Charles getpass.getpass() performs differently on Windows vs *nix (2005-07-07) http://python.org/sf/1233785 opened by Darryl Dixon tkFileDialog.askopen... fails when dir="" (2005-07-06) http://python.org/sf/1233799 opened by Russell Owen datetime.strftime %s (2005-07-07) http://python.org/sf/1234123 opened by Peter Kleiweg 'insufficient disk space' message wrong (msi on win xp pro) (2005-07-07) http://python.org/sf/1234328 opened by Patrick Vrijlandt configure: error: cannot compute sizeof (int), 77 (2005-07-07) http://python.org/sf/1234473 opened by Tekhne filecmp.cmp's "shallow" option (2005-07-08) http://python.org/sf/1234674 opened by Mendez Admin privs required for Windows? (2005-07-08) CLOSED http://python.org/sf/1234850 opened by Tim Peters Tutorial Section 6.3 example wrong (2005-07-08) CLOSED http://python.org/sf/1234956 opened by Phoebus Chen ConfigParser generating strings I can't compare (2005-07-08) CLOSED http://python.org/sf/1234965 opened by Robert Guico Lock.acquire treats only 1 as True (2005-07-08) CLOSED http://python.org/sf/1234979 opened by Chris Perkins using some_re.sub() often imports sre.__doc__ (2005-07-09) http://python.org/sf/1234985 opened by Steve Alexander debug info file descriptor of tarfile is inconsistent (2005-07-10) http://python.org/sf/1235266 opened by George Yoshida Inconsistent singleton constructor messages (2005-07-10) CLOSED http://python.org/sf/1235569 opened by Pavel Pergamenshchik codecs.StreamRecoder.next doesn't encode (2005-07-10) http://python.org/sf/1235646 opened by Sebastian Wangnick crashes in bgen wrappers (2005-07-11) http://python.org/sf/1236090 opened by Michael Hudson Bugs Closed ___________ openssl-0.9.8 requires _ssl.mak change (2005-07-06) http://python.org/sf/1233049 closed by loewis chr() returns ? when input > 127 in OS X (2005-07-02) http://python.org/sf/1231488 closed by loewis Build failure (2005-06-30) http://python.org/sf/1230161 closed by ceramond Pickle protocols 1, 2 can't handle "inf" floats. (2005-07-06) http://python.org/sf/1233578 closed by mwh Admin privs required for Windows? (2005-07-08) http://python.org/sf/1234850 closed by loewis Tutorial Section 6.3 example wrong (2005-07-08) http://python.org/sf/1234956 closed by birkenfeld ConfigParser generating strings I can't compare (2005-07-08) http://python.org/sf/1234965 closed by tim_one Lock.acquire treats only 1 as True (2005-07-08) http://python.org/sf/1234979 closed by birkenfeld function and method objects confounded in Tutorial (2004-06-09) http://python.org/sf/969757 closed by birkenfeld Inconsistent singleton constructor messages (2005-07-10) http://python.org/sf/1235569 closed by rhettinger PyObject_Realloc bug in obmalloc.c (2005-04-19) http://python.org/sf/1185883 closed by tim_one Need locale arg to strftime() (2005-06-13) http://python.org/sf/1219840 closed by bcannon ``from sys import stdin,`` doesn't raise a SyntaxError (2005-04-25) http://python.org/sf/1190012 closed by bcannon [AST] distinct code objects not created (2005-04-25) http://python.org/sf/1190011 closed by bcannon [AST] automatic unpacking of arguments broken (2005-04-19) http://python.org/sf/1186353 closed by bcannon [AST] genexps get scoping wrong (2005-04-19) http://python.org/sf/1186195 closed by bcannon From python-ml at nn7.de Mon Jul 25 16:29:31 2005 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Mon, 25 Jul 2005 22:29:31 +0200 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: <1122215068.30698.37.camel@localhost> Message-ID: <1122323372.30698.119.camel@localhost> On Sun, 2005-07-24 at 11:50 -0700, Robert Kern wrote: > Soeren Sonnenburg wrote: > > On Sun, 2005-07-24 at 13:36 +1000, Steven D'Aprano wrote: > > > >>On Sat, 23 Jul 2005 18:30:02 +0200, Soeren Sonnenburg wrote: [...] > >>Lists in Python can contain anything, not just numeric values. > > > > That seems to be *the point*. > > Whose point? If you mean that you want to be able to use arbitrary > objects in an array, then look in numarray.objects for an array type > that handles arbitrary Python objects. Well, one cannot efficiently deal with these 'list-arrays' as they can contain different data types (typechecking necessary; atlas etc won't work). [...] > > *I* would rather drop > > '+' and '*' to work like they do in *array ... > > Tough. It's 14 years or so too late to make that change. Ok got it. A seperate array type which can only contain objects of the same type simply makes sense. Soeren From http Wed Jul 13 20:20:28 2005 From: http (Paul Rubin) Date: 13 Jul 2005 17:20:28 -0700 Subject: Efficiently Split A List of Tuples References: Message-ID: <7xmzoqck6r.fsf@ruckus.brouhaha.com> Richard writes: > I have a large list of two element tuples. I want two separate > lists: One list with the first element of every tuple, and the > second list with the second element of every tuple. > > I know I can use a 'for' loop and create two new lists > using 'newList1.append(x)', etc. Is there an efficient way > to create these two new lists without using a slow for loop? Not really. You could get a little cutesey with list comprehensions to keep the code concise, but the underlying process would be about the same: a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) x,y = [[z[i] for z in a] for i in (0,1)] # x is now (1,3,5,7,9) and y is (2,4,6,8,10) From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 5 12:57:36 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 5 Jul 2005 18:57:36 +0200 Subject: Folding in vim References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: Andrea Griffini enlightened us with: > - never ever use tabs I always use one tab for indents, and set my editor to display it as four spaces. I like being able to unindent a line by deleting a single character. I don't see a reason why _not_ to use tabs, really. As long as the use is consistent - I hate those files with an 8-space tab and 4-space indent, where they replace two indents with a single tab. For me, one indent = one tab. No matter the tab setting, it'll look good. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From beliavsky at aol.com Sun Jul 3 08:54:03 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 3 Jul 2005 05:54:03 -0700 Subject: Python, mysql, floating point values question In-Reply-To: <21gec1lgopab3sjbhkh6m2amd51e1rcq1v@4ax.com> References: <43b72594050701154055297e73@mail.gmail.com> <21gec1lgopab3sjbhkh6m2amd51e1rcq1v@4ax.com> Message-ID: <1120395243.114914.188240@o13g2000cwo.googlegroups.com> Dennis Lee Bieber wrote: > Considering how often this has come up, I've sort of lost faith > in CS programs at colleges. Now, this might be an unfair statement as I > don't know if any of those bringing up the question ever had college CS > courses... But the fluff of floating point data was something I vaguely > recall had been covered in my second FORTRAN class [1976-77; I ran > FORTRAN, Advanced FORTRAN, and Assembly in my first year] (since COBOL > used packed decimal, it wasn't a candidate for the behavior -- not > problem, as it is not erroneous behavior, just something one needs to > learn about). > > A book that may be out of print "Real Numbers Made Real" (hope I > recalled the name) covers some of this. Almost -- the book is "Real Computing Made Real: Preventing Errors in Scientific and Engineering Calculations", by Forman S. Acton From dalke at dalkescientific.com Fri Jul 29 14:05:22 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 29 Jul 2005 18:05:22 GMT Subject: can list comprehensions replace map? References: <42ea596d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Can I play too? How about: Sweet! Andrew dalke at dalkescientific.com From saint.infidel at gmail.com Wed Jul 6 12:13:05 2005 From: saint.infidel at gmail.com (infidel) Date: 6 Jul 2005 09:13:05 -0700 Subject: Conditionally implementing __iter__ in new style classes In-Reply-To: References: Message-ID: <1120666385.048448.228450@f14g2000cwb.googlegroups.com> I'm not sure I understand why you would want to. Just don't define __iter__ on your newstyle class and you'll get the expected behavior. From jason at tishler.net Mon Jul 25 16:11:32 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 25 Jul 2005 16:11:32 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E52646.7070902@llnl.gov> References: <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> <42E4E14B.2030905@llnl.gov> <20050725165530.GB2672@tishler.net> <42E52646.7070902@llnl.gov> Message-ID: <20050725201132.GA3440@tishler.net> Dean, On Mon, Jul 25, 2005 at 10:49:58AM -0700, Dean N. Williams wrote: > For version control and other reasons, it would be nice to be able to > build Python from source and it should build from source. How did the > Cygwin version build? I built using an older version of Cygwin (i.e, 1.5.12-1). > I've attached the Python log file with the specific error. What file > is missing? None. See below... The "root cause" is the following: under Cygwin 1.5.12-1: $ configure [snip] checking for inet_pton... no [snip] under Cygwin 1.5.18-1: $ configure [snip] checking for inet_pton... yes [snip] So, when you build under 1.5.18-1, pyconfig.h has the following: #define HAVE_INET_PTON 1 This causes a chunk of code in socketmodule.c to be compiled under 1.5.18-1 that wasn't compiled before. I will have to research why INET_ADDRSTRLEN is not defined under Cygwin and submit a patch to Cygwin or Python as appropriate. Thanks for bringing this problem to my attention. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From ptmcg at austin.rr.com Sun Jul 31 00:13:21 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Jul 2005 21:13:21 -0700 Subject: HTML Scraping?? In-Reply-To: References: Message-ID: <1122783201.088220.272210@g44g2000cwa.googlegroups.com> There are several HTML scraping examples that ship with pyparsing, including a URL extractor, temperature display, and NTP server extractor (this last is probably closest to your question). Download pyparsing at http://pyparsing.sourceforge.net. -- Paul From rgacote at AppropriateSolutions.com Sat Jul 2 09:57:21 2005 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Sat, 2 Jul 2005 09:57:21 -0400 Subject: web programming with mod_python In-Reply-To: <5xzm6obuegpo$.1u6l6qmydgi2v$.dlg@40tude.net> References: <5xzm6obuegpo$.1u6l6qmydgi2v$.dlg@40tude.net> Message-ID: At 7:17 PM -0300 7/1/05, Rodrigo Dominguez wrote: >My question is: is there some kind of framework that works with mod_python? You could take a look at Myghty: -- Raymond Cote Appropriate Solutions, Inc. PO Box 458 ~ Peterborough, NH 03458-0458 Phone: 603.924.6079 ~ Fax: 603.924.8668 rgacote(at)AppropriateSolutions.com www.AppropriateSolutions.com From steve at REMOVETHIScyber.com.au Wed Jul 6 11:48:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 07 Jul 2005 01:48:19 +1000 Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> <42cbdbde$0$10471$da0feed9@news.zen.co.uk> Message-ID: On Wed, 06 Jul 2005 14:25:30 +0100, Will McGugan wrote: >> But if you are just trying to optimize for the sake of optimization, >> that's a terrible idea. Get your program working first. Then when it >> works, measure how fast it runs. If, and ONLY if, it is too slow, >> identify the parts of the program that make it too slow. That means >> profiling and timing. Then optimize those parts, and nothing else. >> >> Otherwise, you will be like the car designer trying to speed up his sports >> cars by making the seatbelts aerodynamic. > > No need for the 'premature optimization is the root of all evil' speech. > I'm not trying to optimize anything - just enquiring about the nature of > frozenset. If typing 'frozenset' over 'set' gave me a saving in time or > memory (even if tiny) I would favour immutable sets, where appropriate. Well, obviously the "premature optimization" speech just went in one ear and out the other. "Saving in time or memory" is what optimization is about. What did you think optimization means? set and frozenset have different functionality (one is mutable, the other is not) and use cases (you use one where you need to dynamically add and remove items from a set, and the other where you need to use a set as a key in a dictionary). In most cases, they aren't interchangable. While you're spending time worrying about shaving a thousandth of a millisecond off a program that takes five seconds to run, I'll get on with development using the right object for the functionality needed. -- Steven. From grante at visi.com Sat Jul 9 11:57:17 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 09 Jul 2005 15:57:17 -0000 Subject: Defending Python References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> Message-ID: <11cvsutdl580b17@corp.supernews.com> On 2005-07-09, Brian wrote: > > folks as an easily acquired extra skill. > > I agree 100% with your statement above. Python may not be sufficient > for being the only programming language that one needs to know -- yet, > it does come in VERY handy for projects that need to perform tasks on > non-Microsoft operating systems. :-) It's also darned handy for projects that need to perform tasks on Microsft operating systems but you want to do all the development work under a real OS. -- Grant Edwards grante Yow! I'm into SOFTWARE! at visi.com From jason.massey at gmail.com Mon Jul 18 10:52:06 2005 From: jason.massey at gmail.com (Jason) Date: 18 Jul 2005 07:52:06 -0700 Subject: wxPython date Message-ID: <1121698326.616726.284280@o13g2000cwo.googlegroups.com> How do I form a new wxPython date using day, month and year? I've tried the wx.DateTimeFromDMY but it crashes in Pythonwin when I test it out and I get all manner of complaints when I try it from the command line. Surely there's an equivalent to the python datetime.date(2005,07,18) thanks, jason From tiissa at nonfree.fr Wed Jul 20 16:39:30 2005 From: tiissa at nonfree.fr (tiissa) Date: Wed, 20 Jul 2005 22:39:30 +0200 Subject: Printing a variable's name not its value In-Reply-To: <1121886771.309517.156380@g47g2000cwa.googlegroups.com> References: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> <1121886771.309517.156380@g47g2000cwa.googlegroups.com> Message-ID: <42deb680$0$7324$636a15ce@news.free.fr> Simon Dahlbacka wrote: > as you have been told, there is no way to get a variable's name Well, if you really want to, you can get all the names bound to a given object: def get_names(obj): g = globals() names = [] for name in g: if g[name] is obj: names.append(name) return names Then you can play around: >>> list1 = [] >>> list2 = [list1] >>> get_names(list2) ['list2'] >>> list3 = list2 >>> get_names(list2) ['list3', 'list2'] >>> get_names(1) [] >>> a = 1 >>> get_names(1) ['a'] >>> b = 1 >>> get_names(1) ['a', 'b'] >>> get_names(a) ['a', 'b'] >>> c = 4/3. >>> d = 4/3. >>> get_names(c) ['c'] >>> get_names(d) ['d'] >>> get_names(4/3.) [] >>> But I wouldn't do it. If I want a name to be attached to some objects, I usually include it as a member/property of my class. From jd33526 at gmail.com Fri Jul 29 19:03:38 2005 From: jd33526 at gmail.com (bob sacamano) Date: 29 Jul 2005 16:03:38 -0700 Subject: urllib2 bug? Message-ID: <1122678218.500967.7170@g47g2000cwa.googlegroups.com> Certain pages cause urllib2 to go into an infinite loop when using readline(), but everything works fine if read() is used instead. Is this a bug or am I missing something simple? import urllib2 url = 'http://www.naylamp.com' f = urllib2.urlopen(url) i = 0 #this works fine when uncommented #print f.read() #print 'finished' #this never ends while 1: line = f.readline() if not line: break print line print i i = i + 1 #end while From defaultuserbr at yahoo.com Tue Jul 19 12:22:52 2005 From: defaultuserbr at yahoo.com (Default User) Date: 19 Jul 2005 16:22:52 GMT Subject: Xah's edu corner: on Microsoft hatred References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: <3k4nmsFs7kocU2@individual.net> J|rgen Exner wrote: > Just for the records at Google et.al. in case someone stumbles across > Xah's masterpieces in the future: > Xah is very well known as the resident troll in many NGs and his > 'contributions' are less then useless. > > Best is to just ignore him. I already had him killfiled. I'm going to add a few of these non-comp.lang.c newsgroups as well, not due to any animosity towards them but because I don't read them and don't plan to, so any message crossed to them is likely a troll. A good newsreader and aggressive use of filtering is the best way to handle such people. Brian From bokr at oz.net Thu Jul 14 19:01:28 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 14 Jul 2005 23:01:28 GMT Subject: all possible combinations References: Message-ID: <42d6ed37.197174802@news.oz.net> On Thu, 14 Jul 2005 17:10:37 -0400, William Park wrote: >rbt wrote: >> Say I have a list that has 3 letters in it: >> >> ['a', 'b', 'c'] >> >> I want to print all the possible 4 digit combinations of those 3 >> letters: >> >> 4^3 = 64 >> >> aaaa >> abaa >> aaba >> aaab >> acaa >> aaca >> aaac >> ... >> >> What is the most efficient way to do this? > >Since you're doing cross product (ie. 3*3*3*3), manual loop of 4 level >deep would be the fastest in terms of algorithm. C vs. Python is >implementation detail. > >In Bash shell, this is one-liner, > echo {a,b,c}{a,b,c}{a,b,c}{a,b,c} >or maybe two, > abc=(a b c) > echo {^abc}{^abc}{^abc}{^abc} > It's a one liner in Python too ;-) >>> print ' '.join([x+y+z+q for s in ['abc'] for x in s for y in s for z in s for q in s]) aaaa aaab aaac aaba aabb aabc aaca aacb aacc abaa abab abac abba abbb abbc abca abcb abcc acaa a cab acac acba acbb acbc acca accb accc baaa baab baac baba babb babc baca bacb bacc bbaa bbab bb ac bbba bbbb bbbc bbca bbcb bbcc bcaa bcab bcac bcba bcbb bcbc bcca bccb bccc caaa caab caac cab a cabb cabc caca cacb cacc cbaa cbab cbac cbba cbbb cbbc cbca cbcb cbcc ccaa ccab ccac ccba ccbb ccbc ccca cccb cccc Regards, Bengt Richter From janssen at parc.com Tue Jul 12 19:27:02 2005 From: janssen at parc.com (Bill Janssen) Date: Tue, 12 Jul 2005 16:27:02 PDT Subject: Browser plug-in for Python? Message-ID: <05Jul12.162705pdt."58617"@synergy1.parc.xerox.com> Has anyone written a browser plug-in for Python, similar to the Java plug-in that Sun has switched to for applets? Bill From rutt at bmi.osu.edu Thu Jul 7 10:04:06 2005 From: rutt at bmi.osu.edu (Benjamin Rutt) Date: Thu, 07 Jul 2005 10:04:06 -0400 Subject: question about introspection using inspect module Message-ID: <5vll4ihfvt.fsf@akron.bmi.ohio-state.edu> I'm trying to learn about introspection in Python. my ultimate goal is to be able to build a module "text database" of all modules that are in the sys.path, by discovering all candidate modules (I've already done that), importing all of them, and then introspecting on each module to discover its functions, globals and classes. But for now I am having a problem with the latter. I would like to import a module and figure out the names of its defined functions, globals, and classes. Here's my attempt, file foo.py, which has a single function, class, and global defined: #!/usr/bin/env python def somefunction(i): i = i + 1 class someclass: def __init__(self): self.x = 0 self.y = 1 someglobal = 1.2 if __name__ == "__main__": # when run as a script import foo import inspect from inspect import * isfuncs = filter(lambda x: re.match("^is", x) and x, dir(inspect)) print isfuncs print filter(lambda x: re.match("some", x[0]) and x[0], getmembers(foo)) for f in isfuncs: exec('print "trying %20s: ",; print getmembers(foo, %s)' % (f, f)) the output of running it as a script is the following: ['isbuiltin', 'isclass', 'iscode', 'isdatadescriptor', 'isframe', 'isfunction', 'ismethod', 'ismethoddescriptor', 'ismodule', 'isroutine', 'istraceback'] [('someclass', ), ('somefunction', ), ('someglobal', 1.2)] trying isbuiltin: [] trying isclass: [('someclass', )] trying iscode: [] trying isdatadescriptor: [] trying isframe: [] trying isfunction: [('somefunction', )] trying ismethod: [] trying ismethoddescriptor: [] trying ismodule: [] trying isroutine: [('somefunction', )] trying istraceback: [] I was trying to use inspect.getmembers(foo, ) with an appropriate predicate ("is" function). it looks like I am able to discover that 'someclass' is a class, and that 'somefunction' is a function (and also a routine, apparently). However, I cannot seem to discover that 'someglobal' is a global. How to do so? Thanks, -- Benjamin Rutt From lorinh at gmail.com Wed Jul 27 11:42:09 2005 From: lorinh at gmail.com (lorinh at gmail.com) Date: 27 Jul 2005 08:42:09 -0700 Subject: Stripping C-style comments using a Python regexp Message-ID: <1122478928.879240.89110@g47g2000cwa.googlegroups.com> Hi Folks, I'm trying to strip C/C++ style comments (/* ... */ or // ) from source code using Python regexps. If I don't have to worry about comments embedded in strings, it seems pretty straightforward (this is what I'm using now): cpp_pat = re.compile(r""" /\* .*? \*/ | # C comments // [^\n\r]* # C++ comments """,re.S|re.X) s = file('myprog.cpp').read() cpp_pat.sub(' ',s) However, the sticking point is dealing with tokens like /* embedded within a string: const char *mystr = "This is /*trouble*/"; I've inherited a working Perl script, which I'd like to reimplement in Python so that I don't have to spawn a new Perl process in my Python program each time I want to strip comments from a file. The Perl script looks like this: #!/usr/bin/perl -w $/ = undef; # no line delimiter $_ = <>; # read entire file s! ((['"]) (?: \\. | .)*? \2) | # skip quoted strings /\* .*? \*/ | # delete C comments // [^\n\r]* # delete C++ comments ! $1 || ' ' # change comments to a single space !xseg; # ignore white space, treat as single line # evaluate result, repeat globally print; The Perl regexp above uses some sort of conditional to deal with this, by replacing a quoted string with itself if the initial match is a quoted string. Is there some equivalent feature in Python regexps? Lorin From jforcier at strozllc.com Sun Jul 24 10:25:34 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: Sun, 24 Jul 2005 10:25:34 -0400 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: <42e2f10e.984589695@news.oz.net> References: <42e2f10e.984589695@news.oz.net> Message-ID: <6C0B4F7F-0579-4B1A-976A-5AA07BABC2B3@strozllc.com> On Jul 24, 2005, at 5:00 AM, Bengt Richter wrote: > Actually, it's not just the "magic" methods. [...] Thanks for the clarification/explanation =) > This looks a little strange because the repr of the bound method > includes a repr of the thing bound to, > which returns the Edit/View presentation (after the 'of' above). > (A possible reason to consider using just __str__ and letting > __repr__ be). Yea, I must apologize, I pasted in a slightly different version of the class in my original email than I intended to...I fully understand the difference between __str__ and __repr__ and that bit of code where I attempted to bind to both was me attempting to discern exactly what was going on. The "real" version would only be binding to __str__ and leaving __repr__ alone so it could be used as intended =) > A function's __get__ method will deliver a bound method if the lookup > is via an inst, or an unbound method if the lookup is via the > class, in which > case None is passed to __get__ instead of the instance. > > The upshot is that you can create descriptors __str__ and > __repr__for your class that will > return bound methods using __str__ and __repr__ function attributes > of your instance (if they exist) > instead of the normal class attributes, and we can chose from > several normal class attributes according > to a general mode flag of the class. [big-arse snip of code/output] I half-understood this and what followed, but that's my fault and not that of your explanation. Honestly, I'm still trying to elevate my Python knowledge from a primarily quick-scripting level to one suitable for larger applications (or at least, more intelligent scripts =)). Specifically with things like descriptors and their ilk, I need to reread the various docs and PEPs out there. But, thanks for the detailed example, and you can be sure I'll return to it in the near future after some more reading. > You could use this kind of thing in a base class and specialize > in subclasses to override stuff, and you can do other stuff too. > Your choices are more varied that you probably thought ;-) Oh, I know there's a whole host of ways to accomplish this, I just tend to get narrowly focused on a single option or couple of options for stretches of time, heh. >> And ideally I wanted to be able to hold a collection of these objects >> and toggle them all to one state or the other, then bandy them about >> > ^^^^^^^^^^^^^^^ > does that mean all instances with a single toggling action, or each > individually? You could have both. I.e., a general mode flag and the > ability to assign an arbitrary __str__ and/or __repr__ override for > a particular instance. See example, where all are toggled by default. Well, either, depending on how flexible I want the overall design to be, but primarily all at once. E.g. I'd have a Page or PageBody container class holding a bunch of (implementing the same interface) objects as discussed, and would want all of those sub-objects to be in the same mode. In other words...a page is either displaying text fields for editing, or plain text for display (but with myriad form elements, not just text fields, of course). Thanks again, Jeff -- Jeffrey E. Forcier Junior Developer, Research and Development Stroz Friedberg, LLC 15 Maiden Lane, 12th Floor New York, NY 10038 [main]212-981-6540 [direct]212-981-6546 http://www.strozllc.com This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by any error in transmission. If you have received this message in error, please immediately notify the sender by e-mail or by telephone at 212.981.6540, delete the message and all copies from your system and destroy any hard copies. You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient. From pekka.niiranen at wlanmail.com Fri Jul 22 15:24:18 2005 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Fri, 22 Jul 2005 22:24:18 +0300 Subject: Question about namespaces and import. How to avoid calling os.system Message-ID: <42e14753$0$27392$39db0f71@news.song.fi> Hi there, I have two scripts. The first "main.py" sets some variables and then imports another called "gen.py". The idea is to provide "main.py" that defines some paths, variables etc. without using Windows environment variables. Various other "hackers" will make additional Python scripts (subroutines) like "gen.py" that utilize variables set by the "main.py" and which "main.py" calls. I can do this with "subprocess" module by setting its env -variable but I try to avoid calling shell. How can I merge temporary the namespaces of the two modules? ----- example run STARTS --- c:\home\pekka>main.py imported module: {'todir': 'c:\\'} Traceback (most recent call last): File "C:\home\pekka\main.py", line 16, in ? gencmd.run_gen() File "c:\home\gen.py", line 7, in run_gen print env_params # HOW MAKE THIS DICTIONARY FROM main.py VISIBLE NameError: global name 'env_params' is not defined ----- example run STOPS --- ---- main.py STARTS ---- import os, sys env_params = {} env_params['EDITOR'] = "foo" def import_libs(dir, script): """ Imports python script""" sys.path.insert(0,(os.path.normpath(dir))) module_name, ext = os.path.splitext(script) my_script = __import__(module_name) print "\nimported module: %s" % (my_script) del sys.path[0] return my_script if __name__ == "__main__": gencmd = import_libs("c:\home", "gen.py") gencmd.run_gen() ---main.py ENDS ----- ---- gen.py STARTS ---- # Store this script to directory c:\home" my_env_params ={} my_env_params['todir'] = "c:\\" def run_gen(): # Get commandline arguments print my_env_params print env_params # HOW MAKE THIS DICTIONARY FROM main.py VISIBLE if __name__ == "__main__": run_gen() ---gen.py ENDS ----- -pekka- From amk at amk.ca Fri Jul 1 11:43:20 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 01 Jul 2005 10:43:20 -0500 Subject: Accepted Summer of Code proposals Message-ID: For anyone who's interested: the Python wiki now contains a list of the PSF-mentored proposals that were accepted for Google's Summer of Code: http://wiki.python.org/moin/SummerOfCode --amk From phillip.watts at anvilcom.com Sat Jul 2 11:55:19 2005 From: phillip.watts at anvilcom.com (phil) Date: Sat, 02 Jul 2005 10:55:19 -0500 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: <42C6B8E7.2040202@anvilcom.com> Peter Hansen wrote: > godwin wrote: > >> I wanna thank Martin for helping out with my ignorance concerning >>execution of stored procedure with python. Now i have decided to write >>a web app that googles into my companies proprietary database. >> > > Just checking... do you really mean "googles", or is that in your mind a > synonym for "search"? > > >>I need >>to know whether zope is good for that job. >> > > For which part of it? The web part, or the searching part? It's not > likely sufficient for the searching part, since it doesn't include > database interfaces other than to its own ZODB. What proprietary > database is involved? > > -Peter > I think the guy might like to know what Zope is. I went to an IBM all day once, can't even remember the name of their "web services". At smoke breaks would compare notes with other attendees. I'm not sure we ever understood, but we all agreed the problem was "undefined terms" which I call organic buzz words. Zope is like that to me. I ask what is it and the answer sounds like "Oh, it's oierbv for the zxcvioupo of 7cvn^djh'. Now understand, I know what very well what Python, Apache, PhP, MySQL, IE and javascript do. I just don't know what Zope does. And if the answer is going contain phrases like "brings together" or "sits on top of", don't bother. :-) From thiswillbounce at bumblbee.demon.co.uk Wed Jul 27 20:49:36 2005 From: thiswillbounce at bumblbee.demon.co.uk (Lemming) Date: Thu, 28 Jul 2005 01:49:36 +0100 Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> <2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net> <6DhBe.3077$dU3.691@newsread2.news.pas.earthlink.net> Message-ID: <7qage1h9vve4ba0ub0ka3fuo4nph7j3qv0@4ax.com> On Wed, 13 Jul 2005 23:39:46 GMT, "Hank Oredson" wrote: >In particular I am interested in the EM dataset. Hank, with respect ... Posted to nine newsgroups; fluffy responses when you ask specific questions; evasion when you repeatedly ask for real data ... I regret to say, YHBT. Lemming -- Curiosity *may* have killed Schrodinger's cat. From gsakkis at rutgers.edu Wed Jul 6 13:15:31 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 6 Jul 2005 10:15:31 -0700 Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> <42cbdbde$0$10471$da0feed9@news.zen.co.uk> Message-ID: <1120670131.471176.133020@g14g2000cwa.googlegroups.com> "Steven D'Aprano" wrote: > On Wed, 06 Jul 2005 14:25:30 +0100, Will McGugan wrote: > > No need for the 'premature optimization is the root of all evil' speech. > > I'm not trying to optimize anything - just enquiring about the nature of > > frozenset. If typing 'frozenset' over 'set' gave me a saving in time or > > memory (even if tiny) I would favour immutable sets, where appropriate. > > Well, obviously the "premature optimization" speech just went in one ear > and out the other. "Saving in time or memory" is what optimization is > about. What did you think optimization means? > > set and frozenset have different functionality (one is mutable, the other > is not) and use cases (you use one where you need to dynamically add and > remove items from a set, and the other where you need to use a set as a > key in a dictionary). In most cases, they aren't interchangable. Well, they *may* be interchangable under some conditions, and that was the OP's point you apparently missed. If you don't need to dynamically modify a set and don't add sets as keys in dictionaries, you currently have a choice; both frozenset and set will work. So all other things being equal, it makes sense to ask about the relative performance if the only 'evil' it may introduce can be rectified in a single import. George From bronger at physik.rwth-aachen.de Sat Jul 30 11:40:49 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 30 Jul 2005 17:40:49 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <871x5gs6oy.fsf@wilson.rwth-aachen.de> Message-ID: <87slxwqp32.fsf@wilson.rwth-aachen.de> Hall?chen! Peter Decker writes: > On 7/30/05, Torsten Bronger wrote: > >> I'm aware of it (and there is Wax and maybe a third one). >> Actually it illustrates my point quite well: These projects are >> small and instable (Dabo has a developer basis of very few >> people, Wax has only one); they are even worse documented; they >> add another layer which slows down and requires the end-user to >> install another package; they force you to test even more GUI >> approaches. > > Well, wxPython itself is largely the work of a single person, but > I doubt that many consider that a reason to avoid it. But the developer and contributor base is much larger, so the project has reached the critical mass. > As far as your comment about 'slowing down' the app, I've found > that Dabo and pure-wxPython apps run indistinguishably. Perhaps > there are some microseconds of extra processing, but I sure > haven't noticed it. And I don't think that the comment about > installing another package is fair; *anything* outside of the > standard distribution requires that, and Dabo is no more difficult > than copying to site-packages. I didn't want to say that Dabo is bad. I just wanted to point out that its presence (and the presence of comparable projects) doesn't ease the IMO unfortunate situation with GUI toolkits for Python. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From caleb1 at telkomsa.net Tue Jul 19 17:23:06 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 19 Jul 2005 23:23:06 +0200 Subject: OO design References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: Chris > 1. get arbitrary numerical data (typically large data sets in columnar > format or even via COM from other packages. I generally have to deal with > one or more sets of X,Y data) > 2. manipulate the data (scaling, least squares fitting, means, peaks, > add/subtract one XY set from another etc) > 3. plot data (original set, results of manipulation, scatterplot, > histograms > etc - I use matplotlib) Matplotlib is really coming on. I still use gnuplot out of familiarity (and features, to be sure) but one of these days I'm going to spend a bit of time on Matplotlib. > 4. export data (print, csv, shelve) I do very much the same kind of work with python. I write mostly in Delphi at work, but for processing stuff like this, I always use python when the dataset is not too big and the processing of the data is not too expensive. Despite the awesome Delphi IDE, python with a text editor is *still* more productive (for *me*) in jobs like this. > I have no problem writing bits of functional code to do any of the above. > But for the life of me I can't see how I can hook them altogether in an > OO > based framework that I can build and extend (with more data formats, > manipulations, GUI etc). To be honest, I am probably a poor source of advice here because I think I tend to overuse the class paradigm when often a more sensible approach would be a top-down strategy. I just tend to think in terms of objects, for better or worse. At least python's class declarations are not expensive in terms of setting up, so I tell myself it's ok. Lets look at what you suggested: > class XY: > def read_file > def scale_data > def plot_data > def shelve_data This is exactly the kind of thing I do as well, but maybe separate the dataset from the processing (and put the classes into separate files, if you prefer - I find the "one class per file" idea easier to manage in my editor , Vim) class XYpoint(object): def __init__(self,x=0,y=0): self.x = x self.y = y class Dataset(object): def __init__(self): self.data = [] # Will be a list of XYpoint objects - probably filled in with Gather? def Gather(self,source): pass # You fill this in, using source as you prefer def Scale(self,factorX,factorY): # Filled out with example implementation below for i in range(len(self.data)): self.data[i].x = self.data[i].x * factorX self.data[i].y = self.data[i].y * factorY def Plot(self): pass # Do what you gotta do def Shelve(self): pass # Do what you gotta do class MultipleDatasets(object): def __init__(self): self.datasets = [] # Will be a list of dataset objects, which you must populate def PlotAll(self): for i in self.datasets: i.Plot # How to plot all your datasets, for example [FWIW - This is how I write all my python programs - very very naively and simply. I just cannot remember all the fancy things enough to use when I need to get something done. This is the kind of simple syntax that lured me to python in the first place, and I have a disconcerting feeling about all the "advanced" features for "master" programmers creeping into the language lately, or at least getting discussed - I don't think I am smart enough to absorb it all - CS isn't my area] > But somehow that doesn't feel right, especially when I expect the number > of > methods will grow and grow, which would make the class very unwieldy. I would be interested to know if you think what I wrote "feels" right to you or not - It certainly feels "right" to me, but then that is hardly surprising. In any case, what I presented almost exactly fits how I "think" about the problem, and that is what I want. > bwaha. ? regards Caleb From jgrahn-nntq at algonet.se Wed Jul 6 06:38:02 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 6 Jul 2005 10:38:02 GMT Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> Message-ID: On Sun, 03 Jul 2005 17:35:16 +0100, anthonyberet wrote: ... > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of I use no IDE, just emacs for editing my sources, and a terminal window or two. And CVS for version control. Often I run Python interactively to try out small "one-liners". For example, I don't try to remember the slicing syntax, or what 'list("foo")' means, or if range(0) is legal, etc -- I just try it out interactively. If I get stuck or if the problem is non-trivial, or if I'm writing a standalone module, I use module unittest so I have something easily runnable at all times. This unittest code doesn't even have to be true unit tests -- it can be any speculative code I want, driven by the unittest framework. Between these two (interactive tinkering and unittest-based code) I feel little need for IDEs or 'environments for experimentation'. Others will feel differently, of course. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From elmo13 at jippii.fi Mon Jul 25 10:23:12 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Mon, 25 Jul 2005 17:23:12 +0300 Subject: How can I encode something in base32 preferably very fast? Message-ID: I want to encode a plaindigest or a hexdigest in base 32. Any hints? Elmo From python at rcn.com Sat Jul 23 12:59:12 2005 From: python at rcn.com (Raymond Hettinger) Date: 23 Jul 2005 09:59:12 -0700 Subject: unit test nested functions References: <1122134462.286558.16160@f14g2000cwb.googlegroups.com> Message-ID: <1122137952.092438.34830@f14g2000cwb.googlegroups.com> > > [Andy] > >>How can you unit test nested functions? [Raymond Hettinger] > > For whitebox testing, you could make an inner function visible by > > binding it to the enclosing function's attribute namespace. > > > > def f(x): > > def g(y): > > . . . > > f.g = g # make g visible as an attribute of f > > . . . [Benji York] > Note that when using this technique, f.g will not be bound until after > you call the function: That is a feature, not a bug. The inner function isn't even created until the outer function is run. >>> def f(x): z = 30 def g(y): return 10 return 20 >>> from dis import dis >>> dis(f) 2 0 LOAD_CONST 1 (30) 3 STORE_FAST 1 (z) 3 6 LOAD_CONST 2 (", line 3>) 9 MAKE_FUNCTION 0 12 STORE_FAST 2 (g) 5 15 LOAD_CONST 3 (20) 18 RETURN_VALUE The MAKE_FUNCTION step is where g comes into existence. That is a run-time operation, not compile time. If you are willing to be tricky, it is possible to write an accessor function that goes into f.func_code.co_consts, finds the code object whose co_name attribute is 'g', builds a wrapper function using types.FunctionType, and returns the result for unittesting. But that is not for the faint of heart ;-) Raymond From lutz.horn at gmx.de Tue Jul 5 04:46:07 2005 From: lutz.horn at gmx.de (Lutz Horn) Date: 5 Jul 2005 08:46:07 GMT Subject: what is __init__.py used for? References: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> Message-ID: <3iuvmfFnguasU1@individual.net> * zelzel.zsu at gmail.com: > root\ > system1\ > __init__.py > utilities.py > main.py > other.py ... > I was wonderring ... what is the __init__.py used for ? > This question may seems to be stupid for an expert. The __init__.py is needed for Python to recognize the system1 directory as an importable module. Lutz From http Sat Jul 30 05:17:12 2005 From: http (Paul Rubin) Date: 30 Jul 2005 02:17:12 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> Message-ID: <7xwtn87iw7.fsf@ruckus.brouhaha.com> Stefan Rank writes: > I am sorry if this has already been proposed (I am sure it has). > Why not substitue python-lambdas with degenerated generator expressions:: > > (lambda x: func(x)) == (func(x) for x) I don't think I've seen that one before, and FWIW it's kind of cute. But what's wrong with leaving lambdas the way they are? Anyone who can understand generator expressions can understand lambda. I don't see any point in trying to improve on lambda, without actually fixing its main problem, which is the inability to create multi-statement closures. From tim.peters at gmail.com Thu Jul 14 20:31:57 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 14 Jul 2005 20:31:57 -0400 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? In-Reply-To: <42d6dd7a$0$11014$9b622d9e@news.freenet.de> References: <11ddckucctde603@corp.supernews.com> <42d6dd7a$0$11014$9b622d9e@news.freenet.de> Message-ID: <1f7befae050714173184a1cfd@mail.gmail.com> [Grant Edwards] >> 1/0 is defined by the standard as +Inf and 0/0 is NaN. [Martin v. L?wis] > I wonder why Tim hasn't protested here: Partly because this thread (unlike the other current thread on the topic) isn't moving toward making progress, and I have little time for this. But mostly because Python's fp design was in no way informed by 754, so logic-chopping on the 754 standard wrt what Python actually does is plainly perverse <0.5 wink>. > I thought this was *not* the case. I thought IEEE 754 defined +Inf and NaN > as only a possible outcome of these operations with other possible > outcomes being exceptions... In that case, Python would comply to IEEE > 754 in this respect (although in a different way than the C implementation on > the same system). Ya, and Unicode defines 16-bit little-endian characters . Seriously, the 754 standard is quite involved, and there's just no visible point I can see to trotting out its elaborate details here. If Python claimed to support 754, then details would be important. Short course wrt this specific point: there's no reasonable way in which Python's float arithmetic can be said to comply to IEEE 754 in this case, neither in letter nor spirit. The decimal module does, though (mutatis mutandis wrt base). From wpog at hoobydooby.com Sun Jul 10 15:52:12 2005 From: wpog at hoobydooby.com (wpog) Date: Sun, 10 Jul 2005 19:52:12 GMT Subject: An absolute Newbie question References: Message-ID: WOW!!! I really appreciate the immediate response from the community!!! I thank you all for all the help, and now I can start programming, and I also now have a resource for help for a Newbie;-) Later on I will broach the subject of creating .exe programs so that anyone can run them on Windows, but that won't be for a while yet, but I did download ":cx_Freeze-3.0.1-win32-py24"; however, I don't have a clue on what the hell I'm doing yet, so I'll get to that later. Anyway, I once again thank you all for the support, and suggestions, and I hope to actually create something that people might use, like a magic 8 ball generator!;-p Best Regards, wpog "Scott Durkin" wrote in news:mailman.1570.1121016355.10512.python-list at python.org: > wpog, > > In IDLE, go to the File menu and select New Window. You can write > your program there. Just save the file with the extension .py, such > as hello.py > > Once the program is written, you can save the changes and press F5 to > run the script. > > If you haven't checked out the links below, you might want to refer to > them: > > http://www.ibiblio.org/obp/thinkCSpy > http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html > > Scott Durkin > > > -------------------------------------------------------------------- > S c o t t J. D u r k i n > -------------------------------------------------------------------- > > Computer Science |||| Preston Junior High > > sdurkin at psdschools.org |||| http://staffweb.psdschools.org/sdurkin > ____________________________________________________________________ > ___ _ ___ _ ___ _ ___ _ ___ _ > [(_)] |=| [(_)] |=| [(_)] |=| [(_)] |=| [(_)] |=| > '-` |_| '-` |_| '-` |_| '-` |_| '-` |_| > /mmm/ / /mmm/ / /mmm/ / /mmm/ / /mmm/ / > |____________|____________|____________|____________| > | | | > ___ \_ ___ \_ ___ \_ > Computer Room [(_)] |=| [(_)] |=| [(_)] |=| > Lab N205 '-` |_| '-` |_| '-` |_| > /mmm/ /mmm/ /mmm/ > ____________________________________________________________________ > > 970.419.7358 |||| 2005-2006 > From flupke at nonexistingdomain.com Wed Jul 27 02:58:45 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 27 Jul 2005 06:58:45 GMT Subject: finding out the calling function In-Reply-To: <2%FFe.154619$cb5.8344628@phobos.telenet-ops.be> References: <2%FFe.154619$cb5.8344628@phobos.telenet-ops.be> Message-ID: flupke wrote: > Hi, > > i have a property in a class that gets changed > and i would want to know who changes it. > Is there a way i can find out the calling function of a property? > > Thanks, > Benedict I solved it by using import traceback, sys traceback.print_stack() in the property However, i'm not sure this is the best way. I also tried to use the print_tb funtion from the traceback function traceback.print_tb(sys.last_traceback) This produces an error AttributeError: 'module' object has no attribute 'last_traceback' So how can i pass a valid "traceback" object to the print_tb function and where do i find one? Thanks, Benedict From grante at visi.com Thu Jul 14 18:09:19 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 14 Jul 2005 22:09:19 -0000 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? References: <11ddckucctde603@corp.supernews.com> <42d6dd7a$0$11014$9b622d9e@news.freenet.de> Message-ID: <11ddokflq699v4b@corp.supernews.com> On 2005-07-14, Martin v. L?wis wrote: >> 1/0 is defined by the standard as +Inf and 0/0 is NaN. > > I wonder why Tim hasn't protested here: I thought this was *not* > the case. I thought IEEE 754 defined +Inf and NaN as only a possible > outcome of these operations with other possible outcomes being > exceptions... The "exceptions" specified by the standard aren't required, but it's "strongly recommended" that they be provided as options for the programmer. If provided, I believe they are to be resumable so that the user can determine what operation was attempted on what operands and return a result if desired. > In that case, Python would comply to IEEE 754 in this respect My recollection is that returning Inf and NaN is to be the default behavior, and a resumable exception is a recommended option. > (although in a different way than the C implementation on the > same system). I can't find my copy of the standard at the moment, though I did just re-read Goldberg's 1991 discussion of the standard. -- Grant Edwards grante Yow! My Aunt MAUREEN was at a military advisor to IKE & visi.com TINA TURNER!! From spam.csubich+block at block.subich.spam.com Thu Jul 21 00:51:45 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 21 Jul 2005 00:51:45 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: References: Message-ID: Jp Calderone wrote: > In the particular case of wxWidgets, it turns out that the *GUI* blocks > for long periods of time, preventing the *network* from getting > attention. But I agree with your position for other toolkits, such as > Gtk, Qt, or Tk. Wow, I'm not familiar with wxWidgets; how's that work? From paolo_veronelli at tiscali.it Thu Jul 28 06:27:57 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Thu, 28 Jul 2005 12:27:57 +0200 Subject: Mailing list question Message-ID: <42E8B32D.5030306@tiscali.it> Puzzling. I have subscribed this list with an address int the gmail.com domain, and I receive your postings there,but it seems I can send messages with THIS address ,and I don't receive my messages sent with the gmail account. I don't receive any "python.org mailing list memberships reminder" on this address, while I receive in the gmail one. I didn't touch the options ,so I should receive my messages. Sinking in the sea of impotence. Thanks for help ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From cmedcoff at hotmail.com Mon Jul 18 18:09:44 2005 From: cmedcoff at hotmail.com (chuck) Date: 18 Jul 2005 15:09:44 -0700 Subject: stdin/stdout fileno() always returning -1 from windows service In-Reply-To: References: <1121650980.574867.244590@g44g2000cwa.googlegroups.com> <1121697436.413522.268110@g49g2000cwa.googlegroups.com> Message-ID: <1121724584.695701.287450@g43g2000cwa.googlegroups.com> "common wisdom".... interesting. The value of the closed attribute is "False" when tested from within the service. Still digging.... From gsakkis at rutgers.edu Fri Jul 1 10:31:34 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 07:31:34 -0700 Subject: Question about Python References: <42c54149$1@griseus.its.uu.se> Message-ID: <1120228293.990893.27790@g44g2000cwa.googlegroups.com> Backwards compatibility is addressed in several Python Enhancement Proposals (PEPs): http://www.python.org/peps/pep-0005.html http://www.python.org/peps/pep-0236.html http://www.python.org/peps/pep-0004.html http://www.python.org/peps/pep-0291.html You also may want to check related threads in c.l.py, e.g. http://tinyurl.com/d3lfx. HTH, George From http Sat Jul 30 04:40:37 2005 From: http (Paul Rubin) Date: 30 Jul 2005 01:40:37 -0700 Subject: keylogger in Python References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> Message-ID: <7xy87optyy.fsf@ruckus.brouhaha.com> "Jay" writes: > ok, i thought for 2 seconds i might have created a Keylogger in python > but i still have one major think stopping me... PYTHON. when i run the > program i have python create a file named keylog2.log and it then logs > all keys pressed/typed in the python IDE into that file. All i want to > know now is how do i hide or background python so that it will log all > the keys pressed outside of Python. You are completely confused and keyloggers don't work anything like that. Why do you want to log keystrokes anyway? From newtonapple at gmail.com Sun Jul 31 23:16:47 2005 From: newtonapple at gmail.com (Apple) Date: 31 Jul 2005 20:16:47 -0700 Subject: Determining method type given its string name presentation and itscorresponding object reference. In-Reply-To: <42ed8b67@news.eftel.com> References: <1122853524.374812.326580@g14g2000cwa.googlegroups.com> <42ed8b67@news.eftel.com> Message-ID: <1122866207.771321.151120@g47g2000cwa.googlegroups.com> "or perhaps callable(getattr(obj, strg, None)) if the need is related to an unknown string which may be a callable attribute of an object whose class is unknown ..." Hm.. the problem is I cannot call getattr() at all. Because getattr() will call my __repr__() which will call another m() that will eventually call getattr() again.. It's an infinite recursion. In general, I think every time you try to qualify a method attribute, e.g. obj.method, it'd actually end up making a call to __repr__()... obj.method would usually get you this output: () More or less I am trying to understand what getattr did to figure out the name "method" is actually a method (bounded or not). This way I can avoid the recursive call to __repr__(). I hope this clarifies my question a bit? Thanks a lot for the help ;) From utabintarbo at gmail.com Tue Jul 19 15:17:17 2005 From: utabintarbo at gmail.com (utabintarbo at gmail.com) Date: 19 Jul 2005 12:17:17 -0700 Subject: How to kill easygui dialog? Message-ID: <1121800637.589080.210700@g47g2000cwa.googlegroups.com> I am using an easygui(http://www.ferg.org/easygui/index.html) dialog (enterbox) to retrieve some info from a user. The program then goes on and does a bit of processing, sometimes for several minutes. In the meantime, the dialog stays there, dead but visible. I would prefer that either another dialog ("Processing....") would be shown while background stuff happens, or that the current dialog would simply disappear. Ideas? TIA, Bob From rrr at ronadam.com Fri Jul 8 15:21:39 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 08 Jul 2005 19:21:39 GMT Subject: Use cases for del In-Reply-To: <1120825627.498017.19370@g47g2000cwa.googlegroups.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <1120825627.498017.19370@g47g2000cwa.googlegroups.com> Message-ID: <7nAze.187987$IO.122406@tornado.tampabay.rr.com> George Sakkis wrote: > > How about using the right way of comparing with None ? > > x = None > t = time.time() > for i in range(1000000): > if x is None: > pass > print 'is None:',time.time()-t > > I get: > > None: 0.549999952316 > String: 0.498000144958 > is None: 0.450000047684 Yep, that occurred to me after I posted. :-) >>Anyway, time to call it a night so tomorrow I don't make anymore silly >>mistakes on comp.lang.python. :) > > > That would be a great idea ;-) An even greater idea would be to give up > on this "None should mean undefined" babble; it looks like a solution > looking for a problem and it raises more complications than it actually > solves (assuming it does actually solve anything, which is not quite > obvious). Already gave up on it as a serious idea quite a while ago and said so in several posts. From two days ago... in this same thread ... I said. >>Yes, I agree using None as an alternative to delete currently is >>unacceptable. Cheers, Ron From callmebill at gmail.com Thu Jul 14 14:03:42 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 14 Jul 2005 11:03:42 -0700 Subject: Native ODBC access for python on linux? Message-ID: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> I'm getting my feet wet with making Python talk to MySQL via ODBC. I started on Windows, and it went smoothly enough due to the ODBC stuff that apparently is native to Python at least on windows (I've been following ch. 13 of Mark Hammond's py on win32 book). But now I'm trying to do equivalent stuff on linux (Fedora Core 3) with python 2.3.5 and mysql. I'd like to stick with packages that are native to python, rather than relying on external stuff (e.g., MySQLdb and mxODBC). Is this possible, or do I have to use 3rd party pieces to use ODBC with Python under linux? As an aside, I've only used ODBC to access db's, period. I've never used, for example, MySQL's API for working with a MySQL db. I'm curious to see what that looks like, if anyone has any examples (python, c, or otherwise). Thanks in advance for any help. -Bill From slug57_98 at yahoo.com Mon Jul 18 21:21:20 2005 From: slug57_98 at yahoo.com (Chad Best) Date: Tue, 19 Jul 2005 01:21:20 GMT Subject: Help with images References: <1121731806.578272.174590@z14g2000cwz.googlegroups.com> Message-ID: "max" wrote in message news:Xns9697D48FD7131notrealmail at 216.168.3.44... > "Chad" wrote in > news:1121731806.578272.174590 at z14g2000cwz.googlegroups.com: > >> I have installed a TWAIN module(from >> http://twainmodule.sourceforge.net) today and figured out how to >> acquire an image. The only problem is that the image is way too >> large in terms of filesize. It is over 1MB. >> >> I can do either one of two things. Try to figure out how to >> manupilate the image with this module(which I am been doing all >> day) or just use a module that can compress jpegs. Can anybody >> help? >> >> > > Check out PIL: > http://www.pythonware.com/products/pil/ > http://www.pythonware.com/library/pil/handbook/ > > > but also be sure to read the "Setting Capababilities" section of this > document: > > http://twainmodule.sourceforge.net/docs/caps.html > > max Max, I have read the document about setting the capabilities. I have also tried the twexplore.exe to see the capabilities of my scanner. The twexplore.exe will give you the option to save the file or "retrieve it natively." On the window where it gives you this option, it also allows you to set attributes like bit size, or compression. No matter how many times I change these options, it still gives an image with the same filesize. The reason, I mentioned that was because those attributes that you can change correlate to the ICAP values. If changing those attributes in twexplore.exe does not do anything, then I am thinking that it probably won't do anything when I write a script either. From jan.danielsson at gmail.com Sun Jul 31 21:11:53 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Mon, 01 Aug 2005 03:11:53 +0200 Subject: Escaping certain characters In-Reply-To: References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> <42eca481$1@griseus.its.uu.se> <42ed452f$1@griseus.its.uu.se> Message-ID: <42ed7567$1@griseus.its.uu.se> Robert Kern wrote: [---] >> I need to escape '\n', '"', '[' and ']'. I finally went with a few of >> these: >> string.replace('\n', '\\n') >> string.replace('"', '\\"') >> ... >> >> I assume that's good enough, but I somehow expected there to exist >> some form of "insert your conversion table here" built-in string escaper. > > Write a codec. Is that what string.encode() uses? Some behind-the-scenes "codec"? I tried searching for it, but could only find UTF/Unicode-related information. Is it in the normal python documentation? Semi-Offtopic: The "search" facility in the Python help has stopped functioning for me (I'm using XP on this system). No matter what I search for, I get no results. A week ago, I got a lot of hits for almost anything I searched for. Anyone seen this behavior, and knows what to do about it? -- Kind Regards, Jan Danielsson Te audire no possum. Musa sapientum fixa est in aure. From fowlertrainer at anonym.hu Wed Jul 6 05:23:52 2005 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Wed, 06 Jul 2005 11:23:52 +0200 Subject: Python exception hook simple example needed In-Reply-To: References: Message-ID: <42CBA328.3000102@anonym.hu> Hi ! I think I found an example: import sys def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook print "yyy" sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... print "xxx" traceback.print_exception(type, value, tb) # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info But I don't know it is working or not.... Thanx: ft > > T?rgy: > Re: Python exception hook simple example needed > Felad?: > Benji York > D?tum: > Tue, 05 Jul 2005 10:34:23 -0400 > C?mzett: > python-list at python.org > > C?mzett: > python-list at python.org > > > fowlertrainer at anonym.hu wrote: > >> If anyone has an idea, how to I catch exceptions globally, please >> write me. > > > I believe there is an example of this in the demo that comes with > wxPython (don't have an install handy to check). > -- > Benji York > > From beliavsky at aol.com Sat Jul 9 10:43:53 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 9 Jul 2005 07:43:53 -0700 Subject: FORTRAN like formatting References: <0DF798CBF125BF4AA1227F26431C29BD01A32ECA@pnlmse27.pnl.gov> <7fhuc19d6dma38457scg5g7pp18bqrjd0g@4ax.com> Message-ID: <1120920233.895333.180730@g49g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > > On 7/8/05, Einstein, Daniel R wrote: > > > > > > > > > Hi, > > > > > > Sorry for this, but I need to write ASCII from my Python to be read by > > > FORTRAN and the formatting is very important. Is there any way of doing > > > anything like: > > > > > > write(*,'(3(" ",1pe20.12))') (variable) > > > > > Which Fortran compiler? I know VMS Fortran was very friendly, > when specifying "blanks not significant" or something like that... To > read three floating numbers (regardless of format) merely required > something like: > > read(*, '(bn,3f)') a, b, c > > (or 'bs' for blanks significant -- I forget which one enabled free > format input processing) Fortran 77 and later versions have "list-directed" I/O, so the OP could simply write read (inunit,*) a,b,c if the numbers in his input file are separated by spaces or commas. An online reference is http://docs.hp.com/cgi-bin/doc3k/B3150190022.12120/9 . From mcherm at gmail.com Tue Jul 5 15:11:47 2005 From: mcherm at gmail.com (mcherm at gmail.com) Date: 5 Jul 2005 12:11:47 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: <1120590707.093007.175330@o13g2000cwo.googlegroups.com> Up until a few years ago, I ran the computer science department at a high-school. I provided support for the English teachers who taught *all* students -- but they taught things like the use of a word processor or the internet, and never covered the meaning of "lambda". I taught a computer applications course which was taken by only small fraction of the students (<10%) but there I taught things like the use of photo-editing software, creating web sites, and the use of simple databases; I never covered the meaning of "lambda". I also taught the programming class (taken by only a dozen or so students per graduating class) -- students learned basic concepts like variables, looping, up through fancier bits like a couple different sorting algorithms. But I didn't cover the meaning of "lambda". And I also taught the "AP" computer course (taken by an average of just 4 students per year!), in which I explained things like object oriented programming and recursion and managed to get the students to the level where they could work together as a group to write a moderately complex program, like a simple video game. And I didn't teach the meaning of "lambda", nor was it covered by the "AP" exam, which is supposed to be equivalent to a single college-level course in computer programming. So I'd say that it's a pretty obscure name that most people wouldn't know. And besides, "def" isn't a "magic" word... it's an abreviation for "define"... I hope that any student who didn't understand a word as common as "define" wouldn't have graduated from our school. -- Michael Chermside From richie at entrian.com Mon Jul 4 03:56:01 2005 From: richie at entrian.com (Richie Hindle) Date: Mon, 04 Jul 2005 08:56:01 +0100 Subject: Better console for Windows? In-Reply-To: References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> <5aj2c11l5vl4qds031uj7ucikikcf7uvji@4ax.com> <42c60f3b.300522458@news.oz.net> Message-ID: [Richie] > does anyone know of a way to scroll a Command Prompt window using the keyboard? [Bengt] > Alt-spacebar, e, l, (uparrow/downarrow)*, Esc > (lower case L)--^ ^^^^^^^^^^^^^^^^^--does the scrolling. Esc ends the scrolling mode. [Christos] > Damn! it says Scroll in there in the system menu, doesn't it? Talk > about blindness... Me too! Many thanks, Bengt. -- Richie Hindle richie at entrian.com From steve at REMOVETHIScyber.com.au Fri Jul 29 19:47:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 30 Jul 2005 09:47:04 +1000 Subject: On fighting fire with fire... References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: On Thu, 28 Jul 2005 17:24:06 -0400, Asad Habib wrote: > Well, even if you are a hobbyist, that does not excuse you from being > civil. After all, we are all humans beings that deserve to be treated with > respect. Professional, hobbyist, vagabond, ogre, instigator, troll ... > THERE IS NO EXCUSE ... please treat others with respect. And yet your earlier angry, aggressive reply to Robert Kern was not very respectful, don't you think? Your assumption that Robert is wrapped up in an "academic cocoon" was uncalled for, and viciously aggressive pacifism like you have displayed is almost as bad as aggressive flaming, and far worse than Robert's self-depreciating humour. In any case, I don't agree with you that all people deserve the same amount of respect. Respect is rare currency, and has to be earned, not just given away to anyone. -- Steven. From rkern at ucsd.edu Wed Jul 20 11:53:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 08:53:16 -0700 Subject: What does "::" mean? In-Reply-To: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> References: <311b5ce1050719175054e268b6@mail.gmail.com> <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Message-ID: qwweeeit at yahoo.it wrote: > Hi Robert, > I didn't succeed in reversing a string with the "full form" you > proposed: > live[len(live)-1:-1:-1] # where live="live" > The result is an empty string. > To reverse "live" (in a "full form"), I have to put a char in front of > the string and...: > ('x'+live)[len(live)+1:0:-1] # --> "evil" > Is it due to the Python's version (I still have 2.3.4)? No, it's because I am stupid. There isn't a full form. live[len(live)::-1] is the closest expansion. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From spam.csubich+block at block.subich.spam.com Mon Jul 11 09:00:50 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Mon, 11 Jul 2005 09:00:50 -0400 Subject: decorators as generalized pre-binding hooks In-Reply-To: <1121084778.253840.101070@z14g2000cwz.googlegroups.com> References: <42d02c21.231516573@news.oz.net> <1121034087.932596.221010@g43g2000cwa.googlegroups.com> <1121084778.253840.101070@z14g2000cwz.googlegroups.com> Message-ID: <%2uAe.59388$Tt.29694@bignews3.bellsouth.net> Kay Schluehr wrote: > I think it would be a good idea to pronounce the similarity between > function decorators and metaclasses. Metaclasses were once introduced > as an arcane art of fuzzy bearded hackers or supersmart 'enterprise > architects' that plan at least products of Zope size but not as a tool > for the simple programmer on the street. But maybe they should be and > there should also be librarys of them representing orthogonal > customizations ready for plug in. In which case, I point out the need for better, more accessible documentation. The Python 2.4 tutorial, for example, doesn't mention them at all as far as I've noticed. From kboruff at _*_&&_*_optonline.net Sun Jul 24 09:36:28 2005 From: kboruff at _*_&&_*_optonline.net (Keith P. Boruff) Date: Sun, 24 Jul 2005 09:36:28 -0400 Subject: FAQ? In-Reply-To: <1122212120.494718.221890@z14g2000cwz.googlegroups.com> References: <1122212120.494718.221890@z14g2000cwz.googlegroups.com> Message-ID: gene tani wrote: > Here's my trove of FAQ/Gotcha lists > > http://www.ferg.org/projects/python_gotchas.html > http://zephyrfalcon.org/labs/python_pitfalls.html > http://zephyrfalcon.org/labs/beginners_mistakes.html > > > http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html > http://www.norvig.com/python-iaq.html > http://www.faqts.com/knowledge_base/index.phtml/fid/245 > http://amk.ca/python/writing/warts > Thanks Gene. I'll give thme a look. KPB From bruce+usenet at cenderis.demon.co.uk Wed Jul 20 18:33:05 2005 From: bruce+usenet at cenderis.demon.co.uk (Bruce Stephens) Date: Wed, 20 Jul 2005 23:33:05 +0100 Subject: Lots of pdf files References: <7xu0iptbi7.fsf@ruckus.brouhaha.com> Message-ID: <878y01az1a.fsf@cenderis.demon.co.uk> Paul Rubin writes: > Greg Lindstrom writes: >> There does not appear to be a simple way to merge many pdf's into one. > > There's probably some way to do it with pstops or some related program > or set of programs. The pdftk manpage gives this as one of its examples: pdftk *.pdf cat output combined.pdf From mwm at mired.org Thu Jul 21 19:41:11 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 21 Jul 2005 19:41:11 -0400 Subject: Generating images with text in them References: Message-ID: <86irz3ralk.fsf@bhuda.mired.org> zen19725 at zen.co.uk (phil hunt) writes: > On Thu, 21 Jul 2005 02:44:03 -0500, Terry Hancock wrote: >>While bitmap font files are not copyrightable, there are license issues >>with most of the "nicer" fonts you are probably talking about. > > Oh? I can understand them being copyrighted; but if they are not > copywritable, what licnese issues are there? In any case, there > presumably are not license issues with the fonts that come with a > standard GNU/Linux distribution such as SuSE 9.1, which is what I am > using. I haven't looked in a while; the situation may have changed. The font files per se are copyrightable, and you may have licensing issues if you want to give those away. The *output* from the font files - the bitmaps that Terry mentions - are not copyrightable. You are free to do whatever you want with the images you get from them, including scan them all in and create a bitmapped font file, or scan them in in multipe sizes and cons up a competing font. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From edvard+news at majakari.net Wed Jul 13 03:47:40 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 13 Jul 2005 10:47:40 +0300 Subject: removing list comprehensions in Python 3.0 References: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> Message-ID: <87ackrf8pv.fsf@titan.staselog.com> Steven Bethard writes: > $ python -m timeit "for x in (i for i in xrange(10)): y = x" > 100000 loops, best of 3: 4.75 usec per loop Yowza! One of the features I really liked in Perl has shored Python island somewhere in the 2.4'ies, it seems[1]. Thanks for the tip! PS. In case it wasn't clear what I referred to, it was the ability to run given module as a script. Of course you could supply full path to timeit.py: $ python2.3 /usr/lib/python2.3/timeit.py \ "for x in [i for i in xrange(10)]: y = x" 100000 loops, best of 3: 9.96 usec per loop But using -m makes it much more convenient. Footnotes: [1] Well, not exactly equal to -M in Perl, but close enough for timing stuff -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! You shouldn't verb verbs. From newsgroups at jhrothjr.com Mon Jul 4 09:08:33 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 4 Jul 2005 07:08:33 -0600 Subject: Unicode drives me crazy... References: Message-ID: <11cid6nml3ecb4f@news.supernews.com> wrote in message news:mailman.1311.1120477323.10512.python-list at python.org... > Hi ! > > I want to get the WMI infos from Windows machines. > I use Py from HU (iso-8859-2) charset. > > Then I wrote some utility for it, because I want to write it to an XML > file. > > def ToHU(s,NoneStr='-'): > if s==None: s=NoneStr > if not (type(s) in [type(''),type(u'')]): > s=str(s) > if type(s)<>type(u''): > s=unicode(s) > s=s.replace(chr(0),' '); > s=s.encode('iso-8859-2') > return s > > This fn is working, but I have been got an error with this value: > 'Kommunik\xe1ci\xf3s port (COM1)' > > This routine demonstrates the problem > > s='Kommunik\xe1ci\xf3s port (COM1)' > print s > print type(s) > print type(u'aaa') > s=unicode(s) # error ! > > This is makes me mad. > How to I convert every objects to string, and convert (encode) them to > iso-8859-2 (if needed) ? > > Please help me ! As Tim Golden already explained, you're getting a unicode object from the WMI interface. The best design help I can give is to either convert it to iso-8859-2 at the point you get the object and do your entire program with iso-8859-2 encoded strings, or do your entire program with unicode objects and encode them as iso-8859-2 strings whenever you want to write them out. Trying to do your conversion in the middle will lead to excessive complexity, with the resulting debugging problems. If you do go the unicode route, you must remember that any method or function that's defined to return a string will most likely throw an exception. This includes str()! Whether or not the print statement will work depends on a number of factors in how your Python installation was set up. HTH John Roth > Thanx for help: > ft From steve at REMOVETHIScyber.com.au Sun Jul 3 04:36:51 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 18:36:51 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> <1120362708.992006.49040@g14g2000cwa.googlegroups.com> Message-ID: On Sun, 03 Jul 2005 00:39:19 -0400, Christopher Subich wrote: > Devan L wrote: >> sum(sequence[0] + [1/element for element in sequence[1:]]) >> >> I think that should work. > > That won't work, because it misses the x*y part of the expression > (x[n]*x[n+1] + 1/x[n+1], for people who haven't immediately read the > grandparent). > > Personally, I think demanding that it be writable as a sum (or product, > or any, or all) is a false standard -- nobody's claimed that these would > replace all cases of reduce, just the most common ones. Er, excuse me, but that is EXACTLY what Devan claimed. Quote: "With the exception of reduce(lambda x,y:x*y, sequence), reduce can be replaced with sum, and Guido wants to add a product function." -- Steven. From chr0m3spartan at yahoo.com Fri Jul 1 21:36:31 2005 From: chr0m3spartan at yahoo.com (Thomas) Date: 1 Jul 2005 18:36:31 -0700 Subject: $6 into $1000ands this actually works! Message-ID: <1120268191.451376.48310@g47g2000cwa.googlegroups.com> PAYPAL VERIFIES THAT THIS $6 INVESTMENT SCHEME IS 100% LEGAL AND IS A BIG HIT THIS YEAR SEE THEIR NOTE BELOW OR ASK THEM DIRECTLY... THIS SCHEME MIGHT TAKE 15-30 MINUTES AND JUST $6, BUT IT IS 100% WORTH IT TO MAKE THOUSANDS SO QUICKLY. THIS IS NOT ANOTHER SCAM THAT TAKES LOTS OF YOUR HARD EARNED MONEY; THIS IS A NO RISK INVESTMENT THAT WILL MAKE YOU THOUSANDS OF DOLLARS VERY EASILY AND QUICKLY. >From PayPal: "Dear Member, it has come to our attention that there is a paypal scheme floating around at the moment you may have heard or seen the $6 scheme. You may have even taken part in it well we have been asked a lot of questions about this scheme the answer is yes it does work and yes it is safe to use providing you follow the rules it is legal and has made a big hit on the internet this year. If you would like to take part in this scheme or would like a bit more information then please see the attached file that was kindly donated to us. Thank you for using PayPal!" TURN $6 INTO $15,000 IN ONLY 30 DAYS...HERES HOW! You have most likely seen or heard about this project on TV programs such as 20/20 and Oprah, or you may have read about it in the Wall Street Journal. If not, here it is below - revealed to you in step-by-step detail. This program is by no means new. It has been in existence in many forms for at least a decade. But in the early days, it required a lot more time and effort, as well as an investment of a few hundred dollars. However, thanks to PayPal and the Internet, the investment is now virtually ZERO! And what's more, the entire process is FASTER, EASIER, and MORE LUCRATIVE than it has EVER been! Below is the email sent to me: How to Turn $6 into $15,000 in 30 Days with PayPal I WAS SHOCKED WHEN I SAW HOW MUCH MONEY CAME FLOODING INTO MY PAYPAL ACCOUNT I turned $6 into $14,706 within the first 30 days of operating the business plan that I am about to reveal to you free of charge. If you decide to take action on the following instructions, I will GUARANTEE that you will enjoy a similar return! STILL NEED PROOF? Here are just 3 testimonials from the countless individuals who decided to invest nothing more than $6 and half an hour of their time to participate in this program: "What an amazing plan! I followed your instructions just 3 weeks ago, and although I haven't made 15 grand yet, I'm already up to $9,135. I'm absolutely gob smacked." -Pam Whittemore , Ohio "Well, what can I say?... THANK YOU SO MUCH! I sent 40 e-mail's out like you said and then I just forgot about the whole thing. To be honest, I didn't really think anything would come of it. But when I checked my paypal account a week later, there was over $5,000 in it! After 30 days I now have over $11,000 to spend! I can't thank you enough!"-Juan Tovar, NY, NY "I was shocked when I saw how much money came flooding into my paypal account. Within 3 weeks my account balance has ballooned to $12,449. At first I thought there had been some sort of error with my account!" -Richard Barrie, Boulder, CO The only things you will need are: An email address. A Business PayPal account with at least $6 deposited in it, and just 15 to 30 minutes of your time. This program takes just half an hour to set up. After that, there is absolutely no work whatsoever to do on your part. You have absolutely NOTHING to lose, and there is NO LIMIT to the amount of income you can generate from this one single business program. Let's get started, just follow the instructions exactly as set out below and then prepare yourself for a HUGE influx of cash over the next 30 days! Here's what you need to do. . . REQUIREMENTS #1) an email address #2) a Premier or Business PayPal account STEP #1 - Setting up your FREE PayPal Account It's extremely safe and very easy to set up a FREE PayPal account! Copy and paste this to the address bar https://www.paypal.com (notice the secure "https" within the link) Be sure to sign up for a free PREMIER or BUSINESS account (and not just a PERSONAL account) otherwise you won't be able to receive credit card payments from other people. STEP #2 - Sending PayPal money "It is an undeniable law of the universe that we must first give in order to receive." Now all you have to do is send $1.00 by way of PayPal to each of the six email addresses listed below. Make sure the subject of the payment says... *PLEASE PUT ME ON YOUR EMAIL LIST* (this keeps the program 100% legal.. so please don't forget!) Note: (If you do not see the full email address for the 6 members, just hit reply To this email and they will show up.) (Just in case you still haven't opened your PayPal account yet, use this link to open one in your name), https://www.paypal.com #1) aacjr2004 at yahoo.com #2) faithmichelle_mo at yahoo.com #3) reesefork at yahoo.com #4) artofficial at grics.net #5) wingman9 at shaw.ca #6) chr0m3spartan at yahoo.com Remember, all of this is ABSOLUTELY LEGAL! You are creating a service! If you have any doubts, please refer to Title 18 Sec. 1302 & 1241 of the United States Postal laws. STEP #3 - Adding Your Email Address After you send your six $1.00 payments, it's your turn to add your email address to the list! Take the #1) email off the list that you see above, move the other addresses up one (6 becomes 5 & 5 becomes 4, etc) then put YOUR email address (the one used in your PayPal account) as #6) on the list. **MAKE SURE THE EMAIL YOU SUPPLY IS EXACTLY AS ITAPPEARS IN YOUR PAYPAL ACCOUNT.** STEP #4 - The Pure Joy of Receiving PayPal Money! You are now ready to post your copy of this message, to at least 200 newsgroups, message boards, etc. (I think there are close to 32,000 groups) All you need is 200, but remember, the more you post, the more money you make - as well as everyone else on the list! In this situation your job is to let as many people see this letter as possible. So they will make you and me rich!!!! You can even start posting the moment your email is confirmed. Payments will still appear in your PayPal account even while your bank account is being confirmed. HOW TO POST TO NEWSGROUPS & MESSAGE BOARDS Step #1) You do not need to re-type this entire letter to do your own posting. Simply put your CURSOR at the beginning of this letter and drag your CURSOR to the bottom of this document, and select 'copy' from the edit menu. This will copy the entire letter into your computer's temporary memory. Step #2) Open a blank 'Notepad' file and place your cursor at the top of the blank page. From the 'Edit' menu select 'Paste'. This will paste a copy of the letter into notepad so that you can add your email to the list. Step #3) Save your new Notepad file as a .txt file. If you want to do your postings in different sittings, you'll always have this file to go back to. Step #4) Use Netscape or Internet Explorer and try searching for various newsgroups, on-line forums, message boards, bulletin boards, chat sites, discussions, discussion groups, online communities, etc. EXAMPLE: go to any search engine like yahoo.com, google.com, altavista.com, excite.com - then search with subjects like ?millionaire message board? or ?money making message board? or ?opportunity message board? or ?money making discussions? or ?business bulletin board? or ?money making forum? etc. You will find thousands & thousands of message boards. Click them one by one then you will find the option to post a new message. Step #5) Visit these message boards and post this article as a new message by highlighting the text of this letter and selecting 'Paste' from the 'Edit' menu. Fill in the Subject, this will be the header that everyone sees as they scroll thru the list of postings in a particular group, click the post message button. You're done with your first one! Congratulations! THAT'S IT!! All you have to do is jump to different newsgroups and post away. After you get the hang of it, it will take about 30 seconds for each newsgroup! REMEMBER, THE MORE NEWSGROUPS AND/OR MESSAGE BOARDS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200** That's it! You will begin receiving money within days! **JUST MAKE SURE THE EMAIL YOU SUPPLY IS EXACTLY AS IT APPEARS ON PAYPAL.** $$$$$ NOW THE WHY PART: Out of 200 postings, say I receive only 5 replies (a very low example). So then I Made $5.00 with my email at #6 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my email at #5 and only 5 persons respond to each of the original 5, that is another $25.00 for me, now those 25 each make 200 MINIMUM posts with my email at #4 and only 5 replies each, I will bring in an additional $125.00! Now, those 125 persons turn around and post the MINIMUM 200 with my email at #3 and only receive 5 replies each, I will make an additional $625.00! OK, now here is the fun part, each of those 625 persons post a MINIMUM 200 letters with my email at #2 and they only receive 5 replies that just made me $3,125.00!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my email at #1 and if still 5 persons per 200 newsgroups react I will receive $15,625.00! With an original investment of only $6.00! AMAZING!! When your email is no longer on the list, you just take latest posting in the newsgroups, and send out another $6.00 to emails on the list, putting your email at number 6 again. And start posting again. The thing to remember is, thousands of people all over the world are joining the internet and reading these articles everyday, JUST LIKE YOU are now!! So can you afford $6?? And see if it really works?? I think so? People have said,what if the plan is played out and no onesends you the money? So what are the chances of that happening when there are tons of new honest users and new honest people who are joining the internet and newsgroups everyday and are willing to give it a try? Estimates are at 20,000 to 50,000 new users,every day, with thousands of those joining the actual Internet. Remember, play FAIRLY and HONESTLY and this will work. This really isn't another one of those crazy scams! As long as people follow through with sending out $6.00, it works! With warm wishes, bless you and your loved ones, https://www.paypal.com $$$$$ REMEMBER, IT IS 100% LEGAL! DON'T PASS THIS UP! From none at pacbell.net Wed Jul 13 19:55:39 2005 From: none at pacbell.net (Richard) Date: Wed, 13 Jul 2005 23:55:39 GMT Subject: Efficiently Split A List of Tuples Message-ID: I have a large list of two element tuples. I want two separate lists: One list with the first element of every tuple, and the second list with the second element of every tuple. Each tuple contains a datetime object followed by an integer. Here is a small sample of the original list: ((datetime.datetime(2005, 7, 13, 16, 0, 54), 315), (datetime.datetime(2005, 7, 13, 16, 6, 12), 313), (datetime.datetime(2005, 7, 13, 16, 16, 45), 312), (datetime.datetime(2005, 7, 13, 16, 22), 315), (datetime.datetime(2005, 7, 13, 16, 27, 18), 312), (datetime.datetime(2005, 7, 13, 16, 32, 35), 307), (datetime.datetime(2005, 7, 13, 16, 37, 51), 304), (datetime.datetime(2005, 7, 13, 16, 43, 8), 307)) I know I can use a 'for' loop and create two new lists using 'newList1.append(x)', etc. Is there an efficient way to create these two new lists without using a slow for loop? r From uche.ogbuji at gmail.com Fri Jul 29 19:43:17 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 29 Jul 2005 16:43:17 -0700 Subject: xml-object mapping In-Reply-To: References: Message-ID: <1122680597.372818.48400@g49g2000cwa.googlegroups.com> "I am looking for an xml-object mapping tool ('XML Data Binding-design time product') where I can define the mapping rules in 'binding files' and the parser is generated automatically. Similar to the solution of Dave Kuhlman (http://www.rexx.com/~dkuhlman/ generateDS.html) where the mapping is defined in an xml file (if I am understand well). But I already have the target object. The xml-tags should not be used as a property/member name, but should be mapped to an existing object. " In generateDS the mapping is not just deined in any old sort of XML file: it's defined in a W3C XML Schema file, which makes good sense (except that in my case I dislike WXS). Amara does not use a mapping specification: it maps automatically, and it allows you to specify your own classes for the mapping. This is discussed in the manual. http://uche.ogbuji.net/tech/4Suite/amara/ -- Uche http://uche.ogbuji.net From kay.schluehr at gmx.net Tue Jul 19 06:00:58 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jul 2005 03:00:58 -0700 Subject: Documentation bug: Python console behaviour changed Message-ID: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> The documentation of the Python console behaviour is not correct anymore for Python 2.4.1. At least for the Win2K system I'm working on 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. The Python interpreter tells me instead: >>> quit 'Use Ctrl-Z plus Return to exit.' Nah, 'Ctrl-Z' is now undo :-) Side remark: IDLE closes the console either with Ctrl-D or Ctrl-Q. But IDLEs configure dialog window showing the key combinations is so tight and nothing is recognizable without scrolling back and forth that it is discouring to use it at all ;) IPython closes with 'Ctrl-D'. Thanks to IPython I also determined this as the correct shutdown keys for Python too. Kay From jepler at unpythonic.net Wed Jul 6 16:07:23 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 6 Jul 2005 15:07:23 -0500 Subject: Strange os.path.exists() behaviour In-Reply-To: <42cc3613$0$22287$8fcfb975@news.wanadoo.fr> References: <42cc3613$0$22287$8fcfb975@news.wanadoo.fr> Message-ID: <20050706200720.GB5936@unpythonic.net> Pierre wrote: > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 ^^^^^^^ Here's the bug. You're using Windows. It's a filesystem, but not as we know it... Anyway, You are getting exactly what the low-level Windows APIs return. Here's a small "C" program. It prints "0" next to the filename if the file exists, -1 otherwise, as described at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt__access.2c_._waccess.asp int main(int argc, char **argv) { int i; for(i=1; idir Volume in drive C has no label. Volume Serial Number is 171D-4D2A Directory of C:\TMP\example 07/06/05 03:04p . 07/06/05 03:04p .. 07/06/05 03:05p 3 exist 3 File(s) 3 bytes C:\TMP\example>x:a.exe exist exist. exist.... nonexist nonexist. nonexist... exist: 0 exist.: 0 exist....: 0 nonexist: -1 nonexist.: -1 nonexist...: -1 C:\TMP\example>type nonexist.... The system cannot find the file specified. C:\TMP\example>type exist.... C:\TMP\example> As you can see, not only does Windows think that "exist...." exists, but it can successfully "type" its contents too! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From theller at python.net Thu Jul 7 03:51:42 2005 From: theller at python.net (Thomas Heller) Date: Thu, 07 Jul 2005 09:51:42 +0200 Subject: Conditionally implementing __iter__ in new style classes References: <42cc0e23.693458660@news.oz.net> Message-ID: <7jg35a0h.fsf@python.net> bokr at oz.net (Bengt Richter) writes: > On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller wrote: > >>I'm trying to implement __iter__ on an abstract base class while I don't >>know whether subclasses support that or not. > Will a property or custom descriptor do what you want? E.g. > > >>> class Base(object): > ... def __getIter(self): > ... if hasattr(self, "Iterator"): > ... return self.Iterator > ... raise AttributeError, name > ... __iter__ = property(__getIter) > ... > >>> class Concrete(Base): > ... def Iterator(self): > ... yield 1 > ... yield 2 > ... yield 3 > ... > >>> iter(Base()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iteration over non-sequence > >>> iter(Concrete()) > > >>> list(iter(Concrete())) > [1, 2, 3] Yep, that's exactly what I need - thanks. Thomas From andreas at kostyrka.org Fri Jul 1 14:47:45 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 01 Jul 2005 20:47:45 +0200 Subject: No subject In-Reply-To: References: Message-ID: <1120243665.6823.51.camel@andi-lap> Am Freitag, den 01.07.2005, 13:50 +0100 schrieb Tom Anderson: > On Fri, 1 Jul 2005, Adriaan Renting wrote: > > > I'm not a very experienced Python programmer yet, so I might be > > mistaken, but there are a few things that would make me prefer C++ over > > Python for large (over 500.000 LOC) projects. > > Hmm. I don't know C++, but here goes ... > > > - namespaces > > Aren't namespaces basically the same as packages/modules in python? Basically. And one could probably argue that their are superior to C++ namespaces. > > > - templates > > These would be meaningless in python - they're part of typefulness, which ... Worse than that. C++ templates are hack which has grown quite powerful with time. And they are a kind of "compile-time" late binding. You get the worst from both worlds. All the complication of a static typing system, and at the same time no safety. One of the more popular arguments pro C++ typing has been that x.write doesn't have a semantics in Python, while in C++ x->write can have an expected semantics, because x is restrained to a given type or subtype. So it's not some random method called write that get's selected. Problem: This is not valid as such for templates, as templates will luckily accept any type for a class argument. > > - strong type checking > > ... python eschews. > > Not that this is necessarily a good thing. I have to say that my Java > roots do lead me to think that strong typing is a plus for big projects, > since it's a way of defining and enforcing interfaces between bits of code > written by different people (or by one person at different times!). > Optional static typing in python would be nice for this. This is a good thing. Because static typing as such catches a big percentage of certain classes of errors, it makes it harder to catch the surviving errors. But the type system doesn't know if an integer represents a temperature, in fahrenheit, kelvin or celsius, or a pixel row or column. For an ironclad "type checking" the type system, and especially the type system of C++ doesn't give enough information. * Combined with automatic conversion between types this can lead to many bugs going undetected. And compared to Python, C++ does have the additional drawback, that it offers * an unsafe environment -> anything can kill your runtime. And your crash happens sometime later ;) If you are lucky it happens when your application goes live with clients ;) * quote a highlevel view. With STL you can write quite a bit of code in one liners. But because C++ as such is unsafe, and the type system of C++ is far from perfect, this can lead to subtle bugs that crash your system or just corrupt data. Contrast this to Python. It's safe. So the worst what usually happens is that you get an exception. Much easier to debug than a subtle STL bug that surfaces only if one uses the wrong kind of argument. But which is not caught by the type system. Basically the mix of high expressivness, the lowlevel runtime access and a non-perfect type system gives something that is quite explosive, especially when employed in an huge enterprise system. So basically no matter if you program in C/C++/Python whatever you need tests of all kinds. And here again the static typing of C++ makes it harder to fake interfaces for unit tests. So to summarize: * It makes testing harder * It "claims" to catch many error classes. The reader is invited to think if more C++ programs or more Python programs have unit tests. > > > - data hiding > > Surely you can hide data in python? Basically the same way as in C++. Although one needs a cast to overcome private: declarations in C++ ;) > > > - more available libraries and more advanced developement tools. > > True. The more advanced development tools are offset to a large degree by > the advanced crappiness of C++ as a language, though; i'd be surprised if > a C++ programmer borged up with all the latest tools was actually more > productive than a python programmer with a syntax-colouring, > auto-indenting text editor. It'd be very interesting to get some real > numbers on that. Difficult to measure. So it's almost always either just a personal observation, or a study with a methodology that is suspect :( But I'm quite sure that even the best IDE cannot solve memory bugs in C++. Ok, one can program almost without pointers and new/delete, but this leads "almost" automatically to slower programs. And not all problems are solvable with "simple" vector arrays and other trivially wrapped containers. So anyone who tells you it's easy to program C++ is either doing only very limited C++ work (say huge C++ programs that are 99% template generated code) or doesn't know how buggy his programs in reality are ;) > > >> Ultimately, manageability of a project is far and away more about the > >> people involved and the techniques used than it is about any single > >> technology involved. > > > > Agreed. > > +1 getting to the crux of it. And here the crux lies. Software development scales badly. And higher productivity languages like Python allow smaller teams to develop more functionality. And compared with other "dynamic" languages like Tcl, Perl, Ruby, Python does have the benefit that it got a syntax that enforces better readable code. This can manifest itself in many ways. Be it that Python/Pyrex code beats C++ code at tasks like huge data manipulation. (Personal experience: The C++ guys gave up after 12-18 months, and they've just managed to read the data somehow. I've been able to read the data after one month, another month I've spent interfacing with the existing C++ app, and afterwards I've optimized for 4 months. And actually did a number of feature requests the C++ team never ever contemplated to do.) To put it bluntly for most cases where today C/C++ is used, it's used unneccessarily and causes pain and costs for all involved. You know this projects, where even with a strong dislike for Perl, one prays "Couldn't they do it in Perl, anything, not C?". *g* Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From schwehr at gmail.com Wed Jul 6 11:28:45 2005 From: schwehr at gmail.com (schwehr at gmail.com) Date: 6 Jul 2005 08:28:45 -0700 Subject: latex/bibtex python paper? Message-ID: <1120663725.339927.141870@g47g2000cwa.googlegroups.com> Hi All, Does anyone have a good template that I might use for writing a python paper in latex/bibtex? I've got the paper mostly done, but am having issues with the references. I am definitely not an expert at latex/bibtex. Right now, I have references defined like this: @article{imp, title = {imp -- Access the import internals}, journal = "http://www.python.org/doc/current/lib/module-imp.html", author = {Python Software Foundation}, year = {2005} } When I cite these, I get something like this (Foundation[2005]). Is anyone willing to offer up a tarball of a complete paper with sty and bst that would make for a nice python paper? Thanks! -kurt http://schwehr.org/software/segy-py From philippe at philippecmartin.com Tue Jul 5 19:43:54 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 05 Jul 2005 23:43:54 GMT Subject: adding a character to the last string element of a list Message-ID: <_WEye.1218$Ae.676@newssvr12.news.prodigy.com> I guess my slicing was wrong, l[-1] worked Regards, Philippe From rwgk at yahoo.com Tue Jul 5 19:21:01 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Tue, 5 Jul 2005 16:21:01 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code Message-ID: <20050705232102.18901.qmail@web31508.mail.mud.yahoo.com> Hi Michael, Thanks for taking a careful look, and thanks for the balanced analysis! Michael Chermside wrote: > A better name would help with this. OK. After getting so many beatings I'd agree to anything. :) > The need for locals() is unavoidable. It is in fact not unavoidable. I pointed to my prototype before, but sorry, it is probably confusing that my two prototypes have the same name. They just live in different modules. For easier access I inline the second version that works without having to write "locals()" (from libtbx.introspection): def frame_object(frames_back=0): try: raise Exception except: t = sys.exc_info()[2] f = t.tb_frame for i in xrange(frames_back+1): if (f.f_back is None): break f = f.f_back return f def adopt_init_args(exclusions=[], prefix="", frames_back=0): frame = frame_object(frames_back=frames_back+1) varnames = frame.f_code.co_varnames exclusions.append(varnames[0]) # self init_locals = frame.f_locals self = init_locals[varnames[0]] for varname in varnames: if (varname not in exclusions): setattr(self, prefix+varname, init_locals[varname]) if ("__init__varnames__" not in exclusions): setattr(self, "__init__varnames__", varnames) I am sure this can be improved and stripped down to the essentials. E.g. I wasn't aware of sys._getframe() as just pointed out by Thomas Heller (thanks!). To me this just shows that finding the optimal solution is not entirely trivial and should therefore be done "right" once and forever in a community effort. Ultimately I hope it will be done in C for speed. That's the main goal of my proposal. > But for REAL beginners, I wouldn't even bother... writing out "self.x = x" > is useful for beginners since it helps make it very clear and concrete to > them just what is happening. In my experience real Python beginners grow very skeptical when I make them type highly redundant code. Many are just waiting for excuses not to learn Python and to continue with whatever they know (in my field FORTRAN!). Even class point: def __init__(self, x, y): self.x = x self.y = y makes for wrinkled noses. If I didn't use my home-grown adopt_init_args() function in the real-world code pointed out earlier the FORTRAN faction probably wouldn't stop making fun of me ("Why doesn't he use COMMON blocks?"). > > - In some cases the ``adopt_init_args()`` overhead was found to > > introduce a significant performance penalty (in particular the > > enhanced version discussed below). > > Again... a different code will help here. And if execution speed is > REALLY a concern, then you can just write it out the long way! Why should anyone have to think about technicalities like this? If we had an efficient C version included with Python nobody would have to. One solution works for everything. > The VERY simple, VERY straightforward, VERY common behavior of > "store all the arguments as like-named attributes of self" is > worth having a standard idiom (and *perhaps* a built-in). But > odd special cases like skipping some arguments... that calls > for writing the whole thing out. I'm firmly -1 on any proposal > to support skipping arguments. OK. "del x" is almost as good. I was motivated by speed concerns (first adding x to self.__dict__, then removing it again), but it is most likely a very minor issue, and my prototype with the repeated list lookup may even backfire anyway. > > When ``__slots__`` are used (cool feature!) the boilerplate problem > > becomes even worse:: > > > > class grouping: > > > > __slots__ = ["keep_this", "and_this", "but_this_again"] > > > > def __init__(self, keep_this, and_this, but_not_this, but_this_again): > > self.keep_this = keep_this > > self.and_this = and_this > > self.but_this_again = but_this_again > > # real code, finally > > > > Each variable name appears four times! > > ** NO! ** > > __slots__ is *NOT* to be used except for those times when you NEED > the performance advantages (mostly memory use). The simple rule is > that you should *NEVER* use __slots__ (if you are in a situation > where you *do* need it, then you'll know enough to understand why > this advice doesn't apply to you). There should NOT be any support > for auto-setting __slots__ *anywhere* in the standard library, > because it would make it FAR too tempting for people to mis-use > __slots__. > > Besides, a metaclass would be a better solution, and it can be done > today with no modifications to Python. I am very puzzled to see the huge ** NO! **. If __slots__ improve performance and reduce memory, what is wrong with using this feature? I clearly was in situations where I needed __slots__, but I still don't know what the dangers could be. Could you please explain a little more? > All in all, I think there's SOME merit to this idea, in that this > is a common enough practice that it might be nice to make it easy > to type (and read). But your proposal entangles the good idea with > several ideas I rather dislike, and on the whole I think it sounds > rather dangerous. I am OK to strip down the proposal to concentrate solely on an optimal, fast, C-coded built-in function. That alone would be a major step forward, with a life-changing potential similar to that of zip, enumerate, or inplace operators (+=, *=, etc.). (I guess I am showing my age.) I was also considering working in Josiah Carlson's metaclass solution (http://mail.python.org/pipermail/python-list/2005-July/288349.html) to the __slots__ problem, but after reading your message I am not so sure anymore... Cheers, Ralf ____________________________________________________ Yahoo! Sports Rekindle the Rivalries. Sign up for Fantasy Football http://football.fantasysports.yahoo.com From me at privacy.net Wed Jul 6 11:04:45 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 06 Jul 2005 11:04:45 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <42CBDC5B.9020208@syscononline.com> Message-ID: On Wed, 06 Jul 2005 08:27:55 -0500, Larry Bates wrote: [ reusable, stable, debugged, and documented libraries are a Good Thing ] Absolutely. Two related stories from my days working as a software engineer for a large telecomm company. Both stories begin with the annual ritual of management telling us that code reuse was the silver bullet of software development. 1. We replied that we needed about 5 calendar years to design, develop, debug, and document sufficient libraries to pay for the effort. Then management would tell us that 5 years is too long, and the project(s) would be scrapped. I worked there for 12 years, and was still watching new hires argue over linked list code and build tools when I left. 2. Right after that (and often in the same speech), management would also tell us that they would be measuring our productivity by (a) LOC written rather than LOC reused, and (b) the number of new ideas and code we submitted for patent. There is no better example of a Mixed Message. (Not to mention that we did all or most of our coding in C and C++, and every department and every project had its own method(s) of determining what a Line Of Code looked like, but that's even farther off-topic....) Regards, Dan -- Dan Sommers From steve at REMOVETHIScyber.com.au Wed Jul 6 11:15:16 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 07 Jul 2005 01:15:16 +1000 Subject: Deleting variables [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote: >> del -> delete > > How about just getting rid of del? Removal from collections could be done > with a method call, Which would be called object.del() I presume. And that opens a big can of worms. Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do? It looks like it should result in L becoming [4, 3, 2, 0]. An easy mistake to make, if you forget that the argument is (presumably) an index. You could make it clear by insisting on L.del[1] but that requires a big change in Python's syntax. What should L.del() do, with no arguments? Raise an error? Now, you have something like this: class thing: pass obj = thing() obj.alpha = [4, 3, 2, 1, 0] obj.beta = 5 Python's object model suggests that obj.alpha.del() should call alpha's del method, in the same way that obj.alpha.append() would call alpha's append method. So how do you delete obj.alpha? obj.del("alpha") might work. But what if obj itself is a mapping, with a key "alpha" as well as an attribute alpha. Which one should obj.del("alpha") delete? Now, if you said that L.del() should raise an exception earlier, what about obj.beta.del()? Presumably every object automatically has a del method, so you don't have to program a del method yourself. obj.del is a method object. So it has a del method. (Yes, sometimes you want to delete methods. Functions are first class objects in Python.) Which has a del method. Which has a del method. What should obj.del.del.del.del.del.del.del.del.del() do? > and i'm not convinced that deleting variables is > something we really need to be able to do (most other languages manage > without it). Most other languages don't have namespaces that can get polluted, or on-the-fly creation of variables. Most other languages don't consider variables to be simply attributes of a module object. And most other languages don't allow you to run interactive sessions where it is easy to mistakenly make variables you don't want. py> x = 1 py> u = x+2 # oops, typo, meant y not u py> del u # prevent confusion in the programmer's mind It is also useful sometimes to delete a module object from the top level namespace before re-importing it, rather than merely reloading it. That requires being able to delete a variable. In summary: del being a keyword works. del() being an object method is unclear, confusing and complicated. -- Steven. From negroup at gmail.com Wed Jul 6 05:01:55 2005 From: negroup at gmail.com (Negroup) Date: 6 Jul 2005 02:01:55 -0700 Subject: Create datetime instance using a tuple. Message-ID: <2fdabf19.0507060101.6184974e@posting.google.com> Hi, all. I would like to know if it is possible to create a datetime instance using a tuple instead of single values. I mean: >>> from datetime import datetime >>> t = (1, 2, 3) >>> dt = datetime(t) Traceback (most recent call last): File "", line 1, in ? TypeError: function takes at least 3 arguments (1 given) (class datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) Thanks. From pruebauno at latinmail.com Fri Jul 15 13:47:22 2005 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: 15 Jul 2005 10:47:22 -0700 Subject: Issues compiling with large file support Message-ID: <1121449642.160065.294670@g49g2000cwa.googlegroups.com> Hello all, I am having issues compiling Python with large file support. I tried forcing the configure script to add it but then it bombs in the make process. Any help will be appreciated. Information: Architecture: PowerPc on AIX version 5 Compiler: VisualAge C++ Professional / C for AIX Compiler, Version 6 Python version: Python 2.4.1 Error Message: cc_r -c -DNDEBUG -g -O2 -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -I . -I./Include -DPy_BUILD_CORE -o Objects/fileobject.o Objects/fileobject.c "Objects/fileobject.c", line 382.2: 1506-205 (S) #error "Large file support, but neither off_t nor fpos_t is large enough." "Objects/fileobject.c", line 389.27: 1506-046 (S) Syntax error. "Objects/fileobject.c", line 423.2: 1506-205 (S) #error "Large file support, but no way to fseek." "Objects/fileobject.c", line 431.8: 1506-166 (S) Definition of function Py_off_t requires parentheses. "Objects/fileobject.c", line 432.1: 1506-276 (S) Syntax error: possible missing '{'?"Objects/fileobject.c", line 446.2: 1506-205 (S) #error "Large file support, but no way to ftell." "Objects/fileobject.c", line 456.18: 1506-275 (S) Unexpected text offset encountered. "Objects/fileobject.c", line 456.9: 1506-045 (S) Undeclared identifier Py_off_t. "Objects/fileobject.c", line 468.9: 1506-045 (S) Undeclared identifier offset. "Objects/fileobject.c", line 476.48: 1506-099 (S) Unexpected argument. "Objects/fileobject.c", line 494.18: 1506-275 (S) Unexpected text newsize encountered. "Objects/fileobject.c", line 494.9: 1506-045 (S) Undeclared identifier Py_off_t. "Objects/fileobject.c", line 496.18: 1506-275 (S) Unexpected text initialpos encountered. "Objects/fileobject.c", line 513.9: 1506-045 (S) Undeclared identifier initialpos. "Objects/fileobject.c", line 525.17: 1506-045 (S) Undeclared identifier newsize. "Objects/fileobject.c", line 586.52: 1506-099 (S) Unexpected argument. "Objects/fileobject.c", line 604.18: 1506-275 (S) Unexpected text pos encountered. "Objects/fileobject.c", line 604.9: 1506-045 (S) Undeclared identifier Py_off_t. "Objects/fileobject.c", line 610.9: 1506-045 (S) Undeclared identifier pos. make: 1254-004 The error code from the last command is 1. Stop. More info: checking MACHDEP... aix5 checking EXTRAPLATDIR... checking for --without-gcc... checking for --with-cxx=... no checking for c++... no checking for g++... no checking for gcc... no checking for CC... no checking for cxx... no checking for cc++... no checking for cl... no checking for gcc... cc_r checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... no checking whether cc_r accepts -g... yes checking for cc_r option to accept ANSI C... none needed checking how to run the C preprocessor... cc_r -E checking for egrep... grep -E checking for AIX... yes checking for --with-suffix... checking for case-insensitive build directory... no checking LIBRARY... libpython$(VERSION).a checking LINKCC... $(srcdir)/Modules/makexp_aix Modules/python.exp . $(LIBRARY); $(PURIFY) $(CC) checking for --enable-shared... no checking for --enable-profiling... checking LDLIBRARY... libpython$(VERSION).a checking for ranlib... ranlib checking for ar... ar checking for a BSD-compatible install... ./install-sh -c checking for --with-pydebug... no checking whether cc_r accepts -OPT:Olimit=0... no checking whether cc_r accepts -Olimit 1500... no checking whether pthreads are available without options... yes checking for ANSI C header files... yes From jepler at unpythonic.net Mon Jul 18 12:41:00 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Jul 2005 11:41:00 -0500 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) In-Reply-To: References: Message-ID: <20050718164058.GF2199@unpythonic.net> I honestly don't know why anyone would spend money for a development environment, no matter how fancy. I don't know why anyone would develop software in a language that doesn't have at least one open implementation. It's a great way to get screwed when Borland goes under or decides they only want to sell a new, incompatible product. What do you do with your existing product when that happens? Re-train on a new platform, and re-write from scratch? Just say no to proprietary software. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From none Sat Jul 23 01:26:28 2005 From: none (none) Date: Sat, 23 Jul 2005 00:26:28 -0500 Subject: Location of tk.h In-Reply-To: References: Message-ID: Christopher Subich wrote: > none wrote: > >> Probably a stupid question, but... >> >> I was attempting to install the Tkinter 3000 WCK. It blew up trying >> to build _tk3draw. The first error is a 'No such file or directory' >> for tk.h. I can import and use Tkinter just fine, so I'm not sure >> what is what here. > > > You can import and user Tkinter, sure, but the WCK setup is trying to > -build- itself. Have you installed the relevant Tk development libraries? Installing tk-devel solved that problem. Thank you. From k04jg02 at kzoo.edu Sun Jul 3 16:36:09 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Sun, 03 Jul 2005 14:36:09 -0600 Subject: Python for everything? In-Reply-To: <3radnVbQrOpNwlnfRVn-3w@comcast.com> References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <3radnVbQrOpNwlnfRVn-3w@comcast.com> Message-ID: <42C84C39.3010902@kzoo.edu> Larry Bates wrote: >poorly. When new version of Python ships, you just learn what is new. >If you try to keep up with C, C++, Visual Basic, ... it gets to be >impossible. > >Hope information helps. > >Larry Bates > > > Huh? Part of C++'s problem is that it takes too long for obvious good stuff to get into the language. It stays the same for years at a crack inbetween the committees approving stuff. Python in contrast can see a release every few months. Python is a moving target. C++ is not. From kbk at shore.net Tue Jul 5 23:08:55 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 5 Jul 2005 23:08:55 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200507060308.j6638t9Y014186@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 348 open ( +4) / 2879 closed ( +4) / 3227 total ( +8) Bugs : 898 open ( +1) / 5103 closed ( +9) / 6001 total (+10) RFE : 193 open ( +2) / 170 closed ( +0) / 363 total ( +2) New / Reopened Patches ______________________ tarfile.py: ExFileObject's tell() is wrong after readline() (2005-06-30) http://python.org/sf/1230446 opened by Lars Gust?bel Patch for (Doc) #1168746 (2005-06-30) CLOSED http://python.org/sf/1230615 opened by Peter van Kampen Patch for (Doc) #1162912 (2005-07-03) CLOSED http://python.org/sf/1231890 opened by Peter van Kampen audioop - alaw encoding/decoding added, code updated (2005-07-01) http://python.org/sf/1231053 opened by Lars Immisch Add unicode for sys.argv, os.environ, os.system (2005-07-02) http://python.org/sf/1231336 opened by Neil Hodgson Typo fix in compiler/transformer.py (WalkerEror) (2005-07-02) CLOSED http://python.org/sf/1231538 opened by Adrien Di Mascio MS Windows - module search path fix (2005-07-04) http://python.org/sf/1232023 opened by K. Thananchayan PyOS_Readline (2005-07-04) http://python.org/sf/1232343 opened by Lisandro Dalcin Patches Closed ______________ Patch for (Doc) #1168746 (2005-06-30) http://python.org/sf/1230615 closed by birkenfeld Patch for (Doc) #1162912 (2005-07-03) http://python.org/sf/1231890 closed by birkenfeld Patch for (Doc) bug #1228904 (2005-06-29) http://python.org/sf/1229935 closed by birkenfeld Typo fix in compiler/transformer.py (WalkerEror) (2005-07-02) http://python.org/sf/1231538 closed by birkenfeld New / Reopened Bugs ___________________ Build failure (2005-06-30) http://python.org/sf/1230161 opened by L.M tokenize bug (2005-06-30) http://python.org/sf/1230484 opened by Eduardo Aguiar sys.excepthook doesn't work in threads (2005-06-30) http://python.org/sf/1230540 opened by Jonathan Ellis decimal module is no longer 2.3 compatible (2005-06-30) CLOSED http://python.org/sf/1230553 opened by Mike Orr ioctl has problem with -ive request codes (2005-07-01) http://python.org/sf/1231069 opened by Barry Alan Scott chr() returns ? when input > 127 in OS X (2005-07-02) http://python.org/sf/1231488 opened by Craig Howard typesseq-mutable lacks note on combined key/cmp usage (2005-03-14) CLOSED http://python.org/sf/1162912 reopened by birkenfeld OverflowError in time.utime() causes strange traceback (2005-07-04) CLOSED http://python.org/sf/1232517 opened by Joe Peterson Mistakes in online docs under "5.3 Pure Embedding" (2005-07-05) http://python.org/sf/1232768 opened by Matt Smart non-admin install may fail (win xp pro) (2005-07-05) http://python.org/sf/1232947 opened by pvrijlandt openssl-0.9.8 requires _ssl.mak change (2005-07-05) http://python.org/sf/1233049 opened by Alan Meyer Bugs Closed ___________ Two requests to one file are not done in parallel (2005-06-25) http://python.org/sf/1227480 closed by jafo usage of type "char*" instead of "const char*" (2005-06-27) http://python.org/sf/1228053 closed by tjreedy decimal module is no longer 2.3 compatible (2005-06-30) http://python.org/sf/1230553 closed by rhettinger frame.f_exc_type,value,traceback (2005-03-23) http://python.org/sf/1168746 closed by birkenfeld __getattribute__ documentation error? (2005-05-19) http://python.org/sf/1204734 closed by birkenfeld weakref example broken (2005-06-28) http://python.org/sf/1228904 closed by birkenfeld typesseq-mutable lacks note on combined key/cmp usage (2005-03-14) http://python.org/sf/1162912 closed by birkenfeld typesseq-mutable lacks note on combined key/cmp usage (2005-03-14) http://python.org/sf/1162912 closed by birkenfeld random.py/os.urandom robustness (2005-04-06) http://python.org/sf/1177468 closed by birkenfeld OverflowError in time.utime() causes strange traceback (2005-07-05) http://python.org/sf/1232517 closed by mwh New / Reopened RFE __________________ platform.processor() could be smarter (2005-07-01) http://python.org/sf/1231081 opened by Stephan Springer Links to tutorials and howtos from references (2005-07-04) http://python.org/sf/1232073 opened by Michael Hoffman From fabioz at esss.com.br Wed Jul 20 12:23:24 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Wed, 20 Jul 2005 13:23:24 -0300 Subject: ANN: PyDev 0.9.6 released Message-ID: <42DE7A7C.1020105@esss.com.br> Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.6 has just been released. This is to be considered a stable release for all features but the debugger, as there are still some integration issues for it to work with Eclipse 3.1, so, if you are using PyDev because of its debugger support, you should stick to version 3.0.x until those issues are fixed. Check the homepage (http://pydev.sourceforge.net/) for more details. The major release highlights is that it Eclipse 3.1 is now supported. Older versions of Eclipse are no longer supported. 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 From tpherndon at gmail.com Fri Jul 8 10:00:52 2005 From: tpherndon at gmail.com (Peter Herndon) Date: 8 Jul 2005 07:00:52 -0700 Subject: Windows Cmd.exe Window In-Reply-To: <1120747817.247502.106680@g14g2000cwa.googlegroups.com> References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <1120747817.247502.106680@g14g2000cwa.googlegroups.com> Message-ID: <1120831252.684872.145350@g14g2000cwa.googlegroups.com> Giles, you keep mentioning syntax errors as the (/a) cause of the problem. I suggest you avoid such problems, so that the import sethook approach, et al. will actually work. The easiest thing to do is to run PyChecker on your script prior to executing it. PyChecker will catch your syntax errors (and a whole host of other things, some of which are actual problems, some not) and let you know where they are. With that simple bit of testing, the other approaches that rely on a syntactically-correct script will work, because you will have corrected the syntax errors. You *will* have corrected the syntax errors, right? :) From slomojo83 at gmail.com Mon Jul 4 14:42:30 2005 From: slomojo83 at gmail.com (Josiah Manson) Date: 4 Jul 2005 11:42:30 -0700 Subject: Existance of of variable Message-ID: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> Hello. I am very new to Python, and have been unable to figure out how to check if a variable exists or not. In the following code I have made a kludge that works, but I think that it would be clearer to check if closest exists and not have to initialize it in the first place. How is that check done? The following code finds the closest place to a position and rejects places that are too far away. dist = 1e9 closest = -1 for n,p in galaxy.places.iteritems(): dif = p.pos - pos len = dif.len() if len < dist and len < 10.0/self.zoom: dist = len closest = p if closest != -1: self.sel = [closest.name] I also have a few other questions to tack on if you don't mind. I am setting dist to 1e9, because that is a larger value than any of the places in the galaxy will be far away. Is there a better way to initialize dist so that it is impossible for this to fail? For example, would setting dist to infinity work, and how is that done? Extending my existance checking question, how does one check what type a variable has? Thanks for your help! -- Josiah From max at alcyone.com Sat Jul 30 15:40:22 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Jul 2005 12:40:22 -0700 Subject: Comparison of functions In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > Um, I didn't ask to compare complex numbers using comparison operators. I > asked to sort a list. And please don't tell me that that sorting is > implemented with comparison operators. That just means that the > implementation is confusing numeric ordering with sort order. Python doesn't have a distinction between these two, so yes, you're sorting with comparison operators. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I am not a Virginian, but an American. -- Patrick Henry From martin.witte at gmail.com Wed Jul 6 15:23:35 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 6 Jul 2005 12:23:35 -0700 Subject: from date/time string to seconds since epoch In-Reply-To: References: Message-ID: <1120677815.189895.11580@f14g2000cwb.googlegroups.com> You can calculate the offset of where you are like this: martin at ubuntu:~ $ python Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> import time py> offset = 0 py> if time.daylight: py. offset = time.altzone py. else: py. offset = time.timezone py. py> print offset -7200 py> You can use time.time() to get the UTC time, then add the offset. From harold.fellermann at upf.edu Thu Jul 14 10:58:34 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 14 Jul 2005 16:58:34 +0200 Subject: How can I import a py script by its absolute path name? In-Reply-To: <4222a849050714074264811bbd@mail.gmail.com> References: <311b5ce105071404412d4bf318@mail.gmail.com> <4222a849050714074264811bbd@mail.gmail.com> Message-ID: > for f in os.listdir(os.path.abspath(libdir)): > module_name = f.strip('.py') > import module_name > > Obviously, this throws: > > ImportError: No module named module_name > > Is there some way to do this? have a look at help(__import__) to import a module whose name is given as a string. - harold - -- Tages Arbeit, abends G?ste, saure Wochen, frohe Feste! -- Johann Wolfgang v. Goethe From eric_brunel at despammed.com Mon Jul 4 03:07:32 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 04 Jul 2005 09:07:32 +0200 Subject: Tkinter Checkbutton initialization problem References: <7xzmt4fd5m.fsf@ruckus.brouhaha.com> Message-ID: On 03 Jul 2005 02:32:21 -0700, Paul Rubin wrote: > Python 2.4, Windows XP. If I say: > > f = Frame() > f.grid() > v = IntVar() > c = Checkbutton(f, text='hi there', variable=v) > c.grid() > f.mainloop() > > then the checkbutton should initially display as being checked. > But it doesn't. It shows up unchecked, even though v.get() returns 1. > The select operation DOES update the display if there's no variable. In tcl/tk, booleans are not integers. So using an IntVar to represent something which is basically a boolean will cause unexpected behaviors like the one you're experiencing here. Just do: ... v = BooleanVar() v.set(1) ... and everything should be fine. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From walterbrunswick at sympatico.ca Sun Jul 24 13:12:04 2005 From: walterbrunswick at sympatico.ca (Walter Brunswick) Date: Sun, 24 Jul 2005 13:12:04 -0400 Subject: Importing User-defined Modules Message-ID: I need to import modules with user-defined file extensions that differ from '.py', and also (if possible) redirect the bytecode output of the file to a file of a user-defined extension. I've already read PEP 302 (http://www.python.org/peps/pep-0302.html), but I didn't fully understand it. Would someone [who understands it] please be able to give me a synopsis of it, along with a few explanatory examples, or some other alternatives, if any? From ispork at gmail.com Tue Jul 12 15:17:40 2005 From: ispork at gmail.com (Alex Dempsey) Date: Tue, 12 Jul 2005 12:17:40 -0700 Subject: Slicing every element of a list Message-ID: <8025cc1305071212173f030365@mail.gmail.com> Recently I tried to slice every element of a list of strings. First I tried: f = open("export.xls", "r") lines = f.readlines() for line in lines: line = line[1:-5] line = line.split('\"\t\"') This went without returning any errors, but nothing was sliced or split. Next I tried: for i in range(len(lines)): lines[i] = lines[i][1:-5] lines[i] = lines[i].split('\"\t\"') This of course worked, but why didn't the first one work. Further why didn't the first one return an error? From gene.tani at gmail.com Thu Jul 21 22:36:55 2005 From: gene.tani at gmail.com (gene tani) Date: 21 Jul 2005 19:36:55 -0700 Subject: dictionary that discards old items In-Reply-To: References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> Message-ID: <1121999815.943316.136530@g14g2000cwa.googlegroups.com> not clear if you want a FIFO, or a LRU on read or write, so for the non-dictionary component of this, you could also ( (search Cookbook) || google) for terms like "ring buffer", "fixed-size cache", um, "bounded queue", "circular buffer", "deque", there's probably a bunch of others. From sizelji at insightbb.com Thu Jul 21 17:28:08 2005 From: sizelji at insightbb.com (Jim Sizelove) Date: Thu, 21 Jul 2005 21:28:08 GMT Subject: What does "::" mean? In-Reply-To: References: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Message-ID: Robert Kern wrote: > Michael Hoffman wrote: > >> Robert Kern wrote: > > >>> Well, that part's easy at least: >>> >>> live[::-1] >>> >>> :-) And so the circle is complete ... >> >> >> What about reversed(live)? Or if you want a list instead of an >> iterator, list(reversed(live))? > > > That's fine if you want to iterate over it. Often, especially with > strings, you just want an object of the same type back again. > Then you could use: ''.join(reversed(live)) though, I think that live[::-1] is the most obvious way to do it. :-) Regards, Jim Sizelove From jstroud at mbi.ucla.edu Wed Jul 27 22:44:02 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 27 Jul 2005 19:44:02 -0700 Subject: any thing to do??? In-Reply-To: References: Message-ID: <200507271944.02906.jstroud@mbi.ucla.edu> The world needs an open source tool for working with DNA sequences graphically. I know what needs to be done, but I am not finding much time to do it. I have already coded a graphical sequence editor and some cool tools for sequence analysis. For this project I am using Tkinter as the gui and biopython as the main code-base. Right now, a critical thing to do would be to use the Tkinter Canvas to draw plasmid maps. Don't worry if you don't know what a plasmid is. It is a simple concept. If you want to become a hero to thousands in a field with 0 competition, this is the place. If you are interested, let me know. Maybe we can find a way to harness your time and enthusiasm. If you are good at organization, maybe you could help to turn this into a true open source project that interfaces with biopython. (Does anybody recognize the plea-for-help aspect of my message?) James On Wednesday 27 July 2005 08:00 am, mustafa wrote: > i hav just finished learning pythob from "A byte of python"(an online > book) so i wanted to apply my new skills. to learn and to have some fun. > is there any place which lists jobs to be done...you know minor jobs and > requests thats nobody has found time to do. > i would point out that i am not looking for a JOB as job with payment. > i am looking for a JOB that is to be done and nobody has done it yet. > > also aside from this is there any other way i could use python and > improve. i figure this practice will make me a lot better. but if anybody > else has any ideas than that would be good too . -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mwm at mired.org Tue Jul 5 13:31:25 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 05 Jul 2005 13:31:25 -0400 Subject: Folding in vim References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: <8664vpxiqa.fsf@bhuda.mired.org> Sybren Stuvel writes: > Andrea Griffini enlightened us with: >> - never ever use tabs > > I always use one tab for indents, and set my editor to display it as > four spaces. I like being able to unindent a line by deleting a single > character. I don't see a reason why _not_ to use tabs, really. As long > as the use is consistent - I hate those files with an 8-space tab and > 4-space indent, where they replace two indents with a single tab. For > me, one indent = one tab. No matter the tab setting, it'll look good. And so if you're working with someone who uses a different tab stop - say the traditional 8-space tabs - they'll get code that may well be unreadable. If you're the only one dealing with your code, you can keep the use consistent. As soon as theirs more than one person editing the code, that pretty much goes out the window. You either mandate a standard - which is hard for a large group - or you mandate that you don't use tabs. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From apardon at forel.vub.ac.be Wed Jul 6 04:30:34 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Jul 2005 08:30:34 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> <86irzu5sp9.fsf@bhuda.mired.org> Message-ID: Op 2005-07-01, Mike Meyer schreef : > "iK" writes: > >> Seems like he wants python programmers to solve their problems all in the >> same way. While that is great for corporate slaves it is terrible for the >> creative programmer. > > No, he wants Python to be Pythonic. TMTOWTDI is not Pythonic. If Guido should change his mind on this, then it will be pythonic. I don't think a concept that has so little meaning has any real value. >> Python is quickly becoming the visual basic of the 21 century. If you want >> to have fun while getting some work done you need to look elsewhere. It's a >> shame... > > If you'd rather spend your time figuring out which of multiple ways to > do things is the best for the job at hand than producing code, there's > a language that makes TMTOWTDI a way of life. There are always many ways to do things, and depending on circumstances the best way to do something may differ every time. So if python no longer allows multiple ways to do things, it won't help the programmer. The programmer will now face the question if python is still the right language to do the job. -- Antoon Pardon From aahz at pythoncraft.com Sun Jul 3 19:57:45 2005 From: aahz at pythoncraft.com (Aahz) Date: 3 Jul 2005 16:57:45 -0700 Subject: Determining actual elapsed (wall-clock) time References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: In article <3ZGdnfw6ZLlvaVvfRVn-jA at powergate.ca>, Peter Hansen wrote: > >I would like to determine the "actual" elapsed time of an operation >which could take place during a time change, in a platform-independent >manner (at least across Linux/Windows machines). > >Using time.time() doesn't appear to be suitable, since time might jump >forwards or backwards at the user's whim, if the system clock is reset, >or when a daylight savings time change occurs. You have to do one of two things: rely on system clock or require a network connection (so you can call a timeserver directly). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From ptmcg at austin.rr.com Sat Jul 16 21:42:46 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Jul 2005 18:42:46 -0700 Subject: Parsing html :: output to comma delimited In-Reply-To: <1121540573.555193.243760@g49g2000cwa.googlegroups.com> References: <1121540573.555193.243760@g49g2000cwa.googlegroups.com> Message-ID: <1121564566.094694.27610@o13g2000cwo.googlegroups.com> Pyparsing includes a sample program for extracting URLs from web pages. You should be able to adapt it to this problem. Download pyparsing at http://pyparsing.sourceforge.net -- Paul From tommy.nordgren at chello.se Mon Jul 11 17:08:21 2005 From: tommy.nordgren at chello.se (Tommy Nordgren) Date: Mon, 11 Jul 2005 23:08:21 +0200 Subject: Extending and embedding Python Message-ID: I want to write an application that embeds and extends (at least) the Python and Perl interpreters. Now i want to find as much as possible about the Python tools used for extending and embedding Python. To be more specific: My app should: 1. Parse an input file. 2. Call a script in some scripting language, to generate an output file, for example in C++. For task 2 I need to call an embedded interpreter, and also provide call backs from the scripting language to C++, in order to read global information collected during parsing. In order to correctly compile and link my Application, I need a OS independent way to find compiler options and linker options necessary to find header files and libraries. What methods should I use from DistUtils for this purpose. I also need to find some way to verify that linker options necessary for embedding Perl is not incompatible with linking options for embedding Python. Stockholm July 11, 2005 Tommy Nordgren From steve at REMOVETHIScyber.com.au Tue Jul 12 21:20:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 11:20:59 +1000 Subject: Creating anonymous functions using eval References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> <1121184988.996652.126350@g47g2000cwa.googlegroups.com> Message-ID: On Tue, 12 Jul 2005 17:17:46 -0600, Joseph Garvin wrote: > Robert Kern wrote: > >>Not everyone is reading this list in a conveniently threaded >>form >> >> > Why not? Just about every modern newsgroup reader and e-mail app has a > threaded view option. Technology as a substitute for manners is it? I have a modern newsgroup reader. I don't like threaded views, but even if I did, that's not the point. News servers sometimes drop posts, or the posts expire. Sometimes news readers lose posts (that just happened to me yesterday). Sometimes threading breaks. Quoting enough of the previous post to establish context is the only sensible behaviour in the face of all these potential problems. But even that is not the point. It is rude for people to assume that their post is so vitally important to me that I'll drop what I'm doing to hunt back through past posts searching for context. Even if that search is "back one post in the thread", that's still one post too many. In the face of that breach of manners, people may choose to respond in many ways. Some might choose to reward the rudeness by searching previous posts, then responding with an answer to the question. Some might choose to just ignore the post, which has the disadvantage of leaving the original poster no wiser and likely to repeat his behaviour. Some might flame them, which is usually counterproductive. And some might drop some fairly heavy hints, but that assumes the poster is capable of getting a clue. -- Steven. From lambacck at computer.org Fri Jul 22 23:57:45 2005 From: lambacck at computer.org (Chris Lambacher) Date: Fri, 22 Jul 2005 23:57:45 -0400 Subject: is this pythonic? In-Reply-To: <797fe3d4050721072775cff831@mail.gmail.com> References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> <797fe3d4050721072775cff831@mail.gmail.com> Message-ID: <20050723035745.GA4161@computer.org> On Thu, Jul 21, 2005 at 10:27:24AM -0400, Bill Mill wrote: > On 7/21/05, Steven D'Aprano wrote: > > On Wed, 20 Jul 2005 16:30:10 -0400, Bill Mill wrote: > > > > > On 7/20/05, Simon Brunning wrote: > > >> On 7/20/05, Mage wrote: > > >> > Or is there better way? > > >> > > > >> > for (i, url) in [(i,links[i]) for i in range(len(links))]: > > >> > > >> for i, url in enumerate(links): > > >> > > > > > > +2 for creating seeing a need and crafting a reasonable solution, but > > > -1 for not reading the section on builtins to see if it existed > > > already. > > > > To see if *what* existed already? > > > > It is well and good to say RTFM, but there are 697 subsections to the > > Python Library reference, and if you don't know what you are looking for, > > and beginners rarely are, it isn't obvious which is the right section to > > read. And the Library Reference isn't even "the" manual: there is also the > > global module reference and language reference. > > > > If you already know what you are looking for, reading the manual is great > > advice. Browsing the manual looking for interesting tidbits can even be > > fun for a certain mindset. But if you don't know enough to know what to > > look for, where in the 2000-odd sections of the Python references will > > you find it? > > > > I said the *builtins* section. I think you learn pretty quick that > figuring out what functions are builtins is pretty important in every > language. There's a fair number of people out there giving the advice > to read chapter 2 of the library reference cover-to-cover for a good > starter on python. The quick reference guide is also a nice place to find all the most important information: http://rgruet.free.fr/PQR24/PQR2.4.html > > Furthermore, I wasn't being hard on the guy, he still added up to +1. > Lighten up, I was joking. > > > > > > > > (As for its pythonicity, I would have recommended isolating it into a > > > function and making it a generator: > > > > It is easy to take this to extremes. It isn't necessary to isolate > > everything into its own object, or class, or module. Too much > > encapsulation is just as bad as too little. > > > > agreed; his listcomp just looks awkward inside the for loop statement; > if it were my code, I would put it into a function. He asked if his > code was pythonic, and I think the (non-extreme) pythonic thing to do > would be to put his listcomp into a function. > > > > > > def my_enumerate(enumerable): > > > i = 0 > > > for elt in enumerable: > > > yield (i, elt) > > > i += 1 > > > > > > for i, url in my_enumerate(links): > > > > > > but it's not too bad as it is. Also, my function is completely > > > untested - it's close to right though.) > > > > What is the advantage of your function my_enumerate over the Python > > built-in enumerate? > > > > > > absolutely none; I just was saying how I would encapsulate it into a function. Except that enumerate was introduced in 2.3 so if you are working with an older version of Python it won't be there. > > Peace > Bill Mill > bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list From steve at REMOVETHIScyber.com.au Tue Jul 5 19:52:14 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 06 Jul 2005 09:52:14 +1000 Subject: math.nroot [was Re: A brief question.] References: <42C8B151.2010503@REMOVEMEcyber.com.au> Message-ID: On Tue, 05 Jul 2005 10:10:47 -0500, Terry Hancock wrote: > I have to mention that the idea of a math package that > allows NaN to propagate as though it were a number > scares the willies out of me. God help me if I were to use > it on something like Engineering where lives might > depend on the answer being right. The whole point of propogating NaNs is that they ever go away. Instead of putting hundreds of tests for error conditions all through your code, and god help you if you miss some obscure error condition or put it in the wrong place, you put one test at the very end: is the final result a NaN or not? Of course, the point is moot, since the IEEE standard allows you to specify that errors are signalling or non-signalling (quiet). You can pick the behaviour that suits the application. > That'd be like having a math package that allowed, > say 0/0 = 1 or Inf/Inf = 1. If I recall correctly, the IEEE standard requires both of those to return NaN, which is really the only correct thing to do. -- Steven From mike at maibaum.org Mon Jul 18 07:40:10 2005 From: mike at maibaum.org (Michael Maibaum) Date: Mon, 18 Jul 2005 12:40:10 +0100 Subject: What is your favorite Python web framework? In-Reply-To: References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> Message-ID: <61FA3BEC-2542-4E50-9B41-CCC77C82E183@maibaum.org> On 18 Jul 2005, at 10:29, Cyril Bazin wrote: > Hello, > > I never used a web framework using Python modules, but I think > cheetah, Karrigel and CherryPy are not good since they allow user > to play with the HTML code. IMO, it's not pythonic but phpythonic. Well, pretty much anything would allow that, it is more a matter of how much they encourage it ;) I find the cherrypy + HTML Template combination pretty resistant to excessive HTML in the Python, or Python in the HTML. One day when I get some time I'll have a look at Django, though I must say the templating language looked less nice than the rest of it on first glance, it says you don't have to use it though... Michael From szymon.rozga at gmail.com Mon Jul 18 19:43:01 2005 From: szymon.rozga at gmail.com (szymon.rozga at gmail.com) Date: 18 Jul 2005 16:43:01 -0700 Subject: Python to C++ translation? References: <1121722762.525859.255890@g49g2000cwa.googlegroups.com> Message-ID: <1121730181.870233.169830@g43g2000cwa.googlegroups.com> Ok so here's what you have: A a(42); B b(23.0); a is now of type A, and b is now of type B. Right? The constructor for class C takes in two arguments. The first one _has_ to be of type A and the second one _has_ to be of type B. This is how you defined it. This is why C(a,b) works fine. But C(b,a) shouldn't work because of how you defined the constructor for C. You could add a second constructor to C as follows: C(B &_propB, A &_propA) { propA = &_propA; propB = &_propB; } which would let you call C(b,a). From cam.ac.uk at mh391.invalid Fri Jul 22 05:04:58 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 10:04:58 +0100 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Duncan Booth wrote: > You should need an explicit call to convert a path to a string and that > forces you when passing the path to something that requires a string to > think whether you wanted the string relative, absolute, UNC, uri etc. Egad. I'm not sure if that will really make people's lives easier. -- Michael Hoffman From max at alcyone.com Sun Jul 3 20:28:08 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 03 Jul 2005 17:28:08 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <86acl31ldw.fsf@bhuda.mired.org> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <86acl31ldw.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > I'd say that removing functions is a bad thing. On the other hand, I'd > say moving them from builtins to the standard library when Python has > functionality that covers most of the use cases for them is a good > thing. We all can pretty much guess that map, filter, and reduce will be reimplemented in a functional module by a third party within mere seconds of Python 3000 being released :-). So it's really just a question of whether it will be let back in to the standard library as a module (rather than builtins) or not. Even granting the reasons for removing them as builtins, I really can't understand the motivation for removing them entirely, not even as a standard library module. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Golf is a good walk spoiled. -- Mark Twain From deets at web.de Sun Jul 24 06:08:35 2005 From: deets at web.de (Diez B.Roggisch) Date: Sun, 24 Jul 2005 10:08:35 +0000 (UTC) Subject: How do i do this References: <42E32290.3060307@neolinuxsolutions.com> Message-ID: Amit Regmi neolinuxsolutions.com> writes: > For some commad Linux like (pdbedit) its not possible to supply password > in the command line itself while we add a samba user account into the You might be able to utilize pexpect for this. Go google :) Diez From mwm at mired.org Mon Jul 18 19:40:00 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 18 Jul 2005 19:40:00 -0400 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: <867jfnu1in.fsf@bhuda.mired.org> rbt writes: > Many of the world's most profitable software companies (MS for example) > have thousands of goto statements in their code... oh the horror of it > all. Why aren't these enlightened-by-the-gods know-it-alls as profitable > as these obviously ignorant companies? Because profitability has *nothing* to do with code quality, and everything to do with marketing. MS, in particular, has done an excellent job of divorcing code quality from their bottom line by shuffling the bulk of the support work off to other companies: hardware vendors who bundle MS software, system integrators, and customers friends and family being very high on the list. That they felt the need to do this speaks volumes about their code quality. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From darkcowherd at gmail.com Tue Jul 12 22:34:16 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Wed, 13 Jul 2005 08:04:16 +0530 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: <5f4d3cb50507121934f23f71b@mail.gmail.com> OK, I can see that the Python way of doing things is very different. However I think Roy made a very pertinent point "Imagine if do_setup_code or do_stuff_with(f) unexpectedly threw an IOError for some reason totally unrelated to the file not existing." This is the kind of situation that the rule 'catch it on the next line' is trying to avoid What I didnt realise till I read Thomas comment is that the try except had an else clause. This is nice. But seriously, if you expected to write reasonably large business applications with multiple people in the team and teams changing over time what would you give as a guideline for Error handling DarkCowherd From renting at astron.nl Fri Jul 1 09:38:43 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 01 Jul 2005 15:38:43 +0200 Subject: No subject Message-ID: Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> Tom Anderson 07/01/05 2:50 PM >>> >On Fri, 1 Jul 2005, Adriaan Renting wrote: >> I'm not a very experienced Python programmer yet, so I might be >> mistaken, but there are a few things that would make me prefer C++ over >> Python for large (over 500.000 LOC) projects. > >Hmm. I don't know C++, but here goes ... > >> - namespaces > >Aren't namespaces basically the same as packages/modules in python? > Not in the way C++ uses them. In Python if would be something like this: --------------------------- import os using namespace casa class os: def open(self, file): pass a = os.open('something') b = std::os.open('something') using namespace std c = casa::os.open('something') d = os.open('something') --------------------------- This is a realy stupid example. It's essentially an extra hierarchy layer to avoid naming clashes. I don't know of a way to do this in Python, how would you do this? >> - templates > >These would be meaningless in python - they're part of typefulness, which ... > >> - strong type checking > > >Not that this is necessarily a good thing. I have to say that my Java >roots do lead me to think that strong typing is a plus for big projects, >since it's a way of defining and enforcing interfaces between bits of code >written by different people (or by one person at different times!). >Optional static typing in python would be nice for this. > Exactly what I my point is, see also my other post on this (the LOC post) >> - data hiding > >Surely you can hide data in python? > Again, how? Is there a way to force that an external user of my lib can not use my internal data/methods/classes, unless he uses odd compiler hacks? >> - more available libraries and more advanced developement tools. > >True. The more advanced development tools are offset to a large degree by >the advanced crappiness of C++ as a language, though; i'd be surprised if >a C++ programmer borged up with all the latest tools was actually more >productive than a python programmer with a syntax-colouring, >auto-indenting text editor. It'd be very interesting to get some real >numbers on that. > I think my point is: I would be, for large projects. Just comparing my Borland C++Builder experience with my Eric3+QtDesigner experience. This is not only because of differences between C++ and Python though, a good IDE alone can make 50% difference but that's another subject. For small simple projects where I am familiar with the libs I need, I think I'd prefer Python. >>> Ultimately, manageability of a project is far and away more about the >>> people involved and the techniques used than it is about any single >>> technology involved. >> >> Agreed. > >+1 getting to the crux of it. > Thank you >tom From dial#####$$NOSPAM##$#$##tone at gmail.com Tue Jul 19 16:36:55 2005 From: dial#####$$NOSPAM##$#$##tone at gmail.com (Valentino Volonghi aka Dialtone) Date: Tue, 19 Jul 2005 22:36:55 +0200 Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121796584.974756.132430@g14g2000cwa.googlegroups.com> <1121805242.574679.298990@f14g2000cwb.googlegroups.com> Message-ID: <1gzyxek.10hvbk81iqiktgN%dial#####$$NOSPAM##$#$##tone@gmail.com> istvan.albert at gmail.com wrote: > I think the difficulties will arise from the inability to visually > track closing tags. > ]]] versus

United Rentals Inc.

3401 Commercial Dr.  Anchorage AK, 99501-3024

 

Phone - 907/272-4425
Fax - 907/272-9683

So from that I want output like : United Rentals Inc.,3401 Commercial Dr.,Anchorage,AK,"995013024","9072724425","9072729683" or United Rentals Inc. 3401 Commercial Dr. Anchorage AK 995013024 9072724425 9072729683 I have been messing around with beautiful soup (http://www.crummy.com/software/BeautifulSoup/index.html) but haven't gotten very far. (specially because the html is so sloppy) Any help would be really appreciated! Just point me in the right direction, what to use, examples... Thanks! -Sam From kay.schluehr at gmx.net Tue Jul 19 02:00:47 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jul 2005 23:00:47 -0700 Subject: Ordering Products In-Reply-To: References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: <1121752847.005587.145960@g44g2000cwa.googlegroups.com> Ron Adam wrote: > Kay Schluehr wrote: > > Here might be an interesting puzzle for people who like sorting > > algorithms ( and no I'm not a student anymore and the problem is not a > > students 'homework' but a particular question associated with a > > computer algebra system in Python I'm currently developing in my > > sparetime ). > > > > For motivation lets define some expression class first: > > > This works for (simple) expressions with mixed multiplication and addition. > > > class F(list): > def __init__(self,*x): > #print '\nF:',x > list.__init__(self,x) > def __add__(self, other): > return A(self,other) > def __radd__(self, other): > return A(other,self) > def __mul__(self, other): > return M(self,other) > def __rmul__(self, other): > return M(other,self) > def __repr__(self): > return str(self[0]) > def __order__(self): > for i in self: > if isinstance(i,A) \ > or isinstance(i,M): > i.__order__() > self.sort() > > class A(F): > def __init__(self, *x): > #print '\nA:',x > list.__init__(self, x) > def __repr__(self): > self.__order__() > return "+".join([str(x) for x in self]) > > class M(F): > def __init__(self,*x): > #print '\nM:',x > list.__init__(self,x) > def __repr__(self): > self.__order__() > return "*".join([str(x) for x in self]) > > > a = F('a') > b = F('b') > c = F('c') > d = F('d') > > print '\n a =', a > > print '\n b+a+2 =', b+a+2 > > print '\n c*b+d*a+2 =', c*b+d*a+2 > > print '\n 7*a*8*9+b =', 7*a*8*9+b > > > > >>> > > a = a > > b+a+2 = 2+a+b > > c*b+d*a+2 = 2+a*d+b*c > > 7*a*8*9+b = 9*8*7*a+b <-- reverse sorted digits? > >>> > > > The digits sort in reverse for some strange reason I haven't figured out > yet, but they are grouped together. And expressions of the type a*(c+b) > don't work in this example. > > It probably needs some better logic to merge adjacent like groups. I > think the reverse sorting my be a side effect of the nesting that takes > place when the expressions are built. > > Having the digits first might be an advantage as you can use a for loop > to add or multiply them until you get to a not digit. > > Anyway, interesting stuff. ;-) > > Cheers, > Ron Hi Ron, I really don't want to discourage you in doing your own CAS but the stuff I'm working on is already a bit more advanced than my mono-operational multiplicative algebra ;) Mixing operators is not really a problem, but one has to make initial decisions ( e.g about associativity i.e. flattening the parse-tree ) and sub-algebra generation by means of inheritance: >>> a,b = seq(2,Expr) >>> type(a+b) >>> class X(Expr):pass >>> x,y = seq(2,X) >>> type(x+y) This is not particular hard. It is harder to determine correspondence rules between operations on different levels. On subalgebras the operations of the parent algebra are induced. But what happens if one mixes objects of different algebras that interoperate with each other? It would be wise to find a unified approach to make distinctive operations visually distinctive too. Infix operators may be re-introduced just for convenience ( e.g. if we can assume that all algebras supporting __mul__ that are relevant in some computation have certain properties e.g. being associative ). ########################################################################## After thinking about M ( or Expr ;) a little more I come up with a solution of the problem of central elements of an algebra ( at least the identity element e is always central ) that commute with all other elements. Here is my approach: # Define a subclass of list, that provides the same interface as list and # a customized sorting algorithm import sets class Factors(list): def __init__(self,li): list.__init__(self,li) self.elems = sets.Set(li) # raw set of factors used in the __mul__ self._center = () # storing central elements commuting with # with all others def _get_center(self): return self._center def _set_center(self,center): Center = sets.Set(center) if not Center<=self.elems: raise ValueError,"Subset required" else: self._center = Center center = property(_get_center, _set_center) def __add__(self,li): return Factors(list.__add__(self,li)) def sort(self): center = list(self.center) def commutator(x,y): if isinstance(x,(int,float,long)): # numeral literals should return -1 # always commute if isinstance(y,(int,float,long)): return 1 if x == y: return 0 if x in center: if y in center: if center.index(x)>> a,b,c,d = M("a"),M("b"),M("c"),M("d") >>> y = c*3*a*d*c*b*7*c*d*a >>> y c*3*a*d*c*b*7*c*d*a >>> y.center = (c,d) >>> y.factors.sort() >>> y 7*3*c*c*c*d*d*a*b*a Regards, Kay From tiang_ono at yahoo.com Thu Jul 14 00:40:12 2005 From: tiang_ono at yahoo.com (Titi Anggono) Date: Wed, 13 Jul 2005 21:40:12 -0700 (PDT) Subject: installing vrmlexport module ?? Message-ID: <20050714044012.64586.qmail@web30711.mail.mud.yahoo.com> Hi all, I've downloaded vrmlexport.py from: http://www.andrew.cmu.edu/user/mzk/vrmlexport/ and install it under /usr/lib/python2.2/lib-old directory using command: python vrmlexport.py I got the following error: ============================================= Traceback (most recent call last): File "vrmlexport.py", line 662, in ? print export() File "vrmlexport.py", line 653, in export povray_code += findframes(scene) File "vrmlexport.py", line 584, in findframes vrml_objects += function(obj) File "vrmlexport.py", line 220, in export_box if (new_axis.x!=0 or new_axis.y!=0 or new_axis.z!=0): UnboundLocalError: local variable 'new_axis' referenced before assignment =============================================== Are there any suggestion ? (note, I am very new to python :) ) Thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From t-meyer at ihug.co.nz Fri Jul 29 21:26:13 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sat, 30 Jul 2005 13:26:13 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > We're talking at this point about how Path should work, not > whether it's preferable to os.path.join, even though that was > really the point of Reinhard's original post. That's not what I'm talking about. I'm talking about whether __div__ should be a shortcut to joinwith, or whether users should be forced to use joinwith explicitly. So far, there have been various statements that look like +0 for __div__, but no-one with a +1. (And I've said this a couple of times now, which really is just trolling for a +1 from someone). > It's not a question of saving characters, but readability which, as > you've said, is a matter of opinion. (Those who are offended by sweeping generalisations should ignore this next bit) I think it's also worth considering that Windows users are more clueless than users of posix systems. The readability of __div__ comes from familiarity with posix filesystems; for a Windows user, \ would be the natural character. So we're making things more readable for users that are already more likely figure things out, and less readable for users that have trouble figuring things out. > I can live with the latter, but as *someone who has used the > path module already* I can only say that you might want to try it > for a few months before condemning the approach using / as being > unacceptable. 1. ISTM that standard library modules should be as readable as possible, even for those that don't use them. If I'm reading the source for module X and it uses a Path object, then it should be pretty straightforward to understand what is happening without also having to read the Path source/docs. This (readability without knowing the language/standard libraries) is a huge benefit of using Python. 2. If I did use the Path module, then I wouldn't use __div__, because it looks less readable to me. I suppose I might find that I got annoyed typing joinpath, but I doubt it. Also, because I have followed this PEP, I know that __div__ means joinwith, so if I read code that used path, I would understand it - it's too late for me to try reading code as a 'fresh' user and see if it confuses me or not. =Tony.Meyer From davecook at nowhere.net Sun Jul 24 22:53:58 2005 From: davecook at nowhere.net (Dave Cook) Date: Mon, 25 Jul 2005 02:53:58 GMT Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> Message-ID: On 2005-07-24, Torsten Bronger wrote: > Is PyGTK more Pythonic by the way? I find it more Pythonic than "raw" wxpython. However, the API still has the fingerprints of C programmers all over it. Compare the gtk's clunky treemodel/treeview API to Cocoa's elegant delegates. There is a higher level interface for pygtk called kiwi: http://async.com.br/projects/kiwi/ Dave Cook From xah at xahlee.org Sun Jul 10 05:57:04 2005 From: xah at xahlee.org (Xah Lee) Date: 10 Jul 2005 02:57:04 -0700 Subject: What is Expresiveness in a Computer Language? Message-ID: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> What is Expresiveness in a Computer Language 20050207, Xah Lee. In languages human or computer, there's a notion of expressiveness. English for example, is very expressive in manifestation, witness all the poetry and implications and allusions and connotations and dictions. There are a myriad ways to say one thing, fuzzy and warm and all. But when we look at what things it can say, its power of expression with respect to meaning, or its efficiency or precision, we find natural languages incapable. These can be seen thru several means. A sure way is thru logic, linguistics, and or what's called Philosophy of Languages. One can also glean directly the incapacity and inadequacy of natural languages by studying the artificial language lojban, where one realizes, not only are natural languages incapable in precision and lacking in efficiency, but simply a huge number of things are near impossible to express thru them. One thing commonly misunderstood in computing industry is the notion of expressiveness. If a language has a vocabulary of (smile, laugh, grin, giggle, chuckle, guffaw, cackle), then that language will not be as expressive, as a language with just (severe, slight, laugh, cry). The former is "expressive" in terms of nuance, where the latter is expressive with respect to meaning. Similarly, in computer languages, expressiveness is significant with respect to semantics, not syntactical variation. These two contrasting ideas can be easily seen thru Perl versus Python languages, and as one specific example of their text pattern matching capabilities. Perl is a language of syntactical variegations. Python on the other hand, does not even allow changes in code's indentation, but its efficiency and power in expression, with respect to semantics, showcases Perl's poverty in specification. http://xahlee.org/perl-python/what_is_expresiveness.html ? Copyright 2005 by Xah Lee. Xah xah at xahlee.org ? http://xahlee.org/ From elmo13 at jippii.fi Wed Jul 13 16:22:01 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Wed, 13 Jul 2005 23:22:01 +0300 Subject: Searching for metadata related tools for use with python References: Message-ID: On Wed, 13 Jul 2005 15:49:27 +0300, Elmo M?ntynen wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I'm interested in various metadata > extraction/prosessing/distribution/something tools(including ways of > differentiating between files, eg hashing etc) and especially python > enabled ones. I'm also considering content-recognition/differentiating > eg. image recognition. I'm already aware of these: python-bitzi, > python-musicbrainz, mmpython, IMDbPY, python-mhash and imgSeek. If you > could point me to other relating resources it would be great. > > Elmo > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.1 (GNU/Linux) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFC1Q3WctNFyQJObrsRAjXbAJ92B53YC9NqtC9nymK07OL+L3mNTwCgmlbb > dPfSDsqJzBh+xa3h5L28Qac= > =AtAo > -----END PGP SIGNATURE----- I would also like comments if you're pretty sure the aren't any other related resources. Anything related to organizing one's filecollections(be it music, photos, books etc.), though i'm not particularly interested in another mp3/ogg-tagger(report it still though, if you will), would be interesting also. Elmo From buzzard at urubu.freeserve.co.uk Wed Jul 13 12:07:33 2005 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 13 Jul 2005 17:07:33 +0100 Subject: all possible combinations In-Reply-To: <1121269202.29571.1.camel@athop1.ath.vt.edu> References: <1121267364.28617.4.camel@athop1.ath.vt.edu> <1121269202.29571.1.camel@athop1.ath.vt.edu> Message-ID: rbt wrote: > On Wed, 2005-07-13 at 11:09 -0400, rbt wrote: > >>On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: >> >>>Say I have a list that has 3 letters in it: >>> >>>['a', 'b', 'c'] >>> >>>I want to print all the possible 4 digit combinations of those 3 >>>letters: >>> >>>4^3 = 64 >>> >>>aaaa >>>abaa >>>aaba >>>aaab >>>acaa >>>aaca >>>aaac >>>... >>> >>>What is the most efficient way to do this? >> >>Expanding this to 4^4 (256) to test the random.sample function produces >>interesting results. It never finds more than 24 combinations out of the >>possible 256. This leads to the question... how 'random' is sample ;) >> >>Try it for yourselves: >> >>test = list('1234') >> >>combinations = [] >>while 1: >> combo = random.sample(test, 4) >> possibility = ''.join(combo) >> if possibility not in combinations: >> print possibility >> combinations.append(possibility) >> continue >> else: >> continue >> > > > Someone pointed out off-list that this is doing permutation, not > combination. Is there a way to make random.sample to do combinations? > Probably not in any sensible way. But what you list in your original post are not distinct combinations. e.g. abaa and aaba are both 3 a's and 1 b. Maybe you mean that order does matter (and you're actually looking for all distinct permutations of all combinations)? Duncan From newsgroups at jhrothjr.com Fri Jul 29 08:42:21 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 29 Jul 2005 06:42:21 -0600 Subject: why functions in modules need 'global foo' for integer foo but not dictionary foo? References: <1122616696.886226.279510@f14g2000cwb.googlegroups.com> Message-ID: <11ek91h8lqqgj8d@news.supernews.com> wrote in message news:1122616696.886226.279510 at f14g2000cwb.googlegroups.com... > At top of a module I have an integer like so... > > foo = 4 > > In a function in that module I know I need to do 'global foo' to get at > the value 4. Actually, you don't need a "global foo" statement to _access_ the value. You do need a "global foo" to _rebind_ the value. > ... > > IIRC, for dictionaries you DO NOT have this issue? > > Why this scope problem with integers but not dictionaries? Telling an object to mutate itself doesn't rebind the object. so, if you wanted to say: foo = 5 and have it work at the module level, you'd need a global foo statement, while foo["bar"] = "spam" doesn't. The dictionary "foo" isn't rebound, all that's happening is that its state is being changed (that is, the key and value is being added to the dictionary). HTH John Roth > > Chris > From skip at pobox.com Mon Jul 25 13:39:22 2005 From: skip at pobox.com (skip at pobox.com) Date: Mon, 25 Jul 2005 12:39:22 -0500 Subject: how to imput usernames and passwords?? In-Reply-To: <000201c5913d$47909f20$8235a8c0@co.montezuma.co.us> References: <000201c5913d$47909f20$8235a8c0@co.montezuma.co.us> Message-ID: <17125.9162.34556.426438@montanaro.dyndns.org> Patrick> Is there a way I can have Python tell Oracle what the username Patrick> and password is? Dunno what db adapter module is used for Oracle, but the ones I've used for Sybase, PostgreSQL and MySQL all accept username/password parameters either individually or stuffed into a DSN string. Check the docs for the module you use to talk to Oracle. Skip From mwm at mired.org Sun Jul 3 20:10:35 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 20:10:35 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: <86acl31ldw.fsf@bhuda.mired.org> Steven D'Aprano writes: > I don't object to adding sum and product to the language. I don't object > to adding zip. I don't object to list comps. Functional, er, functions > are a good thing. We should have more of them, not less. Yes, but where should they go? Adding functions in the standard library is one thing. Adding builtins is another. Builtins make every python process heavier. This may not matter on your desktop, but Python gets used in embedded applications as well, and it does there. Builtins also clutter the namespace. Nothing really wrong with that, but it's unappealing. I'd say that removing functions is a bad thing. On the other hand, I'd say moving them from builtins to the standard library when Python has functionality that covers most of the use cases for them is a good thing. The latter has occured for map, filter, and reduce. Lambda I'm not so sure of, but it gets swept up with the same broom. Moving the first three into a library module seems like a good idea. I'm not sure about removing lambda. Removing map, filter and reduce remove most of my use cases for it. But not all of them. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From none at no.chance Fri Jul 29 05:14:54 2005 From: none at no.chance (Peter Tillotson) Date: Fri, 29 Jul 2005 09:14:54 +0000 Subject: Advanced concurrancy In-Reply-To: References: Message-ID: Cheers Guys, I have come across twisted and used in async code. What i'm really looking for is something that provides concurrency based on CSP or pi calculus. Or something that looks much more like Java's JSR 166 which is now integrated in Tiger. Peter Tillotson wrote: > Hi, > > I'm looking for an advanced concurrency module for python and don't seem > to be able to find anything suitable. Does anyone know where I might > find one? I know that there is CSP like functionality built into > Stackless but i'd like students to be able to use a standard python build. > > I'm trying to develop distributed / Grid computing modules based on > python. The aim is to be able to use barriers for synchronisation and > channels for communication between processes running on a single box. > Then the jump to multiple processes on multiple boxes and eventually to > MPI implementations. Hopefully, each jump should not be that big a leap. > > Of course it would be nice if there was a robust way of managing > concurrency in python aswell ;-) > > p From max at alcyone.com Tue Jul 26 02:51:11 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 25 Jul 2005 23:51:11 -0700 Subject: Extreme n00b question In-Reply-To: <1122358384.455900.91810@g44g2000cwa.googlegroups.com> References: <1122358384.455900.91810@g44g2000cwa.googlegroups.com> Message-ID: <7dydnSiF8ozCQHjfRVn-hg@speakeasy.net> Anupam Kapoor wrote: > is there a way to continue naming python sources as above, and still > use it as python modules ? i can ofcourse change the name to > 'a_simple_python_example.py', which then works. Something like a_simple_python_example = __import__('a-simple-python-example') -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From mwm at mired.org Sun Jul 3 16:24:22 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 16:24:22 -0400 Subject: website catcher References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> <3iq5e7Fmn8drU1@uni-berlin.de> <1120396132.606888.322880@g14g2000cwa.googlegroups.com> Message-ID: <86y88n1vux.fsf@bhuda.mired.org> "jwaixs" writes: > If I should put the parsedwebsites in, for example, a tablehash it will > be at least 5 times faster than just putting it in a file that needs to > be stored on a slow harddrive. Memory is a lot faster than harddisk > space. And if there would be a lot of people asking for a page all of > them have to open that file. if that are 10 requests in 5 minutes > there's no real worry. If they are more that 10 request per second you > really have a big problem and the framework would probably crash or > will run uber slow. That's why I want to open the file only one time > and keep it saved in the memory of the server where it don't need to be > opened each time some is asking for it. While Diez gave you some good reasons not to worry about this, and had some great advice, he missed one important reason you shouldn't worry about this: Your OS almost certainly has a disk cache. This means that if you get 10 requests for a page in a second, the first one will come off the disk and wind up in the OS disk cache. The next nine requests will get the pages from the OS disk cache, and not go to the disk at all. When you keep these pages in memory yourself, you're basically declaring that they are so important that you don't trust the OS to cache them properly. The exact details of how your using extra memory interact with the disk cache vary with the OS, but there's a fair chance that you're cutting down on the amount of disk cache the system will have available. In the end, if the OS disagrees with you about how important your pages are, it will win. Your pages will get paged out to disk, and have to be read back from disk even though you have them stored in memory. With extra overhead in the form of an interrupt when your process tries to access the swapped out page, at that. A bunch of very smart people have spent a lot of time making modern operating systems perform well. Worrying about things that it is already worrying about is generally a waste of time - a clear case of premature optimization. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From pinard at iro.umontreal.ca Fri Jul 1 11:41:12 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 1 Jul 2005 11:41:12 -0400 Subject: map/filter/reduce/lambda opinions and background In-Reply-To: <42C54DD2.B33289C7@pauahtun.org> References: <42C54DD2.B33289C7@pauahtun.org> Message-ID: <20050701154112.GA9550@phenix.progiciels-bpi.ca> [Ivan Van Laningham] > [Tom Anderson] > > [Guido] > > "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme > > folks. :-)" > > I disagree strongly with Guido's proposals, and i am not an ex-Lisp, > > -Scheme or -any-other-functional-language programmer; my only other > > real language is Java. I wonder if i'm an outlier. > > So, if you're a pythonista who loves map and lambda, and disagrees > > with Guido, what's your background? Functional or not? > I'm a pythonista who doesn't love them. Same here. `lambda' could go away. Yet `map' is sometimes useful... > And I've spent months inside of Lisp/Emacs Lisp/Scheme [...] I worked on Lisp / Scheme / Emacs-Lisp for many dozens of years. Moreover, a few times for unusual machines, I implemented Lisps. > (I have the world's second largest .emacs file [my friend Andy Glew > has the largest], even though I can't use it on Windows;-). You are a shameless lier! :-) It just _cannot_ beat the size of mine, at least not so long ago when I still was an Emacs user. And despite its size, my .emacs worked on a lot of systems, Windows included. > Personally, I find that Lisp & its derivatives put your head in a very > weird place. Lisp / Scheme are very OK! Usable for a wide range of applications, including system' -- with the proper choices, they can be fairly speedy as well. Yet, for ubiquitous and day-to-day work, Python is nicer! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From davecook at nowhere.net Sat Jul 9 08:00:58 2005 From: davecook at nowhere.net (Dave Cook) Date: Sat, 09 Jul 2005 12:00:58 GMT Subject: Defending Python References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> Message-ID: On 2005-07-08, Charlie Calvert wrote: > I perhaps rather foolishly wrote two article that mentioned Python as a > good alternative language to more popular tools such as C# or Java. I Sounds like a really hidebound bunch over there. Good luck. Dave Cook From mwm at mired.org Sun Jul 31 15:09:18 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 15:09:18 -0400 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <7x3bpve8w5.fsf@ruckus.brouhaha.com> Message-ID: <86wtn6g5cx.fsf@bhuda.mired.org> Paul Rubin writes: > The others are non-Pythonic because they're not included in the > standard distro and therefore the Pythonic "use the included > batteries" tenet says to use Tkinter despite its flaws. When did "use the included batteries" become pythonic? "import this" says nothing about batteries. Nah, using Tkinter is pythonic because "practicality beats purity". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jbellis at gmail.com Tue Jul 5 11:37:32 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 5 Jul 2005 08:37:32 -0700 Subject: threads and sleep? In-Reply-To: References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> Message-ID: <1120577852.042709.251940@o13g2000cwo.googlegroups.com> Jeffrey Maitland wrote: > The problem I have is I had an application > (wrote/co-wrote) that has a long run time dependant on some variables > passed to it (mainly accuracy variables, the more accurate the longer > the run time - makes sense). However in the hopes to speed it up I > decided to write a threaded version of the program to try and speed > it up. How ever what I am noticing is that the threaded version is > taking as long possibly longer to run. The thing is the threaded > version is running on an 8 ia-64 proccessor system and it seems to > only be using 2 or 3 porcessors at about 30% (fluxiates). My guess is > that 6 threads are running they are using 30% sprox each of a 2 given > CPUS. In many ways, Python is an incredibly bad choice for deeply multithreaded applications. One big problem is the global interpreter lock; no matter how many CPUs you have, only one will run python code at a time. (Many people who don't run on multiple CPUs anyway try to wave this off as a non-problem, or at least worth the tradeoff in terms of a simpler C API, but with multicore processors coming from every direction I think the "let's pretend we don't have a problem" approach may not work much longer.) If the GIL isn't an issue (and in your case it clearly is), you'll quickly find that there's little support for debugging multithreaded applications, and even less for profiling. Sometimes running multiple processes is an acceptable workaround; if not, good luck with the rewrite in Java or something else with real thread support. (IIRC Jython doesn't have a GIL; that might be an option too.) Python is a great tool but if you really need good threading support you will have to look elsewhere. -Jonathan From jmeile at hotmail.com Fri Jul 29 10:13:36 2005 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 29 Jul 2005 16:13:36 +0200 Subject: functions without parentheses In-Reply-To: References: <42e9c49b.24281464@news.oz.net> Message-ID: <42EA3990.9040202@hotmail.com> Steven D'Aprano wrote: > On Fri, 29 Jul 2005 06:37:52 +0000, Bengt Richter wrote: > > >>I suggested in a previous thread that one could support such a syntax by >>supporting an invisible binary operator between two expressions, so that >>examine "string" translates to examine.__invisbinop__("string") if >>examine as an expression evaluates to an object that has a __invisbinop__ method. > > > Why would you want to? > My best guest is that the OP uses VB, where you can do that. I personally hate this feature because it just makes me do a lot of mistakes. ie: In VB you can do: fooFunction fooParameter but if you want to assign this to a variable you **must** use this: fooVer = fooFunction(fooParaMeter) I really get confused because I automatically use the braces. Regards, Josef From rrr at ronadam.com Sat Jul 9 01:15:00 2005 From: rrr at ronadam.com (Ron Adam) Date: Sat, 09 Jul 2005 05:15:00 GMT Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120883125.259644.80490@g47g2000cwa.googlegroups.com> References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> <1120883125.259644.80490@g47g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > > Leif K-Brooks schrieb: > >>Kay Schluehr wrote: >> >>>Well, I want to offer a more radical proposal: why not free squared >>>braces from the burden of representing lists at all? It should be >>>sufficient to write >>> >>> >>>>>>list() >>> >>>list() >> >>So then what would the expression list('foo') mean? Would it be >>equivalent to ['foo'] (if so, how would you convert a string or other >>iterable to a list under Py3k?), or would it be equivalent to ['f', 'o', >>'o'] as it is in now (and is so, what gives?)? > > > Spiltting a string and putting the characters into a list could be done > in method application style: > > >>>>"abc".tolist() > > list('a','b','c') "abc".splitchrs() There's already a str.split() to create a list of words, and a str.splitline() to get a list of lines, so it would group related methods together. I don't thin adding sting methods to lists is a good idea. Cheers, Ron From deets at web.de Sun Jul 3 10:36:45 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 03 Jul 2005 16:36:45 +0200 Subject: How to dump an interpreter image? In-Reply-To: <1120399050.c415fe77ae7ee03d168dc545a8537022@teranews> References: <1120399050.c415fe77ae7ee03d168dc545a8537022@teranews> Message-ID: <3iqbftFmpo8nU1@uni-berlin.de> VansMll wrote: > Hi, is it possible to save a state of the python interpreter to disk and > load it later? Should be doable in stackless python. Diez From guettli at thomas-guettler.de Tue Jul 12 09:54:02 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 12 Jul 2005 15:54:02 +0200 Subject: Search & Replace with RegEx References: <1121155904.551248.102700@o13g2000cwo.googlegroups.com> Message-ID: Am Tue, 12 Jul 2005 01:11:44 -0700 schrieb tchurm at gmail.com: > Hi Pythonistas, > > Here's my problem: I'm using a version of MOOX Firefox > (http://moox.ws/tech/mozilla/) that's been modified to run completely > from a USB Stick. It works fine, except when I install or uninstall an > extension, in which case I then have to physically edit the compreg.dat > file in my profile directory, replacing all instances of Absolute Path > links to relative ones. (And, yes, I have filed a Bugzilla report.) > > For example, after installing a new extension, I change in compreg.dat > > lines such as: > > abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{0538E3E3-7E9B-4d49-8831-A227C80A7AD3}\components\nsForecastfox.js,1111185900000 > abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{c4dc572a-3295-40eb-b30f-b54aa4cdc4b7}\components\wml-service.js,1114705020000 > > to: > > rel:nsForecastfox.js,1111185900000 > rel:wml-service.js,1114705020000 Hi, some time ago I wrote "replace-recursive.py": http://www.thomas-guettler.de/scripts/replace_recursive.py.txt Maybe this helps you, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 07:55:56 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 13:55:56 +0200 Subject: Path inherits from basestring again In-Reply-To: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> References: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> Message-ID: <3l186cF10lgkmU1@individual.net> NickC wrote: > [Re: alternatives to overloading '/'] > > Is there a reason the Path constructor is limited to a single argument? > If it allowed multiple arguments, the following would seem very > straightforward: > > p = Path(somePath, user.getFolder(), 'archive', oldPath + ".bak") That's a quite good idea. Thanks! > I'm usually not much of a purist, but C++ has convinced me that > overloading an operator to mean something entirely unrelated to its > mathematical meaning can be very unwise. It's much the same as with @ decorators. Those who have used them much don't object to the syntax any more. Reinhold From rrr at ronadam.com Fri Jul 8 02:41:49 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 08 Jul 2005 06:41:49 GMT Subject: Use cases for del In-Reply-To: <42CE0E38.60305@REMOVEMEcyber.com.au> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Ron Adam wrote: >> def count_records(record_obj, start=0, end=len(record_obj)): > > > That would work really well, except that it doesn't work at all. Yep, and I have to stop trying to post on too little sleep. Ok, how about... ? def count_records(record_obj, start=0, end='to-end'): if end == 'to-end': end = len(record_obj) n = 0 for rec in record_obj.data[start:end]: if not rec.isblank(): n += 1 return n This isn't really different from using None. While it's possible to avoid None, its probably not worth the trouble. I use it myself. Here's something interesting: import time x = None t = time.time() for i in range(1000000): if x==None: pass print 'None:',time.time()-t x = 'to-end' t = time.time() for i in range(1000000): if x=='to-end': pass print 'String:',time.time()-t >>> None: 0.46799993515 String: 0.360000133514 Of course the difference this would make on a single call in practically Nill. Anyway, time to call it a night so tomorrow I don't make anymore silly mistakes on comp.lang.python. :) Cheers, Ron From bokr at oz.net Sat Jul 30 19:58:22 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Jul 2005 23:58:22 GMT Subject: Comparison of functions References: <42eb70a1$0$28646$636a15ce@news.free.fr> Message-ID: <42ebfa3d.169083369@news.oz.net> On Sat, 30 Jul 2005 23:37:04 +1000, Steven D'Aprano wrote: >On Sat, 30 Jul 2005 14:20:50 +0200, tiissa wrote: > >> Steven D'Aprano wrote: >>> Playing around with comparisons of functions (don't ask), I discovered an >>> interesting bit of unintuitive behaviour: >>> >>>>>>a = lambda y: y >>>>>>b = lambda y: y >>>>>>a >>> at 0xf70598ec> >>>>>>b >>> at 0xf7059844> >>>>>>a < b >>> False >>> >>> So I'm puzzled about how Python compares the two. >> >> Seems to me the object addresses are compared in this case. But I'm too >> lazy to check it in the source. ;) > >Strangely enough, I'm lazy enough to not check the source too :-) > >Actually, more to the point, I don't read C, so even if I did check the >source, I wouldn't know what it was trying to tell me. > >> However, the doc [1] warns you about such comparisons: """Most other >> types compare unequal unless they are the same object; the choice >> whether one object is considered smaller or larger than another one is >> made arbitrarily but consistently within one execution of a program.""" > >I am aware of that. That's a wart. > What if rich sorting "measured" the objects it was sorting, to form a measurement tuple of primitive types, so that you'd wind up sorting as if by a decorated list with the measurement tuple as the decoration, e.g., (an I think having to wrap complex for sorting is CWrap ;-) Just a sketch to illustrate an idea for sorting... ----< richlysorted.py >------------------------------------- def richlysorted(seq): return ((type(v) is CWrap and [v.v] or [v])[0] for d,v in sorted(measure_dec(seq))) INT = LONG = FLOAT = 0 COMPLEX = 1 STR = 2 UNICODE = 3 FUNCTION = 4 TYPE = 5 DEFAULT = 6 type_sort_order = dict( int=INT, long=LONG, float=FLOAT, complex=COMPLEX, str=STR, unicode=UNICODE, function=FUNCTION, type=TYPE) class CWrap(object): def __init__(self, v): self.v=v def __eq__(self, other): return True def measure_dec(seq): for v in seq: sort_priority = type_sort_order.get(type(v).__name__, DEFAULT) if sort_priority == COMPLEX: yield (sort_priority, v.real, v.imag), CWrap(v) elif sort_priority <= UNICODE: yield (sort_priority,), v elif sort_priority == FUNCTION: yield (sort_priority, v.func_name, v.func_code.co_argcount), v elif sort_priority == TYPE: yield (sort_priority, v.__name__), v else: yield (sort_priority, type(v).__name__, repr(v)) , v def test(): class C: pass class D(object): pass def foo(): pass def bar(a,b): pass tbs = [1, -1.0, 1+0j, 2j, lambda x:x, test, measure_dec, lambda:None, foo, bar, D, D(), C(), C, 2**32, -2**32] for tup in zip(tbs, measure_dec(tbs)): print '%35s | %-s' % tup print '%s\nSorted:'% (50*'-') for item in richlysorted(tbs): print '%35s' % item if __name__ == '__main__': test() ------------------------------------------------------------ [16:57] C:\pywk\ut>py24 richlysorted.py 1 | ((0,), 1) -1.0 | ((0,), -1.0) (1+0j) | ((1, 1.0, 0.0), <__main__.CWrap object at 0x02F00B2C>) 2j | ((1, 0.0, 2.0), <__main__.CWrap object at 0x02F00B4C>) at 0x02EE8DF4> | ((4, '', 1), at 0x02EE8DF4>) | ((4, 'test', 0), ) | ((4, 'measure_dec', 1), ) at 0x02EE8E2C> | ((4, '', 0), at 0x02EE8E2C>) | ((4, 'foo', 0), ) | ((4, 'bar', 2), ) | ((5, 'D'), ) <__main__.D object at 0x02F0044C> | ((6, 'D', '<__main__.D object at 0x02F0044C>'), <__main__. D object at 0x02F0044C>) <__main__.C instance at 0x02F004CC> | ((6, 'instance', '<__main__.C instance at 0x02F004CC>'), < __main__.C instance at 0x02F004CC>) __main__.C | ((6, 'classobj', ''), ) 4294967296 | ((0,), 4294967296L) -4294967296 | ((0,), -4294967296L) -------------------------------------------------- Sorted: -4294967296 -1.0 1 4294967296 2j (1+0j) at 0x02EE8E2C> at 0x02EE8DF4> <__main__.D object at 0x02F0044C> __main__.C <__main__.C instance at 0x02F004CC> Regards, Bengt Richter From pramodgold at hotmail.com Fri Jul 15 22:20:53 2005 From: pramodgold at hotmail.com (peter patel) Date: Sat, 16 Jul 2005 02:20:53 -0000 Subject: urllib2.URLError: Urlopen error - (7, 'getaddrinfo failed') It means their tracker is overworked. Nothin you can do about it.. let it run.. it should start workin sooner or later. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Wed Jul 6 10:41:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 06 Jul 2005 08:41:07 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: Terry Hancock wrote: > And a syntax just occured to me -- what about this: > > [y*x for x,y] > > ? > > (that is: > > [ for ] If you haven't already, see: http://wiki.python.org/moin/AlternateLambdaSyntax for other similar proposals. STeVe From varghjarta at gmail.com Sun Jul 24 23:41:17 2005 From: varghjarta at gmail.com (=?ISO-8859-1?Q?Varghj=E4rta?=) Date: Mon, 25 Jul 2005 11:41:17 +0800 Subject: Fire event when variable is Set/Get Message-ID: Hey! I'm a hobby programmer since many years now and I've done most of my latest 'real application' coding in C#. I've played with python of and on yet not catching on until a few months ago when I got myself hocked on it for real and now I love C# _and_ Python. But there is something that keeps bugging me, and that keeps me from embracing Python even more as a serious alternative to C#(for me). In C# I make heavy use of Get & Set, mainly to fire an event that some property has changed so that one can act on that _if one would need to. I've grown very used to doing it and it feels like the best way to make very OO and reusuable and easy to use Classes. Is there _anything_ that I could do in Python which would allow me to known when a variable has been set or when it's being fetched to allow me to fire an event there?. I seriously _hate_ having to use methods for editing variables (setVariable1("blah")) since it just adds more code -- or perhaps not but the code doesn't flow as nicely. So I don't count this as a real valid option. This might seem like not such a big thing but to me it's such a problem that it's driving me to even consider trying out Boo (the c#/python hybrid) when I get the chance eventhough I think i'd rather use the _original_ (python) now when i'm almost getting the hang of it. How does python coders generally deal with this? Does everyone inherit from a class and override the methods that sets variables and does the work from there? I love events and use them heavily -- in GUI apps what else would one use? Would be thankful for any pointers that would evolve my pythonic strives. From gnb at itga.com.au Thu Jul 7 00:01:13 2005 From: gnb at itga.com.au (Gregory Bond) Date: Thu, 07 Jul 2005 14:01:13 +1000 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> <1120635954.442101.99920@g47g2000cwa.googlegroups.com> Message-ID: <9e9iad.b46.ln@lightning.itga.com.au> Rocco Moretti wrote: > Actually, Google's answer to that question is something called "ILOG > CPLEX", We use this. It's a library / command line tool (not a language) for doing optimization - linear programming, quadratic programming, mixed-integer programming etc. Very cool and very, very scarey. From jasx at freemail.it Tue Jul 5 12:47:06 2005 From: jasx at freemail.it (Jxzzy78) Date: Tue, 5 Jul 2005 18:47:06 +0200 Subject: resume upload Message-ID: How can i resume a partial upload using ftplib ? From jgrahn-nntq at algonet.se Wed Jul 6 06:18:45 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 6 Jul 2005 10:18:45 GMT Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <1120575861.296553.303750@z14g2000cwz.googlegroups.com> Message-ID: On 5 Jul 2005 08:04:21 -0700, jwaixs wrote: ... > The python re module is, in my opinion, a non beginner user friendly > module. And it's not meant for beginning python programmers. I don't > have any experience with perl or related script/programming languages > like python. (I prefer to do things in c) So the re module is > completely new for me. Actually, REs are a useful tool even in C, for example for validating input before parsing it with custom code, so you can forget about some of the error checking in the parsing code. ... although you have to be on a Unix system to be reasonably sure that they are available, and even then you're looking at a much less powerful RE language than the ones in Python and Perl. That's another problem with REs -- there are many slightly different RE languages, and sometimes you cannot even be sure which one you're working with. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From roy at panix.com Fri Jul 1 14:47:04 2005 From: roy at panix.com (Roy Smith) Date: 1 Jul 2005 14:47:04 -0400 Subject: Assigning to None References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <86ekai5sk7.fsf@bhuda.mired.org> Message-ID: >Peter Hansen writes: > >> Mike Meyer wrote: >>> Yes. I once grabbed an old program that did assignments to None. But >>> that's always been a bad idea. >> What was the use case!? > >Unpacking a tuple. Something like this: > > (foo, bar, None) = gen_tuple(stuff) I can see several reasonable ways to avoid that. 1) If you wrote gen_tuple(), and know you don't need the third element of the tuple, just change gen_tuple() to only return the first two! Or, invent a little data class for it to return. If you can't do that (for whatever reason), then... 2) foo, bar, baz = gen_tuple(stuff), where foo, bar, and baz are all meaningful names. 3) foo, bar, dummy = gen_tuple(stuff), to emphasize that the last value is ignored. 4) foo, bar = gen_tuple(stuff)[0:1]. In some ways, this is the cleanest because it doesn't pollute the namespace with an un-needed variable, but I think it's the least readable. From peter at engcorp.com Fri Jul 1 00:08:44 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 00:08:44 -0400 Subject: How to run commands in command line from a script In-Reply-To: References: Message-ID: Peter Hansen wrote: > Ivan Shevanski wrote: >> Alright well I'm quite a noob and when I run a simple command to >> change the current directory, nothing happens. I made a little test >> script to show it: > > Generally, the only way to use an application (i.e. a program like the > Python interpreter, or your own .exe) to change the working folder is to > have your script executed from within a batch file, write out a new > batch file in your script, and then have the calling batch file execute > that script if it exists. And, after that long-winded reply, here's another option, if you're just trying to change the directory _within_ your app but don't care if the change persists: import os os.chdir(r'c:\Program Files') -Peter From steven.bethard at gmail.com Sun Jul 24 16:14:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 24 Jul 2005 14:14:15 -0600 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: Thanos Tsouanas wrote: > Steven Bethard wrote: > >>Maybe I'm not understanding your problem, but have you looked at the >>builtin "vars()"? > > I didn't know about it, but I knew about object.__dict__ which is, as I > see equivalent with vars(object). But it doesn't do the job for me, > since it fails to grab all obj.foo's, some of them being properties, > etc. How about something like: dict((name, getattr(obj, name)) for name in dir(obj)) For example: py> class C(object): ... x = 1 ... @property ... def y(self): ... return 2 ... def __init__(self): ... self.z = 3 ... py> c = C() py> d = dict((name, getattr(c, name)) for name in dir(c)) py> d['x'] 1 py> d['y'] 2 py> d['z'] 3 Looks like this will get instance attributes, class attributes and properties just fine. STeVe From rtw at freenet.co.uk Sat Jul 9 08:34:51 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 09 Jul 2005 07:34:51 -0500 Subject: Problem with sha.new References: Message-ID: Florian Lindner wrote in news:daodmf$4gf$00$1 at news.t-online.com in comp.lang.python: > Hello, > I try to compute SHA hashes for different files: > > > for root, dirs, files in os.walk(sys.argv[1]): > for file in files: > path = os.path.join(root, file) > print path > f = open(path) Here you rebind 'sha' from what it was before (presumably the module sha) to the result of 'sha.new' presumably the new 'sha' doesn't have a 'new' method. try renameing your result variable. > sha = sha.new(f.read()) > sha.update(f.read()) > print sha.hexdigest() result = sha.new(f.read()) result.update(f.read()) print result.hexdigest() also I don't think you need the second call to update as f will have been read by this time and it will add nothing. > > > this generates a traceback when sha.new() is called for the second > time: > > sha = sha.new(f.read()) > AttributeError: new > Rob. -- http://www.victim-prime.dsl.pipex.com/ From bokr at oz.net Wed Jul 13 01:44:29 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Jul 2005 05:44:29 GMT Subject: extend for loop syntax with if expr like listcomp&genexp ? References: <42d30319.417620065@news.oz.net> <42d30af1$1@news.eftel.com> <42d31b7a.423861700@news.oz.net> Message-ID: <42d4a7e7.48358205@news.oz.net> On Tue, 12 Jul 2005 23:07:07 -0500, Terry Hancock wrote: >On Monday 11 July 2005 08:53 pm, Bengt Richter wrote: >> On Tue, 12 Jul 2005 10:12:33 +1000, John Machin wrote: >> >Bengt Richter wrote: >> >> for x in (x for x in seq if x is not None): >> >Byzantine ... >> Perhaps not if you wanted to enumerate the selected elements, as in >> for i, x in enumerate(x for x in seq if x is not None): > >Seems like a bug waiting to happen -- wouldn't someone using that >idiom most likely have *meant* something like this: > >for i,x in enumerate(seq): > if x is not None: > print "seq[%d] = %s is not None" % (i, repr(x)) > >? > >But of course that's not equivalent. It's hard to imagine a >use case for an enumerated loop when the object being >iterated over is anonymous (will be lost as soon as the loop >exits). > Line numbers in a listing of non-None things? Page breaks at the right places? Filtering out '' instead of NOne from results of a string split before creating numbered html names for links to non-blank text elements in rendering text as html? I dunno, seems like at least a few possibilities for something halfway sensible... Regards, Bengt Richter From davefickbohm at yahoo.com Wed Jul 20 17:07:17 2005 From: davefickbohm at yahoo.com (David Fickbohm) Date: Wed, 20 Jul 2005 14:07:17 -0700 (PDT) Subject: looking for an introduction to python book Message-ID: <20050720210717.8129.qmail@web50802.mail.yahoo.com> People, I am looking for an introduction to python book. Hopefully with a windows orientation Thanks Dave Dave Fickbohm Use Technology to the Fullest 1250 45th st suite 200 Emeryville, CA, 94608 510 594 4151 voice --------------------------------- Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thorsten at thorstenkampe.de Sat Jul 30 07:21:37 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 30 Jul 2005 12:21:37 +0100 Subject: Hiding References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> <1122662993.207041.89630@f14g2000cwb.googlegroups.com> <1122692712.976074.48870@g49g2000cwa.googlegroups.com> <1122709872.393066.162510@g43g2000cwa.googlegroups.com> Message-ID: <13l1l1db7tw24$.1rz9j5a48d12m$.dlg@40tude.net> * Jay (2005-07-30 08:51 +0100) > but also, wat if i needed to hide the loading of a file As others have pointed out: your question is pointless as opening a file doesn't load it or open it in your preferred application. You are confusing Operating System semantics with Python semantics. You're probably only asking this question because you've never actually tried it. The solution for your problem is to read a beginner's tutorial about Python. > or the even hide the whole python window to run in background?? is > there no module or function i can use???? On windows: use pythonw.exe instead of python.exe. From c at cdot.de Sun Jul 10 14:40:05 2005 From: c at cdot.de (Chris) Date: Sun, 10 Jul 2005 20:40:05 +0200 Subject: urllib2.urlopen hangs, urllib.urlopen works? Message-ID: hello, I have an odd behaviour. I try to download some files connected to a specific webpage (e.g. all stylesheets) with urllib2.urlopen(x) This seems to hang on the 2nd file or so. Doing the exact same thing via urllib.urlopen(x) does work without a hitch... I don't really to use urllib instead of urllib2 but am wondering where the problem is and if there is a workaround (or just my own stupidity)? Also with urllib I cannot send my own user-agent header as i wanted to do... thanks for any hint! chris From tdelaney at avaya.com Wed Jul 6 19:45:18 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 7 Jul 2005 09:45:18 +1000 Subject: frozenset question Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CB3E@au3010avexu1.global.avaya.com> Steven D'Aprano wrote: > If, over a thousand runs of the program, you save a millisecond of > time in total, but it costs you two seconds to type the comment in > the code explaining why you used frozenset instead of the more > natural set, then your "optimization" is counter-productive. Even > just considering the question is a waste of valuable developer time! > THAT is the lesson of premature optimization: don't even THINK about > optimizing code until you have it WORKING and you have MEASURED that > it is too slow. Tell me about it. I've had to strongly argue against premature optimisation in my current project. I said "make it work and we'll make it fast at the end". Well, I made my part work. Then I spent less than a week optimising and made it over 1000 times faster, without obfuscating it. Meanwhile other parts still don't work, but contain lots of premature optimisations that combined have taken well over a week to put into place. Tim Delaney From http Sun Jul 31 19:57:46 2005 From: http (Paul Rubin) Date: 31 Jul 2005 16:57:46 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <8664uqhkfj.fsf@bhuda.mired.org> Message-ID: <7xu0iale9x.fsf@ruckus.brouhaha.com> Cliff Wells writes: > > And what do I use to bundle my application for Unix? Most of the > > things I build get installed on Unix servers. > > You install GUI apps on Unix *servers*? The usual way to do that is with a web GUI, but nothing stops you from running Tkinter on a Unix server through a remote X connection. From hancock at anansispaceworks.com Sat Jul 23 21:24:48 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 23 Jul 2005 20:24:48 -0500 Subject: is this possible? In-Reply-To: References: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> <1122044382.956382.287310@g47g2000cwa.googlegroups.com> Message-ID: <200507232024.48612.hancock@anansispaceworks.com> On Saturday 23 July 2005 03:26 am, Steven D'Aprano wrote: > On Fri, 22 Jul 2005 07:59:42 -0700, scrimp wrote: > As others have suggested, if you have to deal with PDF files without > Acrobat, you could use ghostscript. Also pre-installed on many versions > of Linux, and probably other Unixes as well, is pdf2ps which will convert > the PDF file to a pure postscript file, which you can then print to any > printer which understands postscript. IIRC, "pdf2ps" is a utility that comes with Ghostscript, and actually does use it to do the transformation (that is, I think it's just a script to run ghostscript with the appropriate options). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From paolo.veronelli at gmail.com Thu Jul 28 02:11:42 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Thu, 28 Jul 2005 08:11:42 +0200 Subject: can list comprehensions replace map? In-Reply-To: <1122508803.920261.303730@g49g2000cwa.googlegroups.com> References: <1122508803.920261.303730@g49g2000cwa.googlegroups.com> Message-ID: <42E8771E.8010404@gmail.com> Raymond Hettinger wrote: > [David Isaac] > >>>I have been generally open to the proposal that list comprehensions >>>should replace 'map', but I ran into a need for something like >>>map(None,x,y) >>>when len(x)>len(y). I cannot it seems use 'zip' because I'll lose >>>info from x. How do I do this as a list comprehension? (Or, >>>more generally, what is the best way to do this without 'map'?) > > > [Paolino] > >>Probably zip should change behaviour,and cover that case or at least >>have another like 'tzip' in the __builtins__ .Dunno, I always thought >>zip should not cut to the shortest list. > > > Heck no! For the core use case of lockstep iteration, it is almost > always a mistake to continue iterating beyond the length of the > shortest input sequence. Even for map(), the use cases are thin. How > many functions do something meaningful when one or more of their inputs > changes type and becomes a stream of Nones. Consider for example, > map(pow, seqa, seqb) -- what good can come of one sequence or the other > suddenly switching to a None mode? > > As Andrew pointed out, if you really need that behavior, it can be > provided explicity. See the padNone() recipe in the itertools > documentation for an easy one-liner. > > IMO, reliance on map's None fill-in feature should be taken as a code > smell indicating a design flaw (not always, but usually). There is a > reason that feature is missing from map() implementations in some other > languages. > > In contrast, the existing behavior of zip() is quite useful. It allows > some of the input sequences to be infinite: > > zip(itertools.count(1), open('myfile.txt')) > Right point. Well, for my little experiences use cases in which the lists have different lengths are rare, but in those cases I don't see the reason of not being able to zip to the longest one.What is really strange is that I have to use map(None,....) for that,instead of another zip-like function which ,at least would be intutitive for the average user.Also map(None,...) looks like a super-hack and it's not elegant or readable or logic (IMO) I think zip comes to substitute the tuple.__new__ untolerant implementation.A dumb like me wuold expect map(tuple,[1,2,3],[2,3,4]) to work, so pretending map(None,....) would do it is like saying that None and tuple are near concepts, which is obviously an absurdity. Thanks anyway, for explanations. Paolino > > Raymond > From steve at REMOVETHIScyber.com.au Sat Jul 2 21:45:41 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 11:45:41 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> Message-ID: On Fri, 01 Jul 2005 09:13:58 -0700, mcherm wrote: > Lambda serves a very specific purpose: declaring small, in-place > functions which are no bigger than a single expression. I do this often > enough that I DO want special syntax for it. But I'll admit that I > wish "lambda" were about 5 or 6 characters shorter As in an empty string? :-) > and didn't have such an obscure name. Lambda is no more an obscure name than "function", "decorator", "closure", "class", or "module". The first time you come across it, you don't know what it means. Then you learn what it means, and then you know. -- Steve From peter at engcorp.com Mon Jul 11 23:41:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Jul 2005 23:41:06 -0400 Subject: tuple.index(item) In-Reply-To: References: Message-ID: David Isaac wrote: > Why don't tuples support an index method? > It seems natural enough ... This question has been posed several (many?) times in the past. See the archives for more detail, but basically the answer that is usually given is this: Tuples are intended to be used somewhat like C "structs", or Pascal "records", which is to say they should contain heterogeneous sequences of information for which the concept of ".index()" is fairly meaningless. They are _not_ generally intended to be used as "read-only lists", and that's basically why .index() wasn't defined for them. Another answer that probably follows close on the heels of that one is along the lines of "patches are always welcome", but I honestly don't know if a patch to add this would be accepted. Probably checking Sourceforge for past patches would give an answer, since it seems likely someone has already tried. -Peter From fred.dixon at gmail.com Wed Jul 20 11:20:16 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 20 Jul 2005 08:20:16 -0700 Subject: wxPython field validation In-Reply-To: <1121870807.661993.27740@f14g2000cwb.googlegroups.com> References: <1121870807.661993.27740@f14g2000cwb.googlegroups.com> Message-ID: <1121872816.588189.45600@g44g2000cwa.googlegroups.com> why not validate then put cursor back into that field until satisfied. might use the lost focus (cant remember exact name right now) From gijs at globaltrack.com Fri Jul 1 09:56:40 2005 From: gijs at globaltrack.com (Gijs Korremans) Date: Fri, 1 Jul 2005 06:56:40 -0700 Subject: FWD: [python-win32] coinitialize problem Message-ID: <200507011358.j61DwkUt016500@rrba-146-123-117.telkomadsl.co.za> Hi, I'm extending a Python application that uses several com objects and threads. The origional programmer set the main thread to multithreaded by doing this: * sys.coinit_flags = 0 * import pythoncom This is nessacary because otherwise a com (MapObjects2 from ESRI) can't run in a thread, but now I need to use another com object, which is running in a thread as well. This com object, made by one of our clients, needs to run in a single threading model. For some reason, these two com object won't work together in one application. MapObjects2 works when the coini_flags is set to 0 but then the other com object isn't working and the other way around. I've tried a lot of things to solve this: 1) don't import pythoncom in the main thread -- set the mapobjects thread with coInitializeEx(COINIT_MULTITHREADED) -- set the other trhead with CoInitialize() 2) tried the same things but then with initializing coinit in the mainthread with both models 3) Made a some test programs, but I had always the same problems, except when I made 2 functions for the 2 com objects, and started them with beginthreadex (like described on page 626 from Mark Hammonds book Python programming on win32) and then coinitialize in the functions, but unfortunately, this is not an option in our main program Strange enough, we use 2 other comobjects, adotable for mssql and a com object for sending smses, and these two are always working. Can anyone help me with a solution? and maybe som examples? Kind Regards, Gijs -- This message has been scanned for viruses and dangerous content by Network Sentry, and is believed to be clean. http://www.networksentry.co.za From reinhold-birkenfeld-nospam at wolke7.net Sun Jul 10 04:49:36 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 10 Jul 2005 10:49:36 +0200 Subject: Use cases for del In-Reply-To: References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <1120825627.498017.19370@g47g2000cwa.googlegroups.com> <42d0529a$1@nntp0.pdx.net> Message-ID: <3jc5p0Fp4nlgU1@individual.net> Ron Adam wrote: >> >>> 'abc' is 'abcd'[:3] >> False > > Well of course it will be false... your testing two different strings! > And the resulting slice creates a third. > > Try: > > ABC = 'abc' > > value = ABC > if value is ABC: # Test if it is the same object > pass That's not going to buy you any time above the "is None", because identity- testing has nothing to do with the type of the object. Additionally, using "is" with immutable objects is horrible. Reinhold From rbt at athop1.ath.vt.edu Tue Jul 19 13:36:09 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 19 Jul 2005 13:36:09 -0400 Subject: goto In-Reply-To: References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <1121781747.6b5089eb6576a56f3b0851ea53fe69e0@teranews> <1121786998.7497.0.camel@athop1.ath.vt.edu> Message-ID: <1121794569.9943.3.camel@athop1.ath.vt.edu> On Wed, 2005-07-20 at 03:43 +1000, Steven D'Aprano wrote: > On Tue, 19 Jul 2005 11:29:58 -0400, rbt wrote: > > >> It should not really come as a shock that the same fellow who came up with a brilliant efficient way > >> to generate all permutations (http://tinyurl.com/dnazs) is also in favor of goto. > >> > >> Coming next from rbt: "Pointer arithmetic in python ?". > >> > >> George > >> > >> > > > > I have moments of brilliance and moments of ignorance. You must admit > > though, that was a unique way of generating permutations... how many > > other people would have thought of that approach? It did solve my > > problem ;) > > Sorry rbt, but your algorithm isn't unique, nor was it clever, and in fact > your implementation wasn't very good even by the undemanding requirements > of the algorithm. It is just a minor modification of bogosort (also known > as "bozo-sort") algorithm: > > http://en.wikipedia.org/wiki/Bogosort > > I quote: > > "...bogosort is 'the archetypal perversely awful algorithm', one example > of which is attempting to sort a deck of cards by repeatedly throwing the > deck in the air, picking the cards up at random, and then testing whether > the cards are in sorted order." > > Bogosort is nothing to be proud of, except as a joke. It *was* a joke. From gsakkis at rutgers.edu Mon Jul 4 11:23:29 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 4 Jul 2005 08:23:29 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: <1120490609.134384.206840@g47g2000cwa.googlegroups.com> "Tom Anderson" wrote: > I'll just chip in and say i'd quite like a flatten(), too; at the moment, > i have one like this: > > def flatten(ll): > return reduce(lambda a, l: a.extend(l), ll, []) This doesn't work; a.extend() returns None, not the extended list a: >>> seq = [[1,2],[3],[],[4,[5,6]]] >>> flatten(seq) AttributeError: 'NoneType' object has no attribute 'extend' This works for 1-level flattening: def flatten(ll): return reduce(lambda a, l: a.extend(l) or a, ll, []) >>> flatten(seq) [1, 2, 3, 4, [5, 6]] And finally for recursive flattening: def flatten(seq): return reduce(_accum, seq, []) def _accum(seq, x): if isinstance(x,list): seq.extend(flatten(x)) else: seq.append(x) return seq >>> flatten(seq) [1, 2, 3, 4, 5, 6] George From mfranklin1 at gatwick.westerngeco.slb.com Fri Jul 22 04:42:12 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 22 Jul 2005 09:42:12 +0100 Subject: wxPythin installation woes In-Reply-To: <1121940070.906251.124580@g43g2000cwa.googlegroups.com> References: <1121940070.906251.124580@g43g2000cwa.googlegroups.com> Message-ID: linuxfreak wrote: > Hi all, > > Was working with python 2.3 in a fedora core 3 machine. I upgraded it > to Fedora Core 4 with a clean install. So now I have python 2.4 > installed. But when I try to install wxPython for python 2.4 using an > rpm file i downloaded from the wxpython web site i get dependencies > errors. Turns out that libstdc++.so.5 is needed but I checked and i > see that libstdc++.so.6 is installed on my system. Help needed guys and > needed pronto. Thanks a ton once again :) > I have fedora core 4 and a yum list wx* produces this:- wxGTK.i386 2.4.2-12 extras wxGTK-common.i386 2.4.2-12 extras wxGTK-common-devel.i386 2.4.2-12 extras wxGTK-devel.i386 2.4.2-12 extras wxGTK-gl.i386 2.4.2-12 extras wxGTK-stc.i386 2.4.2-12 extras wxGTK-xrc.i386 2.4.2-12 extras wxGTK2.i386 2.4.2-12 extras wxGTK2-devel.i386 2.4.2-12 extras wxGTK2-gl.i386 2.4.2-12 extras wxGTK2-stc.i386 2.4.2-12 extras wxGTK2-xrc.i386 2.4.2-12 extras wxPythonGTK2.i386 2.4.2.4-7 extras So I assume a yum install wxPythonGTK2 will get you wxPython installed. *I havn't done that since I only use Tkinter* Martin From caleb1 at telkomsa.net Thu Jul 21 17:00:49 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 21 Jul 2005 23:00:49 +0200 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu> Message-ID: Terry Yes, I must agree with you that it is something I should know. I do try to keep with things but there are always some things that slip through the cracks, like enumerate, in this case. That is why I am extremely grateful the for the activity, generosity and pure knowledge on this newsgroup to fill in the blanks for me. It is guys like you who are willing to take the time to give responses that make it what it is. In another newsgroup, I could have been flamed for letting Simon know he helped more than just the OP with his post :) Thanks Caleb On Wed, 20 Jul 2005 23:41:36 +0200, Terry Reedy wrote: > >> Wow, I didn't know about enumerate. > > It is listed and explained in Lib Ref Manual, Chapter 2, on builtin > functions and types and their methods. Everyone should read at least > that > much of the Lib manual. > > Terry J. Reedy > > > From alanmk at hotmail.com Mon Jul 18 07:39:31 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 18 Jul 2005 12:39:31 +0100 Subject: Java RMI-like services in Python In-Reply-To: References: Message-ID: [Maurice LING] > I am wondering if Python has services or frameworks that does the same > as Java RMI? As Harald mentioned, Pyro is firmly in the "Remote Method Invocation" space. And there's always CORBA, of which there are multiple python and java implementations. Which might be useful, if you wanted to have a mixed language implementation. Another technology that could be very useful for you is Spread, for which both python and java libraries exist. http://www.zope.org/Members/tim_one/spread/ [Maurice LING] > What I am seeking is to do "pseudo-clustering". [ .. snip .. ] > I know something like this had been achieved in Java > (http://www-128.ibm.com/developerworks/java/library/j-super.html) but > wondering if it is possible in Python. Is so, how? So, do you want to A: Build your own "pseudo-clustering" implementation? B: Use one that's already been written? If the answer is the latter, I recommend you take a look at PyLinda. PyLinda - Distributed Computing Made Easy http://www-users.cs.york.ac.uk/~aw/pylinda/ -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From fuzzyman at gmail.com Mon Jul 4 08:50:00 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jul 2005 05:50:00 -0700 Subject: Unicode drives me crazy... In-Reply-To: References: Message-ID: <1120481400.689362.52720@z14g2000cwz.googlegroups.com> fowlertrainer at citromail.hu wrote: > Hi ! > > I want to get the WMI infos from Windows machines. > I use Py from HU (iso-8859-2) charset. > > Then I wrote some utility for it, because I want to write it to an XML file. > > def ToHU(s,NoneStr='-'): > if s==None: s=NoneStr > if not (type(s) in [type(''),type(u'')]): > s=str(s) > if type(s)<>type(u''): > s=unicode(s) > s=s.replace(chr(0),' '); > s=s.encode('iso-8859-2') > return s > > This fn is working, but I have been got an error with this value: > 'Kommunik\xe1ci\xf3s port (COM1)' > > This routine demonstrates the problem > > s='Kommunik\xe1ci\xf3s port (COM1)' > print s > print type(s) > print type(u'aaa') > s=unicode(s) # error ! > > This is makes me mad. > How to I convert every objects to string, and convert (encode) them to > iso-8859-2 (if needed) ? > s is a 'byte string' - a series of characters encoded in bytes. (As is every string on some level). In order to convert that to a unicdoe object, Python needs to know what encoding is used. In other words it needs to know what character each byte represents. See this : t = s.decode('iso-8859-1') t u'Kommunik\xe1ci\xf3s port (COM1)' print t Kommunik?ci?s port (COM1) print type(s) print type(t) The decode instruction converts s into a unicode string - where Python knows what every character is. If you call unicdoe with no encoding specified, Python reverts to the system default - which is *probably* 'ascii'. You string contains characters which have *no meaning* in the ascii codec - so it reports an error.... Does this help ? Once you 'get unicode', Python support for it is pretty easy. It's a slightly complicated subject though. Basically you need to *know* what encoding is being used, and whenever you convert between unicode and byte-strings you need to specify it. What can complicate matters is that there are lot's of times an *implicit* conversion can take place. Adding strings to unicode objects, printing strings, or writing them to a file are the usual times implicit conversion can happen. If you haven't specified an encoding, then Python has to use the system default or the file object default (sys.stdout often has a different default encoding than the one returned by sys.getdefaultencoding()). It is these implicit conversions that often cause the 'UnicodeDecodeError's and 'UnicodeEncodeError's. HTH Best Regards, Fuzzy http://www.voidspace.org.uk/python > Please help me ! > > Thanx for help: > ft From sybrenUSE at YOURthirdtower.com.imagination Sun Jul 10 16:21:44 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 10 Jul 2005 22:21:44 +0200 Subject: Yet Another Python Web Programming Question References: Message-ID: Daniel Bickett enlightened us with: > It would be a long while before he would find Python, and since that > time he would have no desire to ever touch PHP again. My thoughts exactly. > He would, however, be compelled to write a web application again, > but in Python now, of course. Same here :) > * They required installation (as opposed to, simply, the placement > of modules), whereas the only pythonic freedom he had on his hosting > was a folder in his /home/ dir that was in the python system path. I can't help you here. For instance, if you want to get a proper performance, you should install something like mod_python to get Python functionality in Apache. > Python using CGI, for example, was enough for him until he started > getting 500 errors that he wasn't sure how to fix. Check the web server's error logs. My solution was to take a look at Cheetah. It's a template engine that's written in Python. I've written a mod_python handler for it so I can easily create & edit my website using Cheetah as a template engine. Check out http://www.unrealtower.org/mycheetah if you want to read more about the handler & other stuff I wrote. Perhaps you can even help me improve it! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From kay.schluehr at gmx.net Fri Jul 8 10:47:50 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Jul 2005 07:47:50 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <1120834070.272672.143850@f14g2000cwb.googlegroups.com> seberino at spawar.navy.mil schrieb: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. Yes, Paul is a postmodern hero who reininvents himself and his language every day and with every program: "Experienced Lisp programmers divide up their programs differently. As well as top-down design, they follow a principle which could be called bottom-up design-- changing the language to suit the problem. In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. As you're writing a program you may think "I wish Lisp had such-and-such an operator." So you go and write it. Afterward you realize that using the new operator would simplify the design of another part of the program, and so on. Language and program evolve together." http://www.paulgraham.com/progbot.html Remark: The same may be claimed about Forth. This might be a great self experience for some "great hackers" but just annoying for others who used to work with modular standard librarys and think that the border of the language and an application should be somehow fixed to enable those. Kay From rebound1618 at yahoo.com Thu Jul 28 03:59:51 2005 From: rebound1618 at yahoo.com (Jerry He) Date: Thu, 28 Jul 2005 00:59:51 -0700 (PDT) Subject: functions without parentheses Message-ID: <20050728075951.74221.qmail@web51507.mail.yahoo.com> Hi, Is it possible to create a function that you can use without parenthesizing the arguments? for example, for def examine(str): ..... ..... Is there some way to define it so that I can call it like examine "string" instead of examine("string")? thanks in advance -Jerry ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From peter at engcorp.com Fri Jul 1 12:00:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 12:00:14 -0400 Subject: is there a better way to walk a file system? In-Reply-To: <1120230335.548382.96880@z14g2000cwz.googlegroups.com> References: <1120230335.548382.96880@z14g2000cwz.googlegroups.com> Message-ID: ina wrote: > I want to walk a folder structor and group all the files by extention. > > Here is the code I put together is there a better way of doing this? > [snip] If you were to download Jason Orendorff's "path" module, which is a convenient single-file package that vastly simplifies all manner of dealings with directory and file names, I suspect your example code could be reduced to less than half the number of lines it now uses, and with a corresponding increase in readability and maintainability. The answer to the question "is there a better way of doing this?" in relation to paths is always "yes, use Jason Orendorff's path module". -Peter From mohan at terabolic.com Fri Jul 15 20:33:39 2005 From: mohan at terabolic.com (MKoool) Date: 15 Jul 2005 17:33:39 -0700 Subject: Filtering out non-readable characters Message-ID: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> I have a file with binary and ascii characters in it. I massage the data and convert it to a more readable format, however it still comes up with some binary characters mixed in. I'd like to write something to just replace all non-printable characters with '' (I want to delete non-printable characters). I am having trouble figuring out an easy python way to do this... is the easiest way to just write some regular expression that does something like replace [^\p] with ''? Or is it better to go through every character and do ord(character), check the ascii values? What's the easiest way to do something like this? thanks From invalidemail at aerojockey.com Sun Jul 3 05:57:24 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 3 Jul 2005 02:57:24 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> Message-ID: <1120384643.995676.226320@g43g2000cwa.googlegroups.com> John Roth wrote: > "Robert Kern" wrote in message > news:mailman.1226.1120271406.10512.python-list at python.org... > > > > > map and filter are being removed *because of* list comprehensions. Did you > > even read Guido's articles about this issue? Your understanding of why > > these changes are planned is incorrect; consequently your projection based > > on that understanding is not on firm footing. > > May I most respectfully point out that you've got it backwards. > Part of the justification for list comprehensions was that they could > be used to replace map and filter. > > The jihad against the functional constructs has been going on for a > long time, and list comprehensions are only one piece of it. Many people believe that the functional constructs in Python exist to enhance Python's support of functional programming, but that's wrong. They exist to enhance support of procedural programming. In other words, the functional elements were added not because Python embraced functional programming, but because discreet use of functional code can make procedural programs simpler and more concise. Listcomps et al. cannot do everything map, lambda, filter, and reduce did. Listcomps are inferior for functional programming. But, you see, functional is not the point. Streamlining procedural programs is the point, and I'd say listcomps do that far better, and without all the baroque syntax (from the procedural point of view). Jihad? I'd say it's mostly just indifference to the functional programming cause. -- CARL BANKS From Scott.Daniels at Acm.Org Fri Jul 22 13:27:49 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 22 Jul 2005 10:27:49 -0700 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <42e1245c@nntp0.pdx.net> Duncan Booth wrote: > BTW, does it matter at all in practical use that the base class of path > varies between str and unicode depending on the platform? Isn't it even worse than this? On Win2K & XP, don't the file systems have something to do with the encoding? So D: (a FAT drive) might naturally be str, while C: (an NTFS drive) might naturally be unicode. Even worse, would be a path that switches in the middle (which it might do if we get to a ZIP file or use the newer dir-in-file file systems. --Scott David Daniels Scott.Daniels at Acm.Org From n.favrefelix at eggbaconandspam--free.fr Fri Jul 22 12:47:59 2005 From: n.favrefelix at eggbaconandspam--free.fr (Nicolas) Date: Fri, 22 Jul 2005 18:47:59 +0200 Subject: Data available on socket? In-Reply-To: <42e11ed0@griseus.its.uu.se> References: <42e11ed0@griseus.its.uu.se> Message-ID: <42e122da$0$3332$636a15ce@news.free.fr> Jan Danielsson a ?crit : > Hello all, > > How do I find out if a blocking socket has data available [for > reading] on it? > > I assume I could do something like this: > > tmp = self.read(1, socket.MSG_PEEK) > if len(tmp) > 0: > # Data available > > But is there a better way? A call which specifically checks if data > is available? Hello, You might want to use select.select. See http://effbot.org/librarybook/select.htm for an example with sockets. Nicolas. From bokr at oz.net Sat Jul 2 00:22:06 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 02 Jul 2005 04:22:06 GMT Subject: How to find Windows "Application data" directory?? References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> <1120017647.696243.154880@f14g2000cwb.googlegroups.com> <7xbr5pkdnb.fsf@ruckus.brouhaha.com> Message-ID: <42c61632.302305382@news.oz.net> On 28 Jun 2005 21:09:12 -0700, Paul Rubin wrote: >"Rune Strand" writes: >> You have the environment variable APPDATA. You can access it with >> os.environ(). > >Thanks!!!!!! Wow, I'd been hacking away at much messier approaches >than that. It's actually os.environ['APPDATA'] ;-) Hm, which windows is that? Not NT4 ;-) Regards, Bengt Richter From michael.lieschnegg at virtuellesfahrzeug.at Tue Jul 19 02:22:30 2005 From: michael.lieschnegg at virtuellesfahrzeug.at (Michael Lieschnegg) Date: Tue, 19 Jul 2005 08:22:30 +0200 Subject: WG: creating new process with pipes under win xp ->troubles Message-ID: <067FFD3D085A1E4B860486DD33A23DF83366C6@vifs1.vif.intern> hello! I wrote a python parent script which starts a separate script in a new process (under Windows XP Pro SP2, Python 2.4.1). Through anonymous pipes I have a bidirectional communication to the child. Now I embedded the parent script in a CPP program, but when I start the cpp dummy application it seems as the application is producing copies of itself (like a recursive function -> in the windows task manager the number of the same process is increasing) and the child process is not working! But when i start the parent script directly, it works well. Maybe you can tell me the reason why it does not work in CPP. Below you can find the the part of the code which is starting the client process. I hope you can help me. Thank you! Michael Lieschnegg I took following code from a closed forum to create the child process: class Process: def __init__(self, command, args, environment, path): # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create pipes hStdin_r, self.hStdin_w = win32pipe.CreatePipe(sAttrs, 0) self.hStdout_r, hStdout_w = win32pipe.CreatePipe(sAttrs, 0) # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdInput = hStdin_r StartupInfo.hStdOutput = hStdout_w StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Create new output read handles and the input write handle. Set # the inheritance properties to FALSE. Otherwise, the child inherits # the these handles; resulting in non-closeable handles to the pipes # being created. pid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle( pid, self.hStdin_w, pid, 0, 0, # non-inheritable!! win32con.DUPLICATE_SAME_ACCESS) # Close the inhertible version of the handle win32file.CloseHandle(self.hStdin_w) self.hStdin_w = tmp tmp = win32api.DuplicateHandle( pid, self.hStdout_r, pid, 0, 0, # non-inheritable! win32con.DUPLICATE_SAME_ACCESS) # Close the inhertible version of the handle win32file.CloseHandle(self.hStdout_r) self.hStdout_r = tmp # start the process. print "creating process" cmdline = "%s %s" % (command, string.join(args, ' ')) hProcess, hThread, dwPid, dwTid = win32process.CreateProcess( None, # program cmdline,# command line None, # process security attributes None, # thread attributes 1, # inherit handles, or USESTDHANDLES won't work. # creation flags. Don't access the console. 0, # Don't need anything here. # If you're in a GUI app, you should use # CREATE_NEW_CONSOLE here, or any subprocesses # might fall victim to the problem described in: # KB article: Q156755, cmd.exe requires # an NT console in order to perform redirection.. environment, # new environment path, # new directory StartupInfo) # Child is launched. Close the parents copy of those pipe handles # that only the child should have open. win32file.CloseHandle(hStdout_w) win32file.CloseHandle(hStdin_r) self.outQueue = Queue.Queue() self.closed = 0 self.stdoutClosed = 0 threading.Thread(target=self.doWrite).start() def write(self, data): self.outQueue.put(data) def closeStdin(self): self.outQueue.put(None) def connectionLost(self): if not self.closed: print "connection lost" self.closed = 1 self.closeStdin() win32file.CloseHandle(self.hStdout_r) def doWrite(self): while 1: data = self.outQueue.get() if data == None: break try: win32file.WriteFile(self.hStdin_w, data, None) except win32api.error: print "error" break win32file.CloseHandle(self.hStdin_w) def doReadOut(self): try: hr, data = win32file.ReadFile(self.hStdout_r, 8192, None) except win32api.error: self.stdoutClosed = 1 return self.handleData(data) return repr(data) def handleData(self, data): print "Got", repr(data) if __name__ == '__main__': exe = win32api.GetModuleFileName(0) print exe p = Process(exe, ['-u', 'dispatcher.py', '8888'], None, None) print "ok, made process object" while 1: p.write("hello, world! Who you are?\n") p.doReadOut() When I run this script directly, the client process ("dispatcher.py") will be started correctly. But when I create a instance of the class Process in my cpp application, the client does not start and the cpp application is producing and starting copies of itself (it seems so). -------------- next part -------------- An HTML attachment was scrubbed... URL: From rzzzwilson at hotmail.com Thu Jul 14 22:01:15 2005 From: rzzzwilson at hotmail.com (Ross Wilson) Date: Fri, 15 Jul 2005 12:01:15 +1000 Subject: Newbie question: Explain this behavior References: Message-ID: On Thu, 14 Jul 2005 15:46:40 -0700, David Smith wrote: > Why does code snippet one work correctly, but not two. The only > difference is the placement of the "else". I know that indentation > affects execution, but how does it change behavior in the following > examples? Thank you. > > 1. for n in range(2, 10): > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > # loop fell through without finding a factor > print n, 'is a prime number' A quote from "Python: Essential Reference (2/e)" (p56) says it best: "The 'else' clause of a loop executes only if the loop runs to completion. This either occurs immediately (if the loop wouldn't execute at all) or after the last iteration. On the other hand, if the loop is terminated early using the 'break' statement, the 'else' clause is skipped." Ross From peter at engcorp.com Sun Jul 10 10:13:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Jul 2005 10:13:32 -0400 Subject: Python Forum In-Reply-To: <1120968976.764802.277130@g14g2000cwa.googlegroups.com> References: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> <1120968976.764802.277130@g14g2000cwa.googlegroups.com> Message-ID: Devan L wrote: > I see a total of 12 posts and 8 users. Which at least makes it a record so far, surpassing every other "hey, i just made a new forum, it's awesome and everyone should join!" post that has been made here in the past, by about 9 posts and 5 users... ;-) -Peter From simon.dahlbacka at gmail.com Thu Jul 21 07:20:33 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 21 Jul 2005 04:20:33 -0700 Subject: spurious syntax error when updating to 2.4 ? In-Reply-To: <1121935049.573062.191030@g49g2000cwa.googlegroups.com> References: <1121935049.573062.191030@g49g2000cwa.googlegroups.com> Message-ID: <1121944833.643281.19660@g43g2000cwa.googlegroups.com> Replying to self, it seems to be related to https://sourceforge.net/tracker/index.php?func=detail&aid=1163244&group_id=5470&atid=105470 (Syntax error on large file with MBCS encoding) even though my files had # -*- coding: ascii -*- However, if I removed this explicit ascii encoding then I did not get any syntax error. /Simon From jepler at unpythonic.net Fri Jul 8 08:35:57 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 8 Jul 2005 07:35:57 -0500 Subject: Query In-Reply-To: <001101c583b7$b4ac6d20$1c04010a@relqind01.relq.com> References: <001101c583b7$b4ac6d20$1c04010a@relqind01.relq.com> Message-ID: <20050708123553.GA18263@unpythonic.net> python-xlib includes an implementation of the xtest extension, which is enabled on most users' X servers, and can be used to send arbitrary keyboard or mouse events. jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From reinhold-birkenfeld-nospam at wolke7.net Tue Jul 26 11:57:11 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 26 Jul 2005 17:57:11 +0200 Subject: Bug Report / Patch (1159139 cgi.py invalid REQUEST_METHOD set) In-Reply-To: <_ICdnT-Tg-3_ynvfRVn-qw@comcast.com> References: <_ICdnT-Tg-3_ynvfRVn-qw@comcast.com> Message-ID: <3kn4qoFuvvdgU1@individual.net> Joe wrote: > Back in March I submitted a patch for cgi.py to sourceforge to fix a problem > with the handling of an invalid REQUEST_METHOD. > > I thought I followed all the steps to properly submit the bug and patch but > the patch is still sitting there in limbo. > > This is the first patch I have submitted for Python, did I miss a step in > the patch process? > > What else needs to be done? Can you provide an example script demonstrating the problem you describe? I tried something like this (Py2.4.1): ------- test_cgi.py #!/bin/env python import cgi fs = cgi.FieldStorage() print fs $ python test_cgi.py "a=1&b=2" FieldStorage(None, None, [MiniFieldStorage('a', '1'), MiniFieldStorage('b', '2')]) $ There's no REQUEST_METHOD or QUERY_STRING env var set. Reinhold From bronger at physik.rwth-aachen.de Sun Jul 31 02:22:23 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 08:22:23 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> Message-ID: <87ack3qyu8.fsf@wilson.rwth-aachen.de> Hall?chen! zen19725 at zen.co.uk (phil hunt) writes: > On Sat, 30 Jul 2005 16:51:13 +0200, Torsten Bronger wrote: > >> zen19725 at zen.co.uk (phil hunt) writes: >> >>> [...] >>> >>> How about sometihing with the same API as Tkinter (so no need to >>> relearn), but which looks prettier? Would that fix your gripes? >> >> I haven't learned Tkinter. > > [...] > > Not that I'm a particular fan of it, it's just I like > standardisation, because then you get network effects. Me too. Therefore I'd like to see a new toolkit in the standard library to see a new network growing. You mustn't do something like this too often of course but I think in this case it would be the right time. >> So for me, it needn't be like Tkinter. The three most important >> attributes for me are Pythonic, modern (both nice-looking and >> comprehensive), and non-niche. > > What you say Pythonic, what do you mean? And how do you rate > Tkinter, PyGtk, PyQt/PyKDE, wxWindows for "Pythonicness"? I don't like to set arguments to -1 or NULL, but to None. I'd like to have extensive support for keyword arguments. I don't like mucking about with ID values. Partly this is cosmetical but partly it's a rich source of errors. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 2 06:17:47 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 02 Jul 2005 12:17:47 +0200 Subject: Accepted Summer of Code proposals In-Reply-To: References: Message-ID: <3in7ucFmcn6iU1@individual.net> A.M. Kuchling wrote: > For anyone who's interested: the Python wiki now contains a list of the > PSF-mentored proposals that were accepted for Google's Summer of Code: > http://wiki.python.org/moin/SummerOfCode Is it right that two Wax proposals were accepted? Reinhold From pydecker at gmail.com Tue Jul 12 11:30:40 2005 From: pydecker at gmail.com (Peter Decker) Date: Tue, 12 Jul 2005 11:30:40 -0400 Subject: Why does reply to messages on this list put the sender in the To In-Reply-To: <5f4d3cb5050712081720b880ac@mail.gmail.com> References: <5f4d3cb5050712081720b880ac@mail.gmail.com> Message-ID: On 7/12/05, Dark Cowherd wrote: > Most lists when i hit reply it puts the list address back in the To > address and some lists allow you to configure this. > > But in this list reply sends the mail back as a private mail and there > seems to be no option to configure this. > > Am I missing something Nope, it's a preference set by the list managers. There are two distinct POVs on this subject, and the feeling is pretty intense on both sides. Here are two summaries: Reply to sender: http://www.unicom.com/pw/reply-to-harmful.html Reply to list: http://www.blackgate.net/consulting/reply-to_munging_useful.html IMO, the various purist postions are meaningless drivel by people more concerned with following a ideal notion instead of being concerned with how the software is actually used. If you think in those terms, replies to discussion lists should go to the list, and replies to announcement-type lists should go to the sender. In cases where people are discussing problems and supplying solutions, replying to the list is essential so that as many people as possible can benefit from the knowledge contained in the reply. Private replies only benefit the lone recipient, while list replies benefit everyone on the list and everyone who later searches the archives. # p.d. From mangabasi at gmail.com Mon Jul 18 17:39:22 2005 From: mangabasi at gmail.com (Mangabasi) Date: 18 Jul 2005 14:39:22 -0700 Subject: Python to C++ translation? Message-ID: <1121722762.525859.255890@g49g2000cwa.googlegroups.com> Hi there, I need to translate the following code (rather something similar) to C++. I have been studying C++ for the last two days but I could not find an easy way to do the following Python snippet. class A: def __init__(self, x): self.x = x def methodA(): pass # Ignore the details class B: def __init__(self, x): self.x = x def methodB(): def methodB(): pass # Ignore the details class C: def __init__(self, A, B): self.A = A self.B = B a = A(5) b = B(5.5) c = C(a, b) print c.A.x print c.B.x #so far I can do it in C++ #how do I do the following in C++? d = C(b, a) print d.A.x print d.B.x Basically I want A and B to be instances of different classes if necessary like the above code. #include class A { public: int x; A( ) { } A(int _x) { x = _x; } }; class B { public: double x; B( ) { } B(double _x) { x = _x; } }; class C { public: A *propA; B *propB; C(A &_propA, B &_propB) { propA = &_propA; propB = &_propB; } }; main( ) { A a = A(42); B b = B(23.0); C c1 = C(a, b); cout << c1.propA->x << "\n"; cout << c1.propB->x << "\n"; } How do I make this work for C c2 = C(b, a) as well? Thank you in advance, I know this is somehow offtopic in the Python group but I would not dare asking this in the C++ groups. Abusing the civility of this grouply yours... Peace From gsakkis at rutgers.edu Sun Jul 3 09:48:03 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 06:48:03 -0700 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> <1120368681.573445.199710@g44g2000cwa.googlegroups.com> <1120371274.448543.145890@g43g2000cwa.googlegroups.com> Message-ID: <1120398483.415818.95360@o13g2000cwo.googlegroups.com> wrote: > Thanks! Even the fact that these ideas > have been organized into a PEP is > exciting to me....there is hope that > they may *someday* be implemented. Maybe sooner than people think. Given that the latest 2.x python will be 2.9 and that 3.0 may be released in parallel with 2.5-2.9 (http://www.python.org/doc/essays/ppt/euro2004/euro2004.ppt), I guess this *someday* will be no later than 2015-16, probably sooner than that. George From rrr at ronadam.com Wed Jul 6 16:25:26 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 20:25:26 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Stian S?iland wrote: > On 2005-07-06 16:33:47, Ron Adam wrote: > > >>*No more NamesError exceptions! >> print value >> >> None > > > So you could do lot's of funny things like: > > def my_fun(extra_args=None): > if not extraargs: > print "Behave normally" > extra_args = 1337 > > if extraargs: > asdkjaskdj > .. > if extra_args: > kajsdkasjd Yes, returning None from an undefined name is DOA. In the above case you would get an error by the way. "if extraargs:" would evaluate to "if None:", which would evaluate to "if:" which would give you an error. >>*No initialization needed for a while loop! >> >> while not something: >> if : >> something = True > > > This is the only "good" case I could find, but opening for a lots of > errors when you get used to that kind of coding: It would need to be.. while not (something==None): and the compiler would need to handle it as a special case. But this one could still work without allowing something=undefined to be valid. > while not finished: > foo() > finished = calculate_something() > > (..) > (..) # Added another loop > while not finished: > bar() > finished = other_calculation() > > Guess the amount of fun trying to find out the different errors that > could occur when bar() does not run as it should because the previous > "finished" variable changes the logic. It's not really differnt than any other value test we currently use. notfinished = True while notfinished: notfinished = (condition) # Need to set notfinished back to True here. while notfinished: >>*Test if name exists without using a try-except! >> if something == None: >> something = value > > Now this is a question from newcomers on #python each day.. "How do I > check if a variable is set?". > > Why do you want to check if a variable is set at all? If you have so > many places the variable could or could not be set, your program design > is basically flawed and must be refactored. There's a few places the Python library that do exactly that. try: value except: value = something I admit it's something that should be avoided if possible because if there's doubt that a name exists, then there would also be doubt concerning where it came from and weather or not it's value/object is valid. Anyway, it was an interesting but flawed idea, I should of thought more about it before posting it. Cheers, Ron From jzgoda at gazeta.usun.pl Fri Jul 22 16:05:51 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 22 Jul 2005 22:05:51 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: TPJ napisa?(a): > In the nearest future I will have to decide what to use: PyGTK or > wxPython. I like those both APIs. wxPython has more widgets, but PyGTK > seems to be faster. I can use them both for free (it's very important). > My only concern is that although I'm doing development on Linux, I'd > like to make my application runnable on Windows as well (Py2Exe). I'd > like to choose PyGTK (because of its rich documentation), but I'm not > sure if PyGTK is stable on Windows... For now I know that wxPython runs > well on Windows. > > For now I haven't experienced any problems with wxPython on Linux > (Slackware, Aurox /Polish RH-like distro/). I used wxPython on Linux, > but I stopped because of its poor documentation (mainly C++ docs, not > Python docs). But recently I noticed this documentation got better > (*much* better!). > > How well does PyGTK run on Windows (98, 2K, XP)? How stable is it? Will > I be able to make an executable (using Py2Exe) of an application that > uses PyGTK? PyGTK runs reasonably well on Win32, although not as good as wx. On linux situation is reversed -- wx runs acceptably well, in contrast to PyGTK which works like a charm. PyQt works equally well on both systems. -- Jarek Zgoda http://jpa.berlios.de/ From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 11 14:50:59 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 11 Jul 2005 20:50:59 +0200 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: Message-ID: <3jftckFpvhv2U2@individual.net> Mark Jackson wrote: > "Ric Da Force" writes: > >> It is hard to explain but this is what I mean: >> >> Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is >> not'} >> >> I want this to return a new dict with string keys and lists containing the >> previous keys for repeated values. >> >> NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} > > NewDict = {} > for x in Dict.keys(): > try: > NewDict[Dict[x]].append(x) > except KeyError: > NewDict[Dict[x]] = [x] Or, more up-to-date: NewDict = {} for key, val in Dict.iteritems(): NewDict.setdefault(val, []).append(key) Reinhold From jziniti at speakeasy.net Tue Jul 19 14:40:42 2005 From: jziniti at speakeasy.net (John Ziniti) Date: Tue, 19 Jul 2005 14:40:42 -0400 Subject: Web Framework Reviews In-Reply-To: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> Message-ID: <42DD492A.4050004@speakeasy.net> istvan.albert at gmail.com wrote: > I thought it would make sense to write up some of my experiences with > python based web frameworks: > > http://www.personal.psu.edu/staff/i/u/iua1/python_reviews.html > From the web-page: """ Zope - Generation Z ... Weakness: Not pythonic. In fact you can barely use python with it! Ad-hoc lookup rules, competing standards DHTML vs ZPT. Can only be used with these two! The Z shaped thingy. """ "barely use python with it" and "can only be used with these two" are not entirely true. Zope development can be done in a through-the-web (TTW) fashion or via filesystem products. When developing TTW, it is true that you are somewhat limited in the amount of Python that you will be able to use. When you graduate to filesystem products, though, Zope becomes more of a set of APIs and a persistence layer for your objects and methods that are coded entirely in Python, with very little DTML (not DHTML) and ZPTs. IMHO, this is when Zope development becomes powerful. Maybe this is the Z-shaped learning curve you speak of: it takes a while developing in Zope to even know what all of the options are! HTH, JZ From tsmets at brutele.be.be Wed Jul 27 20:00:42 2005 From: tsmets at brutele.be.be (Thomas SMETS) Date: Thu, 28 Jul 2005 02:00:42 +0200 Subject: Trimming X/HTML files Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dear, I need to parse XHTML/HTML files in all ways : ~ _ Removing comments and javascripts is a first issue ~ _ Retrieving the list of fields to submit is my following item (todo) Any idea where I could find this already made ... ? \T, -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFC6CAqqN0SJr+xLBURAkc5AKCAb5pdsUZjCezr8bcpd2GTJ9FueACg7raK pMU5Y4Z7PaPGfGZkJ/wCDpw= =iM7V -----END PGP SIGNATURE----- From slug57_98 at yahoo.com Mon Jul 18 20:10:06 2005 From: slug57_98 at yahoo.com (Chad) Date: 18 Jul 2005 17:10:06 -0700 Subject: Help with images Message-ID: <1121731806.578272.174590@z14g2000cwz.googlegroups.com> I have installed a TWAIN module(from http://twainmodule.sourceforge.net) today and figured out how to acquire an image. The only problem is that the image is way too large in terms of filesize. It is over 1MB. I can do either one of two things. Try to figure out how to manupilate the image with this module(which I am been doing all day) or just use a module that can compress jpegs. Can anybody help? From python at hope.cz Fri Jul 22 06:53:52 2005 From: python at hope.cz (Lad) Date: 22 Jul 2005 03:53:52 -0700 Subject: Web frame systems vs. pure Python Message-ID: <1122029632.548775.161360@z14g2000cwz.googlegroups.com> I am thinking about a new project and I do not know if I should use Python with HTML code only or use a web frame such as Cherry or a similar ( which one then??) and a template system. Can you please explain what I will get / lose if I use a web frame system? Thanks a lot La. From fuzzyman at gmail.com Tue Jul 12 10:37:44 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 12 Jul 2005 07:37:44 -0700 Subject: Software needed In-Reply-To: References: Message-ID: <1121179064.680810.287300@g43g2000cwa.googlegroups.com> Sounds like the sort of project that could work as a plugin to chandler. There's a Python interface to TWAIN (the scanner protocol) - but I'm not *aware* of anything built on top of it. google may have a better idea though. Regards, Fuzzy http://www.voidspace.org.uk/python From tuxlover at gmail.com Tue Jul 12 13:32:58 2005 From: tuxlover at gmail.com (tuxlover) Date: 12 Jul 2005 10:32:58 -0700 Subject: Environment Variable References: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> Message-ID: <1121189578.883915.50620@o13g2000cwo.googlegroups.com> No, the replies from Grant's and Sybren's do answer my question. I posted twice because my browser locked itself up, and I ended up typing twice :( From rkern at ucsd.edu Wed Jul 6 18:26:45 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 06 Jul 2005 15:26:45 -0700 Subject: Compatibility of recent GCC/Python versions In-Reply-To: References: Message-ID: David Abrahams wrote: > Recently people testing Boost.Python with GCC on Linux have reported > that the extensions being tested have to be compiled with exactly the > same version of GCC as the Python they're being loaded into, or they > get mysterious crashes. > > That doesn't correspond to my past experience; it has always been true > that, as long as the compiler used to build Python and the one used to > build the extension have compatible 'C' ABIs, we've been okay. Yes, > if you were going to pass types like FILE* across the Python/C API, > then you additionally need to be sure that the two compilers are using > the same 'C' library. That said, none of the Boost.Python tests do > that. > > I'm wondering if there has been a well-known recent change either in Python > or GCC that would account for these new reports. Any relevant > information would be appreciated. I've had intermittent problems on OS X and gcc-4.0 with, well, everything, Python-related or otherwise. So I ignore it and use gcc-3.3 and g77-3.4 and live happily ever after. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jstier at cs.uvic.ca Thu Jul 7 08:45:02 2005 From: jstier at cs.uvic.ca (J) Date: 7 Jul 2005 05:45:02 -0700 Subject: VC++ linking problem In-Reply-To: References: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> Message-ID: <1120740302.923649.291570@f14g2000cwb.googlegroups.com> Thank you very much Miki! That was an easy solution. It links... I will put a hold on compiling the latest version until I really have to. I will probably switch to VC 7 before that. Cheers Jochen Miki Tebeka wrote: > Hello Jochen, > > > I started embedding python into a 3D graphics App and I came > > across this linking problem. > > > > > > SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol > > __imp__Py_InitModule4TraceRefs > > SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol > > __imp___Py_RefTotal > > SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol > > __imp___Py_RefTotal > > > > I am linking against python24.lib using VC++ 6.0. Before I got to this > > point it couldn't find python24_d.lib. After searching around > > for a while I came across a solution that included changing > > python24_d.lib to python24.lib in one of the header files. I hope that > > didn't have a negative effect. I would really appreciate > > some help.... > This is since Python header file is in debug mode and you link with the > regular library. > > Just do: > #undef _DEBUG /* Link with python24.lib and not python24_d.lib */ > #include > > and you'll be fine. > > IMO python should try and link with python24.lib when compiling in debug > mode since we want to debug our program and not Python. > > Bye. > -- > ------------------------------------------------------------------------ > Miki Tebeka > http://tebeka.bizhat.com > The only difference between children and adults is the price of the toys From steven.bethard at gmail.com Fri Jul 8 18:07:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Jul 2005 16:07:50 -0600 Subject: removing list comprehensions in Python 3.0 Message-ID: George Sakkis wrote: > "Steven Bethard" wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course, is that dict comprehensions don't gain you >> much at all over the dict() constructor plus a generator expression, >> e.g.: >> dict((i, chr(65+i)) for i in range(4)) > > Sure, but the same holds for list comprehensions: list(i*i for i in > xrange(10)). The difference is historic I guess; list comprehensions > preceded generator expressions and so they cannot be removed, at least > not before 3.0. I wonder if they will/should be in the language when > the constraint of backwards compatibility is lifted. IMO they should > not (TIOOWTDI, uniformity among builtin data structures, not > overwhelmingly more useful than set or dict comprehensions), but > there's a long way till that day. I think the jury's still out on this one: * Alex Martelli expects list comprehensions to be removed. [1] * Robert Kern wants list comprehensions removed. [2] * Raymond Hettinger encourages continued use of list comprehensions [3] * Jeremy Bowers thinks list comprehensions should stay. [4] I only searched a few relatively recent threads in c.l.py, so there are probably more, but it looks to me like the final decision will have to be made by a pronouncement from Guido. [1]http://groups-beta.google.com/group/comp.lang.python/msg/f5613c00cb8c9539 [2]http://groups-beta.google.com/group/comp.lang.python/msg/b2cf0cd72d53fbe5 [3]http://groups-beta.google.com/group/comp.lang.python/msg/781dfab03701dd18 [4]http://groups-beta.google.com/group/comp.lang.python/msg/771a47d9eb24c863 From cliff at develix.com Sun Jul 31 18:16:21 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 15:16:21 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <87iryqzm1d.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <861x5ehk4g.fsf@bhuda.mired.org> <87iryqzm1d.fsf@wilson.rwth-aachen.de> Message-ID: <1122848181.19618.168.camel@localhost.localdomain> On Sun, 2005-07-31 at 23:46 +0200, Torsten Bronger wrote: > Hall?chen! > > Cliff Wells writes: > > > [...] > > > > Well, I think this exposes one of the more interesting sides of > > open source software in general. For better or worse, you get > > choices. If you don't like choice, you won't like open source. > > On the other hand, the GUI package bundled with Python is a regular > decision of some sort of committee. No, it's a decision made by Guido some years ago that remains in place because it's more pain to remove than to simple leave there. Besides, define "bundled with". My python install doesn't have it. Tkinter was separated out sometime ago as a separate download that just happens to have a link next to the standard installer. Having a link on python.org hardly qualifies as "bundled with" IMO. "Bundled near" would be more accurate. Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From me at privacy.net Tue Jul 19 09:43:25 2005 From: me at privacy.net (Admin) Date: Tue, 19 Jul 2005 10:43:25 -0300 Subject: How to send a query to the browser from time to time? References: <1121778228.962141.70680@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 19 Jul 2005 10:03:48 -0300, Simon Dahlbacka wrote: > I'd go for the ajax route if you don't need to support old browsers. I already use AJAX on several applications, but I don't want to use it in this one because it would poll the server a lot and it may bring the server down if there are many people using the chat application at the same time (too many queries to the database). -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From samgurung at gmail.com Thu Jul 21 06:01:10 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 03:01:10 -0700 Subject: wxPythin installation woes Message-ID: <1121940070.906251.124580@g43g2000cwa.googlegroups.com> Hi all, Was working with python 2.3 in a fedora core 3 machine. I upgraded it to Fedora Core 4 with a clean install. So now I have python 2.4 installed. But when I try to install wxPython for python 2.4 using an rpm file i downloaded from the wxpython web site i get dependencies errors. Turns out that libstdc++.so.5 is needed but I checked and i see that libstdc++.so.6 is installed on my system. Help needed guys and needed pronto. Thanks a ton once again :) From fgeiger at datec.at Fri Jul 8 11:44:59 2005 From: fgeiger at datec.at (F. GEIGER) Date: Fri, 8 Jul 2005 17:44:59 +0200 Subject: [PythonWin] how to stop execution in interactive window? References: <1120833596.025452.166020@g14g2000cwa.googlegroups.com> Message-ID: Right-click on the Pythonwin icon in the tray and select "Break into running code". HTH Franz GEIGER schrieb im Newsbeitrag news:1120833596.025452.166020 at g14g2000cwa.googlegroups.com... > Hi All, > (sorry for my bad english) > I wrote a __tiny__ and __stupid__ recursive script directly into > pythonwin > interactive window with a time.sleep(1) and a print before each > recursion... > I should have taken a closer look at the ending condition (never > satisfied!), > anyway I was quite confident that a control-C would have stopped the > intepreter as it is (incidentally?) when this break sequence is entered > during a screen-i/o of the python interpreter in a CMD prompt... > Instead I discovered my pythonwin session no more responding even > though the output shows that it was still working correctly... and my > other > open files in pythonwin still needing to be saved - my salvation was > that > while I was searching a solution with google, after 984 nested call > ~ more than a quarter later, the recursion stack was full and > an exception was raised! ;-P). > So my question is: is there a keystroke combination to stop the > interpreter > in pythonwin interactive window? Or even better > Is there a "pythonwin interactive window" keystrokes list? > (btw: I remember an old post explaining the keystroke to > reset interactive window memory without being forced to > close and open pythonwin - very usefull but I could not find it > anymore...) > TIA! > bye, > PiErre > From steven.bethard at gmail.com Tue Jul 5 20:17:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 05 Jul 2005 18:17:17 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <11cloakd4glsbef@corp.supernews.com> References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120590707.093007.175330@o13g2000cwo.googlegroups.com> <11cloakd4glsbef@corp.supernews.com> Message-ID: <-8ydnZxXGOCQvlbfRVn-3Q@comcast.com> Grant Edwards wrote: > mcherm at gmail.com wrote: >> So I'd say that it's a pretty obscure name that most people >> wouldn't know. > > I can't believe that anybody with any computer science > background doesn't know it. Perhaps this reflects on the quality of education in the United States ;) but I managed to get a BS in Computer Science at the University of Arizona without ever seeing the word lambda (in the programming languages sense). However, I only took one class in programming languages, and it was more of a survey class than a theory class. When I did take a theory class, here at University of Colorado at Boulder, they did, of course, cover lambda calculus. But there was at least a year or two in which I would have considered myself somebody "with any computer science background" who wasn't familiar with lambda. OTOH, I fully agree with Peter Hansen: "Really, the name is such a trivial, unimportant part of this whole thing that it's hardly worth discussing." STeVe From tjreedy at udel.edu Thu Jul 28 13:17:36 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 28 Jul 2005 13:17:36 -0400 Subject: Graphics files & Python References: Message-ID: "Pekka Karjalainen" wrote in message news:slrndehdg5.d96.pkarjala at lastu33.oulu.fi... > How can I create image files and animations with Python? Besides the other responses, you might also check out the pygame site where there once were some tutorial examples of manipulating bitmaps with Numerical Python to get various effects. Terry J. Reedy From levub137 at wi.rr.com Sat Jul 23 09:01:42 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 23 Jul 2005 13:01:42 GMT Subject: Windows Porting Help Requested Message-ID: I am preparing to release an extension module that interfaces Python to the Class Library for Numbers (http://www.ginac.de/CLN/). This module will provide Python types for arbitrary precision floating point numbers, rational numbers, and their complex counterparts. The module also includes most of the functions found in the Python math and cmath libraries. This module will be useful in applications where gmpy (http://gmpy.sourceforge.net/) doesn't have enough capability (e.g. extended precision trig, complex numbers, etc.). I would like to make this module available to Windows users but have neither the development environment nor the interest to get the module to build for the standard Python distribution. I am requesting the help of a developer who is familiar with building extension modules and understands C++ porting issues. I don't think my code is the issue, since it builds with distutils. However, it depends on two libraries (CLN and GMP) that look like they have porting issues to a Windows platform. I suspect they can be made to work with some of the GNU tools on Windows. The challenge is making an extension module that contains all the required parts for the standard Python distribution. If you are a developer with the required skills and the time, I would appreciate your help. From grante at visi.com Fri Jul 15 09:18:26 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Jul 2005 13:18:26 -0000 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? References: <11ddckucctde603@corp.supernews.com> Message-ID: <11dfdt2g35vdp78@corp.supernews.com> On 2005-07-15, Michael Hudson wrote: > Grant Edwards writes: > >> I've read over and over that Python leaves floating point >> issues up to the underlying platform. > > Please read the conversation Tim and I are having in the "Re: > math.nroot [was Re: A brief question.]" elsewhere in this same > newsgroup. Thanks, I just found it. -- Grant Edwards grante Yow! I Know A Joke!! at visi.com From http Sat Jul 30 23:34:53 2005 From: http (Paul Rubin) Date: 30 Jul 2005 20:34:53 -0700 Subject: Dabo in 30 seconds? References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050730171613.1839738924.EP@zomething.com> Message-ID: <7xr7df7in6.fsf@ruckus.brouhaha.com> James Stroud writes: > My advice is to choose something, one thing, that is REAL standard, > and in the standard library (e.g. Tkinter). And go for it. Learn it > inside and out--it will always be there for you. It is the green, > green grass of home, not that greener grass on the other side of the hill. This is good advice. I hope the stdlib gets something better than tkinter added to it, but until they're actually in the stdlib, all those alternative toolkits like wxpython are of limited interest. From roccomoretti at hotpop.com Mon Jul 11 19:04:10 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 11 Jul 2005 18:04:10 -0500 Subject: How does this code works: In-Reply-To: References: Message-ID: vch wrote: > Here's an example from some book: > > def foo(n): > s = [n] > def bar(i): > s[0] += i > return s[0] > return bar > > what I don't understand is how this example works, taking into account > the LGB rule. I thought that s is not accessible from bar, but it is, > apparently. Why? Nested Scopes (Since Python 2.1): http://www.python.org/peps/pep-0227.html From mensanator at aol.com Wed Jul 13 17:59:41 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Jul 2005 14:59:41 -0700 Subject: all possible combinations In-Reply-To: References: Message-ID: <1121291980.964463.140580@z14g2000cwz.googlegroups.com> rbt wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: > > 4^3 = 64 Should be 3**4 = 81. > > aaaa > abaa > aaba > aaab > acaa > aaca > aaac > ... > > What is the most efficient way to do this? Table t [c] a b c Query q SELECT t_3.c AS c1, t_2.c AS c2, t_1.c AS c3, t.c AS c4 FROM t, t AS t_1, t AS t_2, t AS t_3; output [c1] [c2] [c3] [c4] a a a a a a a b a a a c a a b a a a b b a a b c a a c a a a c b a a c c a b a a a b a b a b a c a b b a a b b b a b b c a b c a a b c b a b c c a c a a a c a b a c a c a c b a a c b b a c b c a c c a a c c b a c c c b a a a b a a b b a a c b a b a b a b b b a b c b a c a b a c b b a c c b b a a b b a b b b a c b b b a b b b b b b b c b b c a b b c b b b c c b c a a b c a b b c a c b c b a b c b b b c b c b c c a b c c b b c c c c a a a c a a b c a a c c a b a c a b b c a b c c a c a c a c b c a c c c b a a c b a b c b a c c b b a c b b b c b b c c b c a c b c b c b c c c c a a c c a b c c a c c c b a c c b b c c b c c c c a c c c b c c c c Record 81 of 81 From cowie.rob at gmail.com Fri Jul 22 10:58:11 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 22 Jul 2005 07:58:11 -0700 Subject: is this possible? In-Reply-To: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> References: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> Message-ID: <1122044291.340701.94900@g14g2000cwa.googlegroups.com> Yeah, Acrobat Reader is for viewing PDF's, not creating them. See http://www.reportlab.org/ for a couple of mature PDF libraries. From riccardo_cut1 at cut2_sideralis.net Sat Jul 2 09:49:17 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Sat, 02 Jul 2005 15:49:17 +0200 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119988656.668457.202660@g43g2000cwa.googlegroups.com> Message-ID: On Tue, 28 Jun 2005 12:57:36 -0700, xeys_00 wrote: > The other alternative > is to install console mode linux on it and hope that the ncurses library > can be used by python. Hi, for curses module and linux, I made a library which give you various widgets (combobox, buttons,checkbox,menubar,...). It's hard to find googling so I let you know it here. curses-extra is its name http://www.sideralis.net/index.php?action=4&pjid=20 Bye, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From bokr at oz.net Sun Jul 3 15:57:27 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Jul 2005 19:57:27 GMT Subject: Determining actual elapsed (wall-clock) time References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: <42c842d1.444800939@news.oz.net> On Sat, 2 Jul 2005 19:44:19 -0400, Tim Peters wrote: >[Peter Hansen] >> Hmmm... not only that, but at least under XP the return value of >> time.time() _is_ UTC. At least, it's entirely unaffected by the >> daylight savings time change, or (apparently) by changes in time zone. > >On all platforms, time.time() returns the number of seconds "since the >epoch". All POSIX systems agree on when "the epoch" began, but that >doesn't really matter to your use case. Number of seconds since the >epoch is insensitive to daylight time, time zone, leap seconds, etc.=20 >Users can nevertheless make it appear to jump (into the future or the >past) by changing their system clock. If you need an absolute measure >of time immune to user whims, you need to connect to special hardware, >or to an external time source. For the latter, Peter, you can probably adapt Paul Rubin' setclock.py found at http://www.nightsong.com/phr/python/setclock.py Regards, Bengt Richter From __peter__ at web.de Wed Jul 13 04:11:35 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Jul 2005 10:11:35 +0200 Subject: Frankenstring References: Message-ID: Thomas Lotze wrote: > I think I need an iterator over a string of characters pulling them out > one by one, like a usual iterator over a str does. At the same time the > thing should allow seeking and telling like a file-like object: >>> from StringIO import StringIO >>> class frankenstring(StringIO): ... def next(self): ... c = self.read(1) ... if not c: ... raise StopIteration ... return c ... >>> f = frankenfile("0123456789") >>> for c in f: ... print c ... if c == "2": ... break ... 0 1 2 >>> f.tell() 3 >>> f.seek(7) >>> for c in f: ... print c ... 7 8 9 >>> A non-intrusive alternative: >>> def chariter(instream): ... def char(): return instream.read(1) ... return iter(char, "") ... >>> f = StringIO("0123456789") >>> for c in chariter(f): ... print c ... if c == "2": break ... 0 1 2 >>> f.tell() 3 Performance is probably not so good, but if you really want to do it in C, with cStringIO you might be /almost/ there. Peter From tchurm at gmail.com Thu Jul 14 11:10:46 2005 From: tchurm at gmail.com (tchurm at gmail.com) Date: 14 Jul 2005 08:10:46 -0700 Subject: Ann: Tkinter drag and drop module References: <1121336778.344208.224820@f14g2000cwb.googlegroups.com> Message-ID: <1121353846.723518.165110@g49g2000cwa.googlegroups.com> i remember freezing a python console app i wrote some time ago using the mcmillan installer (kinda like py2exe) and was surprised to discover that binaries dragged and dropped onto the .exe file were handled properly as args...making a kind of no-gui drag and drop... how about a no-gui drag and drop for the console, would such a thing be possible? From stefan.rank at ofai.at Fri Jul 29 02:45:52 2005 From: stefan.rank at ofai.at (Stefan Rank) Date: Fri, 29 Jul 2005 08:45:52 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: <42E9D0A0.1070704@ofai.at> [__div__ for .joinpath()] on 29.07.2005 04:48 Tony Meyer said the following: >>I, herewith, claim to have used it in the past. >>But I am indifferent as to if its needed, it just looks natural to me. > > So far there seem to have been a few +0s, but no +1s... > >>What I use quite often is:: >> >> path(__file__).dirname() / "somesiblingfileiknowisthere" >> >>you do not have to think about trailing slashes or absolute vs. >>relative. and its much better than:: >> >> from os.path import * >> join(dirname(__file__), "somesiblingfileiknowisthere") > > In what way is this "much better"? because of the 'object-orientedness'. i hope we agree on that (that's the reason for a path PEP?). the first is only sugar for the explicit:: path(__file__).dirname().joinpath("blablablabalbal") and as i said +0 operator overloading is only good if it's intuitive for the majority. (or Guido i suppose, in case this majority-person does not show up) [snip] > Would you really choose this: > > p = Path() / "build" / "a" / "very" / "very" / "long" / "path" (Path() is the current dir I think) > > Over this: > > p = Path(os.path.join("build", "a", "very", "very", "long", "path")) > > ? A saving of six characters, and the second one is a lot clearer. If > there was a os.path.joinPath (or whatever name) function that returned a > Path object rather than a string, then you'd get: > > p = joinPath("build", "a", "very", "very", "long", "path") > > Which is better (clearer, more concise) than either of the others, IMO. actually for explicitness i would choose: (original jorendorff):: p = path("build").joinpath("any", "path", "you", "can", "imagine") or otherwise maybe:: p = path("alpha") / "and" / "omega" From gene.tani at gmail.com Fri Jul 22 10:09:01 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jul 2005 07:09:01 -0700 Subject: broken links In-Reply-To: <1122040156.31319.0.camel@athop1.ath.vt.edu> References: <1122040156.31319.0.camel@athop1.ath.vt.edu> Message-ID: <1122041341.587298.205620@g43g2000cwa.googlegroups.com> OR: (I think it does the same thing) os.access(filename,OS.F_OK) From tim.golden at viacom-outdoor.co.uk Tue Jul 5 05:43:14 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 5 Jul 2005 10:43:14 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file Message-ID: <9A28C052FF32734DACB0A288A3533991EBB97A@vogbs009.gb.vo.local> [Guy Lateur] | Thanks for the suggestion, Tim. Unfortunately, I get a | 'connection refused' | error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error: | (10061, 'Connection refused')". I've tried both the external | IP adress and | the internal one (10.0.0.2). I'm sure there's a way to get | over this, isn't | there? Could simply be that the Exchange server isn't running an IMAP service (or whatever it's called). Ours doesn't. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From zen19725 at zen.co.uk Thu Jul 21 00:59:58 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Thu, 21 Jul 2005 05:59:58 +0100 Subject: Generating images with text in them Message-ID: I am trying to generate some images (gifs or pngs) with text in them. I can use the Python Imaging Library, but it only has access to the default, rather crappy, font. Ideally I'd like to use one of the nicer fonts that come with my X Windows installation. Using Tkinter I can draw these fonts on the screen; is there any way to get these fonts into a bitmapped image? For example, can I draw some text on a canvas and then "grab" that canvas as a bitmap into PIL, and then save it as a file? Alternately, is there a good source of PIL font files (.pil files) somewhere? If the writers of the Python Imaging Library are reading this, may I suggest that they add more fonts to it. Yes, that would increase the size, but these days disk space is cheap and programmer time expensive. -- Email: zen19725 at zen dot co dot uk From oddr at home.no.no Fri Jul 22 07:06:45 2005 From: oddr at home.no.no (Odd-R.) Date: 22 Jul 2005 11:06:45 GMT Subject: find a specified dictionary in a list Message-ID: I have this list: [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] All the dictionaries of this list are of the same form, and all the oids are distinct. If I have an oid and the list, how is the simplest way of getting the dictionary that holds this oid? Thanks in advance -- Har du et kj?leskap, har du en TV s? har du alt du trenger for ? leve -Jokke & Valentinerne From eric_brunel at despammed.com Wed Jul 6 11:36:01 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 06 Jul 2005 17:36:01 +0200 Subject: Tkinter grid layout References: Message-ID: On Wed, 06 Jul 2005 11:44:55 +0100, Richard Lewis wrote: > Hi there, > > I've got a tree control in Tkinter (using the ESRF Tree module) but I > can't get it to layout how I want it. > > I'd like to have it so that it streches north/south (anchored to the top > and bottom), is of a fixed width and is anchored to the left hand side. > Here's my code (its derived from one of the examples from the ESRF web > site): > > class MainWindow(Frame): [snip code] First of all, it is not a good idea to make your so-called window inherit from Frame: a Frame is not a window in tk, but a generic container. Creating a Frame without a container window will automatically initialize the tk toolkit, creating a default window which will become the default parent for widgets where you don't specify one. According to the well-known "explicit is better than implicit" principle, if a MainWindow instance are actually the main window for your application, you'd really better inherit from the Tkinter class for the main window, which is Tk. Doing it this way has a lot of advantages over what you do; for example, if you later have to create a menu bar for your application, you will be able to do it in the MainWindow class. If you inherit from Frame, you won't get any access to the actual window, so you won't be able to create a menu in it. This may seems to be unrelated to your problem, but it's not: by creating a Frame, you introduce one more unneeded container. So, in some code you don't show here, you have to insert the MainWindow instance into its parent window via a call to its pack or grid method. Since the code you show seems to be correct, I guess the problem is in this call to pack or grid, which probably does not tell the Frame how to behave when its parent window is resized, causing it to get the default behaviour, which is "do nothing at all". To be sure this actually is the problem, try to replace the line: Frame.__init__(self, master) in MainWindow.__init__ by: Frame.__init__(self, master, bg='blue', bd=2) This way, a blue border will appear around the frame, allowing you to see how it grows. Then run your application, and resize the window. You should see that the frame does not grow when the window grows, explaining why your tree deos not grow (in fact, it would grow if its container did; but its container doesn't...) So you should either make your MainWindow class inherit from Tk, which eliminates the unneeded container and the problems it may cause, or make sure the pack or grid on your MainWindow instance actually tells the container to grow with its container. With pack, it's quite easy: just do myWindow.pack(fill=BOTH, expand=1). With grid, it's a bit more complicated, since you will have to configure the grid on the container. But basically, my advice would be: - Never make your windows inherit from Frame; make them inherit from Tk for the main window or from Toplevel for all other ones - When you have resize problems, always check the whole widget hierarchy from the actual window down to the widget showing the problem. The cause is very often not on the widget itself, but on one of its containers. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From tzot at sil-tec.gr Fri Jul 1 16:04:20 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 01 Jul 2005 23:04:20 +0300 Subject: [OT] Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> <5aj2c11l5vl4qds031uj7ucikikcf7uvji@4ax.com> Message-ID: On Tue, 28 Jun 2005 14:44:21 +0100, rumours say that Richie Hindle might have written: >Just to take this thread *completely* off-topic: does anyone know of a way >to scroll a Command Prompt window using the keyboard? This comparison page suggests there is no keyboard shortcut to scroll: http://www.xvsxp.com/power_user/terminal/ -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From rrr at ronadam.com Sun Jul 10 01:35:01 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 10 Jul 2005 05:35:01 GMT Subject: decorators as generalized pre-binding hooks In-Reply-To: <42d02c21.231516573@news.oz.net> References: <42d02c21.231516573@news.oz.net> Message-ID: <9s2Ae.227054$w15.137655@tornado.tampabay.rr.com> Bengt Richter wrote: > ;-) > We have Have we? Looks like not a lot of interested takers so far. But I'll bite. ;-) > So why not > > @deco > foo = lambda:pass > equivalent to > foo = deco(lambda:pass) > > and from there, > @deco > = > being equivalent to > = deco() > > e.g., > @range_check(1,5) > a = 42 > for > a = range_check(1,5)(42) > > or > @default_value(42) > b = c.e['f']('g') > for > b = default_value(42)(c.e['f']('g')) So far they are fairly equivalent. So there's not really any advantage over the equivalent inline function. But I think I see what you are going towards. Decorators currently must be used when a function is defined. This option attempts to makes them more dynamic so that they can be used where and when they are needed. How about if you make it optional too? if keep_log: @log_of_interesting_values b = get_value(c,d): Or... @@keeplog log_of_interesting_values # if keeplog decorate. b = get_value(c,d) Just a thought. > Hm, binding-intercept-decoration could be sugar for catching exceptions too, > and passing them to the decorator, e.g., the above could be sugar for > > try: > b = default_value(42)(c.e['f']('g')) > except Exception, e: > b = default_value(__exception__=e) # so decorator can check > # and either return a value or just re-raise with raise [Note 1] I'm not sure I follow this one.. Well I do a little. Looks like it might be going the direction of with statements, but only applied to a single expression instead of a block or suite. > This might be useful for plain old function decorators too, if you wanted the decorator > to define the policy for substituting something if e.g. a default argument evaluation > throws and exception. Thus > > @deco > def foo(x=a/b): pass # e.g., what if b==0? > as > try: > def foo(x=a/b): pass # e.g., what if b==0? > foo = deco(foo) > except Exception, e: > if not deco.func_code.co_flags&0x08: raise #avoid mysterious unexpected keyword TypeError > foo = deco(__exception__=e) Wouldn't this one work now? > [Note 1:] > Interestingly raise doesn't seem to have to be in the same frame or down-stack, so a decorator > called as above could re-raise: > > >>> def deco(**kw): > ... print kw > ... raise > ... > >>> try: 1/0 > ... except Exception, e: deco(__exception__=e) > ... > {'__exception__': } > Traceback (most recent call last): > File "", line 2, in ? > File "", line 1, in ? > ZeroDivisionError: integer division or modulo by zero Interestin. When it comes to decorators, and now the with statements, I can't help but feel that there's some sort of underlying concept that would work better. It has to do with generalizing flow control in a dynamic way relative to an associated block. One thought is to be able to use a place holder in an expression list to tell a statement when to do the following block of code. I'll use 'do' here... since it's currently unused and use @@@ as the place holder. (These are *NOT* thought out that far yet, I know... just trying to show a direction that might be possible.) do f=open(filename); @@@; f.close(): # do the block where @@@ is. for line in f: print line, print And an alternate version similar to a "with" statement. try f=open(filename); @@@; finally f.close(): for line if f: print line, print Maybe the exception could be held until after the try line is complete? The place holder idea might be useful for decorating as well. But I'm not sure how the function name and arguemtns would get passed to it. do deco(@@@): def foo(): pass or maybe it would need to be... do f=@@@, deco(f): def foo() pass As I said, it still needs some thinking.. ;-) Maybe leaving off the colon would use the following line without indenting as per your example? do deco(@@@) b = 42 It doesn't quite work this way I think. Possibly having a couple of different types of place holder symbols which alter the behavior might work? do deco($$$) # $$$ intercept name binding operation? b = 42 Well, it may need to be a bit (or a lot) of changing. But the idea of controlling flow with a place holder symbol might be a way to generalize some of the concepts that have been floating around into one tool. I like the place holders because I think they make the code much more explicit and they are more flexible because you can put them where you need them. > orthogonal-musing-ly ;-) "Orthogonal is an unusual computer language in which your program flow can go sideways. In actuality in can go in just about any direction you could want." http://www.muppetlabs.com/~breadbox/orth/ ;-) Cheers, Ron > Regards, > Bengt Richter From hancock at anansispaceworks.com Tue Jul 5 11:49:37 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 10:49:37 -0500 Subject: precision problems in base conversion of rational numbers In-Reply-To: <42C91973.6090208@po-box.mcgill.ca> References: <42C91973.6090208@po-box.mcgill.ca> Message-ID: <200507051049.37103.hancock@anansispaceworks.com> On Monday 04 July 2005 06:11 am, Brian van den Broek wrote: > As a self-directed learning exercise I've been working on a script to > convert numbers to arbitrary bases. It aims to take any of whole > numbers (python ints, longs, or Decimals), rational numbers (n / m n, > m whole) and floating points (the best I can do for reals), and > convert them to any base between 2 and 36, to desired precision. Interesting, I'd like to see that. > I'm pretty close but I know I am not handling the precision quite > right. Nothing other than understanding hangs on it, but, that's > enough :-) Okay. You do understand that many numbers that can be exactly represented in one base cannot be in another? E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating decimal: 0.3333333.... And of course, there are infinitely many other examples. So what you're really doing is trying to make sure that you don't *lose* precision in the conversion, *except* due to this point. I.e. you want to do the best you can do. I would say that if you have a number of places past the decimal point, that can be interpreted as the error of the representation: 1/3 ~= 0.33333 base10 +- 0.000005 Needless to say, the conventional floating point numbers in Python are actually stored as *binary*, which is why there is a "decimal" module (which is new). If you're going to be converting between bases anyway, it probably makes little difference whether you are using the decimal module or not, of course. You'll have the same problems the conventional float numbers do. Getting back to your precision problem: I bet if you simply evaluate the error term as I have above, and then convert *that* into your base of choice, you will be able to tell how many places are correct in the conversion. That is to, say, stop think about "number of places" and instead think about "representation error". That number is a real property of the data which can be represented in any base. Then you can convert it to number of places in the representation process. e.g. 0.000005 has 6 places behind the zero in decimal, how many does base3(0.000005)? --- that's the accuracy of the statement 0.33333 base10 ~= 0.1 base3 +- base3(0.000005 base10) Roughly, we know that 0.000005 = 10^-5 / 2. The same term in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved using logarithms, but I'll "leave that as an excercise for the reader", because I'm too lazy to go look it up, and I've forgotten the details. ;-) I hope this is helpful, though, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Wed Jul 13 11:57:25 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 14 Jul 2005 01:57:25 +1000 Subject: all possible combinations References: <1121267364.28617.4.camel@athop1.ath.vt.edu> Message-ID: On Wed, 13 Jul 2005 11:09:25 -0400, rbt wrote: > On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: >> Say I have a list that has 3 letters in it: >> >> ['a', 'b', 'c'] >> >> I want to print all the possible 4 digit combinations of those 3 >> letters: [snip] > Expanding this to 4^4 (256) to test the random.sample function produces > interesting results. It never finds more than 24 combinations out of the > possible 256. This leads to the question... how 'random' is sample ;) See below. > Try it for yourselves: > > test = list('1234') > > combinations = [] > while 1: > combo = random.sample(test, 4) > possibility = ''.join(combo) > if possibility not in combinations: > print possibility > combinations.append(possibility) > continue > else: > continue That's not very efficient code. Why not just write it like this? combinations = [] while 1: combo = random.sample(test, 4) possibility = ''.join(combo) if possibility not in combinations: print possibility combinations.append(possibility) You don't need either of the two continue statements. But in fact, random.sample is correct. You have four items to choose from: "1", "2", "3", "4". If you choose them with replacement, then there are 4*4*4*4 = 256 possibilities, but that includes duplicates: [4, 4, 4, 4] is one such possibility. As the documentation for random.sample clearly says: "sample(self, population, k) method of random.Random instance Chooses k unique random elements from a population sequence." Notice the UNIQUE part? You should have realised that just by looking at the strings as they were printed. None of them have duplicated digits. Sampling WITHOUT replacement gives 4*3*2*1 = 24 possibilities, exactly as your code produces. -- Steven. From tprimke at interia.pl Sun Jul 24 09:04:28 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jul 2005 06:04:28 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <1122210268.757687.20290@g49g2000cwa.googlegroups.com> > PyQt works equally well on both systems. I believe you. The problem is I don't like GPL. From could.net at gmail.com Tue Jul 19 20:50:37 2005 From: could.net at gmail.com (could ildg) Date: Wed, 20 Jul 2005 08:50:37 +0800 Subject: What does "::" mean? Message-ID: <311b5ce1050719175054e268b6@mail.gmail.com> I know that ":" can do slice works. But I saw "::" today and it puzzled me much, I can't find it in the python doc, so I raise this question here. The code is as below: ---------------------------------------------------------- Jython 2.2a1 on java1.5.0_03 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> live='live';print live live >>> live=live[::-1];print live evil >>> -------------------------------------------------------- "[::-1]" can reverse a string magicly, how did it do it? From peter at engcorp.com Tue Jul 19 07:43:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 19 Jul 2005 07:43:49 -0400 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? In-Reply-To: References: Message-ID: <-I2dnSRstZxiekHfRVn-rA@powergate.ca> Chris wrote: > Could anyone write a small program to log the Signal-to-Noise figures > for a Netgear DG834 router? Sure, though I don't have a Netgear DG834. Maybe you could, uh, enable remote administration and publish the admin password here, and those of us without that equipment could access yours in order to test out the script as we write it. ;-) -Peter From python at rcn.com Wed Jul 6 19:31:55 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jul 2005 16:31:55 -0700 Subject: precision problems in base conversion of rational numbers References: <42C91973.6090208@po-box.mcgill.ca> <200507051049.37103.hancock@anansispaceworks.com> <1120642550.714547.256540@z14g2000cwz.googlegroups.com> <1120671142.077815.269630@g49g2000cwa.googlegroups.com> Message-ID: <1120692715.670429.90360@g47g2000cwa.googlegroups.com> > > For a simple example, convert both 10247448370872321 and > > 10247448370872319 from base ten to 4 digits of hex. The calculations > > need to be carried out to 15 places of hex (or 17 places of decimal) > > just to determine whether the fourth hex digit is a 7 or 8: > > > > >>> hex(10247448370872321) > > '0x24680000000001L' > > >>> hex(10247448370872319) > > '0x2467ffffffffffL' > > I don't understand your simple example. > > log(10)/log(16) = 0.83048202372184058696757985737235 > > Multiplying by the number of decimal digits (17) gives > > 14.11819440327128997844885757533 > > Rounding up to an integer digit count, we need need 15 hex digits. > Isn't that exactly what you concluded? Where does that 4 hex digit > stuff come from? It is part of the OP's problem spec. Given a number x (which may be a decimal, float, long integer, or rational), a base b, and a desired precision p, compute the conversion to p-digits: >>> convert(x=10247448370872319L, b=16, p=4) '24680000000000' He wanted to know what decimal precision he needed to set to make the conversion accurate to the last place. The required precision for intermediate calculations depends on how close x is to a representable value in the target base. The 16 digits are not known a priori since x may be a rational, float, or decimal. For instance, an internal precision of 17 digits would also be needed for other nearby values of x: >>> convert(x=Decimal("10247448370872319.000000001", b=16, p=4) '24680000000000' The number 17 does not just pop-out of a simple logarithm. How many internal digits of precision do you need for convert(math.pi, b=16, p=5)? If the result falls closely between reprentable values, the OP may need to set his "magic number" to something larger than you would have predicted. If you want insight into why the OP's problem statement is deeper than it appears, then ponder the mystery of why the following returns False: >>> x = 554459760520464551937111727196883414687442277344893869152167 >>> float(x) == float(str(x)) False Hint, the two different underlying routines are trying to compute, convert(x, b=2, p=53), without the benefit of arbitrary precision arithmetic. Raymond From thomasbartkus at comcast.net Thu Jul 28 11:47:38 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 28 Jul 2005 10:47:38 -0500 Subject: Why Tcl/Tk? References: <97c93$42e80da0$d8fe9d88$9743@PRIMUS.CA> Message-ID: "William Park" wrote in message news:97c93$42e80da0$d8fe9d88$9743 at PRIMUS.CA... > Jerry He wrote: > > I'm a little curious, why does most scripting > > languges(i.e. python and ruby) use Tcl/Tk rather than > > wx or Fox as its standard GUI? Although I did notice > > that the Vpython IDE that uses Tkinker starts up a lot > > faster than the DrPython IDE that uses wxpython. But > > that makes no sense, Tk is based on Tcl, a scripting > > language, but wx is written in C++. > > Old habits die hard. Soon, these folks will die off, and we'll be left > with GTK+ or wxWidgets. > Ahhh! That devilish little "or" If we only knew which one :-) Thomas Bartkus From sjmaster at gmail.com Wed Jul 13 16:57:39 2005 From: sjmaster at gmail.com (Steve M) Date: 13 Jul 2005 13:57:39 -0700 Subject: PY2EXE => Is there a way to go backwards? EXE2PY In-Reply-To: <1121277611.573163.318250@g49g2000cwa.googlegroups.com> References: <1121277611.573163.318250@g49g2000cwa.googlegroups.com> Message-ID: <1121288259.850230.171020@g49g2000cwa.googlegroups.com> >I have the executable of a script that I wrote, that has been erased. >Is there any way to retrieve the uncompiled python script from the >executable that was created with py2exe? You're gonna need a case of 20-weight ball bearings and several quarts of antifreeze. Preferably Quakerstate. No, better make it Penzoil. From simon.brunning at gmail.com Wed Jul 27 07:31:48 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 27 Jul 2005 12:31:48 +0100 Subject: question about deleting records from mysql In-Reply-To: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> Message-ID: <8c7f10c605072704311c6deea5@mail.gmail.com> On 27 Jul 2005 04:29:33 -0700, nephish at xit.net wrote: > Hey there, > sorry , second question in as many days. > i am trying to do some stuff with MySQLdb and the thing is, i can > select records and such, but when i try to delete them, they dont > really go away. A fiver says you need to commit your changes. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rrr at ronadam.com Sun Jul 3 01:40:18 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 03 Jul 2005 05:40:18 GMT Subject: Folding in vim In-Reply-To: References: Message-ID: <6TKxe.212644$w15.190818@tornado.tampabay.rr.com> Terry Hancock wrote: > My general attitude towards IDEs and editors has been > extremely conservative, but today I decided to see what > this "folding" business was all about. > > I see that vim (and gvim, which is what I actually use) > has this feature, and it is fairly nice, but at present it's > very manual --- and frankly it's hard for me to see the > point if I have to manually mark folds every time I start > up. I been trying to learn and use the 'Cream' distribution of Vim. http://cream.sourceforge.net/ Playing around with it a bit.... If I highlight any block of code... then press F9 it folds it. Put the cursor on the fold and pressing F9 again unfolds it. It remembers the folds, so putting the cursor anywhere in the previous folded area and pressing F9 again refolds the fold. Folds can be inside of folds. Saving the file exiting and reopening it... the folded folds remained folded. I'm not sure where it keeps the fold info for the file. The folds don't have anything to do with classes or functions, but are arbitrary selected lines, with the first line displayed after the number of lines folded. So a whole file gets reduced to... 1 # SliderDialog.py 2 3 +--- 20 lines: """ SIMPLE SLIDER DIALOG ------------------------- 23 24 +-- 24 lines: # Imports------------------------------------------ 48 49 +-- 13 lines: # Values extracted from win32.com------------------ 62 63 +-- 67 lines: class SliderDialog(dialog.Dialog):----------------- 130 131 +-- 4 lines: def GetSliderInput( title, text, label, value=0 ):- 135 136 +-- 17 lines: if __name__ == '__main__':------------------------- 153 Pretty cool, I'll probably use folding more now that I've played with it a bit. I like Vim-Cream, but I still haven't gotten the script right for executing the current file in the shell. And a second script for executing the current file in the shell and capturing the output in a pane. I think some of it may be windows path conflicts. Ron From peterbe at gmail.com Tue Jul 19 08:16:28 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 19 Jul 2005 05:16:28 -0700 Subject: Finding # prefixing numbers In-Reply-To: References: <1121772902.193765.258700@g49g2000cwa.googlegroups.com> Message-ID: <1121775387.975777.199620@g43g2000cwa.googlegroups.com> Thank you! That solved my problem. From hongqn at gmail.com Fri Jul 22 11:48:19 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Fri, 22 Jul 2005 23:48:19 +0800 Subject: tuple to string? In-Reply-To: <42E0EED4.4020001@gmx.net> References: <42E0EED4.4020001@gmx.net> Message-ID: <42E11543.4050803@gmail.com> Francois De Serres wrote: > hiho, > > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to > the string 'spam'? Use ''.join and chr() as others have pointed out. Here are just-for-fun versions ;) .>>> t = (0x73, 0x70, 0x61, 0x6D) (use string formatter): .>>> '%c%c%c%c' % t 'spam' (use struct model): .>>> import struct .>>> struct.pack('bbbb', *t) 'spam' -- Qiangning Hong I'm usually annoyed by IDEs because, for instance, they don't use VIM as an editor. Since I'm hooked to that, all IDEs I've used so far have failed to impress me. -- Sybren Stuvel @ c.l.python Get Firefox! From see at signature.invalid Sun Jul 31 22:58:31 2005 From: see at signature.invalid (Nigel Rowe) Date: Mon, 01 Aug 2005 12:58:31 +1000 Subject: Thaughts from an (almost) Lurker. References: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Message-ID: <11er3uo5162vlb0@news.supernews.com> Benji York wrote: > Paddy wrote: >> Sometimes when reading c.l.p. I mentally stand off from what I have >> been reading and get an odd feeling that 'WE ARE BEING TESTED'. That >> someone else is purposefully posting a near repetitive post, or obvious >> flame bait etc - not for the usual reasons, but to track the dynamics >> af the replies. > > "Never attribute to malice that which can be adequately explained by > stupidity." > -- > Benji York And its corollary, "sufficiently advanced cluelessness is indistinguishable from malice." -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From jgrahn-nntq at algonet.se Tue Jul 19 12:33:35 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 19 Jul 2005 16:33:35 GMT Subject: email format in python References: <20050718102120.64241.qmail@web42004.mail.yahoo.com> Message-ID: On Mon, 18 Jul 2005 06:44:36 -0400, Benji York wrote: > met at n wrote: >> I want to have the python equivalent function of this >> (that checks email format) >> ... >> if (ereg("[[:alnum:]]+@[[:alnum:]]+\.[[:alnum:]]+", ... > > While it is possible to translate the above code into Python (see > http://docs.python.org/lib/module-re.html), you should know that the > regex above will not validate all possible email addresses. To be even more explicit about it, the regexp is extremely naive, and gives the wrong results for a lot of common address formats -- not to mention for even more uncommon formats. Do not use it, and do not try to modify it to work! > In general > it is a fools errand to try to anyway. Agree. In the case of user input validation, it might be ok to politely inform the user that the address looks a bit funny, but refusing to work with it will anger a user sooner or later. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From thomasbartkus at comcast.net Thu Jul 14 16:00:53 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 14 Jul 2005 15:00:53 -0500 Subject: Native ODBC access for python on linux? References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> Message-ID: <8NCdnRaSkdR-XkvfRVn-jg@telcove.net> wrote in message news:1121364222.540501.198600 at g14g2000cwa.googlegroups.com... > I'm getting my feet wet with making Python talk to MySQL via ODBC. I > started on Windows, and it went smoothly enough due to the ODBC stuff > that apparently is native to Python at least on windows (I've been > following ch. 13 of Mark Hammond's py on win32 book). > > But now I'm trying to do equivalent stuff on linux (Fedora Core 3) with > python 2.3.5 and mysql. I'd like to stick with packages that are > native to python, rather than relying on external stuff (e.g., MySQLdb > and mxODBC). Is this possible, or do I have to use 3rd party pieces to > use ODBC with Python under linux? > > > As an aside, I've only used ODBC to access db's, period. I've never > used, for example, MySQL's API for working with a MySQL db. I'm > curious to see what that looks like, if anyone has any examples > (python, c, or otherwise). > > Thanks in advance for any help. > -Bill We have a Linux/Apache/MySQL server. We use the ODBC driver to write Windows clients using VB. I only understand ODBC as a means to bring the Linux/Apache/MySQL to speaking terms with the Microsoft world. ODBC serves as the translator between these 2 alien systems. Although I hear rumors about ODBC drivers on Linux, I confess I don't understand the need. Certainly you can use Python with the MySQLdb module from any Linux machine and query away at the server. As long as the MySQL server accepts your IP/usr/pwd, it will respond to the SQL you pass it from Python. IOW - who/what needs an ODBC driver here? Thomas Bartkus From dalke at dalkescientific.com Thu Jul 28 03:05:58 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 28 Jul 2005 07:05:58 GMT Subject: can list comprehensions replace map? References: Message-ID: Steven Bethard wrote: > Here's one possible solution: > > py> import itertools as it > py> def zipfill(*lists): > ... max_len = max(len(lst) for lst in lists) A limitation to this is the need to iterate over the lists twice, which might not be possible if one of them is a file iterator. Here's a clever, though not (in my opinion) elegant solution import itertools def zipfill(*seqs): count = [len(seqs)] def _forever(seq): for item in seq: yield item count[0] -= 1 while 1: yield None seqs = [_forever(seq) for seq in seqs] while 1: x = [seq.next() for seq in seqs] if count == [0]: break yield x for x in zipfill("This", "is", "only", "a", "test."): print x This generates ['T', 'i', 'o', 'a', 't'] ['h', 's', 'n', None, 'e'] ['i', None, 'l', None, 's'] ['s', None, 'y', None, 't'] [None, None, None, None, '.'] This seems a bit more elegant, though the "replace" dictionary is still a bit of a hack from itertools import repeat, chain, izip sentinel = object() end_of_stream = repeat(sentinel) def zipfill(*seqs): replace = {sentinel: None}.get seqs = [chain(seq, end_of_stream) for seq in seqs] for term in izip(*seqs): for element in term: if element is not sentinel: break else: # All sentinels break yield [replace(element, element) for element in term] (I originally had a "element == tuple([sentinel]*len(seqs))" check but didn't like all the == tests incurred.) Andrew dalke at dalkescientific.com From steven.bethard at gmail.com Fri Jul 8 20:18:46 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Jul 2005 18:18:46 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Well, I want to offer a more radical proposal: why not free squared > braces from the burden of representing lists at all? It should be > sufficient to write > >>>>list() > list() > > After being free one can use them for other purposes e.g. replacing the > ugly @ decorator character by the lovely [ .. ] notation or other > important features no one never trusted to implement waiting for the > right syntax sugar. More than this round braces together with lists can > be considered as a concession to the LISP programmer who was repelled > from Python by the decision to eliminate functional programming > features. Heh heh. So how do I write a list literal then? Or do we only get tuple literals in Python 3.0. ;) STeVe From me at privacy.net Sun Jul 10 19:00:29 2005 From: me at privacy.net (Dan Sommers) Date: Sun, 10 Jul 2005 19:00:29 -0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: On Sun, 10 Jul 2005 16:26:24 -0400, "Terry Reedy" wrote: > "Ralf W. Grosse-Kunstleve" wrote in message > news:20050710133959.83611.qmail at web31512.mail.mud.yahoo.com... > I have a suggestion I don't remember seeing for flagging which vars to > autoinit without new syntax: use '_' instead of '.'. I have never seen > local vars with a leading '_'. So, in combination with whatever other > mechanism (metaclass, __init__ decorator?) > def __init__(self, _x, y, _z) : > would automatically do self.x = _x, self.z = _z, but not self.y = y. > Terry J. Reedy That's a pretty big change; now all formal parameters beginning with an underscore have a brand new meaning. How about this: def __init__(self, self.x, y, self.z): # self.x, self.z from first and third explicit parameters do_something_with_y() where "self" in "self.x" and "self.y" would have to match the first parameter (so that the pathological among us could write this: def __init__(this, this.x, y, this.z): do_something_with_y() instead). (Sorry if this posts multiple times; gnus and/or my news server were not happy when I was composing this reply.) Regards, Dan -- Dan Sommers From cliff at develix.com Sun Jul 31 17:00:39 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 14:00:39 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <5e1qe19sflih44nvmso90hnsbgbpef7mjp@4ax.com> References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <5e1qe19sflih44nvmso90hnsbgbpef7mjp@4ax.com> Message-ID: <1122843640.19618.130.camel@localhost.localdomain> On Sun, 2005-07-31 at 18:00 +0000, Dennis Lee Bieber wrote: > On Sun, 31 Jul 2005 00:13:18 -0400, Ed Leafe declaimed > the following in comp.lang.python: > > > > > Sorry you feel that way. You'll miss out on really great Python products that > > aren't in the standard Library, such as Twisted, Zope/Plone, Dabo, and many > > others. > > > Zope/Plone are applications in their own right... They aren't > designed to be plug-ins for the development of Python programs. Yes, > they USE Python as the runtime basis but they are complete as is -- one > can install Plone and never have to know about Python (be a touch > limited, but it can be used). In a way, Python is part of the Zope/Plone > standard library, not the other way around. > > Can that be said for the others? Twisted, for one, can't be used without knowing Python. In fact, without knowing Python quite well. For that matter, it can't easily be used . Cliff (who has a love/hate relationship with Twisted) -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From steve at REMOVETHIScyber.com.au Wed Jul 6 11:30:40 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 07 Jul 2005 01:30:40 +1000 Subject: Use cases for del References: Message-ID: On Wed, 06 Jul 2005 10:00:02 -0400, Jp Calderone wrote: > On Wed, 06 Jul 2005 09:45:56 -0400, Peter Hansen wrote: >>Tom Anderson wrote: >>> How about just getting rid of del? Removal from collections could be >>> done with a method call, and i'm not convinced that deleting variables >>> is something we really need to be able to do (most other languages >>> manage without it). >> >>Arguing the case for del: how would I, in doing automated testing, >>ensure that I've returned everything to a "clean" starting point in all >>cases if I can't delete variables? Sometimes a global is the simplest >>way to do something... how do I delete a global if not with "del"? >> > > Unless you are actually relying on the global name not being defined, "someGlobal = None" would seem to do just fine. > > Relying on the global name not being defined seems like an edge case. Er, there is a lot of difference between a name not existing and it being set to None. $ cat mymodule1.py # define some temporary names a, b, c, d, e, f = 1, 2, 3, 4, 5, 6 # do some work result = a+b+c+d*e**f # delete the temp variables del a del b del c del d del e del f $ cat mymodule2.py # define some temporary names a, b, c, d, e, f = 1, 2, 3, 4, 5, 6 # do some work result = a+b+c+d*e**f # delete the temp variables a = None b = None c = None d = None e = None f = None Now import them into Python: py> import mymodule1, mymodule2 py> dir(mymodule1) ['__file__', '__name__', result] py> dir(mymodule2) ['__file__', '__name__', result, a, b, c, d, e, f] Or worse, do this: py> a = 1 py> from mymodule2 import * py> a + 1 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' It is bad enough that from module import * can over-write your variables with the modules' variables, but for it to do so with DELETED variables is unforgivable. -- Steven. From owner-discussion at Softimage.COM Tue Jul 19 04:14:47 2005 From: owner-discussion at Softimage.COM (owner-discussion at Softimage.COM) Date: Tue, 19 Jul 2005 04:14:47 -0400 Subject: BOUNCE discussion@Softimage.COM: Non-member submission from [python-list@python.org] Message-ID: <200507190814.j6J8ElNu003612@paperboy.global.avidww.com> >From Discussion-owner at paperboy.global.avidww.com Tue Jul 19 04:14:47 2005 Received: from mtl-smtpgw2.global.avidww.com (mtl-smtpgw2.global.avidww.com [172.24.33.104]) by paperboy.global.avidww.com (8.12.9/8.12.6) with ESMTP id j6J8ElvQ003608 for ; Tue, 19 Jul 2005 04:14:47 -0400 Received: from softgate1.softimage.com ([172.24.33.30]) by mtl-smtpgw2.global.avidww.com with Microsoft SMTPSVC(5.0.2195.6713); Tue, 19 Jul 2005 04:14:31 -0400 Received: from python.org (IDENT:U2FsdGVkX1+OCYGwA1jbkYmfj8ulD36u42FAOXmREtc at localhost.localdomain [127.0.0.1]) by softgate1.softimage.com (8.12.11/8.12.1) with SMTP id j6J79xHO019613 for ; Tue, 19 Jul 2005 03:10:00 -0400 Message-Id: <200507190710.j6J79xHO019613 at softgate1.softimage.com> From: python-list at python.org To: discussion at softimage.com Subject: MAIL SYSTEM ERROR - RETURNED MAIL Date: Tue, 19 Jul 2005 09:14:21 +0100 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0013_B2929ED7.98D0B0AF" X-Priority: 3 X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook Express 6.00.2600.0000 X-MIMEOLE: Produced By Microsoft MimeOLE V6.00.2600.0000 X-OriginalArrivalTime: 19 Jul 2005 08:14:31.0648 (UTC) FILETIME=[E404EE00:01C58C39] This is a multi-part message in MIME format. ------=_NextPart_000_0013_B2929ED7.98D0B0AF Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit This message was not delivered due to the following reason(s): Your message could not be delivered because the destination server 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 3 days: Server 54.158.252.173 is not responding. The following recipients could not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. ------=_NextPart_000_0013_B2929ED7.98D0B0AF Content-Type: text/plain Content-Transfer-Encoding: 7bit [Filename: discussion at softimage.com, Content-Type: application/octet-stream] The attachment file in the message has been removed by eManager. ------=_NextPart_000_0013_B2929ED7.98D0B0AF-- From me at privacy.net Sat Jul 30 11:38:21 2005 From: me at privacy.net (Dan Sommers) Date: Sat, 30 Jul 2005 11:38:21 -0400 Subject: How to do this? References: Message-ID: On Fri, 29 Jul 2005 22:34:23 +0800, "flyaflya" wrote: > the codes as follow: > class Base: > def fun(self): > print "base_fun" > def fun2(self): > print "base_fun2" > class Foo: > def __init__(self, base): > self.__base = base > def fun3(self): > print "foo_fun3" > b = Base() > foo = Foo(b) > my aim is:when "foo.fun3()" be called,it run as usually, but when > "foo.fun()" or "foo.fun2() be called, as Foo hasn't attribute "fun()" and > "fun2()", foo will call "self.__base.fun()" or "self.__base.fun2()". > when a attr can't be find in foo, it's will try to search 'self.__base". I > think this maybe need to use "__getattr__" and "__setattr__" ,but I cant do > it successfully. can someone help me? class Foo(Base): def fun3(self): print "fun_foo3" HTH, Dan -- Dan Sommers From rkern at ucsd.edu Sun Jul 10 17:10:20 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 10 Jul 2005 14:10:20 -0700 Subject: ZipFile and file rigths In-Reply-To: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> Message-ID: perchef wrote: > hi, > > i have written this small code which allow me to unzip files using > python : > > import zipfile > import os > import os.path > > pathDir="/home/toto/Desktop" > pathZip= os.path.join(pathDir,"foobar.zip") > > if zipfile.is_zipfile(pathZip): > zf = zipfile.ZipFile(pathZip) > > for file in zf.namelist(): > newPath = os.path.join(pathDir,file) > print newPath > if not file.endswith('/') and not os.path.exists(newPath) : > newFile = open(newPath, 'wb') > newFile.write(zf.read(file)) > newFile.flush() > newFile.close() > else : > os.makedirs(newPath) > > zf.close() > else: > print pathZip + " is not a zip file" > > it works well but i have a small problem : i can't see how i can deal > with file rights. > When I unzip files with this script all the unzipped files haven't the > good rights. > for example : > with this script : > -rw-r--r-- foo.exe > with a traditional zip program (ie : stuffit ): > -rwxr-xr-x foo.exe > ZipInfo objects doesn't store informations about rights ? > (http://www.python.org/doc/current/lib/zipinfo-objects.html#zipinfo-objects) > > How can i fix this ? This is possibly related, I'm not sure: http://article.gmane.org/gmane.comp.python.apple/8012 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From Florian.Lindner at xgm.de Sun Jul 3 16:55:07 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sun, 03 Jul 2005 22:55:07 +0200 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> <6f-dnTeTQayMRVvfRVn-jQ@powergate.ca> Message-ID: Peter Hansen wrote: > Florian Lindner wrote: >> Peter Hansen wrote: >>>[Zope] doesn't include >>>database interfaces other than to its own ZODB. >> >> That's not correct. Zope2 includes DB interfaces to MySQL, PostGre, ODBC >> and many others. > > It actually *includes* them? I thought those were all add-in modules, > not ones that Zope actually installs. (I admit it's been a couple of > years since I was current with the state of Zope... and my memory sucks. > :-( ) Ok, you're right. But I don't really think it makes a difference to install them afterwards. Florian From peterbe at gmail.com Fri Jul 8 13:48:11 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 8 Jul 2005 10:48:11 -0700 Subject: Snakespell In-Reply-To: References: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> Message-ID: <1120844891.616631.168860@f14g2000cwb.googlegroups.com> Tried that. They don't store the .tar.gz file. It becomes a blank page. From cam.ac.uk at mh391.invalid Thu Jul 21 11:43:00 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 16:43:00 +0100 Subject: is this pythonic? In-Reply-To: References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: Steven D'Aprano wrote: > The great thing about Usenet and the Internet is that we can pick each > other's brains for answers, instead of flailing around blindly in manuals > that don't understand the simplest natural language query. And isn't that > why we're here? Personally, I feel my time is better served by answering questions that would not be easy to find without assistance. I can't expect everyone to know about or expect enumerate() from the beginning, so I don't have any objections to it being asked here. If people were to ask what the function signature for enumerate() was when that is easy to Google, then I would think they were wasting everyone's time. -- Michael Hoffman From max at alcyone.com Sun Jul 3 20:05:44 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 03 Jul 2005 17:05:44 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> <1120424454.854518.100610@o13g2000cwo.googlegroups.com> Message-ID: Christopher Subich wrote: > Interesting; could you post an example of this? Whenever I try to think > of that, I come up with unwieldly syntax for the functional case. In > purely functional code the results of map/filter/etc would probably be > directly used as arguments to other functions, which might make the > calls longer than I'd consider pretty. This is especially true with > lots of lambda-ing to declare temporary expressions. I personally think that map looks clearer than a list comprehension for a simple function call, e.g. map(str, sequence) vs. [str(x) for x in sequence] -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis In Heaven all the interesting people are missing. -- Friedrich Nietzsche From duncan.booth at invalid.invalid Wed Jul 13 09:47:11 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jul 2005 13:47:11 GMT Subject: Building a function call? (update) References: <42D50A88.3070909@gmx.net> Message-ID: Francois De Serres wrote: > Sorry, I was unclear about the fact that the args are formals. I'm > trying to do something like: > > func = "dothat" > args = ('x','y') > localcontext = () > r = None > while r is None: > try: > r = eval("dothat(x,y)", None, localcontext) #how do I construct > "dothat(x,y)"? with 'dothat(%s,%s)' % args? > except NameError: > ensure_context(args) #find/compute the formals, eg: localcontext >= (('x', 100), ('y', 200)) I think when your code ends up in as big a mess as this, you need to take a step back. Forget about asking us how you get at functions or arguments as strings, instead tell us what problem you are really trying to solve. I'm pretty sure that whatever your problem is, the solution won't involve using 'eval', and it almost certainly won't involve looking up variables or functions from their names. From twic at urchin.earth.li Fri Jul 1 09:38:08 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 1 Jul 2005 14:38:08 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey Message-ID: Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him. What really struck me, though, is the last line of the abstract: "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme folks. :-)" I disagree strongly with Guido's proposals, and i am not an ex-Lisp, -Scheme or -any-other-functional-language programmer; my only other real language is Java. I wonder if i'm an outlier. So, if you're a pythonista who loves map and lambda, and disagrees with Guido, what's your background? Functional or not? tom -- Batman always wins From GoogleGroups at garringer.net Thu Jul 14 13:22:56 2005 From: GoogleGroups at garringer.net (GoogleGroups at garringer.net) Date: 14 Jul 2005 10:22:56 -0700 Subject: How do I send keystrokes to a console window in Windows XP? Message-ID: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> How do I use Python to send keystrokes to a console window in Windows XP? Or perhaps there is an application that I can call to do this? Thank you for your help. From pinard at iro.umontreal.ca Sun Jul 10 13:12:21 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 10 Jul 2005 13:12:21 -0400 Subject: computer algebra packages In-Reply-To: <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> Message-ID: <20050710171221.GA29664@phenix.progiciels-bpi.ca> [Florian Diesch] > Probably this is usable for you (I never used any of them): > This system MAXIMA is [...] based on the original implementation of > Macsyma at MIT [...] Wow! A derivative of Joel Moses' integrator!! I was not aware this existed, so thanks for the pointer. It worked out of the box for me! > Description: A user-friendly frontend for MAXIMA > Mascyma is (trying to be) a user-friendly graphical frontend for the Computer > Algebra System GNU MAXIMA. It is written in Python and provides two GUIs, > one of which based on PyGTK, the other based on wxPython. I was not successful googling for this one. Would you have an URL handy? -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From philippe at philippecmartin.com Fri Jul 8 13:26:30 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 08 Jul 2005 17:26:30 GMT Subject: Options to integrate Python modules into native windows applications References: <42ce9f7c$0$25046$8fcfb975@news.wanadoo.fr> Message-ID: Thanks Michel et salutations. Your english is fine. A+ Philippe Do Re Mi chel La Si Do wrote: > Re Hi ! > > > I had only test (little) Python for .Net ; OK, it's run. It is possible to > make winform from Python. And I had try to use Python for .Net from my > COM-server, and from VBscript. OK also. > > Plus, I had try to call my Python-server-COM, from C# : OK it's run. C# > can use Python. > > And, I had try to make, in Internet-Explorer, a page, with > Html+javascript, who call the Python-server-COM, and at the same time, > contains an object-assembly dotNET, who call also the server-COM. It is > twisted, but it's run OK (that opens two sessions of the server-COM, which > communicate by mmap). > > * sorry for my bad english * > > > @-salutations > > Michel Claveau From dsiroky at email.cz Mon Jul 11 09:06:44 2005 From: dsiroky at email.cz (David Siroky) Date: Mon, 11 Jul 2005 15:06:44 +0200 Subject: pyo contains absolute paths References: <1120934931.720410.61380@z14g2000cwz.googlegroups.com> Message-ID: V Sat, 09 Jul 2005 11:48:51 -0700, ncf napsal(a): > Python is compiling the files with absolute paths because it is much > faster to load a file when you know where it is, than to have to find > it and then load it. > > I'm guessing you're wondering this so you can distribute it compiled or > such? If so, I wouldn't do that in the first place. Python's compiled > files might be version/architecture dependant. > > -NcF I want to write a commercial application in Python and I don't want the customer to see the source code and absolute paths of my modules which have btw. the same base path as the main module so I would expect only relative paths in the compiled files. David From rrr at ronadam.com Mon Jul 4 17:46:00 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 04 Jul 2005 21:46:00 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120490609.134384.206840@g47g2000cwa.googlegroups.com> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > And finally for recursive flattening: > > def flatten(seq): > return reduce(_accum, seq, []) > > def _accum(seq, x): > if isinstance(x,list): > seq.extend(flatten(x)) > else: > seq.append(x) > return seq > > >>>>flatten(seq) > > [1, 2, 3, 4, 5, 6] > > > George > How about this for a non recursive flatten. def flatten(seq): s = [] while seq: while isinstance(seq[0],list): seq = seq[0]+seq[1:] s.append(seq.pop(0)) return s seq = [[1,2],[3],[],[4,[5,6]]] flatten(seq) Ron From apardon at forel.vub.ac.be Wed Jul 6 05:39:17 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Jul 2005 09:39:17 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> <868y0q3pcn.fsf@bhuda.mired.org> Message-ID: Op 2005-07-02, Mike Meyer schreef : > "Sean McIlroy" writes: > >> Peter Hansen wrote: >> >>> Sean, what gave you the impression this would change? >> if that's the case then list comprehensions and/or "first class >> functions" are likely to be the next target. > > The existence of list comprehensions are the reason that these > functions are going away, so they aren't likely to be next. It's all > part of "There should be one-- and preferably only one --obvious way > to do it." IMO people concentrate too much on the "and preferably only one" part of this. If you really want at least one obvious way to do things then, there also will be a lot of things that have more than one obvious way. Trying to eliminate all those mulitiple obvious ways, which seems to be one of the goals here, will result in removing the one obvious way for doing other things. -- Antoon Pardon From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 11 18:03:33 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 12 Jul 2005 00:03:33 +0200 Subject: Environment Variable In-Reply-To: <1121118260.761875.293230@z14g2000cwz.googlegroups.com> References: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> <3jg6e1Fpm157U1@individual.net> <1121118260.761875.293230@z14g2000cwz.googlegroups.com> Message-ID: <3jg8llFpiootU1@individual.net> tuxlover at gmail.com wrote: > Sorry for posting twice. > Sorry for forgetting my . Reinhold From GoogleGroups at garringer.net Mon Jul 18 14:56:46 2005 From: GoogleGroups at garringer.net (GoogleGroups at garringer.net) Date: 18 Jul 2005 11:56:46 -0700 Subject: How do I send keystrokes to a console window in Windows XP? In-Reply-To: References: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> Message-ID: <1121713006.253298.302050@g49g2000cwa.googlegroups.com> Thank you, Benji. This gives me hope, but what I really need to do is to send keystrokes to an <<>> console window. Any help there? (P.S. Sorry that I wasn't more specific.) From brian at sweetapp.com Fri Jul 22 10:35:23 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 22 Jul 2005 16:35:23 +0200 Subject: REMINDER: Python Contest Message-ID: <42E1042B.5020209@sweetapp.com> This is just a reminder that the deadline for my little programming competition is Monday. Original E-mail --------------- I've decided that it would be be fun to host a weekly Python programming contest. The focus will be on algorithms that require a bit of thought to design but not much code to implement. I'm doing to judge the solutions based on execution speed. It sucks but that is the easiest important consideration to objectively measure. I'll also indicated which solutions I think are good examples of Python design. Hopefully, people's solutions can provide a resource for people looking for best practice examples and also for people looking for performance ideas. You can find the first problem here: http://www.sweetapp.com/pycontest/contest1 I'm always looking for feedback, so let me know what you think or if you have any ideas for future problems. Cheers, Brian From mjackson at alumni.caltech.edu Fri Jul 22 13:48:23 2005 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 22 Jul 2005 17:48:23 GMT Subject: Interleave merge pdf files References: <1122051911.027433.162650@g14g2000cwa.googlegroups.com> Message-ID: "Chirayu Krishnappa" writes: > Hi, > > I need to scan documents with pages having printed matter on both > sides. It is easiest to stack them in the autosheet feeder and let it > scan. I end up with one file (say A.pdf) containing the odd pages in > sequence. Similarly, I can end up with B.pdf containing the even pages. > I want to combine them into result.pdf which contains A.1, B.1, A.2, > B.2, A.3, B.3, ... (A.1 = page 1 of A.pdf). > > Does someone know a simple way to achieve this? I noticed the other > thread on this newsgroup about merging lots of pdf files and > multivalent tools and pdftk were mentioned. However, I could not find a > way to do this using them. I am interested in another free tool or a < > 25 lines python script (which may use any freeware library) to do the > same. I face exactly the same problem. Based on examination of the pdftk man page I *think* it can be done by something like (untested): pdftk A.pdf burst output %04d_A.pdf pdftk B.pdf burst output %04d_B.pdf pdftk *_?.pdf cat output combined.pdf assuming fewer than 10,000 pages per document, of course. I would be interested in an alternative approach which does not generate a ton of intermediate pdfs. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson It is difficult for men in high office to avoid the malady of self-delusion. - Calvin Coolidge From ali.jan at gmail.com Thu Jul 14 06:02:34 2005 From: ali.jan at gmail.com (Ali) Date: 14 Jul 2005 03:02:34 -0700 Subject: more newbie list questions In-Reply-To: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> References: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> Message-ID: <1121335354.408890.120880@g44g2000cwa.googlegroups.com> It's not really clear what you mean? From nothingcanfulfill at gmail.com Sun Jul 24 21:14:13 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 24 Jul 2005 18:14:13 -0700 Subject: Simple Problem Message-ID: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> I know I've seen this somewhere before, but does anyone know what the function to escape a string is? (i.e., encoding newline to "\n" and a chr(254) to "\xfe") (and visa-versa) Thanks for helping my ignorance :P -Wes From godoy at ieee.org Fri Jul 29 13:19:48 2005 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 29 Jul 2005 14:19:48 -0300 Subject: Wheel-reinvention with Python (was: Ten Essential Development Practices) References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> Message-ID: <935qr2-km9.ln1@strongwill.g2ctech> Jeremy Moles wrote: > Four? > > 1. wx > 2. PyGTK > 3. Tk (Are you including this one even?) > 4. ??? PyQt / PyKDE. > Of the few I can think of, only one would qualify as great. :) The fourth one? ;-) -- Jorge Godoy From peter at engcorp.com Sat Jul 23 10:12:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Jul 2005 10:12:35 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kehbmFtv6lpU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> Message-ID: <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> Reinhold Birkenfeld wrote: > One thing is still different, though: a Path instance won't compare to a regular > string. Could you please expand on what this means? Are you referring to doing < and >= type operations on Paths and strings, or == and != or all those or something else entirely? > Other minor differences, as requested on python-dev, are: > > * size property -> getsize() method. > * atime/mtime/ctime properties -> atime()/mtime()/ctime() methods What does this mean? The .size property and a getsize() method both already exist (in my copy of path.py anyway) and do the same thing. Same with the other ones mentioned above. Is someone working from an out-of-date copy of path.py? > * dirs() method -> subdirs() method Given that .files() exists, and returns a list of the files contained in a path which represents a folder, why would one want to use subdirs() instead of just dirs() to do the same operation for contained folders? If subdirs() is preferred, then I suggest subfiles() as well. Otherwise the change seems arbitrary and ill-conceived. > * joinpath() method -> added alias joinwith() > * splitall() method -> parts() method This reminds me of the *one* advantage I can think of for not subclassing basestring, though it still doesn't make the difference in my mind: strings already have "split()", so Jason had to go with "splitpath()" for the basic split operation to avoid a conflict. A minor wart I guess. > * Default constructor: Path() == Path(os.curdir) To construct an empty path then one can still do Path('') ? > * staticmethod Path.getcwd() -> Path.cwd() > > * bytes() / lines() / text() -> read_file_{bytes,lines,text} methods > * write_{bytes,lines,text} -> write_file_{bytes,lines,text} methods Under Linux isn't it possible to open and read from directories much as with files? If that's true, the above would seem to conflict with that in some way. As with the the .subdirs() suggestion above, these changes seem to me somewhat arbitrary. .bytes() and friends have felt quite friendly in actual use, and I suspect .read_file_bytes() will feel quite unwieldy. Not a show-stopper however. -Peter From deets at web.de Mon Jul 18 04:07:03 2005 From: deets at web.de (Diez B.Roggisch) Date: Mon, 18 Jul 2005 08:07:03 +0000 (UTC) Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121663450.495821.102780@g49g2000cwa.googlegroups.com> Message-ID: > I have to admit that I don't understand what you mean with the > 'constant parts' of an expression? >From what I percieved of your example it seemed to me that you wanted to evaluate the constants like 7*9 first, so that an expression like a * 7 * 9 * b with variables a,b is evaluated like this: a * 63 * b So my suggestion was simply to make the *-operator more precedent when in between two constants. What I mean with constants here are of course integer/float literals. The concept of a differing operator precedence can be extended to arbitray elements when their types are known - which should be possible when variable values are known at parsing time. > The associativity of __mul__ is trivially fullfilled for the dummy > class M if an additional __eq__ method is defined by comparing factor > lists because those lists are always flat: I don't care about that, as my approach deosn't use python's built-in parser - it can't, as that wouldn't allow to re-define operator precedence. What you do is to simply collect the factors as list. But what you need (IMHO) is a parsing tree (AST) that reflects your desired behaviour by introducing a different precedence thus that the expression a * 7 *9 * b is not evaluated like ((a*7)*9)*b (which is a tree, and the standard way of evaluationg due to built-in parsers precedence rules) but as a*(7*9)*b which is also a tree. > The sorting ( or better 'grouping' which can be represented by sorting > in a special way ) of factors in question is really a matter of > (non-)commutativity. For more advanced expressions also group > properties are important: No, IMHO associativity is the important thing here - if (a * 7) * 9 yields a different solution than a *(7*9) your reordering can't be done - in the same way as re-arranging factors a*b to b*a only works if the commute - or, to put in in algebraic terms, the group is abelian. > If a,b are in a center of a group G ( i.e. they commute with any > element of G ) and G supplies an __add__ ( besides a __mul__ and is > therefore a ring ) also a+b is in the center of G and (a+b)*c = c*(a+b) > holds for any c in G. > > It would be nice ( and much more efficient ) not to force expansion of > the product assuming distributivity of __add__ and __mul__ and > factorization after the transposition of the single factors but > recognizing immediately that a+b is in the center of G because the > center is a subgroup of G. Well, you don't need to expand that product - the subexpression a+b is evaluated first. If you can sort of "cache" that evaluation's result because the expressions involved are of a constant nature, you can do so. The rason (a+b) is evaluated first (at least in the standard python parser, and in my proposed special parser) is that the parentheses ensure that. To sum things up a little: I propose not using the python built-in parser which results in you having to overload operators and lose control of precedence, but by introducing your own parser, that can do the trick of re-arranging the operators based on not only the "usual" precedence (* binds stronger than +), but by a type-based parser that can even change precedence of the same operator between different argument types is's applied to. That might sound complicated, but I think the grammar I gave in my last post shows the concept pretty well. regards, Diez From sjmachin at lexicon.net Mon Jul 25 17:26:25 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 26 Jul 2005 07:26:25 +1000 Subject: pyparsing 1.3.2 released In-Reply-To: References: Message-ID: <42e55901$1@news.eftel.com> Paul McGuire wrote: > "The best laid plans o' mice an' men / Gang aft a-gley" > > So said Robert Burns (who really should do something about that speech > impediment!). If "schemes" sounds like "plans", perhaps the impediment is in the region of your ears :-) From newstonne at web.de Fri Jul 8 03:35:28 2005 From: newstonne at web.de (Roland Heiber) Date: Fri, 08 Jul 2005 09:35:28 +0200 Subject: python nested class In-Reply-To: References: Message-ID: Vedanta Barooah wrote: > o = mother() > o.show() > y=mother.child() > y.increase(20) > # this should print 20 > o.show() > > ...... is it possible somehow ??? Hi, this should do what you want: --- test.py class mother: x=0 def __init__(self): mother.x=1 def show(self): print mother.x class child: def increase(self,num): mother.x=num o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() --- >pythonw -u "test.py" 1 20 >Exit code: 0 HtH, Roland From rkern at ucsd.edu Sun Jul 3 01:28:52 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 02 Jul 2005 22:28:52 -0700 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? In-Reply-To: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > Guido gave a nice "Python Regrets" Power Point talk at OSCON few years > ago. > > I was wondering if the plan is to ever implement these ideas. > > e.g. Guido said he'd prefer 'print' to be a *function* with perhaps a > 'println' version IIRC. > > He also had a ton of stuff he'd rather see become iterators. As currently being (re)discussed at tedious length in recent threads here, changes would will only be realized in Python 3.0 (aka Python 3000 in facetious reference to when we can expect to see such a beast). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at REMOVETHIScyber.com.au Tue Jul 5 19:57:58 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 06 Jul 2005 09:57:58 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120590707.093007.175330@o13g2000cwo.googlegroups.com> Message-ID: On Tue, 05 Jul 2005 12:11:47 -0700, mcherm wrote: > And besides, "def" isn't a "magic" word... it's an abreviation for > "define"... Really? I thought it was an abbreviation for "definition". As in, "definition of MyFunc is..." > I hope that any student who didn't understand a word as > common as "define" wouldn't have graduated from our school. How about tuple? -- Steven. From dirk.dierickx at liamg.moc Sun Jul 10 13:17:55 2005 From: dirk.dierickx at liamg.moc (dirk dierickx) Date: Sun, 10 Jul 2005 19:17:55 +0200 Subject: An absolute Newbie question References: Message-ID: On Sun, 10 Jul 2005 16:41:23 +0000, wpog wrote: > So, how to I get it to not execute, so that I can write a program that has > ordinary executable functions, and stuff like that? file > open new window the new window will not execute your code you type in there. -- The first thing we do, let's kill all the lawyers. -- Wm. Shakespeare, "Henry VI", Part IV From dotpyFE at gmail.com Tue Jul 12 00:06:22 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Tue, 12 Jul 2005 04:06:22 GMT Subject: a new Python Podcast series (and the use of Python in creating podcasting tools) In-Reply-To: <1121135302.110610.188420@f14g2000cwb.googlegroups.com> References: <1121135302.110610.188420@f14g2000cwb.googlegroups.com> Message-ID: <2lHAe.21508$eM6.7938@newsread3.news.atl.earthlink.net> rdsteph at mac.com wrote: > Python411 is a series of podcasts about Python, aimed at hobbyists and > others who are learning Python. Each episode focuses on one aspect of > learning Python, or one kind of Python programming, and points to > online tools and tutorials. Python related news and events will also be > reported upon. > > This podcast series will probably not be of much interest to expert or > professional programmers. I am a hobbyist and am not qualified nor > capable of creating a podcast series for accomplished programmers. > Maybe someone else will do that. > > The four podcasts so far are titled as such: > > Introduction to Python > > Computer Programming for Everybody > > GUI toolkits for Python > > Python for Mobile Devices > > New podcasts will appear from time to time. > > Interestingly, while on the subject of podcasts, I would like to point > out that Python is emerging as the programming language of choice for > creating tools for creating podcasts and using podcasts. For instance, > iPodder is the leading podcast aggregator, or podcatcher, and is > written in Python. Also, a new program called Podcatcher on a Stick is > an open source Python project that is creating a podcatcher that runs > on a mobile mp3 player itself, rather than on a PC. Links to these > programs can be found on my web site. > > The home page for Python411 is > http://www.awaretek.com/python/index.html and one can click on the > podcasts there to play them, or better you can subscribe to an rss feed > at http://www.awaretek.com/python/index.xml > Nice idea!! It would be great to get some of the advanced Python guys in on this from time to time. -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From devlai at gmail.com Fri Jul 1 12:51:14 2005 From: devlai at gmail.com (Devan L) Date: 1 Jul 2005 09:51:14 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <1120236674.379545.17530@f14g2000cwb.googlegroups.com> None of them are really indispensible. Map and filter cab be replaced with list comprehensions. reduce is redundant except when multiplying a series; there's a sum function for a reason. Lambda looks cleaner in some cases, but you don't gain any functionality. What really struck me, though, is the last line of the abstract: "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme folks. :-)" Guido wrote somewhere that the original map, filter, and reduce came from a lisp hacker who missed them. From graham.fawcett at gmail.com Wed Jul 20 14:51:56 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 20 Jul 2005 11:51:56 -0700 Subject: How to store "3D" data? (data structure question) In-Reply-To: References: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> Message-ID: <1121885516.735405.50910@g43g2000cwa.googlegroups.com> Sebastian Bassi wrote: > On 20 Jul 2005 10:47:50 -0700, Graham Fawcett wrote: > > This looks a lot like 2D data (row/column), not 3D. What's the third > > axis? It looks, too, that you're not really interested in storage, but > > in analysis... > > I think it as 3D like this: > 1st axis: [MARKER]Name, like TDF1, TDF2. > 2nd axis: Allele, like 181, 188 and so on. > 3rd axis: Line: RHA280, RHA801. > > I can have a star in MarkerName TDF1, Allele 181 and Line RHA280. > I can have an empty (o none) in TDF1, Allele 181 and Line RHA801. Okay. I think what will drive your data-structure question is the way that you intend to use the data. Conceptually, it will always be 3D, no matter how you model it, but trying to make a "3D data structure" is probably not what is most efficient for your application. If 90% of your searches are of the type, 'does TDF1/181/RHA280 have a star?' then perhaps a dict using (name,allele,line) as a key makes most sense: d = {('TDF1',181,'RHA280'):'*', ...} query = ('TDF1', 181, 'RHA280') assert query in d Really, you don't need '*' as a value for this, just use None if you like, since all the real useful info is in the keyspace of the dict. If you're always querying based on line first, then something like my earlier 'results' dict might make sense: d = {'RHA280':[('TDF1',181), ...], ...} for name, allele in d['RHA280']: if allele == 181: # or some other "query" within RHA280 ... You get the idea: model the data in the way that makes it most useable to you, and/or most efficient (if this is a large data set). But note that by picking a structure like this, you're making it easy to do certain lookups, but possibly harder (and slower) to do ones you hadn't thought of yet. The general solution would be to drop it into a relational database and use SQL queries. Multidimensional analysis is what relational DBs are for, after all. A hand-written data structure is almost guaranteed to be more efficient for a given task, but maybe the flexibility of a relational db would help serve multiple needs, where a custom structure may only be suitable for a few applications. If you're going to roll your own structure, just keep in mind that dict-lookups are very fast in Python, far more efficient than, e.g., checking for membership in a list. Graham From siona at chiark.greenend.org.uk Thu Jul 7 11:50:04 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Jul 2005 16:50:04 +0100 (BST) Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: =?ISO-8859-2?Q?Pawe=B3?= Sakowski wrote: >>>> ll=[[1,2],[3,4,5],[6]] >>>> sum(ll,[]) >[1, 2, 3, 4, 5, 6] That's a great argument for list.__add__ having the semantics of extend rather than append 8-) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From mwm at mired.org Tue Jul 5 15:57:12 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 05 Jul 2005 15:57:12 -0400 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Message-ID: <861x6dxbzb.fsf@bhuda.mired.org> Peter Hansen writes: > Tom Anderson wrote: >> +1 insight of the century. This is the heart of the unix way - lots >> of simple little programs that do exactly one thing well, and can be >> composed through simple, clean interfaces. For actually getting >> things done, a toolkit beats a swiss army knife. > > Perhaps, but I'm puzzled how that explanation would apply to emacs and > those who use it as a swiss army knife, doing everything from editing > to email to laundry in the same editor... Since you asked.... Unix tools require a complex environment to run in. Without a Unix kernel (or some simulation thereof), the don't work at all. Without a friendly shell, it's hard to get them to communicate with each other - which is what makes building things out of the pieces so easy. If you want to run those tools on a different OS, you have to port the environment. Emacs tools require a different environment: a running emacs. It's all kept in one process, so it looks like one big program from the Unix perspective. But it's actually a lot of smaller(*) programs running in a shared address space. There's lots of differences between the two, but a discussion of that is really OT for the group. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rkern at ucsd.edu Thu Jul 28 09:44:59 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 06:44:59 -0700 Subject: all possible combinations In-Reply-To: References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> <42d6de96@news.eftel.com> <1122547119.104995.43340@o13g2000cwo.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Have you looked at what's in the standard Python library? > > aifc.py => Stuff to parse AIFF-C and AIFF files. > imghdr.py => Recognize image file formats based on their first few bytes. > gopher.py => Gopher protocol client interface. > token.py => Token constants (from "token.h"). > > I'm sure they are useful to somebody, but do you really think that the > majority of Python users need to parse AIFF files? There's a *huge* difference between, "Should we add such-and-such module?" and "Should we keep such-and-such module?" The burden for the latter is much, much lower. Some of those modules are there because Python itself needs them (token.py). Some are there because way back in the day before python-dev got disciplined (or, for that matter, existed), a sufficient criterion for inclusion into the standard library was, "Guido uses it." He needed to parse AIFF files and various arcane image formats and do graphics using the old SGI GL (the precursor to OpenGL). That's why some of that stuff is there. That said, I really would like a nice standard way to get the base-n representations of numbers for at least 2 <= n <= 36. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From flamesrock at gmail.com Mon Jul 4 14:10:55 2005 From: flamesrock at gmail.com (flamesrock) Date: 4 Jul 2005 11:10:55 -0700 Subject: Considering moving from Delphi to Python [Some questions] In-Reply-To: References: Message-ID: <1120500655.496872.10900@g47g2000cwa.googlegroups.com> The curve may take a while, but I'd definately recommend it. While you're at it, why not switch th front end to python too? From t-meyer at ihug.co.nz Sun Jul 31 21:16:14 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 1 Aug 2005 13:16:14 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: >> I agree. It's yuck. > > So don't use it. If it were that simple, I wouldn't have bothered bringing it up. I really do believe this is a case of "There should be one-- and preferably only one --obvious way to do it" (as well as "Explicit is better than implicit" and "Readability counts"). If it's there, people will use it, and that means that people will have to know about it to understand that it means join and not divide (as some will expect). They'll to choose whether to use it (be explicit) or not, where the "only one obvious way" would remove the need for the choice. One could argue that since "Although practicality beats purity" and "Although that way may not be obvious at first unless you're Dutch" also apply here, although the latter will require Guido's answer, of course. =Tony.Meyer From steve at REMOVETHIScyber.com.au Sat Jul 2 22:08:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 12:08:21 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> <86irzu5sp9.fsf@bhuda.mired.org> Message-ID: On Fri, 01 Jul 2005 13:42:10 -0400, Mike Meyer wrote: > "iK" writes: > >> Seems like he wants python programmers to solve their problems all in the >> same way. While that is great for corporate slaves it is terrible for the >> creative programmer. > > No, he wants Python to be Pythonic. TMTOWTDI is not Pythonic. Too Many T--- Only Way To Do It? There Might Tangle One Way To Do It? T--- M--- Two Obvious Ways To Do It? Nope, sorry, still not getting it. >> Python is quickly becoming the visual basic of the 21 century. If you want >> to have fun while getting some work done you need to look elsewhere. It's a >> shame... > > If you'd rather spend your time figuring out which of multiple ways to > do things is the best for the job at hand than producing code, there's > a language that makes TMTOWTDI a way of life. Figuring out which of multiple ways to do things is the best for the job at hand _is_ part of producing code. There will always be multiple ways to do the job. For starters, there is the choice, which language should I use? Top-Down or Bottom-Up design? Test-driven or not? For loop or list comprehension or generator? Procedural programming or object-oriented or a mixture of both? Singleton or Borg design pattern? Test your data first or deal with the exceptions when they happen? And so on. Only One Obvious Way makes a nice slogan, but it is easy to turn a flexible language like Python into a straight-jacket where there is Only One Way To Do It Regards Of Whether It Is The Best For The Job On Hand Or Not. Not such a short and concise slogan. Now that Python has list comps, should for loops be removed from the language? Why did Python bother introducing list comps when there is nothing they can do that a for loop can't? Functional programming using map etc does require a slightly different way of thinking about programming than does procedural programming, just as object-oriented needs a different way of thinking than spaghetti-coding using GOTOs. Different ways of thinking about programming should be encouraged, not discouraged. Even the much-maligned GOTO has its modern usage case: the Exception. If map/filter/reduce have to be removed from the built-ins, and I don't think they should, I'd prefer for them to be moved into a module rather than dropped altogether. Provided list comps are made as fast as map and filter, then at the cost of readability they can be replaced by list comps. But reduce can't be written as a list comp, only as a relatively complex for loop at a HUGE loss of readability -- and I've never used Lisp or Scheme in my life. I'm surely not the only one. -- Steven From coollakshman at gmail.com Wed Jul 20 10:43:28 2005 From: coollakshman at gmail.com (laksh) Date: 20 Jul 2005 07:43:28 -0700 Subject: Crafting IP packets with DNS queries .........newbie Message-ID: <1121870608.737606.75850@g14g2000cwa.googlegroups.com> hi all im looking for some code that can capture the IP packets from my system and craft them so that im able to put lots of DNS requests in them and send them to the server..... is it possible and will the DNS server takes it for legal DNS request packets?? and should i need to incorporate some code at the server end to decode the packets from my machine and encode the results from the DNS?? is all this possible ? first of all i want to know to craft some IP packets in python with loads of DNS queries in them.............. regards laksh From jason at tishler.net Wed Jul 27 15:16:27 2005 From: jason at tishler.net (Jason Tishler) Date: Wed, 27 Jul 2005 15:16:27 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: References: <20050725201132.GA3440@tishler.net> Message-ID: <20050727191626.GC2272@tishler.net> On Mon, Jul 25, 2005 at 03:02:45PM -0700, williams13 at mail.llnl.gov wrote: > Let me know when you have it solved. The problem has been fixed in Cygwin CVS: http://cygwin.com/ml/cygwin/2005-07/msg01257.html http://cygwin.com/ml/cygwin-cvs/2005-q3/msg00046.html > In the meantime, I have a workaround. Unfortunately, you will have to live with your workaround until Cygwin 1.5.19 is released. :,( Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From rkern at ucsd.edu Mon Jul 4 11:59:37 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 04 Jul 2005 08:59:37 -0700 Subject: missing cephes module In-Reply-To: <20050704150401.13007.qmail@web51107.mail.yahoo.com> References: <20050704150401.13007.qmail@web51107.mail.yahoo.com> Message-ID: Justin wrote: > Hi All: > > When I used py2exe to create executable file, "cephes" module missing > error occurred. > I have installed python 2.3 and scientific and numeric python. > Can anybody suggest me how to resolve the problem? Did you try what I suggested the last time you posted this question here? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From abstractwhiz at gmail.com Fri Jul 15 10:01:34 2005 From: abstractwhiz at gmail.com (Nadeem Mohsin) Date: 15 Jul 2005 07:01:34 -0700 Subject: IDLE in Jython Message-ID: <1121436094.769121.247470@z14g2000cwz.googlegroups.com> Me and a couple of friends have been thinking of doing something involving Python for our final year undergrad project. We're considering the first idea mentioned on this page: http://wiki.python.org/moin/JythonProjects. Unfortunately, their statement is a little terse, so I was hoping someone could give us a better idea of what they wanted. As far as I can see, they want us to build an integrated development environment for Jython along the lines of Python's traditional IDLE. Have I gotten confused, or this really the gist of the idea? If I've got it right, I'd appreciate some help on the following issues: 1. The broad outlines of what we'll have to do - how much Java and how much Python? 2. Any Jython specific issues I need to be aware of? How big a part will Jython play in development? 3. Some idea of the scope of this project and the time it might take a team of three to get it up and running. We're looking for something fairly challenging, but not so difficult that we won't be able to finish it off in time. We have about 7-8 months to pull it off, but we'll have a bunch of pretty hectic exams, assignments, entrance tests, grad school apps and stuff like that for a pretty significant proportion of that time. The 'powers that be' are officially giving us one day a week for it, though I'm pretty certain we can increase that, and we'll have about a month of free time at the end of this semester, and less hectic schedules in the next. I'm pretty certain it's possible, but better heads than mine have been wrong...If anyone has any ideas for other interesting projects involving Python, we'd like to hear them too. At present I'm the only Python coder in the group, but all three of us are pretty good with Java, and we have a fair amount of experience doing GUIs in Swing. Hope you guys can help us out. Nadeem. From steve at REMOVETHIScyber.com.au Tue Jul 12 10:39:14 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 00:39:14 +1000 Subject: append one file to another References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Message-ID: On Tue, 12 Jul 2005 06:47:50 -0700, b83503104 at yahoo.com wrote: > Hi, > > I want to append one (huge) file to another (huge) file. What do you call huge? What you or I think of as huge is not necessarily huge to your computer. > The current > way I'm doing it is to do something like: > > infile = open (infilename, 'r') > filestr = infile.read() > outfile = open(outfilename, 'a') > outfile.write(filestr) > > I wonder if there is a more efficient way doing this? Why? Is it not working? Is it too slow? Does it crash your computer? If you have any expectation that you code needs to run under Windows, or cross-platform, or contains binary data, you should open your files in binary mode: infile = open(infilename, 'rb') outfile = open(outfilename, 'ab') For raw copying, you should probably use binary mode even if they just contain text. Better safe than sorry... Then, if you are concerned that the files really are huge, that is, as big or bigger than the free memory your computer has, read and write them in chunks: data = infile.read(64) # 64 bytes at a time is a bit small... outfile.write(data) Instead of 64 bytes, you should pick a more realistic figure, which will depend on how much free memory your computer has. I suppose a megabyte is probably reasonable, but you will need to experiment to find out. Then when you are done, close the files: infile.close() outfile.close() This is not strictly necessary, but it is good practice. If your program dies, the files may not be closed properly and you could end up losing data. -- Steven. From rkern at ucsd.edu Sun Jul 31 03:51:50 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 00:51:50 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <7xy87nctxm.fsf@ruckus.brouhaha.com> References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > E.g., on > Linux, to use wxPython, you need wxWidgets, which needs GTK 1.5, which > has been obsolete for years, Nope. It's on GTK2 now. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at REMOVEMEcyber.com.au Sun Jul 31 23:05:25 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 01 Aug 2005 13:05:25 +1000 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: <42ED9175.1050006@REMOVEMEcyber.com.au> Rob Williscroft wrote: > Steven D'Aprano wrote in > news:pan.2005.07.31.14.30.04.607118 at REMOVETHIScyber.com.au in > comp.lang.python: > > >>Quoting Rob Williscroft: >> >> >>> > def translate( text ) >>> > import string all=string.maketrans('','') >>> > badcars=all.translate(all,string.letters+string.digits) >>> > TABLE = string.maketrans(badcars,'_'*len(badcars)) >>> > >>> > global translate >>> > def translate( text ): >>> > return text.translate(TABLE) >>> > >>> > return translate( text ) >> >>This is a difficult piece of code to understand and maintain. > > > Its 8 lines, of self contained code. It does everyting its supposed to do > and nothing its not. I didn't say it didn't work. I didn't say it was buggy. I didn't say it was too long, or had too many dependencies. Brevity is not always a blessing -- that's how we get obfuscated C and Perl programs that fit the most functionality into the fewest lines. In this _specific_ case, perhaps I was a little harsh. I've been badly burnt before with self-modifying code: once burnt, twice shy. I'm still uncomfortable with your code, but after spending more time following the program logic, I'm less uncomfortable with it than I was. However, see additional comments below. >>You have >>a function called translate, which in turn calls the string >>translate() method. That's okay. But then you have a global variable >>*also* called translate -- does that refer to the same function? > > This is how globals work in python, if you wish to (re)bind to a global > before reading it at function scope, you need to say so. Yes, I know that. Sorry, my rhetorical question gave you the wrong impression. I wasn't questioning how globals work, I was attempting (poorly) to show the mental hoops a new programmer unfamiliar with the code has to jump through to get it straight in his head. >>Is >>this self-modifying code? That is a dangerous, hard to debug, hard to >>understand technique that is too-clever-by-half. > > Maybe so, but if true, python as a language is too-clever-by-half. Most languages can create self-modifying code. That's not the question. The question is whether developers should write self-modifying code, not whether language designers should prohibit it. >>Then you create a local variable, also called translate, also a > > No, that isn't how globals work in python, there is no local called > translate above. Terminology conflict: I'm refering to the fact that your second translate function definition is written locally to the first top-level translate. My bad: I should have said nested rather than local. >>function, which simply calls the translate method of its argument. A >>waste of a function, when all you need to do is call the pre-existing >>translate method. If I have understood this code correctly, the >>*local* translate is bound to the *global* translate, which is the >>function being defined. > > Close but there isn't, and never was, a *local* translate function. Agreed: I meant nested. >>And lastly, just to complete the confusion, the original function >>itself appears to call itself -- presumably the rebound copy that >>points to what was the local copy -- recursively, with the same >>argument. > > > def f() > global g > def g(): > return "something" > return g() > > f() is a function that (re)creates a global function g() and calls it. > Is it just that translate() rebinds itself that is too much, or do you > object to f() too ? I do object to f() but only because its useless. Yes, unless there is a very good reason for rebinding g dynamically, I would be very cautious of using that technique. It means that g changes its behaviour, not because of the input it gets, but because of when it is called. g does a certain thing, then in some obscure corner of your program, hardly noticed, some function or method calls f and suddenly g acts completely differently. In principle, you the developer may not even be able to predict when this change of behaviour will happen. It comes with the considerable risk that your developers are desperately trying to read and understand g as it first was, and not understanding why it is acting differently. It is a technique that begs to be misused: if you think you can write confusing, baroque code with GOTO, you can do worse with dynamically rebinding functions and self-modifying code. Just as there are good uses for GOTO, I am happy to admit that there are good cases for self-modifying code. But not for something as trivial as creating an alias for a string method. All meta-programming should be used with care, and only when the more, shall we say traditional, alternatives have serious deficiencies. At the very least it should be documented in detail. >>That's a nifty piece of code for showing how clever you are at writing >>mildly obfuscated code. But for commercial use, where the code has to >>be maintained and debugged, it is a terrible idea. > > 8 lines of self contained code are a terrible idea !, you have IMO a > very strange idea of what is or isn't maintainable. No. I work for an IT company, and I know the sort of code we are called on to maintain, and the sort of developers that are available. It isn't that eight lines are too many, but that the behaviour of the function changes. The fact that it is self-modifying just makes it even less intuitive. Our human intuition of behaviour is that things act a certain way, and while the behaviour should change depending on the input, it shouldn't change radically from one time to the next. For example, we understand that a ball thrown at the ground will bounce at a different angle depending on the angle it was tossed at, but we would be shocked to see it bounce the first time, then stick to the ground the second, then start bouncing again the tenth time we toss it. We intuitively understand changes in state, eg we have little problem understanding rebinding x from a float to a string, because that's like changing a glass that holds water to broken shards that don't (except better: we can reverse the transformation of x). But we have little intuitive about glasses that hold water, then don't hold water -- that's why we get worried and confused when people suddenly start acting out of character: behaviour changes, without any visible change of state. Any programming technique that acts against human intuition about how objects "should" behave will cause many developers confusion and difficulty, and anything which causes developers confusion and difficulty will generally lead to buggy code and always to higher costs. (We have to pay our developers for their time when they are confused, not just when they are coding in the zone.) That's why meta-programming and self-modifying code should be used with care, and documented well. You might understand it, but the next guy who comes along to maintain your code is going to be faced with the code equivalent of somebody acting out of character. > Is using generators and decorators a terrible idea too ? Generators don't mysteriously change behaviour, except in the limited sense that they halt when they run out of data, and that is perfectly intuitive. Halting when you run out of data is so intuitive that one common bug in code is to forget to program in a halting condition, especially in recursive functions but even in while loops -- we just expect that it will stop when it is done. The principle of how generators work takes a little understanding, but once you understand the principle, understanding any specific generator is no harder than understanding the non-generator equivalent code, and probably much easier. Decorators, well, I've never used them, and I still don't understand why people seem so excited about them, so I don't have an opinion. -- Steven. From mcherm at gmail.com Tue Jul 5 08:03:32 2005 From: mcherm at gmail.com (mcherm at gmail.com) Date: 5 Jul 2005 05:03:32 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> Message-ID: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Steven D'Aprano writes: > Lambda is no more an obscure name than "function", "decorator", "closure", > "class", or "module". The first time you come across it, you don't know > what it means. Then you learn what it means, and then you know. I believe you've made two errors here. First of all, "lambda" is part of the Python language, while "function", "decorator", "closure", and "module" are not. The fact that some words which are NOT part of the Python language are obscure has no bearing whatsoever on "lambda". The obnubilation created by this comparison is an obscure word also, but, it isn't relevent to the Python language. The second error is that I believe most english speakers COULD provide a definition for the fairly common words "function", "class", and "decorator". The exact meaning of "class" might not be what they expect at first, but exposure to any object oriented language would make the concept quickly familiar. But "lambda" has a very clear meaning... it's a letter of the greek alphabet. The connection between that letter and anonymous functions is tenuous at best, and fails the test of making Python read like "executable pseudocode". -- Michael Chermside From rkern at ucsd.edu Tue Jul 12 05:17:34 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 02:17:34 -0700 Subject: Trying to come to grips with static methods In-Reply-To: References: Message-ID: Cyril Bazin wrote: > (sorry, my fingers send the mail by there own ;-) > > Im my opinion, class method are used to store some functionalities > (function) related to a class in the scope of the class. > > For example, I often use static methods like that: > > class Point: > def __init__(self, x, y): > self.x, self.y = x, y > > def fromXML(xmlText): > x, y = functionToParseXMLUsingMinidomForExample(xmlText) > return Point(x, y) > fromXML = staticmethod(fromXML) > > Here, it is used to define some kind of second constructor... > > Note that class decorator can simplify the notation, but break the > compatility with older Python... Huh? classmethod was introduced with staticmethod, and in fact, this use case is exactly what classmethods are for, not staticmethods. In [2]: class Point(object): # <-- note inheritance from object ...: def __init__(self, x, y): ...: self.x, self.y = x, y ...: def fromXML(cls, xmlText): ...: x, y = parseXML(xmlText) ...: return cls(x, y) ...: fromXML = classmethod(fromXML) ...: In [3]: class NewPoint(Point): ...: pass ...: In [4]: def parseXML(xmlText): ...: return 1, 4 ...: In [5]: p = NewPoint.fromXML('') In [6]: isinstance(p, NewPoint) Out[6]: True -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From roy at panix.com Sat Jul 9 15:06:07 2005 From: roy at panix.com (Roy Smith) Date: Sat, 09 Jul 2005 15:06:07 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Steve Juranich wrote: > Without fail, when I start talking with some of the "old-timers" > (people who have written code in ADA or Fortran), I hear the same > arguments that using "if" is "better" than using "try". Well, you've now got a failure. I used to write Fortran on punch cards, so I guess that makes me an "old-timer", and I don't agree with that argument. > I think that the argument goes something like, "When you set up a 'try' > block, you have to set up a lot of extra machinery than is necessary > just executing a simple conditional." That sounds like a very C++ kind of attitude, where efficiency is prized above all else, and exception handling is relatively heavy-weight compared to a simple conditional. > What do I mean by "cheaper"? I'm basically talking about the number > of instructions that are necessary to set up and execute a try block > as opposed to an if block. Don't worry about crap like that until the whole application is done and it's not running fast enough, and you've exhausted all efforts to identify algorithmic improvements that could be made, and careful performance measurements have shown that the use of try blocks is the problem. Exceptions are better than returning an error code for several reasons: 1) They cannot be silently ignored by accident. If you don't catch an exception, it bubbles up until something does catch it, or nothing does and your program dies with a stack trace. You can ignore them if you want, but you have to explicitly write some code to do that. 2) It separates the normal flow of control from the error processing. In many cases, this makes it easier to understand the program logic. 3) In some cases, they can lead to faster code. A classic example is counting occurances of items using a dictionary: count = {} for key in whatever: try: count[key] += 1 except KeyError: count[key] = 1 compared to count = {} for key in whatever: if count.hasKey(key): count[key] += 1 else: count[key] = 1 if most keys are going to already be in the dictionary, handling the occasional exception will be faster than calling hasKey() for every one. From steven.bethard at gmail.com Thu Jul 28 11:25:33 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 28 Jul 2005 09:25:33 -0600 Subject: functions without parentheses In-Reply-To: References: Message-ID: <97udndQn87N3ZXXfRVn-vQ@comcast.com> Jerry He wrote: > def examine(str): > ..... > ..... > > Is there some way to define it so that I can call it > like > > examine "string" > instead of examine("string")? What do you want to happen when someone types: examine ??? Or better yet, what if you do something like: map(examine, list_of_strs) ??? Should examine be called with no arguments? Or should it be passed as a function object to map? STeVe From tzot at sil-tec.gr Sat Jul 2 09:26:02 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 16:26:02 +0300 Subject: Python choice of database References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: <5f5dc1dhhhn8dndr3nrdkq6pjnldg437rk@4ax.com> On Tue, 21 Jun 2005 17:00:17 +0300, rumours say that Konstantin Veretennicov might have written: >On 6/21/05, Charles Krug wrote: >> >> Related question: >> >> What if I need to create/modify MS-Access or SQL Server dbs? > >You could use ADO + adodbapi for both. >http://adodbapi.sourceforge.net/ Or pywin32/ctypes and COM (btw, I prefer DAO to ADO, but that is a personal choice). -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From darkcowherd at gmail.com Wed Jul 20 00:15:06 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Wed, 20 Jul 2005 09:45:06 +0530 Subject: email format in python In-Reply-To: <20050718102120.64241.qmail@web42004.mail.yahoo.com> References: <20050718102120.64241.qmail@web42004.mail.yahoo.com> Message-ID: <5f4d3cb5050719211573877e0f@mail.gmail.com> This seems to give reasonable results. import re pattern = r'\b[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z]{2,4}\b' pattobj = re.compile(pattern) ps = pattobj.search if ps(stringtocheck): But as lots of people have already told you on this list. This should only be used to give a warning and not prevent the use of that particular address. DarkCowherd From waldemar.osuch at gmail.com Wed Jul 20 17:50:37 2005 From: waldemar.osuch at gmail.com (waldemar.osuch at gmail.com) Date: 20 Jul 2005 14:50:37 -0700 Subject: mod_python Apache/2.0.52 (Win32) Python 2.4 References: <38d6a9b7.0507201214.12c048ac@posting.google.com> Message-ID: <1121896237.234560.108850@g43g2000cwa.googlegroups.com> Dieter Raber wrote: > Hi there, > > I am wondering if there is a mod_python for the above configuration. I > downloaded mod_python-3.1.3.win32-py2.3.exe, which of course as the > name implies keeps on asking me for a python 2.3 installation. I > imagine one could cheat a little bit with a fake registry entry that > says it was about python 2.3 but that points to python 2.4. Then again > I don't know what entry mod_python's installer is looking for. > > Thanks for your help > > Dieter Development version (3.2) of mod_python is here: http://www.lehuen.com/nicolas/download/mod_python/ It works for me Waldemar From harold.fellermann at upf.edu Tue Jul 12 12:17:19 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 12 Jul 2005 18:17:19 +0200 Subject: automatic form filling In-Reply-To: <20050712154638.80392.qmail@web60323.mail.yahoo.com> References: <20050712154638.80392.qmail@web60323.mail.yahoo.com> Message-ID: <138d8649afbce751834a64e48397064b@upf.edu> > I would like to know how I could automatically fill a > (search) form on a web page and download the resulting > html page. More precisely I would like to make a > program that would automatically fill the "Buscador > lista 40" (in spanish, sorry) form in the following > webpage: > http://www.los40.com/actualidad/listas/lista40.html > and download the results for several dates > (dia/mes/a?o = day/month/year). > I am not sure this is the right place to ask, but I > would be very grateful if anybody can help or redirect > me to another mailing list... The relevant part of the sites source code is the following:
You can do things like: t.html[ t.head[ t.title["Foobar"] ], t.body[ t.p["This is some content"] ] ] This is not harder than normal xhtml tags to follow. plus you don't have to remember what tag you are closing :) -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.4 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From steve at REMOVETHIScyber.com.au Sat Jul 23 23:25:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 13:25:23 +1000 Subject: Getting a dictionary from an object References: <86br4tpg2b.fsf@bhuda.mired.org> Message-ID: On Sat, 23 Jul 2005 13:50:36 -0400, Mike Meyer wrote: >> I don't think this is particularly useful behaviour. How do you use it? > > def __str__(self): > return self._format % self That doesn't work. It calls self.__str__ recursively until Python halts the process. >>> class Thing(dict): ... _format = "Thing %s is good." ... def __str__(self): ... return self._format % self ... >>> X = Thing() >>> X # calls __repr__ so is safe {} >>> str(X) # not safe File "", line 4, in __str__ File "", line 4, in __str__ ... File "", line 4, in __str__ File "", line 4, in __str__ RuntimeError: maximum recursion depth exceeded -- Steven. From lsolis at mu.intecsa-inarsa.es Thu Jul 21 06:17:42 2005 From: lsolis at mu.intecsa-inarsa.es (luis) Date: Thu, 21 Jul 2005 10:17:42 GMT Subject: is a file open ? In-Reply-To: <42de3b80$1@news.eftel.com> References: <42de3b80$1@news.eftel.com> Message-ID: John Machin wrote: > Daniel Dittmar wrote: > >> luis wrote: >> >>> for root, dirs, files in os.walk(path): >>> for file in files: >>> # ? is opened ? >> >> >> >> On Linux and some other Unixes, you can probably read the /proc >> filesystem. >> >> On Windows, you'll probably get the quickest result by running >> handle.exe (http://www.sysinternals.com/Utilities/Handle.html). >> >> Either way, the information you'll get is restricted by your permissions. >> >> Either information will get stale really fast, so it's not suitable if >> your task is something like 'can I backup this directory or is someone >> writing to a file?' > > > If that's what the OP had in mind, the question might have been better > phrased as "given the path to a file, how can I tell if it is currently > opened by another process/thread", and better directed to OS-specifc > newsgroup(s). > there is a specific python function ? From xah at xahlee.org Mon Jul 18 18:01:19 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jul 2005 15:01:19 -0700 Subject: Xah's edu corner: on Microsoft hatred Message-ID: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Dear Joe, It is well known that you are an avid hater of Microsoft, from their technologies to their leader to their business practices. I have now and then seen your impassioned expression of this hatred, scattered among your newsgroup posts. Personally, i have an inherent distrust toward big organizations. This applies to Microsoft. Since perhaps 1995, MS has become more and more large, and as well becoming a hate target especially among unix communities. Of MS hatred there are two aspects: those who think MS products are utterly incompetent, and those who think MS business practices are the most evil. I have always been an Apple Macintosh user. I have used a few MS products such as MS Word word processor on the Mac since about 1990, and Mac version of MS Internet Explorer web browser and Outlook Express email program when they became available around 1997 or so free of charge. My experiences have been that MS software on the Mac are pretty good, if not usually better than competitors. In fact, before the MS-hatred era of late 1990s, i recall that i was found of MS Word and would say it was the software that never crashed, with the richest (useful) features. I have not used MS Windows much until 1999, so i cannot judge from my own experience whether people's complains about MS's product's poor quality. By the time i used MS Windows daily in 1999, it was MS Windows NT, and i have moved into industrial programing field now called IT. At the time Apple's OS is around version 8. Although Windows is not as aesthetic or intuitive as my beloved Mac OS, but on the whole i think Windows NT beats the shit out of Mac OS by far. Mac OS crashed daily if a info-collecting tech-head like myself are careful, hourly if not, and among quite a few of other reasons. As the MS hatred is rolling like a snowball, i started to pay attention. On one hand, i never cared for Microsoft. Their sole impression on me before 1998 was that MS Word is good software, and i hate Windows just because i'm a dedicated Apple fan just because Apple had made many revolutionary innovations in both software and hardware and MS was Apple's market enemy. Although i think the unix crowd are tech morons of the world, but when it comes to political issues, i'm inclined to side with their freedom loving and paranoia propensities. I'm ashamed to admit, that i started to visit unix moron's mecca the slashdot.org around 1999, and have read quite a lot of their MS hatred verbiage, from drivel of sopho-morons to Eric Raymond's OpenSource Jihad to Richard Stallman's Free Software Foundation. Perhaps due to their propaganda, at times i shudder at the mind-numbing MS juggernaut, and have felt ready to join their cause and kill Microsoft. Since 1999, my behavior have in fact been mildly anti-Microsoft. I would, for example, mention FreeSoftware or OpenSource in meetings, avoid using MS products myself and convert all my MS Word files i have on my Mac to some standard format such as plain text, and also use the Free Software Foundation's GNU Public License for my own software dabblings. Still, i was never a MS hater. Some people i know are MS haters, but i'm just a mild FreeSoftware proponent and was never sure i should be a MS hater. I could have investigated the issue, by studying the various lawsuits, check out MS history, exam and verify MS hater's essays, but life is short and i have other interests so i did not undertook such activities and never decided whether MS should be hated. I just disliked big organizations, and thus Microsoft. Since 1999 i entered the field of industrial programing known as Info Technology. In particular, i'm a web application programer on the unix platform. My daily office machines are PC running Windows (NT and followings) and remote unix servers. I find NT quite usable and almost never crashed at least as a desktop machine. I don't know much about any MS-bred technologies, but i knew quite a lot about unix. My attitude towards unixes is that it is the MOST incompetent thing in the computing world. I am an outright unix HATER. I have becoming increasingly nosy about unix MS-hater's claims technology-wise as most readily found from slashdot.org, from User Interface design to protocol embrace & extend to innovation to power & flexibility to security considerations. In the past few years, i started to pay mild attention to the question of wether from a technical or technological point of view MS should be hated. Even i don't know much Microsoft technologies except as a daily Windows user, but in my personal judgment system among all things considered, i think that if MS has done damage to society then unix has done hundred times more. I believe that Microsoft Windows technologies is on the whole FAR superior to unixes both as a PC and server, all things considered. (this includes the fact that unix is more stable then Windows NT, today.) Comparing to the other major desktop Operating System the Mac OS (where unixes are so incompetent it is out of the question), with intact conscience i think that MS's OS since about 1997 has left my beloved Mac OS in dust. If Windows 98 is poor quality (i know it is), then Mac OS of that year is neighborhood crap. (i plan to have book-length material on the reasons, but here for now i can only briefly state my beliefs in a conclusive manner.) The above is my beliefs on product or technological quality aspect of Microsoft-hatred. I have much interest in technology than politics or business, thus my know-how of social oriented issues pales in comparison. I have never examined the accusations of MS's evil business practices, other than news hearsay. To this day, i know little of what is true or false regarding MS's business practices. Although i have never undertook an interest of a topic, but as a philosopher i have gathered opinions regarding a topic from great variety of sources and experiences, and can form a personal judgment. And from my observations of computing industry, and my little knowledge of economics, all things and experiences lead me to believe that there is little to no reason to hate MS for their business practice either. Sometimes last year i read Thomas Sowell's Basic Economics. Although he never talked about software in the book, but that book made a major impression on my views of MS-hating issues. Around 1994 i read the book _Steve Jobs and the NeXT big thing_ by historian Randall E. Stross, and i was highly positively impressed by him. I have then learned that he also wrote a book in 1997 on MS: _The Microsoft Way : The Real Story of How the Company Outsmarts Its Competition_. Although i have not read the book, but from amazon.com reviews it indicated that he simply think that the success of MS is due to being smart. There are various lawsuits against the MS giant in the last few years, from Sun Microsystem's Java lawsuit, to United States vs Microsoft anti-trust lawsuit, to last month's AOL suit for Netscape browser. As you know, Sun is a unix vendor, with its own greedy grip on Java. I frankly don't buy any bullshit from the Sun Micro commercial turd. MS may be devious with their own ?standard?-breaking java, but no more hanky-panky than Sun's ?Universal? Java sham in the first fucking place. Any commercial organizations do devious things for their own interest. As to United State's claim that MS screwed innovation by bundling browser, that itself is a fantastic fucking idea. Integrating browser into OS is an innovation, and amid so great many claims that MS does not innovate, i can think of quite a few cases where MS has in fact been innovative or responsible for technological lead from my personal computing experiences. (Microsoft Word accounts for great many innovations in word processing along.) And, who needs the government to meddle with industry? (as i have learned in Thomas's Sowell's book, anti-trust cases are invariably all the same.) Lastly is the AOL's bandwagon-hopping lawsuit in the name of fantastically incompetent Netscape the-loser-browser. Fuck America On-Line. I'm often ignorant when it comes to economics practicality, such as stock market or personal finance. Since about 1999, i started to become a stock holder, thus started to learn a bit of its nature. On this process, one thing came to my attention is that Microsoft is a public owned company. Public owned companies are directed by the people who own its stock, and any joe can purchase it. That means, if Microsoft is an evil empire, then the public shares a great blame. From this aspect, i don't see any sense of Microsoft-hatred either. Blame the public, such as your boss and neighbors and wife and friends and community, or, blame the fantastic greed-oriented system called capitalism that made USA so prosperous far beyond the moral-oriented communist/socialist nations or sovereignly ruled kingdoms & queendoms. this post is archived at: http://xahlee.org/UnixResource_dir/writ/mshatred155.html ? copyright 2003 by Xah Lee. Xah xah at xahlee.org ? http://xahlee.org/ From hancock at anansispaceworks.com Mon Jul 4 06:13:54 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 4 Jul 2005 05:13:54 -0500 Subject: How do you program in Python? In-Reply-To: <3iqif8Fmj34kU1@individual.net> References: <3iqif8Fmj34kU1@individual.net> Message-ID: <200507040513.54887.hancock@anansispaceworks.com> On Sunday 03 July 2005 11:35 am, anthonyberet wrote: > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of > code, to see the effects of tweaks, without having to save it each time, > or re-typing it over and over (I haven't even worked out how to cut and > paste effectively in the IDLE environment). How old style? Basic has changed a lot over the years. ;-) But seriously, I think I know what you mean. I'm going to suggest that you try going very "low tech" with this and don't use an IDE at all. I'm sure you have some form of window environment (X, Windows, or Mac) and can open a terminal and an editor of your choice on screen (even if it's "Notepad"). Start the Python interpreter up in the terminal by just typing "python". In the interpreter you can try simple one or two liners. You can even define a short function and try it out. But you'll get annoyed by having to "up-arrow" and retrieve lines one- by-one to repeat the function after you've made a mistake, so that'll get old for anything more than 5 lines long. So, use your editor. Type up a short program that you want to test in the editor, then copy and paste it into the Python interpreter. This way, when you (inevitably) find mistakes, you can just tweak them in the editor and then paste them again. You can, of course, paste statements from the interpreter back into your editor, but you'll have to avoid the ">>>" prompts (or delete them), so it's usually better to write in the editor and paste into the interpreter. And when you're done, you can just save the result to file so you can get it back later. My point is, you don't have to use a fancy all-in-one application to do the job, nor must you run your programs from within your editor. It's not so hard to just use tools you already understand. Personally, I did things like this for years, and still do from time to time. I've hardly ever used an IDE, and I'm still not totally convinced they are worth the effort involved in learning them. I used to hop from computer to computer a lot, and if I tried to learn my way around separate IDEs on Macs, Windows, DOS, Solaris, and Debian Linux, I would've spent a lot of time twiddling with the tools instead of just writing code. Lately, I've settled into using Vim, which is nice editor (especially if you once wrote a several thousand line program in Vi with nothing but a fold-up quick reference for a manual ;-) ). There may well be friendlier ones, but I know this one fairly well, and it has a pretty large community of developers who are constantly tweaking it to make it a better editor for programming. I only just recently started seriously customizing it to work well with Python, though. You can always go shopping for an IDE to buy into heavily *after* you've learned the language. Meanwhile, don't let trifles get in the way -- just use your window system as your IDE. That way, you can pick the editor to suit you. And the Python interpreter is great, it will give you no trouble and quick answers. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From dalke at dalkescientific.com Fri Jul 29 17:22:18 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 29 Jul 2005 21:22:18 GMT Subject: can list comprehensions replace map? References: Message-ID: Peter Otten wrote: > Seems my description didn't convince you. So here's an example: Got it. In my test case the longest element happened to be the last one, which is why it didn't catch the problem. Thanks. Andrew dalke at dalkescientific.com From tjreedy at udel.edu Sat Jul 23 02:02:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 23 Jul 2005 02:02:10 -0400 Subject: return None References: <3kcpbbFtjttlU1@individual.net> Message-ID: "Ximo" wrote in message news:3kcpbbFtjttlU1 at individual.net... > Can I do a function which don't return anything? No, if you mean like subroutines. > The question is that, if I do a function that have a return or without > return, it returns always "None", but i want that it doesnt return me > nothing Why? An answer to that would help you maybe get better answers here. Terry J. Reedy From markus_GETRIDOFALLCAPSwankus at hotmail.com Tue Jul 12 19:09:34 2005 From: markus_GETRIDOFALLCAPSwankus at hotmail.com (Markus Wankus) Date: Tue, 12 Jul 2005 19:09:34 -0400 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: <42d3e666_1@news2.prserv.net> References: <42d3e666_1@news2.prserv.net> Message-ID: Stephen Toledo-Brown wrote: > Tony Meyer wrote: > >>> Everyone complaining about Eclipse in this thread needs to go try >>> 3.1. The interface is much much much more responsive. >> >> >> >> The problem with Eclipse, IMO, is Java. I've tried 3.1 on a WinXP >> machine >> and, like just about any Java program, it's incredibly slow and a real >> pain >> to use. On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and >> smoothly and is reasonably nice to use. I'd happily recommend that Mac >> users try Eclipse, but never a Windows (Python) programmer. > > > I've not tried Mac, but under both Windows and Linux on x86, I find > Eclipse (3.0) is slow with less than 1.25 GB of RAM, reasonably fast > with 1.5GB or more. Processor speed and disk speed don't seem to be > anywhere near as important. I guess we all have different views on "slow". I have been using it to develop a full IDE in Eclipse for over 2 years (since 2.1), and I can't understand where you guys are coming from. I self-host (run a development Eclipse SDK, plus a Runtime - that's 2 Eclipse's running...sometimes 3) all day every day and it does admittedly get "slow", but only down when I am doing serious debugging (Eclipse debugging the internals of Eclipse). I only have 512MB RAM, and a wimpy 1.3 GHz Athlon on Windows. And BTW - if you used Eclipse seriously, you would know that Mac and Linux are inherently slower than Windows due to the SWT GUI library lagging performance-wise on those platforms (especially GTK on Linux), so I have no idea how you can resonably say that you would *never* recommend a Windows programmer to try Eclipse. Those types of performance claims are simply not true (beyond a 10 minute evaluation), and it's just plain silly to say Eclipse is not usable on Windows. My opinion - If you aren't willing to try something new, or have an aversion to it in the first place, nothing we can say will change your mind. As for me - I'll continue to enjoy the benefits of Eclipse's tools - especially with PyDev coming along the way it is. The ultimate would be for something like Jython or JPype to come to fruition so Eclipse plugins could be written in Python. Now *that* would be something. Actually, the *ultimate* would be to implement the equivalent of Eclipse in Python, but that is a pipe dream... ;o) Markus. From skip at pobox.com Wed Jul 13 11:28:46 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 13 Jul 2005 10:28:46 -0500 Subject: automatically assigning names to indexes In-Reply-To: <1121194393.083830.256870@o13g2000cwo.googlegroups.com> References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> <1121169211.877343.200570@z14g2000cwz.googlegroups.com> <1121177247.196389.11080@z14g2000cwz.googlegroups.com> <1121194393.083830.256870@o13g2000cwo.googlegroups.com> Message-ID: <17109.13102.875287.352383@montanaro.dyndns.org> George> What 'magic' ? The (x,y,z) notation is used only for 3D George> vectors. (x,y) is also common for 2D and perhaps (t,x,y,z) for George> 4D, with t for time. Don't forget (w,x,y,z) for quaternions... Skip From simon.brunning at gmail.com Wed Jul 20 09:19:50 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 20 Jul 2005 14:19:50 +0100 Subject: is this pythonic? In-Reply-To: <42DE4F67.7030300@mage.hu> References: <42DE4F67.7030300@mage.hu> Message-ID: <8c7f10c605072006192d8ae378@mail.gmail.com> On 7/20/05, Mage wrote: > Or is there better way? > > for (i, url) in [(i,links[i]) for i in range(len(links))]: for i, url in enumerate(links): -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rkern at ucsd.edu Tue Jul 19 21:01:56 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 19 Jul 2005 18:01:56 -0700 Subject: What does "::" mean? In-Reply-To: <311b5ce1050719175054e268b6@mail.gmail.com> References: <311b5ce1050719175054e268b6@mail.gmail.com> Message-ID: could ildg wrote: > I know that ":" can do slice works. > But I saw "::" today and it puzzled me much, > I can't find it in the python doc, > so I raise this question here. > The code is as below: > ---------------------------------------------------------- > Jython 2.2a1 on java1.5.0_03 (JIT: null) > Type "copyright", "credits" or "license" for more information. > >>>>live='live';print live > > live > >>>>live=live[::-1];print live > > evil > > -------------------------------------------------------- > "[::-1]" can reverse a string magicly, how did it do it? The full form would be live[len(live)-1:-1:-1] much like range(len(live)-1, -1, -1). [start:stop:step] step can be negative. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steven.bethard at gmail.com Thu Jul 28 11:06:18 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 28 Jul 2005 09:06:18 -0600 Subject: Create a variable "on the fly" In-Reply-To: <42e89182$0$13699$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> <42e7c390$0$446$626a14ce@news.free.fr> <42e89182$0$13699$ed9e5944@reading.news.pipex.net> Message-ID: Paul D.Smith wrote: > 2. A simple Python config which searches for all shell environment variables > named "MY_..." and instantiates then as Python variables. my_vars = dict((k, v) for k, v in os.environ.iteritems() if k.startswith('MY_')) globals().update(my_vars) If you ever refactor the code, I'd suggest writing a single configuration file instead of setting environment variables, and reading that configuration file in each script that needs it. Generally I've found that relying on environment variables being set is hard to maintain and a real pain when you have to move to a new system. STeVe From phillip.watts at anvilcom.com Mon Jul 4 18:24:56 2005 From: phillip.watts at anvilcom.com (phil) Date: Mon, 04 Jul 2005 17:24:56 -0500 Subject: PROBLEM?? deepcopy Message-ID: <42C9B738.7010604@anvilcom.com> I wrote the following to prove to myself that deepcopy would copy an entire dictionary which contains an instance of a class to one key of another dictionary. Note that after copying adict to ndict['x'] I delete adict. Then ndict['x'] contains a good copy of adict. works great. class aclass: def __init__(s): s.anint = 123 aninstance = aclass() adict = {} adict['y'] = aninstance ndict = {} ndict['x'] = copy.deepcopy(adict) del adict print ndict print ndict['x']['y'] print ndict['x']['y'].anint # this line prints 123 print Then in the following code when I try to deepcopy s.glob.objs I get following error Note that s.glob.objs is a dictionary and I am attempting to copy to a key of s.save, another dict, just like above. ?????????? s.glob.objs may have several keys, the data for each will be instance of classes like line and circle. Those instances will have tkinter canvas objects in them. class Graph: def __init__(s): class DummyClass: pass s.glob = DummyClass() s.glob.objs = {} .. # here add some instance of objects like .. # circles and lines to s.glob.objs # instantiate dialog s.DI = dialog(s.glob) class dialog: def __init__(s,glob): s.glob = glob s.save = {} def proc(s): cur = someint s.save[cur] = copy.deepcopy(s.glob.objs) Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "/home/phil/geo/g.py", line 303, in enter else:s.proc() File "/home/phil/geo/g.py", line 245, in proc s.save[cur][k] = copy.deepcopy(s.glob.objs[k][0]) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst state = deepcopy(state, memo) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst state = deepcopy(state, memo) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/local/lib/python2.3/copy.py", line 206, in deepcopy y = _reconstruct(x, rv, 1, memo) File "/usr/local/lib/python2.3/copy.py", line 338, in _reconstruct y = callable(*args) File "/usr/local/lib/python2.3/copy_reg.py", line 92, in __newobj__ return cls.__new__(cls, *args) TypeError: function() takes at least 2 arguments (0 given) From john at hazen.net Tue Jul 19 19:33:22 2005 From: john at hazen.net (John Hazen) Date: Tue, 19 Jul 2005 16:33:22 -0700 Subject: socket programming In-Reply-To: <20050719184205.GA24773@mail.smule.com> References: <20050719184205.GA24773@mail.smule.com> Message-ID: <20050719233322.GA30197@gate2.hazen.net> * Helge Aksdal [2005-07-19 11:23]: > if i then change to a console window, and telnet to this server it > sends me to another one. That's probably why my program dies, how > can i get my code to handle this? > > Trying xxx.xxx.xxx.xxx > telnet: connect to address xxx.xxx.xxx.xxx: Connection refused > Trying xxx.xxx.xxx.xxx > Connected to xxxxxx.xxxxx. > Escape character is '^]'. I don't think the server is "sending you to another one". I think perhaps DNS returns two IP addresses for the name, and after the first one fails, your telnet client tries the second? I'm just guessing, since you didn't include what command you ran to do the telnet. As Grant mentioned, the telnet protocol doesn't do redirects. -John From http Sun Jul 31 03:14:01 2005 From: http (Paul Rubin) Date: 31 Jul 2005 00:14:01 -0700 Subject: shelve: writing out updates?! References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: <7x7jf7e9c6.fsf@ruckus.brouhaha.com> zen19725 at zen.co.uk (phil hunt) writes: > What is ACID? Basically it means full-blown a transactional database that handles concurrent updates correctly. See: http://en.wikipedia.org/wiki/ACID > Wierd. I'd expect something like an s.flush() function. Thanks to Robert Kern for pointing out that the answer is s.sync(). From peter at engcorp.com Sun Jul 24 13:36:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Jul 2005 13:36:31 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3khg7cFuh446U1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> <3khg7cFuh446U1@individual.net> Message-ID: <-tWdnRUeMaY5TH7fRVn-sw@powergate.ca> Reinhold Birkenfeld wrote: > Peter Hansen wrote: >> if mypath.splitpath()[0] == 'c:/temp': vs. >> if mypath.splitpath()[0] == Path('c:/temp'): > > But you must admit that that't the cleaner solution. "Cleaner"? Not at all. I'd say it's the more expressive solution, perhaps, but I definitely wouldn't choose the word "cleaner" for something which, to me, adds fairly unnecessary text. But it's clearly a subjective matter, and as the one of us not involved in doing the real work here, I'll bow to your judgement on the matter. ;-) -Peter From me at privacy.net Sun Jul 17 18:03:42 2005 From: me at privacy.net (Admin) Date: Sun, 17 Jul 2005 19:03:42 -0300 Subject: What is your favorite Python web framework? Message-ID: I am doing some research for a Python framework to build web applications. I have discarted Zope because from what I've read, the learning curve is too steep, and it takes more time to build applications in general with Zope. I have kept the following: - PyWork - http://pywork.sourceforge.net (Not sure if it's mature) - Django - http://www.djangoproject.com (Looks interesting) - CherryPy - http://www.cherrypy.org (Unsure) I have also found a more comprehensive list here: http://wiki.python.org/moin/WebProgramming But I'd like to know your opinion on what you think is best. The Python framework I'll use will be to build an e-commerce application looking like Amazon.com I favor speed of development, intensive OO development, performance under heavy load, short learning curve, good documentation and community. -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From python at rcn.com Wed Jul 27 20:00:03 2005 From: python at rcn.com (Raymond Hettinger) Date: 27 Jul 2005 17:00:03 -0700 Subject: can list comprehensions replace map? References: Message-ID: <1122508803.920261.303730@g49g2000cwa.googlegroups.com> [David Isaac] > > I have been generally open to the proposal that list comprehensions > > should replace 'map', but I ran into a need for something like > > map(None,x,y) > > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > > info from x. How do I do this as a list comprehension? (Or, > > more generally, what is the best way to do this without 'map'?) [Paolino] > Probably zip should change behaviour,and cover that case or at least > have another like 'tzip' in the __builtins__ .Dunno, I always thought > zip should not cut to the shortest list. Heck no! For the core use case of lockstep iteration, it is almost always a mistake to continue iterating beyond the length of the shortest input sequence. Even for map(), the use cases are thin. How many functions do something meaningful when one or more of their inputs changes type and becomes a stream of Nones. Consider for example, map(pow, seqa, seqb) -- what good can come of one sequence or the other suddenly switching to a None mode? As Andrew pointed out, if you really need that behavior, it can be provided explicity. See the padNone() recipe in the itertools documentation for an easy one-liner. IMO, reliance on map's None fill-in feature should be taken as a code smell indicating a design flaw (not always, but usually). There is a reason that feature is missing from map() implementations in some other languages. In contrast, the existing behavior of zip() is quite useful. It allows some of the input sequences to be infinite: zip(itertools.count(1), open('myfile.txt')) Raymond From fred at adventistcare.org Wed Jul 6 15:30:33 2005 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 6 Jul 2005 15:30:33 -0400 Subject: How do you program in Python? Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317541@sunbelt.org> I'm old school and have been very happy with emacs (on windows) and the python extensions. I just edit my file and hit control-C twice and it runs. I'm also using eclipse with PyDev and it's ok, but sluggish. -----Original Message----- From: anthonyberet [mailto:nospam at me.invalid] Sent: Sunday, July 03, 2005 12:35 PM To: python-list at python.org Subject: How do you program in Python? My question isn't as all-encompassing as the subject would suggest... I am almost a Python newbie, but I have discovered that I don't get along with IDLE, as i can't work out how to run and rerun a routine without undue messing about. What I would really like is something like an old-style BASIC interpreter, in which I could list, modify and test-run sections of code, to see the effects of tweaks, without having to save it each time, or re-typing it over and over (I haven't even worked out how to cut and paste effectively in the IDLE environment). I see lots of alternate IDEs etc, but which would allow me the simple interface that I have described? - I really don't know about IDEs in general, and I suspect I would be out of my depth with one of those. Thanks, and feel free to mock ;) -- http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From jeremy+complangpython at jeremysanders.net Tue Jul 12 11:21:38 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 12 Jul 2005 16:21:38 +0100 Subject: breaking out of nested loop References: Message-ID: rbt wrote: > What is the appropriate way to break out of this while loop if the for > loop finds a match? queue discussion why Python doesn't have a "break N" statement... -- Jeremy Sanders http://www.jeremysanders.net/ From godoy at ieee.org Sat Jul 30 16:06:11 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 30 Jul 2005 17:06:11 -0300 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Ed Leafe wrote: > There are also several classes in wxPython that Dabo has not wrapped, > primarily the lower-level drawing classes and some of the newer graphics > classes, mainly because they weren't needed for a database application > framework. However, if there's a need, we'll be glad to add it. If it is added, let us know. I can't think of a better way to visualize database reports in an easy and fast way. Specially for BI. -- Jorge Godoy From kirk at jobsluder.net Tue Jul 5 19:58:12 2005 From: kirk at jobsluder.net (Kirk Job Sluder) Date: Tue, 05 Jul 2005 23:58:12 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <87pstw7qjq.fsf@debian.kirkjobsluder.is-a-geek.net> "seberino at spawar.navy.mil" writes: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. > > It got me curious if Lisp > is inherently faster to develop complex apps in. It would seem if you > could create your own language in Lisp using macros that that would be > quite an advantage.... Well, for me, I was playing around with lisp and developing in python for my little scripts until I finally hit something that could leverage a lisp macro to create a new type of iterator. After that things moved foward at a rapid speed. Another point in lisp's favor is that I prefer nested s-expressions to the sometimes ugly mashup of functional and OO calls that I end up creating in python. On the other hand, python benefits from a much richer standard library, so some of the things you take for granted in python such as string.split(None,3) need to be found or created. > thanks! > > Chris > -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From devlai at gmail.com Fri Jul 1 01:29:46 2005 From: devlai at gmail.com (Devan L) Date: 30 Jun 2005 22:29:46 -0700 Subject: Splitting string into dictionary In-Reply-To: References: <59e9fd3a0506302121197c545a@mail.gmail.com> Message-ID: <1120195786.108955.257460@o13g2000cwo.googlegroups.com> One line solution. dict(re.findall(r"'(.+?)' \| '(.+?)'(?:\s\||$)",yourtexthere)) From girish.14 at gmail.com Fri Jul 22 10:11:53 2005 From: girish.14 at gmail.com (Girish) Date: 22 Jul 2005 07:11:53 -0700 Subject: Query - Pexpect Message-ID: <1122041513.698420.278720@o13g2000cwo.googlegroups.com> Hi , I wanna do some automation work using "pexpect". I have an application which must be invoked from the command line in linux environment,it consists of buttons,textboxes etc can i access those widgets using "pexpect",say i wanna enter a value 3.3 in the textbox and then click on the ok button,to run the apllication.The application is developed using wxpython.ur suggestions will be of gr8 help.plz do reply. Regards Girish From grante at visi.com Thu Jul 14 17:00:26 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 14 Jul 2005 21:00:26 -0000 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? References: <11ddckucctde603@corp.supernews.com> <11ddfgsg4nlch86@corp.supernews.com> Message-ID: <11ddkjakresod4a@corp.supernews.com> On 2005-07-14, Tim Peters wrote: > You may have forgotten how much richer the "plausible HW" landscape > was at the time too. I've probably blocked most of it out intentionally. I seem to have vague, repressed, memories of working on a Sperry machine that used base 4 floating point. And of course there was the VAX. > If I had to bet at the time, I would have put my money on 754 > dying out due to near-universal lack of language support, and > incompatible HW implementations. Most programming languages > still have no sane 754 story, but the remarkable dominance of > the Pentium architecture changed everything on the HW side. As messed up as I think the IA32 architecture is, I do think Intel got FP mostly right. :) -- Grant Edwards grante Yow! If I felt any more at SOPHISTICATED I would DIE visi.com of EMBARRASSMENT! From jgrahn-nntq at algonet.se Thu Jul 7 05:25:25 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 7 Jul 2005 09:25:25 GMT Subject: latex/bibtex python paper? References: <1120663725.339927.141870@g47g2000cwa.googlegroups.com> Message-ID: On 6 Jul 2005 08:28:45 -0700, schwehr at gmail.com wrote: > Hi All, > > Does anyone have a good template that I might use for writing a python > paper in latex/bibtex? I've got the paper mostly done, but am having > issues with the references. I am definitely not an expert at > latex/bibtex. Right now, I have references defined like this: ... > > When I cite these, I get something like this (Foundation[2005]). Is > anyone willing to offer up a tarball of a complete paper with sty and > bst that would make for a nice python paper? You really, really should Google around for BibTeX information, or ask in a TeX newsgroup. (Unless I misunderstood you, and Python is somehow involved as something more than the subject of your paper?) I have used BibTeX in the past, but forgotten the details. Getting the exact citation style you want is tricky (and you didn't even say what you wanted the citations to look like). There seem to be many newer, contributed styles which aren't trivial to find without help. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From hancock at anansispaceworks.com Sat Jul 2 18:17:17 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 17:17:17 -0500 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> References: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> Message-ID: <200507021717.17983.hancock@anansispaceworks.com> On Saturday 02 July 2005 05:04 am, Ralf W. Grosse-Kunstleve wrote: > I often find myself writing:: > > class grouping: > > def __init__(self, x, y, z): > self.x = x > self.y = y > self.z = z > # real code, finally Fortunately, you don't have to, try this: #(1) class grouping: def __init__(self, *args): parms = ('x', 'y', 'z') arg_parms = zip(parms, args[:len(parms)]) for parm, arg in arg_parms: setattr(self, parm, arg) In this case, of course, this isn't any shorter, but if you have a few dozen parameters, it can be. Note, that it may be stylistically better to do this: #(2) class grouping: def __init__(self, **kw): for key, val in kw.items(): setattr(self, key, val) or possibly: #(3) class grouping: def __init__(self, **kw): parms = ('x', 'y', 'z') for key, val in kw.items(): if key in parms: setattr(self, key, val) Because, if you are going to have dozens of arguments, it will be hard for you to remember their order in the caller, and keyword arguments will make it possible to set them by name. Example (2) doesn't validate the arguments -- allowing you to set any arbitrary collection of values you want (can be a useful way to create a shared namespace), but (3) does (which is probably important if your class actually does specific things with the parameters). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From limi at plone.org Tue Jul 26 15:30:20 2005 From: limi at plone.org (limi at plone.org) Date: 26 Jul 2005 12:30:20 -0700 Subject: multilanguage site and user informations edition In-Reply-To: <42e4b845$2$13224$636a15ce@news.free.fr> References: <42e4b845$2$13224$636a15ce@news.free.fr> Message-ID: <1122406220.372545.113870@g43g2000cwa.googlegroups.com> Olivier wrote: > first i want to know what is the best and simple solution for a > multilinguage site with plone 2? > i want some tutorial, how to and if possible exemple The best way to approach this is to wait a couple of days until Plone 2.1 is released, and use LinguaPlone + Plone 2.1, which should make this very easy and transparent. > next i need to modify the user standard information to put my personnal > information like address, phone numbre, city, ... and i want to modify the > search member form to find member by all information like city. if anyone > can help me please give me a link to a faq or how to . Most of this is detailed in the Plone Book, and it's really easy to add in more attributes for your users if needed. The online version of the book is here: http://plone.org/documentation/manual/definitive-guide I would assume the plone-users mailing list is a better place to post this than the python language newsgroup. :) Try http://plone.org/contact#users - you can also subscribe via NNTP if you prefer the newsgroup format. > PS: Sorry for the english. Your English is more than good enough. Welcome to Plone. :) -- _____________________________________________________________________ Alexander Limi ? Chief Architect ? Plone Solutions ? Norway Consulting ? Training ? Development ? http://www.plonesolutions.com _____________________________________________________________________ Plone Co-Founder ? http://plone.org ? Connecting Content Plone Foundation ? http://plone.org/foundation ? Protecting Plone From steven.bethard at gmail.com Fri Jul 1 00:52:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 30 Jun 2005 22:52:42 -0600 Subject: aligning text with space-normalized text In-Reply-To: <42C3DC40.4050806@lexicon.net> References: <42C35438.2010207@lexicon.net> <42C3DC40.4050806@lexicon.net> Message-ID: John Machin wrote: > Steven Bethard wrote: > >> John Machin wrote: >> >>> For example, text = 'foo bar', chunks = ['foobar'] >> >> This doesn't match the (admittedly vague) spec > > That is *exactly* my point -- it is not valid input, and you are not > reporting all cases of invalid input; you have an exception where the > non-spaces are impossible, but no exception where whitespaces are > impossible. Well, the input should never look like the above. But if for some reason it did, I wouldn't want the error; I'd want the indices. So: text = 'foo bar' chunks = ['foobar'] should produce: [(0, 7)] not an exception. STeVe From mage at mage.hu Mon Jul 11 11:06:43 2005 From: mage at mage.hu (Mage) Date: Mon, 11 Jul 2005 17:06:43 +0200 Subject: cursor positioning In-Reply-To: References: <42D281D2.9060302@mage.hu> <20050711144249.374391E4002@bag.python.org> Message-ID: <42D28B03.7040705@mage.hu> James Carroll wrote: >I haven't tried this myself, but I think the secret to displaying a >continuously updating %done on the command line is to > print "file 100, 1% done" > >then send exactly 7 backspaces to the terminal, then print 2% done... >so the backspaces will write over the previous text. > >Backspace is a \x08 (ascii character with the value 8.) > >It _could_ work... > > > I tried but printing backslashes won't work in a loop (i think the screen was not refreshed correctly). You can use stdout and flush. Actually I am using this: for (s,i) in [(list[i],i) for i in range(len(list))]: content = file(s).read() sys.stdout.write(chr(8)*35 + str(i + 1) + ' of ' + str(len(list)) + ' files read') sys.stdout.flush() Mage From paul at boddie.org.uk Fri Jul 15 07:42:22 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 15 Jul 2005 04:42:22 -0700 Subject: How to create "cross-backend" python web app References: <1121375775.021103.28610@g43g2000cwa.googlegroups.com> Message-ID: <5339b60d.0507150342.3de87411@posting.google.com> "matt" wrote in message news:<1121375775.021103.28610 at g43g2000cwa.googlegroups.com>... > Hi all- > > I'm trying to port an ajax spell-checker > (http://www.broken-notebook.com/spell_checker/index.php) to use with > the moin moin wiki and have been somewhat successful. (By successful I > mean I can spell check using the php backend and my python port running > as cgi-bin). That looks like an interesting application/component. > My question is this: moinmoin runs on many python web backends > (cgi-bin/mod-python/twisted/standalone). My spell-checker backend runs > as cgi (disclaimer: I've done a bit of php and java(struts) web app > programming, but the last python related web programming I did was Zope > about 5 years ago (does that even count ? ;) )) because that was the > easiest for me to get up to speed on. What is the best way to write > cross-backend python web apps? Is there any abstraction I can use? Although a kind of Web "middleware" standard called WSGI [1] has been proposed to somehow alleviate these kinds of problems, I'd recommend using WebStack [2] to implement a "cross-backend" solution which will run on CGI, mod_python, Twisted, BaseHTTPServer and other technologies. > With cgi-bin, I use the python "cgi" module, which gives me easy access > to form variables, but I'd like to be able to deploy in the other > backends as well. What's the best way to do this? Or is a rewrite > required for each one? Some might argue that writing directly to WSGI would allow you to re-use your CGI-based code moderately easily whilst having some backend portability. I'd argue that WebStack's API is slightly more high-level and that the WebStack distribution should provide you with everything you need to deploy your application on the backends you've chosen (plus others). Either way, you certainly don't need to rewrite your application for every different environment any more. Paul [1] http://www.python.org/peps/pep-0333.html [2] http://www.python.org/pypi/WebStack From enleverlesO.OmcO at OmclaveauO.com Wed Jul 27 13:03:44 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Wed, 27 Jul 2005 19:03:44 +0200 Subject: Create a variable "on the fly" References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Message-ID: <42e7d82f$0$22302$8fcfb975@news.wanadoo.fr> Hi ! Try : OSCAR='the grouch' print OSCAR useless to thank me Michel Claveau From lambacck at computer.org Mon Jul 18 09:35:48 2005 From: lambacck at computer.org (Chris Lambacher) Date: Mon, 18 Jul 2005 09:35:48 -0400 Subject: win32ui CreatePrintDialog Message-ID: <20050718133547.GB18221@computer.org> On Mon, Jul 18, 2005 at 09:18:45AM +0200, Eric Brunel wrote: > On Fri, 15 Jul 2005 18:08:35 -0400, Chris Lambacher wrote: > > > Hi, > > > > This question has come up a few times on the list with no one giving a public > > answer. How do you use CreatePrintDialog from win32ui? > > > > About a year ago someone posted that: > > dlg = win32ui.CreatePrintDialog(1538) > > dlg.DoModal() > > > > will give you the window, but the ok button does not work. > > Here is what I did to make it work: > > > import win32ui > from pywin.mfc import window, dialog > > class WindowsPrintDialog(window.Wnd): > > # Numbers for various items in the dialog > PROPERTIES_BTN = 1025 > PRINTER_NAME = 1139 > PRINT_TO_FILE = 1040 > PRINT_ALL = 1056 > PRINT_PAGES = 1058 > PRINT_SELECTION = 1057 > FIRST_PAGE = 1152 > LAST_PAGE = 1153 > FROM_TEXT = 1089 > TO_TEXT = 1090 > NB_COPIES = 1154 > > def __init__(self): > dlg = = win32ui.CreatePrintDialog(1538) > window.Wnd.__init__(self, printDlg) > > def OnInitDialog(self): > ## Initialize dialog itself > self._obj_.OnInitDialog() > ## Activate all widgets > for i in (WindowsPrintDialog.PRINT_ALL, WindowsPrintDialog.PRINT_PAGES, > WindowsPrintDialog.FIRST_PAGE, WindowsPrintDialog.LAST_PAGE, > WindowsPrintDialog.FROM_TEXT, WindowsPrintDialog.TO_TEXT, > WindowsPrintDialog.PRINT_SELECTION): > itm = self._obj_.GetDlgItem(i) > itm.EnableWindow() > ## Disable "Properties" button: it doesn't work... > itm = self._obj_.GetDlgItem(WindowsPrintDialog.PROPERTIES_BTN) > itm.EnableWindow(0) > > def OnOK(self): > ## Call on dialog itself > self._obj_.OnOK() > self._obj_.UpdateData(1) > ## Now you can get values entered in dialog via: > ## - self.IsDlgButtonChecked() pour check-buttons > ## - self.GetDlgItemText() for textual fields > ## - self.GetDlgItemInt() for integer fields > ## Then use these info. to create your printer DC; for example: > printerName = self.GetDlgItemText(WindowsPrintDialog.PRINTER_NAME) > dc = win32ui.CreateDC() > dc.CreatePrinterDC(printerName) > ## And so on... > > > Note that the printer properties button is explicitely disabled. If it's not, it seems to be working (it actually opens the printer properties dialog and all options can be modified without any error), but actually doesn't change a thing: the printing will be done with the printer default settings. If anybody has any idea on how this thing works, please let me know: I'm very interested. > In the MFC documentation, CPrintDialog has a GetPrinterDC method. This method AFAICT gives you a printer device contex which has all the settings set for you. > > Diging into the source shows that the 1538 is being loaded as a template > > resource. The MSDN documentation does not say anything about this being > > neccessary and in fact, other common dialogs provide this as an option, but > > not a requirement. Why is this made a requirement? If it was not made a > > requirement, would the dialog work? > > I guess it would just be a matter of giving the default value 1538 to the idRes parameter in win32ui.CreatePrintDialog; AFAICT, this is always the id for the default print dialog. Can't figure out why it was not done in the first place... > The problem is that 1538 is loaded as a template resource. I get exactly the same result from many resources all the way up to 20000 (I tried them in a loop). I suspect that this number just works because it is an ever present resource id, and does not actually do anything to help us. When used in conjuntion with the rest of the MFC printing framework, the dialog seems to work, but this does not help me because the rest of my application is in PyGTK, I would rather limit my MFC programming to the bare minimum. If I could get the PrintDlg function to work, I would use that instead. Unfortunately I can't figure out how to make that work either. I may just have to pull out MinGW and compile a module that uses the PrintDlg function. > > Unfortunately I can't play with this because I don't have Visual Studio. I > > guess the logical next step, if the above worked, would be to add the > > GetPrinterDC() method (and maybe some others) so that we can do something > > useful with the dialog. > > Yep. See above. > > > Thanks, > > Chris > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" > -- > http://mail.python.org/mailman/listinfo/python-list ----- End forwarded message ----- From peter at engcorp.com Tue Jul 5 15:15:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Jul 2005 15:15:40 -0400 Subject: threads and sleep? In-Reply-To: References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> Message-ID: Jeffrey Maitland wrote: > I was hoping that python would allow for the cpu threading such in > Java etc.. but I guess not. (from the answers,and other findings) I > guess I will have to write this part of the code in something such as > java or c or something that allows for it then I can either wrap it in > python or avoid python for this part of the app. Or investigate the use of Irmen's Pyro package and how it could let you almost transparently move your code to a *multi-process* architecture which would then let you take advantage of all the CPUs you have available (even if they _aren't_ on the same machine!). -Peter From hpj at urpla.net Wed Jul 20 14:14:32 2005 From: hpj at urpla.net (Hans-Peter Jansen) Date: Wed, 20 Jul 2005 20:14:32 +0200 Subject: convert ascii escapes into binary form References: Message-ID: Robert Kern wrote: > Hans-Peter Jansen wrote: >> Hi Pythonistas, >> >> I need to convert ascii escapes into binary form, e.g.: >> \f -> ^L >> \033@\x1bk\000 -> ^[@^[k^@ >> >> (rvalues in terminal representation) >> >> Any idea, how to do this most elegantly in python? >> Do I really need to do a search n'replace orgy, combined with >> regex for this task? > > In [11]: s = '\\f' > > In [12]: s.decode('string_escape') > Out[12]: '\x0c' That did the trick, thanks a lot, Peter. Unfortunately, on the target system, there's still python 2.0 running :-( Looks like I've to bite the apple.. Pete From and-google at doxdesk.com Sat Jul 9 08:05:25 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 9 Jul 2005 05:05:25 -0700 Subject: Problem with sha.new References: Message-ID: <1120910725.028985.246570@z14g2000cwz.googlegroups.com> Florian Lindner wrote: > sha = sha.new(f.read()) > this generates a traceback when sha.new() is called for the second time You have reassigned the variable 'sha'. First time around, sha is the sha module object as obtained by 'import sha'. Second time around, sha is the SHA hashing object you used the first time around. This does not have a 'new' method. Python does not have separate namespaces for packages and variables. Modules are stored in variables just like any other object. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From sjmachin at lexicon.net Thu Jul 21 17:01:12 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jul 2005 07:01:12 +1000 Subject: Difference between " and ' In-Reply-To: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: <42e00d17$1@news.eftel.com> b83503104 at yahoo.com wrote: > Hi, > > Can someone tell me the difference between single quote and double > quote? >>> ord("'") - ord('"') 5 or ask a meaningful question ... From alexs at advfn.com Wed Jul 6 05:13:01 2005 From: alexs at advfn.com (Alex Stapleton) Date: Wed, 6 Jul 2005 10:13:01 +0100 Subject: threads and sleep? In-Reply-To: <1120625123.135496.318590@g44g2000cwa.googlegroups.com> Message-ID: Is SYS V shared memory a totalyl stupid way of doing distributed locks between processes then? -----Original Message----- From: python-list-bounces+alexs=advfn.com at python.org [mailto:python-list-bounces+alexs=advfn.com at python.org]On Behalf Of Jonathan Ellis Sent: 06 July 2005 05:45 To: python-list at python.org Subject: Re: threads and sleep? Peter Hansen wrote: > Jeffrey Maitland wrote: > > I was hoping that python would allow for the cpu threading such in > > Java etc.. but I guess not. (from the answers,and other findings) I > > guess I will have to write this part of the code in something such as > > java or c or something that allows for it then I can either wrap it in > > python or avoid python for this part of the app. > > Or investigate the use of Irmen's Pyro package and how it could let you > almost transparently move your code to a *multi-process* architecture Unless you're doing anything that would require distributed locking. Many if not most such projects do, which is why almost everyone prefers to use threads on an SMP machine instead of splitting it across multiple smaller boxes. -Jonathan -- http://mail.python.org/mailman/listinfo/python-list From gene.tani at gmail.com Wed Jul 13 09:57:18 2005 From: gene.tani at gmail.com (gene tani) Date: 13 Jul 2005 06:57:18 -0700 Subject: Web App like Google In-Reply-To: References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> Message-ID: <1121263038.681422.14550@g44g2000cwa.googlegroups.com> a good text indexer will help, look at lupy, pyndex, xapian etc http://www.pypackage.org/packages/python-pyndex http://www.divmod.org/Home/Projects/Lupy/ From hancock at anansispaceworks.com Fri Jul 22 10:29:58 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 22 Jul 2005 09:29:58 -0500 Subject: Difference between " and ' In-Reply-To: <20050722130902.GB2284@alcyon.progiciels-bpi.ca> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <20050722130902.GB2284@alcyon.progiciels-bpi.ca> Message-ID: <200507220929.58036.hancock@anansispaceworks.com> On Friday 22 July 2005 08:09 am, Fran?ois Pinard wrote: > [Robert Kern] > > One habit that seems to crop up, though, is that I will use '' for > > internal strings and "" for strings that will eventually get seen by > > the user. Don't ask me why. > > One sure thing is that it would help, later, if you ever want to > internationalise a Python program. Not that it occurs that often! :-) Whoa. Why? Does xgettext not recognize _('')? I'm just learning to use it. Maybe I should pay attention to this point if that's so. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From simon.brunning at gmail.com Wed Jul 6 11:30:17 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 6 Jul 2005 16:30:17 +0100 Subject: Favorite non-python language trick? In-Reply-To: <87hdf8ync5.fsf@titan.staselog.com> References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> <87hdf8ync5.fsf@titan.staselog.com> Message-ID: <8c7f10c605070608307265d1d0@mail.gmail.com> On 7/6/05, Edvard Majakari wrote: > Ability to tag some methods 'deprecated' as in Java (from 1.5 > onwards?). However, Python interpreter doesn't have to do it: pydoc and > similar tools could detect, say, '@deprecated' in method comment string and > warn user about it. http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at REMOVETHIScyber.com.au Sat Jul 30 09:37:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 30 Jul 2005 23:37:04 +1000 Subject: Comparison of functions References: <42eb70a1$0$28646$636a15ce@news.free.fr> Message-ID: On Sat, 30 Jul 2005 14:20:50 +0200, tiissa wrote: > Steven D'Aprano wrote: >> Playing around with comparisons of functions (don't ask), I discovered an >> interesting bit of unintuitive behaviour: >> >>>>>a = lambda y: y >>>>>b = lambda y: y >>>>>a >> at 0xf70598ec> >>>>>b >> at 0xf7059844> >>>>>a < b >> False >> >> So I'm puzzled about how Python compares the two. > > Seems to me the object addresses are compared in this case. But I'm too > lazy to check it in the source. ;) Strangely enough, I'm lazy enough to not check the source too :-) Actually, more to the point, I don't read C, so even if I did check the source, I wouldn't know what it was trying to tell me. > However, the doc [1] warns you about such comparisons: """Most other > types compare unequal unless they are the same object; the choice > whether one object is considered smaller or larger than another one is > made arbitrarily but consistently within one execution of a program.""" I am aware of that. That's a wart. -- Steven. From hancock at anansispaceworks.com Tue Jul 19 21:27:33 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 19 Jul 2005 20:27:33 -0500 Subject: goto In-Reply-To: <261d32a705071804483ef68021@mail.gmail.com> References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: <200507192027.33461.hancock@anansispaceworks.com> On Monday 18 July 2005 06:48 am, Hayri ERDENER wrote: > hi, > what is the equivalent of C languages' goto statement in python? > best regards For the only valid uses of C's "goto", you should use the "try-except" or the "for/while-break-else" idioms. See the "language reference" for details on these statement blocks. If you're using "goto" for anything these blocks aren't appropriate for, then you should probably read the advice in the other replies. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From simonwittber at gmail.com Sun Jul 31 09:52:57 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 31 Jul 2005 06:52:57 -0700 Subject: keylogger in Python References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> Message-ID: <1122817977.591696.198240@f14g2000cwb.googlegroups.com> Michael Hoffman wrote: > I think this is going to be much harder than you think, and I imagine > this will only end in frustration for you. You will not be able to do it > well with just Python. I would recommend a different fun project. Actually, it's pretty easy, using the pyHook and Python win32 modules. I use code like this to detect when the user is away from the keyboard. import pyHook import time import pythoncom def OnKeyboardEvent(event): print event.Ascii hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() while True: pythoncom.PumpMessages() Sw. From steve at REMOVETHIScyber.com.au Sun Jul 31 10:30:05 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 01 Aug 2005 00:30:05 +1000 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: On Sun, 31 Jul 2005 15:09:48 +0200, Paolino wrote: > Steven D'Aprano wrote: > >> def translate(text): >> import string >> all=string.maketrans('','') >> badcars=all.translate(all,string.letters+string.digits) >> table=string.maketrans(badcars,'_'*len(badcars)) >> return text.translate(table) >> >> No pollution. > > And no efficience.Recalculating all,badcars and table was not an > acceptable solution ,sorry if I didn't state this point :( Why not? Is it too slow? Too many lines of code? Uses too much memory? What exactly is the problem? I would like to see your profile tests that show why this is not acceptable. Are you sure that this solution is less efficient than creating a class? A class has all that extra machinery and methods and attributes that needs to be created, only to be thrown away. How do you know that my solution is less efficient than your solution? >> Then after you are finished with the bindings, delete them: >> >> import string >> all=string.maketrans('','') >> badcars=all.translate(all,string.letters+string.digits) >> table=string.maketrans(badcars,'_'*len(badcars)) >> def translate(text): >> return text.translate(table) >> # clean up the temporary variables so as to prevent namespace pollution >> del string; del all; del badcars; del table > > Well,a solution but not a programming pattern for an elegant language ? > More this is also loosing informations. Deleting things you don't need or want is not losing information. You asked for a solution to make the bindings go away. Deleting them makes them go away. > Probably I've not been clear with the word pollution and the example is > poor. > I didn't mean 'binding to unuseful informations' but 'bindings in a non > -structured organization' > > I restate the problem.Python is in some ways unable to project the > module structure inside the module.Or ... namespace pattern instances > seems not deriving from a common pattern. I'm sorry, but I do not understand this. > Finally, (before I get polemic which is not my aim) I start thinking > classes (namespaces defined via 'class' keyword) are a specialization of > generic namespaces in which there-defined methods get a special way of > being called and __call__ method is a way of cloning access to them. > (Thin ice....) Yes, classes are a namespace. I don't know what you mean by "cloning access", but __call__ is the method called for arbitrary objects when you call them as if they were a function: someobject(). > Don't really know if modules can be defined as specialization of > generic namespaces and be placed somewhere next to classes. > > Even worse I get with methods and function namespaces. What is "even worse" about them? Quoting Rob Williscroft: > > def translate( text ) > > import string > > all=string.maketrans('','') > > badcars=all.translate(all,string.letters+string.digits) > > TABLE = string.maketrans(badcars,'_'*len(badcars)) > > > > global translate > > def translate( text ): > > return text.translate(TABLE) > > > > return translate( text ) This is a difficult piece of code to understand and maintain. You have a function called translate, which in turn calls the string translate() method. That's okay. But then you have a global variable *also* called translate -- does that refer to the same function? Is this self-modifying code? That is a dangerous, hard to debug, hard to understand technique that is too-clever-by-half. Then you create a local variable, also called translate, also a function, which simply calls the translate method of its argument. A waste of a function, when all you need to do is call the pre-existing translate method. If I have understood this code correctly, the *local* translate is bound to the *global* translate, which is the function being defined. And lastly, just to complete the confusion, the original function itself appears to call itself -- presumably the rebound copy that points to what was the local copy -- recursively, with the same argument. That's a nifty piece of code for showing how clever you are at writing mildly obfuscated code. But for commercial use, where the code has to be maintained and debugged, it is a terrible idea. > There is a way to access 'all' and 'badcars' here? I can't see any way to access them. Isn't that the point? You don't want them available? > In my trial translate.all and translate.badcars can be accessed easily > and maybe coherently. Yes, and you asked for that not to happen. That's what namespace pollution means -- you get temporary objects persisting after you no longer need them, and showing up in the namespace when you don't want them there. -- Steven. From cf_1957 at hotmail.com Tue Jul 19 06:09:05 2005 From: cf_1957 at hotmail.com (chris) Date: Tue, 19 Jul 2005 10:09:05 GMT Subject: OO design Message-ID: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> I've been scripting with python for a while now. Basically writing a few functions and running in the ipython shell. That's been very useful. But the more I do this the more I see that I'm doing more or less the same thing over and over again. So its feels like I need to get into class programming with all its attendant benefits. However my biggest problem is a conceptual one. I just can't get my head around defining suitable classes, how they aquire data and communicate with each other. I'm hoping some of you python lamas out there might be able to share some of your wisdom on the subject. What I basically do is a lot of the following:: 1. get arbitrary numerical data (typically large data sets in columnar format or even via COM from other packages. I generally have to deal with one or more sets of X,Y data) 2. manipulate the data (scaling, least squares fitting, means, peaks, add/subtract one XY set from another etc) 3. plot data (original set, results of manipulation, scatterplot, histograms etc - I use matplotlib) 4. export data (print, csv, shelve) I have no problem writing bits of functional code to do any of the above. But for the life of me I can't see how I can hook them altogether in an OO based framework that I can build and extend (with more data formats, manipulations, GUI etc). When I think about what I should do I end up with a class XY that has a method for everything I want to do eg. class XY: def read_file def scale_data def plot_data def shelve_data But somehow that doesn't feel right, especially when I expect the number of methods will grow and grow, which would make the class very unwieldy. Even if that was a legitimate option, I don't understand conceptualy how I would, for example, plot two different XY objects on the same graph or add them together point by point. How do two different XY objects communicate and how do you deal with the thing that they must have in common (the plot screen for example). Clearly I'm having some conceptualisation problems here. Hope someone can shed some light on the subject bwaha. From cam.ac.uk at mh391.invalid Thu Jul 21 17:24:20 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 22:24:20 +0100 Subject: PEP on path module for standard library In-Reply-To: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> References: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> Message-ID: mkent at webmd.net wrote: > I really love Jason's 'path' module. Sadly, I've encountered a serious > problem with using it. When you try to 'freeze' an application module, > and Jason's 'path' module is present in any of the directories that are > looked at by freeze's module finder (your app doesn't have to import > it), freeze goes into an infinite loop of imports, eventually getting a > 'maximum recursion depth' exception. This seems to be related to > freeze getting confused between 'os.path' and Jason's 'path'. > > I encountered this using Jason's latest 'path' module and Python 2.3.2. > I was able to solve it for my use by renaming path.py to newpath.py > and using 'from newpath import path' in my modules. > > I've just notified Jason about this. I presume a solution like mine > will be used, and look forward to seeing Jason's module in stdlib. This sounds like a bug in "freeze" rather than something that should be worked around in the standard library. Although there have already been people opposed to naming it path because the duplication with os.path might confuse humans. -- Michael Hoffman From onurb at xiludom.gro Mon Jul 25 10:08:20 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 25 Jul 2005 16:08:20 +0200 Subject: Getting a dictionary from an object In-Reply-To: <42e4e61c@news.eftel.com> References: <42e3fd9f$0$18620$626a14ce@news.free.fr> <42e4e61c@news.eftel.com> Message-ID: <42e4f256$0$7310$636a15ce@news.free.fr> John Machin wrote: > Dark Cowherd wrote: > >>> voiceless-ly'rs >> >> >> What does this mean?? Just curious (googled that and ly'rs and didnt >> find anything relevant) s/ly'rs/ly y'rs/ > The voiceless part I understand to mean that Bruno is "shocked and > stunned and not a little bit amazed" [1] at Steven's masterstroke which > came out of the blue and trumped all previous efforts -- a true "deus ex > machina", a thunderbolt from Olympus -- or if you want a one-word > colloquialism, he's gobsmacked. > > The -ly'rs part means that in his shocked state he has tried to emulate > the timbot's characteristic sign-off [2], but failed to get the syntax > correct. > one-hundred-percent-correct-ly y'rs !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rkern at ucsd.edu Fri Jul 1 22:29:20 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 01 Jul 2005 19:29:20 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120270309.103244.53600@g49g2000cwa.googlegroups.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> Message-ID: Sean McIlroy wrote: > Peter Hansen wrote: > > >>Sean, what gave you the impression this would change? > > just inductive reasoning. i've been wrong before (like anyone who makes > that claim), and i'm a former python enthusiast, so my judgement must > be colored to some extent by bitterness. maybe they have solid reasons > for scrapping the functional constructs. but to me it seems like > they're eliminating them just because they offend the sensibilities of > C-programmers. This is incorrect. > (i mean those stereotypical C-programmers, baffled by > recursion and the like, who don't want to be reproached with the fact > of their mathematical illiteracy.) if that's the case then list > comprehensions and/or "first class functions" are likely to be the next > target. map and filter are being removed *because of* list comprehensions. Did you even read Guido's articles about this issue? Your understanding of why these changes are planned is incorrect; consequently your projection based on that understanding is not on firm footing. > even if they're not, it's pretty clear that python is leaving > its multiparadigmatic origins behind. "do it our way," the pundits are > effectively saying, "or get out". for my part, i'm getting out. If that's what you want to do, no one is going to stop you. But please do it quietly. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Wed Jul 20 21:19:44 2005 From: http (Paul Rubin) Date: 20 Jul 2005 18:19:44 -0700 Subject: Newbie question about lists References: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> <1121908372.875767.321980@f14g2000cwb.googlegroups.com> Message-ID: <7x4qap551r.fsf@ruckus.brouhaha.com> "Leo Jay" writes: > [Decimal("0.25"), Decimal("0.10"), Decimal("0.05"), Decimal("0.01")] I wonder if we should have some special syntax for decimals: maybe [$.25, $.10, $.05, $.01] That would even fit in with decimals being used for financial quantities. From gregm at taming-tech.com Thu Jul 7 16:31:34 2005 From: gregm at taming-tech.com (GregM) Date: 7 Jul 2005 13:31:34 -0700 Subject: Calculating average time Message-ID: <1120768294.287881.169030@z14g2000cwz.googlegroups.com> Hi, I'm hoping that someone can point me in the right direction with this. What I would like to do is calculate the average time it takes to load a page. I've been searching the net and reading lots but I haven't found anything that helps too much. I'm testing our web site and hiting +6000 urls per test. Here is a subset of what I'm doing. import IEC #IE controller from http://www.mayukhbose.com/python/IEC/index.php from win32com.client import Dispatch import time import datetime from sys import exc_info, stdout, argv, exit failedlinks = [] links = open(testfile).readlines() totalNumberTests = len(links) ie = IEC.IEController() start = datetime.datetime.today() # asctime() returns a human readable time stamp whereas time() doesn't startTimeStr = time.asctime() for link in links: start = datetime.datetime.today() ie.Navigate(link) end = datetime.datetime.today() pagetext = ie.GetDocumentText() #check the returned web page for some things if not (re.search(searchterm, pagetext): failedlinks.append(link) ie.CloseWindow() finised = datetime.datetime.today() finishedTimeStr = time.asctime() # then I print out results, times and etc. So: 1. Is there a better time function to use? 2. To calculate the average times do I need to split up min, sec, and msec and then just do a standard average calculation or is there a better way? 3. is there a more efficient way to do this? 4. kind of OT but is there any control like this for Mozilla or firefox? This is not intended to be any sort of load tester just a url validation and page check. Thanks in advance. Greg. From stian at soiland.no Wed Jul 6 15:08:22 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 6 Jul 2005 21:08:22 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <20050706190822.GW12095@itea.ntnu.no> On 2005-07-06 16:33:47, Ron Adam wrote: > *No more NamesError exceptions! > print value > >> None So you could do lot's of funny things like: def my_fun(extra_args=None): if not extraargs: print "Behave normally" extra_args = 1337 if extraargs: asdkjaskdj .. if extra_args: kajsdkasjd and get no errors at all, but switching back and forth between the different behavours because you actually did expect None, but from an EXISTING variable. > *No initialization needed for a while loop! > > while not something: > if : > something = True This is the only "good" case I could find, but opening for a lots of errors when you get used to that kind of coding: while not finished: foo() finished = calculate_something() (..) (..) # Added another loop while not finished: bar() finished = other_calculation() Guess the amount of fun trying to find out the different errors that could occur when bar() does not run as it should because the previous "finished" variable changes the logic. If you want to experiment with such designs, all you need to do is to start your code with *Test if name exists without using a try-except! > if something == None: > something = value Now this is a question from newcomers on #python each day.. "How do I check if a variable is set?". Why do you want to check if a variable is set at all? If you have so many places the variable could or could not be set, your program design is basically flawed and must be refactored. -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] From tim.golden at viacom-outdoor.co.uk Tue Jul 26 11:17:02 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 26 Jul 2005 16:17:02 +0100 Subject: [path-PEP] Path inherits from basestring again Message-ID: <9A28C052FF32734DACB0A288A3533991044D2150@vogbs009.gb.vo.local> [Peter Hansen] | | Ron Adam wrote: | >>>> Tony Meyer wrote: | >>>>> Do people really like using __div__ to mean join? | | > I think the '+' is used as a join for both strings and lists, so it | > would probably be the better choice as far as consistency with the | > language is concerned. | | The issue with that is that as long as we are subclassing | strings, the + | is already defined for a useful operation and the subclass probably | shouldn't be changing the way that works. Well, I actually had some correspondence with Jason on this very subject a year or so ago: [Me] | Not sure if it's a bug or a feature, but __add__ does a + on the two | strings/paths while the __div__ does a join. The principal difference from | my point of view is that if I add two absolute paths: [...] [Jason] | Well... from my point of view, it's a feature... :) | The purpose of + is (for example) to add extensions to the end of filenames: | p = path('C:\\blorpl\\flarg.txt') | z = p + '.zip' | Without it, this would be pretty awkward. | (path.__add__ is overloaded only to make this operation return a path | object. Otherwise it would return a plain string.) | The other purpose of + is so that a path behaves just like a string for all | string operations. This means you can safely pass a path object to any | function that expects a string. Obviously, I don't know how much weight Jason's original ideas have on the prepped-for-syslib module, but it does support what other people have been saying: that the Path should behave like a string where a string is expected. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Fri Jul 22 17:56:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 17:56:10 -0400 Subject: Getting TypeError in Changing file permissions In-Reply-To: References: Message-ID: Benjamin Niemann wrote: > Pranav Bagora wrote: >>" os.chmod(outfile,0700) >>TypeError: coercing to Unicode: need string or buffer, >>file found" > > Looks as if your are using a file object (that you got from an open() call) > as the first parameter. What you need is a string with the path to the > file. Which this should do: os.chmod(outfile.name, 0700) -Peter From lbates at syscononline.com Mon Jul 11 10:11:58 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 11 Jul 2005 09:11:58 -0500 Subject: cursor positioning In-Reply-To: References: Message-ID: <42D27E2E.3040904@syscononline.com> While not "curses" based this class will update screen as you want. You could use it as a basis upon which to do a curses version with your cursor positioning. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 -Larry Bates Mage wrote: > Dear All, > > I am writing a database import script in python and I would like to > print the percentage of the process to the last line. I would like to > update the last line at every percent. You know what I mean. > > How can the cursor be positioned to the last line or somewhere else on > the screen? Curses starts with clearing the whole screen and it is > overkill. Many modules are on the net but I would like to resolve this > simply task with native python. > > I tried: > > for something: > print chr(8)*20+mystring, > > but it is nasty and didn't work well. > > Mage > From python-ml at nn7.de Sun Jul 24 10:24:28 2005 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Sun, 24 Jul 2005 16:24:28 +0200 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: Message-ID: <1122215068.30698.37.camel@localhost> On Sun, 2005-07-24 at 13:36 +1000, Steven D'Aprano wrote: > On Sat, 23 Jul 2005 18:30:02 +0200, Soeren Sonnenburg wrote: > > > Hi all, > > > > Just having started with python, I feel that simple array operations '*' > > and '+' don't do multiplication/addition but instead extend/join an > > array: > > * and + are not array operations, they are list operations. > > Lists in Python can contain anything, not just numeric values. That seems to be *the point*. Although list(a) + list(b) could create a list [ a[0]+b[0], ...] and bail out if for elements '+' is not defined... > Python doesn't have built-in mathematical arrays, otherwise known as > matrices. There are modules that do that, but I haven't used them. Google > on Numeric Python. Well I am aware of that but I don't understand the reasons of having both lists (which are infect arrays) and *arrays ? *I* would rather drop '+' and '*' to work like they do in *array ... Soeren From steven.bethard at gmail.com Fri Jul 8 20:15:37 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 8 Jul 2005 18:15:37 -0600 Subject: python-dev Summary for 2005-06-16 through 2005-06-30 Message-ID: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-06-16_2005-06-30.html] ===================== Summary Announcements ===================== ------------------ OSCON Registration ------------------ Though if you haven't yet registered, you've already missed the early registration period (which ended June 20), you should still consider taking a look at the O'Reilly Open Source Convention (OSCON). Guido assures us that "the Python program is really good!" Contributing Thread: - `Please spread the word about OSCON early reg deadline `__ ========= Summaries ========= ------------ PEP Clean Up ------------ Raymond Hettinger decided to go through the `list of PEPs`_ and do some spring cleaning (late for the Northern Hemisphere, but early down south). * Rejection of `PEP 303`_ ("Extend divmod() for Multiple Divisors") was proposed on the grounds that it has been open for two and half years and hasn't generated discussion or support, is unpersuasive, and unnecessary. No-one spoke up for it (and some against), so it is now rejected. * Rejection of `PEP 254`_ ("Making Classes Look More Like Types") was proposed on the grounds that it is only an empty stub and is unlikely to ever get filled-out. No-one spoke up either way, and it is now rejected. * Rejection of `PEP 265`_ ("Sorting Dictionaries by Value") was proposed on the grounds that as of Python 2.4 its use case is easily solved with a one-line sorted() solution. Several people agreed, and no-one disagreed, so the PEP is now rejcted. * Rejection of `PEP 276`_ ("Simple iterator for ints") was proposed on the grounds that the principal use case was largely met by enumerate() and that the proposed syntax was problematic. Guido agreed, so the PEP was rejected. * Rejection of `PEP 281`_ ("Loop Counter Iteration with range and xrange") was proposed on the grounds that it too was solved by the enumerate() built-in. Guido agreed again, and this PEP too was rejected. * Rejection of `PEP 294`_ ("Type Names in the types Module") was proposed on the grounds that a centralized repository of type names was a mistake and that neither the "types" nor "new" modules should be carried forward to Python 3.0. No-one disagreed, and the PEP was rejected. * Rejection of `PEP 313`_ ("Adding Roman Numeral Literals to Python" - yes, this is a real PEP!) was proposed, and the PEP was rejected. * Rejection of `PEP 336`_ ("Make None Callable") was proposed on the grounds that no support has grown beyond the original poster, and that it fails the tests of obviousness, necessity, clarity, and explicitness. Many people, including Guido, agreed, and the PEP was rejected. * Raymond suggested updating `PEP 284`_ ("Integer for-loops"), but several people spoke up against it, including Guido, so the PEP was rejected. * Raymond asked whether `PEP 330`_ ("Python Bytecode Verification") had any known uses. Guido said that he believes that a verification tool has some value, but if someone wants to add it to Tools/scripts, no PEP is required, so the PEP was rejected. * A.M. Kuchling volunteered to take over `PEP 206`_ ("Python Advanced Library", or the "Batteries Included" PEP) and rewrite it to describe a set of third-party packages to complement the standard library. This was approved, and so he's now the maintainer. * Raymond suggested accepting `PEP 312`_ ("Simple Implicit Lambda"), which resulted in the most discussion of any of the PEP recommendations. However, Guido hates the unary colon syntax, and it was decided that the PEP needs to go back to the drawing board and find a more Pythonic syntax (perhaps an alternative unary operator). The PEP is now deferred. * Raymond asked whether `PEP 237`_ ("Unifying Long Integers and Integers") was now complete and could be marked as final. Guido noted that it was complete for 2.x, but that phase C will be implemented in Python 3.0, as the PEP states. He indicated that he would be fine with marking `PEP 237`_ as final and moving this phase to `PEP 3000`_; at the time of writing, this hadn't been done yet. .. _list of PEPs: http://wwww.python.org/peps .. _PEP 303: http://www.python.org/peps/pep-0303.html .. _PEP 265: http://www.python.org/peps/pep-0265.html .. _PEP 254: http://www.python.org/peps/pep-0254.html .. _PEP 276: http://www.python.org/peps/pep-0276.html .. _PEP 281: http://www.python.org/peps/pep-0281.html .. _PEP 294: http://www.python.org/peps/pep-0294.html .. _PEP 313: http://www.python.org/peps/pep-0313.html .. _PEP 336: http://www.python.org/peps/pep-0336.html .. _PEP 284: http://www.python.org/peps/pep-0284.html .. _PEP 330: http://www.python.org/peps/pep-0330.html .. _PEP 206: http://www.python.org/peps/pep-0206.html .. _PEP 312: http://www.python.org/peps/pep-0312.html .. _PEP 237: http://www.python.org/peps/pep-0237.html .. _PEP 3000: http://www.python.org/peps/pep-3000.html Contributing Threads: - `Propose rejection of PEP 303 -- Extend divmod() for Multiple Divisors `__ - `Propose to close PEP 254 -- Making Classes Look More Like Types `__ - `Propose to reject PEP 265 -- Sorting Dictionaries by Value `__ - `Propose to reject PEP 276 -- Simple iterator for ints `__ - `Propose to reject PEP 281 -- Loop Counter Iteration with range and xrange `__ - `Propose to reject PEP 294 -- Type Names in the types Module `__ - `Propose to reject PEP 313 -- Adding Roman Numeral Literals to Python `__ - `Propose to reject PEP 336 -- Make None Callable `__ - `Propose updating PEP 284 -- Integer for-loops `__ - `Question about PEP 330 -- Python Bytecode Verification `__ - `Request to rewrite PEP 206 `__ - `Recommend accepting PEP 312 -- Simple Implicit Lambda `__ - `Is PEP 237 final -- Unifying Long Integers and Integers `__ [TAM] ------------------------------------------- PEP 342: Coroutines via Enhanced Generators ------------------------------------------- Raymond Hettinger withdrew `PEP 288`_, since the exception-handling part is now covered in `PEP 343`_ and the generator-attributes part was never very popular. Though he seemed to think `PEP 342`_ could replace the generator-attributes part, he was concerned that `PEP 342`_ was proposing too extensive a set of changes, as it modified the basic for-loop and continue statement semantics, and created a split between new- and old-style iterators. As a result of those comments, Phillip J. Eby took over `PEP 342`_, eliminated the continue expression and modification of the for-loop, added some motivating examples, and provided a `prototype patch`_ implementing the proposal. `PEP 342`_ now retains normal Python for-loop and continue statements, and does not introduce a new iterator protocol. Instead, it modifies the generator-iterator type by adding the methods: - send(value) which acts like the previously proposed single-argument form of next(). (Introducing a new method instead of overloading next() minimizes overhead for simple next() calls.) Calling send(value) before the generator has advanced to the first yield-expression raises a TypeError. - throw() which injects exceptions at the point of the generator's last yield-expression. - close() which injects a GeneratorExit exception into the generator to make sure that it terminates. PEP 342 also attempts to ensure that this close() method will be called when a generator-iterator is garbage-collected. Additionally, Phillip's patch addressed some garbage collection issues, having generators set their gi_frame to None when they finish, and modifying gcmodule.c to check for tp_del methods on instance objects (instead of just on heap types) so that the close() methods of generators would be properly invoked. The revised PEP was accepted by Guido at EuroPython. .. _PEP 288: http://www.python.org/peps/pep-0288.html .. _PEP 342: http://www.python.org/peps/pep-0342.html .. _PEP 343: http://www.python.org/peps/pep-0343.html .. _prototype patch: http://python.org/sf/1223381 Contributing Threads: - `Withdrawn PEP 288 and thoughts on PEP 342 `__ - `Implementing PEP 342 (was Re: Withdrawn PEP 288 and thoughts on PEP 342) `__ - `gcmodule issue w/adding __del__ to generator objects `__ - `Generator enhancements patch available `__ [SJB] -------------------------------------------------- Adding Jason Ordenorff's path module to the stdlib -------------------------------------------------- Reinhold Birkenfeld suggested that Jason Ordenorff's `path module`_ should be in the standard library as it has a large user base, frequently c.l.py praises, is a superior interface to OS paths than the existing os.path module, and could more easily be made to properly support unicode paths. Phillip J. Eby reviewed the module and made a list of suggested changes, primarily changing so that there is only one way to do things and clearing up naming confusion between the module and the existing os.path module, but was generally in favour of inclusion. The suggestion was to call the object either "path" or "Path" and put it either in the os module or os.path module, although Guido vetoed os.path.path and Tony Meyer begged for more differentiation between the path class and path module than a single character's case. Early enthusiasm suggested that a PEP wasn't needed to include the module, as there was general agreement about the inclusion and all but minor details. Guido disagreed, however, asking whether there was a need for a completely different mechanism for doing the same things that os.path already does, and inevitable disgreements about details (e.g. time in seconds, or a datetime object?) reinforced the need for a PEP. Discussion was still continuing at the end of the summary period; a PEP seems the likely outcome. .. _path module: http://www.jorendorff.com/articles/python/path/ Contributing Thread: - `Adding the 'path' module (was Re: Some RFE for review) `__ [TAM] ------------------------------- PEP 304 searches for a champion ------------------------------- Skip Montanaro wrote `PEP 304`_ ("Controlling Generation of Bytecode Files") a couple of years ago, and has mostly sat idle other than minor updates. Skip has no personal use for the PEP, and can't offer championing for it than continuing to respond to people's inputs. He asked whether anyone would be willing to take up championship of the PEP, or if it could be rejected. There were a couple of people interested in the idea, but no-one has yet volunteered to take the PEP from Skip. .. _PEP 304: http://www.python.org/peps/pep-0304.html Contributing Threads: - `PEP 304 - is anyone really interested? `__ - `PEP 304 "Controlling Generation of Bytecode Files" - patch updated `__ [TAM] ------------------------- Merging float and Decimal ------------------------- Fredrik Johansson suggested that Python floats and decimal.Decimal objects should be merged together much in the way that Python ints and longs have been. The idea would be that a binary or decimal represenation could be selected at runtime using a context object like decimal.Context. This would allow code like:: >>> from __future__ import new_float_behaviour >>> 1.1 1.1 >>> import sys >>> sys.float_context.binary = True >>> 1.1 1.1000000000000001 One issue would be the extent to which various context settings could be respected for both binary and decimal floating-point numbers. Since binary floating-point numbers would be represented using C floats, they would not have direct access to the traps and flags that decimal.Decimal floats do because these signals are not available in C. This issue could possibly be addressed by maintaining platform-dependent code for accessing traps and flags. People seemed generally to agree with the proposal, with Raymond Hettinger suggesting a roadmap: first move decimal.Decimal objects to C code, next introduce decimal literals such as 123.45d, and then perhaps use decimal floating-point numbers as the default in Python 3.0. Contributing Thread: - `Decimal floats as default (was: discussion about PEP239 and 240) `__ [SJB] ------------------------------------------------ API differences between builtin set and sets.Set ------------------------------------------------ Barry Warsaw noted that builtin set objects (unlike sets.Set objects) do not have .union_update() methods as aliases for their .update() methods. He also pointed out that the documentation for builtin set objects does not cover the .update() method, and wrongly indicates that the set methods only accept sequences, not iterables. Raymond Hettinger pointed-out that dropping union_update() from the API was an intentional design decision that was be discussed prior to release. At Barry's suggestion, Raymond expanded the docs to include a detailed list of differences between the set builtins and the sets module. The list is thankfully short. Contributing Thread: - `Inconsistent API for sets.Set and build-in set `__ [SJB] ---------------------------------- Using the alternate form of iter() ---------------------------------- In the dowhile threads, Jp Calderone pointed out a useful case for the alternate form of iter() which takes a no-argument function to call repeatedly, and a sentinel value to look for:: for chunk in iter(lambda: f1.read(CHUNK_SIZE), ''): f2.write(chunk) This started a brief discussion on how this very useful idiom could be made easier to read. I suggested that it would be nice if iter() had a signature like unittest.TestCase.assertRaises which accepts ``*args`` and ``**kwargs`` to be passed to the function when it is called. This would have to be a Python 3.0 change because it's backwards incompatible, but would look something like:: for chunk in iter('', f1.read, CHUNK_SIZE): f2.write(chunk) Benji York, Michael Hudson and James Y Knight suggested that functional.partial (which will be available in Python 2.5) is a more general solution because it does not require argument reordering and it can also be used in the occasional cases that require multiple callables:: for chunk in iter(partial(f1.read, CHUNK_SIZE), ''): f2.write(chunk) Raymond Hettinger suggested a Python 3.0 roadmap: the file API should evolve an iterblocks(size) method, and iteration patterns terminating with '' should all be replaced with modern iterators that terminate by raising StopIteration. Contributing Thread: - `iter alternate form and *args and **kwargs `__ [SJB] -------------------------------------- Adding lightweight cooperative threads -------------------------------------- Adam Olsen outlined various problems with the current state of Python threading (they are expensive, unpredictable, uninterupptible, fail silently, and have finely grained atomicity), and proposed adding lightweight cooperative threads to Python (including a new operator for threaded calls, and new statement for creating threads). The proposal received no support, however, with Adam pointed towards `Stackless Python`_ and greenlets from `the Py lib`_ as similar solutions that do not require modification of the language. `PEP 342`_ was also touted as a solution - the PEP includes a short (<50 lines) cooperative threading example. .. _Stackless Python: http://www.stackless.com/ .. _the Py lib: http://codespeak.net/py .. _PEP 342: http://www.python.org/peps/pep-0342.html Contributing Thread: - `Adding Python-Native Threads `__ [TAM] ------------------------------ Syntax for ignoring exceptions ------------------------------ Dmitry Dvoinikov proposed a shorthand for ignoring exceptions:: ignore TypeError: do stuff [else: do other stuff] which would replace:: try: do stuff except TypeError: pass [else: do other stuff] Most people seemed to think that generally the except and/or else clauses would be non-trivial, so the savings of two lines were not really worth the complications to the language. Contributing Thread: - `Explicitly declaring expected exceptions for a block `__ [SJB] ---------------------------------- Proposed new serialization format. ---------------------------------- Simon Wittber proposed a pre-PEP for `RFE 46738`_, to provide a safe, documented class for serialization of simple python types; however, many people commented that they felt that there were already sufficient serialization formats. Simon felt that they were all slow, bloated or unsafe, but wasn't able to convince anyone that there was a need for a new format. .. _RFE 46738: http://python.org/sf/467384 Contributing Thread: - `PEP for RFE 46738 (first draft) `__ [TAM] --------------------------------------- Behavior of subprocess.call(stdin=PIPE) --------------------------------------- In a followup to a `sourceforge patch`_, Stuart Bishop asked that subprocess.call() close the input stream if it receives the keyword argument stdin=PIPE. Since subprocess.call() creates a process and waits for it to complete before returning, the stdin pipe is never available to the caller and thus can never be written to while the process is running. Stuart suggested that if subprocess.call() closed the input stream when stdin=PIPE, subprocesses that incorrectly read from stdin would break out with an error immediately instead of hanging. While people seemed to agree that the current behavior of subprocess.call(stdin=PIPE) was mildly undesirable, there was disagreement as to the solution. Michael Chermside suggested that subprocess.call(stdin=PIPE) should raise an exception, while Peter ?strand felt that keeping the subprocess.call() wrapper around subprocess.Popen() as simple as possible spoke against complicating it with error checking code. .. _sourceforge patch: http://www.python.org/sf/1220113 Contributing Thread: - `subprocess.call() and stdin `__ [SJB] =============== Skipped Threads =============== - `getch() in msvcrt does not accept extended characters. `__ - `Terminology for PEP 343 `__ - `List copy and clear (was Re: Inconsistent API for sets.Set and build-in set) `__ - `Multiple expression eval in compound if statement? `__ - `refcounting vs PyModule_AddObject `__ - `Some RFE for review `__ - `Please spread the word about OSCON early reg deadline `__ - `New python developer `__ - `Possible C API problem? `__ - `PyPI: no space left on device `__ - `PySWT -- Python binding of SWT using GCJ + SIP `__ - `Subclassing in 'C' `__ - `is type a usable feature? `__ - `misplaced PEP `__ - `using pyhon from the MSYS shell `__ - `[Python-checkins] python/dist/src/Lib Cookie.py, 1.17, 1.18 `__ - `[Python-checkins] python/dist/src/Tools/bgen/bgen bgenGenerator.py, 1.17, 1.18 bgenObjectDefinition.py, 1.29, 1.30 bgenType.py, 1.15, 1.16 bgenVariable.py, 1.6, 1.7 scantools.py, 1.37, 1.38 `__ - `floatobject.c 2.136 `__ ======== Epilogue ======== ------------ Introduction ------------ This is a summary of traffic on the `python-dev mailing list`_ from June 16, 2005 through June 30, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the sixth summary written by the python-dev summary cabal of Steve Bethard, Tim Lesher, and Tony Meyer. To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tim Lesher (tlesher at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. I do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow me to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/ .. _original text file: http://www.python.org/dev/summary/2005-06-16_2005-06-30.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From brenNOSPAMbarn at NObrenSPAMbarn.net Mon Jul 4 03:09:46 2005 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Mon, 4 Jul 2005 07:09:46 +0000 (UTC) Subject: math.nroot [was Re: A brief question.] References: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> Message-ID: Tom Anderson wrote: > Yes. However, it's an excellent reason why python's precedence > rules are wrong - in conventional mathematical notation, the unary > minus, used to denote the sign of a literal number, does indeed > have higher precedence than exponentiation: -1^2 evaluates to 1, > not -1. This isn't true. The "unary minus operator" is just a shorthand for multiplication by -1. As such, it has the same operator precedence as multiplication. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From steven.bethard at gmail.com Sat Jul 9 00:25:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Jul 2005 22:25:20 -0600 Subject: python-dev Summary for 2005-06-16 through 2005-06-30 In-Reply-To: <42cf2b4f.165770875@news.oz.net> References: <42cf2b4f.165770875@news.oz.net> Message-ID: Bengt Richter wrote: > On Fri, 8 Jul 2005 18:15:37 -0600, Steven Bethard wrote: > >>[The HTML version of this Summary is available at >>http://www.python.org/dev/summary/2005-06-16_2005-06-30.html] > > Not when I just looked, but maybe it takes a while ;-) Yes, sorry, we're still in the transition period at this point. It means that I can't make any commits, so the HTML versions will typically take a bit longer to appear than the ones mailed to the python-list. Sorry for the inconvenience! STeVe From sjmachin at lexicon.net Mon Jul 25 09:16:11 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 25 Jul 2005 23:16:11 +1000 Subject: Getting a dictionary from an object In-Reply-To: References: <42e3fd9f$0$18620$626a14ce@news.free.fr> Message-ID: <42e4e61c@news.eftel.com> Dark Cowherd wrote: >>voiceless-ly'rs > > What does this mean?? Just curious (googled that and ly'rs and didnt > find anything relevant) The voiceless part I understand to mean that Bruno is "shocked and stunned and not a little bit amazed" [1] at Steven's masterstroke which came out of the blue and trumped all previous efforts -- a true "deus ex machina", a thunderbolt from Olympus -- or if you want a one-word colloquialism, he's gobsmacked. The -ly'rs part means that in his shocked state he has tried to emulate the timbot's characteristic sign-off [2], but failed to get the syntax correct. [1] Billy Connolly [2] http://www.python.org/tim_one/ ... or just check out a few postings by Tim Peters in this newsgroup. From michele.simionato at gmail.com Wed Jul 27 04:49:20 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Jul 2005 01:49:20 -0700 Subject: multiple inheritance super() In-Reply-To: <42e748e9$0$32207$626a14ce@news.free.fr> References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> <42e748e9$0$32207$626a14ce@news.free.fr> Message-ID: <1122454160.835071.87690@z14g2000cwz.googlegroups.com> >I am mostly >using old style (without type unification) init but this motivate the >shift for the new style. Is there somewhere a document about this? Yes, see http://www.python.org/2.3/mro.html by yours truly Michele Simionato From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 03:26:44 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 09:26:44 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: <3kjihkFubvl6U1@individual.net> Tony Meyer wrote: > [...] >> Open issues: > [...] >> What about path * 4? > > If you keep the current join meaning of __div__, then assigning any sort of > multiplication meaning to __mul__ would not be a good idea, IMO. It's > natural to expect that __div__ and __mul__ are opposites. I suppose this > means that you could make __mul__ mean split (and f(*tuple) does do > splitting of a sort), but I don't know what splitting by 4 would mean, > necessarily. Yes. I think I'll not attach any meaning to it. If used, it will have the same meaning as string * 4. > Do people really like using __div__ to mean join? On the python-dev > discussion, Just van Rossum spoke out against it, but there weren't (IIRC) > any other comments, either pro or con. I'm not too happy with it, too, but do we have alternatives? As paths are strings, we can hardly override the '+' operator, so there's not much operators left. Of course, one can use joinwith() if he doesn't like '/'. Reinhold From peter at engcorp.com Thu Jul 14 01:57:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 01:57:11 -0400 Subject: installing vrmlexport module ?? In-Reply-To: References: Message-ID: Titi Anggono wrote: > I've downloaded vrmlexport.py from: > http://www.andrew.cmu.edu/user/mzk/vrmlexport/ ... > File "vrmlexport.py", line 220, in export_box > if (new_axis.x!=0 or new_axis.y!=0 or > new_axis.z!=0): > UnboundLocalError: local variable 'new_axis' > referenced before assignment > =============================================== > > Are there any suggestion ? (note, I am very new to > python :) ) It's a bug. You should probably report it to the maintainer of that project, not just as you did here. Probably describing the conditions that led to that failure too (i.e. your input file, etc). -Peter From adityabhambri at yahoo.com Fri Jul 22 13:51:34 2005 From: adityabhambri at yahoo.com (adityabhambri at yahoo.com) Date: 22 Jul 2005 10:51:34 -0700 Subject: Using python to runother programs Message-ID: <1122054694.450950.216900@g44g2000cwa.googlegroups.com> HI guys, I am trying to automate some project work which the accounting dept of the company uses. They have to go through multiple steps to achieve the final goal. Is there some way that I can use python to automate these manual steps. I can give you an example. 1. run the crystal report using some ***.excel file 2. Store the output as *.txt file. 3. use accounting software and use the *.txt file (this step can be excluded) I don't know how to use python to run the crystal report and save the output as an txt file using python scripts. Is this even possible? Thanks. Sincerely, Aditya. From avera at coes.org.pe Fri Jul 15 09:37:39 2005 From: avera at coes.org.pe (Alberto Vera) Date: Fri, 15 Jul 2005 08:37:39 -0500 Subject: open a mail and... Message-ID: <000c01c58942$5e6632d0$1603a8c0@avc> Hello Is it possible to open a mail and download its files attached in a hard-disk using a python script? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVETHIScyber.com.au Tue Jul 12 12:23:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 02:23:29 +1000 Subject: Help with inverted dictionary References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> Message-ID: On Tue, 12 Jul 2005 08:25:50 -0700, rorley wrote: > OK, so my problem is I have a text file with all of these instances, > for example 5000 facts about animals. I need to go through the file > and put all of the facts (lines) that contain the word lion into a file > called lion.txt. If I come across an animal or other word for which a > file does not yet exist I need to create a file for that word and put > all instances of that word into that file. I realize that this should > probably create 30,000 files or so. Any help would be REALLY > appreciated. Thanks. Reece Sounds like homework to me... Start by breaking the big problem down into little problems: Step 1: read the data from the file You do that with something like this: data = file("MyFile.txt", "r").read() Notice I said *something like* -- that's a hint that you want to change that to something slightly different. Step 2: grab each line, one at a time Somehow you want to read lines (hint! hint!) from the file, so that you have a list of text lines in data. How do you read lines (hint!) from a file in Python? Once you do that, data should look something like this: ["lions are mammals\n", "lions eat meat\n", "sheep eat grass\n"] So you can work with each line in data with: for line in data: do_something(line) Step 3: grab each word from the line I'll make this one easy for you: words = line.split() words now looks like: ["lions", "are", "mammals"] Step 4: for each word, open a file: This one is also easy: for word in words: fp = file(word, "w") fp.write(all the other words) fp.close() Hint: this code won't quite do what you want. You need to change a few things. Does this help? Is that enough to get started? See how far you get, and then come back for more help. -- Steven. From Scott.Daniels at Acm.Org Sat Jul 9 20:21:26 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 09 Jul 2005 17:21:26 -0700 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: References: Message-ID: <42d06226$1@nntp0.pdx.net> Ralf W. Grosse-Kunstleve wrote: > My initial proposal > (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't > exactly get a warm welcome... > > And Now for Something Completely Different: > > class autoinit(object): > > def __init__(self, *args, **keyword_args): > self.__dict__.update( > zip(self.__autoinit__.im_func.func_code.co_varnames[1:], args)) > self.__dict__.update(keyword_args) > self.__autoinit__(*args, **keyword_args) Should be: class autoinit(object): def __init__(self, *args, **keyword_args): for name, value in zip(self.__autoinit__.im_func.func_code. co_varnames[1:], args): setattr(self, name, value) for name, value in keyword_args.items(): setattr(self, name, value) self.__autoinit__(*args, **keyword_args) Since using setattr will take care of any slots used in other classes. Not all data is stored in the __dict__. For example: class Example(autoinit): __slots__ = 'abc', def __autoinit__(self, a=1, abc=1): print a, abc a = Example(1,2) print a.__dict__ print a.a print a.abc --Scott David Daniels Scott.Daniels at Acm.Org From renmybiru at libero.it Mon Jul 4 04:48:55 2005 From: renmybiru at libero.it (Vittorio) Date: Mon, 4 Jul 2005 08:48:55 +0000 (UTC) Subject: email link and foreign accent References: <6f-dnTSTQazBSlvfRVn-jQ@powergate.ca> Message-ID: Peter Hansen wrote in news:6f-dnTSTQazBSlvfRVn- jQ at powergate.ca: > Vittorio wrote: >> print"""""" %(campovalore.encode('iso-8859-1')) >> print campovalore.encode('iso-8859-1') >> print """""" >> > It might help if you showed us the output of "repr(x)" where x is the > output of the campovalore.encode('iso-8859-1') part above. Thanks Peter for replying. This is an example of the output of repr(x) as you requested: 'carr\xe0 at pluto.it' Results: link opened from IE6->Outlook: it works link opened from IE6->Pocomail: it works link opened from Firefox->Outlook: characters with accent fail link opened from Firefox->Pocomail: characters with accent fail It looks like having to do more with Firefox than with Python itself but maybe someone can help anyway? vittorio From steve at REMOVETHIScyber.com.au Tue Jul 12 01:41:46 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 15:41:46 +1000 Subject: __eq__ on a dict References: Message-ID: On Mon, 11 Jul 2005 13:54:05 +0200, Aaron Bingham wrote: >> Two dicts are equal if they have the same keys and the same values. > > That is what I would expect, but where is that documented? Also, > where is the behavior of the much less obvious dictionary methods > __ge__, __gt__, __le__, __lt__, and __cmp__ methods documented? > >> In general, you should not call __eq__ directly, but use the == operator >> instead. > > That is clear enough, the OP was seeking information about the > behavior of these operators when used with dictionaries. That wasn't clear from his post at all. If he had explained what he wanted, I wouldn't have wasted my time explaining what he already knew. You know, something like "I already know that __eq__ is equivalent to ==, likewise for the other operators > etc, what I want to know is how are equality, less than, greater than, etc implemented specifically for dicts." Asking the right question helps. But not in this case, because comparison of objects is ... confusing. There doesn't seem to be any definitive answer to the question, not that I have been able to find, although plenty of hints. My first thought was the comparisons between dicts is implemented as comparisons between their items, ie cmp(dictA, dictB) is turned into cmp(dictA.items(), dictB.items()). But that doesn't seem to be the case: py> dictA = {None: None, 1:1} py> dictB = {1: 1} py> cmp(dictA, dictB) 1 py> cmp(dictA.items(), dictB.items()) -1 My second thought was that comparison is implemented by first comparing keys, then values, ie cmp(dictA, dictB) turns into: order = cmp(dictA.keys(), dictB.keys()) if order == 0: # keys are equal order = cmp(dictA.values(), dictB.values()) return order I don't think I can prove it though. -- Steven. From Scott.Daniels at Acm.Org Wed Jul 13 11:54:19 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 13 Jul 2005 08:54:19 -0700 Subject: Building a function call? (update) In-Reply-To: References: <42D50A88.3070909@gmx.net> Message-ID: <42d53131$1@nntp0.pdx.net> Francois De Serres wrote: > Francois De Serres wrote: >> Having a string: "dothat" >> and a tuple: (x, y) >> 1. What's the best way to build a function call like: dothat(x,y)? >> >> Assuming dothat is def'd in the same module, >> 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) >> the right way to have it executed? You do know that you could do something like: result = eval('dothat')(100, 200) That is, eval of the function name gives you a function. --Scott David Daniels Scott.Daniels at Acm.Org From eric_brunel at despammed.com Thu Jul 7 03:38:32 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 07 Jul 2005 09:38:32 +0200 Subject: Tkinter grid layout References: Message-ID: On Wed, 06 Jul 2005 16:32:42 GMT, William Gill wrote: > Excuse me for intruding, but I followed examples and ended up with a > similar architecture: > > from Tkinter import * > class MyMain(Frame): > def __init__(self, master): > self.root = master > self.master=master > root = Tk() > app = MyMain(root) > app.master.title("Object Editor") > root.mainloop() > > Erick, are you saying it should be modified to something like : > > from Tkinter import * > class MyMain(Tk): > ... > ... > app = MyMain() > app.title("My App") > app.mainloop() Well, basically, that's what I'm saying; but your example is a bit better than the OP's. Basically, the problem is that an instance of MyMain will just be some kind of graphical component that can be inserted into basically anything. So nothing prevents me to do for example: root = Tk() Label(root, text='This is my application').pack(side=TOP) frm = Frame(root) frm.pack(side=TOP) app = MyMain(frm) # You don't show where you pack or grid your MayMain instance in its # parent, so I'm doing it explicitely here... app.pack() root.mainloop() So the container for MyMain is a Tk instance in your example, and a Frame instance in mine. And it works, because it's basically the use case for Frame sub-classes: they can be pack'ed or grid'ed or place'd into anything. So MyMain cannot make any assumption on its container (self.master in your first example), since it can be any valid container. So there are many things that you just can't do in MyMain, because you don't have a window. For example, you can't set the window title, or define a menu bar, since all these are defined via methods only available on windows, i.e. Tk or Toplevel instances. Basically, you did this right, since you call app.master.title(...) in the main script, where you know that app.master is a Tk instance. But what can be the reason to do it *outside* MyMain? Isn't it the window itself that knows what title it should have? So in your second version, you can do: from Tkinter import * class MyMain(Tk): Tk.__init__(self) self.title("My App") ... ... app = MyMain() app.mainloop() And this always works: since an instance of MyMain is an instance of Tk, you do have a window on which to call title. Note that this cannot be safely done in your first version, since self.master may not have a title method (see my example above). So you should really stick to the following rules: - If you write a class defining the main window for your application, make it inherit from Tkinter.Tk - If you write a class defining a "secondary" window for your application, make it inherit from Tkinter.Toplevel - If you write a class defining a graphical component that can be placed anywhere in a GUI, make it inherit from Tkinter.Frame This is basically just a matter of good OO programming: you should choose the most accurate super-classes for the classes you define, or someday, you'll run into problems... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From eurleif at ecritters.biz Wed Jul 6 23:44:35 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 07 Jul 2005 03:44:35 GMT Subject: Use cases for del In-Reply-To: <11cp7fusjoid468@corp.supernews.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> <11cp7fusjoid468@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-07-07, Leif K-Brooks wrote: >>_NOVALUE = object() >>class demo: >> def foo(v=_NOVALUE): >> if v is _NOVALUE: >> return self.v >> else: >> self.v = v > > > Apart from the change in the logic such that the set operation > doesn't return a value, how is that any different? You're just > creating your own non-integer-value "None" object instead of > using the one built in to the language. Sorry, my mistake: for some reason, I misunderstood your message as complaining that you couldn't do the same thing if you needed None to be usable as a value too. >>But what's wrong with properties? > > Huh? Why not use a property (http://www.python.org/2.2.1/descrintro.html#property) instead of a special property-like method? From ujelin at yahoo.com Tue Jul 12 11:46:38 2005 From: ujelin at yahoo.com (ulrice jardin) Date: Tue, 12 Jul 2005 08:46:38 -0700 (PDT) Subject: automatic form filling Message-ID: <20050712154638.80392.qmail@web60323.mail.yahoo.com> hi, I would like to know how I could automatically fill a (search) form on a web page and download the resulting html page. More precisely I would like to make a program that would automatically fill the "Buscador lista 40" (in spanish, sorry) form in the following webpage: http://www.los40.com/actualidad/listas/lista40.html and download the results for several dates (dia/mes/a?o = day/month/year). I am not sure this is the right place to ask, but I would be very grateful if anybody can help or redirect me to another mailing list... thx jul __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From nethawg1 at verizon.net Mon Jul 18 12:54:47 2005 From: nethawg1 at verizon.net (windozbloz) Date: Mon, 18 Jul 2005 16:54:47 GMT Subject: Python scripts wont run - HELP References: <42dbd734_2@x-privat.org> Message-ID: Damjan wrote: > >> I'm a fairly literate windoz amateur programmer mostly in visual basic. I >> have switched to SuSE 9.2 Pro and am trying to quickly come up to speed >> with Python 2.3.4. I can run three or four line scripts from the command >> line but have not been able to execute a script from a file. >> >> I have used EMACS and JEDIT to create small test routines. I would right >> click the file and set properties to executable. I would then click the >> icon, the bouncy ball would do its thing then a dialog box would flash on >> the screen for a fraction of a second. I could tell it had a progress >> bar >> on it but could not catch anything else on it. Then nothing else would >> happen. >> >> If I could execute a script the world would once again be my >> playground... PLEASE HELP. > > Open a terminal program like "konsole". > change the directory to where your files are ("cd /path/to/files/"). > execute them ("python my-script.py'). > > THANK YOU THANK YOU THANK YOU It now works from the command line like you said. Shouldn't I also be able to 'click' an icon that has been set to executable and launch the whole process that way? Doug -- LINUX protects me from the GATES of hell !!! From mensanator at aol.com Wed Jul 6 13:32:22 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 6 Jul 2005 10:32:22 -0700 Subject: precision problems in base conversion of rational numbers In-Reply-To: <1120642550.714547.256540@z14g2000cwz.googlegroups.com> References: <42C91973.6090208@po-box.mcgill.ca> <200507051049.37103.hancock@anansispaceworks.com> <1120642550.714547.256540@z14g2000cwz.googlegroups.com> Message-ID: <1120671142.077815.269630@g49g2000cwa.googlegroups.com> Raymond Hettinger wrote: > [Terry Hancock] > > > Needless to say, the conventional floating point numbers in Python > > > are actually stored as *binary*, which is why there is a "decimal" > > > module (which is new). > > > > > > If you're going to be converting between bases anyway, it probably > > > makes little difference whether you are using the decimal module > > > or not, of course. You'll have the same problems the conventional > > > float numbers do. > > Not really. floats won't do because they may not have sufficient > precision to differentiate rational values falling close the split > between representable values in a given base. The decimal module > offers arbitrarily large precision for making sure the error-term is > small enough to not make a difference. > > > > [Brian van den Broek] > > Thanks. mensanator provided the actual formula for my case. I had a > > "magic number" in my code by which I multiplied my desired level of > > "number of places in the representation" to obtain the value for > > decimal.getcontext.prec. > > > > mensanator wrote: > > > > > The value you want for x is log(17)/log(10) = > > > 1.2304489213782739285401698943283 > > > > where x was my "magic number". I've not had a chance to think it > > through yet, but I feel confident that given the formula, I'll be able > > to work out *why* that is the formula I need. > > That "formula" just gives a starting point estimate. The required > decimal precision may be much higher. If the rational falls very close > to the half-way point between two representable numbers, the > calculation needs to be retried with increased precision until the > split-point is definitive (when the error-term becomes less than the > distance to the next representable value). > > For a simple example, convert both 10247448370872321 and > 10247448370872319 from base ten to 4 digits of hex. The calculations > need to be carried out to 15 places of hex (or 17 places of decimal) > just to determine whether the fourth hex digit is a 7 or 8: > > >>> hex(10247448370872321) > '0x24680000000001L' > >>> hex(10247448370872319) > '0x2467ffffffffffL' I don't understand your simple example. log(10)/log(16) = 0.83048202372184058696757985737235 Multiplying by the number of decimal digits (17) gives 14.11819440327128997844885757533 Rounding up to an integer digit count, we need need 15 hex digits. Isn't that exactly what you concluded? Where does that 4 hex digit stuff come from? > > For an example of using decimal with iteratively increasing precision, > see the dsum() recipe at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 . > > > Raymond From bokr at oz.net Sat Jul 30 17:09:51 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Jul 2005 21:09:51 GMT Subject: functions without parentheses References: <42e9c49b.24281464@news.oz.net> Message-ID: <42ebec8a.165576266@news.oz.net> On Sat, 30 Jul 2005 08:14:16 +0100, zen19725 at zen.co.uk (phil hunt) wrote: >On Fri, 29 Jul 2005 06:37:52 GMT, Bengt Richter wrote: >> >>I suggested in a previous thread that one could support such a syntax by >>supporting an invisible binary operator between two expressions, > >That's a truely appalling idea. > >>so that >>examine "string" translates to examine.__invisbinop__("string") if >>examine as an expression evaluates to an object that has a __invisbinop__ method. >> >>Then you wouldn't define examine as a function, you would define it as an instance >>of a class like >> class Examine(object): >> define __invisbinop__(self, other): >> #...whatever >> examine = Examine() >>and then >> examine "string" > >Pass the sick bucket. > LOL ;-) Regards, Bengt Richter From peter at engcorp.com Tue Jul 5 19:56:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Jul 2005 19:56:34 -0400 Subject: adding a character to the last string element of a list In-Reply-To: References: Message-ID: <-rOdncUnLNafg1bfRVn-qw@powergate.ca> Philippe C. Martin wrote: > l = ['ABCDE','FGHI'] Okay so far... > l[1:] #returns ['FGHI'] Which is a _copy_ (via slicing) of part of the list. Another way of saying this is that it is a _new_ list which has a copy of the references from the appropriate part of the old list. Try "l[1:] is l[1:]" to prove that... > l[1:][0] #return 'FGHI' Sure does. From the new list. > a = l[1:][0] + 'J' #a becomes 'FGHIJ' Because you are actually storing a reference to the new list, whose first element you have modified. > l[1:][0] += 'J' #NO ERROR BUT l[1:][0] == 'FGHI' You are modifying the first element of the *copy* of the slice of the list, but you don't ever store a copy of it. When you try to check what happened with the second part, you are creating yet another copy of part of the list and sure enough the original has never been changed. > What am I missing ? That slicing makes copies. If you directly access the element in the first list (without using a slice) it will work. (I think I've got most of the correct...) -Peter From http Thu Jul 14 03:19:24 2005 From: http (Paul Rubin) Date: 14 Jul 2005 00:19:24 -0700 Subject: extend for loop syntax with if expr like listcomp&genexp ? References: <42d30319.417620065@news.oz.net> <42d30af1$1@news.eftel.com> <42d31b7a.423861700@news.oz.net> Message-ID: <7xzmsp3ldv.fsf@ruckus.brouhaha.com> Terry Hancock writes: > But of course that's not equivalent. It's hard to imagine a > use case for an enumerated loop when the object being > iterated over is anonymous (will be lost as soon as the loop exits). Huh? Not at all. print 'List of Python fans:' for i,x in enumerate([p for p in people if p.favorite_language == 'Python']): print '%d. %s'% (i, x.name) From rdsteph at mac.com Thu Jul 14 09:40:49 2005 From: rdsteph at mac.com (rdsteph at mac.com) Date: 14 Jul 2005 06:40:49 -0700 Subject: Python Newbie In-Reply-To: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> References: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> Message-ID: <1121348449.883655.53650@g47g2000cwa.googlegroups.com> You might want to take a look at my page listing over 200 pythonic tutorials by category. http://www.awaretek.com/tutorials.html linuxfreak wrote: > Hi all, > I came accross this article by Eric Raymond in which he has sung > peans about the python language. Well that has whetted my appetite... > So I decided to get down and dirty. But alas I got down but not dirty.. > i cant seem to find a good tutorial to help me get started. Whats the > next best thing to do? Ask the pros and where do you find them...in a > mailing list of course. So heres me asking if anyone has any pointers > to some good basic python tutorial. Something that teaches one to get > going. > Thanks a ton guys, > > > > Linuxfreak From philippe at philippecmartin.com Wed Jul 20 20:42:11 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 21 Jul 2005 00:42:11 GMT Subject: returning list of strings from Python COM to Visual basic 6 References: Message-ID: I can now pass and return quite a few types except object instances: my python code gets to the point where I do: def Get_Obj(self): ..... return an_object My VB code looks like Dim obj as Variant obj = acom.Get_Obj() I get an "unexpected Python error ..... Objects of type 'instance' can not be converted to a COM VARIANT" Is there a way out ? Thanks, Philippe Philippe C. Martin wrote: > Hi, > > Is it possible ? > > ex: return ['1','2'] > > If so which type should I use in VB ? > > dim res as ??????? > > Set testObj = CreateObject("xxxx") > > res = testObj.AMethodThatReturnsAListOfStrings() > > > Thanks, > > Philippe From mark.english at liffe.com Mon Jul 18 11:04:11 2005 From: mark.english at liffe.com (MarkE) Date: 18 Jul 2005 08:04:11 -0700 Subject: Windows command line problem Message-ID: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> I'm sure someone else has posted a similar problem but I can't find it, nor the solution... I have a python script which accepts a command line argument. E.g. python.exe myscript.py -n Foo I build this as part of a package using distutils with the bdist_wininst option on a Windows 2K (SP4) machine. I have tested installing and running it fine on a Windows XP (SP2) machine. I build my package-installer with a Python.org 2.4.1 distribution which is source-compiled locally. I have installed my package-installer on a machine running ActiveState Python 2.4.1 installed from a .msi file. That all works fine. I have problems delivering it to the test team (of course). After some investigation, if I install the package on one of our test machines and butcher my installed file to dump the command line and exit (i.e. print 'hi', sys.argv) then I get the following: hi ['c:\\Python24\\Lib\\site-packages\\MyPackage\\myscript.py', '\x96n, 'Foo'] If I run it specifying --name instead of -n I get: hi ['c:\\Python24\\Lib\\site-packages\\MyPackage\\myscript.py', '\x96-name, 'Foo'] The machine in question is also running XP service pack 2 as far as I know, with Python.org's 2.4.1 distribution. Does anyone know why the first character on the command line (here '-') is getting adjusted (to '\x96') in this way ? Is it a Unicode/encodings kind of a problem ? I can make the problem go away by running with quotes like this: python.exe myscript.py "-n" Foo I'm hoping I can add an entry to my setup.py. Thanks for any and all help. Mark From peter at engcorp.com Mon Jul 4 09:43:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Jul 2005 09:43:40 -0400 Subject: python project layout In-Reply-To: References: <9JqdnRP9IqxM_ljfRVn-rA@powergate.ca> Message-ID: Huron wrote: > For instance, if you have several classes implementing the same interface > (say, doing the same things with different strategies), how would you > organize that in terms of files (modules) and directories (packages) ? A concrete example would probably help. What are you envisioning? From mwm at mired.org Fri Jul 1 13:42:10 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 13:42:10 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> Message-ID: <86irzu5sp9.fsf@bhuda.mired.org> "iK" writes: > Seems like he wants python programmers to solve their problems all in the > same way. While that is great for corporate slaves it is terrible for the > creative programmer. No, he wants Python to be Pythonic. TMTOWTDI is not Pythonic. > Python is quickly becoming the visual basic of the 21 century. If you want > to have fun while getting some work done you need to look elsewhere. It's a > shame... If you'd rather spend your time figuring out which of multiple ways to do things is the best for the job at hand than producing code, there's a language that makes TMTOWTDI a way of life. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tom at thebrownboys.net Sat Jul 2 19:44:33 2005 From: tom at thebrownboys.net (Tom Brown) Date: Sat, 02 Jul 2005 16:44:33 -0700 Subject: A brief question. In-Reply-To: References: Message-ID: <200507021644.34038.tom@thebrownboys.net> On Saturday 02 July 2005 10:55, Nathan Pinno wrote: > Brief question for anyone who knows the answer, because I don't. Is > there anyway to make Python calculate square roots? from math import sqrt From kay.schluehr at gmx.net Mon Jul 18 11:40:16 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jul 2005 08:40:16 -0700 Subject: goto References: Message-ID: <1121701216.092182.87990@g14g2000cwa.googlegroups.com> Hayri ERDENER schrieb: > hi, > what is the equivalent of C languages' goto statement in python? > best regards No, but some of goto's use cases can be covered by unconditional jumps provided by exceptions. Here is a C function using goto: void main() { int i, j; for ( i = 0; i < 10; i++ ) { printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 2; j++ ) { printf( " Inner loop executing. j = %d\n", j ); if ( i == 3 ) goto stop; } } /* This message does not print: */ printf( "Loop exited. i = %d\n", i ); stop: printf( "Jumped to stop. i = %d\n", i ); } And here is a Python equivalent using exception handling: def main(): class stop(Exception):pass try: for i in range(10): print "Outer loop executing. i = %d"%i for j in range(2): print " Inner loop executing. j = %d"%j if i == 3: raise stop print "Loop exited. i = %d"%i # message does not print except stop: print "Jumped to stop. i = %d"%i Regards, Kay From t-meyer at ihug.co.nz Sun Jul 31 21:08:06 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 1 Aug 2005 13:08:06 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > Yes, I read and understood it. Saying "Don't read this if > you don't want to be offended" doesn't make an offensive > statement inoffensive. No, but it makes complaining that it was offensive pointless. > I grant that Python is much easier to learn than other > programming languages; students can pick up the basics > rapidly. Once the basics are mastered and mentoring is over, > reliance on guess and intuition is not a substitute for > documentation, or for reading the code if documentation is > not available. Working with paths *is* the basics, especially since another strength of Python is as a form of shell script. > However, if > the intention here is to create something different from > Jason's original module, create something different and call > it by another name than path; don't attempt to guess "what > Jason really meant." It is not Pythonic to guess. I believe the intent here is to add an OO path object to the standard library. If the intent was to add Jason's path module to the standard library, then there would be no room for discussion about how it was. No doubt Reinhold can clarify the intent here. Certainly there will be times when what is suitable for a third-party module is not suitable for a standard library module. =Tony.Meyer From dan at cellectivity.com Tue Jul 26 10:48:52 2005 From: dan at cellectivity.com (Dan Richter) Date: Tue, 26 Jul 2005 15:48:52 +0100 Subject: Packages and modules Message-ID: <1122389340.20317.26.camel@localhost.localdomain> I'm trying to create a package+module structure, specifically a "test" package with all the unit tests. I'd like to have a package (directory) "test" that has various test modules, and I'd also like "test" itself to be a module that runs all the tests. Is this not possible? I created a directory called "test" with an __init__.py file that defines a variable __all__. That works, but no executable code in __init__.py is executed, even though "import test" seems to succeed. I have confirmed that it's not a naming conflict (i.e., there's not some other Python module also named "test"). -- I had picked out the theme of the baby's room and done other things. I decided to let Jon have this. - Jamie Cusack (of the Netherlands), whose husband Jon finally talked her into letting him name their son Jon 2.0 From http Sat Jul 30 18:20:42 2005 From: http (Paul Rubin) Date: 30 Jul 2005 15:20:42 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> <3l1blnF10c1i9U1@individual.net> <7xr7dgnmiw.fsf@ruckus.brouhaha.com> Message-ID: <7xvf2sszph.fsf@ruckus.brouhaha.com> Peter Hansen writes: > > sign_of_a = ternary{a < 0, -1, 1} > > I'd consider this an interesting idea if it weren't for the fact that > (at least with the fonts I generally use) I can barely make out the > difference between the {} and the () above. Ok, how about an escaped paren: sign_of_a = ternary\(a < 0, -1, 1) From mikej at well.com Wed Jul 27 05:01:42 2005 From: mikej at well.com (Michael Josephson) Date: Wed, 27 Jul 2005 10:01:42 +0100 Subject: [OT] Problems with permissions etc References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: <60jee15bc5d7eihs0gf56dd49lq3sbl5df@4ax.com> Hi, On 27 Jul 2005 00:36:37 -0700, "Frank Millman" wrote: >Alternatively, there >may be a better way of getting the mac address or identifying the >workstation. As Paul pointed out you should not rely on the MAC address as a secure identifier. However, if it's suitable for your purposes you might want to take a look at libdnet (http://libdnet.sourceforge.net/) which is a library that provides access to low level networking routines. Hope this helps, -Michael From sp1d3rx at gmail.com Tue Jul 19 18:43:25 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 19 Jul 2005 15:43:25 -0700 Subject: How to send a query to the browser from time to time? In-Reply-To: References: <1121778228.962141.70680@f14g2000cwb.googlegroups.com> Message-ID: <1121813005.393406.302980@f14g2000cwb.googlegroups.com> rewrite the server to bake a /lastmsg/ folder with the last message in it. otherwise, my only suggestion is to use another protocol instead of http. From dotpyFE at gmail.com Wed Jul 6 08:55:27 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Wed, 06 Jul 2005 12:55:27 GMT Subject: VBR mp3 length In-Reply-To: References: Message-ID: <3xQye.5306$aY6.2161@newsread1.news.atl.earthlink.net> No One wrote: > Hello all, > If this isn't the correct newsgroup, please redirect me. > > I'm trying to extract the song length from variable bit rate mp3's. > Does anyone know of a library or bit of code that will do this? I've > tried pymad, but it seems to grab the bitrate of the first frame and > then apply that to the the file length to come up with a total length. > Needless to say, if the bitrate of the first frame isn't close to the > overall average, it's wildly off. > > Thanks, > -Steve Take a look at http://pymedia.org. -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From jdennett at acm.org Sun Jul 3 16:07:57 2005 From: jdennett at acm.org (James Dennett) Date: Sun, 03 Jul 2005 13:07:57 -0700 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> Message-ID: <8AXxe.3186$HV1.2814@fed1read07> Tom Anderson wrote: > On Sun, 3 Jul 2005, George Sakkis wrote: > >> "Tom Anderson" wrote: >> >>>>> And finally, does Guido know something about arithmetic that i >>>>> don't, or >>>>> is this expression: >>>>> >>>>> -1.0 ** 0.5 >>>>> >>>>> Evaluated wrongly? >>>> >>>> >>>> No, it is evaluated according to the rules of precedence. It is >>>> equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which >>>> fails as expected. >>> >>> >>> Ah. My mistake. I submit that this is also a bug in python's grammar. >>> There's probably some terribly good reason for it, though. >> >> >> How about 'conformance with standard mathematic notation', does this >> count for a terribly good reason? > > > Yes. However, it's an excellent reason why python's precedence rules are > wrong - in conventional mathematical notation, the unary minus, used to > denote the sign of a literal number, does indeed have higher precedence > than exponentiation: -1^2 evaluates to 1, not -1. No... that would mean that -x^2 == x^2 always, and we certainly expect the lhs to always be negative or zero (for real x), and the rhs to be non-negative. Unary minus has lower precendence than exponentiation, in conventional mathematics. You'll often see (-1)^n written in mathematics when we want the alternating sequence +1, -1, +1, -1, ..., as -1^n wouldn't do it (giving -1, -1, -1, -1). -1^n evaluates to -1, for all non-zero integral n. > >> What would one expect to be the result of 5^2 - 2^2, 29 or 21? > > > 21. True, unambiguously; there are no negative numbers involved at any time, just a simple binary minus. > >> Would you expect 5^2 + - 2^2 to be different, even if you write it as >> 5^2 + -2 ^ 2 ? > > > Yes: 5^2 + -2^2 is 29, however you write it. *If* you take -2 as a number, but not if you take the number as 2 and the unary minus as an operator with lower precedence than exponentiation. > >> White space is not significant in math AFAIK ;-) > > > No, but there's a very big difference between unary and binary minus. Not in this respect. However, the question is whether that's a unary -, which binds lower than exponentiation in most systems, or part of the negative number minus 2. -- James From bokr at oz.net Sat Jul 9 11:02:02 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 15:02:02 GMT Subject: removing list comprehensions in Python 3.0 References: <78huc11mgkvn1sho01qegi221k7hhc5u1p@4ax.com> <42cf6d0d.182600044@news.oz.net> Message-ID: <42cfe57b.213430837@news.oz.net> On Sat, 09 Jul 2005 10:16:17 -0400, Peter Hansen wrote: >Bengt Richter wrote: >> On Fri, 08 Jul 2005 22:29:30 -0600, Steven Bethard wrote: >>>(1) There's no reason to get uncomfortable even if they're removed. >>>You'd just replace [] with list(). >> >> So list(1, 2, 3) will be the same as [1, 2, 3] ?? > >No, the discussion is about list comprehensions. [1,2,3] is not a list >comprehension, as you know. > D'oh. Sorry to have come in from contextual outer space ;-/ Regards, Bengt Richter From rkern at ucsd.edu Fri Jul 1 11:37:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 01 Jul 2005 08:37:39 -0700 Subject: missing cephes module In-Reply-To: <20050701152438.5323.qmail@web51108.mail.yahoo.com> References: <20050701152438.5323.qmail@web51108.mail.yahoo.com> Message-ID: Justin wrote: > When I used py2exe to create executable file, "cephes" module missing > error occurred. > I have installed python 2.3 and scientific and numeric python. > Can anybody suggest me how to resolve the problem? scipy uses a lazy import mechanism. IIRC, without some help, py2exe's dependency inference won't pick up scipy's subpackages. Please consult py2exe's documentation on how to force it to include all of scipy and not rely on the default inference. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Thu Jul 28 14:00:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Jul 2005 14:00:17 -0400 Subject: Adding code and methods to a class dynamically In-Reply-To: References: Message-ID: Sarir Khamsi wrote: > I have a class (Command) that derives from cmd.Cmd and I want to add > methods to it dynamically. I've added a do_alias() method and it would > be nice if I could turn an alias command into a real method of Command > (that way the user could get help and name completion). The code would > be generated dynamically from what gets passed to the do_alias() > method. I've tried looking in the Python cookbook and have tried: > > def funcToMethod(func, clas, method_name=None): > setattr(clas, method_name or func.__name__, func) > > class Command(object, cmd.Cmd): > # ... > def do_f1(self, rest): print 'In Command.do_f1()' > def do_alias(self, rest): > rest.strip() # remove leading and trailing whitespace > pat = re.compile(r'^(\w+)\s+(\w+)$') > mo = pat.search(rest) > if mo: > newName = mo.group(1) > existingName = mo.group(2) > code = 'def do_' + newName + '(self, rest):\n' > code += ' self.do_' + existingName + '(rest)\n' > exec code > funcToMethod(getattr(newModule, 'do_' + existingName), > self, > 'do_' + 'existingName') > else: > print 'Invalid alias command' > > but this does not seem to work. If it's truly just an alias you want, then something like this should work better. Replace everything in the if mo: section with this: if mo: newName = mo.group(1) existingName = mo.group(2) existingMethod = getattr(self, 'do_' + existingName) setattr(self, 'do_' + newName, existingMethod) -Peter From giles_brown at hotmail.com Thu Jul 7 08:56:29 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 7 Jul 2005 05:56:29 -0700 Subject: Windows Cmd.exe Window Message-ID: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> For my sins I'm a MS Windows user at work and apart from that I have a small problem ... I like to write python scripts to do small tasks and then double click on them from the file explorer to run them. Unfortunately I'm not perfect and sometimes I make mistakes and have unhandled exceptions or syntax errors when running the scripts. The default behaviour is to shut down the command window which leaves you no chance of reading the exception. In the past I have created .bat wrapper files that just call the python interpreter, but it is a bit tedious to have to create a matching .bat file for every script. So I came up with the following approach... 1. Copy python.exe to pythoncmd.exe 2. Add a bit of stuff to sitecustomize.py 3. Add a special first line to every python script and give it a .cmd extension. The stuff added to sitecustomize.py (actually I created a sitecustomize.py for this) is: """ import sys import os if os.path.basename(sys.executable) == 'pythoncmd.exe': def cmdexcepthook(*args): sys.__excepthook__(*args) # Let use confirm/inspect error os.system('pause') sys.excepthook = cmdexcepthook """ The special first line is: @pythoncmd -x "%~f0" %* & exit /b (In the python.org FAQ for windows it says @setlocal enableextensions & python -x %~f0 %* & goto :EOF but since I have no idea which is "right" I chose the simpler looking one) This approach does require pythoncmd.exe to by in your %PATH% but I think that is reasonable ;) I am a bit disappointed I couldn't think of a way of deciding if I was running a ".cmd" file in sitecustomize.py so that I could just use the normal python.exe. Using a renamed interpreter .exe is just a trick for detecting when I am running .cmd files, but it means that the script won't run on another machine that hasn't had the python.exe copied to pythoncmd.exe on it. Which is a shame. So my question. Is there a better way? I'm not really happy with this approach. Should I stop worrying and go and play my new ukulele? Answers please. Giles From peter at engcorp.com Sat Jul 30 13:48:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 13:48:17 -0400 Subject: string methods In-Reply-To: References: <3l1js6F10d0leU1@individual.net> Message-ID: Brian Beck wrote: > anthonyberet wrote: >>I know this touches on immutability etc, but I can't find string methods >>to return the first 3 characters, and then the last 2 characters, which >>I could concatenate with newchar to make a new string. > > As tiissa said, you want slicing: > > py> s = "foobar" > py> s[:3] > 'foo' > py> s[:3] + "B" + s[4:] > 'fooBar' And if that's too ugly for you and you think you need to do this operation a lot, just define a function to do it for you based on the index value and string that you pass in to it. -Peter From geon at post.cz Fri Jul 22 13:46:15 2005 From: geon at post.cz (geon) Date: Fri, 22 Jul 2005 19:46:15 +0200 Subject: return None In-Reply-To: <3kcpbbFtjttlU1@individual.net> References: <3kcpbbFtjttlU1@individual.net> Message-ID: Ximo wrote: > Can I do a function which don't return anything? > > The question is that, if I do a function that have a return or without > return, it returns always "None", but i want that it doesnt return me > nothing Nothing is None, or isnt? You probably print the function, what you neednt, of course. You can just call it: def x(): pass print x() # calling with printing x() # calling only x() prints really nothing, even not None ;-) -- geon Vyj?mka je pravidlo. Rekurzivn?. From rrr at ronadam.com Sun Jul 3 18:07:30 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 03 Jul 2005 22:07:30 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <42c83dec.443548208@news.oz.net> References: <42c83dec.443548208@news.oz.net> Message-ID: Bengt Richter wrote: > What if parameter name syntax were expanded to allow dotted names as binding > targets in the local scope for the argument or default values? E.g., > > def foometh(self, self.x=0, self.y=0): pass > > would have the same effect as > > def foometh(self, self.y=0, self.x=0): pass > > and there would be a persistent effect in the attributes of self > (whatever object that was), even with a body of pass. > > I'm not sure about foo(self, **{'self.x':0, 'self.y':0}), but if > you didn't capture the dict with a **kw formal parameter, IWT you'd > have to be consistent and effect the attribute bindings implied. > > (Just a non-thought-out bf here, not too serious ;-) > > Regards, > Bengt Richter Well it works the other way around to some degree. def foo(self, x=x, y=y):pass x=x binds the class variables to the arguments without the self. if no value is given. Which is kind of strange, since x by it self gives an error if no value is given. The strange part is x=x is not the same as just x. I understand why, but it still looks odd. Why isn't there a dict method to get a sub dict from a key list? Fromkeys doesn't quite do it. sub-dict = dict.subdict(key_list) Or have dict.copy() take a key list. (?) The following works and doesn't seem too obscure, although the x=x, etc.. could be annoying if they were a lot of long names. Seems like mutable default arguments is what's needed to make it work, not that it's needed IMO. But it's an interesting problem. def subdict(dict, keys): d = {} for k in keys: d[k] = dict[k] return d class foo(object): x = 1 y = 2 z = 3 def __init__(self,x=x,y=y,z=z): save_these = subdict(locals(),['x','y']) self.__dict__.update(save_these) # rest of code print self.x, self.y, self.z f = foo() f = foo(5,6,7) From williams13 at llnl.gov Wed Jul 27 15:41:05 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Wed, 27 Jul 2005 12:41:05 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050727191626.GC2272@tishler.net> References: <20050725201132.GA3440@tishler.net> <20050727191626.GC2272@tishler.net> Message-ID: <42E7E351.3030706@llnl.gov> Jason, Thanks for fixing this bug in Cygwin. Remember there was another undefined variable for the Python build _bsd... Best regards, Dean >On Mon, Jul 25, 2005 at 03:02:45PM -0700, williams13 at mail.llnl.gov wrote: > > >>Let me know when you have it solved. >> >> > >The problem has been fixed in Cygwin CVS: > > http://cygwin.com/ml/cygwin/2005-07/msg01257.html > http://cygwin.com/ml/cygwin-cvs/2005-q3/msg00046.html > > > >>In the meantime, I have a workaround. >> >> > >Unfortunately, you will have to live with your workaround until Cygwin >1.5.19 is released. :,( > >Jason > > > From Python.LeoJay at gmail.com Wed Jul 20 21:38:28 2005 From: Python.LeoJay at gmail.com (Leo Jay) Date: 20 Jul 2005 18:38:28 -0700 Subject: Newbie question about lists In-Reply-To: <7x4qap551r.fsf@ruckus.brouhaha.com> References: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> <1121908372.875767.321980@f14g2000cwb.googlegroups.com> <7x4qap551r.fsf@ruckus.brouhaha.com> Message-ID: <1121909908.439806.175200@o13g2000cwo.googlegroups.com> IMO, python should use the decimal for default. .25 is right for Decimal(".25"). isn't that better? From mwh at python.net Tue Jul 5 09:59:12 2005 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Jul 2005 13:59:12 GMT Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> Message-ID: "Terry Reedy" writes: > "Grant Edwards" wrote in message > news:11bja5bienakv68 at corp.supernews.com... > > I'm working on it. I should have said it's trivial if you have > > access to the platforms to be supported. I've tested a fix > > that supports pickle streams generated under Win32 and glibc. > > That's using the "native" string representation of a NaN or > > Inf. > > > > A perhaps simpler approach would be to define a string > > representation for Python to use for NaN and Inf. Just because > > something isn't defined by the C standard doesn't mean it can't > > be defined by Python. > > I believe that changes have been made to marshal/unmarshal in 2.5 CVS with > respect to NAN/INF to eliminate annoying/surprising behavior differences > between corresponding .py and .pyc files. Perhaps these revisions would be > relevant to pickle changes. If you use a binary protocol for pickle, yes. Cheers, mwh -- Java sucks. [...] Java on TV set top boxes will suck so hard it might well inhale people from off their sofa until their heads get wedged in the card slots. --- Jon Rabone, ucam.chat From tbr at nospam.nos Thu Jul 14 07:36:59 2005 From: tbr at nospam.nos (TechBookReport) Date: Thu, 14 Jul 2005 12:36:59 +0100 Subject: Python Newbie In-Reply-To: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> References: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> Message-ID: linuxfreak wrote: > Hi all, > I came accross this article by Eric Raymond in which he has sung > peans about the python language. Well that has whetted my appetite... > So I decided to get down and dirty. But alas I got down but not dirty.. > i cant seem to find a good tutorial to help me get started. Whats the > next best thing to do? Ask the pros and where do you find them...in a > mailing list of course. So heres me asking if anyone has any pointers > to some good basic python tutorial. Something that teaches one to get > going. > Thanks a ton guys, > > > > Linuxfreak > Take a look at Dive Into Python (http://diveintopython.org/), it's a great place to start (there's a review of it here: http://www.techbookreport.com/tbr0103.html). -- TechBookReport Programming: http://www.techbookreport.com/ProgIndex.html From bigfox at altern.org Sat Jul 30 07:45:13 2005 From: bigfox at altern.org (Nicolas Lebas) Date: Sat, 30 Jul 2005 13:45:13 +0200 Subject: getting Arrays and variables from R In-Reply-To: <42E62AC0.9050201@grignon.inra.fr> References: <42E62AC0.9050201@grignon.inra.fr> Message-ID: <42EB6849.9060708@altern.org> Finally i found the solution in Rpy-list : there is a bug in python2.4-rpy_0.4.1. An alternative solution which works fine it's to use the R get(str) function instead of using directly the variable (i.e r.tab) like that : r.get('tab') This bug is fixed in the rpy_0.4.6 release. Nicolas Lebas a ?crit : > hello, > > i don't know if this is the best list to send this question, but i'm > already trying to ask. > > I need to import variables from .RData files (arrays or variables). > I'm trying to use the rpy module, but without success beccause when i > try to access to a variable loaded from the .RData file i have a > segmentation fault ! > > This is what i'm doing : > - in R-projet, i create a .RData file with some variables : > > tab<-c(2,5,8,6) > > v<-0.5 > > save.image("file.RData") > > - in Python : > > from rpy import * > > r.load("file.RData") > ['tab', '.Traceback', 'v'] > > r.tab > segmentation fault ! > > I don't understand very well what does python crash. > > If someone has an idea to solve my problem or to give me a method which > permit to import arrays and variables from .RData files with another module. > > Thanks > > Nicolas From ntv1534 at gmail.com Tue Jul 5 19:42:10 2005 From: ntv1534 at gmail.com (MooMaster) Date: 5 Jul 2005 16:42:10 -0700 Subject: multiple checkboxes highlighted when one clicked = not good In-Reply-To: References: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> Message-ID: <1120606930.677363.22260@f14g2000cwb.googlegroups.com> right, I'm basically drawing a table with 3 columns, and I want checkboxes when we are at column 0. In columns 1-3 I will want Entries and Labels, but I always want checkboxes @ column 0. From andreas at kostyrka.org Sat Jul 2 11:43:22 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 02 Jul 2005 17:43:22 +0200 Subject: No subject In-Reply-To: References: <1120231547.928636.59270@g43g2000cwa.googlegroups.com> Message-ID: <1120319002.5745.1.camel@andi-lap> Am Samstag, den 02.07.2005, 15:11 +0100 schrieb Tom Anderson: > On Fri, 1 Jul 2005, Andreas Kostyrka wrote: > > > Am Freitag, den 01.07.2005, 08:25 -0700 schrieb George Sakkis: > > > >>> Again, how? Is there a way to force that an external user of my lib can > >>> not use my internal data/methods/classes, unless he uses odd compiler > >>> hacks? > >> > >> I never understood how mainstream OO languages expect the designer of a > >> class to know in advance that an attribute should be hidden or > >> unnecessary to its subclasses by being declared "private" instead of > >> "protected". > > > > The problem is, that the classic private/protected/public visibility > > tags try to solve multiple problems. > > > > Private: Ok, that's all that's really only for the implementation. > > public: Well, that's all for my "customers". Hmm. What if I've got two > > kinds of customers? Say a customer like in bank customer, and second > > customer that plays the role of the bank employee? oops. > > C++ has 'friend' for that: > > http://www.cplusplus.com/doc/tutorial/tut4-3.html Well, than you have to know who your friend is, don't you? And my friend comes on "private" term, doesn't he? *g* Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From benji at benjiyork.com Sun Jul 31 21:31:05 2005 From: benji at benjiyork.com (Benji York) Date: Sun, 31 Jul 2005 21:31:05 -0400 Subject: Thaughts from an (almost) Lurker. In-Reply-To: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> References: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Message-ID: <42ED7B59.4070604@benjiyork.com> Paddy wrote: > Sometimes when reading c.l.p. I mentally stand off from what I have > been reading and get an odd feeling that 'WE ARE BEING TESTED'. That > someone else is purposefully posting a near repetitive post, or obvious > flame bait etc - not for the usual reasons, but to track the dynamics > af the replies. "Never attribute to malice that which can be adequately explained by stupidity." -- Benji York From bokr at oz.net Sun Jul 24 01:04:09 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 05:04:09 GMT Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> <42d985a0.367263667@news.oz.net> <7Lidnc4MB60sTUffRVn-pw@comcast.com> Message-ID: <42e3213f.996926885@news.oz.net> On Sun, 17 Jul 2005 15:42:08 -0600, Steven Bethard wrote: >Bengt Richter wrote: >> Thanks for the nudge. Actually, I know about generator expressions, but >> at some point I must have misinterpreted some bug in my code to mean >> that join in particular didn't like generator expression arguments, >> and wanted lists. > >I suspect this is bug 905389 [1]: > > >>> def gen(): >... yield 1 >... raise TypeError('from gen()') >... > >>> ''.join([x for x in gen()]) >Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in gen >TypeError: from gen() > >>> ''.join(x for x in gen()) >Traceback (most recent call last): > File "", line 1, in ? >TypeError: sequence expected, generator found > >I run into this every month or so, and have to remind myself that it >means that my generator is raising a TypeError, not that join doesn't >accept generator expressions... > >STeVe > >[1] http://www.python.org/sf/905389 That must have been it, thanks. Regards, Bengt Richter From ivanlan at pauahtun.org Mon Jul 18 12:55:42 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Mon, 18 Jul 2005 10:55:42 -0600 Subject: Image orientation and color information with PIL? References: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> Message-ID: <42DBDF0E.C380CB11@pauahtun.org> Hi All-- tvmaly at gmail.com wrote: > > Does anyone know if it is possible to determine if an image is > horizontal/vertical and color or black & white using the python image > library? I have been searching this news group and the information was > not all clear on this. > How are you going to determine the orientation of an image without sophisticated image analysis? I suspect Adobe Photoshop can do it, but I don't know for sure. You'd have to look for things like sky, or clouds, overcast sky, people's faces, and so on and so forth. It'd be cool to have this available in Python, but unless the F-bot is busier than I thought and working behind the scenes using his time machine, it's not there now. If you write it I'll use it;-) Color vs B&W ought to be easy, though, by analysing the color table, if there is one, and/or image mode. Check the PIL documentation. If you have only searched the newsgroup then you might have overlooked the docs. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From rrr at ronadam.com Sun Jul 3 21:36:29 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 04 Jul 2005 01:36:29 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sun, 03 Jul 2005 19:31:02 +0000, Ron Adam wrote: > > >>First on removing reduce: >> >>1. There is no reason why reduce can't be put in a functional module > > > Don't disagree with that. > > >>or >>you can write the equivalent yourself. It's not that hard to do, so it >>isn't that big of a deal to not have it as a built in. > > > Same goes for sum. Same goes for product, ... Each item needs to stand on it's own. It's a much stronger argument for removing something because something else fulfills it's need and is easier or faster to use than just saying we need x because we have y. In this case sum and product fulfill 90% (estimate of course) of reduces use cases. It may actually be as high as 99% for all I know. Or it may be less. Anyone care to try and put a real measurement on it? which doesn't have that many > common usages apart from calculating the geometric mean, and let's face > it, most developers don't even know what the geometric mean _is_. I'm neutral on adding product myself. > If you look back at past discussions about sum, you will see that there is > plenty of disagreement about how it should work when given non-numeric > arguments, eg strings, lists, etc. So it isn't so clear what sum should do. Testing shows sum() to be over twice as fast as either using reduce or a for-loop. I think the disagreements will be sorted out. >>2. Reduce calls a function on every item in the list, so it's >>performance isn't much better than the equivalent code using a for-loop. > > That is an optimization issue. Especially when used with the operator > module, reduce and map can be significantly faster than for loops. I tried it... it made about a 1% improvement in the builtin reduce and an equal improvement in the function that used the for loop. The inline for loop also performed about the same. See below.. >> *** (note, that list.sort() has the same problem. I would support >>replacing it with a sort that uses an optional 'order-list' as a sort >>key. I think it's performance could be increased a great deal by >>removing the function call reference. *** >> >> >>Second, the addition of sum & product: >> >>1. Sum, and less so Product, are fairly common operations so they have >>plenty of use case arguments for including them. > > Disagree about product, although given that sum is in the language, it > doesn't hurt to put product as well for completion and those few usages. I'm not convinced about product either, but if I were to review my statistics textbooks, I could probably find more uses for it. I suspect that there may be a few common uses for it that are frequent enough to make it worth adding. But it might be better in a module. >>2. They don't need to call a pre-defined function between every item, so >>they can be completely handled internally by C code. They will be much >>much faster than equivalent code using reduce or a for-loop. This >>represents a speed increase for every program that totals or subtotals a >>list, or finds a product of a set. > > I don't object to adding sum and product to the language. I don't object > to adding zip. I don't object to list comps. Functional, er, functions > are a good thing. We should have more of them, not less. Yes, we should have lots of functions to use, in the library, but not necessarily in builtins. >>>But removing reduce is just removing >>>functionality for no other reason, it seems, than spite. >> >>No, not for spite. It's more a matter of increasing the over all >>performance and usefulness of Python without making it more complicated. >> In order to add new stuff that is better thought out, some things >>will need to be removed or else the language will continue to grow and >>be another visual basic. > > Another slippery slope argument. Do you disagree or agree? Or are you undecided? >>Having sum and product built in has a clear advantage in both >>performance and potential frequency of use, where as reduce doesn't have >>the same performance advantage and most poeple don't use it anyway, so >>why have it built in if sum and product are? > > Because it is already there. Hmm.. I know a few folks, Good people, but they keep everything to the point of not being able to find anything because they have so much. They can always think of reasons to keep things, "It's worth something", "it means something to me", "I'm going to fix it", "I'm going to sell it", "I might need it". etc.. "Because it is already there" sound like one of those type of reasons. >>Why not just code it as a >>function and put it in your own module? > > Yes, let's all re-invent the wheel in every module! Why bother having a > print statement, when it is so easy to write your own: > > def myprint(obj): > sys.stdout.write(str(obj)) Yes, Guido wants to make print a function in Python 3000. The good thing about this is you can call your function just 'p' and save some typing. p("hello world") Actually, I think i/o functions should be grouped in an interface module. That way you choose the interface that best fits your need. It may have a print if it's a console, or it may have a widget if it's a gui. > Best of all, you can customize print to do anything you like, _and_ it is > a function. > > >> def reduce( f, seq): >> x = 0 >> for y in seq: >> x = f(x,y) >> return x > > > Because that is far less readable, and you take a performance hit. They come out pretty close as far as I can tell. def reduce_f( f, seq): x = seq[0] for y in seq[1:]: x = f(x,y) return x import time t = time.time() r2 = reduce(lambda x,y: x*y, range(1,10000)) t2 = time.time()-t print 'reduce builtin:', t2 t = time.time() r1 = reduce_f(lambda x,y: x*y, range(1,10000)) t2 = time.time()-t print 'reduce_f: ', t2 if r1!=r2: print "results not equal" >>> reduce builtin: 0.156000137329 reduce_f: 0.155999898911 >>> reduce builtin: 0.15700006485 reduce_f: 0.155999898911 >>> reduce builtin: 0.141000032425 reduce_f: 0.155999898911 >>But I suspect that most people would just do what I currently do and >>write the for-loop to do what they want directly instead of using lambda >>in reduce. > > That's your choice. I'm not suggesting we remove for loops and force you > to use reduce. Or even list comps. Just don't force me to use decorators! ;-) Nah, they're ok too, but it did take me a little while to understand their finer points. Cheers, Ron From steve at REMOVETHIScyber.com.au Sat Jul 30 13:59:40 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 03:59:40 +1000 Subject: Comparison of functions References: Message-ID: On Sat, 30 Jul 2005 16:13:22 +0000, Adriano Varoli Piazza wrote: > Steven D'Aprano ha scritto: > >> It was easy. I never once asked myself whether some complex number was >> greater or less than another, I just asked "which one comes first in a >> lexicographic sort?" >> >> The two questions are NOT the same, and it is an ugliness in an otherwise >> beautiful language that Python treats them as the same. >> >> Mathematically, 1 == 1.0 == 1+0j but in the dictionary "1" should sort >> before "1.0" which sorts before "1.0+0.0j". > > Because, of course, when I sort numbers the first thing I think of is > looking at the ascii table... Here I was, thinking maths was useful. > Sorting numbers "lexicographically" might make sense to you, but it's > totally unintuitive to me. For example, why or how would I guess that > "3-3j" is bigger (or smaller) than "3+3j"? 3-3j is NOT bigger than 3+3j, nor is it smaller. You said so yourself: "it's not possible to define an order that preserves the properties of arithmetical operations on complex numbers." Fortunately, when we sort a list, we don't care about preserving the properties of arithmetical operations, we just need to place each item in a known, non-arbitrary (or at least not too arbitrary) position. > You'll still want to sort complex numbers lexicographically. It'll still > have no meaning whatsoever, so you might as well leave the list > unsorted. Your mathematical purity does you great credit. Unfortunately, it is also quite impractical. I'll give you a real-world actual case where sorting complex numbers is important: "The Penguin Dictionary Of Curious and Interesting Numbers" by David Wells. Some few hundreds of numbers are listed, including i. Should Wells have listed those numbers in random unsorted order just to satisfy some purists who insist that placing i in the list makes sorting the other 399 entries meaningless? > You might think you sorted something. 100? 200? years of maths > say you didn't. Sorting is not just numeric ordering. There are many different collation systems, not just ordering numbers by their magnitude. Think about sorting guests around a dinner table: married couples next to each other, single people across from another single person of the opposite sex, children at the end of the table, babies next to their mother, Uncle Enno as far away from Aunt May as possible. It is a complicated algorithm, but it is still sorting (people, in this case, not numbers). I appreciate your strong feelings about not doing comparisons on complex numbers, but if you actually studied the mathematics of orderings sets, you would realise how silly it was to say that a century of mathematics says that I didn't sort a list. Mathematicians are fully aware that numeric sorting is just one way of many of sorting. Do you understand the difference between partial and total ordering, or weakly and strongly ordered? When you do understand them, come back and tell me again whether you still think lexicographic sorting has no meaning whatsoever. -- Steven. From peter at engcorp.com Sat Jul 2 23:48:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 23:48:54 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> <86irzu5sp9.fsf@bhuda.mired.org> Message-ID: Steven D'Aprano wrote: > On Fri, 01 Jul 2005 13:42:10 -0400, Mike Meyer wrote: >>No, he wants Python to be Pythonic. TMTOWTDI is not Pythonic. > > Too Many T--- Only Way To Do It? > > There Might Tangle One Way To Do It? > > T--- M--- Two Obvious Ways To Do It? > > Nope, sorry, still not getting it. If you were serious, Google would be a real good friend here, since the answer is in its first search result... without even having to click on the link! Heck, it even points you to the web site: http://tmtowtdi.com :-) -Peter From tim.golden at viacom-outdoor.co.uk Tue Jul 19 09:05:42 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 19 Jul 2005 14:05:42 +0100 Subject: Documentation bug: Python console behaviour changed Message-ID: <9A28C052FF32734DACB0A288A3533991044D2122@vogbs009.gb.vo.local> [Lucas Raab] | Peter Hansen wrote: | > Kay Schluehr wrote: | > | >> The documentation of the Python console behaviour is not correct | >> anymore for Python 2.4.1. At least for the Win2K system | I'm working on | >> 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. | >> | >> The Python interpreter tells me instead: | >> | >> | >>>>> quit | >> | >> | >> 'Use Ctrl-Z plus Return to exit.' | >> | >> Nah, 'Ctrl-Z' is now undo :-) | > | > | > Are you really using the console, started with the "Command | Prompt" icon | > from the Start Menu (or some equivalent)? And are you sure | you haven't | > installed something else that magically changed the | behaviour of Ctrl-Z? | > | > (I get the documented behaviour with Python 2.4.1, under Win XP.) | > | > -Peter | | I'm getting the same behavior as Kay. Usually means you have a readline package installed: I know that this one gives the effect described: http://sourceforge.net/projects/uncpythontools/ Don't know about this one: http://newcenturycomputers.net/projects/readline.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dan at nospam.com Thu Jul 7 18:33:43 2005 From: dan at nospam.com (Dan) Date: Thu, 07 Jul 2005 17:33:43 -0500 Subject: import Help Needed - Newbie Message-ID: Hi I am trying to learn Python with the "Dive Into Python" book coming from VB, but am getting stuck at Example 2.3 (http://www.diveintopython.org/getting_to_know_python/everything_is_an_object.html). Here is what I get following the book's directions for: >>> import odbchelper Traceback (most recent call last): File "", line 1, in ImportError: No module named odbchelper I am thinking this has something to do with the PATH that Python traverses to find code to load as a module. I would greatly appreciate it if you could help me get this to work. Thanks, Dan From jepler at unpythonic.net Thu Jul 28 19:12:47 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 28 Jul 2005 18:12:47 -0500 Subject: poplib.POP3.list() returns extra value? In-Reply-To: <42e94d88$0$544$a726171b@news.hal-pc.org> References: <42e94d88$0$544$a726171b@news.hal-pc.org> Message-ID: <20050728231243.GA11708@unpythonic.net> With a judicious bit of UTSL, that count seems to be the total number of octets in the reply. This information comes from any user of _getlongresp(), which actually returns a tuple (resp, list, octets). These methods would be: list retr top uidl I'd consider it a doc bug too. If you feel comfortable doing it, dive in and improve the documentation of poplib. Submitting a patch to the patch tracker on sf.net/projects/python is probably the best way to do this, if you have the necessary knowledge of cvs to produce a patch. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rkern at ucsd.edu Thu Jul 7 05:35:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 07 Jul 2005 02:35:26 -0700 Subject: HELP! In-Reply-To: <20050707092141.5ED904BEAD@ws1-1.us4.outblaze.com> References: <20050707092141.5ED904BEAD@ws1-1.us4.outblaze.com> Message-ID: Ert Ert wrote: > Please help me i down loaded python nd itplays on MS-DOS mode and not on normal please help So what's your problem? Please read http://www.catb.org/~esr/faqs/smart-questions.html Then reformulate your question so that we can answer it. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From roy at panix.com Wed Jul 27 11:44:05 2005 From: roy at panix.com (Roy Smith) Date: 27 Jul 2005 11:44:05 -0400 Subject: Need to understand python license Message-ID: I'm looking into the possibility of getting my employer to use Python as an embedded scripting language. A big issue is licensing; we can't use anything that's GPL-like, because that would make us release our source code. Obviously, our lawyers will have the final say, but I'm looking for a rough idea, to see if this is even worth pursuing. I've read the copyright statement, and it sounds good to me, but I'm hardly an expert in this stuff. What I've been told is, "Basically, you want something with a Berkeley-like license, or an Apache 1.1-like license". I know that Java's license has been deemed acceptable, but Perl's has not. We ship Perl, but for stand-alone support stuff, not embedded in the core product. Where does Python fit into the GPL-Apache-Berkeley license spectrum? Specifically, can we take the Python interpreter source code, modify it, compile it, staticly link it into our binaries, ship it to our paying customers, and still retain the right to not show anybody our source? From bill.mill at gmail.com Wed Jul 13 11:20:54 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 13 Jul 2005 11:20:54 -0400 Subject: String Manipulation In-Reply-To: <1121266142.619153.142480@g49g2000cwa.googlegroups.com> References: <1121266142.619153.142480@g49g2000cwa.googlegroups.com> Message-ID: <797fe3d4050713082026fec3d9@mail.gmail.com> On 13 Jul 2005 07:49:02 -0700, Michael Jordan wrote: > hey, i have this huge text file and i need to go through and remove all > punctuation and every instance of the phrase "fruitloops=$" where $ is > any number 0-100" um, and yeah this is homework but i've tried to no > avail. thanks guys. cheerio :). jen Jen, This program iterates through one file and outputs all lines to another file which have the word "homework" in them. #-------------------------- Begin program 1 file_in = file('data.in') file_out = file('data.out') for line in file_in: #line is a string containing one line of the file if "homework" in line: file_out.write("homework") #--------------------------- End program 1 Here is a program which turns a string containing the phrase "number=42" into a variable containing the integer 42: #-------------------------- Begin program 2 #create a string variable called x x = "number=42" #split the string at the '=', resulting in ['number', '42'] n = x.split('=')[1] #turn n from a string into a number, so we could test its value n = int(n) if 0 < n < 100: print "n is between 0 and 100" else: print "n is not between 0 and 100" #-------------------------- End program 2 And, finally, a program to remove punctuation from a string: # ------------------------ Begin program 3 import string #create a sentence with punctuation punct = "This. is a, sentence with - punctuation" #remove the punctuation; make sure the first argument #to maketrans is the same length as the second, which #should be all blanks punct = punct.translate(string.maketrans('.,-', ' ')) #read the docs at # http://docs.python.org/lib/node109.html # for more details #------------------------------------End program 3 Hope this helps; you should be able to put the pieces together to do what you want to do. If you can't, feel free to ask more questions. Also, just so you know, there is a list at tutor at python.org set up just to answer questions like these. Peace Bill Mill bill.mill at gmail.com From jepler at unpythonic.net Fri Jul 22 15:33:38 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 22 Jul 2005 14:33:38 -0500 Subject: Mapping a drive to a network path In-Reply-To: <1122059720.962075.53260@g44g2000cwa.googlegroups.com> References: <1122059720.962075.53260@g44g2000cwa.googlegroups.com> Message-ID: <20050722193334.GB25836@unpythonic.net> import os os.system(r"net use z: \\computer\folder") Something in the win32net module of win32all may be relevant if you don't want to do it through os.system: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32net__NetUseAdd_meth.html Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From apoco at cox.net Thu Jul 14 23:58:04 2005 From: apoco at cox.net (Jacob Page) Date: Thu, 14 Jul 2005 20:58:04 -0700 Subject: set and frozenset unit tests? In-Reply-To: References: <3jhaoaFq2kajU1@individual.net> Message-ID: Steven Bethard wrote: > Jacob Page wrote: > >> Oye, there's quite a number of set and frozenset features that aren't >> well-documented that I now need to implement. What a fun chore! > > It would be a great help if you could submit appropriate documentation > patches for the areas you don't think are well-documented: Hmm, after closer scrutiny, I'm not sure if the documentation really does need modification. The largest incompatibility between IntervalSet and set was that my code wasn't enforcing hashability, and that property of sets actually IS documented. However, there are two minor things I don't see documented that caught me by surprise: * Since the <=, <, >, and >= operators raise an exception if the right-hand operand is not a set or frozenset, it seemed reasonable to me to assume that == and != should, too. However, the test suite for sets expect the comparisons to be allowed; == between a set and non-set return False, != returns True. Seems inconsistent with the rest of the operators, but then again, the odd use of > and < for purposes other than ordering also seems strange. * Apparently, if fs is a frozenset instance, fs.copy() returns a reference to fs instead of a copy of fs, and frozenset(fs) does the same. The unit tests also ensure that subclasses of frozenset don't do this. It makes sense that it's done that way to save on storage space, but it's not documented that this happens. Both issues seem to be pretty minor unless you're making functionally equivalent classes. I'm sure neither one will confuse someone into using them improperly, so I think it's fine to leave the docs alone. By the way, IntervalSet and FrozenIntervalSet, when used in place of set and frozenset, now pass most of the tests. One notable difference between them is that whereas sets can contain any hashable object, IntervalSet elements must be both hashable and orderable (implement __cmp__). Thus, commands like IntervalSet([FrozenIntervalSet(...)]) fail, unlike set([frozenset(...)]). I've also changed the methods with mixedCase capitalization to lower_case_with_underscores, as recommended by PEP 8. Version 0.2.2 of the module can now be downloaded from http://members.cox.net/apoco/interval/. I'm about to freeze the interfaces and transition the module to beta, so if you have any interest in the project or design change ideas, please send feedback soon. From bokr at oz.net Sat Jul 9 02:24:12 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 06:24:12 GMT Subject: removing list comprehensions in Python 3.0 References: <78huc11mgkvn1sho01qegi221k7hhc5u1p@4ax.com> Message-ID: <42cf6d0d.182600044@news.oz.net> On Fri, 08 Jul 2005 22:29:30 -0600, Steven Bethard wrote: >Dennis Lee Bieber wrote: >> On Fri, 08 Jul 2005 16:07:50 -0600, Steven Bethard >> declaimed the following in comp.lang.python: >> >>>I only searched a few relatively recent threads in c.l.py, so there are >>>probably more, but it looks to me like the final decision will have to >>>be made by a pronouncement from Guido. >> >> Great... It takes me two releases of Python to get comfortable >> with them, and then they are threatened to be removed again... >> >> Might as well submit the language to ISO for standardization -- >> then I wouldn't be following an erratic target > >Two points: > >(1) There's no reason to get uncomfortable even if they're removed. >You'd just replace [] with list(). So list(1, 2, 3) will be the same as [1, 2, 3] ?? Right now, >>> list(1,2,3) Traceback (most recent call last): File "", line 1, in ? TypeError: list() takes at most 1 argument (3 given) have fun ;-) > >(2) *IMPORTANT* If this happens *at all*, it won't happen until Python >3.0, which is probably at least 5 years away. And the Python 2.X branch >will still be available then, so if you don't like Python 3.0, you don't >have to use it. > >STeVe Regards, Bengt Richter From metawilm at gmail.com Wed Jul 27 14:06:15 2005 From: metawilm at gmail.com (Willem Broekema) Date: 27 Jul 2005 11:06:15 -0700 Subject: Create a variable "on the fly" References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> <1122484531.000796.99020@g47g2000cwa.googlegroups.com> Message-ID: <1122487575.123974.268880@g47g2000cwa.googlegroups.com> Steve M: > >>> locals()['OSCAR'] = 'the grouch' > >>> OSCAR > 'the grouch' > >>> Use "globals", not "locals": globals()['OSCAR'] = 'the grouch' because states: locals() Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. Function globals() is not subject to this restriction. - Willem From exarkun at divmod.com Thu Jul 14 11:23:25 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 14 Jul 2005 11:23:25 -0400 Subject: how to get rate of pop3 receiving progress? In-Reply-To: <4e307e0f0507140209a295e8a@mail.gmail.com> Message-ID: <20050714152325.26278.1725624082.divmod.quotient.11692@ohm> On Thu, 14 Jul 2005 17:09:10 +0800, Leo Jay wrote: >when i use POP3.retr() in poplib module, the retr() function will not >return until the receiving progress is finished > >so, is there any way to get the rate of receiving progress? > An extremely rudamentary example of how you might do this using Twisted's POP3 client support is attached. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: pop3progress.py Type: application/x-python Size: 1420 bytes Desc: not available URL: From kay.schluehr at gmx.net Sat Jul 30 03:02:41 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Jul 2005 00:02:41 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42ead151@nntp0.pdx.net> Message-ID: <1122706961.907563.29900@z14g2000cwz.googlegroups.com> Tim Roberts schrieb: > Scott David Daniels wrote: > > > >What kind of shenanigans must a parser go through to translate: > > < > > > >this is the comparison of two functions, but it looks like a left- > >shift on a function until the second with is encountered. Then > >you need to backtrack to the shift and convert it to a pair of > >less-thans before you can successfully translate it. > > C++ solves this exact problem quite reasonably by having a greedy > tokenizer. Thus, that would always be a left shift operator. To make it > less than and a function, insert a space: > < > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. Python does have such a greedy/longest match tokenizer too: >>> 2 .__add__(3) # insert whitespace before dot 5 >>> 2.__add__(3) # 2. is a float -> Exception Kay From fdeserres at gmx.net Fri Jul 22 09:04:20 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Fri, 22 Jul 2005 15:04:20 +0200 Subject: tuple to string? Message-ID: <42E0EED4.4020001@gmx.net> hiho, what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to the string 'spam'? TIA, Francois From fake at comcast.net Tue Jul 26 20:20:17 2005 From: fake at comcast.net (Gordon Airporte) Date: Tue, 26 Jul 2005 20:20:17 -0400 Subject: Tkinter - Resizing a canvas with a window Message-ID: I'm trying to get my canvas to resize to fill its frame within a window, but I can't figure out how to handle the callback data from the window's properly. It has very strange behavior - resizing randomly or growing by itself, shrinking to 0. The following works passably but jumps around at random if you move the window and goes nuts if you add the button (watch any wrapping): from Tkinter import * class testApp2: def __init__( self, master ): self.ma = master self.f = Frame( self.ma ) self.f.pack() self.cv = Canvas(self.f, width=25, height=25, bg='red') self.cv.pack() #self.b1 = Button( self.f, text='hello', command=None ) #self.b1.pack(side='bottom') self.ma.bind('', self.resize ) def resize( self, event ): #print '(%d, %d)' % (event.width, event.height) self.cv.configure( width = event.width-4, height = event.height-4 ) root = Tk() app = testApp2(root) root.mainloop() From onurb at xiludom.gro Wed Jul 13 04:19:41 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 13 Jul 2005 10:19:41 +0200 Subject: Slicing every element of a list In-Reply-To: References: Message-ID: <42d4ce9f$0$6697$626a14ce@news.free.fr> Alex Dempsey wrote: > Recently I tried to slice every element of a list of strings. First I tried: > > f = open("export.xls", "r") http://www.python.org/doc/2.4.1/lib/module-csv.html (snip, see other posts in this thread) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From exarkun at divmod.com Thu Jul 21 10:38:55 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 10:38:55 -0400 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <42dfb111@griseus.its.uu.se> Message-ID: <20050721143855.26278.69992747.divmod.quotient.15457@ohm> On Thu, 21 Jul 2005 16:34:30 +0200, Jan Danielsson wrote: >Hello all, > > How do I make a python script actually a _python_ in unix:ish >environments? > > [snip] Put "#!/usr/bin/python". Install the program using distutils: if necessary, distutils will rewrite the #! line to fit the configuration of the system the program is being installed on. Jp From edvard+news at majakari.net Thu Jul 7 08:29:30 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Thu, 07 Jul 2005 15:29:30 +0300 Subject: Favorite non-python language trick? References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> <87hdf8ync5.fsf@titan.staselog.com> Message-ID: <87ll4ix0id.fsf@titan.staselog.com> Simon Brunning writes: > http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb Neat. I guess about 75% about programming-related things classified as neat-o or "convenient!" are already implemented by some Pythonista(s). Spoils all the fun for reinventing the wheel, doesn't it. :) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From jack at performancedrivers.com Thu Jul 28 10:31:25 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 28 Jul 2005 10:31:25 -0400 Subject: Sr. Compiler Engineering Opportunity In-Reply-To: <20050728073757.45C491E4002@bag.python.org> References: <20050728073757.45C491E4002@bag.python.org> Message-ID: <20050728143125.GG4840@performancedrivers.com> Great, Transmeta is hiring. What does this have to do with python? Hmm, Mutliprocessor or Multicore Transmeta chips? Let the rumor mongering begin. On Thu, Jul 28, 2005 at 12:40:13AM -0700, Nathan Sanders wrote: > Hello- > > I'm hoping to network with you and find out if you know anyone who > you think could be interested in the following opportunity? > > > Sr. Compiler Engineer > > Position Type: Full-Time Employee > Location: San Jose, California (Silicon Valley, USA) > Generous Compensation and Stock package > -------------------------------------------------------------------- > Job Description: > You will be responsible for identifying, developing, and delivering > critical enhancements to programming models and the compiler tool > chain > for a new and unique multi-processor architecture. > > Requirements: > Experience with compiler back-end technology > In-depth understanding of processor architectures > Excellent interpersonal and debugging skills > Candidate should be self-motivated and comfortable working in a fast > paced, mission-critical engineering environment > > Valuable Skills: > Candidates with previous experience in multi-processor architectures, > SIMD > architectures and media architectures, as well as familiarity with > the GCC > source base is a plus. > > Experience: > Minimum 3-5 years of experience > M.S. in Computer Science, Computer or Electrical Engineering required > PhD > in Computer Science, Computer or Electrical Engineering a plus > > More about the company: > Our client develops and licenses innovative computing, microprocessor > and semiconductor technologies and related intellectual property. > Founded in the mid 90's, They first became known for designing, > developing and selling their highly efficient x86-compatible software- > based microprocessors, which deliver a balance of low power > consumption, high performance, low cost and small size suited for > diverse computing platforms. They also develop advanced power > management technologies for controlling leakage and increasing power > efficiency in semiconductor and computing devices. > > > Thanks, > > ------------------------------------------------------------------ > Nathan Sanders > Principal/Manager > Bridgenex LLC > 2464 El Camino Real #206 > Santa Clara, Ca 95051 > Office: 1.800.881.5733 > Email: nathan at bridgenex.com > Corporate: www.bridgenex.com > > :::STAFFING CONLULTANT SERVICES FOR HIGH TECH::: > > > -- > http://mail.python.org/mailman/listinfo/python-list > From esj at harvee.org Sun Jul 10 12:12:13 2005 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 10 Jul 2005 12:12:13 -0400 Subject: Berkely DB =?windows-1252?Q?=96_many_writers=2C_many_?= =?windows-1252?Q?readers?= In-Reply-To: References: Message-ID: Andy Leszczynski wrote: > > I need to now option I open the Berkley DB (both db and env) to have > configuration for multiple writers and multiple readers. Via multiple > processes and multiple threads. No trx needed. the simple answer is you can't. bdbm is probably single writer multiple reader. I believe if you use of the the most recent sleepy cat database, you have support for multiple readers and writers in any context. when I did this, I stuck my gdbm database into a multithreaded stand-alone process. I used XML RPC for access and used a per key locking mechanism internal to the data storage and retrieval process. This locking mechanism set appropriate locks so that a writer for specific key would wait for all readers of that key to finish, and block all subsequent readers until it was done. so far is working pretty well but I haven't tried it in a high load situation. ---eric From tim.peters at gmail.com Fri Jul 29 10:44:41 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 29 Jul 2005 10:44:41 -0400 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <1f7befae0507290744207c8a88@mail.gmail.com> [Dan Sommers] > Ok, not universal. But as usual, Zen is not easily nailed to a tree. > > Was Tim writing about developing Python itself, or about developing > other programs with Python? Tim was channeling Guido, and that's as far as our certain knowledge can go. It _seems_ reasonable to believe that since Guido's mind is, by definition, perfectly Pythonic, any truth channeled from it necessarily applies to all things Pythonic. nevertheless-we-interpret-the-gods-at-our-peril-ly y'rs - tim From elmo13 at jippii.fi Mon Jul 25 14:59:12 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Mon, 25 Jul 2005 21:59:12 +0300 Subject: How can I encode something in base32 preferably very fast? References: Message-ID: On Mon, 25 Jul 2005 21:15:36 +0300, Elmo M?ntynen wrote: > On Mon, 25 Jul 2005 16:51:05 +0200, Johannes Findeisen wrote: > >> On Mon, 2005-07-25 at 17:23 +0300, Elmo M?ntynen wrote: >>> I want to encode a plaindigest or a hexdigest in base 32. Any hints? >> >> Search Google for "python base32" isn't as hard... >> >> First result are the original python lib documentation: >> http://docs.python.org/lib/module-base64.html >> >> I think you need to convert to a String before encoding... >> >> Have fun, > > I thought I had looked at that particular module:). Thanks for pointing it > out. > > Elmo I'm using python2.3(because of my distro of choise, debian) and did a help(base64) and of course didn't see anything about base32:). Now i have good reason to change to 2.4:) Thanks Elmo From markus_GETRIDOFALLCAPSwankus at hotmail.com Tue Jul 12 19:18:22 2005 From: markus_GETRIDOFALLCAPSwankus at hotmail.com (Markus Wankus) Date: Tue, 12 Jul 2005 19:18:22 -0400 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: <42d3e666_1@news2.prserv.net> Message-ID: Markus Wankus wrote: > > My opinion - If you aren't willing to try something new, or have an > aversion to it in the first place, nothing we can say will change your > mind. Correction... *There are some people, who* if they aren't willing to try something new, or have an aversion to it in the first place, nothing we can say will change their mind. M. From ac063 at lafn.org Fri Jul 15 16:20:46 2005 From: ac063 at lafn.org (David Smith) Date: Fri, 15 Jul 2005 13:20:46 -0700 Subject: Newbie question: Explain this behavior - a followup In-Reply-To: References: Message-ID: First, thanks to those who offered answers. They didn't really answer my question, only because I had not worked through the example sufficiently well. Doing this, I believe I understand what is happening, and, if my understanding is correct, have discovered that for other beginning and ending values for the two range statements, the example doesn't work. Given that the beginning and ending values for the inner range statement are the same, the inner range statement will never be executed for its first iternation; the else will be. This is not correct. Simply make the beginning value a non-prime number, and the program still prints out that that number is prime. Changing both beginning and ending values on the two statements, the ouput is differentially buggy. From tim.peters at gmail.com Thu Jul 14 16:20:04 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 14 Jul 2005 16:20:04 -0400 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? In-Reply-To: <11ddfgsg4nlch86@corp.supernews.com> References: <11ddckucctde603@corp.supernews.com> <11ddfgsg4nlch86@corp.supernews.com> Message-ID: <1f7befae0507141320b8d4e57@mail.gmail.com> [Tim Peters] ... >> What does your platform C return for the integer expression >> 42/0? Is any other outcome "wrong"? [Grant Edwards] > I guess I though it was obvious from my reference to IEEE 754 > that I was referring to floating point operations. Yes, that was obvious. Since I thought my point would be equally obvious, I won't spell it out <0.7 wink>. ... >> Note that support for 754 was rare on Python platforms at the >> time Python was designed, and nobody mentioned 754 support as >> even a vague desire in those days. > I often foget how old Python is. Still, I've been using IEEE > floating point in C programs (and depending on the proper > production and handling of infinities and NaNs) for more than > 20 years now. I had thought that Python might have caught up. It has not. Please see the other thread I mentioned. >> In the absence of user interest, and in the absence of HW >> support for NaNs or infinities on most Python platforms, > Really? Yes, but looks like you didn't finish reading the sentence. Here's the rest, with emphasis added: >> the decision to raise an exception was quite sensible AT THE TIME. You may have forgotten how much richer the "plausible HW" landscape was at the time too. I was deeply involved in implementing Kendall Square Research's HW and SW 754 story at the time, and it was all quite novel, with little prior art to draw on to help resolve the myriad language issues 754 didn't address (e.g., what should Fortran's 3-branch Arithmetic IF statement do if fed a NaN? there were hundreds of headaches like that, and no cooperation among compiler vendors since the language standards ignored 754). The C standards didn't mention 754 until C99, and then left all support optional (up to the compiler implementer whether to do it). That didn't help much for a bigger reason: major C vendors (like Microsoft and Borland) are still ignoring C99. "Subset" HW implementations of 754 were also common, like some that didn't support denorms at all, others that didn't implement the non-default rounding modes, some that ignored signed zeroes, and several that implemented 754 endcases by generating kernel traps to deal with infinities and NaNs, making them so much slower than normal cases that users avoided them like death. If I had to bet at the time, I would have put my money on 754 dying out due to near-universal lack of language support, and incompatible HW implementations. Most programming languages still have no sane 754 story, but the remarkable dominance of the Pentium architecture changed everything on the HW side. > I would have guessed that most Python platforms are > '586 or better IA32 machines running either Windows or Linux. Today, yes, although there are still Python users on many other OSes and architectures. Most of the latter support 754 too now. > They all have HW support for NaNs and Infinities. Yes, Intel-based boxes certainly do (and have for a long time), and so do most others now. From aljosa.mohorovic at gmail.com Fri Jul 1 07:55:14 2005 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jul 2005 04:55:14 -0700 Subject: PyQT, QProcess.readyReadStdout() problem Message-ID: <1120218914.695528.167150@g14g2000cwa.googlegroups.com> part of code: >>> try: self.isdnlog = QProcess(self) self.isdnlog.addArgument("/usr/bin/tail") self.isdnlog.addArgument("-f") self.isdnlog.addArgument("/home/aljosa/qt/isdn.log") [...] QObject.connect(self.isdnlog, SIGNAL("readyReadStdout()"), self.onPhoneCall) self.isdnlog.start() <<< problem is that isdnlog logs 2 or more lines per call, and QProcess moves one line per call. is there something like QProcess.readLastLine()? Aljosa From gregm at taming-tech.com Thu Jul 7 17:36:32 2005 From: gregm at taming-tech.com (GregM) Date: 7 Jul 2005 14:36:32 -0700 Subject: Calculating average time In-Reply-To: References: <1120768294.287881.169030@z14g2000cwz.googlegroups.com> Message-ID: <1120772192.312489.218780@g47g2000cwa.googlegroups.com> Thanks Skip. As usual I want to make it harder then it actually is. From future_retro at yahoo.co.uk Fri Jul 22 05:01:28 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 22 Jul 2005 02:01:28 -0700 Subject: RegUnloadkey access denied Message-ID: <1122022887.947520.152460@o13g2000cwo.googlegroups.com> In the following script I can't get the reg key to unload. Anyone got any ideas? I can load and save the key without any problems. I can unload the key from regedit and have checked security on the key. The docs don't mention any special privileges are needed (SeRestorePrivilege should do it). I'm stumped. Cheers peeps, MW. import ntsecuritycon import win32security import win32api import _winreg import win32con flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) Loadid = win32security.LookupPrivilegeValue(None, 'SeRestorePrivilege') #Saveid = win32security.LookupPrivilegeValue(None, 'SeBackupPrivilege') LoadPrivilege = [(Loadid, ntsecuritycon.SE_PRIVILEGE_ENABLED)] #SavePrivilege = [(Saveid, ntsecuritycon.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(htoken, 0, LoadPrivilege) #win32security.AdjustTokenPrivileges(htoken, 0, SavePrivilege) key = _winreg.HKEY_USERS hkey = win32api.RegLoadKey(key,'Marc','c:\\ntuser.dat') okey = win32api.RegOpenKeyEx(key,'Marc\\test',0,win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(okey,'test',0,_winreg.REG_DWORD,0) #win32api.RegSaveKey(okey,'c:\\ntuser2.dat',None) #win32api.RegFlushKey(_winreg.HKEY_USERS) win32api.RegUnLoadKey(key,'Marc') From zen19725 at zen.co.uk Sun Jul 31 01:32:35 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 06:32:35 +0100 Subject: shelve: writing out updates?! References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: On 30 Jul 2005 17:48:39 -0700, Paul Rubin wrote: >Shelve uses dbm and pickle to make a persistent object store. The >"db" in "dbm" stands for "database" and while I didn't expect full >ACID capability, What is ACID? > I'd have thought there'd be at least some minimum >gesture towards durability of updates. But say that s is a shelve >object. If I say > > s[whatever] = value > >there is no way apparent from the shelve docs to get the update >flushed out to the disk file until the shelve is actually closed. Wierd. I'd expect something like an s.flush() function. -- Email: zen19725 at zen dot co dot uk From bill.mill at gmail.com Wed Jul 27 15:04:24 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 27 Jul 2005 15:04:24 -0400 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: <797fe3d4050727120453a847f3@mail.gmail.com> On 7/27/05, Tito wrote: > Thank you both for your quick answers. > > What I wanted is to parameterize a function with another member > function, like this: > > def printFunctionForEach(collection, functionName): > for elem in collection: > print eval("elem." + functionName + "()") > > Moreover, I wanted to do it with a property: > > def printPropertyForEach(collection, propertyName): > for elem in collection: > print eval("elem." + propertyName) > > Is there another approach to do it? > Sure, piece of cake: >>> class test: ... def func1(self): print 'func1 called' ... >>> class test2: ... def func1(self): print 'other func1' ... >>> x = [test(), test2(), test()] >>> def call_this_func(lst, func_name): ... for e in lst: ... getattr(e, func_name)() ... >>> call_this_func(x, 'func1') func1 called other func1 func1 called >>> Note that the getattr raises an AttributeError if func_name doesn't exist in the object; you should probably wrap it in a try/except. Peace Bill Mill bill.mill at gmail.com From ark at acm.org Tue Jul 12 11:27:16 2005 From: ark at acm.org (Andrew Koenig) Date: Tue, 12 Jul 2005 15:27:16 GMT Subject: breaking out of nested loop References: Message-ID: "rbt" wrote in message news:mailman.1657.1121177960.10512.python-list at python.org... > What is the appropriate way to break out of this while loop if the for > loop finds a match? Make it a function and use a "return" statement to break out. From reinhold-birkenfeld-nospam at wolke7.net Thu Jul 21 15:51:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 21 Jul 2005 21:51:09 +0200 Subject: PEP on path module for standard library In-Reply-To: References: Message-ID: <3kacleFslj6sU1@individual.net> FYI: I modified the path module a bit so that it fits many of the suggestions from python-dev, and put the result in the Python CVS tree under nondist/sandbox/path. Most prominent change is that it doesn't inherit from str/unicode anymore. I found this distinction important, because as a str subclass the Path object has many methods that don't make sense for it. Peter Hansen wrote: > Michael Hoffman wrote: >> For the PEP, do any of you have arguments for or against including path? >> Code samples that are much easier or more difficult with this class >> would also be most helpful. > > I believe the strongest argument for "path" can be made for how it > integrates functionality which, although closely related conceptually, > is currently distributed across a half dozen or more different modules > in the standard library. Especially for newbies (I can only imagine, at > this stage) it would make working with files much easier in a many ways. > > "Easier" or "more difficult" is a subjective thing, of course, but one > can't argue with the fact that path can sometimes do through a single > object what would otherwise require several imports and a bunch of calls > into things like open(), os.path, grep, and shutil. Correct. > Examples showing effective uses of path that simplify those cases would > probably merit the label "easier" even in Guido's mind, though > unfortunately that's not certain. "Easier" in some minds might simply > translate to "many lines less code", and while path can sometimes do > that, aside from the ease of splitting and joining stuff without > multiple calls to os.path.this-and-that, it really doesn't often reduce > code size _that_ much, in my experience. (Postings to c.l.p showing a > 50% reduction in code size for contrived examples notwithstanding.) Well, these examples are the ones we'd like to see here. So, people: If you posted examples to c.l.py in the past, please try to collect them here! > A related thoughts: since paths are objects, they have attributes or > properties, and having things like ".basename" and ".parent" readily > available without having to do obscure things like > os.path.split(somepath)[0] makes things much easier to read (therefore > more maintainable). In fact, I'd propose that as another strong > argument in path's favour: it makes code much more readable, even if not > "easier" to write. > > Hmm... does "easier" or "more difficult" apply to the writing of the > code or the reading of it? I find it self-evident that code written > using "path" is much easier to read, not necessarily much easier to > write (for non-newbies). And it is much more "Pythonic" in my eyes. Though that word may be inaccurate when it comes from someone else that Guido, I feel that endless chains of '[os.path.join(os.path.join(z, "a"), x) for x in os.path.listdir(os.path.join(z, "a") if os.path.isfile(os.path.join(.... are not qualified as being Pythonic. > I'd summarize this by saying that the integration of "path" in the > stdlib would make it easier for newbies to write code (that might not be > obvious to a non-newbie... shall we ask some to help?), and easier for > everyone to read code (self-evident, no?), and if that's not a > sufficient condition for inclusion I don't know what is. Reinhold From bokr at oz.net Sun Jul 3 15:19:05 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Jul 2005 19:19:05 GMT Subject: Assigning to None (was Re: Question about Python) References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> Message-ID: <42c8388f.442175024@news.oz.net> On Sun, 03 Jul 2005 11:47:07 +1000, Steven D'Aprano wrote: >On Fri, 01 Jul 2005 12:59:20 -0400, Fran?ois Pinard wrote: > >> [Peter Hansen] >>> Mike Meyer wrote: >>> > Yes. I once grabbed an old program that did assignments to None. But >>> > that's always been a bad idea. >> >>> What was the use case!? >> >> People used to assign None to itself as a keyword argument in function >> headers. The goal was to make a local copy of the reference, which was >> then accessed faster than the global thing. > >Can you say "premature optimization is the root of all evil"? > >I'd like to see the profiling that demonstrated that this made a >significant -- or even measurable -- speed-up in anything but the most >unusual cases. > The difference between local and global access is definitely measurable, though there's no reason to use None as the local name if you want to do that kind of optimization (not possible in 2.4+) >>> from time import clock >>> def test(): ... none = None # local ... t0 = clock() ... for i in xrange(10**6): v = None ... t1 = clock() ... for i in xrange(10**6): v = none ... t2 = clock() ... print 't1-t0 = %f, t2=t1 = %f, ratio = %f' %(t1-t0, t2-t1, (t1-t0)/(t2-t1)) ... >>> test() t1-t0 = 0.971914, t2=t1 = 0.766901, ratio = 1.267327 about 25% longer to get a global (AND bind it locally, which the two timings share) than to do the same for a local, it seems. Regards, Bengt Richter From jgrahn-nntq at algonet.se Sat Jul 23 08:45:11 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 23 Jul 2005 12:45:11 GMT Subject: Reading network interface data in linux References: <873bqjf7oq.fsf@titan.staselog.com> Message-ID: On Wed, 13 Jul 2005 11:09:57 +0300, Edvard Majakari wrote: > > Suppose one wants to fetch the following data from given network interface, > say, eth0: > >>>> Ethinf('eth0').addr() > '192.168.1.42/24' ... >>>> Ethstat('eth0').rx_bytes() > 14325235341223 ... > One could implement modules by installing eg. ethtool and reading speed/duplex > information by parsing ethtool output, but it is ugly way to do it, prone to > errors, requires launching a process as well as installation of ethtool. On the other hand, I have a hunch that the interface that ethtool uses is unstable, changes between major kernel versions, varies with the kind of hardware you have, etc. If that is the case, you might want to keep parsing ethtool's output. Letting /them/ worry about tracking kernel changes would actually be the most stable solution. The ethtool authors are kernel developers, and probably know all that stuff. Or convince the ethtool authors to release future ethtool versions as a Python module with an optional command-line interface ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From flamesrock at gmail.com Sat Jul 2 15:52:12 2005 From: flamesrock at gmail.com (flamesrock) Date: 2 Jul 2005 12:52:12 -0700 Subject: wxPython: Terminal Output -> Scrollable Panel? References: <1120289025.359671.148450@g14g2000cwa.googlegroups.com> <-uOdneuY58vY4VvfRVn-sA@powergate.ca> Message-ID: <1120333932.108782.45740@g49g2000cwa.googlegroups.com> Thanks much for your response. I looked at PyCrust, and while its given me a few cool ideas, I may have described the problem incorrectly. What I really need is not something that takes input, but merely redirects the 'print' statements to something like a terminal window. Is this even possible without entering the function calls directly into a pycrust like terminal? Maybe I'm trying to do the wrong thing. Thanks Peter Hansen wrote: > flamesrock wrote: > > I want to make it so that clicking on a button that performs an > > operation will output it to the scrollable wxpython terminal panel, and > > (if possible) save that output as text (or maybe into a logfile). > > The example code includes something called "PyCrust" which does pretty > much this. (The logging part is fairly trivial, so I won't mention it.) > I'm sure you could look in the source to learn more. You can start by > running the demo, and finding that particular one, playing with it a > bit, and then seeing how the demo code invokes PyCrust. Then find the > source for PyCrust in the wxPython folder (under your lib/site-packages > folder in c:\python24) and start reading. > > -Peter From tchurm at gmail.com Thu Jul 21 03:36:38 2005 From: tchurm at gmail.com (tchurm at gmail.com) Date: 21 Jul 2005 00:36:38 -0700 Subject: Ann: Tkinter drag and drop module In-Reply-To: References: <1121336778.344208.224820@f14g2000cwb.googlegroups.com> <1121353846.723518.165110@g49g2000cwa.googlegroups.com> Message-ID: <1121931398.244379.97020@g44g2000cwa.googlegroups.com> yup. that's exactly what i did, on win2k... somehow, i was surprised that it would work - the filepath + file name from the binary i'd dragged and dropped onto the .exe file was properly passed to the frozen python script as an arg... From rahoool at gmail.com Fri Jul 1 04:25:44 2005 From: rahoool at gmail.com (rahoool at gmail.com) Date: 1 Jul 2005 01:25:44 -0700 Subject: nested lists - utter newbie Message-ID: <1120206344.531419.54240@g47g2000cwa.googlegroups.com> Hi, why is this possible - >>>b = [1,2,3] >>>b[2] = b >>>b [1,2,[...]] >>>b[2] [1,2,[...]] >>>b[2][2][2][2][2] [1,2,[...]] but this is not - >>>x = [1,2,x] Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined thanks r_a_h_o_o_l From walterbrunswick at sympatico.ca Thu Jul 14 12:00:14 2005 From: walterbrunswick at sympatico.ca (Walter Brunswick) Date: Thu, 14 Jul 2005 12:00:14 -0400 Subject: Consecutive Character Sequences References: Message-ID: Thank you mensanator at aol.com , George Sakkis and Aries Sun for your code contributions. I haven't tested them yet, but they look alright and enough for me to work with. Thanks to everyone else for your comments. W. Brunswick. From tjreedy at udel.edu Sat Jul 9 16:30:50 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jul 2005 16:30:50 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? References: <56190b6c05070911213409433e@mail.gmail.com> Message-ID: "Steve Juranich" wrote in message news:56190b6c05070911213409433e at mail.gmail.com... > Without fail, when I start talking with some of the "old-timers" > (people who have written code in ADA or Fortran), I hear the same > arguments that using "if" is "better" than using "try". I think that > the argument goes something like, "When you set up a 'try' block, you > have to set up a lot of extra machinery than is necessary just > executing a simple conditional." I believe 'setting up a try block' is one bytecode (you can confirm this with dis.dis). It is definitely cheaper than making a function call in an if condition. Catching exceptions is the time-expensive part. For more, see my response to 'witte'. Terry J. Reedy From bh at intevation.de Tue Jul 19 10:57:53 2005 From: bh at intevation.de (Bernhard Herzog) Date: Tue, 19 Jul 2005 16:57:53 +0200 Subject: Can I make the Python build use an already-installed version of Expat? References: Message-ID: Steve Juranich writes: > I'm running into problems where Python and VTK both ship with their > own distribution of the Expat parser. As long as you never use the > Python XML package, everything is fine. But if you try using the > Python XML parser after doing an `import vtk', a nice little message > saying "Segmentation Fault" is your reward. This sounds like this bugreport on sourceforge: http://python.org/sf/1075984 Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From steve at REMOVETHIScyber.com.au Thu Jul 21 12:28:27 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 22 Jul 2005 02:28:27 +1000 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: On Thu, 21 Jul 2005 16:43:00 +0100, Michael Hoffman wrote: > Personally, I feel my time is better served by answering questions that > would not be easy to find without assistance. I can't expect everyone to > know about or expect enumerate() from the beginning, so I don't have any > objections to it being asked here. > > If people were to ask what the function signature for enumerate() was > when that is easy to Google, then I would think they were wasting > everyone's time. And on that, I think we can agree! -- Steven. From samrobertsmith at gmail.com Sun Jul 3 06:49:02 2005 From: samrobertsmith at gmail.com (shisa) Date: Sun, 3 Jul 2005 06:49:02 -0400 Subject: No sys.ps2 in IDLE (was Re: question) In-Reply-To: References: Message-ID: <1d987df3050703034927a8f4d3@mail.gmail.com> What should I do to correct the errors accordingly? On 7/3/05, Michael Hoffman wrote: > yipusi wrote: > > IDLE 1.0.3 > > > >>>>import sys > >>>>sys.ps2 > > > > > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > sys.ps2 > > AttributeError: 'module' object has no attribute 'ps2' > > > > > > where is the problem? > > The problem is that you are using IDLE (and an old version at that), > which doesn't use sys.ps2. > -- > Michael Hoffman > -- > http://mail.python.org/mailman/listinfo/python-list > From "simonb\" at (none) Tue Jul 12 23:49:25 2005 From: "simonb\" at (none) (@(none)) Date: Wed, 13 Jul 2005 13:49:25 +1000 Subject: if not DEBUG: log = null_log In-Reply-To: <42d47595.35476352@news.oz.net> References: <42d47595.35476352@news.oz.net> Message-ID: <42d48f45$1@clarion.carno.net.au> Bengt Richter wrote: > On Wed, 13 Jul 2005 11:00:14 +1000, Simon Burton wrote: > > >>Hi, >> >>I'm after a no-op command, so that i can redirect >>logging commands in performance critical code. >> >>Something like this: >> >>def log(*args): print args >>def null_log(*args): pass >>if not DEBUG: log = null_log >> >>is unacceptable because of the overhead of calling >>functions in python. >> > > I think you could make the existence of log calls dependent on > whether you compile with an optimize flag by abusing > an assert statement, e.g., > > assert log(some, args) or True > This is a session with the -O flag, so asserts disapear: >>> from time import time >>> >>> def count(N=10000000): ... for i in xrange(N): i=0 ... >>> >>> t=time(); count(); print time()-t 0.821492910385 >>> >>> def count_call(N=10000000): ... for i in xrange(N): foo() ... >>> t=time(); count_call(); print time()-t 3.50276303291 >>> >>> def log(): print "log" ... >>> >>> def count_assert(N=10000000): ... for i in xrange(N): assert log() ... >>> >>> t=time(); count_assert(); time()-t 0.61060500144958496 Woohoo!! Simon. From nemesis at nowhere.invalid Sat Jul 30 05:08:39 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Sat, 30 Jul 2005 09:08:39 GMT Subject: rfc822 module bug? Message-ID: <20050730085418.2139.16534.XPN@orion.homeinvalid> Hi all, I found that the function parsedate_tz of the rfc822 module has a bug (or at least I think so). I found a usenet article (message-id: <2714d.q75200 at myg.winews.net>) that has this Date field: Date: Tue,26 Jul 2005 13:14:27 GMT +0200 It seems to be correct?, but parsedate_tz is not able to decode it, it is confused by the absence of a space after the ",". I studied the parsedate_tz code and the problem is on its third line: ... if not data: return None data = data.split() ... After the split I have: ['Tue,26', 'Jul', '2005', '13:14:27', 'GMT', '+0200'] but "Tue," and "26" should be separated. Of course parsedate_tz correctly decode the field if you add a space after the ",". Do you think that's a bug? Which is the most correct place where to file this bug? ? and looking at rfc822 par3.3 it should be correct: date-time = [ day-of-week "," ] date FWS time [CFWS] day-of-week = ([FWS] day-name) / obs-day-of-week day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = day month year -- A pat on the back is only a few centimeters from a kick in the butt. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From jepler at unpythonic.net Tue Jul 12 20:27:50 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 12 Jul 2005 19:27:50 -0500 Subject: Browser plug-in for Python? In-Reply-To: <05Jul12.162705pdt."58617"@synergy1.parc.xerox.com> References: <05Jul12.162705pdt."58617"@synergy1.parc.xerox.com> Message-ID: <20050713002747.GA26579@unpythonic.net> Back in the day there was 'grail', which was a browser in its own right. There may also have been a plug-in for other browsers, but I don't know any real details about them. Python itself has deprecated the 'restricted execution' environment it had in previous versions, because ways to break out of the jail existed or were thought to exist, and nobody stepped forward and offered to spend the requisite time to create and validate (even in a hand-wavy kind of way) a new security model. If you want to write programs in Python and run them in today's browsers, the shortest path from here to there is jython. Several applet demos are available at http://www.jython.org/applets/index.html I have used Jython a little bit, but never seriously and not in the past few years. Jython implements an older version of the Python language, corresponding to cPython 2.1 if I remember correctly. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rafi at free.fr Sun Jul 24 09:58:13 2005 From: rafi at free.fr (rafi) Date: Sun, 24 Jul 2005 15:58:13 +0200 Subject: FAQ? In-Reply-To: References: Message-ID: <42e39e79$0$13224$636a15ce@news.free.fr> Keith P. Boruff wrote: > Michael Hoffman wrote: > >> Keith P. Boruff wrote: >> >>> Is there an FAQ available specific to this NG as I'm sure some of the >>> list slicing questions I have have been asked before. >> >> Try Google for . > > I tried and didn't find one. That's why I asked here. surprising as the first (for me at least on googgle.com) response is: www.python.org/doc/faq/ >> I don't know why you would want to look in a FAQ *specific* to a >> newsgroup to look up slicing questions, > > I have a specific question about list slicing and this is a python NG. > What's not to understand? Michael answer could be subtitled as: "if the faq is wider that the newsgroup, then you have more probability to find an answer." > A more general FAQ (or the stuff I've accessed on slicing) didn't answer > my question. If, after looking for information on your own you did not find a solution, it may mean that you are ready to post a question :-) my 2 cents -- rafi "Imagination is more important than knowledge." (Albert Einstein) From jlconlin at lanl.gov Mon Jul 18 11:14:34 2005 From: jlconlin at lanl.gov (Jeremy) Date: Mon, 18 Jul 2005 09:14:34 -0600 Subject: re.IGNORECASE and re.VERBOSE Message-ID: I am using regular expressions and I would like to use both re.IGNORECASE and re.VERBOSE options. I want to do something like the following (which doesn't work): matsearch = r'''^\ {0,4}([mM]\d+) ''' MatSearch = re.compile(matsearch, re.VERBOSE, re.IGNORECASE) Does anyone have any suggestions? Thanks, Jeremy From flupke at nonexistingdomain.com Wed Jul 27 02:39:58 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 27 Jul 2005 06:39:58 GMT Subject: finding out the calling function Message-ID: <2%FFe.154619$cb5.8344628@phobos.telenet-ops.be> Hi, i have a property in a class that gets changed and i would want to know who changes it. Is there a way i can find out the calling function of a property? Thanks, Benedict From tpherndon at gmail.com Tue Jul 12 11:44:49 2005 From: tpherndon at gmail.com (Peter Herndon) Date: 12 Jul 2005 08:44:49 -0700 Subject: Software needed In-Reply-To: References: Message-ID: <1121183089.760096.300450@z14g2000cwz.googlegroups.com> "Document Management Software" is a little vague. What do you want it to do? In general though, when someone says "content management" and "Python", the general response is Zope, usually with Plone on top. From rrr at ronadam.com Wed Jul 27 14:18:07 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 27 Jul 2005 18:18:07 GMT Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Toby Dickenson wrote: > On Wednesday 27 July 2005 05:37, Meyer, Tony wrote: > > >>I can see that this would make sense in some situations, but ISTM that it >>would make a great deal more sense (and be much more intuitive) to have >>concatenation include the separator character (i.e. be join). > > > def functions_which_modifies_some_file_in_place(path): > output = open(path+'.tmp', 'w') > ..... > > I dont want a seperator inserted between path and the new extension. My impression of '+', is it always join like objects... str+str -> str list+list -> list tuple+tuple -> tuple So ... path+path -> path In all current cases, (that I know of), of differing types, '+' raises an error. Question: Is a path object mutable? Would the += operator create an new object or modify the original? p = path('C://somedir//somefile') p+='.zip' what would this do? p[-1]+='.zip' Or this? Cheer's Ron. From cliff at develix.com Sun Jul 31 20:43:32 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 17:43:32 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7xu0iale9x.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <8664uqhkfj.fsf@bhuda.mired.org> <7xu0iale9x.fsf@ruckus.brouhaha.com> Message-ID: <1122857012.19618.202.camel@localhost.localdomain> On Sun, 2005-07-31 at 16:57 -0700, Paul Rubin wrote: > Cliff Wells writes: > > > And what do I use to bundle my application for Unix? Most of the > > > things I build get installed on Unix servers. > > > > You install GUI apps on Unix *servers*? > > The usual way to do that is with a web GUI, but nothing stops you from > running Tkinter on a Unix server through a remote X connection. Of course not, but unless the servers are on a trusted network and use an authentication scheme such as kerberos, you are asking for trouble. Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From bronger at physik.rwth-aachen.de Sat Jul 30 02:54:59 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 30 Jul 2005 08:54:59 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> Message-ID: <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Hall?chen! Calvin Spealman writes: > The choice is GUI toolkits is largely seperate from > Python. Consider that they are just bindings to libraries that are > developed completely seperate of the language. GUI is should be > seperate from the language, and thus not bound to same > expectations and desires as elements of the language itself. I disagree. A modern language must provide a convenient and well-embedded way to write GUI applications. This is not a sign of decadence, but a very good promotional argument. Delphi and first and foremost VB are extremely popular, and it's sad to see that Python could get a lot more of the cake if the efforts for IDEs and toolkits were somewhat streamlined. Besides, all other already good aspects of Python wouldn't suffer at all. Tkinter fits into Python very well and it is very easily (if not trivially) accessible for users of our applications. People complain about non-native look-and-feel on Windows, but sorry, I simply find it unacceptably ugly on all platforms. Don't misunderstand me: I don't like neat GUI effects just for the sake of it but Tkinter makes an outdated impression on the end-user. I've been having a closer look at wxPython which is not Pythonic at all and bad documented. Probably I'll use it nevertheless. PyGTK and PyQt may have their own advantages and disadvantages. However, in my opinion we don't need yet another binding so thin that C or C++ is shining through, but a modern replacement for Tkinter with its Pythonic way of thinking. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From paul.villani at verizon.net Fri Jul 22 16:04:14 2005 From: paul.villani at verizon.net (Paul Villani) Date: Fri, 22 Jul 2005 20:04:14 GMT Subject: What does "::" mean? References: Message-ID: <2jcEe.258$eg4.204@trndny01> I'm very new to Python, but.... I think it's really ':' and ':' side-by-side with no values, not a single "::". In V2.3 and higher, slicing supports an optional third index which works as a step, e.g., X[2:9:2] fetches every other item in indexes 2-8. The useage you cite is really defaulting the start and end indexes, and decrementing the step index. Regards, "could ildg" wrote in message news:mailman.1932.1121820680.10512.python-list at python.org... I know that ":" can do slice works. But I saw "::" today and it puzzled me much, I can't find it in the python doc, so I raise this question here. The code is as below: ---------------------------------------------------------- Jython 2.2a1 on java1.5.0_03 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> live='live';print live live >>> live=live[::-1];print live evil >>> -------------------------------------------------------- "[::-1]" can reverse a string magicly, how did it do it? From mwm at mired.org Wed Jul 27 00:26:00 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 27 Jul 2005 00:26:00 -0400 Subject: Safest manner to extend search path for modules? References: <1122353419.940318.226640@g47g2000cwa.googlegroups.com> Message-ID: <8664uwoox3.fsf@bhuda.mired.org> "Joseph Turian" writes: > Hi, > > What is the safest manner to extend search path for modules, minimizing > the likelihood of shooting oneself in the foot? > > The system (which includes scripts and their shared modules) may be > checked out in several different locations, but a script in a > particular checked-out version of the system should only use modules > from that checkout location. > > e.g. if the system contains a directory scripts/foo/ where all the > scripts are housed, and scripts/modules/ where all the modules are > housed, then is it correct for each script in scripts/foo/ to begin > with: > import sys, os.path > sys.path.append(os.path.join(sys.path[0], "../modules")) > > If so, is there a cleaner way of doing this than including the above > text in all scripts? Put that text in a module that is already on the path, and then import that module. Or mabye generalize it into a function: import sys, os.path def fixpath(*new): sys.path.extend(os.path.join(sys.path[0], x) for x in new) This requires 2.4. Change it to ([os.path ... new]) for earlier versions. Of course, I note that sys.path[0] is '', so the join doesn't do anything. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jstroud at mbi.ucla.edu Sat Jul 2 20:09:45 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 2 Jul 2005 17:09:45 -0700 Subject: Regular Expression for pattern substitution In-Reply-To: <20050701163933.35954.qmail@web53912.mail.yahoo.com> References: <20050701163933.35954.qmail@web53912.mail.yahoo.com> Message-ID: <200507021709.45963.jstroud@mbi.ucla.edu> You might want to be a little more explicit. Do you know that this = "this" that = "that" or do you mean this = `the part before the \D*` that = `the part after the \D*` If you mean the former, then the previously proposed py> import re py> line = 'see this man with that woman holding this dog and that cat' py> r = re.compile(r'this(\D*?)that') py> r.sub(r'that\1this',line) will do fine. If you mean the latter, then you should describe the type of pattern that this and that belong to. Also, consider how greedy your \D* is: py> line = 'this abcd this efgh that' py> r.sub(r'that\1this',line) 'that abcd this efgh this' Would this be the result you expect? James On Friday 01 July 2005 09:39 am, Vibha Tripathi wrote: > It'd be silly to write the code for it if it already > exists somewhere in the Python re or sre library > module: > > I need to find and replace all strings in a text file > from a certain pattern to another pattern. > > so for example if I see 'this(\D*)that' anywhere in > the file then I'd like to make is 'that(\D*)this' > where the middle part of the strings remains > unmodified. > > Any suggestions? > > Peace. > Vibha > > PS. How do I avoid getting my email ID web-published > for this mailing list.? > > > > ____________________________________________________ > Yahoo! Sports > Rekindle the Rivalries. Sign up for Fantasy Football > http://football.fantasysports.yahoo.com -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at REMOVETHIScyber.com.au Sat Jul 30 07:45:38 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 30 Jul 2005 21:45:38 +1000 Subject: Comparison of functions Message-ID: Playing around with comparisons of functions (don't ask), I discovered an interesting bit of unintuitive behaviour: >>> (lambda y: y) < (lambda y: y) False Do the comparison again and things become even more bizarre: >>> (lambda y: y) < (lambda y: y) True >>> (lambda y: y) < (lambda y: y) False This behaviour should be easy for experienced Pythonisters to answer, but will probably confuse beginners greatly. For the benefit of beginners, imagine we expand the first line into two, and commit what some people call an abuse of lambdas: we bind them to names. >>> a = lambda y: y >>> b = lambda y: y >>> a at 0xf70598ec> >>> b at 0xf7059844> a and b are now bound to two objects, each of which is an anonymous function that just happens to do the same thing. But each time you create a lambda function, you get a different object at some unpredictable location in memory. This is where my level of Python knowledge fails me. I don't understand how Python is comparing the two objects since neither a nor b have any rich comparison methods or even the old-style __cmp__ method. >>> a < b False So I'm puzzled about how Python compares the two. If we compare a and b again, we will always get the same answer. But if we create a new pair of anonymous functions with lambda, and compare them, it is the luck of the draw each time whether the first compares bigger or smaller than the second. -- Steven. From rbt at athop1.ath.vt.edu Fri Jul 22 09:22:39 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 22 Jul 2005 09:22:39 -0400 Subject: broken links Message-ID: <1122038559.30697.0.camel@athop1.ath.vt.edu> How can I find broken links (links that point to files that do not exist) in a directory and remove them using Python? I'm working on RHEL4 Thanks, rbt From phillip.watts at anvilcom.com Tue Jul 5 09:48:53 2005 From: phillip.watts at anvilcom.com (phil) Date: Tue, 05 Jul 2005 08:48:53 -0500 Subject: More On - deepcopy, Tkinter References: <42C9B738.7010604@anvilcom.com> Message-ID: <42CA8FC5.4000607@anvilcom.com> I posted the following yesterday and got no response and did some testing simplifying the circumstances and it appears that deepcopy fails when the object to be copied contains a reference to a Canvas Object. Perhaps any Tkinter object, didn't get that far. The problem arises because I have a geometry tutorial with a progression of drawings and want the students to be able to go "back". Creating "snapshots" of points in time in the tutorial makes a clean and elegant solution possible. Other solutions I am trying to come up with are very messy. It is frustrating to think that in a language like python there might be things which you can't make a copy of. That is bizarre enough to wonder about a deep flaw or hopefully I'm just doing something very wrong. Any ideas appreciated. phil wrote: > I wrote the following to prove to myself that > deepcopy would copy an entire dictionary > which contains an instance of a class to > one key of another dictionary. > Note that after copying adict to ndict['x'] > I delete adict. > Then ndict['x'] contains a good copy of adict. > works great. > > > class aclass: > def __init__(s): > s.anint = 123 > aninstance = aclass() > adict = {} > adict['y'] = aninstance > > ndict = {} > ndict['x'] = copy.deepcopy(adict) > del adict > print ndict > print ndict['x']['y'] > print ndict['x']['y'].anint # this line prints 123 > print > > Then in the following code when I try to deepcopy > s.glob.objs I get following error > Note that s.glob.objs is a dictionary and I am > attempting to copy to a key of s.save, another dict, > just like above. > ?????????? > s.glob.objs may have several keys, the data for each > will be instance of classes like line and circle. > Those instances will have tkinter canvas objects in them. > > class Graph: > def __init__(s): > class DummyClass: pass > s.glob = DummyClass() > s.glob.objs = {} > .. # here add some instance of objects like > .. # circles and lines to s.glob.objs > # instantiate dialog > s.DI = dialog(s.glob) > > class dialog: > def __init__(s,glob): > s.glob = glob > s.save = {} > > def proc(s): > cur = someint > s.save[cur] = copy.deepcopy(s.glob.objs) > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "/home/phil/geo/g.py", line 303, in enter > else:s.proc() > File "/home/phil/geo/g.py", line 245, in proc > s.save[cur][k] = copy.deepcopy(s.glob.objs[k][0]) > File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy > y = copier(x, memo) > File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst > state = deepcopy(state, memo) > File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy > y = copier(x, memo) > File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict > y[deepcopy(key, memo)] = deepcopy(value, memo) > File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy > y = copier(x, memo) > File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst > state = deepcopy(state, memo) > File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy > y = copier(x, memo) > File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict > y[deepcopy(key, memo)] = deepcopy(value, memo) > File "/usr/local/lib/python2.3/copy.py", line 206, in deepcopy > y = _reconstruct(x, rv, 1, memo) > File "/usr/local/lib/python2.3/copy.py", line 338, in _reconstruct > y = callable(*args) > File "/usr/local/lib/python2.3/copy_reg.py", line 92, in __newobj__ > return cls.__new__(cls, *args) > TypeError: function() takes at least 2 arguments (0 given) > > From renting at astron.nl Fri Jul 29 06:16:22 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 29 Jul 2005 12:16:22 +0200 Subject: Filtering terminal commands on linux Message-ID: I have the problem that I need to interact with a CD/DVD burning program called gear. I do this by running it in a pseudo terminal. I also need to log what I'm doing, so I copy all output I get from gear to a logfile. The problem is that gear uses terminal control commands to create a nice commandline interface. I can filter out all non printable characters to get something I can put in my logfile, but this leaves a lot of the terminal control commands. My problem is that the control sequences are variable in length, and themselves printable text. they probably vary depending on the $TERM setting too. Does anyone have code that can parse this, so I can get rid of the ugly control sequences? Any suggestions on how to do this with regular expressions is welcome too, with my limited knowledge I don't know how to do it. Finding the beginning is kind of easy, as it always starts with [, but the length varies after that. My output now looks like this: 2005-07-28 14:27:58 Message : [76C^M Scanning busses for recorder devices...please wait... 2005-07-28 14:27:59 Message : [K[77C^M Driver found: Linux Scsi Generic v3 Driver. 2005-07-28 14:27:59 Message : [76C^M PLEXTOR DVDR PX-716A revision 1.07 found on /dev/sg1 2005-07-28 14:27:59 Message : 2005-07-28 14:27:59 Message : [76C^M [23;54H[25DPLEXTOR DVDR PX-716A [11;78H^M Recorder PLEXTOR DVDR PX-716A used. 2005-07-28 14:27:59 Message : [9B[K[79C[6DReady^M[K[79C[18DInitializing tape^M[K[79C [25DInitializing tape driver[12;78H^M Selected tape interface: Standard SCSI driver 2005-07-28 14:27:59 Message : [76C^M Scanning bus for tape units...please wait...^M [K[77C^M Driver found: Linux Scsi Generic v3 Driver. 2005-07-28 14:27:59 Message : [76C^M HP[7CC5683A[11Crevision C908 found on /dev/sg0 I would like: 2005-07-28 14:27:58 Message : Scanning busses for recorder devices...please wait... 2005-07-28 14:27:59 Message : Driver found: Linux Scsi Generic v3 Driver. 2005-07-28 14:27:59 Message : PLEXTOR DVDR PX-716A revision 1.07 found on /dev/sg1 2005-07-28 14:27:59 Message : 2005-07-28 14:27:59 Message : PLEXTOR DVDR PX-716A Recorder PLEXTOR DVDR PX-716A used. 2005-07-28 14:27:59 Message : Ready Initializing tape Initializing tape driver Selected tape interface: Standard SCSI driver 2005-07-28 14:27:59 Message : Scanning bus for tape units...please wait... Driver found: Linux Scsi Generic v3 Driver. 2005-07-28 14:27:59 Message : HP 5683A revision 08 found on /dev/sg0 Thank you. From dalloliogm at fastwebnet.it Thu Jul 7 05:51:19 2005 From: dalloliogm at fastwebnet.it (Giovanni Dall'Olio) Date: 7 Jul 2005 02:51:19 -0700 Subject: Do a "Python beginners e-mail list" exist? In-Reply-To: References: Message-ID: <1120729879.930416.320630@g44g2000cwa.googlegroups.com> Hi, have you seen the python ML at www.python.it? It's in Italian. You can find even other tutorial for beginners here. See also www.zonapython.it From user at host.invalid Wed Jul 20 08:21:14 2005 From: user at host.invalid (Heikki Orsila) Date: Wed, 20 Jul 2005 12:21:14 +0000 (UTC) Subject: list implementation References: <1121655435.153214.292520@o13g2000cwo.googlegroups.com> <1121665250.103706.323680@g47g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [sj] >> Thus, random access is an O(1) operation while insertion/deletion is an >> O(n) operation. > Yes. Unfortunately no. Check Terry Reeds answer. Random access is O(1), insertion/deletion to front is O(n), and i/d to back is O(1). The back i/d operation has amortized O(1) cost. -- Heikki Orsila Barbie's law: heikki.orsila at iki.fi "Math is hard, let's go shopping!" http://www.iki.fi/shd From ntv1534 at gmail.com Wed Jul 20 13:44:22 2005 From: ntv1534 at gmail.com (MooMaster) Date: 20 Jul 2005 10:44:22 -0700 Subject: Need to interrupt to check for mouse movement In-Reply-To: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> References: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> Message-ID: <1121881462.490728.154290@g43g2000cwa.googlegroups.com> Have you tried binding EVT_MOTION(func) to your window? From steve at REMOVETHIScyber.com.au Mon Jul 18 08:52:12 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 18 Jul 2005 22:52:12 +1000 Subject: Efficiently Split A List of Tuples References: <1121654309.453199.112300@f14g2000cwb.googlegroups.com> Message-ID: On Sun, 17 Jul 2005 19:38:29 -0700, Raymond Hettinger wrote: > Executive summary: Python's for-loops are both elegant and fast. It > is a mistake to habitually avoid them. And frequently much more readable and maintainable than the alternatives. I cringe when I see well-meaning people trying to turn Python into Perl, by changing perfectly good, fast, readable pieces of code into obfuscated one-liners simply out of some perverse desire to optimize for the sake of optimization. -- Steven. From williams13 at llnl.gov Wed Jul 27 17:56:16 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Wed, 27 Jul 2005 14:56:16 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050727210307.GB3876@tishler.net> References: <20050725201132.GA3440@tishler.net> <20050727191626.GC2272@tishler.net> <42E7E351.3030706@llnl.gov> <20050727210307.GB3876@tishler.net> Message-ID: <42E80300.4030708@llnl.gov> [snip] >I didn't get this error. Did you forgot to install one of the >libdb${version}-devel packages: > > $ cygcheck -cd | grep 'libdb.*-devel' > libdb2-devel 2.7.7-4 > libdb3.1-devel 3.1.17-2 > libdb4.1-devel 4.1.25-1 > libdb4.2-devel 4.2.52-1 > No, I did an install all at the top of the installation. Didn't know I needed to specify libraries. If I select "install" for everything (that is, all packages show "install") shouldn't this include the above? -Dean From rkern at ucsd.edu Fri Jul 22 11:07:27 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 22 Jul 2005 08:07:27 -0700 Subject: is this possible? In-Reply-To: <1122044382.956382.287310@g47g2000cwa.googlegroups.com> References: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> <1122044382.956382.287310@g47g2000cwa.googlegroups.com> Message-ID: scrimp wrote: > I am using reportlab not to generate PDF files, but I want to be able > to print them without having to install acrobat reader. I looked > through the users guide and found nothing about printing to a printer > (programmatically). I want to be able to automate the printing of > reports when they are available. Does anyone know how this is done > using reportlab? thanks! It isn't done using ReportLab. Follow Terry Hancock's advice. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gn at oglaroon.de Sat Jul 30 10:14:14 2005 From: gn at oglaroon.de (Georg Neis) Date: 30 Jul 2005 14:14:14 GMT Subject: Comparison of functions References: <3l1druF10aj5pU1@individual.net> Message-ID: * Reinhold Birkenfeld wrote: > Steven D'Aprano wrote: >>>>> 1+0j == 1 > 0 >> True > > (1+0j == 1) yields True, which is comparable to 0. "a == b > c" is equivalent to "a == b and b > c": >>> 1 == 1+0j > 0 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= From nochiel at gmail.com Thu Jul 21 09:22:49 2005 From: nochiel at gmail.com (yoda) Date: 21 Jul 2005 06:22:49 -0700 Subject: Listing Processes Running on Remote Machines Message-ID: <1121952169.006705.162960@g49g2000cwa.googlegroups.com> Hello Hackers, I'm developing a large scale distributed service and part of the requirement is that I be able to monitor clients in a very granular way. To this end, I'd like to know if there is any way to get a list of all the processes running on a remote client\machine. I need to be able to do this on demand. (i.e on user demand) Please note that the clients run heterogeneous operating systems mainly Linux and Windows2000\XP From guy.lateur at b-b.be Fri Jul 8 09:37:00 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Fri, 08 Jul 2005 13:37:00 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: <0kvze.140169$Q37.7422045@phobos.telenet-ops.be> Yes! I finally got it to work. I've written a VBscript which I'll call from python. It uses Outlook.Redemption's SafeMailItem. No need to use IMAP or whatever services. Only weird thing is it doesn't put the msg in the Inbox, as I intended, but in the Drafts folder. Well, never mind that, it's a temp object anyway. Here's the code: Dim sItem, oItem Dim myDestBox, myNS, myOL Set myOL = CreateObject("Outlook.Application") Set myNS = myOL.GetNamespace("MAPI") Set sItem = CreateObject("Redemption.SafeMailItem") Set myDestBox = myNS.GetDefaultFolder(6) Set oItem = myDestBox.Items.Add(0) sItem.Item = oItem sItem.Import "H:\Inhoud-iedereen\Inhoud-Guy\app\BBProject\data\test\Leemarchitect.msg", 3 sItem.Save Cheers, g From sjmaster at gmail.com Wed Jul 27 13:15:31 2005 From: sjmaster at gmail.com (Steve M) Date: 27 Jul 2005 10:15:31 -0700 Subject: Create a variable "on the fly" In-Reply-To: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Message-ID: <1122484531.000796.99020@g47g2000cwa.googlegroups.com> PythonWin 2.3.5 (#62, Feb 9 2005, 16:17:08) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> locals()['OSCAR'] = 'the grouch' >>> OSCAR 'the grouch' >>> From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 13:10:50 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 19:10:50 +0200 Subject: Comparison of functions In-Reply-To: References: <3l1druF10aj5pU1@individual.net> Message-ID: <3l1qkrF10ngb6U1@individual.net> Steven D'Aprano wrote: > On Sat, 30 Jul 2005 15:32:45 +0200, Reinhold Birkenfeld wrote: > >>> Um, I didn't ask to compare complex numbers using comparison operators. I >>> asked to sort a list. And please don't tell me that that sorting is >>> implemented with comparison operators. That just means that the >>> implementation is confusing numeric ordering with sort order. >> >> Sorting is implemented with comparison operators. How should it be otherwise? > > That's a good question, and that's why I'm exploring different comparisons > in Python, trying to understand what Python already does, and the pros and > cons thereof, before I suggest anything new. > >> Would you prefer a __sort__ method to specify sort order? > > Well, there are an infinite number of sort orders. Most of them are pretty > much useless, but even if we limit ourselves to common, useful sort > orders, there are still a good half dozen or more. That's why the sort method does have certain keyword arguments with which you can customize sorting to your liking. But unless the standard sort without arguments should be disallowed, it has to resort to comparison. > So at this time, I'd rather not be pinned down to some half-baked > "solution" before I have even understood the problem. That's wise. >> But complex numbers are not greater or littler than others. You can't order them, >> not on a one-dimensional scale. > > Of course you can order them. You are confusing order with magnitude. The > two are not identical, although they are similar enough in some contexts > as to cause confusion. Well, you can order everything according to some specs, but you can't find a default sort order for everything. That's where custom comparison functions can help. Correct me if I'm wrong, but is there a default order for complex number? Reinhold From godoy at ieee.org Sun Jul 31 17:01:52 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 31 Jul 2005 18:01:52 -0300 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <861x5ehk4g.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > We already have multiple distributions of Python: CPython, IronPython, > and Jython (and there's at least one more). We even have multiple > distributions of CPython, what with Active State doing their own and > the MacPython distribution. I'm not proposing a fundamental change in > the world, I'm suggesting an addition that would satisify the OPs > needs. > > The "standard" distributor is whichever one your organization settles > on when it comes time to choose a Python distribution. So we don't solve the problem with a "standard" distribution and that was the point I was trying to show. In fact this sounds more like a joke I've heard a while ago: standards, if you don't like the ones out there, create your own. > None of which has stopped linux from following this path. And solve a completely different problem while sharing the very same problem you, on the post prior to mine, was trying to solve: what is the standard GUI on a Linux distribution? QVWM? WindowMaker? Gnome? KDE? FVWM? -- Jorge Godoy From invalidemail at aerojockey.com Sun Jul 24 17:02:25 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 24 Jul 2005 14:02:25 -0700 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: Message-ID: <1122238945.724456.292440@f14g2000cwb.googlegroups.com> Soeren Sonnenburg wrote: > On Sun, 2005-07-24 at 13:36 +1000, Steven D'Aprano wrote: > > On Sat, 23 Jul 2005 18:30:02 +0200, Soeren Sonnenburg wrote: > > > > > Hi all, > > > > > > Just having started with python, I feel that simple array operations '*' > > > and '+' don't do multiplication/addition but instead extend/join an > > > array: > > > > * and + are not array operations, they are list operations. > > > > Lists in Python can contain anything, not just numeric values. > > That seems to be *the point*. Although list(a) + list(b) could create a > list [ a[0]+b[0], ...] and bail out if for elements '+' is not > defined... > > > Python doesn't have built-in mathematical arrays, otherwise known as > > matrices. There are modules that do that, but I haven't used them. Google > > on Numeric Python. > > Well I am aware of that but I don't understand the reasons of having > both lists (which are infect arrays) and *arrays ? *I* would rather drop > '+' and '*' to work like they do in *array ... The number of programmers who do operations on mathematical arrays is pretty small. The number of programmers who need to do things like concatenate lists is much larger. Thus, the decision was made to use the valuable operator for the more common thing. Truth be told, I rarely use + on lists (I tend to use list.extend mostly), and if + had instead been used for element-by-element operations, I don't think it would have affected the overall quality of Python too much. But, as it's been said, it's a little late to change it now. -- CARL BANKS From steve at REMOVETHIScyber.com.au Mon Jul 11 22:54:32 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 12:54:32 +1000 Subject: Parsing Data, Storing into an array, Infinite Backslashes References: <1121114842.623294.156790@g44g2000cwa.googlegroups.com> Message-ID: On Mon, 11 Jul 2005 13:47:22 -0700, supercomputer at gmail.com wrote: > I am using this function to parse data I have stored in an array. > > This is what the array looks like: > > [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed', > 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ... ] [snip more of the array] > This is the code to parse the array: > > count=0 > place=0 place is not used in your function. Remove it. > query=[] > while 1: > try: > i=fetch.next() What is fetch and what does fetch.next() do? It is considered bad programming practice to use a variable i for anything except for i in range(). i for "index", not i for "next record". > except StopIteration: > break > if i[1] != count: What is i? A list? A tuple? A dict? What is stored in it? > ++count > query.append(count) Why are you appending the numeric value of count to the list query? Since count starts at zero, and increases by one, your list is just [1, 2, 3, ...] > qval=`query[count]` It looks like you are setting the variable qval to the string representation of a number. Backticks are being depreciated, you should write this as qval = str(query[count]). But if I have understood your program logic correctly, query[count] up to this point is just count. So a much simpler way is to just use qval = str(count). > query[count]=qval+i[2]+"="+i[3]+", " Impossible to know what this does since we don't know what i is. Hint: it is easier to read and parse expressions by adding a small amount of whitespace: query[count] = qval + i[2] + "=" + i[3] + ", " > print qval,"\n" > > When it runs I get an output similar to this. > > \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Type=DDR > SDRAM, > \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Size=512, > \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Slot=DIMM2/J13, > \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'ConfigurationType=2, > \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Summary=0, > \\\\\\\\\\\\\\\'Speed=PC3200U-30330, \\\\\\\'Type=DDR SDRAM, > \\\'Size=512, \'Slot=DIMM3/J14, ' > > When it's supposed to print just the plain text with the numbers etc. See below for some further hints. > I have changed these lines: > > qval=`query[count]` > query[count]=qval+i[2]+"="+i[3]+", " > > To this: > > query[count]=query[count]+i[2]+"="+i[3]+", " > > I get this error: > > Traceback (most recent call last): File "infnode.py", line 60, in ? > query[count]=query[count]+i[2]+"="+i[3]+", "TypeError: unsupported > operand type(s) for +: 'int' and 'str' Yes. query[count] is an integer equal to count. i[2] is who-knows-what. "=" is a string. You can't add strings to ints. > So I try and fix it by doing this: > > query[count]=`query[count]`+i[2]+"="+i[3]+", " That is functionally equivalent to your first version. > Can someone please point me in the right direction I am sure that the > `query[count]` is causing the backslashes. I doubt it very much. But you can test it by adding some print lines in your code: change this: qval=`query[count]` query[count]=qval+i[2]+"="+i[3]+", " to this: print "Count is: ", count print "query[count] is: ", query[count] qval=`query[count]` print "qval is: ", qval query[count]=qval+i[2]+"="+i[3]+", " print "query[count] changed.\nNew value is: ", query[count] -- Steven. From scrimp212 at yahoo.com Thu Jul 21 16:24:28 2005 From: scrimp212 at yahoo.com (scrimp) Date: 21 Jul 2005 13:24:28 -0700 Subject: print pdf file to network printer using python In-Reply-To: <11dver1apnfd64a@corp.supernews.com> References: <1121949053.440544.108150@g47g2000cwa.googlegroups.com> <11dver1apnfd64a@corp.supernews.com> Message-ID: <1121977468.665233.162900@g44g2000cwa.googlegroups.com> I just tried it and all that printed out was garbage. I found another way to do it. It all depends on what you wanna do. If u want to print to the default printer (easiest way) then just use this line: win32api.ShellExecute(0, "print", file_path, None, ".", 0) file_path of course being the full path of the file Now, if u wanna print to another printer then u have to add a line: win32print.SetDefaultPrinter(printer_name) win32api.ShellExecute(0, "print", file_path, None, ".", 0) printer_name being the NAME of the printer that is installed on the machine not the path of the printer Everything works good and the PDF file comes out perfect. The only problem I have is that ShellExecute command starts up a blank session of Acrobat Reader. I need that Acrobat to be terminated. I think by using ShellExecute it does not provide the correct handle that python needs to terminate the process. Any suggestions? From benji at benjiyork.com Tue Jul 19 07:35:39 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 19 Jul 2005 07:35:39 -0400 Subject: Windows command line problem In-Reply-To: <1121762108.120184.201340@g47g2000cwa.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> <1121726398.861595.31350@g43g2000cwa.googlegroups.com> <1121759914.689112.272530@z14g2000cwz.googlegroups.com> <1121762108.120184.201340@g47g2000cwa.googlegroups.com> Message-ID: <42DCE58B.6040208@benjiyork.com> MarkE wrote: > The answer appears to be: > An example command line for running the script was written in a word > document. The "Autocorrect" (sic) feature in word replaces a normal > dash There is a lesson there I wish more people would learn: Word is not a text editor. :) -- Benji York From gene.tani at gmail.com Sat Jul 23 11:22:38 2005 From: gene.tani at gmail.com (gene tani) Date: 23 Jul 2005 08:22:38 -0700 Subject: Neat access to db query results In-Reply-To: <1122108021.130671.32330@f14g2000cwb.googlegroups.com> References: <1122108021.130671.32330@f14g2000cwb.googlegroups.com> Message-ID: <1122132158.009005.29670@o13g2000cwo.googlegroups.com> There's a few places to stash apps, libraries, or small code snippets so they can be search engined, if you provide some inline comments, unit/functional tests, and examples of how to use/known limitations: Vaults Parnassus, dmoz, ActiveState cookbook http://aspn.activestate.com/ASPN/Cookbook/Python http://www.pypackage.org/packages http://dmoz.org/Computers/Programming/Languages/Python/Modules/ http://www.vex.net/parnassus/ From rkern at ucsd.edu Sun Jul 24 21:31:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 18:31:39 -0700 Subject: Simple Problem In-Reply-To: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> References: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> Message-ID: ncf wrote: > I know I've seen this somewhere before, but does anyone know what the > function to escape a string is? (i.e., encoding newline to "\n" and a > chr(254) to "\xfe") (and visa-versa) In [1]: s = "foo\n\xfe" In [2]: s.encode("string_escape") Out[2]: 'foo\\n\\xfe' In [3]: repr(s)[1:-1] Out[3]: 'foo\\n\\xfe' -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nun at example.com Fri Jul 15 16:20:20 2005 From: nun at example.com (Mitja) Date: Fri, 15 Jul 2005 22:20:20 +0200 Subject: Python Newbie References: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> Message-ID: On Thu, 14 Jul 2005 12:24:29 +0200, linuxfreak wrote: > So heres me asking if anyone has any pointers > to some good basic python tutorial. Something that teaches one to get > going. The official tutorial is quite informal yet effective: python.org -> documentation -> tutorial From moranar at alice.it Sat Jul 30 13:57:20 2005 From: moranar at alice.it (Adriano Varoli Piazza) Date: Sat, 30 Jul 2005 17:57:20 GMT Subject: Comparison of functions In-Reply-To: References: Message-ID: <4cPGe.28613$fm.2023944@news4.tin.it> Steven D'Aprano ha scritto: > Do you understand the difference between partial and total ordering, or > weakly and strongly ordered? When you do understand them, come back and > tell me again whether you still think lexicographic sorting has no meaning > whatsoever. > I think I answered this in another post... If you want to order text strings (as complex numbers in an index in a book, or in a lexicographic sort are) do so. I understand the importance it has to you, but it's hardly reasonable to argue that Python should do the most unintuitive thing with complex numbers by default just because it suits you. -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar MSN: adrianomd at hotmail.com ICQ: 4410132 From wpower at zeta.org.au.nospamplease Wed Jul 20 04:37:48 2005 From: wpower at zeta.org.au.nospamplease (David Trudgett) Date: Wed, 20 Jul 2005 18:37:48 +1000 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: "Thomas Bartkus" writes: > > Good question! Wither Borland? > > My impression (second hand - based on no direct experience with > Kylix!) is that Borlands wonderful Delphi product ported to Linux > has been a dissapointment. > > * * * Someone with real experience on Kylix - please jump in here! It has been two or three years since I gave Kylix a try, so my memory is a bit vague on the specifics. I was working in a Delphi shop and wanted to port (at least some of) our apps to Linux using Kylix (I think it was version 3). I think I ported one and a half apps and more or less gave up or put it on the back burner. My impression was that Kylix still wasn't ready for serious development work. The type of application I was working on (porting) involved client/server database access, and TCP communications with other applications. It never really worked correctly (I forget what the problems were just now), but probably could have been made to work correctly. The point was, however, that porting (a relatively simple) Delphi app to Kylix shouldn't have been that hard. > > Calling Delphi "similar to Visual Basic" is hurtful because I > believe that VB is the product of looting and pillaging the talent > that came out of Borland. I'm guessing that Microsoft has > successfully targeted this perceived competitor with destruction. > > If Kylix were of the quality of Delphi, it would be a killer Linux app. Possibly. Unfortunately, I don't believe that the whole GUI building approach of Delphi/Kylix (or other similar tools) is much chop. It encourages one, for instance, to just place elements on the screen in fixed positions that make no allowance for differing fonts, screen resolutions, etc. Java (my experience is with JBuilder) is much better in this regard, although the different paradigm takes some getting used to. However, all GUI builders with which I'm familiar (not many) seem to have very real limitations when it comes to designing very complex interfaces. Kenny Tilton's Cells project (ask on comp.lang.lisp) has set me to thinking along these lines. In the past, I never gave it much consideration. Programmers who like Pascal should look at Ada as a better alternative. If I wanted to program in a Pascal-like language on Linux, Ada (the GNU Gnat compiler, integrated with GCC) is the one that I would use. Ada, you could say, is like Pascal on steroids. Caveat: I've read Ada books, but haven't programmed in it, and my main concern is that its ultra strong typing might get in my way -- or alternatively, force greater rigour, as the Ada folks might say ;-). These days, for hacking about, I prefer Common Lisp. It's faster (sometimes approaching the speed of compiled C/Pascal) and much more powerful than Python, but doesn't have the same library support (smaller community), and application bundling and delivery *can* be a potential problem, depending on various factors (such as whether you want to license a commercial Common Lisp). Also, similar to Python, there is no standard GUI framework defined for Common Lisp, so choosing from the GUI frameworks available can be a challenge (I've only programmed a simple GUI app using the great little Ltk library by Peter Herth, which talks to Tk over a socket). My advice would be to steer clear of Kylix and choose one of the other environments suggested to you. If you really like Pascal, fpc may be a possibility as someone mentioned. I haven't looked into it any time in the last couple of years, though, so I don't know its status. I really would suggest a serious look at Ada, though, if you want to develop fast, industrial strength applications, or take advantage of built-in concurrency support and lots of other goodies. David -- David Trudgett http://www.zeta.org.au/~wpower/ I was in the pub last night, and a guy asked me for a light for his cigarette. I suddenly realised that there was a demand here and money to be made, and so I agreed to light his cigarette for 10 pence, but I didn't actually give him a light, I sold him a licence to burn his cigarette. My fire-licence restricted him from giving the light to anybody else, after all, that fire was my property. He was drunk, and dismissed me as a loony, but accepted my fire (and by implication the licence which governed its use) anyway. Of course in a matter of minutes I noticed a friend of his asking him for a light and to my outrage he gave his cigarette to his friend and pirated my fire! I was furious, I started to make my way over to that side of the bar but to my added horror his friend then started to light other people's cigarettes left, right, and centre! Before long that whole side of the bar was enjoying MY fire without paying me anything. Enraged I went from person to person grabbing their cigarettes from their hands, throwing them to the ground, and stamping on them. Strangely the door staff exhibited no respect for my property rights as they threw me out the door. -- Ian Clarke From bvande at po-box.mcgill.ca Fri Jul 1 19:25:12 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 01 Jul 2005 19:25:12 -0400 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> <42c41ef2@usenet01.boi.hp.com> <42C5AD1F.5060902@po-box.mcgill.ca> Message-ID: <42C5D0D8.7080500@po-box.mcgill.ca> Robert Kern said unto the world upon 01/07/2005 17:24: > Brian van den Broek wrote: > > >>Well, I found it ironic, but only when you add that the genetic >>algorithm approach came up in the context of a "best fit" problem. >>Survival of the fittest indeed :-) > > > Optimization codes don't always succeed. What's the irony? > Well, the punning on 'fit' (fittest in the sense of "most suitable, or best adapted", appropriate to Darwinian theory vs. fit in the sense of "to be of the right measure or proper shape and size for") amused me. There is at least shades of irony in that the best fit in the Darwinian sense appropriate to genetic algorithms needn't be the best fit in the sense of proper size and shape. So, in suitable circumstances, the meaning of "best fit" in one sense being the opposite of what was intended in the other. (As in, my sense that it was ironic didn't reside solely in the genetic algorithm's possible failure to find the optimal solution, but how the semantic ambiguity of fit plugs into that in the context of the original problem.) I'd call that at least semi-irony. (Yes, I get that the best fit for both evolutionary theory and the genetic algorithm isn't the absolutely best adapted, but best adapted as measured relative to the contrast class of available alternatives--a local maximum if you like.) All in all, I wish I'd not hit send in the first place. This is perilously close to sending me into fits ;-) Best, Brian vdB From aahz at pythoncraft.com Fri Jul 29 10:45:33 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2005 07:45:33 -0700 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: In article , Dan Sommers wrote: > >Was Tim writing about developing Python itself, or about developing >other programs with Python? Yes. (C'mon, didja really expect any other answer?) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From deets at web.de Mon Jul 25 07:03:08 2005 From: deets at web.de (Diez B.Roggisch) Date: Mon, 25 Jul 2005 11:03:08 +0000 (UTC) Subject: Invoke a method to a specific thread References: Message-ID: Varghj?rta gmail.com> writes: > If I have "GUIClass":... > And start another thread and from that thread I want to call the > method "PaintSomething()" in "GUIClass" _in_ the same thread that > "GUIClass" lives in. There is no such thing in python, or any programming language for that matter. If a thread wants to run in an endless loop, there is nothing you can do about that - apart from maybe killing it. But even that won 't work all the time and is dangerous. However, in GUIs there is usually some so called event-loop. And for the task you have in mind you need a way to insert a custom event into that loop that will be executed the next time that gui thread is idle. Qt uses QCustomEvents for this. Swing has it's SwingUtilities.invokeLater http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html#invokeLater and others have different means. So - whatever GUI you use, it depends on that what to do. Diez From huron at sopinspace.com Mon Jul 4 08:16:48 2005 From: huron at sopinspace.com (Huron) Date: Mon, 04 Jul 2005 14:16:48 +0200 Subject: python project layout References: <9JqdnRP9IqxM_ljfRVn-rA@powergate.ca> Message-ID: Hi again, For instance, if you have several classes implementing the same interface (say, doing the same things with different strategies), how would you organize that in terms of files (modules) and directories (packages) ? -- huron From devlai at gmail.com Tue Jul 5 15:46:18 2005 From: devlai at gmail.com (Devan L) Date: 5 Jul 2005 12:46:18 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: <1120592778.753940.162280@z14g2000cwz.googlegroups.com> def flatten(iterable): if not hasattr(iterable, '__iter__'): return [iterable] return sum([flatten(element) for element in iterable],[]) Recursion makes things so much shorter. From bronger at physik.rwth-aachen.de Sun Jul 31 07:46:55 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 13:46:55 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> <7xhdebv1t0.fsf@ruckus.brouhaha.com> <87vf2rpc0i.fsf@wilson.rwth-aachen.de> <7xy87nw75w.fsf@ruckus.brouhaha.com> Message-ID: <87r7dfp58w.fsf@wilson.rwth-aachen.de> Hall?chen! Paul Rubin writes: > Torsten Bronger writes: > >>>> Does py2exe work for all GUI libraries? >>> >>> No, it's Windows-only. >> >> However, OS'es and GUI libraries are different axes in the space >> of possibilities. > > I'm not sure what you mean. I didn't ask "does it work with OSX" but "does it work with wxPython or PyQt". py2exe only creates Windows files, that's right, but why is this important here? Be that as it may, some Google postings suggest that it works at least with wxPython. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From harold.fellermann at upf.edu Sat Jul 2 10:41:18 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Sat, 2 Jul 2005 16:41:18 +0200 Subject: trace function calls to get signatures Message-ID: Hi all, I am trying to write a script that prints out the signatures of each function call that occurs during the execution of a second script which is invoked by my program. i.e. if the inspected program is 'foo.py': def bar(x,y,z=None) : pass bar(1,"a",bar) bar(2,int) the output of my script should be: foo.bar(int,str,function) foo.bar(int,type,NoneType) I thought I go for sys.settrace() and achieved the following: import sys import types def tracefunc(frame,event,arg) : if event is 'call' : return trace_call(frame,event,arg) else : return None def trace_call(frame,event,arg) : code = frame.f_code scope = frame.f_locals try : print code.co_name+"("+",".join( [ str(type(scope[var])).split("'")[1] for var in code.co_varnames ] )+")" except KeyError : pass return None if __name__ == "__main__" : prog = sys.argv[1] sys.argv.pop(0) sys.settrace(tracefunc) __import__(prog) the output of the above example is: bar(int,str,function) bar(int,type,NoneType) which is pretty close, but I need / would like to improve several things, but have no idea how to do it: 1. I would like to have not only the name of the functions and type arguments but their full package/module/class-path, e.g. xml.dom.pulldom.PullDOM.clear However, I cannot find a way from the frame object to the function object where I could find the information. 2. The KeyError in my code is raised by the "from XXX import" statement: "from distutils import setup" results in File "tracetest.py", line 28, in ? __import__(prog) File "/Volumes/space/Users/harold/uni/pace/dpd/setup.py", line 1, in ? from distutils.core import setup, Extension File "tracetest.py", line 5, in tracefunc if event is 'call' : return trace_call(frame,event,arg) File "tracetest.py", line 12, in trace_call print code.co_name+"("+",".join( KeyError: 'setup' does anyone know how I can circumvent this? 3. Is there any way to set the __name__ attribute for the inspected script to "__main__", so that tracing is really transparent? 4. finally, does a functionality like this already exist in the library or did anyone of you come up with an implementation? thanks, - harold - -- Military intelligence is a contradiction in terms. -- Groucho Marx From david at fielden.com.au Wed Jul 27 08:43:24 2005 From: david at fielden.com.au (Rowdy) Date: Wed, 27 Jul 2005 22:43:24 +1000 Subject: question about deleting records from mysql In-Reply-To: <1122466366.005107.303840@z14g2000cwz.googlegroups.com> References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> <42E7720E.90307@xit.net> <1122466366.005107.303840@z14g2000cwz.googlegroups.com> Message-ID: <42E7816C.5080501@fielden.com.au> nephish at xit.net wrote: > ok. did this > > >>>>cursor.execute("DELETE FROM table WHERE autoinc > 1000") > > 245L > >>>>cursor.commit() > > > i got an AttributeError 'Cursor' object has no attribute 'commit' > > hmm. what should i do now? > the stuff about writing a lightweight layer between the dbapi and the > program shot right over my head. sorry, but thanks > IIRC it is the connection that can commit(), not the cursor. Rowdy From rkern at ucsd.edu Thu Jul 28 15:46:11 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 12:46:11 -0700 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Asad Habib wrote: > I agree with Mustafa. After all, we are a bunch of professionals and not > vagabonds hired to take pot shots at one another. Speak for yourself. ;-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From godoy at ieee.org Sat Jul 30 19:15:03 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 30 Jul 2005 20:15:03 -0300 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Ed Leafe wrote: > I'll defer this to my partner, Paul McNett. He's spearheading the > reporting > module for Dabo, and may know of some tools that are already out there > that could generate the image, which Dabo could then display. There are some out there. There's one implementation that is compatible with Matlab and is also compatible with wxPython. Take a look at matplotlib: http://matplotlib.sourceforge.net/ -- Jorge Godoy From rkern at ucsd.edu Fri Jul 1 22:24:09 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 01 Jul 2005 19:24:09 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <87k6kai39n.fsf@bigfoot.com> References: <1120236674.379545.17530@f14g2000cwb.googlegroups.com> <87k6kai39n.fsf@bigfoot.com> Message-ID: Chris Smith wrote: > My question is, why not move them into, say, a "functional" library, > so that legacy code can be handled via an import, and those heads > preferring to think that way can be satisfied, and those little corner > cases not handled by the newer, sweller syntaxes can still be managed? > IOW, just ripping them out of the core and leaving everyone in the > lurch doesn't seem too pythonic to me. Python 3000 will be breaking more backwards compatibility than map/reduce/filter. That legacy code won't work anyways. I predict, though, that one of the first 3rd party modules to come out for Python 3000 will be such a library. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Sun Jul 31 19:22:09 2005 From: http (Paul Rubin) Date: 31 Jul 2005 16:22:09 -0700 Subject: Dabo in 30 seconds? References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> Message-ID: <7xr7de5zoe.fsf@ruckus.brouhaha.com> Cliff Wells writes: > wxWidgets/wxPython hasn't required GTK 1.x in quite a long time. Please > get your facts straight. It did last time I tried installing it, which was maybe 3-6 months ago. Someone posted that it had been updated recently. > Also, the "1600" dependencies you complain > about come standard on any modern Linux system or can be easily > installed with the system's package management tool. I've also built > wxPython from source on OS/X, which, while orders of magnitude more > difficult than on Linux, still wasn't that hard. I'm seriously getting > the impression you are criticizing something you've never even tried. I spent several hours trying to install wxPython on Linux without success (a lot of that was figuring out that some undefined symbol it was complaining about was some GTK 1.5 function that had didn't exist in GTK 2.1). As I remember, wxPython itself compiled without too much trouble but wxWidgets and/or GTK 1.5 (once I got a copy of that) had some problems. I decided I just didn't care enough to keep pursuing it. > > http://www.software-lab.de/down.html > > It sounded interesting until you said "Java Applet". Talk about causing > deployment issues... Yeah, I don't have Java in my browser, but it's very widely deployed. For most of the stuff I do though, a plain HTML interface is fine. From gsakkis at rutgers.edu Sat Jul 16 20:48:20 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 16 Jul 2005 20:48:20 -0400 Subject: Filtering out non-readable characters References: Message-ID: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> "Peter Hansen" wrote: > Jp Calderone wrote: > > On Sat, 16 Jul 2005 19:01:50 -0400, Peter Hansen wrote: > >> George Sakkis wrote: > >>>>>> identity = string.maketrans('','') > >> > >> Wow! That's handy, not to mention undocumented. (At least in the > >> string module docs.) Where did you learn that, George? > >> > > http://python.org/doc/lib/node109.html > > Perhaps I was unclear. I thought it would be obvious that I knew where > to find the docs for maketrans(), but that the particular behaviour > shown (i.e. arguments of '' having that effect) was undocumented in that > page. > > -Peter Actually I first read about this in the Cookbook; there are two or three recipes related to string.translate. As for string.maketrans, it doesn't do anything special for empty string arguments: maketrans( from, to) Return a translation table suitable for passing to translate() or regex.compile(), that will map each character in from into the character at the same position in to; from and to must have the same length. So if from and to are empty, maketrans will map zero characters, hence the identity. It's not the only way to get the identity translation table by the way: >>> string.maketrans('', '') == string.maketrans('a', 'a') == string.maketrans('hello', 'hello') True George From devlai at gmail.com Tue Jul 12 16:27:55 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 13:27:55 -0700 Subject: automatically assigning names to indexes In-Reply-To: <1121177247.196389.11080@z14g2000cwz.googlegroups.com> References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> <1121169211.877343.200570@z14g2000cwz.googlegroups.com> <1121177247.196389.11080@z14g2000cwz.googlegroups.com> Message-ID: <1121200075.131843.27710@f14g2000cwb.googlegroups.com> import math class Vector: def __init__(self, coordinates): self.coordinates = coordinates self.magnitude = sum([c**2 for c in coordinates])**0.5 self.direction = getangle(Vector([1]+[0 for i in range(len(coordinates)-1)])) def dotproduct(self, vector): sum([a*b for a,b in zip(self.coordinates,vector.coordinates)]) def crossproduct(self, vector, pvector): return pvector*self.magnitude*vector.magnitude*math.sin(self.getangle(vector)) def getangle(self, vector): return math.acos(self.dotproduct(vector)/(self.magnitude*vector.magnitude)) def __mul__(self, scalar): return Vector([c*scalar for c in self.coordinates]) def __add__(self, vector): return Vector([c+d for c,d in zip(self.coordinates,vector.coordinates)]) def __sub__(self, vector): return Vector([c-d for c,d in zip(self.coordinates,vector.coordinates)]) What about this? From max at alcyone.com Mon Jul 4 16:32:20 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Jul 2005 13:32:20 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: <3uqdndaex_FJAVTfRVn-pA@speakeasy.net> Steven Bethard wrote: > And it's almost two times slower: That's because you're not using operator.add. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Virtue has never been as respectable as money. -- Mark Twain From peter at engcorp.com Mon Jul 25 11:19:25 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 11:19:25 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kjihkFubvl6U1@individual.net> Message-ID: <74SdndmpGeuannjfRVn-1w@powergate.ca> Michael Hoffman wrote: > Reinhold Birkenfeld wrote: >> Tony Meyer wrote: >>> Do people really like using __div__ to mean join? >> >> I'm not too happy with it, too, but do we have alternatives? ... >> Of course, one can use joinwith() if he doesn't like '/'. > > I've used the path module pretty extensively and always use joinpath(). > Personally, I'm -0 on __div__, but I suppose if anyone here claimed to > have used in the past, rather than it just being some novelty that might > be a good idea, that would be good enough for keeping it. I've tried it both ways, and ended up accepting / as a useful and clean approach, though as a general rule I find operator-overloading to be fairly hideous and to lead to Perlish code. This one I resisted for a while, then found it fairly pleasant, making it perhaps the exception to the rule... Perhaps it's just that in code that builds paths out of several components, it seemed quite straightforward to read when it used / instead of method calls. For example, from one program: scripts = userfolder / scriptfolder scriptpath = scripts / self.config['system']['commandfile'] instead of what used to be: scripts = userfolder.joinpath(scriptfolder) scriptpath = scripts.joinpath(self.config['system']['commandfile']) Even so I'm only +0 on it. -Peter From bokr at oz.net Mon Jul 11 19:49:05 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 23:49:05 GMT Subject: extend for loop syntax with if expr like listcomp&genexp ? Message-ID: <42d30319.417620065@news.oz.net> E.g., so we could write for x in seq if x is not None: print repr(x), "isn't None ;-)" instead of for x in (x for x in seq if x is not None): print repr(x), "isn't None ;-)" just a thought. Regards, Bengt Richter From user at domain.invalid Mon Jul 25 06:26:43 2005 From: user at domain.invalid (user at domain.invalid) Date: Mon, 25 Jul 2005 13:26:43 +0300 Subject: Retrieving and saving images from internet address In-Reply-To: <1122282085.216772.286680@z14g2000cwz.googlegroups.com> References: <1122282085.216772.286680@z14g2000cwz.googlegroups.com> Message-ID: rock69 wrote: > Hi all :) > > I got this address: > > http://www.infomedia.it/immagini/riviste/covers/cp/cp137.jpg > > and I would like to download that image and save it to a local file. > How do you do that in Python? I'd use urllib.urlretrieve, "Copy a network object denoted by a URL to a local file, if necessary." -- dOb From chris.arndt at web.de Fri Jul 8 17:54:16 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 08 Jul 2005 22:54:16 +0100 Subject: pylize 1.2b released Message-ID: <42CEF608.7070708@web.de> pylize 1.2b relased More than three years after the last release I finally pulled myself together and am now happy to announce a maintenance release for pylize that also brings some new features. From time to time I have been receiving questions and comments from users, which indicated that there are still people, who find this program useful. I hope, those will find this new release beneficial. What's new? - switched template system to EmPy - fixed JavaScript keyboard event handling - fixed windows installation routine - added Spanish translation - added Italian translation - page layout now works (mostly) without using tables - cleaned up CSS - cleaned up templates - refactored code somewhat What is pylize? pylize is a Python script that makes the creation of on-screen presentations a matter of a few minutes. It generates a template master document, which you can edit with your favourite text or HTML editor. The master document is then processed by pylize to generate HTML files for every slide plus a file for the table of contents. You can view the presentation with any CSS-capable webbrowser. Download and further information: Author: Christopher Arndt From pthorstenson at co.montezuma.co.us Wed Jul 27 12:45:39 2005 From: pthorstenson at co.montezuma.co.us (Patrick Thorstenson) Date: Wed, 27 Jul 2005 10:45:39 -0600 Subject: trying to access Oracle Message-ID: <000901c592ca$9ea61220$8235a8c0@co.montezuma.co.us> I am trying to access Oracle using the cx_Oracle module. I can login to Oracle OK, but I am at a loss as to how I should then access the specific table I need so that I can join it to our county parcel layer using the "make table view" tool. I have scoured the internet looking for any examples and have found little that makes sense (to me). Can anyone help? The table I need is called ASR.TEMP_OWNERSHIP. The password, username, and TNS is all "asr". I'm not quite to the point where I can think for myself and improvise with python. # Import system modules import cx_Oracle, win32com.client # Create the Geoprocessor object gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") connection = cx_Oracle.connect("asr", "asr", "asr") # Local variables... ###HERE IS WHERE I DON'T KNOW WHAT TO DO### ..below is the path to temp_ownership.. ASR_JOIN = (connection, "Database Connections\\ASR_Temp_GIS.odc\\ASR.TEMP_OWNERSHIPGIS") gp.MakeTableView_management (ASR_JOIN) Patrick Thorstenson pthorstenson at co.montezuma.co.us -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Jul 27 19:01:51 2005 From: aahz at pythoncraft.com (Aahz) Date: 27 Jul 2005 16:01:51 -0700 Subject: Job available: SF Bay Area (was Re: OT: finding a job) References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> <1122500867.516196.146990@g14g2000cwa.googlegroups.com> Message-ID: In article , Peter Hansen wrote: > >Mass-mailed resumes with generic cover letters are a good way to kill >trees but not a particular effective way to get noticed by an employer, >at least not noticed in a good way... Excellent advice! Speaking of which, my company has an ad up on www.python.org in the jobs area. Look for Printra. Craigslist is supposed to be a good place, but we've been getting spammed pretty heavily from there. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From luismgz at gmail.com Tue Jul 19 22:56:49 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 19 Jul 2005 19:56:49 -0700 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121828209.276340.9640@o13g2000cwo.googlegroups.com> linuxfreak wrote: > Hi guys, > Got going with python...and i must say its a pretty cool language. > Been using Xemacs to write me programs. But I want an IDE that would > give me auto-completion, online help and the like... Tried SPE and > Dr.Pyhton but the former crashes regulary and the latter is quite > unweildy and does not have a great many features. I quite like the UML > feature found in SPE but the damn thing crashes way too often. What are > you guys using and what do you think is the best IDE...or should i > stick with Xemacs/emacs??? Have you tried PyCrust? http://sourceforge.net/projects/pycrust/ From gurpreet.sachdeva at gmail.com Mon Jul 4 05:35:04 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Mon, 4 Jul 2005 15:05:04 +0530 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: try: re.search("()(/python>)", str).group() except: print 'not found' otherwise, re.search("().*?(\/python>)", str).group() this is will help! Regards, Gurpreet Singh Blogging [at] http://garrythegambler.blogspot.com On 4 Jul 2005 01:04:47 -0700, jwaixs wrote: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! There are only reference, and if you don't know how a > module work you won't learn it from a reference! > > This is the problem: > > >>> import re > >>> str = "blablaRe modules sucks!blabla" > >>> re.search("()(/python>)", str).group() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'NoneType' object has no attribute 'group' > > the only thing I want are the number of places blabla, Re modules > sucks! and blabla are. > > Noud > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanks and Regards, GSS From jrastrick at student.usyd.edu.au Sun Jul 3 01:31:21 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 2 Jul 2005 22:31:21 -0700 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? In-Reply-To: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> Message-ID: <1120368681.573445.199710@g44g2000cwa.googlegroups.com> Python 3000 is the proveribal and so far hypothetical version of the language in which backward incompatible changes will be allowed (and encouraged). See http://www.python.org/peps/pep-3000.html for details. seberino at spawar.navy.mil wrote: > Guido gave a nice "Python Regrets" Power Point talk at OSCON few years > ago. > > I was wondering if the plan is to ever implement these ideas. > > e.g. Guido said he'd prefer 'print' to be a *function* with perhaps a > 'println' version IIRC. > > He also had a ton of stuff he'd rather see become iterators. > > Chris From andreas at kostyrka.org Fri Jul 1 17:40:40 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 01 Jul 2005 23:40:40 +0200 Subject: shelve in a ZipFile? In-Reply-To: <42c57b58$1@nntp0.pdx.net> References: <42c57b58$1@nntp0.pdx.net> Message-ID: <1120254041.6823.70.camel@andi-lap> Am Freitag, den 01.07.2005, 10:53 -0700 schrieb Scott David Daniels: > Terry Hancock wrote: > > I only just recently had a look at the shelve module.... > > That would be handy if, for example, I wanted to couple > > (and compress into the bargain) by putting my two > > shelf files into a single zip archive. > > You are, however, fooling yourself if you think a shelve > solution can be made to gracefully interact with a zip- > compressed version. In order to zip the shelve data, it > must all be seen in a pass, so every update would necessarily > rewrite the entire shelve storage. much better to extract the > entire shelve file, operate on it, and re-compress it. > > Even if uncompressed, the zip archive format is not going to > happily allow you to change the size of any of the "files" it > stores. It's even worse: shelve is basically a class that wraps a dictionary. It provides a dictionary string -> pickable object based on a dictioary string -> string. bsddb, gdbm etc. probably access files via lowlevel calls that are not interceptable. One way to achieve your goals would be to add compression and/or a key prefix (which would allow multiple dictionaries or at least key spaces in one file) Andreas > > --Scott David Daniels > Scott.Daniels at Acm.Org -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From spam.csubich+block at block.subich.spam.com Thu Jul 7 21:32:53 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 07 Jul 2005 21:32:53 -0400 Subject: Tkinter grid layout In-Reply-To: References: Message-ID: Eric Brunel wrote: > So you should either make your MainWindow class inherit from Tk, which > eliminates the unneeded container and the problems it may cause, or make > sure the pack or grid on your MainWindow instance actually tells the > container to grow with its container. With pack, it's quite easy: just > do myWindow.pack(fill=BOTH, expand=1). With grid, it's a bit more > complicated, since you will have to configure the grid on the container. To expand on this, the grid-method uses a few calls that aren't immediately obvious. Specifically, the containing object must have row and columnconfigure called on them: >>> r = Tk() >>> g = Text(r) >>> h = Entry(r) >>> g.grid(row=1,sticky=N+S+E+W) >>> h.grid(row=2,sticky=E+W) >>> r.columnconfigure(0,weight=1) >>> r.rowconfigure(1,weight=1) >>> r.mainloop() This creats a window containing a text widget above an entry widget. Both will resize horizontally to fill the entire window, and the text widget will resize vertically. From exarkun at divmod.com Thu Jul 21 00:35:59 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 00:35:59 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: Message-ID: <20050721043559.26278.372453859.divmod.quotient.15307@ohm> On Thu, 21 Jul 2005 00:18:58 -0400, Christopher Subich wrote: >Peter Hansen wrote: >> stringy wrote: >> >>> I have a program that shows a 3d representation of a cell, depending on >>> some data that it receives from some C++. It runs with wx.timer(500), >>> and on wx.EVT_TIMER, it updates the the data, and receives it over the >>> socket. >> >> >> It's generally inappropriate to have a GUI program do network >> communications in the main GUI thread. You should create a worker >> thread and communicate with it using Queues and possibly the >> AddPendingEvent() or PostEvent() methods in wx. There should be many >> easily accessible examples of how to do such things. Post again if you >> need help finding them. > >I'd argue that point; it's certainly inappropriate to do >(long-)/blocking/ network communications in a main GUI thread, but >that's just the same as any blocking IO. If the main thread is blocked >on IO, it can't respond to the user which is Bad. > >However, instead of building threads (possibly needlessly) and dealing >with synchronization issues, I'd argue that the solution is to use a >nonblocking network IO package that integrates with the GUI event loop. > Something like Twisted is perfect for this task, although it might >involve a significant application restructuring for the grandparent poster. > >Since blocking network IO is generally slow, this should help the >grandparent poster -- I am presuming that "the program updating itself" >is an IO-bound, rather than processor-bound process. In the particular case of wxWidgets, it turns out that the *GUI* blocks for long periods of time, preventing the *network* from getting attention. But I agree with your position for other toolkits, such as Gtk, Qt, or Tk. Jp From sklass at pointcircle.com Thu Jul 14 09:36:40 2005 From: sklass at pointcircle.com (rh0dium) Date: 14 Jul 2005 06:36:40 -0700 Subject: Help - Classes and attributes In-Reply-To: <42d5cc75@news.eftel.com> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> <42d5cc75@news.eftel.com> Message-ID: <1121348200.591600.326060@g44g2000cwa.googlegroups.com> I knew it had to be something obvious - thanks so much!! John Machin wrote: > rh0dium wrote: > > Hi all, > > > > I believe I am having a fundamental problem with my class and I can't > > seem to figure out what I am doing wrong. Basically I want a class > > which can do several specific ldap queries. So in my code I would have > > multiple searches. But I can't figure out how to do it without it > > barfing.. > > > > The error is straightforward .. > > > > LDAP Version 2.0.8 > > Traceback (most recent call last): > > File "./ldap-nsc.py", line 62, in ? > > l.search() > > File "./ldap-nsc.py", line 40, in search > > ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, > > retrieveAttrs) > > AttributeError: NSCLdap instance has no attribute 'search_s' > > > > > > The code is also I believe straight forward.. > > > > import ldap > > > > class NSCLdap: > > > > def __init__(self,server="sc-ldap.nsc.com"): > > who=""; cred="" > > self.server=server > > try: > > print "LDAP Version", ldap.__version__ > > l=ldap.open(server) > > l.simple_bind_s(who, cred) > > l.protocol_version=ldap.VERSION3 > > except ldap.LDAPError, error_message: > > print "Couldn't Connect to %s %s " % > > (server,error_message) > > > > def search(self, baseDN="o=nsc.com", > > retrieveAttrs=None,searchAttrs="cn=*klass*" ): > > searchScope = ldap.SCOPE_SUBTREE > > try: > > If you had bothered to do some elementary debugging, like "print > repr(l)" here, just before the exception-triggering statement, .... > > > ldap_result_id = l.search_s(baseDN, searchScope, > > searchAttrs, retrieveAttrs) > > result_set = [] > > while 1: > > result_type, result_data = l.result(ldap_result_id, 0) > > if (result_data == []): > > break > > else: > > ## here you don't have to append to a list > > ## you could do whatever you want with the > > individual entry > > ## The appending to list is just for > > illustration. > > if result_type == ldap.RES_SEARCH_ENTRY: > > result_set.append(result_data) > > print result_set > > except ldap.LDAPError, error_message: > > print "Errors on Search %s " % error_message > > > > def setBaseDN(self, baseDN="o=nsc.com"): > > return baseDN > > > > if __name__ == '__main__': > > > > l = NSCLdap() > > l.search() > > > > > > I would love some pointers - clearly my code thinks that search_s is an > > attribute of my class but it's not.. > > > You are confusing the bejaysus out of yourself and your audience by > using "l" as a name (1) at all (2) to represent two *different* things, > one in script-global scope -- l = NSCLdap() -- and one in the __init__ > method of your class -- l=ldap.open(server). > > Use two different sensible names; then your real problem should become > apparent -- unless of course in the meantime some wally thinks it a good > idea to prevent your attaining a clue yourself by spoon-feeding you. From steve at REMOVETHIScyber.com.au Mon Jul 25 19:27:40 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 26 Jul 2005 09:27:40 +1000 Subject: how to write a line in a text file References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> Message-ID: On Mon, 25 Jul 2005 20:51:42 +0100, Steve Holden wrote: > In Python you can use a text file's readlines() method to build a list > of all the lines in a file. That makes it quite easy to change numbered > lines. Having modified the file's content in memory you can then create > a new file using the writelines() method of a new file. The trick is to > avoid losing both the old and the new files when a low-probability crash > occurs. I'm usually opposed to creeping featuritis in programming languages ("it would be really cool if Python had a built-in command to do my entire application") but safe over-writing of files does cry out for a "batteries included" approach: - it is a common usage; - it is tricky to get right; - it is even trickier to get right in a platform independent way; - and it is even trickier again to get right in a platform independent way that doesn't introduce security risks. The normal trick is to do something like: read file A; write temporary file B without clobbering any existing B; rename file A to C; rename B to A; delete C when you know the writing and renaming has succeeded; and do it all in such a way that it succeeds even if there is very little available disk-space. The platform-independence comes from the fact that different OSes expect the temporary files to live in different places (eg /tmp/ under Linux). Most operating systems consider it poor form to just write temporary files any old place. I'm told by those who claim to know what they're talking about that a potential risk exists if an attacker can predict the temporary file name and thus do nefarious things. The exact nature of those nefarious things was not explained to me, but I do recall the occasional security advisory for applications which use insufficiently-random temporary file names. Does anyone have anything suitable for a "safe-overwrite" module? -- Steven. From pbagora at yahoo.com Fri Jul 22 15:40:44 2005 From: pbagora at yahoo.com (Pranav Bagora) Date: Fri, 22 Jul 2005 12:40:44 -0700 (PDT) Subject: Getting TypeError in Changing file permissions Message-ID: <20050722194044.99411.qmail@web32414.mail.mud.yahoo.com> Hello , i am trying to change mode of files using the os.chmod()function. But i am getting an error " os.chmod(outfile,0700) TypeError: coercing to Unicode: need string or buffer, file found" Please Help, Pranav __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From cliff at develix.com Sun Jul 31 14:45:30 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 11:45:30 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7xd5ozv1ng.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <7xd5ozv1ng.fsf@ruckus.brouhaha.com> Message-ID: <1122835530.19618.71.camel@localhost.localdomain> On Sun, 2005-07-31 at 01:08 -0700, Paul Rubin wrote: > Cliff Wells writes: > > application. End users shouldn't need to worry about installing third > > party packages (or even Python for that matter). Tools such as py2exe > > and Inno installer make this pretty simple on Windows, and py2app on > > OS/X accomplishes the same. It should be irrelevant to end users what > > libraries or tools you use to develop the app. > > What if I want to be able to write multi-platform applications without > having to deal with OS-specific packaging schemes for every OS that I > want to run on? Even if I only want to run on Linux, I don't see how > to package a wxPython application to minimize end user hassle. The > only realistic GUI's to use are Tkinter or HTTP/HTML over a local > socket talking to a user-provided web browser. Hm. That's odd, I thought I had just finished a fairly sophisticated app that runs on Windows, Linux and Mac OSX using wxPython... I must be mistaken. Regardless, if you are doing cross-platform work for *end-users* you had better be prepared for a little pain as there is no magic bullet. As far as Linux only apps go... if a Linux user can't figure out how to install wxPython (which is provided in several common packaging formats), then I suspect they are used to pain. The bottom line is this: some people like Tk, some wxPython. Each has advantages and disadvantages. But to claim that you *can only* do something in one or the other only demonstrates that you haven't really tried. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From ssweber at gmail.com Sun Jul 17 22:47:40 2005 From: ssweber at gmail.com (samuels) Date: 17 Jul 2005 19:47:40 -0700 Subject: Parsing html :: output to comma delimited In-Reply-To: <1121564566.094694.27610@o13g2000cwo.googlegroups.com> References: <1121540573.555193.243760@g49g2000cwa.googlegroups.com> <1121564566.094694.27610@o13g2000cwo.googlegroups.com> Message-ID: <1121654860.923866.152950@g49g2000cwa.googlegroups.com> Thanks for the replies, I'll post here when/if I get it finally working. So, now I know how to extract the links for the big page, and extract the text from the individual page. Really what I need to find out is how run the script on each individual page automatically, and get the output in comma delimited format. Thanks for solving the two problems though :) -Sam From peter at engcorp.com Wed Jul 6 09:50:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Jul 2005 09:50:18 -0400 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> <86u0j8wv02.fsf@bhuda.mired.org> Message-ID: Tom Anderson wrote: > Perhaps the real question, then, is which language allows you to delete > lines of code most quickly. No, then the question becomes "which language allows you to quickly write very many lines of code which then have to be deleted". Of course, writing those lines manually would be silly if you could automate the process. After all, the lines of code aren't required, so they don't really have to do anything, do they? So naturally Assembly would be the proper way to get maximum performance out of your automatic code writing program. Therefore Assembly is clearly the fastest development language. -Peter From jepler at unpythonic.net Sat Jul 30 18:34:02 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 30 Jul 2005 17:34:02 -0500 Subject: A replacement for lambda In-Reply-To: References: <867jf9jmfw.fsf@bhuda.mired.org> <42ead151@nntp0.pdx.net> Message-ID: <20050730223402.GD6418@unpythonic.net> On Fri, Jul 29, 2005 at 10:14:12PM -0700, Tim Roberts wrote: > C++ solves this exact problem quite reasonably by having a greedy > tokenizer. Thus, that would always be a left shift operator. To make it > less than and a function, insert a space: > < Incidentally, I read in an article by Bjarne Stroustrup[1] that "C++0x" will parse vector> v; just like today's compilers parse vector > v; Another of the changes he discusses, letting 'auto i = ...' create i with the type of the expression '...', will certainly be an improvement. Even better if the keyword 'auto' could be made optional! (Of course, this is another break with C, where the declaration auto i; makes 'i' an int) And what's this got to do with Python? I dunno. Sorry. Jeff [1] http://www.informit.com/content/images/art_stroustrup_2005/elementLinks/rules.pdf -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From duncan.booth at invalid.invalid Thu Jul 7 05:36:24 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jul 2005 09:36:24 GMT Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > This is something I've never understood. Why is it bad > form to assign an "anonymous function" (an object) to a > name? Because it obfuscates your code for no benefit. You should avoid making it hard for others to read your code (and 'others' includes yourself in the future). Also, it obfuscates tracebacks: all lambda expressions will identify in tracebacks as , but if you define a function you can give it a meaningful name. > > Why is it considered abuse of lambda to assign the > functions to a name? Is it an abuse of lambda to do this? > > D = {"one": lambda noun: noun, > "two": lambda noun: noun + 's', > "many": lambda noun: 'lots of ' + noun + 's' } > > assert D["two"]("python") == "pythons" > > No, that is approaching a reasonable use of lambda, however I would still be inclined to write it with functions. e.g. def one(noun): return noun def two(noun): return noun+'s' def many(noun): return 'lots of %ss' % (noun,) D = dict(one=one, two=two, many=many) although in this particular case I would probably just put format strings in the dictionary: def D(style, noun): formats = dict(one="%s", two="%ss", many="lots of %ss") return formats.get(style, "an indeterminate number of %ss") % (noun,) assert D("two","python") == "pythons" From pkarjala at paju.oulu.fi Thu Jul 28 06:40:05 2005 From: pkarjala at paju.oulu.fi (Pekka Karjalainen) Date: Thu, 28 Jul 2005 10:40:05 +0000 (UTC) Subject: Graphics files & Python Message-ID: How can I create image files and animations with Python? I will clarify a bit. This is a question of recreational programming. I have already made some animated gifs from Julia sets using Python and some external programs. I hit upon a quick solution of writing ppm image files (it's a simple text based format) and using ppmtogif to make gifs out of them, then using gifsicle (free program found on the web) to join them into animated gif files. You can see some of my results in: That's a small file that links to large (0.8 meg or so) files. They are a bit bland at the moment, but I might get around to improving the things later :-) This seems to work well enough for the modest goals that I have -- I just want to make a few beautiful fractal images and animations, and learn a bit more about Python while tinkering along. However, I might as well ask. Are there other good options for creating images and animations using Python? As it is, I build my data into an array representing the bitmap and the value of each pixel, and then write it into a temp file in ppm format. It's a little slow, but it still runs fast enough for me at the moment. I have no intention of writing a major new fractal exploring software after all, so I'm not worried about execution time, I'm worried about my own programmer's time (which I want to save for other things). Any suggestions? -- Pekka Karjalainen - Oulu, Finland From ed at leafe.com Sun Jul 17 08:06:22 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 17 Jul 2005 08:06:22 -0400 Subject: Python vs. Access VBA In-Reply-To: References: Message-ID: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> On Jul 15, 2005, at 11:19 PM, William Lodge wrote: > Finally, does anybody know of any Web sites having examples of > database apps > in Python? You might want to look at Dabo, which is a database application framework for Python. In about 30 seconds you can create an application that queries a database, displays the results, and allows for editing/updating/inserting/deleting records. Currently we do not have an ODBC interface, which is what you'd need if the data is in Access, since no one involved has written that module. However, if you are interested in developing your app in Dabo, we'd be glad to add that module as long as you're willing to give us the feedback we need to get it working smoothly. BTW, I wouldn't suggest scaling up to Oracle - why get involved with all that licensing? There are many open-source databases, such as PostgreSQL, MySQL and Firebird that can handle large data sets without getting stuck with huge license fees. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From fake at comcast.net Wed Jul 27 14:28:50 2005 From: fake at comcast.net (Gordon Airporte) Date: Wed, 27 Jul 2005 14:28:50 -0400 Subject: Tkinter - Resizing a canvas with a window In-Reply-To: References: Message-ID: <4NKdnekAxNeoT3rfRVn-ug@comcast.com> Thanks you very much. I found something interesting though, the canvas's width and height properties are not updated when it is resized by its packing. Looks like an oversight to me, but I've just demonstrated that I don't have a complete grasp of Tk, so... I can use a Configure callback to keep track of the values, however. from Tkinter import * class testApp3: def __init__( self, master ): self.ma = master self.f = Frame( self.ma ) self.f.pack(fill=BOTH, expand=YES) self.cv = Canvas(self.f, width=125, height=125, bg='red') self.cv.pack(fill=BOTH, expand=YES) self.b1 = Button( self.f, text='Hello', height=1, width=10, padx=0, pady=1, \ command = self.howbig ) self.b1.pack(side=BOTTOM, anchor=S, padx=4, pady=4) self.cv.bind('', self.resize ) def howbig( self ): print self.cv['width'], self.cv['height'] print self.cvw, self.cvh def resize( self, event ): print '(%d, %d)' % (event.width, event.height) self.cvw, self.cvh = event.width-4, event.height-4 root = Tk() app = testApp3(root) root.mainloop() From mweihs at gmx.at Mon Jul 11 14:15:45 2005 From: mweihs at gmx.at (Markus Weihs) Date: Mon, 11 Jul 2005 20:15:45 +0200 Subject: Tricky Dictionary Question from newbie References: Message-ID: Hi! Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} NewDic = {} for k,v in Dict.items(): NewDic.setdefault(v, []).append(k) Regards, mawe From newsgroups at jhrothjr.com Sat Jul 9 14:10:28 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 9 Jul 2005 12:10:28 -0600 Subject: removing list comprehensions in Python 3.0 References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> <1120927567.463458.289770@g49g2000cwa.googlegroups.com> Message-ID: <11d04opdpqas927@news.supernews.com> "George Sakkis" wrote in message news:1120927567.463458.289770 at g49g2000cwa.googlegroups.com... > It's funny how one of the > arguments for removing lambda -- you can do the same by defining a > named function -- does not apply for list comprehensions. Which is a point a number of people have made many times, with about as much effect as spitting into the wind. Making a piece of functionality less convenient simply to satisfy someone's sense of language esthetics doesn't seem to me, at least, to be a really good idea. John Roth > > > George > From fredrik.johansson at gmail.com Sat Jul 2 20:22:23 2005 From: fredrik.johansson at gmail.com (Fredrik Johansson) Date: Sun, 3 Jul 2005 02:22:23 +0200 Subject: A brief question. In-Reply-To: References: Message-ID: <3d0cebfb050702172264866047@mail.gmail.com> On 7/3/05, Tom Anderson wrote: > That's one way. I'd do: > > root = value ** 0.5 > > Does that mean we can expect Guido to drop math.sqrt in py3k? :) I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) gives 3.9999999999999996, and this error could be avoided. --Fredrik From dlyzxl at yahoo.com Mon Jul 4 11:04:01 2005 From: dlyzxl at yahoo.com (Justin) Date: Mon, 4 Jul 2005 08:04:01 -0700 (PDT) Subject: missing cephes module Message-ID: <20050704150401.13007.qmail@web51107.mail.yahoo.com> Hi All: When I used py2exe to create executable file, "cephes" module missing error occurred. I have installed python 2.3 and scientific and numeric python. Can anybody suggest me how to resolve the problem? Justin --------------------------------- Yahoo! Mail Mobile Take Yahoo! Mail with you! Check email on your mobile phone. -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Thu Jul 21 23:15:14 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 21 Jul 2005 20:15:14 -0700 Subject: Difference between " and ' In-Reply-To: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: b83503104 at yahoo.com wrote: > Can someone tell me the difference between single quote and double > quote? One has double the fun. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Forgive your enemies, but never forget their names. -- John F. Kennedy From exarkun at divmod.com Fri Jul 1 17:48:09 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 1 Jul 2005 17:48:09 -0400 Subject: Favorite non-python language trick? In-Reply-To: Message-ID: <20050701214809.26278.17493380.divmod.quotient.3916@ohm> On Fri, 01 Jul 2005 15:02:10 -0500, Rocco Moretti wrote: >Joseph Garvin wrote: > >> I'm curious -- what is everyone's favorite trick from a non-python >> language? And -- why isn't it in Python? > >I'm not aware of a language that allows it, but recently I've found >myself wanting the ability to transparently replace objects. For >example, if you have a transparent wrapper class around a certain >object, and then determine that you no longer need to wrap the object, >you can say the magic incantation, and the wrapper instance is replaced >by what it is wrapping everywhere in the program. Or you have a complex >math object, and you realize you can reduce it to a simple integer, you >can substitue the integer for the math object, everywhere. > >I mainly look for it in the "object replaces self" form, but I guess you >could also have it for arbitrary objects, e.g. to wrap a logging object >around a function, even if you don't have access to all references of >that function. > >Why isn't it in Python? It's completely counter to the conventional >object semantics. Smalltalk supports this with the "become" message. I have also done an implementation of this for Python. Jp From seungwjun at gmail.com Sun Jul 17 22:57:15 2005 From: seungwjun at gmail.com (sj) Date: 17 Jul 2005 19:57:15 -0700 Subject: list implementation Message-ID: <1121655435.153214.292520@o13g2000cwo.googlegroups.com> I believe the type "list" is implemented as an array of pointers. Thus, random access is an O(1) operation while insertion/deletion is an O(n) operation. That said, I have the following questions: 1. Am I correct in saying the above? 2. Implementing list as an array is part of language specification or implementation-dependent? 3. What if I actually need a doubly-linked list for constant-time insertion/deletion? Is there a built-in type or a standard class? Thanks. From amit at digitalpeers.com Sun Jul 3 19:43:30 2005 From: amit at digitalpeers.com (amit) Date: Mon, 04 Jul 2005 01:43:30 +0200 Subject: General questions about embedding Python. Message-ID: <42C87822.2080705@digitalpeers.com> Hello, I am currently studying how to embedd python. I am developing a graphical C++ application. My goal is to embedd python script that will control some kind of animation. I have some questions about python embedding: 1) Is there a good text book or other resource on embedding/extending? (I find it hard to learn only by the tutorial and C/Python API from the python.org site) 2) I have found that there are many ways to embedd a script: PyEvel_EvalCode() PyRun_SimpleFile() PyObject_CallObject() What are the cons and pros of using each of them? 3) Is there a problem with the PyRun_SimpleFile(). I am trying to run the following code: const char *SCRIPT_NAME = "C:\\test_script.py"; int _tmain(int argc, _TCHAR* argv[]) { Py_Initialize(); FILE *script_file; script_file = fopen(SCRIPT_NAME, "r"); if (script_file != NULL) PyRun_SimpleFile(script_file, SCRIPT_NAME); Py_Finalize(); return 0; } The python script has only one line: 'print "hello"' I build it with Python2.3 libraries. When I try to run the code I get access violation. 4) What is the correct way to handle/catch python exceptions in the embedding Python code? Forgive me if I have asked too many questions in one eMail, it is becuase I don't really know where to start learning this subject from. Thanks Amit From pydecker at gmail.com Sat Jul 30 11:16:19 2005 From: pydecker at gmail.com (Peter Decker) Date: Sat, 30 Jul 2005 11:16:19 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <871x5gs6oy.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <871x5gs6oy.fsf@wilson.rwth-aachen.de> Message-ID: On 7/30/05, Torsten Bronger wrote: > I'm aware of it (and there is Wax and maybe a third one). Actually > it illustrates my point quite well: These projects are small and > instable (Dabo has a developer basis of very few people, Wax has > only one); they are even worse documented; they add another layer > which slows down and requires the end-user to install another > package; they force you to test even more GUI approaches. Well, wxPython itself is largely the work of a single person, but I doubt that many consider that a reason to avoid it. As far as your comment about 'slowing down' the app, I've found that Dabo and pure-wxPython apps run indistinguishably. Perhaps there are some microseconds of extra processing, but I sure haven't noticed it. And I don't think that the comment about installing another package is fair; *anything* outside of the standard distribution requires that, and Dabo is no more difficult than copying to site-packages. I do agree about the documentation aspect of Dabo, though. The authors have put together some basic stuff to get you started, but have chosen to focus their time on continued development for the time being. But having said that, I found that Dabo uses a very consistent syntax, and was no more difficult to pick up than Python itself. With wxPython, I constantly had to refer to the docs, as every class did things slightly differently. For example, many controls have some text associated with them. Depending on the control, you need to call SetText(), SetLabel(), SetBitmapLabel(), SetTitle(), etc. Dabo wrapped all of these controls so that the identifying text for each is controlled by a single property: Caption. In any Dabo control, executing ctl.Caption="Something" will change its associated text. This sort of consistency removes the need to constantly refer to documentation in order to write your code. -- # p.d. From grante at visi.com Wed Jul 6 23:14:06 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 03:14:06 -0000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> Message-ID: <11cp7fusjoid468@corp.supernews.com> On 2005-07-07, Leif K-Brooks wrote: > Grant Edwards wrote: >> 1) So I know whether an parameter was passed in or not. Perhaps >> it's not considered good Pythonic style, but I like to use a >> single method for both get and set operations. With no >> parameters, it's a get. With a parameter, it's a set: >> >> class demo: >> def foo(v=None): >> if v is not None: >> self.v = v >> return self.v > > _NOVALUE = object() > class demo: > def foo(v=_NOVALUE): > if v is _NOVALUE: > return self.v > else: > self.v = v Apart from the change in the logic such that the set operation doesn't return a value, how is that any different? You're just creating your own non-integer-value "None" object instead of using the one built in to the language. > But what's wrong with properties? Huh? -- Grant Edwards grante Yow! at TAILFINS!!... click... visi.com From joon.ch at gmail.com Sun Jul 17 09:28:30 2005 From: joon.ch at gmail.com (Joon) Date: Sun, 17 Jul 2005 15:28:30 +0200 Subject: beginner question fibonacci Message-ID: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> >>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... print b ... a, b = b, a+b ... 1 1 2 3 5 8 >>> a, b = 0, 1 >>> while b < 10: print b a = b b = a+b 1 2 4 8 Why a, b = b, a+b isn't a = b; b = a+b ? From rrr at ronadam.com Thu Jul 7 13:57:55 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 17:57:55 GMT Subject: Use cases for del In-Reply-To: <11cqfq3norg5c84@corp.supernews.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> <11cqfq3norg5c84@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-07-07, Ron Adam wrote: >>>>>>It would be a way to set an argument as being optional without >>>>>>actually assigning a value to it. >> >>So it would still work like you expect even though v is not >>bound to anything. Like I said the bigger problem is that >>globals will be visible and that would create a conflict. >>Setting a value to None in a function hides globals of the >>same name. That wouldn't happen if None unbound names as del >>does. > > Good point. I hadn't thought of that. The easiest way to fix that is to create a Nil or Null object as a replacement for the current None object. >>>I find it more obvious to set the name to None during the >>>periods that it isn't valid than to delete it and check for a >>>NameError when I want to know if the value is usable or not. >> >>You would still be able to do that explicitly and it probably would be a >>good idea when you aren't sure if a name is left over from something else. >> >>If a name is None, it means it's available and unassigned, so >>you don't have to check for a NameError. > > > How would you spell "if a name is None"? How about: if name is None: name = something Making None the same as undefined wouldn't change this. I think the parser would need to be a little smarter where None is concerned in order to be able to handle it in bool expressions, and catch improper name = undefined assignments. But it might not change things as much as you think. > Personally, I think the spellings > > del name > if 'name' in locals() > > is much more explicit/obvious than > > name = None > name is None This would be name = None # remove it from locals() if name is None: dosomething # if it's not in locals() No need to check locals or globals. That's one of the plus's I think. Since we can already assign a value to any name without first initializing it, this just allows us to use it in a some expressions without also first initializing it. It would still give an error if we tried to use it in "any" operation. Just like the present None. > I expect the "=" operator to bind a name to a value. Having it > do something completely different some of the time seems a bit > unpythonic. But you are assigning it a value. Instead of having a Name assigned to a None object, the name is just removed from name space to do the same thing and you save some memory in the process. How about keeping None as it is as a place holder object, and having a keyword called "undefined" instead. x = 3 x = undefined # delete x from name space if x is not undefined: print x if an undefined name is used with any operator, it could give a 'UndefinedName' error. This would be more compatible with the current python language. Cheers, Ron From steve at REMOVETHIScyber.com.au Sat Jul 30 12:21:53 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 02:21:53 +1000 Subject: Comparison of functions References: Message-ID: On Sat, 30 Jul 2005 13:22:47 +0000, Adriano Varoli Piazza wrote: > As far as I recall from Math Analysis, which I studied two months ago, > you can't sort complex numbers. It makes no sense. The reason being > (reading from my book), it's not possible to define an order that > preserves the properties of arithmetical operations on complex numbers. > So you can't order them, and you can't compare them. You are confusing mathematical ordering with sorting a list. Here, I will sort some mixed complex and real numbers for you. If you look at them closely, you will even be able to work out the algorithm I used to sort them. 1 1+0j 1+7j 2 2+3j 3+3j 3-3j 3+4j 4 4+2j It was easy. I never once asked myself whether some complex number was greater or less than another, I just asked "which one comes first in a lexicographic sort?" The two questions are NOT the same, and it is an ugliness in an otherwise beautiful language that Python treats them as the same. Mathematically, 1 == 1.0 == 1+0j but in the dictionary "1" should sort before "1.0" which sorts before "1.0+0.0j". -- Steven. From richard.kessler at matteicos.com Fri Jul 22 15:14:50 2005 From: richard.kessler at matteicos.com (Richard Kessler) Date: Fri, 22 Jul 2005 12:14:50 -0700 Subject: sys.path - stuff from nowhere? Message-ID: Just build python 2.3.4 (needed for Zope and Plone). Trying to learn more about use the data in sys.path from importing. When I run Python at the command prompt, import sys and print sys.path I get stuff that makes no sense. For example, /usr/local/lib/python23.zip. Such a file does not even live on my debian machine, I would like to remove it from the sys.path string but I do not understand how it is getting there in the first place. Can anyone tell me how sys.path is initialized other than PYTHONPATH (which I have as /usr/local)? I have no .pth files and site-packages is empty at this point. Thanks much in advance. Richard From simon.dahlbacka at gmail.com Mon Jul 11 08:43:55 2005 From: simon.dahlbacka at gmail.com (simon.dahlbacka at gmail.com) Date: 11 Jul 2005 05:43:55 -0700 Subject: __eq__ on a dict In-Reply-To: References: Message-ID: <1121085835.225259.233810@o13g2000cwo.googlegroups.com> "Use the source, Luke" dict_richcompare: http://fisheye.cenqua.com/viewrep/python/python/dist/src/Objects/dictobject.c?r=2.165#l1510 dict_compare: http://fisheye.cenqua.com/viewrep/python/python/dist/src/Objects/dictobject.c?r=2.165#l1425 /Simon From exarkun at divmod.com Thu Jul 21 09:03:40 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 09:03:40 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: <1121924551.512211@yasure> Message-ID: <20050721130340.26278.2002513114.divmod.quotient.15433@ohm> On Thu, 21 Jul 2005 05:42:32 -0000, Donn Cave wrote: >Quoth Paul Rubin : >| Christopher Subich writes: >| > > In the particular case of wxWidgets, it turns out that the *GUI* >| > > blocks for long periods of time, preventing the *network* from >| > > getting attention. But I agree with your position for other >| > > toolkits, such as Gtk, Qt, or Tk. >| > >| > Wow, I'm not familiar with wxWidgets; how's that work? >| >| Huh? It's pretty normal, the gui blocks while waiting for events >| from the window system. I expect that Qt and Tk work the same way. > >In fact anything works that way, that being the nature of I/O. >But usually there's a way to add your own I/O source to be >dispatched along with the UI events -- the toolkit will for >example use select() to wait for X11 socket I/O, so it can also >respond to incoming data on another socket, provided along with a >callback function by the application. > >Am I hearing that wxWindows or other popular toolkits don't provide >any such feature, and need multiple threads for this reason? > Other popular toolkits do. wxWindows doesn't. Jp From jeremy at emperorlinux.com Fri Jul 29 13:30:42 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Fri, 29 Jul 2005 13:30:42 -0400 Subject: Wheel-reinvention with Python (was: Ten Essential Development Practices) In-Reply-To: <935qr2-km9.ln1@strongwill.g2ctech> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <935qr2-km9.ln1@strongwill.g2ctech> Message-ID: <1122658242.4202.21.camel@localhost.localdomain> On Fri, 2005-07-29 at 14:19 -0300, Jorge Godoy wrote: > Jeremy Moles wrote: > > > Four? > > > > 1. wx > > 2. PyGTK > > 3. Tk (Are you including this one even?) > > 4. ??? > > PyQt / PyKDE. Ah! Can't believe I forgot that one! :) > > Of the few I can think of, only one would qualify as great. :) > > The fourth one? ;-) Hehe. :) I was going to say PyGTK... but in all honesty I'm just a GTK fanboy who hasn't really even TRIED anything else. I remember experimenting a few years back with compiled Qt apps in C/C++, but the whole notion of a MOC just scared me--not that I knew enough back then to really label it as "a bad thing", nor do I now. :) > -- > Jorge Godoy > From mediocre_person at hotmail.com Wed Jul 6 09:34:53 2005 From: mediocre_person at hotmail.com (Terrance N. Phillip) Date: Wed, 06 Jul 2005 08:34:53 -0500 Subject: System Independent Wallpaper Changer In-Reply-To: References: <42cb220c$1_5@alt.athenanews.com> Message-ID: <42cbde11$1_5@alt.athenanews.com> Toby Dickenson wrote: > On Wednesday 06 July 2005 01:12, Terrance N. Phillip wrote: > > >>I've done some searching, and can't seem to find a programatic way of >>getting *** that to happen. > > > http://www.google.com/search?q=setwallpaper+dcop > > I hope this helps > That helps very much, thank-you! And sorry to previous posters: yes, indeed, I changed naming conventions part way through--you got an intermediate version. Nick. From enleverlesO.OmcO at OmclaveauO.com Thu Jul 7 12:25:17 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Thu, 7 Jul 2005 18:25:17 +0200 Subject: how to change a script while it is running References: <1120738578.46b2dbd2b0d50ae7698c95aaea76bc74@teranews> Message-ID: <42cd62c9$0$1250$8fcfb975@news.wanadoo.fr> Hi ! Try : def ff(a): print a*2 ff(111) exec('''def ff(a): print a*3 ''',globals(),globals()) ff(111) @-salutations Michel Claveau From roccomoretti at hotpop.com Sun Jul 31 20:58:29 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Sun, 31 Jul 2005 19:58:29 -0500 Subject: Comparison of functions In-Reply-To: References: Message-ID: Adriano Varoli Piazza wrote: > As far as I recall from Math Analysis, which I studied two months ago, > you can't sort complex numbers. It makes no sense. The reason being > (reading from my book), it's not possible to define an order that > preserves the properties of arithmetical operations on complex numbers. > So you can't order them, and you can't compare them. Debate the merits of Python's method of sorting all you want, but for the love of all that is good and holy, please do not claim that the current way of doing things is somehow mathematically pure. The best explanation of the current method is that it is a compromise borne out of the best use cases encountered as the language grew in it's infancy, and we're stuck with it currently because it would break too much to change things right now. E.g.: 1 < '2' => True '1' < 2 => False 20 < 'Five' => True None < 0 => True [1,2] < (1,2) => True (1,2) < [100,200] => False (None,) < None => False {1:None,2:None} < [1,2] => True [None, 1, 'five', open('README'), (1,2,3)].sort() => works just fine [None, 1, 'five', open('README'), (1,2,3), 1j].sort() => crashes and burns None of these make sense mathematically, nor were they motivated primarily by mathematical arguments. Why is [1,2] < (1,2)? Because 'list' < 'tuple' - No more, no less. One could argue that you could think of complex numbers as tuples of values - but then why does [(1,2),(4,1),(4,-3),(7.2,-1.2)].sort() work and [(1+2j),(4+1j),(4-3j),(7.2-1.2j)].sort() fail? "Practicality beats purity." Python has it's current ordering/sorting scheme not because it is theoretically pure, but because it seemed like the best option at the time. Please don't pretend it's perfect - it's even been admitted that things are going to change in the future, although I haven't yet seen a conversation where it has been made clear exactly what will change. From rkern at ucsd.edu Wed Jul 27 01:25:40 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 26 Jul 2005 22:25:40 -0700 Subject: A Module on Time & Date In-Reply-To: References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: Robert Maas, see http://tinyurl.com/uh3t wrote: >>From: Robert Kern >>As you can see in the datetime documentation, the module was introduced >>in Python 2.3. I recommend updating your Python installation. > > What do you mean "your"?? "The one you are using." > I don't have any Python installation of my > own. All I have is what this small local ISP provides on its Unix shell > machine which I share with hundreds of other users. There's no way I > can install a new version of anything on the system account. > Your recommendation will be disregarded as total crap. Sensitive, much? If you are going to overreact to well-intentioned but apparently unusable advice, then I suggest that you don't ask questions here. USENET and, by extension, mailing lists gatewayed to USENET are not places for such tender sensibilities. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at REMOVETHIScyber.com.au Tue Jul 12 11:18:55 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 01:18:55 +1000 Subject: breaking out of nested loop References: Message-ID: On Tue, 12 Jul 2005 10:19:04 -0400, rbt wrote: > What is the appropriate way to break out of this while loop if the for > loop finds a match? Refactor it into something easier to comprehend? And comments never go astray. (Untested. And my docstrings are obviously bogus.) def make_one_thing(group, x): """Makes a thing by plonking the frobber. Expects group to be a list of foo and x to be an index. """ mix = random.sample(group, x) make_string = ''.join(mix) n = md5.new(make_string) match = n.hexdigest() return match def group_matches(group, target): """Cycles over a group of foos, plonking the frobber of each item in turn, and stopping when one equals target. """ for x in xrange(len(group)): try: match = make_one_thing(group, x) if match == target: return True except Exception, e: # don't stop just because the program has a bug print e # if we get here, there was no successful match after the # entire for loop return False def test_until_success: """Loop forever, or until success, whichever comes first. """ group = [1, 2, 3, 4] target = 5 flag = False while not flag: print "No matches yet, starting to search..." flag = group_matches(group, target) # if we ever get here, it means we found a collision, and # flag became True, so the while loop just dropped out print "Collision!!!" stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime()) print "Stopped at", stop -- Steven. From bokr at oz.net Tue Jul 12 17:13:16 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 21:13:16 GMT Subject: python parser References: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> Message-ID: <42d431c7.18118533@news.oz.net> On Tue, 12 Jul 2005 13:30:14 -0700, Robert Kern wrote: >tuxlover wrote: >> Hello everyone >> >> I have to write a verilog parser in python for a class project. I was >> wondering if all you folks could advise me on choosing the right python >> parser module. I am not comfortable with lex/yacc and as a result find >> myself strugging with any module which use lex/yacc syntax/philosophy. >> pyparser looks good to me, but before I dive into it, I would really >> appreciate feedback from members of this group > >A Verilog parser has been written using pyparsing at least once before, >so I imagine that it shouldn't be too difficult to do so again. Of >course, if you just need *a* Verilog parser, not necessarily one written >by you, you could just email the guy who wrote it and ask him for a >copy. Grep > > http://pyparsing.sourceforge.net/ > >for "Verilog". > or google for verilog site:sourceforge.net BTW googling for verilog site:pyparsing.sourceforge.net will only get one hit (maybe less if I typoed again ;-) Regards, Bengt Richter From steve at REMOVETHIScyber.com.au Sat Jul 23 09:33:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 23 Jul 2005 23:33:36 +1000 Subject: find a specified dictionary in a list References: <42e0dc25$1@news.eftel.com> Message-ID: On Fri, 22 Jul 2005 12:42:04 +0000, Odd-R. wrote: > On 2005-07-22, John Machin wrote: >> Odd-R. wrote: >>> I have this list: >>> >>> [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] >>> >>> All the dictionaries of this list are of the same form, and all the oids >>> are distinct. If I have an oid and the list, how is the simplest way of >>> getting the dictionary that holds this oid? Instead of keeping a list of dictionaries, keep a dict of dicts, indexed by the oid: D = {1: {'i': 'milk'}, 2: {'i': 'butter'}, 3: {'i': 'cake'}} Then you can extract a dictionary with a single call: thedict = D[oid] or just grab the item you want directly: food = D[oid]['i'] No mess, no fuss. Ninety percent of the work is choosing your data structures correctly. >> Something like this: >> >> def oidfinder(an_oid, the_list): >> for d in the_list: >> if d['oid'] == an_oid: >> return d >> return None >> # These are not the oids you are looking for. > > Thank you for your help, but I was hoping for an even simpler > solution, as I am suppose to use it in a > References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Message-ID: On Mon, 4 Jul 2005, Aahz wrote: > In article , > Peter Hansen wrote: > >> After 25 years doing this, I've become something of a Luddite as far as >> fancy IDEs and non-standard features go... and a huge believer in >> strict decoupling between my tools, to the point of ignoring things >> that bundle them together in ways that are, in my opinion, too tight. >> Sorry! :-) > > +1 QOTW +1 insight of the century. This is the heart of the unix way - lots of simple little programs that do exactly one thing well, and can be composed through simple, clean interfaces. For actually getting things done, a toolkit beats a swiss army knife. tom -- This isn't right. This isn't even wrong. From jwaixs at gmail.com Mon Jul 4 04:04:47 2005 From: jwaixs at gmail.com (jwaixs) Date: 4 Jul 2005 01:04:47 -0700 Subject: f*cking re module Message-ID: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> arg... I've lost 1.5 hours of my precious time to try letting re work correcty. There's really not a single good re tutorial or documentation I could found! There are only reference, and if you don't know how a module work you won't learn it from a reference! This is the problem: >>> import re >>> str = "blablaRe modules sucks!blabla" >>> re.search("()(/python>)", str).group() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'group' the only thing I want are the number of places blabla, Re modules sucks! and blabla are. Noud From python at hope.cz Fri Jul 1 05:39:21 2005 From: python at hope.cz (Lad) Date: 1 Jul 2005 02:39:21 -0700 Subject: How to compare files Message-ID: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> Hi, What is the best method for comparing two files by words? I was thinking about reading files by words and compare them but a word in one file can be linked with a new line character ( \n) and this '\n' will cause that the words will considered to be different( eventhough without '\n' are the same) Thanks for help. LAd. From jeremy at emperorlinux.com Wed Jul 27 00:21:27 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Wed, 27 Jul 2005 00:21:27 -0400 Subject: multiple inheritance super() In-Reply-To: <20050727071412.GA13681@mrna.tn.nic.in> References: <20050727071412.GA13681@mrna.tn.nic.in> Message-ID: <1122438087.12498.3.camel@localhost.localdomain> Ignore my last response; just read it fully and realized how dumb my response was. :) On Wed, 2005-07-27 at 12:44 +0530, km wrote: > Hi all, > > In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? > > thanks in advance for enlightment ... > > here's the snippet > > #!/usr/bin/python > > class A(object): > def __init__(self): > self.a = 1 > > class B(object): > def __init__(self): > self.b = 2 > > class C(object): > def __init__(self): > self.c = 3 > > class D(B, A, C): > def __init__(self): > self.d = 4 > super(D, self).__init__() > > if __name__ == '__main__': > x = D() > print x.a # errs with - AttributeError > From steve at REMOVETHIScyber.com.au Sat Jul 30 14:18:02 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 04:18:02 +1000 Subject: Comparison of functions References: Message-ID: On Sat, 30 Jul 2005 16:43:00 +0000, Adriano Varoli Piazza wrote: > If you want to treat numbers as strings, why not convert them before > sorting them? Because that changes the object and throws away information. Here is a list, containing one complex number converted to a string, and one string that just happens to look like a complex number: ['1+1j', '2+2j']. Now convert it back the way it was. > Python is just saying "He's trying to sort complex > numbers. No can do". Python is quite happy to sort a list with one single complex number and nothing else, so it is not SORTING complex numbers that Python objects to, merely greater or less than comparisons. It is an accident of implementation that Python blindly uses GT or LT comparisons for sorting complex numbers, but not other objects. > You're trying to make it guess that you want them > sorted as strings, not as numbers. I don't see how Python treats things > the same way. I see that real numbers and strings can be compared and > sorted (asciibetically? don't remember). It has nothing to do with > complex numbers. The abstraction or overloading or what it is fails, > because they don't have an order as numbers, and Py is not intelligent > enough to know that you want them asciibetized Which has been my point all along: Python confuses the specific case of NUMERIC COMPARISONS with the general case of SORTING. Worse, Python doesn't even do that consistently: it is quite happy to let you compare floats with strings, even though mathematically that is just as much nonsense as to compare floats with complex numbers. As I've said, the two are similar enough that such a mistake is easy to make. And at this time, I'm not sure how to implement a better solution, or even if there is a better solution, but I am giving it some thought. -- Steven. From cam.ac.uk at mh391.invalid Wed Jul 27 14:37:52 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 27 Jul 2005 19:37:52 +0100 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: Tito wrote: > Hi all: > > Is there a metalanguage capability in Python (I know there are many) to > call a function having its name in a string? > > Something like: > __call__("foo") > > instead of: > foo() locals()["foo"]() will be a little more predictable than eval("foo()"). -- Michael Hoffman From rrr at ronadam.com Mon Jul 18 02:37:36 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 18 Jul 2005 06:37:36 GMT Subject: Efficiently Split A List of Tuples In-Reply-To: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> References: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> Message-ID: Raymond Hettinger wrote: >>Variant of Paul's example: >> >>a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) >>zip(*a) >> >>or >> >>[list(t) for t in zip(*a)] if you need lists instead of tuples. > > > > [Peter Hansen] > >>(I believe this is something Guido considers an "abuse of *args", but I >>just consider it an elegant use of zip() considering how the language >>defines *args. YMMV] > > > It is somewhat elegant in terms of expressiveness; however, it is also > a bit disconcerting in light of the underlying implementation. > > All of the tuples are loaded one-by-one onto the argument stack. For a > few elements, this is no big deal. For large datasets, it is a less > than ideal way of transposing data. > > Guido's reaction makes sense when you consider that most programmers > would cringe at a function definition with thousands of parameters. > There is a sense that this doesn't scale-up very well (with each Python > implementation having its own limits on how far you can push this > idiom). > > > Raymond Currently we can implicitly unpack a tuple or list by using an assignment. How is that any different than passing arguments to a function? Does it use a different mechanism? (Warning, going into what-if land.) There's a question relating to the above also so it's not completely in outer space. :-) We can't use the * syntax anywhere but in function definitions and calls. I was thinking the other day that using * in function calls is kind of inconsistent as it's not used anywhere else to unpack tuples. And it does the opposite of what it means in the function definitions. So I was thinking, In order to have explicit packing and unpacking outside of function calls and function definitions, we would need different symbols because using * in other places would conflict with the multiply and exponent operators. Also pack and unpack should not be the same symbols for obvious reasons. Using different symbols doesn't conflict with * and ** in functions calls as well. So for the following examples, I'll use '~' as pack and '^' as unpack. ~ looks like a small 'N', for put stuff 'in'. ^ looks like an up arrow, as in take stuff out. (Yes, I know they are already used else where. Currently those are binary operators. The '^' is used with sets also. I did say this is a "what-if" scenario. Personally I think the binary operator could be made methods of a bit type, then they ,including the '>>' '<<' pair, could be freed up and put to better use. The '<<' would make a nice symbol for getting values from an iterator. The '>>' is already used in print as redirect.) Simple explicit unpacking would be: (This is a silly example, I know it's not needed here but it's just to show the basic pattern.) x = (1,2,3) a,b,c = ^x # explicit unpack, take stuff out of x So, then you could do the following. zip(^a) # unpack 'a' and give it's items to zip. Would that use the same underlying mechanism as using "*a" does? Is it also the same implicit unpacking method used in an assignment using '='?. Would it be any less "a bit disconcerting in light of the underlying implementation"? Other possible ways to use them outside of function calls: Sequential unpacking.. x = [(1,2,3)] a,b,c = ^^x -> a=1, b=2, c=3 Or.. x = [(1,2,3),4] a,b,c,d = ^x[0],x[1] -> a=1, b=2, c=3, d=4 I'm not sure what it should do if you try to unpack an item not in a container. I expect it should give an error because a tuple or list was expected. a = 1 x = ^a # error! Explicit packing would not be as useful as we can put ()'s or []'s around things. One example that come to mind at the moment is using it to create single item tuples. x = ~1 -> (1,) Possible converting strings to tuples? a = 'abcd' b = ~^a -> ('a','b','c','d') # explicit unpack and repack and: b = ~a -> ('abcd',) # explicit pack whole string for: b = a, -> ('abcd',) # trailing comma is needed here. # This is an error opportunity IMO Choice of symbols aside, packing and unpacking are a very big part of Python, it just seems (to me) like having an explicit way to express it might be a good thing. It doesn't do anything that can't already be done, of course. I think it might make some code easier to read, and possibly avoid some errors. Would there be any (other) advantages to it beside the syntax sugar? Is it a horrible idea for some unknown reason I'm not seeing. (Other than the symbol choices breaking current code. Maybe other symbols would work just as well?) Regards, Ron From mjmrifai at gmail.com Fri Jul 1 02:22:43 2005 From: mjmrifai at gmail.com (mjmrifai at gmail.com) Date: 30 Jun 2005 23:22:43 -0700 Subject: I am a Java Programmer Message-ID: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> I am a java programmer and I want to learn Python Please help me. From steve at REMOVETHIScyber.com.au Sat Jul 2 22:30:28 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 12:30:28 +1000 Subject: Another newbie question from Nathan. References: <42c63341$0$6997$b9fe7a78@news.usenetrevolution.com> Message-ID: On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote: > > > Hi all. > > How do I make the computer generate 4 random numbers for the guess? I want > to know because I'm writing a computer program in Python like the game > MasterMind. First you get the computer to generate one random number. Then you do it again three more times. If you only need to do it once, you could do it this way: import random # you need this at the top of your program x0 = random.random() x1 = random.random() x2 = random.random() x3 = random.random() But if you need to do it more than once, best to create a function that returns four random numbers in one go. def four_random(): """Returns a list of four random numbers.""" L = [] # start with an empty list for i in range(4): L.append(random.random()) return L and use it this way: rand_nums = four_random() # rand_nums is a list of four numbers print rand_nums[0] # prints the first random number print rand_nums[3] # prints the last one or like this: alpha, beta, gamma, delta = four_random() # four names for four separate numbers -- Steven. From cowie.rob at gmail.com Fri Jul 22 13:55:19 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 22 Jul 2005 10:55:19 -0700 Subject: Separation of Code in CGI App In-Reply-To: References: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> <1122045475.402933.246760@z14g2000cwz.googlegroups.com> Message-ID: <1122054919.033091.308240@o13g2000cwo.googlegroups.com> Thanks, I have run through the tutorial - very good. One day, I'd like to try and organise a similar tutorial involving CGI programming. There are several very basic examples, but they leave plenty of unanswered questions such as how to best structure a cgi app, apache permissions, etc So to be clear, if a .py module is in the same directory as my python cgi script, I can import it thus 'import XXX.py'? From rkern at ucsd.edu Tue Jul 12 16:23:41 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 13:23:41 -0700 Subject: Creating anonymous functions using eval In-Reply-To: <1121184988.996652.126350@g47g2000cwa.googlegroups.com> References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> <1121184988.996652.126350@g47g2000cwa.googlegroups.com> Message-ID: Devan L wrote: > Well, the string that gets passed is more or less a function > definition, which is then called with exec. I don't see why you'd need > to write a string out with the function definition and then call it. > You could just write the function. > > As for the nested functions, I had been presuming that it was intended > to use as a better function than lambda within a function. Sorry for > the confusion. You missed Steven's point which is to quote the message to which you are replying. Not everyone is reading this list in a conveniently threaded form, so you need to provide some context for them to be able to follow along. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From me at privacy.net Sat Jul 30 11:40:19 2005 From: me at privacy.net (Dan Sommers) Date: Sat, 30 Jul 2005 11:40:19 -0400 Subject: showing help(M) when running module M standalone References: Message-ID: On Sat, 30 Jul 2005 17:04:50 +0200, Chris wrote: > hello, > I have a small module which only contains some utility functions. when > running this standalone I would like to show the module docs and each > function docs, as if doing > import M > help(M) > I came up with the following but I reckon there is a much simpler way? > if __name__ == '__main__': > print __doc__ > print "\nFUNCTIONS:\n" > for x in __all__: > print x > exec "print " + x + ".__doc__" > Works but does not seem right using exec for such a task. So don't use exec. > any hint would be great! for x in __all__: print x.__doc__ HTH, Dan -- Dan Sommers From bdesth.quelquechose at free.quelquepart.fr Wed Jul 6 17:29:24 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 06 Jul 2005 23:29:24 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: <42cc46c1$0$20081$636a15ce@news.free.fr> Stian S?iland a ?crit : > (snip) > Hey, I know! > > t = python.util.ImmutableArrayList.fromCollection(L.getAbstractCollection()) > > python.util.functional.applyFunctionOnCollection( > (class implements python.util.functional.AnonymousFunction: > def anonymousFunction(x): > return x+1 > ), L) > Reminds me of something, but what ?-) From siggy2 at supereva.it Fri Jul 8 11:01:51 2005 From: siggy2 at supereva.it (siggy2 at supereva.it) Date: 8 Jul 2005 08:01:51 -0700 Subject: [PythonWin] how to stop execution in interactive window? Message-ID: <1120833596.025452.166020@g14g2000cwa.googlegroups.com> Hi All, (sorry for my bad english) I wrote a __tiny__ and __stupid__ recursive script directly into pythonwin interactive window with a time.sleep(1) and a print before each recursion... I should have taken a closer look at the ending condition (never satisfied!), anyway I was quite confident that a control-C would have stopped the intepreter as it is (incidentally?) when this break sequence is entered during a screen-i/o of the python interpreter in a CMD prompt... Instead I discovered my pythonwin session no more responding even though the output shows that it was still working correctly... and my other open files in pythonwin still needing to be saved - my salvation was that while I was searching a solution with google, after 984 nested call ~ more than a quarter later, the recursion stack was full and an exception was raised! ;-P). So my question is: is there a keystroke combination to stop the interpreter in pythonwin interactive window? Or even better Is there a "pythonwin interactive window" keystrokes list? (btw: I remember an old post explaining the keystroke to reset interactive window memory without being forced to close and open pythonwin - very usefull but I could not find it anymore...) TIA! bye, PiErre From steven.bethard at gmail.com Wed Jul 27 19:49:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 27 Jul 2005 17:49:03 -0600 Subject: anything to do In-Reply-To: <1122483885.865657.220790@f14g2000cwb.googlegroups.com> References: <1122483885.865657.220790@f14g2000cwb.googlegroups.com> Message-ID: lordverminard at gmail.com wrote: > is there any place which lists jobs to be done...you know minor jobs > and requests thats nobody has found time to do. Not all of these are pure Python, so you may have to wade through a bit to avoid the C ones, but a good place to look is the Python trackers on sourceforge: http://sourceforge.net/tracker/?group_id=5470&atid=105470 Fixing bugs in Python is always greatly appreciated, and could potentially be a good way to better learn the language (and its standard libraries). STeVe From peter at engcorp.com Wed Jul 13 18:15:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 18:15:14 -0400 Subject: timeoutsocket.py mirror? In-Reply-To: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> References: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> Message-ID: <75KdncmICpyiD0jfRVn-pg@powergate.ca> skilpat at gmail.com wrote: > Can anybody provide a mirror for this module? The original URL seems to > be down. I have been looking for over an hour, and every single > resource that uses it links to the timo-tasi.org site to download it. Google returns several sites which link directly to their own copy of timeoutsocket.py. Just google for that name, alone... (I suppose you already searched with Google, but maybe included the word "python", which doesn't help in this case.) Or you could try the Wayback Machine, which seems to have archived the relevant page: http://web.archive.org/web/20040214101340/www.timo-tasi.org/python/timeoutsocket.py (Give it time, it has to retrieve it from some massive offline storage or something. Might take a minute or two to come up.) I'll leave it up to you to figure out which one is the most recent version. -Peter From lsolis at mu.intecsa-inarsa.es Wed Jul 20 03:23:27 2005 From: lsolis at mu.intecsa-inarsa.es (luis) Date: Wed, 20 Jul 2005 07:23:27 GMT Subject: is a file open ? Message-ID: for root, dirs, files in os.walk(path): for file in files: # ? is opened ? Best regards Luis From tzot at sil-tec.gr Fri Jul 8 09:12:51 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 08 Jul 2005 16:12:51 +0300 Subject: pickle alternative References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> <1119161205.327572.136150@g44g2000cwa.googlegroups.com> <7xd5qi3ldp.fsf@ruckus.brouhaha.com> <1119166730.350374.178510@o13g2000cwo.googlegroups.com> <7x64waavoy.fsf@ruckus.brouhaha.com> <1120531507.113161.312630@g44g2000cwa.googlegroups.com> Message-ID: On 4 Jul 2005 19:45:07 -0700, rumours say that simonwittber at gmail.com might have written: > Time and space efficiency, and security do not have to be mutually > exclusive features of a serializer. Python does not provide, in the > standard library, a serializer which can work safely with untrusted > data which is time and space efficient. The proposed gherkin module > goes some way to achieving this. The format is simple enough to > easily write interoperable implementations across platforms. I cannot readily check the source code because your web server listens on port 82 (we're behind a strict firewall), so I don't know if my following question has a reason to exist, but there we go: Have you considered basing your module on xdrlib, which is more of a cross-language standard? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From steve at REMOVETHIScyber.com.au Mon Jul 4 19:21:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 05 Jul 2005 09:21:04 +1000 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> <42c98b40$0$29947$626a14ce@news.free.fr> Message-ID: On Mon, 04 Jul 2005 21:17:21 +0200, tiissa wrote: > Josiah Manson wrote: >> Hello. I am very new to Python, and have been unable to figure out how >> to check if a variable exists or not. In the following code I have made >> a kludge that works, but I think that it would be clearer to check if >> closest exists and not have to initialize it in the first place. How is >> that check done? > > Variables are stored in two dictionnaries: globals() (for global > variables) and locals() (for the local ones, which are also global on > top level). Should we *really* be encouraging newbies to mess with globals() and locals()? Isn't that giving them the tools to shoot their foot off before teaching them how to put shoes on? [snip] >> I also have a few other questions to tack on if you don't mind. I >> am >> setting dist to 1e9, because that is a larger value than any of the >> places in the galaxy will be far away. Is there a better way to >> initialize dist so that it is impossible for this to fail? For example, >> would setting dist to infinity work, and how is that done? > > The float constructed from the string 'inf', float('inf'), may do the > trick. I don't know the details, though. > > >>> 1e100 < float('inf') > True This is not guaranteed to work in any Python. It *might* work, depending on the underlying C library, which is operating system dependent. -- Steven. From me at privacy.net Sun Jul 10 20:38:07 2005 From: me at privacy.net (Dan Sommers) Date: Sun, 10 Jul 2005 20:38:07 -0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: On Sun, 10 Jul 2005 20:11:38 -0400, "Terry Reedy" wrote: > "Dan Sommers" wrote in message > news:m2ll4euv02.fsf at unique.fully.qualified.domain.name.yeah.right... >> That's a pretty big change; now all formal parameters beginning with >> an underscore have a brand new meaning. > As I said, 'in combination with whatever other mechanism', meaning one > that one has to intentionally invoke ... My mistake; I didn't read carefully enough. Regards, Dan -- Dan Sommers From rkern at ucsd.edu Tue Jul 19 18:23:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 19 Jul 2005 15:23:16 -0700 Subject: OO design In-Reply-To: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: chris wrote: > When I think about what I should do I end up with a class XY that has a > method for everything I want to do eg. > > class XY: > def read_file > def scale_data > def plot_data > def shelve_data > > But somehow that doesn't feel right, especially when I expect the number of > methods will grow and grow, which would make the class very unwieldy. I think that a key thing to remember, especially as you start learning OO design, is to not succumb to analysis paralysis. If all you need right now are those four methods, then implement those four methods. You don't know what the other 16 methods are going to be, so don't bother with them yet. When you do end up with the groaning, 20-method behemoth (and you will), then you will have a better idea of what capabilities you need and who needs to talk to whom. At this point, you refactor. Do not fear the refactoring. Embrace it. There's much to be said for just getting it right the first time, but let's face it: it never happens because what's "right" is rarely known at the beginning of a project. Eventually, as you accumulate experience and find designs that work and ones that don't, you'll begin to have a better idea of what's "right" ahead of time and your initial designs are going to get better and better. But for now, don't let the fear of bad design prevent you from writing code. We all do bad designs; we just fix them later. In short slogans: Just Do It. Make It Work, Then Make It Right. Refactor Mercilessly. Do the Simplest Thing That Could Possibly Work. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From benji at benjiyork.com Mon Jul 18 06:44:36 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 18 Jul 2005 06:44:36 -0400 Subject: email format in python In-Reply-To: <20050718102120.64241.qmail@web42004.mail.yahoo.com> References: <20050718102120.64241.qmail@web42004.mail.yahoo.com> Message-ID: <42DB8814.1020100@benjiyork.com> met at n wrote: > I want to have the python equivalent function of this > (that checks email format) > > function CheckEmail($Email = "") { > if (ereg("[[:alnum:]]+@[[:alnum:]]+\.[[:alnum:]]+", > $Email)) { > return true; > } else { > return false; > } > } While it is possible to translate the above code into Python (see http://docs.python.org/lib/module-re.html), you should know that the regex above will not validate all possible email addresses. In general it is a fools errand to try to anyway. -- Benji York From skn at skn.com Wed Jul 13 10:12:25 2005 From: skn at skn.com (skn) Date: Wed, 13 Jul 2005 19:42:25 +0530 Subject: Can JEP alone do the job? Message-ID: Requirement ========== A JAVA Server(RMI Sever) has to invoke some Python scripts. These Python scripts in turn have to make some JAVA API calls. The JAVA APIs will be provided by custom Java Classes and Interfaces. I should be able to receive the "Output" from the Python script into my JAVA server. "Output" can either be:- 1) std out from Python (print statements inside Python script) OR 2) Python Objects Questions ======== >From the initial literature study, I think I can achieve this ONLY using JEP? However I also find that there is another Integrator "JPype". My question is what do I miss if I don't use JPype? What extra does JPype have? Basically I want to avoid too many Integration technologies and use ONLY JEP (or possibly ONLY JPype.) Regards, skn From martin at v.loewis.de Sun Jul 10 18:51:36 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Jul 2005 00:51:36 +0200 Subject: Efficiency of using long integers to hold bitmaps In-Reply-To: <42d165d0.311819733@news.oz.net> References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> Message-ID: <42D1A678.1040705@v.loewis.de> Bengt Richter wrote: > Sounds like a possible^H^H^H^H^H^H^H^Hprobable premature optimization worry ;-) Right. OTOH, I notice a frequent game of Katze und Maus (cat and mouse?) in questions around Python implementation details. The OP doesn't provide details of his application, but instead asks a general question "how is foo implemented in Python, I'm worried it might be bar?". Then, instead of saying "yes, it is bar" or "no, it isn't bar", the response is "we can't answer your real question because you didn't state it well". In this case, I really liked Raymond's answer (arrays are as efficient as long ints, which are both more efficient than lists of integers). It is close enough to the truth for the OP (*), and was stated with much less text than this message (or the one I'm responding to). I really should go to bed now, Martin (*) even closer to the truth is the observation that arrays are slightly more space-efficient, because they can store 32 bits in 4 bytes, whereas long ints only store 30 bits in 4 bytes. Time efficiency is more difficult to compare, because it depends on the individual implementation. From steven.bethard at gmail.com Wed Jul 6 10:41:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 06 Jul 2005 08:41:09 -0600 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com><1120565012.080020.309070@o13g2000cwo.googlegroups.com><1120590707.093007.175330@o13g2000cwo.googlegroups.com><11cloakd4glsbef@corp.supernews.com> <-8ydnZxXGOCQvlbfRVn-3Q@comcast.com> Message-ID: Ron Adam wrote: > Yes, I think a different key word would help. My current favorite > alternative is to put it in parentheses similar to list comprehensions > and use "let". > > (let x,y return x+y) If you haven't already, see: http://wiki.python.org/moin/AlternateLambdaSyntax for other similar proposals. STeVe From sjmachin at lexicon.net Fri Jul 1 10:03:48 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 02 Jul 2005 00:03:48 +1000 Subject: Splitting string into dictionary In-Reply-To: References: Message-ID: <42C54D44.6040107@lexicon.net> David Pratt wrote: > I have string text with language text records that looks like this: > > 'en' | 'the brown cow' | 'fr' | 'la vache brun' Pardonnez-moi, but I thought "how now brown cow" translated into something like "comme maintenant vache brune" -- something about the adjectives agreeing with the noun in both number and gender. But it's a long time since I was in school. Are adjectives unisex these days? From mwh at python.net Thu Jul 21 12:42:22 2005 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Jul 2005 16:42:22 GMT Subject: Hash functions References: Message-ID: Steven D'Aprano writes: > Do people often use hash() on built-in types? Only implicitly. > What do you find it useful for? Dictionaries :) > How about on custom classes? Same here. > Can anyone give me some good tips or hints for writing and using > hash functions in Python? Well, the usual tip for writing them is, don't, unless you need to. If implement __eq__, then you need to, so it's fairly common to just hash a tuple containing the things that are considered by the __eq__ method. Something like: class C(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __eq__(self, other): return self.a == other.a and self.b == other.b def __hash__(self): return hash((self.a, self.b)) Cheers, mwh -- I'm a keen cyclist and I stop at red lights. Those who don't need hitting with a great big slapping machine. -- Colin Davidson, cam.misc From mwm at mired.org Fri Jul 1 13:45:12 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 13:45:12 -0400 Subject: Assigning to None References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> Message-ID: <86ekai5sk7.fsf@bhuda.mired.org> Peter Hansen writes: > Mike Meyer wrote: >> Yes. I once grabbed an old program that did assignments to None. But >> that's always been a bad idea. > What was the use case!? Unpacking a tuple. Something like this: (foo, bar, None) = gen_tuple(stuff) I've never seen that usage anywhere else. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From darkcowherd at gmail.com Fri Jul 29 11:06:41 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Fri, 29 Jul 2005 20:36:41 +0530 Subject: Ten Essential Development Practices In-Reply-To: <42EA1B75.9040307@tiscali.it> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> Message-ID: <5f4d3cb50507290806162c2d09@mail.gmail.com> I am new to Python. I tried it out and think it is fantastic. I really loved this from import this statements: There should be one-- and preferably only one --obvious way to do it. But this not true of Python. GUI, Web development, Application Framework - it is shambles. It is so frustrating for a person who comes from a well designed environment / framework like Delphi. -Quote - Phillip J. Eby from dirtsimple.org Python as a community is plagued by massive amounts of wheel-reinvention. The infamous web framework proliferation problem is just the most egregious example. Why is Python "blessed" with so much reinvention? Because it's often cheaper to rewrite than to reuse. Python code is easy to write, but hard to depend on. You pretty much have to: 1. limit yourself to platforms with a suitable packaging system, 2. bundle all your dependencies into your distribution, or 3. make your users do all the work themselves Ouch. No wonder rewriting looks easier. The only way to stop this trend is to make it easier to reuse than to rewrite, which has been my mission with setuptools and EasyInstall -UnQuote My organisation writes products for Small and Medium Enterprises. We are using Delphi, we want to do more web based and Linux solutions, so I was evaluating Python, but even though I love the language and will probably do hobby programming using the language, I wouldnt really recommend our organisation to plan and execute a tranisition. We have been around a while and we have planned and done transitions from Clipper to FoxproW to VB to Delphi. >From what I understand Database access was in similar shambles in Python but a SIG took up the task and made some decisions which has now streamlined database access in Python. I really would love to have a Python where TOOWTDI Is there some place to discuss topics like this? Is this the right place? -- DarkCowherd From nemesis at nowhere.invalid Mon Jul 25 04:41:03 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Mon, 25 Jul 2005 08:41:03 GMT Subject: [ANN] XPN 0.5.0 released Message-ID: <20050725083558.1974.41689.XPN@orion.homeinvalid> XPN (X Python Newsreader) is a multi-platform newsreader with Unicode support. It is written with Python+GTK. It has features like scoring/actions, X-Face and Face decoding, muting of quoted text, newsrc import/export, find article and search in the body, spoiler char/rot13, random taglines and configurable attribution lines. You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn Changes in this release: * added some checks on the validity of out-going articles, as required by the GNKSA2.0 * added Reply-To, Followup-To and Newsgroups headers in the Article Pane, as required by the GNKSA2.0 * added !setcolor action, it lets you modify the foreground and backgrounnd colors of the article. * added inverted rules, they are successfull when the match is not satisfied. * now is possible to disable the threaded view. * now sorting column in the Threads Pane is stored * the header parser has been rewritten * added double-click support when you subscribe/unsubscribe groups (thanks to Lethalman). * fixed a bug in the autowrap feature that created double lines in some circumstances. * now the "View Raw Article" is correctly stored. XPN is translated in Italian and French, if you'd like to translate it in your language and you are familiar with gettext and po-files editing please contact me (xpn at altervista.org). -- Calm down. It's only ones and zeros. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From Holzmayer.Bernhard at deadspam.com Thu Jul 14 06:20:03 2005 From: Holzmayer.Bernhard at deadspam.com (Bernhard Holzmayer) Date: Thu, 14 Jul 2005 12:20:03 +0200 Subject: more newbie list questions References: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> Message-ID: googleboy wrote: > Hi there. Hi googleboy! > > I am doing a bunch of processing over a list of lists, and am > interested in doing several things taht don't seem to be working for me > just at the moment. > > I have a list of books with several fields (Title, Author1, Author2, > Publisher, ISBN) in a csv. > > I have a cell.txt file that looks like this: > > ++ > The title is %title%.

> The author is %author1% %author2%

> The Publisher is %publisher1% %publisher2%

> The ISBN is %ISBN%

> ++ This looks like a DOS-batch-file. Maybe you'd better just leave it to DOS to populate it, just by exec-uting it in an environment which has title, authort1, ... set. ?? On the other hand, if you need not relate to the cell.txt file, you could just use something like sAuth = "The author is %s" % author1 > > I know how to do something like sAuth = re.sub('%author1%', author1, > sTemplate), but I can't figure out to populate variables within python > from the list of fields. I guess, that you open the csv-file and then use readline for each record. Since csv files are ; separated (or ,), just do recordlist = current_line.split(';') which provides all entries from the read line in a list. Or even better: (title,author1,author2,publisher1,publisher2,ISBN) = current_line.split(';') Now you can do something like sAuth = "The author is %s" % recordlist[1] in the first case, or sAuth = "The author is %s" % author1 in the second > > The second thing I am trying to figure out is how to add a field (or > populate an empty field) called filename with the value of ISBN + > '.txt', though I hope this becomes pretty self evident after someone > helps me with the above. You're certainly right about the evidence of the following: filename="%s.txt" % ISBN > > The last thing that is vexing me at the moment is something I am not > sure if it is possible. Once I have populated this filename field, I > will want to try to do something like: > > for book in all_books > open(r'd:\path\to\files\%filename%', 'a') > some_function > > > Where I replace %filename% with the value of the filename field for > each book. Is it possible to do some sort of search and replace like > that over a command within python? > > Or is there another way entirely different to accomplish such a task, > like maybe assigning the path/filename to a variable... ? > I'd try like this: 0. Initialize an empty list all_books=[] 1. While reading in the csv file line by line, you received the ISBN for that line(book). (Look above the line with the split command) Now add this ISBN to the list by: all_books.append(ISBN) 2. After the list is complete (all records read, file closed), you can do this as you assumed: for book in all_books: f=open(r"d:\path\to\files\%s.txt" % book, 'a') some_function... f.close() > TIA! > > Googleboy Bernhard P.S: 1. Looking into the Python tutorial which is available online at www.python.org, would have answered most of your questions. From simon.dahlbacka at gmail.com Fri Jul 15 05:58:39 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 15 Jul 2005 02:58:39 -0700 Subject: Python Programming Contest In-Reply-To: References: Message-ID: <1121421519.690539.52120@g44g2000cwa.googlegroups.com> Are you aware of http://mathschallenge.net/index.php?section=project ? The "The focus will be on algorithms that require a bit of thought to design but not much code to implement." part seems common, although your problem domain probably is larger. /Simon From rbt at athop1.ath.vt.edu Tue Jul 12 10:19:04 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 12 Jul 2005 10:19:04 -0400 Subject: breaking out of nested loop Message-ID: <1121177944.5591.4.camel@athop1.ath.vt.edu> What is the appropriate way to break out of this while loop if the for loop finds a match? while 1: for x in xrange(len(group)): try: mix = random.sample(group, x) make_string = ''.join(mix) n = md5.new(make_string) match = n.hexdigest() if match == target: print "Collision!!!" print make_string Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime()) print "Stop", Stop break else: continue except Exception, e: print e From peter at engcorp.com Sat Jul 30 17:49:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 17:49:07 -0400 Subject: Comparison of functions In-Reply-To: References: <4cPGe.28613$fm.2023944@news4.tin.it> Message-ID: Steven D'Aprano wrote: > Python already allows you to compare "this is not a number" with the float > 5.0. Mathematically, that is meaningless, but I would bet money that > 99.9% of programmers would demand that they should be able to sort the > list ["this is not a number", 5.0]. Do you think that it is unintuitive > too? I strongly suspect that 99.8% of (let's say non-newbie) programmers would have no expectation that the default sort routine would do something other than barf on that input. You want "garbage in, garbage out", but in Python it's supposed to be "garbage in, exception out, please be explicit about what you want next time". I can't think of any use case for sorting a list like that which wouldn't most appropriately be handled with a custom comparison routine passed to sort. -Peter From phawkins at connact.com Fri Jul 22 20:37:47 2005 From: phawkins at connact.com (Patricia J. Hawkins) Date: Fri, 22 Jul 2005 20:37:47 -0400 Subject: tuple to string? References: <42E0EED4.4020001@gmx.net> Message-ID: QH> On 7/22/05, Francois De Serres wrote: >> what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to >> the string 'spam'? QH> Use ''.join and chr() as others have pointed out. Here are QH> just-for-fun versions ;) .> t = (0x73, 0x70, 0x61, 0x6D) QH> (use string formatter): .> '%c%c%c%c' % t Or more generally: >>> t = (0x73, 0x70, 0x61, 0x6D) >>> '%c'*len(t) % t 'spam' but that's VERY perlonic python. Still, it's a technique that can come in handy when building, say, SQL queries on the fly. -- Patricia J. Hawkins Hawkins Internet Applications www.hawkinsia.com From bronger at physik.rwth-aachen.de Fri Jul 29 11:59:35 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 29 Jul 2005 17:59:35 +0200 Subject: Wheel-reinvention with Python (was: Ten Essential Development Practices) References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> Message-ID: <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> Hall?chen! Michael Hoffman writes: > Dark Cowherd wrote: > >> GUI, Web development, Application Framework - it is shambles. > > Yeah, I agree. When I finally make that GUI application I still > don't know whether I am going to use wx or PyGTK. I agree, too, although I can only talk about GUI toolkits. At first one thinks "well, perfect, I have the choice between four great GUI systems". However, except for very special demands, there is no clear winner. You start learning one, and immediately wonder whether the other might be better. Although it sounds paradoxical, this can be quite frustrating. After all, most of us don't have the energy or motivation to test all candidates thoroughly. Besides, development resources are shared between all projects. This is especially sad with regard to IDEs. There are even more IDEs/dialog editors/widget builders than Toolkits, none of them being mature. >> Is there some place to discuss topics like this? Is this the right place? > > Sure, although you might want to start a new thread. ;) At least a new subject ... Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 27 04:00:28 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 27 Jul 2005 09:00:28 +0100 Subject: [OT] Problems with permissions etc In-Reply-To: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: Hi Frank, Frank Millman wrote: > Hi all > > This is not strictly a Python question, but this newsgroup feels like a > family to me, so I hope that someone will be kind enough to respond to > this, or at least point me in the right direction. > > While developing under linux, I use my own computer, as the only user, > so it has become my habit to login as root and do all my work as a > superuser. I know that this is not desirable, but it has become a > habit, which I am now trying to get out of. > Good. Most 'problems' I have running this kind of system at home can be fixed by adding your user account to the /etc/sudoers file like so:- martin ALL=(ALL) ALL so every now and then when I need to do somthing as root I just sudo (and enter *my* password) Linux distros such as ubuntu use this scheme and I think MAC OS X does too. > Now that I am logging in as an ordinary user, I find that a number of > things that previously 'just worked' have now stopped working. I can > usually find the cause, and tweak whatever is needed to get it working > again, but I am wondering how most people work. Is it normal to > experience these kinds of problems, or am I missing a trick somewhere > and making my life more complicated than it need be? > > I will give two examples. I would like advice on the best way to fix > them, but I would prefer a more general reply that explains how > experienced unix/linux users go about handling these kinds of issues. > > 1. The application I am developing will eventually be deployed as a > multi-user accounting/business system. I want to identify the physical > workstation that generates each transaction, so I am using the mac > address. My method for extracting this is as follows - > mac = os.popen("ifconfig|grep Ether|awk {print '$5'}").read()[:-1] # > I did not come up with this myself, I cribbed it from somewhere > As root, this works fine. As non-root, ifconfig is not found. The > reason is that it is in /sbin, and this is not included in the default > path for non-root users. I could either include /sbin in my path, or I > could change the above line to /sbin/ifconfig ... Alternatively, there > may be a better way of getting the mac address or identifying the > workstation. > Since you are relying on ifconfig anyway I would just stick the fully qualified pathname (/sbin/ifconfig) into the python code > 2. I am using wxPython, which was compiled from source. It so happens > that I did this with a colleague who also has a user account on my > machine, so the compile and install of wxPython was done from his home > directory. > > When I start my app as non-root, the import of wx fails, as it cannot > find certain files. They are in the other user's home directory, but as > the top-level directory has permissions of drwx------, my user cannot > read anything in that directory. I can change the directory > permissions, or I can move the files to another area which all users > can read. If the latter, is there a 'correct' place to put them? > Re-compile and or install wxPython as root, this will install it into a default place (/usr/local or wherever) and you will not need to worry about permissions. > I think that these problems are a result of my lack of experience as a > system administrator. On the other hand, the various books and articles > I have read to try and improve my knowledge have not covered these > kinds of issues. Is it just something that one learns the hard way? > > Any advice, especially pointers to reading matter that covers this > topic, will be much appreciated. > > Thanks > > Frank Millman > Cheers Martin From newstonne at web.de Wed Jul 13 08:42:52 2005 From: newstonne at web.de (Roland Heiber) Date: Wed, 13 Jul 2005 14:42:52 +0200 Subject: Building a function call? In-Reply-To: References: Message-ID: Francois De Serres wrote: > Hiho, > > Having a string: "dothat" > and a tuple: (x, y) > 1. What's the best way to build a function call like: dothat(x,y)? Not the best (not at all) but one way: def dothat(x,y): print "Called with:", x, y c = (1,2) locals().get("dothat")(*c) ---- Called with: 1 2 HtH, Roland From rtw at freenet.co.uk Mon Jul 11 17:28:12 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 11 Jul 2005 22:28:12 +0100 (BST) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: <20050711212812.6288FE000175@astro.systems.pipex.net> Ralf W. Grosse-Kunstleve wrote in news:mailman.1616.1121111515.10512.python-list at python.org in comp.lang.python: > --- Robert Williscroft wrote: > >> My apologies for having to resort to email but for some reason I >> can't post this message to comp.lang.python. I've tried about 4 times >> including starting a >> new thread, but for some reason it doesn't turn up, though I've >> followed up on >> another thread without problem. > > Very strange. I hope it is not a conspiracy! :) > You can email to the list directly (that's what I am doing): > > python-list at python.org > I'll follow up and post this, and then see what happens :). >> > Is there a way out with Python as-is? >> > ------------------------------------- >> > >> > Yes. If you take the time to look at the file in the CVS you'll >> > find that I was cheating a bit. To reduce the terrible clutter >> > above, I am actually using a simple trick:: >> > >> > adopt_init_args(self, locals()) >> > >> >> Also there is a decorator solution: >> >> def init_self( init ): >> vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] >> >> def decorated_init(self, *args, **kw): >> off = 0 >> for name in vn: >> if not name.startswith('_'): >> if name in kw: >> value = kw[name] >> else: >> value = args[off] >> off += 1 >> >> setattr( self, name, value ) >> >> init( self, *args, **kw ) >> return decorated_init >> >> >> class MyClass(object): >> __slots__ = ['x', 'z'] >> >> @init_self >> def __init__( self, x, _y, z ): >> pass >> >> def show( self ): >> for i in self.__slots__: >> print 'self.%s = %d' %(i,eval('self.%s' % (i,))) >> >> MyClass( 1, 2, 3 ).show() >> >> MyClass( z = 1, x = 2, _y = 3 ).show() >> >> The __slots__ is in the test just because you mentioned you like it, >> the decorator doesn't need a "slots" class. >> >> AFAICT this differs from your proposal in that in your proposal you >> want to use '.' as an include prefix the above uses '_' as an exclude >> prefix. >> >> Rob. > > I like the looks of the decorator approach a lot. Could this somehow > be enhanced such that the user doesn't have to know about the > underscore? The underscore is just there so there is a way of having arguments that aren't added as attributes to the first object, so if that isn't required it could just be omited. Also AIUI (the above is my first attempt to write a decorator), decorators can have arguments so the decorator could take an "omit_prefix" argument, so the user could specify there own prefix. Or maybe have an include prefix, say "self_", if thats what you prefer. Personaly I'm happy with the underscore, 1 leading underscore at module scope means hide the name, 2 at class scope means hide the name, so I kinda like that an undersore is used to omit an argument. > Thinking about runtime efficiency, could the decorator > approach somehow achieve that the attribute-to-be arguments are never > added to locals()? > Again AIUI, locals() is an inbuild that constructs a dict of the local arguments and variables, IOW the dict doesn't exist *until* you call locals(). Wether or not the fact the decorator doesn't call locals() makes any difference though I don't know, the real arguments will get passed to decorated_init() in some way and then setattr()'d to the self object. But then again there is a loop, 2 if's and a lookup of the keyword dictionary in there, using this as it stands is going to hurt compared to doing the asignments manually inside __init__(), though as I haven't timed it, I could be wrong ;-). Rob. -- http://www.victim-prime.dsl.pipex.com/ From rkern at ucsd.edu Tue Jul 12 07:10:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 04:10:51 -0700 Subject: Web App like Google In-Reply-To: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> Message-ID: godwin wrote: > Hello there, > I need some thoughts about a web application that i am dreaming > and drooling about in python. I want a search page to look exactly like > Google. But when i press the search button, it should search a database > in an rdbms like Oracle and provide results. > For example, if my keywords are "all customers with names > starting with 'God'" it should somehow search table CUSTOMER , with > following query : > SELECT CUSTNAME FROM CUSTOMER WHERE CUSTNAME LIKE 'God%' This is a Natural Language Processing (NLP) task. In general, it's pretty hard. For Python, there is the Natural Language Toolkit (NLTK): http://nltk.sourceforge.net/ You could get pretty far, though, by accepting a specific subset, the so-called "controlled natural language" approach. For example: http://www.jfsowa.com/clce/specs.htm http://www.ics.mq.edu.au/~rolfs/controlled-natural-languages/ http://www.ifi.unizh.ch/attempto/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From caseyhHAMMER_TIME at istar.ca Fri Jul 15 15:37:32 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Fri, 15 Jul 2005 19:37:32 GMT Subject: IDLE in Jython References: <1121436094.769121.247470@z14g2000cwz.googlegroups.com> Message-ID: How about the following: - making Jython mostly work up to Python 2.4? - making a PVM (Python Virtual Machine) for the Palm? -- Regards, Casey From bokr at oz.net Tue Jul 12 14:47:55 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 18:47:55 GMT Subject: Tricky Dictionary Question from newbie References: <3jftckFpvhv2U2@individual.net> Message-ID: <42d40f61.9312480@news.oz.net> On Tue, 12 Jul 2005 11:52:41 -0400, Tim Peters wrote: >[Peter Hansen] >... >> I suppose I shouldn't blame setdefault() itself for being poorly named, > >No, you should blame Guido for that . > >> but it's confusing to me each time I see it in the above, because the >> name doesn't emphasize that the value is being returned, and yet that >> fact is arguably more important than the fact that a default is set! >> >> I can't think of a better name, though, although I might find "foo" less >> confusing in the above context. :-) > >I wanted to call it getorset() -- so much so that even now I sometimes >still type that instead! The "get" part reminds me that it's fetching >a value, same as dict.get(key, default) -- "or set"'ing it too if >there's not already a value to "get". If you have a fancy enough >editor, you can teach it to replace setdefault by getorset whenever >you type the former ;-) But it isn't get OR set, it's set_default_if_no_value_then_either_way_effectively_get ;-) Regards, Bengt Richter From hancock at anansispaceworks.com Tue Jul 5 10:46:41 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 09:46:41 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: <200507050946.41598.hancock@anansispaceworks.com> On Tuesday 05 July 2005 08:17 am, Steven D'Aprano wrote: > Sorry, but you are mistaken. "lambda" is a _reserved_ word in the > Python language, while "function" etc are not, but they are certainly > part of the language. Try explaining what def and import do without > using the words "function" or "module". Maybe you can do it, using > circumlocutions, but it isn't easy, and costs clarity. This is still a relevant distinction. One relevant point is that I am perfectly free to use, say, the Spanish or Chinese word to describe "module" or "function", but the keywords "def" and "import" will remain the same. > > The second error is that I believe most english speakers COULD provide > > a definition for the fairly common words "function", "class", and > > "decorator". The exact meaning of "class" might not be what they expect > > at first, > > Function, in the sense of a mathematical function, I agree. Class as in > the thing you go to at school and decorator as in the person who advises > you what colour curtains to have, certainly. But in the Python sense? No. > Especially not decorator, which I believe most _programmers_ would have > trouble explaining, let alone non-programmer English speakers. I know I do. The "Python sense" is not arbitrary. There are very direct visual or logical (i.e. INTUITIVE) connections between these words' *English* meanings (not just mathematical, either) and their meanings in Python. A "Function" is (in English) (kdict-gcide*): 1.) The act of executing or performing any duty, office, or calling; performance.... 2.) The appropriate action of any special organ or part of an animal or vegetable organism... [...] 5.) (math) A quantity so connected with another quantity, that if any alteration be made in the latter there will be a consequent alteration in the former. The programming use is probably *closer* to the English meaning than the math jargon meaning (except in the sense of "functional programming" which leans more on the math meaning. Similarly, "decorate" is 'make more attractive by adding ornament, colour, etc.' In Python, a "decorator" applies a wrapper to a function to provide it with some additional functionality. The function definition is furthermore "decorated" with the decorator declaration to give it more meaning, which is arguably more aesthetically pleasing (otherwise, why not literally wrap with a function after defining the function?). These meanings are very connected with the English definition of the word. "Class" can, of course, mean a room in which you teach classes, but again Webster's will certainly provide meaning much closer to the programming term: 1. A group of individuals ranked together as possessing common characteristics... [2 is the class of students sense] 3. A comprehensive division of animate or inanimate objects, grouped together on account of their common characteristics 4. A set; a kind or description, species or variety. Meanings 1,3, & 4 are all arguably intimately connected to the OOP meaning, especially meaning #3 which even mentions "objects". (And I won't bother to point out that the English meaning of "object" is tied closely to what it means in programming). A similar argument can be made for "object", "module", "script", and even "method" and "program". Now, if you are armed ONLY with the English definition, you will possibly run into some trouble, because the programming usage is a *specialization* of the term -- we strictly take only *one* of the English definitions to apply, and we narrow its meaning a bit. "Objects" in computer science never means "the purpose of the program" nor does it ever refer to "a small brick", even though the English word can mean both of those things. But it's not exactly a shocker that a programming term is going to apply to things you can find in a program, so I don't think we're stumping the newbie with such terms. "lambda" has no such advantage. Here's the *entire* gcide definition: Lambda \Lamb"da\, n. [NL., fr. Gr. la`mbda.] 1. The name of the Greek letter [Lambda], [lambda], corresponding with the English letter L, l. [1913 Webster] 2. (Anat.) The point of junction of the sagittal and lambdoid sutures of the skull. [1913 Webster] 3. (Phys.) A subatomic particle carrying no charge, having a mass equal to 2183 times that of an electron; it decays rapidly, typically forming a nucleon and a pion. --MW10 [PJC] Lambda moth (Zool.), a moth so called from a mark on its wings, resembling the Greek letter lambda ([Lambda]). [1913 Webster] > > but exposure to any object oriented language would make the > > concept quickly familiar. > > Just as exposure to functional languages would make lambda very familiar. Yeah, well, there *is* an entry in the "Online Dictionary of Computing": LAMBDA A version of typed lambda-calculus, used to describe semantic domains. ["Outline of a Mathematical Theory of Computation", D.S. Scott, TM PRG-2, PRG, Oxford U, 1971]. If even this means what "lambda" does in Python, I would be surprised, certainly it doesn't mean a whole lot to me. > Think back to when you were a schoolboy at your first day of school. > Unless you had a very unusual upbringing, you probably had never heard the > word "function" before. Total BS. I knew the word "function" in it's English language sense, probably by the time I was 6. I *know* my kids know it. > There is nothing about the word "function" that > brings to mind "a mathematical entity which transforms a variable into a > different variable", They'll get this in about the 6th grade, IIRC. > let alone "a programming subroutine that returns a > result". It also *does something*, which is what my first understanding of a "function" was. Side-effects would seem to be perfectly natural to anyone with an English language background, I guess. ;-) > (Or for that matter, "the purpose which a person or thing is > for", as in the function of a spanner is to tighten nuts on bolts.) You are really stretching if you think kids (let alone average adults) don't know this meaning of the word "function". > You had to learn that word, discover what it means, and then it becomes > familiar. You don't notice the process only because it happened so long > ago, at an age that your brain was operating in "language acquisition > mode" and picking up vocabulary at an incredible rate. If you're arguing that language is acquired rather than innate, you are bludgeoning an obvious point. The point is that *jargon* should ideally derive in a natural way from commonly-used language, if we want it to be easy to acquire for people who don't learn programming between the ages of 1 and 5 as we learn our native languages. Even in the 21st century, I think this includes just about all of us. ;-) > There is nothing about the word "string" that especially brings to mind > "an array of bytes representing characters". The analogy of "string of > characters" to "string of beads" breaks down as soon as you have multiple > lines of text. Ah, but that's useful. "Strings" AREN'T "multiple lines of text" in the computer's memory, are they? '\n' is just another bead. The "multiple lines" is a representation, or way of laying out the beads. Very useful distinction, and immediately driven by the choice of analogy. I'm going to use that, thanks. ;-) > And as for float, that's what boats do, heaven only knows > what it has to do with numbers. Ah, yes. Here, it is clear that Fortran whips Python on readability, it calls them "reals". The only problem is that real mathematicians probably had conniption fits about the fact that "real" variables actually represent "rational" numbers. > (Yes, I know what it has to do with numbers. But that is something I had > to learn, and even now I still have difficulty because I expect floats to > operate like mathematical real numbers, and they don't.) > > And dare I say it, what do constricting snakes have to do with programming? Nothing. Then again *we* know that "Python" hasn't anything to do with snakes, either. ;-D > I won't say that the anonymous function meaning of lambda comes to my mind > before the Greek letter, but it isn't very far behind, and rapidly > catching up. (I use lambda a lot more than I speak Greek.) It wouldn't > surprise me if one day I think of Python programming before the Greek > letter, just as the world aleph brings to my mind the sense of infinity > before the sense of it being a Hebrew letter. Then it is clearly *not you* who should be served by the naming scheme. Anyone so deeply trained and experienced should be expected to adapt, you have the wherewithall to do so. It is the new user for whom the clarity of the jargon is so important. Personally, I find the term "anonymous function" to be a whole lot clearer than "lambda" or "lambda function". Indeed, if asked what "lambda" means, my reply is it's a "stupid name for an anonymous function", and if my listener is less savvy "for a function that doesn't have a name, because you only use it once". Having said that, I too will miss the *concept* of an anonymous function, although I wouldn't mind at all if its name changed, or if it were somehow integrated into the "def" keyword's usage. Using backticks or some other syntax delimiter also sounds promising, although we're sort of running out of them. ;-) -- *An unfortunate acronym for "Gnu Collaborative International Dictionary of English". -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From sybrenUSE at YOURthirdtower.com.imagination Thu Jul 21 07:04:31 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 21 Jul 2005 13:04:31 +0200 Subject: wxPythin installation woes References: <1121939845.672075.122220@z14g2000cwz.googlegroups.com> Message-ID: linuxfreak enlightened us with: > Turns out that libstdc++.so.5 is needed but I checked and i see > that libstdc++.so.6 is installed on my system. On my system (Ubuntu, based on Debian), I can have multiple versions of libstdc++ installed at the same time. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From cliff at develix.com Sat Jul 30 17:58:00 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 14:58:00 -0700 Subject: python SMTP server In-Reply-To: <1122759885.881136.186360@g47g2000cwa.googlegroups.com> References: <1122759885.881136.186360@g47g2000cwa.googlegroups.com> Message-ID: <1122760681.19618.40.camel@localhost.localdomain> On Sat, 2005-07-30 at 14:44 -0700, Fernando M. wrote: > Hi, > i made a test with smtplib module a few days ago, for sending mails, > and i was wondering if there's another module for running an SMTP > server, so i could make a standalone script for sending mails without > using an external SMTP server. > I've been searching but i'm not sure if there are modules for it, or > anything. > Which ones are my options? You might take a look at: http://www.divmod.org/projects/quotient It does quite a bit more than just SMTP, but that is included. However, you should note that if you are running the server at home, chances are that most mail servers will reject mail from your system. It's best to use the server your ISP provides. You can have your local SMTP server forward through your ISP's server, but this is, in most cases, unneeded complexity. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From ac063 at lafn.org Thu Jul 14 18:46:40 2005 From: ac063 at lafn.org (David Smith) Date: Thu, 14 Jul 2005 15:46:40 -0700 Subject: Newbie question: Explain this behavior Message-ID: Why does code snippet one work correctly, but not two. The only difference is the placement of the "else". I know that indentation affects execution, but how does it change behavior in the following examples? Thank you. 1. for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' Output: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 2. for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' Output: 3 is a prime number 4 equals 2 * 2 5 is a prime number 5 is a prime number 5 is a prime number 6 equals 2 * 3 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 8 equals 2 * 4 9 is a prime number 9 equals 3 * 3 From danny_milo at nospam.yahoo.com Mon Jul 11 15:03:23 2005 From: danny_milo at nospam.yahoo.com (Danny Milosavljevic) Date: Mon, 11 Jul 2005 21:03:23 +0200 Subject: cursor positioning References: Message-ID: <1121105408.19900@news.liwest.at> Hi, On Mon, 11 Jul 2005 15:29:41 +0200, Mage wrote: > Dear All, > > I am writing a database import script in python and I would like to > print the percentage of the process to the last line. I would like to > update the last line at every percent. You know what I mean. > > How can the cursor be positioned to the last line or somewhere else on > the screen? Curses starts with clearing the whole screen and it is > overkill. Many modules are on the net but I would like to resolve this > simply task with native python. > > I tried: > > for something: > print chr(8)*20+mystring, > > but it is nasty and didn't work well. > > Mage If you only want to support ansi terminals (which is questionable, but possible), then there are escape codes that are very helpful (searching for ansi escape codes or something in google should help you find the remainder): the general syntax is ESC[ action usually is the first letter in the sequence, hence parameters are usually numbers (duh :)) ESC is chr(27) (ascii 27, octal \033) actions are H cursor go home (top left corner usually) C go right times D go left times A go up times B go down times K clear to end of line 2J clear screen (yes, to every rule there are exceptions :), note that this does not make the cursor go home) m set color/highlight/formatting flags Examples ESC[2JESC[H same as "clear", clear screen, go home \rESC[Kprogress %d probably what you want :) The downside of this is that determining the size of the screen is pretty hard to do right. Process is usually, read TERM environment variable, read /etc/termcap (deprecated) "co" attribute (columns), "li" attribute (rows). That has been deprecated because of all those resizeable terminals out there. Now its something like outputting some magical stuff to make the terminal emulator send back the current sizes immediately once, and whenever they change. I'm not totally clear how that works since I'm too lazy to care :) What you want is probably prc = 0 for prc in range(100): sys.stderr.write("\r\033[KProgress %d%% ... " % prc) sys.stderr.flush() time.sleep(0.5) though :) Note that this can wreck havoc onscreen if the terminal is smaller than what is needed to print that horizontally, so technically its not totally clean code. Hope that helps cheers, Danny From smitty_one_each at bigfoot.com Mon Jul 4 20:48:36 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Mon, 04 Jul 2005 20:48:36 -0400 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <42c929dc$0$27601$636a15ce@news.free.fr> Message-ID: <87wto613iz.fsf@bigfoot.com> >> My question isn't as all-encompassing as the subject would >> suggest... >> >> I am almost a Python newbie, but I have discovered that I don't >> get along with IDLE, as i can't work out how to run and rerun a >> routine without undue messing about. >> >> What I would really like is something like an old-style BASIC >> interpreter, in which I could list, modify and test-run >> sections of code, to see the effects of tweaks, without having >> to save it each time, or re-typing it over and over bruno> (snip) >> I see lots of alternate IDEs etc, but which would allow me the >> simple interface that I have described? bruno> Try Emacs + python-mode. Emacs surely has a lot of warts, bruno> but I'm still looking for a better and more versatile code bruno> editor/IDE - specially when it comes to languages with REPL bruno> (-> Read-Eval-Print Loop). Emacs is an excellent long-term time investment. See http://www.emacswiki.org for good justice. R, C From grante at visi.com Thu Jul 7 00:42:59 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 04:42:59 -0000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> <11cp7fusjoid468@corp.supernews.com> Message-ID: <11cpcmj8m03r98@corp.supernews.com> On 2005-07-07, Leif K-Brooks wrote: > Grant Edwards wrote: >> On 2005-07-07, Leif K-Brooks wrote: >>>_NOVALUE = object() >>>class demo: >>> def foo(v=_NOVALUE): >>> if v is _NOVALUE: >>> return self.v >>> else: >>> self.v = v >> >> >> Apart from the change in the logic such that the set operation >> doesn't return a value, how is that any different? You're just >> creating your own non-integer-value "None" object instead of >> using the one built in to the language. > > Sorry, my mistake: for some reason, I misunderstood your message as > complaining that you couldn't do the same thing if you needed None to be > usable as a value too. Somebody had proposed eliminating None as a usable object and people who use None now should just use 0, [], "", or () depending on the "type" of the expected value. I was providing an example of where I would use None in a context where an "integer context" and where 0 wasn't a good substitue. >>>But what's wrong with properties? >> >> Huh? > > Why not use a property > (http://www.python.org/2.2.1/descrintro.html#property) instead of a > special property-like method? Habit and the desire to make it explicit that something more is going on that just assigning or evaluating an instance's attribute. -- Grant Edwards grante Yow! I want EARS! I at want two ROUND BLACK visi.com EARS to make me feel warm 'n secure!! From godoy at ieee.org Fri Jul 29 22:47:52 2005 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 29 Jul 2005 23:47:52 -0300 Subject: ANN: PyDev 0.9.7 released References: <42A720BD.5050701@esss.com.br> <42C175A5.5000206@esss.com.br> <42E6412A.4020905@esss.com.br> Message-ID: Rocky Burt wrote: > Installing fresh PyDev 0.9.7 onto eclipse 3.1 (no prior PyDev installed) > yields the following error when opening a python file. Seems like a > simple enough error... the PyEdit class seems to be present. I had the same problems today. Then I read the requisites: Java 1.5.0. ;-) Installing it made everything work perfectly. -- Jorge Godoy From jelleferinga at gmail.com Mon Jul 4 08:13:07 2005 From: jelleferinga at gmail.com (jelle) Date: 4 Jul 2005 05:13:07 -0700 Subject: Cancelling a subprocess based on its output Message-ID: <1120479187.911224.269580@f14g2000cwb.googlegroups.com> Hi, I'm using the subprocess module to run a open-source lighting simulation software, Radiance, and am using python to script it. When Radiance finds a scene where no light is present its prints out 'warning - no light sources found' to the console. I'm looking for a way to terminate the subprocess when this message is spitted out to the console. Searching this forum on subprocess & stderr didn't lead to a clue to solving this problem. I'm using both win32 & linux to run these simulations, so a cross-platform way of doing this is important. Any suggestions? Cheers, Jelle. From tjreedy at udel.edu Mon Jul 18 03:04:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 18 Jul 2005 03:04:27 -0400 Subject: Who uses input()? [was Re: question on "input"] References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com><1121179143.995844.28690@g47g2000cwa.googlegroups.com><200507141240.14373.hancock@anansispaceworks.com><3e8ca5c8050717221220121c54@mail.gmail.com> Message-ID: "Nathan Pinno" wrote in message news:BAY106-DAV7A5CF5B26D33618DCED9AC4D50 at phx.gbl... > I use input() all the time. I know many people say it ain't safe, but > whose going to use it to crash their own comp? Only an insane person > would, This is usage Guido intended it for, not for production apps distributed to world. From and-google at doxdesk.com Mon Jul 25 10:10:07 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 25 Jul 2005 07:10:07 -0700 Subject: Importing User-defined Modules In-Reply-To: References: Message-ID: <1122300606.943361.264980@g47g2000cwa.googlegroups.com> Walter Brunswick wrote: > I need to import modules with user-defined file extensions > that differ from '.py', and also (if possible) redirect the > bytecode output of the file to a file of a user-defined > extension. You shouldn't really need a PEP for that; you can take control of the compile and import processes manually. See the py_compile and imp modules. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From Gerald.Klix at klix.ch Thu Jul 7 03:35:56 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Thu, 07 Jul 2005 09:35:56 +0200 Subject: Do a "Python beginners e-mail list" exist? In-Reply-To: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> References: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> Message-ID: <42CCDB5C.1020300@klix.ch> Perhaps irc://irc.freenode.net##python Note the double # This channel is less crowed as the #python channels are. Alessandro Brollo schrieb: > Far from a professional programmer, I'm simply a > newbie Python user. Two basic questions: > > 1. I don't want to post banal questions about Python > to main Python list. Does a "banal Python questions > list" or a "Python beginners list" exist? > > 2. There is somewhere a very patient fellow willing to > be my free "python tutor" by personal e-mailing > outside the mail list? . The ideal candidate would be > someone, sharing with me some other fields of interest > (I'm a middle-aged Italian pathologist, with some > dBase III and dBase IV past programming experience, > and I like nature and mainly horses). > > Thanks > > Alessandro Brollo > > > > > > > > ___________________________________ > Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB > http://mail.yahoo.it -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From fphsml at gmail.com Sun Jul 3 01:48:20 2005 From: fphsml at gmail.com (James) Date: 2 Jul 2005 22:48:20 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <1119648577.754818.119530@z14g2000cwz.googlegroups.com> Message-ID: <1120369700.673002.42970@g47g2000cwa.googlegroups.com> Steven D'Aprano wrote: > On Fri, 24 Jun 2005 14:29:37 -0700, James wrote: > > > Interesting thread ... > > > > 1.) Language support for ranges as in Ada/Pascal/Ruby > > 1..10 rather than range(1, 10) > > What advantages do Pascal-like for loops give over Python for loops? > > The only two I can think of are trivial: > > (1) the Pascal-like for loop is six characters shorter to type: > > for i = 1 to 10: # 16 chars > for i in range(1, 10): # 22 chars > > (2) for very large ranges, you don't have to hold the entire list of > integers in memory. But you can use xrange() instead of range(), which > also doesn't hold the entire list in memory. First, I was never concerned about what I can do with the new keyword that I could not do without since most languages are turing complete. The question is that of elegance and it is subjective. I do know that if Python kept adding features that everyone liked, it will end up like Perl (although D seems to be doing a great job incorporating everyone's favorite features while still retaining language consistancy. Then again, it is very new.). But this thread is about favorite features from other languages. Secondly, the point was about ranges. Their use in loops (as in Ada and Ruby) is just one instance. For me, they are more readable in the same way I like -- for comments as in Eiffel and Ada rather than // and # which do the same. > > 2.) Contracts > > Explain please. Design By Contract (as in Eiffel and D) > > 3.) With > > Explain please. As in Delphi http://www.delphibasics.co.uk/RTL.asp?Name=With There have been some PEPs regarding this. From bmetcalf at nortel.com Thu Jul 14 13:19:56 2005 From: bmetcalf at nortel.com (Brandon Metcalf) Date: Thu, 14 Jul 2005 17:19:56 +0000 (UTC) Subject: trouble importing modules Message-ID: I come from a Perl and C background and have been given an application written in Python to maintain and I know very little about Python. I'm having trouble at run time with importing modules. Specifically, in several places time.strptime() is being used and Freeze is being used to produce binaries for each platform where this application runs. _strptime.py is also being supplied with the binaries. The first problem I encountered coming from _strptime.py was: ImportError: No module named calendar _strptime.py imports calendar, but my thought was that since freeze isn't being run against _strptime.py directly, the calendar module may not be getting built into the resulting binary. So, I added "import calendar" to the file I'm running freeze against. This fixed (probably not in the proper way) the above error, but now I'm getting from calendar.py: ImportError: No module named datetime So, my question is how can I ensure that all modules that _strptime.py, calendar.py, etc. rely are built in the resulting binaries without having to import everything explicitly in my code? I'm using Python 2.3.4. Thanks. -- Brandon From fowlertrainer at anonym.hu Wed Jul 6 05:19:24 2005 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Wed, 06 Jul 2005 11:19:24 +0200 Subject: How to disable rangeselect in wxGrid Message-ID: <42CBA21C.9050202@anonym.hu> Hi ! I have a little problem with wxGrid. In Delphi I can set in grids how I want to select cells. I can select only individual cells, or ranges. In my program I don't wanna use ranges. But I don't find any methods or properties what can set this option. The range selection mode is disturb the users. Usually the ranges are used to select more cells, and do any operations with them. But in my program the user can select only one(!) cell, and this cell set the actual day, and actual person. If many cells are selected, the user (and I too) cannot determine, which day/person is the actual. So if possible, I want to "protect users from this effect". Is anyone can help me ? Thanx for it: ft --------------------------------------------------------------------- To unsubscribe, e-mail: wxPython-users-unsubscribe at lists.wxwidgets.org For additional commands, e-mail: wxPython-users-help at lists.wxwidgets.org From fdeserres at gmx.net Wed Jul 13 08:35:20 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 14:35:20 +0200 Subject: Building a function call? Message-ID: <42D50A88.3070909@gmx.net> Hiho, Having a string: "dothat" and a tuple: (x, y) 1. What's the best way to build a function call like: dothat(x,y)? Assuming dothat is def'd in the same module, 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) the right way to have it executed? If dothat is def'd in another module: 3. what would be the right way to initialize the globals to pass to eval ? TIA, Francois From rkern at ucsd.edu Sun Jul 17 09:53:04 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 17 Jul 2005 06:53:04 -0700 Subject: beginner question fibonacci In-Reply-To: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> References: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> Message-ID: Joon wrote: > > >>> # Fibonacci series: > ... # the sum of two elements defines the next > ... a, b = 0, 1 > >>> while b < 10: > ... print b > ... a, b = b, a+b > ... > 1 > 1 > 2 > 3 > 5 > 8 > > >>> a, b = 0, 1 > >>> while b < 10: > print b > a = b > b = a+b > > 1 > 2 > 4 > 8 > > Why a, b = b, a+b isn't a = b; b = a+b ? It's actually equivalent to: temp = (b, a+b) a = temp[0] b = temp[1] The temporary tuple object is created first, with the old values of a and b. Then a and b are reassigned. The value of a doesn't change until *after* a+b is calculated. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jabel at plus.net Tue Jul 12 10:19:12 2005 From: jabel at plus.net (John Abel) Date: Tue, 12 Jul 2005 15:19:12 +0100 Subject: Missing Something Simple In-Reply-To: <42D3D0D0.9020604@plus.net> References: <42D3C920.2000808@plus.net> <11f99613a4f2a4c64f8055e060b8e965@upf.edu> <42D3D0D0.9020604@plus.net> Message-ID: <42D3D160.5090407@plus.net> >have been declared before being used in the list. Basically, I'm after >the Python way of using deferencing. > > OK, that should say dereferencing. J From dromasca at avaya.com Tue Jul 19 02:53:53 2005 From: dromasca at avaya.com (Romascanu, Dan (Dan)) Date: Tue, 19 Jul 2005 09:53:53 +0300 Subject: Out of Office AutoReply: Returned mail: Data format error Message-ID: I am out-of-office, on a business trip, untill July 23, 2005, and may be able to read your e-mail only after this date. If you need to contact me urgently, please call the mobile phone number +1-917-957-0270. Regards, Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Sat Jul 9 11:10:37 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 15:10:37 GMT Subject: why UnboundLocalError? References: <1120912006.484157.131500@g44g2000cwa.googlegroups.com> Message-ID: <42cfe72d.213864160@news.oz.net> On 9 Jul 2005 05:26:46 -0700, and-google at doxdesk.com wrote: >Alex Gittens wrote: > >> I'm getting an UnboundLocalError > >> def fieldprint(widths,align,fields): [...] >> def cutbits(): [...] >> fields = fields[widths[i]:] > >There's your problem. You are assigning 'fields' a completely new >value. Python doesn't allow you to rebind a variable from an outer >scope in an inner scope (except for the special case where you >explicitly use the 'global' directive, which is no use for the nested >scopes you are using here). > >So when you assign an identifier in a function Python assumes that you >want that identifier to be a completely new local variable, *not* a >reference to the variable in the outer scope. By writing 'fields= ...' >in cutbits you are telling Python that fields is now a local variable >to cutbits. So when the function is entered, fields is a new variable >with no value yet, and when you first try to read it without writing to >it first you'll get an error. > >What you probably want to do is keep 'fields' pointing to the same >list, but just change the contents of the list. So replace the assign >operation with a slicing one: > > del fields[:widths[i]] Except the OP probably had two errors in that line, and doesn't want to slice out fields from the field list, but rather slice characters from the i-th field, and strings are immutable, so he can't do del fields[i][:widths[i]] # slice deletion illegal if fields[i] is a string and so fields[i] = fields[i][:widths[i]] would be the way to go (see my other post). Regards, Bengt Richter From theller at python.net Wed Jul 6 14:59:05 2005 From: theller at python.net (Thomas Heller) Date: Wed, 06 Jul 2005 20:59:05 +0200 Subject: The GIL, callbacks, and GPFs References: Message-ID: Francois De Serres writes: > Hello, > > I'm chasing a GPF in the interpreter when running my extension module. > It's not very elaborated, but uses a system (threaded) callback, and > therefore the GIL. > Help would be mucho appreciated. Here's the rough picture: > > static void external_callback(const Bag * const bag) { if > (my_callback && (my_callback != Py_None)) { > PyObject * arglist = NULL; > PyObject * result = NULL; > arglist = Py_BuildValue("(s#)", bag->data, bag->size); > /* do it */ > PyGILState_STATE gil = PyGILState_Ensure(); You're calling Py_BuildValue without holding the GIL. Not sure if that's the reason for your problems, but I don't think its ok. > result = PyEval_CallObject(my_callback, arglist); > PyGILState_Release(gil); > Py_DECREF(arglist); > Py_DECREF(result); } > } Thomas From steve at REMOVETHIScyber.com.au Sun Jul 3 10:04:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 00:04:36 +1000 Subject: math.nroot [was Re: A brief question.] References: Message-ID: On Sun, 03 Jul 2005 10:56:42 +0100, Tom Anderson wrote: > On Sun, 3 Jul 2005, Steven D'Aprano wrote: > >> On Sun, 03 Jul 2005 02:22:23 +0200, Fredrik Johansson wrote: >> >>> On 7/3/05, Tom Anderson wrote: >>>> That's one way. I'd do: >>>> >>>> root = value ** 0.5 >>>> >>>> Does that mean we can expect Guido to drop math.sqrt in py3k? :) >>> >>> I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) >>> gives 3.9999999999999996, and this error could be avoided. >> >> py> math.exp(math.log(64)/3.0) >> 4.0 >> >> Success!!! > > Eeeeeeenteresting. I have no idea why this works. Given that math.log is > always going to be approximate for numbers which aren't rational powers of > e (which, since e is transcendental, is all rational numbers, and > therefore all python floats, isn't it?), i'd expect to get the same > roundoff errors here as with exponentiation. Is it just that the errors > are sufficiently smaller that it looks exact? I have no idea :-) Unfortunately, floating point maths is a bit of a black art. Try this simple calculation: py> 4.0/3 - 5.0/6 0.49999999999999989 Should be 0.5 exactly. Many numbers which you can write exactly in decimal cannot be stored exactly in floating point. Even something as simple as one tenth 0.1 doesn't have an exact representation in binary: py> 1.0/10 0.10000000000000001 >> Note how much simpler this would be if we could guarantee proper >> infinities and NaNs in the code. We could turn a 23-line block to a >> one-liner. > > YES! This is something that winds me up no end; as far as i can tell, > there is no clean programmatic way to make an inf or a NaN; in code i > write which cares about such things, i have to start: > > inf = 1e300 ** 1e300 > nan = inf - inf > > Every bloody time. I'm going to be buggered if python ever rolls out some > sort of bigfloat support. It fails for me: py> inf = 1e300 ** 1e300 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') But this works: py> inf = float("inf") py> inf inf > And then god forbid i should actually want to test if a number is NaN, > since, bizarrely, (x == nan) is true for every x; Well dip me in chocolate and call me a Tim Tam, you're right. That is bizarre. No, that's not the word I want... that behaviour is broken. > instead, i have to > write: > > def isnan(x): > return (x == 0.0) and (x == 1.0) > > The IEEE spec actually says that (x == nan) should be *false* for every x, > including nan. I'm not sure if this is more or less stupid than what > python does! Well, no, the IEEE standard is correct. NaNs aren't equal to anything, including themselves, since they aren't numbers. Okay, infinity isn't a number either. But there are rules for arithmetic for infinity, based on limit calculations, so it makes sense to treat infinity as a number where possible. Apple Computer had a maths library that implemented a superset of IEEE arithmetic. It allowed for 254 different NaNs (twice that if you looked at the sign bit, which you weren't supposed to do). This wasn't a deliberate feature as such, it merely fell out naturally from the bit-patterns that represented NaNs, but it was useful since Apple took advantage of it by specifying certain particular NaNs for certain failure modes. Eg NaN(1) might represent the square root of a negative number, but NaN(2) might be INF-INF. Furthermore, you could easily query the class of a number (zero, normalised, denormalised, infinity, NaN), so you would test for a NaN by doing something like: if Kind(x) == NanKind: ... or if isNaN(x): ... > And while i'm ranting, how come these expressions aren't the same: > > 1e300 * 1e300 > 1e300 ** 2 Because this is floating point, not real maths :-) I get inf and Overflow respectively. What do you get? > And finally, does Guido know something about arithmetic that i don't, or > is this expression: > > -1.0 ** 0.5 > > Evaluated wrongly? No, it is evaluated according to the rules of precedence. It is equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which fails as expected. -- Steven. From godwinburby at rediffmail.com Thu Jul 14 00:46:25 2005 From: godwinburby at rediffmail.com (Godwin) Date: 13 Jul 2005 21:46:25 -0700 Subject: Web App like Google In-Reply-To: <1121272270.930838.144340@g14g2000cwa.googlegroups.com> References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> <1121188057.886202.86860@g43g2000cwa.googlegroups.com> <1121272270.930838.144340@g14g2000cwa.googlegroups.com> Message-ID: <1121316385.789726.23780@g44g2000cwa.googlegroups.com> Actually i went through the NLTK site tutorials and it has a steep learning curve associated with it. Well if i can learn it, it will be the best fit module for my app. But if it gets hard, i'll definitely opt for the text indexers u gratefully pointed to me. Thanks. From brusstoc at gmail.com Sat Jul 30 20:35:39 2005 From: brusstoc at gmail.com (brusstoc at gmail.com) Date: 30 Jul 2005 17:35:39 -0700 Subject: Friend wants to learn python References: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> <1122646839.822416.36880@g14g2000cwa.googlegroups.com> Message-ID: <1122770139.114523.121320@g44g2000cwa.googlegroups.com> I would recommend starting with www.freenetpages.co.uk/hp/alan.gauld . He has a particularly good way of communicating the basics of Python. Also available in a book if he needs that. PDF available from the website. www.bookpool.com has a large selection of books on Python. The "Python: How to Program" is a good choice (IMO). (I got the book & CD combo - I could have done without the CD. Basically the same as the book. Wasn't worth the extra price to me.) Awaretek does have a good list of tutorials. FYI, if your friend is really wanting to learn programming, have him/her check out www.htdp.org. Although it is scheme-language based, I think they do a great job teaching real programming principals that can be applied to Python - once you get the language down. From cyril.bazin at gmail.com Tue Jul 12 05:08:12 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Tue, 12 Jul 2005 11:08:12 +0200 Subject: Trying to come to grips with static methods In-Reply-To: References: Message-ID: (sorry, my fingers send the mail by there own ;-) Im my opinion, class method are used to store some functionalities (function) related to a class in the scope of the class. For example, I often use static methods like that: class Point: def __init__(self, x, y): self.x, self.y = x, y def fromXML(xmlText): x, y = functionToParseXMLUsingMinidomForExample(xmlText) return Point(x, y) fromXML = staticmethod(fromXML) Here, it is used to define some kind of second constructor... Note that class decorator can simplify the notation, but break the compatility with older Python... Cyril On 7/12/05, Steven D'Aprano wrote: > > I've been doing a lot of reading about static methods in Python, and I'm > not exactly sure what they are useful for or why they were introduced. > > Here is a typical description of them, this one from Guido: > > "The new descriptor API makes it possible to add static methods and class > methods. Static methods are easy to describe: they behave pretty much like > static methods in C++ or Java." > http://www.python.org/2.2.3/descrintro.html > > Great. So I have learn an entire new language to understand static > methods. Perhaps not -- hence this cry for help. > > As near as I can see it, static methods are object methods that act just > like functions. Er. I always thought that object methods *were* functions, > except they had some runtime magic that passed the object itself as the > first argument. > > >From Guido's example: > > >>> class C: > ... def foo(x, y): > ... print "staticmethod", x, y > ... foo = staticmethod(foo) > ... > >>> C.foo(1, 2) > staticmethod 1 2 > >>> c = C() > >>> c.foo(1, 2) > staticmethod 1 2 > > So I compare with an ordinary class function, er, method: > > >>> class D: > ... def foo(self, x, y): > ... print "method", x, y > ... > >>> D.foo (1, 2) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unbound method foo() must be called with D instance as first > argument (got int instance instead) > > Okay, that is to be expected. Actually, I expected an exception that I > hadn't passed enough arguments (2 arguments when foo expects 3), but in > hindsight it is obvious enough. > > First point of confusion. In the above exception, foo is called an unbound > method. But type(D.foo) returns even though foo is > > being access through the class, not an instance. And type(D().foo) returns > the same. > > Can I assume that in Python "unbound method" is just another way of saying > "a method of a class that expects to be called via an instance"? > > > > I next tried this: > > >>> D.foo(D(), 1, 2) > method 1 2 > >>> D().foo(1, 2) > method 1 2 > > Clear as mud. An ordinary method called from an instance is the same as a > static method called from anywhere, provided you don't -- or rather, can't > > -- try to access self from the static method. > > When would you use a static method instead of an ordinary method? It has > been suggested that you might use it for functions that don't need to > access self. But that doesn't seem very convincing to me, because there is > > already a perfectly good idiom for that: > > >>> class E: > ... def foo(): # returns calculated value > ... return 1 > ... foo = staticmethod(foo) > ... def bar(self): > ... return 1 # just ignore the value of self > ... > >>> E.foo() > 1 > >>> e = E() > >>> e.bar() > 1 > > What are some usage cases for using Class.StaticMethod() instead of > instance.method()? Everything I've read seems to just assume that the > benefits of static methods are so obvious that they don't need explaining. > Unfortunately, I haven't come from a background in OO and I'm easily > confused, hence this post. > > > -- > Steven. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cliff at develix.com Sun Jul 31 19:55:10 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 16:55:10 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7xmzo25zmm.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> <7xvf2rync2.fsf@ruckus.brouhaha.com> <87r7dfymy1.fsf@wilson.rwth-aachen.de> <7xmzo25zmm.fsf@ruckus.brouhaha.com> Message-ID: <1122854110.19618.178.camel@localhost.localdomain> On Sun, 2005-07-31 at 16:23 -0700, Paul Rubin wrote: > Torsten Bronger writes: > > I can't really understand your hostility towards non-Tkinter > > toolkits. In the case of wxPython, it's part of SUSE, which is > > probably also true for Fedora and Mandriva. Installing is as easy > > as selecting a checkbox. This covers a very great deal of Linux > > users. On Windows you have to call an exe file. > > No it's not on Fedora, at least FC3. I had huge trouble trying to > build it and gave up. I had similar problems on RH9. I've been installing it from the RPM's on http://wxpython.org from around Redhat 6.2 up through FC4. I've never had an issue, except in cases where I had screwed my Linux install up to the point of no recovery (and I recall only once this happened, when I had decided to use Ximian desktop around 7.3). Also the Windows and Mac installers there seem to work just fine as well. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From spam.csubich+block at block.subich.spam.com Sat Jul 2 22:28:53 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 02 Jul 2005 22:28:53 -0400 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 01 Jul 2005 12:24:44 -0700, Devan L wrote: > > >>With the exception of reduce(lambda x,y:x*y, sequence), reduce can be >>replaced with sum, and Guido wants to add a product function. > > > How do you replace: > > reduce(lambda x,y: x*y-1/y, sequence) > > with sum? You don't, but an almost equally short replacement works just as well, and doesn't even need the lambda: >>>sequence=range(1,100) >>>_res = 0.0 >>>for x in sequence: _res = _res*x + 1/x >>> >>>_res 9.3326215443944096e+155 Sure, this isn't a sum, but I'd argue that the for loop solution is superior: 1) For single expressions, the guts of the operation is still a single line 2) This completely avoids lambda -- while I myself am ambivalent about the idea of lambda going away, lambda syntax can get hairy for complicated expressions -- the comma changes meaning halfway through the expression, from 'parameter delimiter in lambda' to 'next parameter in reduce' 3) This trivially extends to a block of code, which a lambda doesn't 4) Behavior for zero- and one-length lists is explicit and obvious. There are, of course, a few disadvantages, but I think they're more corner corner cases. 1) This solution obviously isn't itself an expression (although the result is a single variable), so it can't be used in totality as a component to a larger call. [Rebuttal: When exactly would this be a good thing, anyway? Reduce statements are at least 11 characters long, 13 with a one-character default value. Using this as a parameter to just about anything else, even a function call, seems a bit unreadable to me.] 2) An explicit intermediate/result value is needed. This seems to be more of a 'cleanliness' argument than anything. Besides, rewriting this as a for loop actually improves performance: >>> sequence = range(1,100) >>> def f1(): j = 0.0 for x in sequence: j = j*x+1/x return j >>> def f2(): return reduce(lambda x,y: x*y - 1/y, sequence) >>> def runtime(f,n): starttime = time.time() for i in xrange(n): f() print time.time()-starttime >>> runtime(f1,10000) 1.37199997902 >>> runtime(f2,10000) 3.67499995232 Making the series bigger results in even worse relative performance (no idea why): >>> sequence = range(1,1000) >>> runtime(f1,10000) 18.4169998169 >>> runtime(f2,10000) 125.491000175 So really, 'reduce' is already useless for large anonymous blocks of code (which can't be defined in lambdas), and it seems slower than 'for .. in' for even simple expressions. From crespoh at gmail.com Wed Jul 27 23:18:55 2005 From: crespoh at gmail.com (crespoh) Date: 27 Jul 2005 20:18:55 -0700 Subject: retrieve data from 2 database Message-ID: <1122520735.066339.235110@z14g2000cwz.googlegroups.com> Hi, How do I select data from two tables from two different databases and compare them? using dbi,odbc From mailman at hanez.org Sat Jul 16 19:30:46 2005 From: mailman at hanez.org (Johannes Findeisen) Date: Sun, 17 Jul 2005 01:30:46 +0200 Subject: Python vs. Access VBA In-Reply-To: References: Message-ID: <1121556646.5653.43.camel@phantom.wg.xw3.org> On Fri, 2005-07-15 at 23:19 -0400, William Lodge wrote: > I'm at a loss on how to compare Python vs. Access VBA for a database > project. I'm estimating 20 tables and several forms and reports. Some of the > tables could grow to many thousands of rows w/i a year or so. The app would > be resident on my client as no network connectivity is needed b/c I'll be > the only user. I'd probably use Access tables for now and plan on scaling up > to Oracle later if necessary (which it probably won't be). Move to Oracle is no problem at all. With Access you could connect to all RDMS that is providing an ODBC driver. In Python you could connect to all Databases you find a class for. Maybe you should take a look at ADOdb [1]. > If the project is successful, it may be adopted in the division. There is no > time limit but this is being done on my own time, and my guestimate for a > practical limit would be 3-4 months. I'm not a developer but have done > programming in the academic world as part of MSIS degree. I also want the > app to have a GUI. The GUI is set up very fast in Access and in Glade [4]. No difference in the speed. > I'm currently reviewing Wingware's Python product. Will review Komodo next. > It doesn't appear that the Wingware product has a GUI builder, but Komodo's > Pro version does (although more costly). Anybody have any recommendations in > this regard? Any thoughts as to whether implementing in Python would be any > harder or easier to do than in Access? Access is click and go but definitely NO freedom. Access has many features but you cant trust them. I have developed a big Access application some years ago and i will never do that gain. You're maybe faster when using Access but, is faster better? If you have enough knowledge of Python you will be as fast as in Access too. Python delivers nearly all features for _real_ application development and when you're a using some of the very hot classes around the web you could nearly do everything with Python. When you are using Komodo, you're in a environment like Access but since i remember you have an interface for using Python. Maybe you should give it try. I think there is a free version with less feature available. > Finally, does anybody know of any Web sites having examples of database apps > in Python? Well, give TinyERP a try [2]. It is a very clean and nice written Python application using the GTK [3] Toolkit for the GUI. That's what other people are using for rapid application development in UNIX environments. The GUI could easy be created using the Glade interface designer and all codework is Python. You don't have to bother about the GUI in the code and you have a dynamically generated GUI at program execution. This makes it easy to change the GUI layout without touching the code. Signal handling is also implemented and very easy to use. Glade and GTK+ are available for Windows operating systems too. Some Links: 1. http://adodb.sourceforge.net/ 2. http://tinyerp.org/ 3. http://pygtk.org/ 4. http://glade.gnome.org/ My recommendation: Use Python! You will love me in some years because i have said this. When using Access you are binding your application to Microsoft. You need a runtime version of Access when distributing the application to others. When using Python you could build an install CD for more the windows and you didn't have to bother about proprietary licensing issues. Good Luck with your decision... ;-) Regards, -- Johannes Findeisen http://hanez.org/ From Scott.Daniels at Acm.Org Sun Jul 3 11:39:24 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 03 Jul 2005 08:39:24 -0700 Subject: Tkinter Checkbutton initialization problem In-Reply-To: <7xzmt4fd5m.fsf@ruckus.brouhaha.com> References: <7xzmt4fd5m.fsf@ruckus.brouhaha.com> Message-ID: <42c7fefc$1@nntp0.pdx.net> Paul Rubin wrote: > Python 2.4, Windows XP. If I say: > f = Frame() > f.grid() > v = IntVar() v.set(1) # Might help. v.get() at this point returned 0 for me. > c = Checkbutton(f, text='hi there', variable=v) > c.grid() > f.mainloop() From desertgarden at netscape.com Sat Jul 9 11:52:03 2005 From: desertgarden at netscape.com (Brian) Date: Sat, 09 Jul 2005 15:52:03 GMT Subject: Defending Python In-Reply-To: <1120920801.730115.9410@g43g2000cwa.googlegroups.com> References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > So, I would recommend Python to these > folks as an easily acquired extra skill. I agree 100% with your statement above. Python may not be sufficient for being the only programming language that one needs to know -- yet, it does come in VERY handy for projects that need to perform tasks on non-Microsoft operating systems. :-) Brian --- From MrJean1 at gmail.com Tue Jul 26 11:53:22 2005 From: MrJean1 at gmail.com (MrJean1) Date: 26 Jul 2005 08:53:22 -0700 Subject: Counting processors In-Reply-To: <1122389455.371659.229710@o13g2000cwo.googlegroups.com> References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> <1122389455.371659.229710@o13g2000cwo.googlegroups.com> Message-ID: <1122393202.465393.178950@g14g2000cwa.googlegroups.com> Or maybe os.sysconf('SC_NPROCESSORS_ONLN') Usually, the value returned by os.sysconf('SC_NPROCESSORS_ONLN') and os.sysconf('SC_NPROCESSORS_CONF') are the same, but if they do differ, os.sysconf('SC_NPROCESSORS_ONLN') is the reliably figure. /Jean Brouwers PS) This applies to Linux and Solaris, at least. k pur wrote: > You can use > > print os.sysconf("SC_NPROCESSORS_CONF") > > works on Linux > > > krishan > > > Pauldoo wrote: > > Hi, > > Is a way in python to obtain the total number of processors present in > > the system? > > > > os.platform doesn't seem to contain anything useful. From nephish at xit.net Mon Jul 25 16:14:38 2005 From: nephish at xit.net (nephish at xit.net) Date: 25 Jul 2005 13:14:38 -0700 Subject: how to write a line in a text file In-Reply-To: <1122321475.234274.180140@g47g2000cwa.googlegroups.com> References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> <1122321475.234274.180140@g47g2000cwa.googlegroups.com> Message-ID: <1122322478.219094.162570@f14g2000cwb.googlegroups.com> Gee whiz, so easy. thanks. Never thought about just changing it while it was read then re-writing it. that will be just fine. these files are only 9 lines long. thanks again ! From db3l at fitlinxx.com Tue Jul 5 18:16:08 2005 From: db3l at fitlinxx.com (David Bolen) Date: 05 Jul 2005 18:16:08 -0400 Subject: No subject References: Message-ID: roy at panix.com (Roy Smith) writes: (...) > We've got code coveage tools. This is a testing tool. You keep > running tests and it keeps track of which lines of code are executed > (i.e. which logic branches are taken). One theory of testing says you > should keep writing test cases until you've exercised every branch. I > don't see any reason such a tool wouldn't be useful in a big Python > project, but I'm not aware of any. The coverage.py module (http://www.garethrees.org/2001/12/04/python-coverage) has worked pretty well for us. Just run your unit test suite under its control. There's also http://www.softwareverify.com/pythonCoverageValidator which is commercial. -- David From roy at panix.com Mon Jul 4 10:13:33 2005 From: roy at panix.com (Roy Smith) Date: Mon, 04 Jul 2005 10:13:33 -0400 Subject: Determining actual elapsed (wall-clock) time References: Message-ID: Peter Hansen wrote: > As it turns out, Windows XP already has support (via NTP > I presume, though of course since this is Microsoft they try to keep the > user base ignorant by making no mention of that even in the help page) > for keeping the clock accurate, right on the last tab (labelled > "Internet Time") of the Date and Time Properties dialog. Sigh. Unfortunately, it's not just MS. Apple does the same thing. In the Date & Time control panel, there's an option to "Set Date & Time Automatically". What it's doing is turning on NTP, but it doesn't say that (even in the help text). In this case, it was pretty easy to guess (and verify with tcpdump), but sometimes it's really infuriating when software providers eschew the use of technical terms for "easy to understand plain english" to the point of making it impossible to figure out what's really going on. From oddr at home.no.no Fri Jul 22 08:42:04 2005 From: oddr at home.no.no (Odd-R.) Date: 22 Jul 2005 12:42:04 GMT Subject: find a specified dictionary in a list References: <42e0dc25$1@news.eftel.com> Message-ID: On 2005-07-22, John Machin wrote: > Odd-R. wrote: >> I have this list: >> >> [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] >> >> All the dictionaries of this list are of the same form, and all the oids >> are distinct. If I have an oid and the list, how is the simplest way of >> getting the dictionary that holds this oid? >> > > Something like this: > > def oidfinder(an_oid, the_list): > for d in the_list: > if d['oid'] == an_oid: > return d > return None > # These are not the oids you are looking for. Thank you for your help, but I was hoping for an even simpler solution, as I am suppose to use it in a ", line 1, in ? > NameError: name 'x' is not defined Because the right hand side ('[1,2,x]') is evaluated *before* the value is bound to the name 'x' - and at this point there is obviously no name 'x' defined. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From ric at next-level.com.au Mon Jul 4 23:22:38 2005 From: ric at next-level.com.au (Ric Da Force) Date: Tue, 5 Jul 2005 11:22:38 +0800 Subject: What are __slots__ used for? Message-ID: I am a C# programmer and new to the language and I am trying to debug some code which uses this feature. Can anyone elaborate on what it is and how it is used? Regards, Ric From phm4 at kent.ac.uk Sun Jul 10 06:19:31 2005 From: phm4 at kent.ac.uk (Philipp H. Mohr) Date: Sun, 10 Jul 2005 11:19:31 +0100 (BST) Subject: passing arguments to a function - do I need type ? In-Reply-To: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: Hello, I got a newbie question, I have written the following distance function: def distance(self,element1, element2): dist = 0 for n in range(len(element1)): dist = dist + pow((element1[n] - element2[n]),2) print 'dist' + dist return sqrt(dist) and in order to be able to use len() and index element1[] the function needs to know that the arguments element1 and element2 are both listst or doesn't it ? I get the following error msg: Traceback (most recent call last): File "Memory.py", line 105, in ? start.inputVector(inP2) File "Memory.py", line 97, in inputVector allDimensions[0].newAttribute(vector) File "Memory.py", line 56, in newAttribute dist = self.distance(n.getCenter,newElement) File "Memory.py", line 75, in distance for n in range(len(element1)): TypeError: len() of unsized object AND if I take len out I get: Traceback (most recent call last): File "Memory.py", line 105, in ? start.inputVector(inP2) File "Memory.py", line 97, in inputVector allDimensions[0].newAttribute(vector) File "Memory.py", line 56, in newAttribute dist = self.distance(n.getCenter,newElement) File "Memory.py", line 76, in distance dist = dist + pow((element1[n] - element2[n]),2) TypeError: unsubscriptable object Thank you very much for your help. Phil From andreas at kostyrka.org Wed Jul 13 03:36:19 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 09:36:19 +0200 Subject: threads and sleep? In-Reply-To: <6829832e050704123645e4547e@mail.gmail.com> References: <6829832e050704123645e4547e@mail.gmail.com> Message-ID: <1121240179.5240.37.camel@andi-lap> Am Montag, den 04.07.2005, 15:36 -0400 schrieb Jeffrey Maitland: > Hello all, > Ok, first thing to consider is that time.sleep in Python does in reality (on Debian Linux, Python2.3) a select syscall with 3 NULLs to wait the time. (The "real" sleep POSIX call might have stupid interactions with signals, to be specific SIGALRM) Don't have a Python source at the moment (I'm offline at the moment) to check how it's done in Win32. > I am in the process of writing a multithreading program and what I was > wondering is a sleep command in an executing function will affect the > threads below it? Here is a basic example of what I mean. > > def main(): > temp_var = True > while temp_var == True: > if > t = threading.Thread( target = func1, args = "String") #note > this is probably non functional (example purposes for the question > only) > t.start() > temp_var = t.isAlive() > else: > print "This line should display a lot" > sleep(2) > > def func1(s): > print s > > so the question I was wondering is if the sleep will pause the t > thread as well as the main function or is the thread independat of the > main function sleep? Well, your program seems to be non-functional (missing if expression?), but as I said above, the main thread waits via select, so the child process should be able to run in this time (assuming time.sleep releases the GIL, but I'd file it as a bug if it doesn't). Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From fperez.net at gmail.com Fri Jul 8 12:02:25 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 08 Jul 2005 10:02:25 -0600 Subject: PyX, matplotlib, 3D & LaTeX References: <1120813229.543202.310640@o13g2000cwo.googlegroups.com> Message-ID: Francisco Borges wrote: > I like PyX, use it a lot and would suggest it as a beter plotting > library than the ones at Scipy (for as long as you don't need on-screen > plotting). FWIW, the plotting support in scipy is essentially unmaintained and abandoned, since the advent of matplotlib. It hasn't been officially deprecated, though I'm wondering if perhaps we should do that just to save users the aggravation. > I just saw matplotlib this week while searching for something that > would do 3D, it seemed pretty nice and it does have many more features > than PyX, is certainly more mature than PyX and more high level. I use both extensively, so I can comment a bit: matplotlib is a fantastic _plotting_ library, and it has very extensive support for doing all kinds of plotting-related things easily and with high output quality. As of v. 0.82, its latex support is on-par with Pyx's, since now you can set it to do _all_ your text rendering (including ticks, numbers, etc.) via latex. It gets a bit slower (much like pyx), but the quality is perfect (it's true latex running underneath). Besides, matplotlib provides widgets for on-screen rendering and embedding into GUI applications, something which can be very important, and outside pyx's domain of interest. Where pyx shines is for generating what I call 'diagrams' for lack of a better term: drawings that don't fall well into the model of 'plot these data points at these coordinates' but that rather involve algorithmically-driven positioning of geometric elements. This power is best seen (despite my poor description) by just looking at the pyx examples page, which shows how even relatively complex diagrams can be done in pyx with very little code, and give stunning results. While you can plot with pyx, and draw with matplotlib, I feel that they each have their strengths, and I use both. I love both, and I feel they complement each other extremely well. For 3d plotting in python, VTK and mayavi are my workhorses, and I'm quite happy with that solution so far. > On the other hand PyX: LaTeX support seems to be way ahead and it can > be used to draw (very funky) figures. [have a look at recent matplotlib for proper latex] Cheers, f From thomas at thomas-lotze.de Fri Jul 15 12:01:06 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Fri, 15 Jul 2005 18:01:06 +0200 Subject: Python Programming Contest References: Message-ID: Brian Quinlan wrote: > I've decided that it would be be fun to host a weekly Python programming > contest. I like the idea, and doing the first problem was fun indeed :o) > I'm always looking for feedback, so let me know what you think or if you > have any ideas for future problems. It would be nice if you could put up a suite of test data with oracle solutions for download. For those sitting behind a modem line (like me), it would be a great help and speed up of the testing cycle. Thanks for your effort, in any case! -- Thomas From rrr at ronadam.com Sat Jul 30 18:35:25 2005 From: rrr at ronadam.com (Ron Adam) Date: Sat, 30 Jul 2005 22:35:25 GMT Subject: PEP on path module for standard library In-Reply-To: <42e29d5c.963163926@news.oz.net> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <42e15f81$1@news.eftel.com> <42e29d5c.963163926@news.oz.net> Message-ID: Bengt Richter wrote: > > > Say, how about > > if Pathobject('gui://message_box/yn/continue processing?').open().read().lower()!='y': > raise SystemExit, "Ok, really not continuing ;-)" > > An appropriate registered subclass for the given platform, returned when the > Pathobject base class instantiates and looks at the first element on open() and delegates > would make that possible, and spelled platform-independently as in the code above. I like it. ;-) No reason why a path can't be associated to any tree based object. > > > Regards, > Bengt Richter I wasn't sure what to comment on, but it does point out some interesting possibilities I think. A path could be associated to any file-like object in an external (or internal) tree structure. I don't see any reason why not. In the case of an internal file-like object, it could be a series of keys in nested dictionaries. Why not use a path as a dictionary interface? So it sort of raises the question of how tightly a path object should be associated to a data structure? When and where should the path object determine what the final path form should be? And how smart should it be as a potential file-like object? Currently the device name is considered part of the path, but if instead you treat the device as an object, it could open up more options. (Which would extend the pattern of your example above. I think.) (also a sketch.. so something like...) # Initiate a device path object. apath = device('C:').path(initial_path) # Use it to get and put data afile = apath.open(mode,position,units) # defaults ('r','line',next) aline = afile.read().next() # read next unit, or as an iterator. afile.write(line) afile.close() # Manually manipulate the path apath.append('something') # add to end of path apath.remove() # remove end of path alist = apath.split() # convert to a list apath.join(alist) # convert list to a path astring = str(apath()) # get string from path apath('astring') # set path to string apath.validate() # make sure it's valid # Iterate and navigate the path apath.next() # iterate path objects apath.next(search_string) # iterate with search string apath.previous() # go back apath.enter() # enter directory apath.exit() # exit directory # Close it when done. apath.close() etc... With this you can iterate a file system as well as it's files. ;-) (Add more or less methods as needed of course.) apath = device(dev_obj).path(some_path_sting) apath.open().write(data).close() or if you like... device(dev_obj).append(path_sting).open().write(data).close() Just a few thoughts, Cheers, Ron From thomas at thomas-lotze.de Tue Jul 12 17:00:22 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 12 Jul 2005 23:00:22 +0200 Subject: Frankenstring References: <1121199858.674056.78250@g14g2000cwa.googlegroups.com> Message-ID: jay graves wrote: > see StringIO or cStringIO in the standard library. Just as with files, iterating over them returns whole lines, which is unfortunately not what I want. -- Thomas From gsakkis at rutgers.edu Sat Jul 9 04:00:07 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Jul 2005 01:00:07 -0700 Subject: Python Module Exposure References: Message-ID: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> Jacob Page wrote: > Thomas Lotze wrote: > > Jacob Page wrote: > > > >>better-named, > > > > Just a quick remark, without even having looked at it yet: the name is not > > really descriptive and runs a chance of misleading people. The example I'm > > thinking of is using zope.interface in the same project: it's customary to > > name interfaces ISomething. > > I've thought of IntervalSet (which is a very long name), IntSet (might > be mistaken for integers), ItvlSet (doesn't roll off the fingers), > ConSet, and many others. Perhaps IntervalSet is the best choice out of > these. I'd love any suggestions. Hi Jacob, I liked a lot the idea of interval sets; I wonder why no one has thought of it before (hell, why *I* haven't thought about it before ? :)) I haven't had a chance to look into the internals, so my remarks now are only API-related and stylistic: 1. As already noted, ISet is not really descriptive of what the class does. How about RangeSet ? It's not that long and I find it pretty descriptive. In this case, it would be a good idea to change Interval to Range to make the association easier. 2. The module's "helper functions" -- which are usually called factory functions/methods because they are essentially alternative constructors of ISets -- would perhaps better be defined as classmethods of ISet; that's a common way to define instance factories in python. Except for 'eq' and 'ne', the rest define an ISet of a single Interval, so they would rather be classmethods of Interval. Also the function names could take some improvement; at the very least they should not be 2-letter abbreviations. Finally I would omit 'eq', an "interval" of a single value; single values can be given in ISet's constructor anyway. Here's a different layout: class Range(object): # Interval @classmethod def lowerThan(cls, value, closed=False): # lt, for closed==False # le, for closed==True return cls(None, False, value, closed) @classmethod def greaterThan(cls, value, closed=False): # gt, for closed==False # ge, for closed==True return cls(value, closed, None, False) @classmethod def between(cls, min, max, closed=False): # exInterval, for closed==False # incInterval, for closed==True return cls(min, closed, max, closed) class RangeSet(object): # ISet @classmethod def allExcept(cls, value): # ne return cls(Range.lowerThan(value), Range.greaterThan(value)) 3. Having more than one names for the same thing is good to be avoided in general. So keep either "none" or "empty" (preferably "empty" to avoid confusion with None) and remove ISet.__add__ since it is synonym to ISet.__or__. 4. Intervals shouldn't be comparable; the way __cmp__ works is arbitrary and not obvious. 5. Interval.adjacentTo() could take an optional argument to control whether an endpoint is allowed to be in both ranges or not (e.g. whether (1,3], [3, 7] are adjacent or not). 6. Possible ideas in your TODO list: - Implement the whole interface of sets for ISet's so that a client can use either or them transparently. - Add an ISet.remove() for removing elements, Intervals, ISets as complementary to ISet.append(). - More generally, think about mutable vs immutable Intervals and ISets. The sets module in the standard library will give you a good idea of the relevant design and implementation issues. After I look into the module's internals, I'll try to make some changes and send it back to you for feedback. Regards, George From newsgroups at jhrothjr.com Mon Jul 18 08:55:38 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 18 Jul 2005 06:55:38 -0600 Subject: goto References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: <11dn9mkgaae8q7e@news.supernews.com> "Mage" wrote in message news:mailman.1854.1121688300.10512.python-list at python.org... > Hayri ERDENER wrote: > >>hi, >>what is the equivalent of C languages' goto statement in python? >>best regards >> >> > You really shouldn't use goto. True. > Fortunately you can't. Of course you can. Recent versions of Python have the ability to change where an element on the call stack will return to. Don't ask me to debug such a program unless you really want my unvarnished opinion of such stupidity. John Roth > > Mage > From benji at benjiyork.com Thu Jul 7 09:58:10 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 07 Jul 2005 09:58:10 -0400 Subject: ANN: python-constraint 1.0 In-Reply-To: <20050707064010.GA7979@burma.localdomain> References: <20050707064010.GA7979@burma.localdomain> Message-ID: <42CD34F2.9020304@benjiyork.com> Gustavo Niemeyer wrote: > **python-constraint** [1]_ is a Python module offering solvers for > Constraint Solving Problems (CSPs) over finite domains in simple > and pure Python. Very cool! I can't wait to get some time to play with this. -- Benji York From rtw at freenet.co.uk Wed Jul 20 17:08:01 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Wed, 20 Jul 2005 16:08:01 -0500 Subject: What does "::" mean? References: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Message-ID: Robert Kern wrote in news:mailman.1954.1121875043.10512.python- list at python.org in comp.lang.python: > qwweeeit at yahoo.it wrote: >> Hi Robert, >> I didn't succeed in reversing a string with the "full form" you >> proposed: >> live[len(live)-1:-1:-1] # where live="live" >> The result is an empty string. >> To reverse "live" (in a "full form"), I have to put a char in front of >> the string and...: >> ('x'+live)[len(live)+1:0:-1] # --> "evil" >> Is it due to the Python's version (I still have 2.3.4)? > > No, it's because I am stupid. There isn't a full form. > live[len(live)::-1] is the closest expansion. > import sys live = 'live' print live[ sys.maxint : : -1 ] print live[ len(live)-1 : : -1 ] print live[ len(live)-1 : -len(live)-1 : -1 ] print live[ len(live)-1 : -sys.maxint : -1 ] print live[ sys.maxint : -sys.maxint : -1 ] print live[ -1 : -len(live)-1 : -1 ] Of course there is only one obvious way to do it, but alas as I'm not Dutch I can't tell which it is. Rob. -- http://www.victim-prime.dsl.pipex.com/ From paolo_veronelli at tiscali.it Sun Jul 31 15:40:14 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sun, 31 Jul 2005 21:40:14 +0200 Subject: namespaces In-Reply-To: <1122826472.004836.273980@g43g2000cwa.googlegroups.com> References: <42EC9690.2040301@tiscali.it> <1122826472.004836.273980@g43g2000cwa.googlegroups.com> Message-ID: <42ED291E.6000505@tiscali.it> George Sakkis wrote: > Then write a closure. You get both encapsulation and efficience, and as > a bonus, customization of the translating function: > > import string > > def translateFactory(validChars=string.letters+string.digits, > replaceChar='_'): > all=string.maketrans('','') > badcars=all.translate(all,validChars) > table=string.maketrans(badcars, replaceChar*len(badcars)) > def translate(text): > return text.translate(table) > # bind any attributes you want to be accessible > # translate.badcars = badcars > # ... > return translate > > > tr = translateFactory() > tr("Hel\xfflo") This is clean,but I suppose it would get cumbersome if I want to have more functions in the namespace/factory and it implies all that bindings in the end. The second point also shows my perplexities about functions namespace: def function(): function.foo='something' a=function.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'foo' How should I read it? The namespace is half done inside the function? Thanks Paolino ___________________________________ Yahoo! Messenger: chiamate gratuite in tutto il mondo http://it.beta.messenger.yahoo.com From c at cdot.de Sat Jul 30 16:02:49 2005 From: c at cdot.de (Chris) Date: Sat, 30 Jul 2005 22:02:49 +0200 Subject: showing help(M) when running module M standalone In-Reply-To: References: Message-ID: Dan Sommers wrote: > On Sat, 30 Jul 2005 17:04:50 +0200, > Chris wrote: > > >>hello, >>I have a small module which only contains some utility functions. when >>running this standalone I would like to show the module docs and each >>function docs, as if doing > > >> import M >> help(M) > > >>I came up with the following but I reckon there is a much simpler way? > > >>if __name__ == '__main__': >> print __doc__ >> print "\nFUNCTIONS:\n" >> for x in __all__: >> print x >> exec "print " + x + ".__doc__" > > >>Works but does not seem right using exec for such a task. > > > So don't use exec. > > >>any hint would be great! > > > for x in __all__: > print x.__doc__ I tried that, problem is that __all__ containts strings... > > HTH, > Dan > From skip at pobox.com Fri Jul 8 13:13:14 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 8 Jul 2005 12:13:14 -0500 Subject: Snakespell In-Reply-To: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> References: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> Message-ID: <17102.46122.333090.245061@montanaro.dyndns.org> peter> I used to use Snakespell from scriptfoundry to do spellchecking peter> on my website (www.peterbe.com/search?q=pyton) but now that I've peter> moved server and wiped the old machine I forgot to take with me peter> the Snakespell code. peter> www.scriptfoundry.com where it used to live seems to have expired. peter> Does anybody know where I can get hold of this? (or even send a peter> tgz to me) Try the Wayback Machine: http://www.archive.org/ Skip From mwm at mired.org Fri Jul 1 11:17:31 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 11:17:31 -0400 Subject: LOC in Python and C++ in large projects References: Message-ID: <86br5m7dys.fsf@bhuda.mired.org> "Adriaan Renting" writes: > I think the choice of a programming language is not very important in > determining the overal succes of a project. C++ and Python are however > my two favorite languages. Well, getting done on time is a crucial part of success, and it takes less time to write fewer LOC. So choice of language can be very important. For an excellent essay on this, see . http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From roccomoretti at hotpop.com Thu Jul 14 16:19:08 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 14 Jul 2005 15:19:08 -0500 Subject: all possible combinations In-Reply-To: References: Message-ID: rbt wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: When I have occasion to do an iteration of iterations, I either use recursion (already posted) or use an accumulator type loop: items = ['a','b','c'] accume = [[],] for pos in range(4): old_accume, accume = accume, [] for comb in old_accume: for item in items: accume.append(comb + [item]) accume = [''.join(x) for x in accume] print accume ['aaaa', 'aaab', 'aaac', 'aaba', 'aabb', 'aabc', 'aaca', 'aacb', 'aacc', 'abaa', 'abab', 'abac', 'abba', 'abbb', 'abbc', 'abca', 'abcb', 'abcc', 'acaa', 'acab', 'acac', 'acba', 'acbb', 'acbc', 'acca', 'accb', 'accc', 'baaa', 'baab', 'baac', 'baba', 'babb', 'babc', 'baca', 'bacb', 'bacc', 'bbaa', 'bbab', 'bbac', 'bbba', 'bbbb', 'bbbc', 'bbca', 'bbcb', 'bbcc', 'bcaa', 'bcab', 'bcac', 'bcba', 'bcbb', 'bcbc', 'bcca', 'bccb', 'bccc', 'caaa', 'caab', 'caac', 'caba', 'cabb', 'cabc', 'caca', 'cacb', 'cacc', 'cbaa', 'cbab', 'cbac', 'cbba', 'cbbb', 'cbbc', 'cbca', 'cbcb', 'cbcc', 'ccaa', 'ccab', 'ccac', 'ccba', 'ccbb', 'ccbc', 'ccca', 'cccb', 'cccc'] Optimize as you see fit. From peter at engcorp.com Sat Jul 16 19:01:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Jul 2005 19:01:50 -0400 Subject: Filtering out non-readable characters In-Reply-To: <1121554550.a71667b7fa93beed82764d3bd61318e3@teranews> References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> <1121554550.a71667b7fa93beed82764d3bd61318e3@teranews> Message-ID: George Sakkis wrote: > "Bengt Richter" wrote: >> >>> identity = ''.join([chr(i) for i in xrange(256)]) > > Or equivalently: >>>>identity = string.maketrans('','') Wow! That's handy, not to mention undocumented. (At least in the string module docs.) Where did you learn that, George? -Peter From edvard+news at majakari.net Wed Jul 13 04:22:37 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 13 Jul 2005 11:22:37 +0300 Subject: Should I use "if" or "try" (as a matter of speed)? References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> <11d0e158o1g8554@news.supernews.com> <18fearebf2js6$.9oemdgamm06p.dlg@40tude.net> <871x64ifl0.fsf@titan.staselog.com> Message-ID: <87y88bdsj6.fsf@titan.staselog.com> Steven D'Aprano writes: > My opinion is, no, you don't need to be a C programmer, or an assembly > programmer, or a hardware level physicist who understands NAND gates, but > it is very useful to have some understanding of what is going on at the > low-level implementation. Yes, I fully agree: in the example presented, it is sufficient to understand that string concatenation is (relatively) expensive. Yet I'd emphasize that most often speed is improved by better algorithms, not by low-level optimisations and language-specific features (if speed is even an issue, that is). > The way I see it, programmers need to be somewhat aware of the eventual > optimization stage in their program, so as to avoid poor design choices > from the start. But you can't always recognise poor design up front, so > even more important is careful encapsulation and design, so you > can make significant implementation changes without needing to throw away > your work. (Well, that's the theory.) So true, extra emphasis on encapsulation and independence. Even seasoned professionals fail to create dazzling products at version 1.0. Good component design is crucial because you eventually want to do major rewrites later. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From zanesdad at bellsouth.net Fri Jul 8 14:57:17 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 08 Jul 2005 14:57:17 -0400 Subject: file handling in a server (.py) file using xmlrpc In-Reply-To: References: Message-ID: <42CECC8D.7070506@bellsouth.net> uwb wrote: >Jeremy Jones wrote: > > > >>uwb wrote: >> >> >> >>>I've got a call to glob in a .py file sitting in an apache cgi-bin >>>directory which refuses to work while the exact same code works from a >>>python console session. >>> >>>I'm guessing that in order to read or write files from any sort of a >>>script file sitting in the cgi-bin directory on a server, something has to >>>be set >>>to allow such activity. I'd appreciate it if anybody with as clue as to >>>what that was could tell me about it. >>> >>> >>> >>> >>> >>> >>> >>So, what do you mean "refuses to work"? Is the cgi script not executing >>at all? Spitting out an error? If so, what error? (And is it an error >>to the browser calling the cgi script, or in your apache logs?) >> >>Jeremy Jones >> >> > > >The script executes, no error messages, but the glob call turns up nothing >while the identical call running from a console does in fact turn up files >names as expected. > > Wild guess, but I'm thinking your webserver process doesn't have permissions to look in your directory. Following is alternating root shell and IPython shell: root at qiwi:~ # chmod 777 /bam root at qiwi:~ # ls -ld /bam drwxrwxrwx 2 root root 96 Jul 8 14:53 /bam In [4]: glob.glob("/bam/*txt") Out[4]: ['/bam/foo.txt', '/bam/bar.txt'] root at qiwi:~ # chmod 000 /bam root at qiwi:~ # ls -ld /bam d--------- 2 root root 96 Jul 8 14:53 /bam In [5]: glob.glob("/bam/*txt") Out[5]: [] HTH, Jeremy Jones From eucci.group at gmail.com Mon Jul 18 15:21:37 2005 From: eucci.group at gmail.com (Jeff Shell) Date: 18 Jul 2005 12:21:37 -0700 Subject: What is your favorite Python web framework? In-Reply-To: References: Message-ID: <1121714497.162978.50480@g49g2000cwa.googlegroups.com> Zope 3, far and away. There's great documentation, quite a few load handling options (different types of caching and ZEO to distribute ZODB caches to multiple machines). Zope 3 aggressively favors small cooperating objects (Zope 2 was inheritance heavy, making customization, extension, etc, a big chore). There are two books in print already and it's quite mature already. Don't discard Zope 3 becaue of what you've heard about Zope 2. Zope 3 is a very different animal. From thanos at sians.org Sat Jul 23 06:12:25 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sat, 23 Jul 2005 13:12:25 +0300 Subject: Getting a dictionary from an object In-Reply-To: <42e20737$0$21113$626a14ce@news.free.fr> References: <42e20737$0$21113$626a14ce@news.free.fr> Message-ID: <20050723101225.GB1756@zermelo.sians.org> On Sat, Jul 23, 2005 at 11:30:19AM +0200, Bruno Desthuilliers wrote: > Thanos Tsouanas a ?crit : > > class dictobj(dict): > > """ > > class dictobj(dict): > > A dictionary d with an object attached to it, > > which treats d['foo'] as d.obj.foo. > > """ > > def __init__(self, obj): > > self.obj = obj > > def __getitem__(self, key): > > return self.obj.__getattribute__(key) > > I'd replace this last line with: > return getattr(self.obj, key) > > Now given your specs, I don't see what's wrong with your solution. I just dont want to use my class, if one already exists in the libraries (or any other way to achieve the same thing), that's all ;) Thanks for the tip. -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From thanos at sians.org Sun Jul 24 05:53:41 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 12:53:41 +0300 Subject: How to run python script in background after i logout In-Reply-To: <20050724095117.GA8785@zermelo.sians.org> References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> <20050724095117.GA8785@zermelo.sians.org> Message-ID: <20050724095341.GB8785@zermelo.sians.org> On Sun, Jul 24, 2005 at 12:51:17PM +0300, Thanos Tsouanas wrote: > On Sun, Jul 24, 2005 at 02:43:44AM -0700, Harlin Seritt wrote: > > I have a remote linux server where I can only access it via ssh. I have > > a script that I need to have run all the time. I run like so: > > > > python script.py & > > > > It runs fine. When I log off ssh I notice that the script died when I > > logged off. How do I make sure it stays running? > > > > thanks, > > This hasn't got to do with python. > > It's a unix/linux question. > > Check at(1): > man at Since you want it to run all the time, check cron(8) as well. Maybe you would like to write a small script, executing script.py if it is not already running. -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From peter at engcorp.com Wed Jul 6 08:57:15 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Jul 2005 08:57:15 -0400 Subject: threads and sleep? In-Reply-To: <11clc1v4el6no7d@corp.supernews.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <11clc1v4el6no7d@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-07-05, Grant Edwards wrote: >>Or is the Python interpreter actually doing the context >>switches itself? > > Upon further thought, that just can't be the case. There has > to be multiple instances of the intepreter because the > interpreter can make C system calls that block (thus blocking > that instance of the interpreter). Other Python threads within > the program continue to run, so there must be multiple Python > intepreters. Maybe you should consider and explain what you mean by "multiple interpreters"? As I understand the concept, and based on my several years' old reading of the virtual machine code, I wouldn't say there are multiple interpreters. There's a reason the GIL is the *global* interpreter lock... -Peter From guettli at thomas-guettler.de Tue Jul 12 09:51:37 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 12 Jul 2005 15:51:37 +0200 Subject: append one file to another References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Message-ID: Am Tue, 12 Jul 2005 06:47:50 -0700 schrieb b83503104 at yahoo.com: > Hi, > > I want to append one (huge) file to another (huge) file. The current > way I'm doing it is to do something like: > > infile = open (infilename, 'r') > filestr = infile.read() > outfile = open(outfilename, 'a') > outfile.write(filestr) > > I wonder if there is a more efficient way doing this? > Thanks. I guess (don't know), that this is faster: for line in infile: outfile.write(line) At least if this a file with "lines". If it is a binary file, you could read N bytes at once: infile.read(N) Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From fuzzyman at gmail.com Mon Jul 4 08:51:23 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jul 2005 05:51:23 -0700 Subject: Unicode drives me crazy... In-Reply-To: References: Message-ID: <1120481483.294387.85200@o13g2000cwo.googlegroups.com> At some point you have to convert - esp. when writing data out to file. If you receive data as a byte string and have to store it as a byte string, it is sometimes convenient to *not* convert in the middle. Best Regards, Fuzzy http://www.voidspace.org.uk/python From wccppp at gmail.com Mon Jul 4 03:34:00 2005 From: wccppp at gmail.com (wcc) Date: 4 Jul 2005 00:34:00 -0700 Subject: how to retrive highlighted text in a browser? References: <1120379718.126989.223300@g14g2000cwa.googlegroups.com> Message-ID: <1120462440.613474.233630@o13g2000cwo.googlegroups.com> Thanks for reply. I did not expect it to be a browser specific problem. I've been using a freeware dictionary tool called wordweb (it is a great tool) and it can detect highlighted text in browsers or text editors, etc.. I'll keep searching. Thanks again. - wcc From max at alcyone.com Fri Jul 1 16:24:00 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Jul 2005 13:24:00 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <7IWdnYp9K8f9O1jfRVn-3w@speakeasy.net> Tom Anderson wrote: > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? I'm familiar with several function languages but haven't used them extensively; I was primarily a C++ programmer before I found Python. I definitely use lambda, map, filter, and reduce, and will miss them when they're gone. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Heaven ne'er helps the man who will not act. -- Sophocles From cliff at develix.com Sun Jul 31 14:35:34 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 11:35:34 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7xy87nw75w.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> <7xhdebv1t0.fsf@ruckus.brouhaha.com> <87vf2rpc0i.fsf@wilson.rwth-aachen.de> <7xy87nw75w.fsf@ruckus.brouhaha.com> Message-ID: <1122834934.19618.60.camel@localhost.localdomain> On Sun, 2005-07-31 at 04:23 -0700, Paul Rubin wrote: > Torsten Bronger writes: > > >> Does py2exe work for all GUI libraries? > > > No, it's Windows-only. > > However, OS'es and GUI libraries are different axes in the space of > > possibilities. > > I'm not sure what you mean. Whatever GUI library the Mac uses, py2exe > doesn't work with it, since py2exe doesn't work for Macs. py2app is the py2exe equivalent for OS/X. And it works fine with wxPython as well. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From peter at engcorp.com Fri Jul 1 12:01:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 12:01:43 -0400 Subject: Assigning to None (was Re: Question about Python) In-Reply-To: <867jga7dcm.fsf@bhuda.mired.org> References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Yes. I once grabbed an old program that did assignments to None. But > that's always been a bad idea. What was the use case!? -Peter From skilpat at gmail.com Wed Jul 13 18:34:02 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 13 Jul 2005 15:34:02 -0700 Subject: timeoutsocket.py mirror? References: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> Message-ID: <1121294042.044790.180570@g49g2000cwa.googlegroups.com> Unfortunately I am stuck with Python 2.2 (I don't think the sysadmins like me), so that's not an option. Thanks though. Scott From tzot at sil-tec.gr Sat Jul 2 17:15:12 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sun, 03 Jul 2005 00:15:12 +0300 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> <864qbf8hvr.fsf@bhuda.mired.org> Message-ID: On Thu, 30 Jun 2005 20:55:20 -0400, rumours say that Mike Meyer might have written: >Actually, I was thinking of pre-K&R Unix compilers. There must be something I am missing here, cause I don't understand what you mean; what is the earliest K&R C compiler ("Unix" compiler) you consider as such? Were there other Unix C compilers before K&R wrote one? Or are you considering as "K&R Unix compilers" those after the publication of the white book and before C89? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From rkern at ucsd.edu Thu Jul 28 04:02:48 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 01:02:48 -0700 Subject: functions without parentheses In-Reply-To: <20050728075951.74221.qmail@web51507.mail.yahoo.com> References: <20050728075951.74221.qmail@web51507.mail.yahoo.com> Message-ID: Jerry He wrote: > Hi, > Is it possible to create a function that you can use > without parenthesizing the arguments? for example, for > > def examine(str): > ..... > ..... > > Is there some way to define it so that I can call it > like > > examine "string" > instead of examine("string")? No. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tjreedy at udel.edu Fri Jul 1 23:28:43 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Jul 2005 23:28:43 -0400 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net><1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> Message-ID: "Devan L" wrote in message news:1120245884.872772.231420 at o13g2000cwo.googlegroups.com... > With the exception of reduce(lambda x,y:x*y, sequence), reduce can be > replaced with sum, and Guido wants to add a product function. The update function is not at all limited to sums and products, but can be any callable with the appropriate signature. The new any() and all() functions are examples that use other updates. Terry J. Reedy From claudio.grondi at freenet.de Wed Jul 20 06:13:46 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 20 Jul 2005 10:13:46 -0000 Subject: Documentation bug: Python console behaviour changed References: Message-ID: <3k6fd9Fsr0baU1@individual.net> >> 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. >> Usually means you have a readline package installed. Right. Readline uninstalled, Ctrl-Z works again. By the way: After trying to take over readline support from Gary Bishop, I have inbetween given up trying to fix readline behaviour on international keyboards in Windows (mainly because the Python 2.4 IDLE works for me best, so I don't need IPython anymore). I haven't digged very deep into it, but I mean, that the whole code must be probably more or less entirely rewritten by someone with experience in internationalization matters on Windows (various keyboards and localized Windows versions) and readline behaviour on *nix systems. Up to now, there is noone known to me willing to support the readline package - any volunteers? Michele Simionato and me can then test the outcome on German and Italian Windows systems and keyboards. Claudio "Tim Golden" schrieb im Newsbeitrag news:mailman.1902.1121778341.10512.python-list at python.org... [Lucas Raab] | Peter Hansen wrote: | > Kay Schluehr wrote: | > | >> The documentation of the Python console behaviour is not correct | >> anymore for Python 2.4.1. At least for the Win2K system | I'm working on | >> 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. | >> | >> The Python interpreter tells me instead: | >> | >> | >>>>> quit | >> | >> | >> 'Use Ctrl-Z plus Return to exit.' | >> | >> Nah, 'Ctrl-Z' is now undo :-) | > | > | > Are you really using the console, started with the "Command | Prompt" icon | > from the Start Menu (or some equivalent)? And are you sure | you haven't | > installed something else that magically changed the | behaviour of Ctrl-Z? | > | > (I get the documented behaviour with Python 2.4.1, under Win XP.) | > | > -Peter | | I'm getting the same behavior as Kay. Usually means you have a readline package installed: I know that this one gives the effect described: http://sourceforge.net/projects/uncpythontools/ Don't know about this one: http://newcenturycomputers.net/projects/readline.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From francois.perche at gmail.com Tue Jul 26 09:54:11 2005 From: francois.perche at gmail.com (perchef) Date: 26 Jul 2005 06:54:11 -0700 Subject: wxPython, Tree and Checkbox Message-ID: <1122386051.477321.277080@g47g2000cwa.googlegroups.com> Hello, I'm looking for a way to select some leafs in a tree. My idea is to use a TreeListCtrl, with the tree in the first column and checkboxes in the second. But I don't know how to do this, tree items seems only to be able to contain text, not a wx-object. ideas or suggestion are welcome. From huron at sopinspace.com Mon Jul 4 11:15:38 2005 From: huron at sopinspace.com (Huron) Date: Mon, 04 Jul 2005 17:15:38 +0200 Subject: python project layout References: <9JqdnRP9IqxM_ljfRVn-rA@powergate.ca> Message-ID: > A concrete example would probably help. What are you envisioning? Let say you have an interface (zope.interface) IMyProduct and two classes implementing the interface MyProduct1 and MyProduct2 ... But I think I found the answer. One file each. Python is just more flexible than java in the sens that you dont NEED to do "one class" = "one file" -- h From and-google at doxdesk.com Sat Jul 9 21:36:13 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 9 Jul 2005 18:36:13 -0700 Subject: Yet Another Python Web Programming Question References: Message-ID: <1120959373.895552.161480@f14g2000cwb.googlegroups.com> Daniel Bickett wrote: > Python using CGI, for example, was enough for him until he started > getting 500 errors that he wasn't sure how to fix. Every time you mention web applications on this list, there will necessarily be a flood of My Favourite Framework Is X posts. But you* sound like you don't want a framework to take over the architecture of your app and tell you what to do. And, indeed, you don't need to do that. There are plenty of standalone modules you can use - even ones that are masquerading as part of a framework. I personally use my own input-stage and templating modules, along with many others, over standard CGI, and only bother moving to a faster server interface which can support DB connection pooling (such as mod_python) if it's actually necessary - which is, surprisingly, not that often. Hopefully if WSGI catches on we will have a better interface available as standard in the future. Not quite sure what 500 Errors you're getting, but usually 500s are caused by unhandled exceptions, which Apache doesn't display the traceback from (for security reasons). Bang the cgitb module in there and you should be able to diagnose problems more easily. > He is also interested in some opinions on the best/most carefree way > of interfacing with MySQL databases. MySQLdb works fine for me: http://sourceforge.net/projects/mysql-python/ (* - er, I mean, Hypothetical. But Hypothetical is a girl's name!) -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From miki.tebeka at zoran.com Fri Jul 8 15:04:57 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Fri, 8 Jul 2005 22:04:57 +0300 Subject: Legacy data parsing In-Reply-To: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: <20050708190457.GJ344@zoran.com> Hello gov, > Here's an example of the raw text that I have to work with: > > > ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: > **************************** > > FOR/POUR AL/LA: 20 > CORR TYP: A1B 2C3 P:3 CHNGD/CHANG > LANG: E CONS/REGR: ####### > MRS XXX X XXXXXXX > ### XXXXXXXXX ST DD TYP: P:6 > CHNGD/CHANG > MONCTON NB LANG: E CONS/REGR: > ####### > MRS XXX X XXXXXXX > ##### > #### > ###-###-# > > ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: > **************************** > > FOR/POUR AL/LA: 30 > BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG > LANG: E CONS/REGR: ####### > MISS XXXX XXXXX > ### XXXXXXXX ST > MONCTON NB > > EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: > *********** > > (the # = any number, and the X's are just regular text) > I would like to extract the address information, but the two different > text objects on the right hand side are difficult to remove. I think > it would be easier if I could just extract a fixed square of > information, but I don't have a clue as to how to go about it. > > If anyone could give me suggestions as to methods in sorting this type > of data, it would be appreciated. Maybe regular expression are too difficult for this. I'd try one of the parsing toolkits (such as PLY, PyParsing ...), it might be more suitable for the job. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From jstroud at mbi.ucla.edu Sun Jul 31 20:09:18 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 31 Jul 2005 17:09:18 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <7xr7de5zoe.fsf@ruckus.brouhaha.com> References: <7xr7de5zoe.fsf@ruckus.brouhaha.com> Message-ID: <200507311709.18243.jstroud@mbi.ucla.edu> OK. I am open to new things and I am definitely open to being wrong. So lets try dabo (results below--how did I know this would happen?). This demonstration is not to pick on the dabo people (I'm sure they mean well), but to give an idea of what I face EVERY time I try to install some new, great, python module. Now the last thing I want to do is to go on a hunt for the source of this error--and fix it, just to find another a little later and another and another--without an inkling of why, in real world practicality, dabo would be so much greater than anything else. So you can see why I stick with one good thing. Its not that I don't want to learn or I am not open, etc. Its just that things don't usually work out of the box, and, to quote GnR, "I ain't got time for the pain." Incidentally, I'm not really interested in knowing what is wrong here, frankly I haven't even looked at the output except that I notice that it is a stack trace, so don't bother telling me how simple it is to fix and that I should know this or that. You might be right, but I simply don't care at this point. Sorry dabo guys. You are only one of many. James Python 2.3.4 (#4, Oct 25 2004, 21:40:10) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> import MySQLdb py> import wx py> import dabo Dabo Info Log: Sun Jul 31 16:51:08 2005: No default UI set. (DABO_DEFAULT_UI) py> dabo.ui.loadUI("wx") Traceback (most recent call last): File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/dabo/ui/__init__.py", line 43, in loadUI exec("from %s import *" % mods[typ], globals()) File "", line 1, in ? File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/dabo/ui/uiwx/__init__.py", line 84, in ? import dShell File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/dabo/ui/uiwx/dShell.py", line 1, in ? import wx, wx.py File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/wx-2.6-gtk2-ansi/wx/py/__init__.py", line 8, in ? import crust File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/wx-2.6-gtk2-ansi/wx/py/crust.py", line 14, in ? import editwindow File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/wx-2.6-gtk2-ansi/wx/py/editwindow.py", line 8, in ? from wx import stc File "/data10/users/jstroud/Programs/lib/python2.3/site-packages/wx-2.6-gtk2-ansi/wx/stc.py", line 10, in ? import _stc ImportError: No module named _stc False py> -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ ----------------------------------------------------------------- The words democracy, socialism, freedom, patriotic, realistic, justice, have each of them several different meanings which cannot be reconciled with one another. In the case of a word like democracy, not only is there no agreed definition, but the attempt to make one is resisted from all sides. It is almost universally felt that when we call a country democratic we are praising it: consequently the defenders of every kind of regime claim that it is a democracy, and fear that they might have to stop using the word if it were tied down to any one meaning. - George Orwell From grante at visi.com Tue Jul 19 17:42:38 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 19 Jul 2005 21:42:38 -0000 Subject: socket programming References: Message-ID: <11dqsuepa9dli50@corp.supernews.com> On 2005-07-19, Helge Aksdal wrote: > if i then change to a console window, and telnet to this > server it sends me to another one. What do you mean "sends me to another one"? The telnet protocol doesn't have any sort of "redirect" capability. > That's probably why my program dies, how can i get my code to > handle this? I don't understand what "this" is. If the server is sending you some sort of redirect message, then parse it and obey it. -- Grant Edwards grante Yow! I'm RELIGIOUS!! I at love a man with a visi.com HAIRPIECE!! Equip me with MISSILES!! From thomas at thomas-lotze.de Fri Jul 8 08:57:54 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Fri, 08 Jul 2005 14:57:54 +0200 Subject: Python Module Exposure References: Message-ID: Jacob Page wrote: > better-named, Just a quick remark, without even having looked at it yet: the name is not really descriptive and runs a chance of misleading people. The example I'm thinking of is using zope.interface in the same project: it's customary to name interfaces ISomething. -- Thomas From gene.tani at gmail.com Mon Jul 25 00:26:52 2005 From: gene.tani at gmail.com (gene tani) Date: 24 Jul 2005 21:26:52 -0700 Subject: Fire event when variable is Set/Get In-Reply-To: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> References: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> Message-ID: <1122265612.762359.178460@z14g2000cwz.googlegroups.com> this recipe takes medium-deep copies (shallow copies of embedded sequences/dict's) of an obj's __dict__ when you need to monitor changes to the object's state from that point on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302742 From rwgk at yahoo.com Sun Jul 10 09:39:59 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sun, 10 Jul 2005 06:39:59 -0700 (PDT) Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> Message-ID: <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> --- Kay Schluehr wrote: > > I stripped your code down to the essence. See attachment. > > For the user your approach then becomes: > > > > class grouping: > > __metaclass__ = autoattr > > def __init__(self, x, y, z): > > pass > > No. This is clearly NOT what I had in mind. I translated your original > proposal which introduced a punctuation syntax '.x' for constructor > parameters forcing the interpreter to create equally named object > attributes into a naming convention that can be handled by a metaclass > customizer. I see. > The grouping.__init__ above does exacly nothing according > to my implementation. I would never accept dropping fine-tuning > capabilities. The "auto_" prefix is all the declarative magic. I got only negative feedback regarding the fine-tuning idea, e.g. http://mail.python.org/pipermail/python-list/2005-July/288833.html. After thinking about it for a while I also came to the conclusion that runtime performance and simplicity is indeed the higher value for a general-purpose solution. Without a supporting syntax change (the idea received almost hysteric opposition) I don't think fine-tuning can be supported without a noticeable runtime-penalty. My syntax-change proposal was meant not to change the user interface. I.e. it was meant to preserve "grouping(x=1,y=2,z=3)", no matter how x,y,z are handled in the constructor. Under your proposal the decision to use "auto init" becomes a visible part of the user interface and may therefore be irreversible in practical applications. > > My __autoinit__ suggestion would result in (assuming object supports > > this by default): > > > > class grouping(object): > > def __autoinit__(self, x, y, z): > > pass > > > > I think that's far more intuitive. > > Being intuitive is relative to someones intuition. If someone looks at the code there is no question he/she knows immediately what is going on. In contrast, the __metaclass__ statement is potentially separated from the __init__ definition by unrelated code, leading to surprises (on top of intimidation for beginners). I don't think that's the best style. It is generally better if the framework doesn't allow for artificial separations in the first place. Cheers, Ralf __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From devlai at gmail.com Fri Jul 1 14:31:25 2005 From: devlai at gmail.com (Devan L) Date: 1 Jul 2005 11:31:25 -0700 Subject: Regular Expression for pattern substitution In-Reply-To: <1120237763.216043.148480@g14g2000cwa.googlegroups.com> References: <1120236251.006103.97030@g43g2000cwa.googlegroups.com> <1120237763.216043.148480@g14g2000cwa.googlegroups.com> Message-ID: <1120242685.381141.212150@z14g2000cwz.googlegroups.com> Hrm, thought it had one. Guess it would help if I actually used regular expression for replacement. From JustinStraube at notmymailbox.com Sun Jul 10 18:15:46 2005 From: JustinStraube at notmymailbox.com (Justin Straube) Date: Sun, 10 Jul 2005 17:15:46 -0500 Subject: An absolute Newbie question In-Reply-To: References: Message-ID: wpog wrote: > I have a question about using "IDLE", and that is whenever I start write my > own program in the "Python Shell" it will automatically execute whatever > command I have written, for example: >>> print 'Hello World" > > So, how to I get it to not execute, so that I can write a program that has > ordinary executable functions, and stuff like that? Also if you open IDLE and in the menu bar go to Options >> Configure IDLE, select the 'General' tab and you can specify if you want the interactive prompt or an Edit Window to open at startup. Then hitting F5 will execute the written code, and you can also go to Run >> Python Shell and open an interactive prompt window. Justin From sjmachin at lexicon.net Thu Jul 7 17:46:35 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 08 Jul 2005 07:46:35 +1000 Subject: print values from Py_BuildValue In-Reply-To: <1120757327.028502.74300@g43g2000cwa.googlegroups.com> References: <1120757327.028502.74300@g43g2000cwa.googlegroups.com> Message-ID: <42CDA2BB.4080403@lexicon.net> ashtonn at gmail.com wrote: > Hello, > > How do i print values returned by Py_BuildValue in Linux? 1. The same way as you would "in" any other operating system. 2. With difficulty. 3. If you must print something from C, print the C components (no difficulty). 4. If you are interested in checking what you have created, return the value to the Python caller, and print from there (no difficulty). 5. However if you have a debugging problem, read on ... > > PyObject *obj = Py_BuildValue("{s:i}", "Status", status); > > I need to print the Status value here What is the 'Status' value? '"Status"' and 'status' are C expressions which you should be able to print using printf. Do you mean 'obj'? Why do you think you need to print something here? Are you asking because you are getting a strange exception? Have you tested the value returned by Py_BuildValue -- like this: /* the following line is written to clarify intent, not as an example of good coding style :-) */ if (obj == NULL) goto free_resources_and_return_NULL; Are you extending or embedding? Is this your first attempt? Have you considered using Pyrex? It does almost of the hard work for you. HTH, John From michael at stroeder.com Wed Jul 6 12:08:47 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 06 Jul 2005 18:08:47 +0200 Subject: website catcher In-Reply-To: <1120393925.181952.192040@g49g2000cwa.googlegroups.com> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> Message-ID: jwaixs wrote: > I need some kind > of database that won't exit if the cgi-bin script has finished. This > database need to be open all the time and communicate very easily with > the cgi-bin framwork main class. Maybe long-running multi-threaded processes for FastCGI, SCGI or similar is what you're looking for instead short-lived CGI-BIN programs forked by the web server. Ciao, Michael. From theller at python.net Fri Jul 1 05:36:59 2005 From: theller at python.net (Thomas Heller) Date: Fri, 01 Jul 2005 11:36:59 +0200 Subject: No subject References: Message-ID: Thomas Heller writes: > "Adriaan Renting" writes: > >> I'm not a very experienced Python programmer yet, so I might be >> mistaken, but there are a few things that would make me prefer C++ over >> Python for large (over 500.000 LOC) projects. >> - namespaces >> - templates >> - strong type checking >> - data hiding >> - more available libraries and more advanced developement tools. >> >> I'm talking about managing the code, not the programmers, the project or >> schedules or what have you. Those are independent from the chosen >> programming language. > > Just a single datapoint: Implementing a trivial COM object in Python > requires, let's guess, about 10 or 20 lines of source code. > > When I do the same in MSVC6, the wizard creates 10 files, with nearly > 400 lines of code. Sure, I didn't have to write these code lines, but > I'm required to understand and manage them as well. Sorry, I forgot to include the .dsw and .dsp files in the above figure. Including them brings the LOC count up to 750 for the C++ project - although, to be fair, on the Python side a setup.py script for py2exe would also have to be written. In simple cases, this is another 10 lines. Thomas From ptmcg at austin.rr.com Sun Jul 10 23:18:47 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Jul 2005 20:18:47 -0700 Subject: inheritance In-Reply-To: <1121038079.306961.322370@g44g2000cwa.googlegroups.com> References: <1121031208.829250.82160@g44g2000cwa.googlegroups.com> <1121038079.306961.322370@g44g2000cwa.googlegroups.com> Message-ID: <1121051927.824397.7460@g47g2000cwa.googlegroups.com> I'm not intimate with Python's C/C++ implementation, but is it possible that your modified code may not be implementation portable? For instance, if some calculation of the size of the object is required, inherited classes may layout data differently than contained classes would, especially if classes do not contain a "nice" (i.e., word-boundary) number of bytes. Or is it possible that there are other Python routines that access the mBase field, perhaps for some form of introspection? What you might do is convert one of the existing typedefs to use your form, then build an run Python regression tests, preferably on Win, Mac, and *nix. Or at least run your own alternative PyStructDerivedClass through a series of tests that specifically target and exercise the class hierarchy. (I'm sorry if I'm proposing an onerous build/test burden, but if you want your C++ code to generally adopted, while straying from accepted practices, then you should probably prepare to put in some extra effort to validate your alternative approach.) I agree, your approach looks much cleaner. Unfortunately, in the face of having to support many platforms and compilers, Python implementation and extension may constrain developers to a clearly portable subset of language features. -- Paul From thomas at thomas-lotze.de Tue Jul 12 16:08:55 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 12 Jul 2005 22:08:55 +0200 Subject: Frankenstring Message-ID: Hi, I think I need an iterator over a string of characters pulling them out one by one, like a usual iterator over a str does. At the same time the thing should allow seeking and telling like a file-like object: >>> f = frankenstring("0123456789") >>> for c in f: ... print c ... if c == "2": ... break ... 0 1 2 >>> f.tell() 3L >>> f.seek(7) >>> for c in f: ... print c ... 7 8 9 >>> It's definitely no help that file-like objects are iterable; I do want to get a character, not a complete line, at a time. I can think of more than one clumsy way to implement the desired behaviour in Python; I'd rather like to know whether there's an implementation somewhere that does it fast. (Yes, it's me and speed considerations again; this is for a tokenizer at the core of a library, and I'd really like it to be fast.) I don't think there's anything like it in the standard library, at least not anything that would be obvious to me. I don't care whether this is more of a string iterator with seeking and telling, or a file-like object with a single-character iterator; as long as it does both efficiently, I'm happy. I'd even consider writing such a beast in C, albeit more as a learning exercise than as a worthwhile measure to speed up some code. Thanks for any hints. -- Thomas From martin at v.loewis.de Sun Jul 31 13:16:55 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 31 Jul 2005 19:16:55 +0200 Subject: string methods In-Reply-To: <3l1js6F10d0leU1@individual.net> References: <3l1js6F10d0leU1@individual.net> Message-ID: <42ed078a$0$6841$9b622d9e@news.freenet.de> anthonyberet wrote: > For example if I wanted to replace the 4th character in 'foobar' (the > b)with the contents of another string, newchar, what would be the > easiest way? Depends on how your input is specified. If you know it is the b you want to replace, you write >>> text="foobar" >>> text = text.replace("b","baz") >>> text 'foobazar' There is no issue with immutability here: .replace returns a new string object, and you assign this to the text variable (thus dropping the reference to the string "foobar"). If you know it is the fourth character you want to replace, you do as people have suggested: >>> text="foobar" >>> text=text[:3]+"baz"+text[4:] >>> text 'foobazar' And, if you know in advance that the string is "foobar", and that it is the fourth character, and that the replacement string is "baz", you write >>> text="foobazar" :-) Regards, Martin From thomas at thomas-lotze.de Wed Jul 13 06:56:47 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Wed, 13 Jul 2005 12:56:47 +0200 Subject: Frankenstring References: Message-ID: Roland Heiber wrote: > if i did understand what you mean, what about using mmap? AIUI (and as a little experimenting seems to confirm), you can't reposition an iterator over an mmap'ed file by seeking. True, you have both iterating by characters and seeking/telling, but the two functionalities don't play together. -- Thomas From alan.green at gmail.com Tue Jul 12 17:25:01 2005 From: alan.green at gmail.com (Alan Green) Date: 12 Jul 2005 14:25:01 -0700 Subject: Searching through a list of tuples In-Reply-To: References: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> Message-ID: <1121203501.716352.83270@g47g2000cwa.googlegroups.com> Peter Otten wrote: > Repton wrote: > > > I often find myself storing data in a list of tuples, and I want to ask > > questions like "what is the index of the first tuple whose 3rd element > > is x", or "give me the first tuple whose 2nd element is y". > >>> items = [(1, "a", 10), (2, "b", 20), (3, "c", 30)] > >>> class Key(object): > ... def __init__(self, key): > ... self.key = key > ... def __eq__(self, other): > ... return self.key(other) > ... > >>> items.index(Key(lambda x: x[2] == 20)) > 1 Neat solution. I'd add an extra kind of Key, since finding tuples where a given position is equal to a given value seems to be the common case: >>> class EqualKey(Key): ... def __init__(self, pos, val): ... super(EqualKey, self).__init__(lambda x: x[pos] == val) ... >>> items.index(EqualKey(2, 20)) 1 Alan From tim.golden at viacom-outdoor.co.uk Tue Jul 26 10:58:48 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 26 Jul 2005 15:58:48 +0100 Subject: Counting processors Message-ID: <9A28C052FF32734DACB0A288A3533991044D214F@vogbs009.gb.vo.local> [k pur] | You can use | | print os.sysconf("SC_NPROCESSORS_CONF") | | works on Linux | | | krishan | | | Pauldoo wrote: | > Hi, | > Is a way in python to obtain the total number of processors | present in | > the system? | > | > os.platform doesn't seem to contain anything useful. And on Windows (2000, at least): import os print os.environ['NUMBER_OF_PROCESSORS'] does the trick. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dotpyFE at gmail.com Tue Jul 19 08:55:28 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Tue, 19 Jul 2005 12:55:28 GMT Subject: Documentation bug: Python console behaviour changed In-Reply-To: <-I2dnSVstZw-ekHfRVn-rA@powergate.ca> References: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> <-I2dnSVstZw-ekHfRVn-rA@powergate.ca> Message-ID: <4L6De.1182$6f.169@newsread3.news.atl.earthlink.net> Peter Hansen wrote: > Kay Schluehr wrote: > >> The documentation of the Python console behaviour is not correct >> anymore for Python 2.4.1. At least for the Win2K system I'm working on >> 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. >> >> The Python interpreter tells me instead: >> >> >>>>> quit >> >> >> 'Use Ctrl-Z plus Return to exit.' >> >> Nah, 'Ctrl-Z' is now undo :-) > > > Are you really using the console, started with the "Command Prompt" icon > from the Start Menu (or some equivalent)? And are you sure you haven't > installed something else that magically changed the behaviour of Ctrl-Z? > > (I get the documented behaviour with Python 2.4.1, under Win XP.) > > -Peter I'm getting the same behavior as Kay. -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From dimitri.pater at gmail.com Wed Jul 20 09:08:51 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 20 Jul 2005 15:08:51 +0200 Subject: python certification In-Reply-To: <1121863299.203822.33180@z14g2000cwz.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> <1121790230.580130.156410@o13g2000cwo.googlegroups.com> <1121863299.203822.33180@z14g2000cwz.googlegroups.com> Message-ID: Hello, Python is not about certificates or diplomas, so do not spend any money on it (the other guy was only joking). If you want to show your python skills to others (like the teachers from the college you want to go to), use this list. Participate in discusions, ask quesions, maybe even write a tutorial. Maybe then they will think: "hey, this guy (or girl) is really doing something with his skills". Just an idea, Dimitri On 20 Jul 2005 05:41:39 -0700, lordverminard at gmail.com < lordverminard at gmail.com> wrote: > > hi > i bassically need it cuz i am appyling to colleges this year and > i know this kind of stuff really helps. > besides since i am learning python i thought i might get some credit > for it as well. > its bassically for a mention in my resume/bio-data/appliccation > i am willing to spend about $50-100 but any more is out of my bugdet. > even $50 is hard on me. > i did find this great site that would let me give a perl exam in $9.99 > but they don't have python. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident. Arthur Schopenhauer ----- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From thanos at sians.org Sat Jul 23 06:10:59 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sat, 23 Jul 2005 13:10:59 +0300 Subject: Getting a dictionary from an object In-Reply-To: <42E216C1.70707@tiscali.it> References: <20050723084827.GA6903@zermelo.sians.org> <42E216C1.70707@tiscali.it> Message-ID: <20050723101059.GA1756@zermelo.sians.org> On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote: > use getattr(self.obj,key) possibly, as __getattribute__ gets total > control on attribute access Thanks, but what do you mean by 'total control'? -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From steve at REMOVETHIScyber.com.au Sun Jul 31 07:14:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 21:14:29 +1000 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: On Sun, 31 Jul 2005 12:44:46 +0200, Paolino wrote: > I show you a piece of code I need to define a function: > > import string > all=string.maketrans('','') > badcars=all.translate(all,string.letters+string.digits) > table=string.maketrans(badcars,'_'*len(badcars)) > def translate(text): > return text.translate(table) Or do this: def translate(text): import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) table=string.maketrans(badcars,'_'*len(badcars)) return text.translate(table) No pollution. > What I'm needing as a global (in globals() or at the module level or in > the module namespace) is 'translate'.The rest of bindings (all,badcars > and table) is something which is 'polluting' the module namespace. Then after you are finished with the bindings, delete them: import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) table=string.maketrans(badcars,'_'*len(badcars)) def translate(text): return text.translate(table) # clean up the temporary variables so as to prevent namespace pollution del string; del all; del badcars; del table -- Steven. From kwharrigan at yahoo.com Fri Jul 22 12:34:27 2005 From: kwharrigan at yahoo.com (kwharrigan at yahoo.com) Date: 22 Jul 2005 09:34:27 -0700 Subject: time.time() under load between two machines In-Reply-To: References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> Message-ID: <1122050067.793702.164780@o13g2000cwo.googlegroups.com> I am seeing negative latencies of up to 1 second. I am using ntp to synchronize both machines at an interval of 2 seconds, so the clocks should be very much in sync (and are from what I have observed). I agree that it is probably OS, perhaps I should hop over to a Microsoft newsgroup and pose the question, although I'm sure they will find a way to blame it on Python. From fake at not.real Mon Jul 11 18:43:50 2005 From: fake at not.real (vch) Date: Tue, 12 Jul 2005 02:43:50 +0400 Subject: How does this code works: Message-ID: Here's an example from some book: def foo(n): s = [n] def bar(i): s[0] += i return s[0] return bar what I don't understand is how this example works, taking into account the LGB rule. I thought that s is not accessible from bar, but it is, apparently. Why? From paul.richards at gmail.com Mon Jul 25 11:01:19 2005 From: paul.richards at gmail.com (Pauldoo) Date: 25 Jul 2005 08:01:19 -0700 Subject: Counting processors In-Reply-To: References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> Message-ID: <1122301796.754851.322040@g47g2000cwa.googlegroups.com> Yeh well I know of /proc/cpuinfo (due to linux's hacked up non-unix /proc, *grumble*) and the NUMBER_OF_PROCESSORS environment variable on windows. I was just hoping for a slightly more platform independant way of doing it. From ssnail at gmail.com Mon Jul 4 06:04:13 2005 From: ssnail at gmail.com (shablool) Date: 4 Jul 2005 03:04:13 -0700 Subject: curses -- getxy() error Message-ID: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> Hi, Could someone please explain why stdscr.getxy() always raise an exception: import curses import traceback def init(stdscr): x = y = 0 while 1: c = stdscr.getch() if c == ord('q'): break stdscr.addch(c) (x, y) = stdscr.getxy() stdscr.refresh() def main(): try: curses.wrapper(init) except Exception, e: traceback.print_exc() if __name__ == "__main__": main() From adurdin at gmail.com Fri Jul 1 03:35:11 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 1 Jul 2005 17:35:11 +1000 Subject: Speaking of list-comprehension? In-Reply-To: <42C4DC20.30805@tds.net> References: <59e9fd3a05063021374c82f949@mail.gmail.com> <42C4DC20.30805@tds.net> Message-ID: <59e9fd3a0507010035149cc171@mail.gmail.com> On 7/1/05, Chinook wrote: > Thank you Andrew, and your elaboration is well taken. I was just > exploring here and the construct you noted is IMHO intuitively readable > - at least for a simple expression and condition. Other than the > choice order [False, True] which seems backward to me. The choice order is based on the fact that True == 1 and False == 0 (as bool is a subclass of int). Also, I should probably have made the choices a tuple instead of a list, if for no other reason than it's slightly clearer: >>> [tai + (10, -10)[tai >= 10] for tai in ta] [15, 5, 2, 0, 19] It may have a performance benefit as well, but (a) I haven't tested it to see, and (b) it would be irrelevant for small lists like this anyway. One other thing I should have noted: unlike the ?: operator in C/C++/Java, this construction (and the iif() function in my message) will always evaluate both expressions, and does not short-circuit. In many instances this is not necessary anyway. > So, where might I have found this construct. It is probably somewhere > obvious, but I searched and searched without success. Of course, I've > had only limited success in finding what I wanted in the "official' > docs, though the QR has been quite useful. It's in the "General Programming FAQ": http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator From dimitri.pater at gmail.com Wed Jul 20 04:25:00 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 20 Jul 2005 10:25:00 +0200 Subject: email format in python In-Reply-To: <5f4d3cb5050719211573877e0f@mail.gmail.com> References: <20050718102120.64241.qmail@web42004.mail.yahoo.com> <5f4d3cb5050719211573877e0f@mail.gmail.com> Message-ID: hello, this one works quite well on validating email syntax: http://www.secureprogramming.com/?action=view&feature=recipes&recipeid=1 regards, Dimitri On 7/20/05, Dark Cowherd wrote: > > This seems to give reasonable results. > import re > pattern = r'\b[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z]{2,4}\b' > pattobj = re.compile(pattern) > ps = pattobj.search > if ps(stringtocheck): > > > But as lots of people have already told you on this list. This should > only be used to give a warning and not prevent the use of that > particular address. > > DarkCowherd > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVETHIScyber.com.au Tue Jul 5 09:17:45 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 05 Jul 2005 23:17:45 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: On Tue, 05 Jul 2005 05:03:32 -0700, mcherm wrote: > Steven D'Aprano writes: >> Lambda is no more an obscure name than "function", "decorator", "closure", >> "class", or "module". The first time you come across it, you don't know >> what it means. Then you learn what it means, and then you know. > > I believe you've made two errors here. First of all, "lambda" is part > of the Python language, while "function", "decorator", "closure", and > "module" are not. Sorry, but you are mistaken. "lambda" is a _reserved_ word in the Python language, while "function" etc are not, but they are certainly part of the language. Try explaining what def and import do without using the words "function" or "module". Maybe you can do it, using circumlocutions, but it isn't easy, and costs clarity. [snip] > The second error is that I believe most english speakers COULD provide > a definition for the fairly common words "function", "class", and > "decorator". The exact meaning of "class" might not be what they expect > at first, Function, in the sense of a mathematical function, I agree. Class as in the thing you go to at school and decorator as in the person who advises you what colour curtains to have, certainly. But in the Python sense? No. Especially not decorator, which I believe most _programmers_ would have trouble explaining, let alone non-programmer English speakers. I know I do. > but exposure to any object oriented language would make the > concept quickly familiar. Just as exposure to functional languages would make lambda very familiar. > But "lambda" has a very clear meaning... it's > a letter of the greek alphabet. The connection between that letter and > anonymous functions is tenuous at best, and fails the test of making > Python read like "executable pseudocode". Think back to when you were a schoolboy at your first day of school. Unless you had a very unusual upbringing, you probably had never heard the word "function" before. There is nothing about the word "function" that brings to mind "a mathematical entity which transforms a variable into a different variable", let alone "a programming subroutine that returns a result". (Or for that matter, "the purpose which a person or thing is for", as in the function of a spanner is to tighten nuts on bolts.) You had to learn that word, discover what it means, and then it becomes familiar. You don't notice the process only because it happened so long ago, at an age that your brain was operating in "language acquisition mode" and picking up vocabulary at an incredible rate. There is nothing about the word "string" that especially brings to mind "an array of bytes representing characters". The analogy of "string of characters" to "string of beads" breaks down as soon as you have multiple lines of text. And as for float, that's what boats do, heaven only knows what it has to do with numbers. (Yes, I know what it has to do with numbers. But that is something I had to learn, and even now I still have difficulty because I expect floats to operate like mathematical real numbers, and they don't.) And dare I say it, what do constricting snakes have to do with programming? I won't say that the anonymous function meaning of lambda comes to my mind before the Greek letter, but it isn't very far behind, and rapidly catching up. (I use lambda a lot more than I speak Greek.) It wouldn't surprise me if one day I think of Python programming before the Greek letter, just as the world aleph brings to my mind the sense of infinity before the sense of it being a Hebrew letter. -- Steven. From paolo_veronelli at tiscali.it Sun Jul 31 05:14:56 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sun, 31 Jul 2005 11:14:56 +0200 Subject: namespaces Message-ID: <42EC9690.2040301@tiscali.it> While it's not so bad we can bind names in the module namespace, (ex writing scripts ?) ,writing modules is someway bound to not polluting that namespace (really IMO). For non-functions we can use 'class' : class ns: foo='something' but writing a function there triggers the binding to 'self' behaviour. The straight solution is @staticmethod class ns: @staticmethod def gulp(*args): pass Another solution is via metaclass class namespaceMeta(type): def __init__(cls,*more): ## wrap all methods with staticmethod() class namespace: __metaclass__=namespaceMeta class ns(namespace): def gulp(*args):pass This solution makes me think the keyword 'namespace' is missing: namespace ns: foo='something' def gulp(*args): pass Solutions and comments appreciated. Regards Paolino ___________________________________ Yahoo! Messenger: chiamate gratuite in tutto il mondo http://it.beta.messenger.yahoo.com From pgrasso at optonline.net Fri Jul 22 11:33:37 2005 From: pgrasso at optonline.net (Paul Grasso) Date: Fri, 22 Jul 2005 11:33:37 -0400 Subject: PYTHONVERBOSE Message-ID: I want to trace an import statement, but only one so I set import os os.environ["PYTHONVERBOSE"] = "1" import wx del os.environ["PYTHONVERBOSE"] but the import wx was NOT traced. Neither was it traced if I use os.putenv. Does anyone know how to set python for import tracing within a script? From tjreedy at udel.edu Wed Jul 6 15:39:19 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 6 Jul 2005 15:39:19 -0400 Subject: map/filter/reduce/lambda opinions and backgroundunscientificmini-survey References: <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <1120656105.175799.311610@f14g2000cwb.googlegroups.com> Message-ID: "George Sakkis" wrote in message news:1120656105.175799.311610 at f14g2000cwb.googlegroups.com... > "Terry Reedy" wrote: > >> "George Sakkis" wrote in message >> news:1120610787.940292.15210 at g43g2000cwa.googlegroups.com... >> > Still it's hard to explain why four specific python keywords - def, >> > del, exec and elif - were chosen to be abbreviated, >> >> Precedence in other languages and CS usage? > > What precedence ? I don't know of another language that uses def or del DOS used DEL, BASIC used DEF. tjr From grante at visi.com Mon Jul 11 16:23:07 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Jul 2005 20:23:07 -0000 Subject: Environment Variable References: Message-ID: <11d5l9b5tfvep9d@corp.supernews.com> On 2005-07-11, Vivek Chaudhary wrote: > Is it possible to set an environment variable in python script whose > value is retained even after the script exits. No, not in Unix/Linux. In VMS I think there is. -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com From gsakkis at rutgers.edu Thu Jul 14 09:14:28 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 14 Jul 2005 09:14:28 -0400 Subject: Consecutive Character Sequences References: <1121318559.d582247e6e25443e247191d29f60b3b0@teranews> <1121325469.494500.291730@z14g2000cwz.googlegroups.com> <1121343722.7ebce1b2a41714687db3ed336af5fc19@teranews> <1121344871.471781.37180@z14g2000cwz.googlegroups.com> Message-ID: <1121346872.4fb0afdb5973442af3c4394c1c8cfdfd@teranews> "Aries Sun" wrote: > Hi George, > I used Python 2.4.1, the following are the command lines. > But the reslut was still False. Is there anything wrong with below > codes?hasConsequent("taaypiqee88adbbba", 3) All indentation was lost in your message, so I'm not quite sure; here it is again, just in case: import itertools as it def hasConsequent(aString, minConsequent): for _,group in it.groupby(aString): if len(list(group)) >= minConsequent: return True return False Run it from a file instead of the command line and see if you get the same result. I'm using 2.4: >>> sys.version '2.4 (#1, Mar 29 2005, 15:15:45) \n[GCC 3.3.3 (cygwin special)]' I would be very surprised if something so crucial changed between 2.4.0 and 2.4.1. What does [list(group) for _,group in it.groupby("taaypiqee88adbbba")] return to you ? George From bill.mill at gmail.com Wed Jul 6 16:10:38 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 6 Jul 2005 16:10:38 -0400 Subject: Folding in vim In-Reply-To: <200507060144.03342.hancock@anansispaceworks.com> References: <200507022235.52847.hancock@anansispaceworks.com> <200507060144.03342.hancock@anansispaceworks.com> Message-ID: <797fe3d405070613101626d614@mail.gmail.com> On 7/6/05, Terry Hancock wrote: > On Tuesday 05 July 2005 03:53 pm, Renato Ramonda wrote: > > Why not use just spaces? Vim simplifies this immensely: > > > > set tabstop=4 > > set shiftwidth=4 > > set expandtab > > set smarttab > > set autoindent > > > > AFAICT this gives me all spaces, 4 spaces indent, tab inserts spaces and > > backspace over a block of 4 spaces deletes all of them (just like > > deleting a tab). > > Yep, this is what I just set up in my .vimrc. Works beautifully. > I don't use any of the fancy indenters; instead, I just add set foldmethod=indent to my .vimrc (_vimrc on windows), along with most of the aforementioned options (I don't like smarttab); it works nearly perfectly. Then zo opens the fold under the cursor one level, zO opens it recursively, zc and zC close it non- and recursively. zr opens all folds one level, zR opens them all recursively, zm closes them all one level, and zM closes them all recursively. It's pretty sweet. Maybe we should have a big Vim-python tip-a-thon thread? Peace Bill Mill bill.mill at gmail.com From thomas at thomas-lotze.de Thu Jul 14 08:30:54 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Thu, 14 Jul 2005 14:30:54 +0200 Subject: Frankenstring References: Message-ID: Thomas Lotze wrote: > And I wonder whether there shouldn't be str.findany and > str.iterfindany, which takes a sequence as an argument and returns the > next match on any element of it. On second thought, that wouldn't gain much on a loop over finding each sequence, but add more complexity than it is worth. What would be more useful, especially thinking of a C implementation, is str.findanyof and str.findnoneof. They take a string as an argument and find the first occurrence of any char in that string or any char not in that string, resp. Especially finding any char not among a given few needs a hoop to jump through now, if I didn't miss anything. -- Thomas From darkpaladin79 at hotmail.com Fri Jul 1 11:08:05 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Fri, 01 Jul 2005 11:08:05 -0400 Subject: How to run commands in command line from a script In-Reply-To: Message-ID: Well, the thing is that I was just using changing directories as an example for running a name specific command, is the the only way to run name specific commands? An example would be (what I am actually trying to do) run the simply command mame s1945 in the command line. MAME is, for those of you that care, the multaple arcade machine emulator and the command runs the classic game strikers 1945. I'm just trying to automate the tedious process of running it through the command line. By the way, thanks to everyone who responded I'm really getting along here. Thanks, -Ivan > > > > Generally, the only way to use an application (i.e. a program like the > > Python interpreter, or your own .exe) to change the working folder is to > > have your script executed from within a batch file, write out a new > > batch file in your script, and then have the calling batch file execute > > that script if it exists. > >And, after that long-winded reply, here's another option, if you're just >trying to change the directory _within_ your app but don't care if the >change persists: > >import os >os.chdir(r'c:\Program Files') > >-Peter >-- _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From williams13 at llnl.gov Mon Jul 25 08:31:49 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Mon, 25 Jul 2005 05:31:49 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050722164420.GA1912@tishler.net> References: <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <20050722164420.GA1912@tishler.net> Message-ID: <42E4DBB5.3070403@llnl.gov> Jason, >Dean, > >On Fri, Jul 22, 2005 at 05:11:45AM -0700, Dean N. Williams wrote: > > >>I downloaded your new Cygwin from http://cygwin.com and tried to build >>install Python/CDAT again. It appears to have built properly, but when >>I try to execute, it receive a sock error. How do I get around this >>problem? >> >> > >I don't know -- it is not clear what you are trying to do. Are you >trying to build Cygwin Python or just CDAT? > I am trying to build Python first, then eventually I'll get to CDAT. > >On Fri, Jul 22, 2005 at 07:09:08AM -0700, Dean N. Williams wrote: > > >>To be more specific. If I try to import socket I get the "ImportError: >>No module named _socket". What do I need to install from Cygwin in >>order for this to work? >> >> > >AFAICT, nothing. The above seems to indicate your Python installation >is broken. > The Python builds with the exception of the socketmodule. There seems to be some problems here. I can import all needed modules except the socket module. > >Jason > > > From ajikoe at gmail.com Mon Jul 18 09:55:18 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 18 Jul 2005 06:55:18 -0700 Subject: wxPython Menu problem In-Reply-To: <1121679552.543928.292670@g49g2000cwa.googlegroups.com> References: <1121679552.543928.292670@g49g2000cwa.googlegroups.com> Message-ID: <1121694918.506490.203420@g43g2000cwa.googlegroups.com> try to check your definition of your function, self is usually used inside a class. pujo From tjreedy at udel.edu Sun Jul 3 16:16:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 3 Jul 2005 16:16:59 -0400 Subject: Accepted Summer of Code proposals References: <68e6a54a005f51ae50ada6932ea22d09@wolke7.net> Message-ID: "Peter Decker" wrote in message news:ca55a99005070312216fee5ca7 at mail.gmail.com... >> Is it right that two Wax proposals were accepted? > > Or that Wax is being promoted over Dabo, which wraps wxPython just as > elegantly in its UI tier, and which is further along (more controls > supported) than Wax, is more powerful (data binding is built in), and > is still being actively developed? I looked at Wax, but it seems to be > at best a side project to Hans, with no goal in sight. Dabo blew me > away with just how easy it is to create UI apps without all that C++ > cruft that wxPython inherits from wxWidgets. Proposals were made by applicants who sent them to Google who forwarded them as they deemed fit. Of those received, PSF accepted at least in part based on mentor commitments. Some of the Python proposals were based on projects listed on the PyWiki project proposal page and/or discussion on the special mailing list, both announced here. I don't remember any Dabo projects listed, so I suspect PSF either received no Dabo proposals or had no Dabo mentors. Terry J. Reedy From tdelaney at avaya.com Thu Jul 7 21:38:01 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 8 Jul 2005 11:38:01 +1000 Subject: Thoughts on Guido's ITC audio interview Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CB51@au3010avexu1.global.avaya.com> Tony Meyer wrote: > It would be interesting to know which JRE the Eclipse advocates are > using, and which the people that dislike Eclipse are using... For me, performance is the minor issue. Usability is the major issue. If find Eclipse to be highly unusable, so I don't use it. Tim Delaney From corey.coughlin at comcast.net Mon Jul 11 20:50:12 2005 From: corey.coughlin at comcast.net (corey.coughlin at comcast.net) Date: 11 Jul 2005 17:50:12 -0700 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: <1121129412.348444.294480@g47g2000cwa.googlegroups.com> It really does depend. For instance, some other programmers where I work came up with a way to represent a hierarchical, somewhat random data set by creating each object and then adding attributes to those for each subobject, and so on down the tree. However, you could never really be sure that the object you wanted was really there, so for every access call they just wrapped it in a try ...except loop. Now that may seem like a good way to go, but when I rewrote some code to use hasattr() instead, it ran a lot faster. So yeah, exceptions can be handy, but if you code requires exception handling for everything, you may want to rethink things. Steve Juranich wrote: > I know that this topic has the potential for blowing up in my face, > but I can't help asking. I've been using Python since 1.5.1, so I'm > not what you'd call a "n00b". I dutifully evangelize on the goodness > of Python whenever I talk with fellow developers, but I always hit a > snag when it comes to discussing the finer points of the execution > model (specifically, exceptions). > > Without fail, when I start talking with some of the "old-timers" > (people who have written code in ADA or Fortran), I hear the same > arguments that using "if" is "better" than using "try". I think that > the argument goes something like, "When you set up a 'try' block, you > have to set up a lot of extra machinery than is necessary just > executing a simple conditional." > > I was wondering how true this holds for Python, where exceptions are > such an integral part of the execution model. It seems to me, that if > I'm executing a loop over a bunch of items, and I expect some > condition to hold for a majority of the cases, then a "try" block > would be in order, since I could eliminate a bunch of potentially > costly comparisons for each item. But in cases where I'm only trying > a single getattr (for example), using "if" might be a cheaper way to > go. > > What do I mean by "cheaper"? I'm basically talking about the number > of instructions that are necessary to set up and execute a try block > as opposed to an if block. > > Could you please tell me if I'm even remotely close to understanding > this correctly? > -- > Steve Juranich > Tucson, AZ > USA From bokr at oz.net Sun Jul 10 22:32:09 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 02:32:09 GMT Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> <7x64vip8eb.fsf@ruckus.brouhaha.com> Message-ID: <42d1d71e.340825300@news.oz.net> On 10 Jul 2005 16:07:40 -0700, Paul Rubin wrote: >Dan Sommers writes: >> def __init__(self, self.x, y, self.z): >> # self.x, self.z from first and third explicit parameters >> do_something_with_y() > >Hey, I like that. Me too. I liked the leading _, but on second thought it is a weird language change re names in a special context. Probably not so good. OTOH, I see in the above a generalizable principle of formal parameter expressions as automatic assignment targets at the beginning of function execution that could allow anything normally allowed locally on the left of an assignment. This is contrived, but illustrates: def setem(key, adict[key]): pass # note that assignment is left-right, # so key is available for adict[key] # and adict is global here adict = {} setem('k', 'value') adict -> {'k':'value'} Regards, Bengt Richter From steve at holdenweb.com Wed Jul 20 17:36:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 20 Jul 2005 22:36:07 +0100 Subject: Windows command line problem In-Reply-To: <1121812275.374283.224000@g47g2000cwa.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> <1121726398.861595.31350@g43g2000cwa.googlegroups.com> <1121759914.689112.272530@z14g2000cwz.googlegroups.com> <1121762108.120184.201340@g47g2000cwa.googlegroups.com> <1121812275.374283.224000@g47g2000cwa.googlegroups.com> Message-ID: sp1d3rx at gmail.com wrote: > I think the lesson there is 'dont depend on getopt, write your own > command line parser'. I always write my own, as it's so easy to do. > I suppose you built your own car so you could get out a bit, too? After all, there's nothing tricky about a simple internal combustion engine, right? ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From j.bijsterbosch at hccnet.nl Sat Jul 16 07:22:19 2005 From: j.bijsterbosch at hccnet.nl (J.Bijsterbosch) Date: Sat, 16 Jul 2005 13:22:19 +0200 Subject: How can I import a py script by its absolute path name? References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> <87ackpeeag.fsf@titan.staselog.com> <42d7ee79$0$809$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <42da14bd$0$803$3a628fcd@textreader.nntp.hccnet.nl> Hello James, "James Dennett" schreef in bericht news:J7_Be.14824$HV1.4893 at fed1read07... > J.Bijsterbosch wrote: > [ snip ] > >>and didn't remember Windows uses path names which need special > >>treatment. > > > > Hmm, what you call special treatment comes from pythons deep underlying C > > and C++ language heietidge I presume. A backslash in a C or C++ string means > > the following character is a so called escape character, like \n represents > > a newline and \r a return to the beginning of a line. > > If you really want a backslash you need to type it twice like so \\. Has > > nothing to do with Windows...;-)) > > Actually, it does have a connection to Windows. > > On Unix, backslashes are rarely used for anything *except* escape > characters. Pathnames tend not to include backslashes, so in most > cases it's not necessary to escape backslashes in path names. I know, I've had mandrake installed for some time until that pc died on me, the pc that is, not mandrake... > On Windows, however, backslash is a valid path separator, and must be > escaped. > > So, on Unix, for a path separator, you type "/". On Windows you > can either do the same, or type "\\". (Or (ab)use raw strings.) Okay, point taken, but I still think it's more a C(++) string thing than a Windows issue. I could of course argue that the backslash path separator is there for backward compatebility with Dos, but I won't, much to off topic...;-)) > James Greetings from overcast Amsterdam, Jan From bokr at oz.net Tue Jul 12 00:49:37 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 04:49:37 GMT Subject: Puzzled References: Message-ID: <42d34a22.435805525@news.oz.net> On Mon, 11 Jul 2005 22:10:33 -0400, "Colin J. Williams" wrote: >The snippet of code below gives the result which follows > >for k in ut.keys(): > name= k.split('_') > print '\n1', name > if len(name) > 1: > name[0]= name[0] + name[1].capitalize() > print '2', name > name[0]= name[0].capitalize() > print '3', name > >1 ['logical', 'or'] >2 ['logicalOr', 'or'] >3 ['Logicalor', 'or'] > >I was expecting that 3 would read ['LogicalOr', 'or'] > >If I replace the above code with: > >for k in ut.keys(): > name= k.split('_') > print '\n1', name > if len(name) > 1: > name[0]= name[0].capitalize() + name[1].capitalize() > print '2', name > else: > name[0]= name[0].capitalize() > print '3', name > >I get the desired result. > If you walk through the results, you can see what happens to name[2] on output line 2: >>> 'logicalOr'.capitalize() 'Logicalor' I.e., >>> help(str.capitalize) Help on method_descriptor: capitalize(...) S.capitalize() -> string Return a copy of the string S with only its first character capitalized. ^^^^-- meaning all the rest lowercased, which changed your trailing 'Or' So, doing .capitalize on all the pieces from split('_') and then joining them: >>> def doit(w): return ''.join([s.capitalize() for s in w.split('_')]) ... >>> doit('logical_or') 'LogicalOr' >>> doit('logical') 'Logical' >>> doit('logical_or_something') 'LogicalOrSomething' >>> doit('UP_aNd_down') 'UpAndDown' Regards, Bengt Richter From bokr at oz.net Sat Jul 23 20:28:43 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 00:28:43 GMT Subject: dictionary that discards old items References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> <1121999372.836621.190950@o13g2000cwo.googlegroups.com> Message-ID: <42e2dfa0.980127588@news.oz.net> On 21 Jul 2005 19:29:32 -0700, "Raymond Hettinger" wrote: >[Will McGugan] >> I need a collection class that behaves like a dictionary but when it >> reaches 'n' items it discards the oldest item so that the length never >> goes above 'n'. (Its for caching search results) > > >import collections > >class Cache(dict): > def __init__(self, n, *args, **kwds): > self.n = n > self.queue = collections.deque() > dict.__init__(self, *args, **kwds) > def __setitem__(self, k, v): > self.queue.append(k) > dict.__setitem__(self, k, v) > if len(self) > self.n: > oldk = self.queue.popleft() > del self[oldk] > > # . . . > # make similar modifications to setdefault, __delitem__, fromkeys > # and other mutating methods as needed > ># Example >c = Cache(3) >for w in 'the quick brown fox jumped over the lazy dog'.split(): > c[w] = w[:1].upper() > print repr(c) > Minor comment: There is a potential name collision problem for keyword n=something, so what is considered best practice to avoid that? __n or such as the n arg? >>> def foo(n, *args, **kw): print n, args, kw ... >>> foo(1) 1 () {} >>> foo(n=5) 5 () {} >>> foo(3, n=5) Traceback (most recent call last): File "", line 1, in ? TypeError: foo() got multiple values for keyword argument 'n' >>> Regards, Bengt Richter From anton.vredegoor at gmail.com Thu Jul 28 06:38:39 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 28 Jul 2005 03:38:39 -0700 Subject: all possible combinations In-Reply-To: <42d6de96@news.eftel.com> References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> <42d6de96@news.eftel.com> Message-ID: <1122547119.104995.43340@o13g2000cwo.googlegroups.com> John Machin wrote: > You don't need to use random sampling. Paul Rubin has shown how it can > be done deterministically. The following is a generalisation of his > code; it generates all possible assemblies of size n from a list of > parts. Is this helpful? > > def all_size_n_knickers(rqd_size, pieces): > npieces = len(pieces) > knicker_count = npieces ** rqd_size > austen = [npieces ** (rqd_size-k-1) for k in xrange(rqd_size)] > for i in xrange(knicker_count): > knicker = [pieces[j] for j in [(i // d) % npieces for d in austen]] > yield knicker > > for alist in all_size_n_knickers(4, 'abc'): > print ''.join(alist) > > print > print list(all_size_n_knickers(2, [1, 42, 666])) Just testing out my ELCH JythonConsole :-) def unint(i,symbols): res = [] radix = len(symbols) while i: i,r = divmod(i,radix) res.append(symbols[r]) return res[::-1] start = int('10000',3) finish = int('20000',3) for i in range(start,finish): print ''.join(unint(i,'abc')[1:]) This makes me wonder why we still don't have something like the unint function above in the standard distribution. Anton From listspam at flowtheory.net Fri Jul 22 10:53:05 2005 From: listspam at flowtheory.net (Joshua Ginsberg) Date: Fri, 22 Jul 2005 08:53:05 -0600 Subject: Iterators from urllib2 Message-ID: <4135b22e47897505851c6f206f932354@flowtheory.net> I'm a bit baffled by something... In a script I wrote, I have defined a function that runs urllib2.urlopen() on a urllib2.Request object and returns the file-like object. The code that calls this function attempts to build a csv.DictReader object based on that file-like object, but an error is thrown saying the file-like object is not an iterator. I could have sworn urllib2.urlopen returned an iterator, so I tested: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> r = urllib2.Request('http://www.google.com') >>> ifs = urllib2.urlopen(r) >>> dir(ifs) ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'fileno', 'fp', 'geturl', 'headers', 'info', 'next', 'read', 'readline', 'readlines', 'url'] Yep. But what about in my code? I modify my code to print dir(ifs) before creating the DictReader... ['__doc__', '__init__', '__module__', '__repr__', 'close', 'fp', 'geturl', 'headers', 'info', 'read', 'readline', 'url'] Traceback (most recent call last): File "CSVParser.py", line 144, in ? print parseQHost(circuits[cktname], cktname) File "CSVParser.py", line 126, in parseQHost r = csv.DictReader(ifs, fieldlist) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/csv.py", line 100, in __init__ self.reader = reader(f, dialect, *args) TypeError: argument 1 must be an iterator Whoa! Where did the __iter__, readlines, and next attributes go? Ideas? -jag From spam.csubich+block at block.subich.spam.com Tue Jul 12 22:34:44 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 12 Jul 2005 22:34:44 -0400 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: <%3%Ae.9910$ag7.9613@bignews4.bellsouth.net> Thomas Lotze wrote: > Neither does it to me. What about > > try: > f=file('file_here') > except IOError: #File doesn't exist > error_handle > else: > do_setup_code > do_stuff_with(f) > > (Not that I'd want to defend Joel's article, mind you...) That works. I'm still not used to having 'else' available like that. I wonder how Joel advocates managing in C++-likes that don't have a try/catch/else semantic. From tim.golden at viacom-outdoor.co.uk Mon Jul 4 08:02:30 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 4 Jul 2005 13:02:30 +0100 Subject: Unicode drives me crazy... Message-ID: <9A28C052FF32734DACB0A288A3533991EBB96C@vogbs009.gb.vo.local> [fowlertrainer at citromail.hu] | I want to get the WMI infos from Windows machines. | I use Py from HU (iso-8859-2) charset. OK, there are people better placed than I to explain about Unicode. Check out the following article, for example: http://www.joelonsoftware.com/printerFriendly/articles/Unicode.html but in short, you need to understand that WMI hands you back a unicode object -- not a string, a unicode object. If you want to write that out to a file, you must write out a string representation of it. And that string representation must use one of the standard encodings (or you could invent your own, I suppose, but why bother?). One way of doing this would be: import wmi import codecs f = codecs.open ("c:/temp/info.txt", "w", encoding="iso-8859-2") try: c = wmi.WMI () for port in c.Win32_SerialPort (): f.write ("Caption = %s\n" % port.Caption) f.write ("DeviceID = %s\n" % port.DeviceID) finally: f.close () You now have a text file -- info.txt -- which holds string representations of several unicode objects. If the characters all fall within the common A-Z/1-9 characters, it will appear just the same as an old-fashioned ascii file. If the original data represented (presumably) Hungarian characters, there will be some representation of that, probably using \x sequences. This file can be read by any other program which knows that it's an iso-8859-2 encoding of unicode. (Knows, because you write the program or because you've told the programmer). Obviously, if this were an XML file, you would put an encoding tag or whatever it's called (I'm not up on XML). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rkern at ucsd.edu Sun Jul 31 17:53:14 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 14:53:14 -0700 Subject: Escaping certain characters In-Reply-To: <42ed452f$1@griseus.its.uu.se> References: <42ec0f65$1@griseus.its.uu.se> <42ec15c0$1@griseus.its.uu.se> <42eca481$1@griseus.its.uu.se> <42ed452f$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Robert Kern wrote: > [---] > >>>Hmm... On second thought, I need to escape more characters. >>> >>>Is there no other way to escape characters in strings? >> >>Which characters? > > I need to escape '\n', '"', '[' and ']'. I finally went with a few of > these: > string.replace('\n', '\\n') > string.replace('"', '\\"') > ... > > I assume that's good enough, but I somehow expected there to exist > some form of "insert your conversion table here" built-in string escaper. Write a codec. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From daniel.dittmar at sap.corp Mon Jul 25 04:54:53 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 25 Jul 2005 10:54:53 +0200 Subject: PEP on path module for standard library In-Reply-To: <11e297jkf6i5bfa@news.supernews.com> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <11e297jkf6i5bfa@news.supernews.com> Message-ID: John Roth wrote: > However, a path as a sequence of characters has even less > meaning - I can't think of a use, while I have an application That's true. But the arguments for path objects as strings go more in the direction of using existing functions that expect strings. > where traversing a path as a sequence of path elements makes > perfect sense: I need to descend the directory structure, directory > by directory, looking for specific files and types. But then your loop doesn't need the individual path elements, but rather sub-path objects for p in pathobj.stepdown ('/usr/local/bin'): if p.join (searchedFile): whatever I'm not saying that there isn't any use for having a list of path elements. But it isn't that common, so it should get an methodname to make it more explicit. Daniel From mailman at hanez.org Mon Jul 25 10:51:05 2005 From: mailman at hanez.org (Johannes Findeisen) Date: Mon, 25 Jul 2005 16:51:05 +0200 Subject: How can I encode something in base32 preferably very fast? In-Reply-To: References: Message-ID: <1122303065.6154.3.camel@phantom.wg.xw3.org> On Mon, 2005-07-25 at 17:23 +0300, Elmo M?ntynen wrote: > I want to encode a plaindigest or a hexdigest in base 32. Any hints? Search Google for "python base32" isn't as hard... First result are the original python lib documentation: http://docs.python.org/lib/module-base64.html I think you need to convert to a String before encoding... Have fun, -- Johannes Findeisen http://hanez.org/ From steve at holdenweb.com Thu Jul 28 07:30:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jul 2005 12:30:23 +0100 Subject: all possible combinations In-Reply-To: <1122547119.104995.43340@o13g2000cwo.googlegroups.com> References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> <42d6de96@news.eftel.com> <1122547119.104995.43340@o13g2000cwo.googlegroups.com> Message-ID: Anton Vredegoor wrote: > John Machin wrote: > > >>You don't need to use random sampling. Paul Rubin has shown how it can >>be done deterministically. The following is a generalisation of his >>code; it generates all possible assemblies of size n from a list of >>parts. Is this helpful? >> >>def all_size_n_knickers(rqd_size, pieces): >> npieces = len(pieces) >> knicker_count = npieces ** rqd_size >> austen = [npieces ** (rqd_size-k-1) for k in xrange(rqd_size)] >> for i in xrange(knicker_count): >> knicker = [pieces[j] for j in [(i // d) % npieces for d in austen]] >> yield knicker >> >>for alist in all_size_n_knickers(4, 'abc'): >> print ''.join(alist) >> >>print >>print list(all_size_n_knickers(2, [1, 42, 666])) > > > Just testing out my ELCH JythonConsole :-) > > def unint(i,symbols): > res = [] > radix = len(symbols) > while i: > i,r = divmod(i,radix) > res.append(symbols[r]) > return res[::-1] > > start = int('10000',3) > finish = int('20000',3) > for i in range(start,finish): > print ''.join(unint(i,'abc')[1:]) > > This makes me wonder why we still don't have something like the unint > function above in the standard distribution. > Because it's not what you'd call (or, at least, it's not what I'd call) universally required. As you have shown it is relatively easy to hack something supp when it's needed, so since it isn't something that's required by the majority it hasn't been added to the library. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Florian.Lindner at xgm.de Sat Jul 9 07:49:12 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sat, 09 Jul 2005 13:49:12 +0200 Subject: Problem with sha.new Message-ID: Hello, I try to compute SHA hashes for different files: for root, dirs, files in os.walk(sys.argv[1]): for file in files: path = os.path.join(root, file) print path f = open(path) sha = sha.new(f.read()) sha.update(f.read()) print sha.hexdigest() this generates a traceback when sha.new() is called for the second time: /home/florian/testdir/testfile c95ad0ce54f903e1568facb2b120ca9210f6778f /home/florian/testdir/testfile2 Traceback (most recent call last): File "duplicatefinder.py", line 11, in ? sha = sha.new(f.read()) AttributeError: new What is wrong there? Thanks, Florian From gsakkis at rutgers.edu Thu Jul 21 20:19:34 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 21 Jul 2005 20:19:34 -0400 Subject: Returning histogram-like data for items in a list References: Message-ID: <1121991583.d3afc1984aea914bde79a8c890963f28@teranews> "Michael Hoffman" wrote: > Ric Deez wrote: > > Hi there, > > > > I have a list: > > L1 = [1,1,1,2,2,3] > > > > How can I easily turn this into a list of tuples where the first element > > is the list element and the second is the number of times it occurs in > > the list (I think that this is referred to as a histogram): > > > > i.e.: > > > > L2 = [(1,3),(2,2),(3,1)] > > >>> import itertools > >>> L1 = [1,1,1,2,2,3] > >>> L2 = [(key, len(list(group))) for key, group in itertools.groupby(L1)] > >>> L2 > [(1, 3), (2, 2), (3, 1)] > -- > Michael Hoffman This is correct if the original list items are grouped together; to be on the safe side, sort it first: L2 = [(key, len(list(group))) for key, group in itertools.groupby(sorted(L1))] Or if you care about performance rather than number of lines, use this: def hist(seq): h = {} for i in seq: try: h[i] += 1 except KeyError: h[i] = 1 return h.items() George From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 03:29:31 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 09:29:31 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kehbmFtv6lpU1@individual.net> <3khgn6Fu8nm8U1@individual.net> <3khrkkFuhpimU1@individual.net> Message-ID: <3kjimrFubvl6U2@individual.net> Andrew Dalke wrote: > Reinhold Birkenfeld wrote: >> Okay. While a path has its clear use cases and those don't need above methods, >> it may be that some brain-dead functions needs them. > > "brain-dead"? > > Consider this code, which I think is not atypical. Okay, convinced. Reinhold From martin at v.loewis.de Sun Jul 17 04:16:58 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 17 Jul 2005 10:16:58 +0200 Subject: SSL problem... SSL23_GET_SERVER_HELLO:unknown protocol In-Reply-To: References: Message-ID: <42DA13FA.3010800@v.loewis.de> John Reese wrote: > Morning. I've been running into an error message pertaining to SSL > that I don't understand, and I was hoping someone had some insight. > Gmail provides POP access over SSL on port 587, so I tried to use > poplib.POP_SSL, with the following results: [...] > socket.sslerror: (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol') > > > Any suggestions or insight? It appears that pop.gmail.com *doesn't* provide SSL on port 587. martin at mira:~/doc$ telnet pop.gmail.com 587 Trying 64.233.185.111... Connected to pop.gmail.com. Escape character is '^]'. 220 mx.gmail.com ESMTP 13sm5173422wrl This rather looks like an unencrypted SMTP connection to me. Indeed, port 587 is the mail submission protocol. Regards, Martin From sjmachin at lexicon.net Fri Jul 22 17:05:05 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 07:05:05 +1000 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <42e15f81$1@news.eftel.com> Daniel Dittmar wrote: > Duncan Booth wrote: > >> I would have expected a path object to be a sequence of path elements >> rather than a sequence of characters. > > > Maybe it's nitpicking, but I don't think that a path object should be a > 'sequence of path elements' in an iterator context. > > This means that > > for element in pathobject: > > has no intuitive meaning for me, so it shouldn't be allowed. Try this: A file-system is a maze of twisty little passages, all alike. Junction == directory. Cul-de-sac == file. Fortunately it is signposted. You are dropped off at one of the entrance points ("current directory", say). You are given a route (a "path") to your destination. The route consists of a list of intermediate destinations. for element in pathobject: follow_sign_post_to(element) Exception-handling strategy: Don't forget to pack a big ball of string. Anecdotal evidence is that breadcrumbs are unreliable. Cheers, John From mauriceling at acm.org Mon Jul 18 03:39:38 2005 From: mauriceling at acm.org (Maurice LING) Date: Mon, 18 Jul 2005 17:39:38 +1000 Subject: Java RMI-like services in Python Message-ID: Hi, I am wondering if Python has services or frameworks that does the same as Java RMI? What I am seeking is to do "pseudo-clustering". That is, a server will contains a program to control what is needed for execution. This will be pretty much like process management. Call this controller, HeadControl.py. What HeadControl.py can do is to expose a SOAP interface. Each client machine will have Executor.py. So when Executor.py is executed, it will connect to HeadControl through SOAP. HeadControl will then spawn a thread to represent the connection. Now, this part is possible in Java, but I am not sure if it is possible in Python. Executor will find out from HeadControl what it can do and downloads the corresponding objects and data from HeadControl and executes it and sends results back to HeadControl. 2 scenarios that this might work. Firstly, Executor can be part of a client program. In this case, temporary files may be written to the client's HDD. Of course, due to security, this method may not be desirable. Secondly, Executor may be made into a web applet kinda thing. In this case, writing to HDD may be impossible. I know something like this had been achieved in Java (http://www-128.ibm.com/developerworks/java/library/j-super.html) but wondering if it is possible in Python. Is so, how? Thanks. Cheers Maurice From ed at leafe.com Sun Jul 31 20:50:43 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 20:50:43 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <7xvf2rync2.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <7xvf2rync2.fsf@ruckus.brouhaha.com> Message-ID: <200507312050.43863.ed@leafe.com> On Sunday 31 July 2005 12:03, Paul Rubin wrote: > How on earth did you decide that, since tkinter actually runs out of > the box when you install Python on most platforms, and wxPython doesn't? Because Tkinter looked like crap on OS X. Sorry, but it's hard to sell an application that looks bad. Our target for the framework is to build cross-platform apps that look native on each platform. Tkinter didn't measure up in that regard. > I can't even think about trying out Dabo unless I'm willing to go through > some enormous pain of getting wxPython to work. There are step-by-step instructions on the wxPython site for building it if you need to go that route. There are also pre-built binaries for many platforms. On my Ubuntu system, the Synaptic Package Manager installed it with a couple of mouse clicks. Hey, if this is really too difficult for you, fine. But I don't think it's fair to insist that everyone else follow your particular preferences in Python. The only one who gets to do that is Guido, and he's already endorsed wxPython, and that's good enough for me and most of the Python community. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From pydecker at gmail.com Sat Jul 30 09:53:08 2005 From: pydecker at gmail.com (Peter Decker) Date: Sat, 30 Jul 2005 09:53:08 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <87mzo4zsu4.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: On 7/30/05, Torsten Bronger wrote: > I've been having a closer look at wxPython which is not Pythonic at > all and bad documented. Probably I'll use it nevertheless. PyGTK > and PyQt may have their own advantages and disadvantages. > > However, in my opinion we don't need yet another binding so thin > that C or C++ is shining through, but a modern replacement for > Tkinter with its Pythonic way of thinking. I had the exact same impression when I started working with wxPython: it looked and ran great, but I held my nose when coding in it - it just was too un-Pythonic for my tastes. I then discovered Dabo (http://dabodev.com), which is a full application framework, but whose UI layer is a very Pythonic wrapper around wxPython. I've created several apps now using Dabo, even though I haven't even looked at the data connectivity aspects of it; the UI code works fine without it. The authors have done such a great job I'm surprised that it hasn't been more widely adopted. Its development is very active, and they have great support for their users. # p.d. From tjreedy at udel.edu Thu Jul 7 16:36:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jul 2005 16:36:29 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <11cbl3rb2alb32@news.supernews.com><1120361191.481114.134500@z14g2000cwz.googlegroups.com><1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: "Pawe? Sakowski" wrote in message news:dajghf$dit$1 at inews.gazeta.pl... Tom Anderson wrote: > def flatten(ll): > return reduce(lambda a, l: a.extend(l), ll, []) > > How would one do that as a list comp, by the way? I'm really not very > good > with them yet. Not really a list-comprehension based solution, but I think what you want is >>> ll=[[1,2],[3,4,5],[6]] >>> sum(ll,[]) [1, 2, 3, 4, 5, 6] Unless sum knows to typecheck input items and special-case lists and use list.extend rather than list+list, this turns an O(n) operation into an O(n**2) operation. Sum is meant for numbers. Terry J. Reedy From apoco at cox.net Sun Jul 10 15:32:17 2005 From: apoco at cox.net (Jacob Page) Date: Sun, 10 Jul 2005 12:32:17 -0700 Subject: Python Module Exposure In-Reply-To: <1120998768.466586.269180@g47g2000cwa.googlegroups.com> References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> <1120934851.208175.19180@f14g2000cwb.googlegroups.com> <1120975905.198149.19240@z14g2000cwz.googlegroups.com> <1120998768.466586.269180@g47g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > "Jacob Page" wrote: > >>If the union of two integers yielded a set of integers, then >>it'd make more since for the union of two Intervals to yield an >>IntervalSet. > > AFAIK union is defined over sets, not numbers, so I'm not sure what you > mean by the "union of two integers". What I'm saying is that while the > union of two intervals is always defined (since intervals are sets), > the result set is not guaranteed to be an interval. More specifically, > the result is an interval if and only if the intervals overlap, e.g. > (2,4] | [3,7] = (2,7] > but > (2,4] | [5,7] = { (2,4], [5,7] } > That is, the set of intervals is not closed under union. OTOH, the set > of intervals _is_ closed under intersection; intersecting two > non-overlapping intervals gives the empty interval. OK, you've convinced me now to support and, or, and xor between every combination of Intervals and IntervalSets, Intervals and IntervalSets, and IntervalSets and Intervals. However, I'm not sure I like the idea of an operation generating either one type or another. Thus, I'll have | and ^ operations between Intervals always return an IntervalSet instead of returning either an IntervalSet or an Interval. & will return an Interval. I suppose that means I should just have + do a union and - return an IntervalSet. It will just have to be documented which types are to be expected for the return values depending on the operands. From ed at leafe.com Wed Jul 6 21:54:50 2005 From: ed at leafe.com (Ed Leafe) Date: Wed, 6 Jul 2005 21:54:50 -0400 Subject: Python exception hook simple example needed In-Reply-To: <1120654753.122331.109950@g43g2000cwa.googlegroups.com> References: <1120654753.122331.109950@g43g2000cwa.googlegroups.com> Message-ID: On Jul 6, 2005, at 8:59 AM, Fuzzyman wrote: > Wax has a brilliant prebuilt dialog/handler. It's a wrapper over > wxPython - so you still use wxPython objects, it's jsut all a lot > easier. And don't forget Dabo, which wraps all of wxPython's dialogs into simple calls. No need to create/show/destroy; just call the appropriate function. I know I'm biased, being one of the authors, but I've used both extensively, and find Dabo so much easier to work with. And if there's a part of wxPython that we haven't wrapped yet, let us know, as we are actively working on Dabo and improving it all the time. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From titogarcia_borra_esto at gmail.com Wed Jul 27 14:12:35 2005 From: titogarcia_borra_esto at gmail.com (Tito) Date: Wed, 27 Jul 2005 20:12:35 +0200 Subject: [Beginner] Calling a function by its name in a string Message-ID: Hi all: Is there a metalanguage capability in Python (I know there are many) to call a function having its name in a string? Something like: __call__("foo") instead of: foo() Regards, Tito From elrei69 at yahoo.es Fri Jul 22 13:40:00 2005 From: elrei69 at yahoo.es (Ximo) Date: Fri, 22 Jul 2005 19:40:00 +0200 Subject: return None Message-ID: <3kcpbbFtjttlU1@individual.net> Can I do a function which don't return anything? The question is that, if I do a function that have a return or without return, it returns always "None", but i want that it doesnt return me nothing Thanks From samgurung at gmail.com Sat Jul 23 01:39:48 2005 From: samgurung at gmail.com (linuxfreak) Date: 22 Jul 2005 22:39:48 -0700 Subject: wxPython & Fedora Core 4 In-Reply-To: References: <1122005756.744692.285840@f14g2000cwb.googlegroups.com> Message-ID: <1122097188.623576.55800@o13g2000cwo.googlegroups.com> Yup rebuilt the rpms and it worked Thanks a lot guys Sybren Stuvel wrote: > Christophe Lambin enlightened us with: > > However, since your wxPython package wasn't built for FC4, you may > > run into other problems. > > That should be solved by recompiling the wxPython RPMs. > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From nyamatongwe+thunder at gmail.com Fri Jul 29 19:58:58 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 29 Jul 2005 23:58:58 GMT Subject: Block-structured resource handling via decorators In-Reply-To: References: Message-ID: <6pzGe.66374$oJ.63803@news-server.bigpond.net.au> John Perks: > When handling resources in Python, where the scope of the resource is > known, there seem to be two schools of thought: > ... This is part of what PEP 343 addresses: http://www.python.org/peps/pep-0343.html Neil From vendredi5h at gmail.com Tue Jul 12 11:28:38 2005 From: vendredi5h at gmail.com (Yannick Turgeon) Date: 12 Jul 2005 08:28:38 -0700 Subject: Web client, https and session management Message-ID: <1121182118.684389.182950@g14g2000cwa.googlegroups.com> Hello all, 2-3 years ago, I did a program in perl. Now I have to modify it and I want to rewrite it from scratch using Python. The program is doing this: 1- Load Yahoo login webpage (https) 2- Log into Yahoo website using my personal login and password. 3- Grasp and extract some information from my mailing lists messages (http, not https). My questions are: - Is it possible to do this using Python? - How? To acheive point #3, which is the goal, my web client has to manage session (because of the login aspect). This is the part I don't know how it's working. Any help would be appreciated. Thanks. Yannick From ironfroggy at gmail.com Thu Jul 28 13:06:34 2005 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 28 Jul 2005 13:06:34 -0400 Subject: Advanced concurrancy In-Reply-To: References: Message-ID: <76fd5acf050728100618a41ffd@mail.gmail.com> Twisted [1] includes lots of support for asyncronous concurrency, using deferreds. There is also the possiblity of PEP 342's [2] concurrency through enhanced generators, and being able to pass data to the generator every iteration. There are ways to simulate this, as well. I've written a recipe [3] for it over at ASPN. Personally, I like the generator approach better, because it gives a feel of threads, but with direct control of the timeslicing, a better sense of understanding, and doesn't rely on things happening in the background, like deferreds often do. On 7/28/05, Peter Tillotson wrote: > Hi, > > I'm looking for an advanced concurrency module for python and don't seem > to be able to find anything suitable. Does anyone know where I might > find one? I know that there is CSP like functionality built into > Stackless but i'd like students to be able to use a standard python build. > > I'm trying to develop distributed / Grid computing modules based on > python. The aim is to be able to use barriers for synchronisation and > channels for communication between processes running on a single box. > Then the jump to multiple processes on multiple boxes and eventually to > MPI implementations. Hopefully, each jump should not be that big a leap. > > Of course it would be nice if there was a robust way of managing > concurrency in python aswell ;-) > > p > -- > http://mail.python.org/mailman/listinfo/python-list > From greg.lindstrom at novasyshealth.com Tue Jul 26 12:47:38 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 26 Jul 2005 11:47:38 -0500 Subject: Knowing when a file completes. Message-ID: <42E6692A.3010208@novasyshealth.com> I have an odd problem that I'm sure someone here can help me solve. I am using Python 2.3 on a Linux box to process text files. At one point in my automated process, I have to zip and ship the files over to a Windows server running a proprietary package to do some manipulation to the file. Problem is that I need to know when the process completes processing the file. Complicating matters is that this package names the output file using a guid type notation, so I don't have a clue as the output filename (though I do know the output directory). We have considered running a query from the Linux box every 10 minutes or so looking for any "new" files in the windows directory, then monitoring the size of the files and when they stop growing bring them back to finish our work, but that doesn't make us feel very good. Is there a way to run a daemon (or whatever it's called on windows) to detect when a new file is created in a directory and, more importantly, when it is "complete" (if that makes sense)? Thanks for your help. --greg -- Greg Lindstrom 501 975.4859 (office) Senior Programmer 501 219-4455 (fax) NovaSys Health greg.lindstrom at novasyshealth.com Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. From siona at chiark.greenend.org.uk Thu Jul 14 10:08:36 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 14 Jul 2005 15:08:36 +0100 (BST) Subject: Consecutive Character Sequences References: <1121325469.494500.291730@z14g2000cwz.googlegroups.com> <1121343722.7ebce1b2a41714687db3ed336af5fc19@teranews> <1121344871.471781.37180@z14g2000cwz.googlegroups.com> Message-ID: <06A*5XzTq@news.chiark.greenend.org.uk> Aries Sun wrote: >I used Python 2.4.1, the following are the command lines. >But the reslut was still False. Is there anything wrong with below >codes? >>>> import itertools as it >>>> def hasConsequent(aString, minConsequent): > for _,group in it.groupby(aString): > if len(list(group)) >= minConsequent: > return True > return False Yes: return False is at the wrong indentation level. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From d0153030 at hotmail.com Mon Jul 18 20:02:42 2005 From: d0153030 at hotmail.com (Sandeep Arya) Date: Tue, 19 Jul 2005 05:32:42 +0530 Subject: How to send broadcast message over network and collect all the IP address? In-Reply-To: <42D7DB06.1050907@fastwebnet.it> Message-ID: Hello I got one reply two days back regarding this from Francesco. Thanks. I came to know that inorder to run any ARP request one need to be superuser. Is this correct? And also I came to know that on some OS like Win XP with SP2 does not go for ARP requests. Again Is this correct? In this case How to effeciently detect computers on my network? The method which can be scalable and portable... I am thinking of one method i.e. sending Broadcast packets on my network. But I do not know how can i will get the IP addresses return back. I have gone thru socket library. I found one function recvfrom(). Does this will help?? Can any body give me an idea how to use this?? Thanking You Sandeep >From: Francesco Ciocchetti >To: Sandeep Arya >CC: python-list at python.org >Subject: Re: How to send broadcast message over network and collect all the >IP address? >Date: Fri, 15 Jul 2005 17:49:26 +0200 > >Sandeep Arya wrote: > >>Hello to all >> >>Well this is my first mail on this list. I am facing a problem associated >>with collecting IP address on my network. >> >>What i thought is to send broadcast packet over the network and then >>recieving back the reply from the computers and bridges connected to my >>network and then adding their IP Address in a list. >> >>How this can be achieved? Say my computer on which application will run's >>IP is 192.168.100.254 and subnetmask is 255.255.255.0 >> >>How to do this in core Python? >> >>Sandeep >> >>_________________________________________________________________ >>7000 classifieds >>http://www.sulekha.com/classifieds/cllist.aspx?nma=IN&ref=msn -Chennai, >>Mumbai, Hyderabad Bangalore. >> >> >> >I'm leaving from office now so i can not give a more complete answer ... i >would use an ARP Request to all network address on your network and check >who answer. Check out libdnet (http://libdnet.sf.net) for a python module >implementing networking funcions. > >bye >Francesco _________________________________________________________________ Meet interesting singles like you http://match.msn.co.in/match/mt.cfm?pg=channel&tcid=234764 Sign up with Match.com From cjw at sympatico.ca Mon Jul 11 22:10:33 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 11 Jul 2005 22:10:33 -0400 Subject: Puzzled Message-ID: The snippet of code below gives the result which follows for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) > 1: name[0]= name[0] + name[1].capitalize() print '2', name name[0]= name[0].capitalize() print '3', name 1 ['logical', 'or'] 2 ['logicalOr', 'or'] 3 ['Logicalor', 'or'] I was expecting that 3 would read ['LogicalOr', 'or'] If I replace the above code with: for k in ut.keys(): name= k.split('_') print '\n1', name if len(name) > 1: name[0]= name[0].capitalize() + name[1].capitalize() print '2', name else: name[0]= name[0].capitalize() print '3', name I get the desired result. Colin W. From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 08:45:40 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 14:45:40 +0200 Subject: Python on a public library computer References: <1122035486.585382.15370@g44g2000cwa.googlegroups.com> Message-ID: Anton Vredegoor enlightened us with: > Some time ago I started a thread about it.(Google won't let me reply > to older topics so I'm starting a new topic with the same title) Why not use a proper Usenet client? > A few days ago I found a Jython console applet that can be run from > a webpage: Nice! For giggles, try "raise SystemExit()" ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From paul at boddie.org.uk Sun Jul 3 18:28:28 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Jul 2005 15:28:28 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> Message-ID: <5339b60d.0507031428.595e4fef@posting.google.com> Mike Holmans wrote in message news:... > Some of those sonorous slow talkers from the South, and majestic bass > African-Americans like James Earl Jones or Morgan Freeman, have far > more gravitas than any English accent can: to us, such people sound > monumental. Yes, get James Earl Jones together with some people speaking in (Standard) British English accents and the impression you get is almost Imperial... Paul From cam.ac.uk at mh391.invalid Sun Jul 3 20:11:08 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 04 Jul 2005 01:11:08 +0100 Subject: looping over a big file In-Reply-To: <86ekaf1pqv.fsf@bhuda.mired.org> References: <11cgnhp3j4th442@corp.supernews.com> <86ekaf1pqv.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Roy Smith writes: > >>The "right" way to do this is: >> >>for line in file ("filename"): >> whatever >> >>The file object returned by file() acts as an iterator. Each time through >>the loop, another line is read and returned (I'm sure there is some >>block-level buffering going on at a low level). > > > I disagree. That's the *convenient* way to do it, and perfectly > acceptable in many situations. But not all Python interpreters will > close the file when for loop ends. Likewise, if you get an exception > during the processing, the file may not get closed properly. Those > things may matter to you, in which case the "right" way is: > > data = open("filename") > try: > for line in data: > whatever > finally: > data.close() > > Guido has made a pronouncement on open vs. file. I think he prefers > open for opening files, and file for type testing, but may well be > wrong. I don't think it's critical. He has said that open() may be used for things other than files in the future. So if you want to be sure you're opening a file, use file(). -- Michael Hoffman From mcherm at gmail.com Tue Jul 5 14:50:07 2005 From: mcherm at gmail.com (mcherm at gmail.com) Date: 5 Jul 2005 11:50:07 -0700 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: <1120589407.845466.261180@g14g2000cwa.googlegroups.com> Ralf W. Grosse-Kunstleve wrote: > I often find myself writing:: > > class grouping: > > def __init__(self, x, y, z): > self.x = x > self.y = y > self.z = z > # real code, finally > > This becomes a serious nuisance in complex applications with long > argument lists Yes... indeed it does. This is so common that there is a standard idiom for handling it: def __init__(self, x, y, z): self.__dict__.update(locals()) sometimes with modifications to avoid setting self.self. > Therefore I propose that Python includes > built-in support for reducing the ``self.x=x`` clutter. If all you were proposing was a built-in function to make this particular idiom clearer and more reliable, then I think I'd back such a feature because the need is SO common. However, the suggestion you actually make: > def __init__(self, .x, .y, .z): > # real code right here is far too broad and introduces new syntax unnecessarily. You yourself are using a helper function (although I belive it could be done more easily than you did it): > I am actually using a simple trick:: > > adopt_init_args(self, locals()) To which you raise the following objections: > - The solution doesn't come with Python -> everybody has to reinvent. Good point. Particularly since people won't think of all the special cases (eg: classes with __slots__ defined). > - People are reluctant to use the trick since scripts become > dependent on a non-standard feature. > - It is difficult to remember which ``import`` to use for > ``adopt_init_args`` (since everybody has a local version/variety). If the implementation is only 3-4 lines long (and a simpler implementation can be), then is can simply be included inline with every script that needs to use it. > - The ``adopt_init_args(self, locals())`` incantation is hard to > remember and difficult to explain to new-comers. A better name would help with this. The need for locals() is unavoidable. But for REAL beginners, I wouldn't even bother... writing out "self.x = x" is useful for beginners since it helps make it very clear and concrete to them just what is happening. > - Inside the ``__init__()`` method, the same object has two names, > e.g. ``x`` and ``self.x``. This lead to subtle bugs a few times > when I accidentally assigned to ``x`` instead of ``self.x`` or vice > versa in the wrong place (the bugs are typically introduced while > refactoring). Hmm... I've never had that problem, myself. > - In some cases the ``adopt_init_args()`` overhead was found to > introduce a significant performance penalty (in particular the > enhanced version discussed below). Again... a different code will help here. And if execution speed is REALLY a concern, then you can just write it out the long way! > - Remember where Python comes from: it goes back to a teaching > language, enabling mere mortals to embrace programming. > ``adopt_init_args(self, locals())`` definitely doesn't live up > to this heritage. No, but "self.x = x" does. It's only when you have lots of variables or very long names that this approach becomes unwieldy. > My minimal proposal is to add an enhanced version of ``adopt_init_args()`` > as a standard Python built-in function (actual name secondary!):: I'd alter the name and the implementation, but the basic idea seems sound to me. > However, there is another problem not mentioned before: > It is cumbersome to disable adoption of selected variables. The VERY simple, VERY straightforward, VERY common behavior of "store all the arguments as like-named attributes of self" is worth having a standard idiom (and *perhaps* a built-in). But odd special cases like skipping some arguments... that calls for writing the whole thing out. I'm firmly -1 on any proposal to support skipping arguments. > When ``__slots__`` are used (cool feature!) the boilerplate problem > becomes even worse:: > > class grouping: > > __slots__ = ["keep_this", "and_this", "but_this_again"] > > def __init__(self, keep_this, and_this, but_not_this, but_this_again): > self.keep_this = keep_this > self.and_this = and_this > self.but_this_again = but_this_again > # real code, finally > > Each variable name appears four times! ** NO! ** __slots__ is *NOT* to be used except for those times when you NEED the performance advantages (mostly memory use). The simple rule is that you should *NEVER* use __slots__ (if you are in a situation where you *do* need it, then you'll know enough to understand why this advice doesn't apply to you). There should NOT be any support for auto-setting __slots__ *anywhere* in the standard library, because it would make it FAR too tempting for people to mis-use __slots__. Besides, a metaclass would be a better solution, and it can be done today with no modifications to Python. . . . All in all, I think there's SOME merit to this idea, in that this is a common enough practice that it might be nice to make it easy to type (and read). But your proposal entangles the good idea with several ideas I rather dislike, and on the whole I think it sounds rather dangerous. -- Michael Chermside From __peter__ at web.de Fri Jul 29 03:59:22 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Jul 2005 09:59:22 +0200 Subject: can list comprehensions replace map? References: Message-ID: Andrew Dalke wrote: > Steven Bethard wrote: >> Here's one possible solution: >> >> py> import itertools as it >> py> def zipfill(*lists): >> ... max_len = max(len(lst) for lst in lists) > > A limitation to this is the need to iterate over the > lists twice, which might not be possible if one of them > is a file iterator. > > Here's a clever, though not (in my opinion) elegant solution > > import itertools > > def zipfill(*seqs): > count = [len(seqs)] > def _forever(seq): > for item in seq: yield item > count[0] -= 1 > while 1: yield None > seqs = [_forever(seq) for seq in seqs] > while 1: > x = [seq.next() for seq in seqs] > if count == [0]: > break > yield x > This seems a bit more elegant, though the "replace" dictionary is > still a bit of a hack > > from itertools import repeat, chain, izip > > sentinel = object() > end_of_stream = repeat(sentinel) > > def zipfill(*seqs): > replace = {sentinel: None}.get > seqs = [chain(seq, end_of_stream) for seq in seqs] > for term in izip(*seqs): > for element in term: > if element is not sentinel: > break > else: > # All sentinels > break > > yield [replace(element, element) for element in term] Combining your "clever" and your "elegant" approach to something fast (though I'm not entirely confident it's correct): def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return while 1: yield None seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Whether we ran out of active sequences is only tested once per sequence. Fiddling with itertools is always fun, but feels a bit like reinventing the wheel in this case. The only excuse being that you might need a lazy map(None, ...) someday... Peter From dan at cellectivity.com Wed Jul 27 12:51:06 2005 From: dan at cellectivity.com (Dan) Date: Wed, 27 Jul 2005 17:51:06 +0100 Subject: Create a variable "on the fly" In-Reply-To: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Message-ID: <1122483070.27936.15.camel@localhost.localdomain> > make_variable('OSCAR', 'the grouch'); > print OSCAR; Try using "setattr". (It's in __builtins__; you don't have to import anything.) >>> print setattr.__doc__ setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. -- If builders built buildings the way programmers write programs, the first woodpecker that came along would destroy civilization. - Original author unknown From horedson at earthlink.net Tue Jul 12 15:38:43 2005 From: horedson at earthlink.net (Hank Oredson) Date: Tue, 12 Jul 2005 19:38:43 GMT Subject: Minor correction July 11, 2005 References: Message-ID: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> "edgrsprj" wrote in message news:upBAe.1915$oZ.930 at newsread2.news.atl.earthlink.net... > "edgrsprj" wrote in message > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... >> PROPOSED EARTHQUAKE FORECASTING >> COMPUTER PROGRAM DEVELOPMENT EFFORT > >> it jumps strait to the display routine and uses the entered command to > begin > > Should be the word "straight" instead of strait. What observational data are used? What are the sources of that observational data? How are those sources accessed? Is there a database to hold historical plus current data? If so, is it centralized or distributed? The project might be of interest if the data sources are rich enough, complete enough, and current enough. -- ... Hank http://home.earthlink.net/~horedson http://home.earthlink.net/~w0rli From python at rcn.com Mon Jul 18 03:53:46 2005 From: python at rcn.com (Raymond Hettinger) Date: 18 Jul 2005 00:53:46 -0700 Subject: Efficiently Split A List of Tuples References: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> Message-ID: <1121673226.458423.133380@g44g2000cwa.googlegroups.com> [Ron Adam] > Currently we can implicitly unpack a tuple or list by using an > assignment. How is that any different than passing arguments to a > function? Does it use a different mechanism? It is the same mechanism, so it is also only appropriate for low volumes of data: a, b, c = *args # three elements, no problem f(*xrange(1000000)) # too much data, not scalable, bad idea Whenever you get the urge to write something like the latter, then take it as cue to be passing iterators instead of unpacking giant tuples. Raymond From steve at REMOVETHIScyber.com.au Thu Jul 28 09:14:01 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 28 Jul 2005 23:14:01 +1000 Subject: functions without parentheses References: Message-ID: On Thu, 28 Jul 2005 00:59:51 -0700, Jerry He wrote: > Hi, > Is it possible to create a function that you can use > without parenthesizing the arguments? What problem are you trying to solve that requires this sort of syntax, and why can't it be solved with parentheses? -- Steven. From python-ml at nn7.de Sat Jul 23 12:30:02 2005 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Sat, 23 Jul 2005 18:30:02 +0200 Subject: consistency: extending arrays vs. multiplication ? Message-ID: <1122136203.26083.103.camel@localhost> Hi all, Just having started with python, I feel that simple array operations '*' and '+' don't do multiplication/addition but instead extend/join an array: a=[1,2,3] >>> b=[4,5,6] >>> a+b [1, 2, 3, 4, 5, 6] instead of what I would have expected: [5,7,9] or >>> 2*a [1, 2, 3, 1, 2, 3] Well it is consistent to strings but tolerating string-operations to be special is ok to me as "a" + "b" -> 'ab' :) Why not make it another function like a.stretch() or a.expand() and a.extend() is there doing the same anyway and is more readable... Putting this in a larger view: Ufuncs are very reasonable sin(a), etc ... all that won't work because of that '+','*' syntax. Ok I can use numarray for that, but seeing its PEP and a possible inclusion into python at some point that inconsistency is giving me quite some headache... Will that change in the future ? Or is this 100*[0] syntax put into stone for all ages ? Best, Soeren. PS: As I am very new to python please forgive/correct me! From pinard at iro.umontreal.ca Tue Jul 12 09:38:10 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 12 Jul 2005 09:38:10 -0400 Subject: automatically assigning names to indexes In-Reply-To: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> Message-ID: <20050712133810.GA5760@alcyon.progiciels-bpi.ca> [simonwittber at gmail.com] > I know its been done before, but I'm hacking away on a simple Vector > class. [...] However, I'd like to add attribute access (magically), > so I can do this: [...] Has anyone got any ideas on how this might be > done? I needed something this last week, while toying with rotations. Allow me to humbly offer my solution, meant for more than one class. Yet for brievety, I'm limiting my example to a single class. A few constructors are used in the example, but the corresponding classes are missing. I hesitated a bit between having my rotation objects be modifiable or not, and finally opted for the later (consequently, the constructor is neatly called for a resulting object). If you really want a modifiable object, derive from `list' instead of deriving from `tuple', rename `NamedTuple' into `NamedList', and wihin sub-classes, initialise your object with `__init__(self, ...)' rather than with `__new__(cls, ...)'. __metaclass__ = type import math # Almost zero, but not yet. epsilon = 1e-9 from math import pi half_pi = .5*pi class NamedTuple(tuple): class __metaclass__(type): def __new__(cls, name, bases, definitions): self = type.__new__(cls, name, bases, definitions) if hasattr(self, '__names__'): def make_property(index): def getter(self): return self[index] return property(getter) for index, name in enumerate(self.__names__): setattr(self, name, make_property(index)) return self class Quaternion(NamedTuple): __names__ = 'w', 'x', 'y', 'z' def __new__(cls, w, x, y, z): l = 1./math.sqrt(w*w + x*x + y*y + z*z) return cls.new(w*l, x*l, y*l, z*l) def new(cls, w, x, y, z): if w < 0.: self = tuple.__new__(cls, (-w, -x, -y, -z)) else: self = tuple.__new__(cls, (w, x, y, z)) assert self.is_normal(), self return self new = classmethod(new) def is_normal(self): # For debugging only. w, x, y, z = self return abs(w*w + x*x + y*y + z*z - 1.) < epsilon and w >= 0. def __eq__(self, other): w1, x1, y1, z1 = self w2, x2, y2, z2 = other return abs(w1-w2) + abs(x1-x2) + abs(y1-y2) + abs(z1-z2) < epsilon def __ne__(self, other): return not self == other def __mul__(self, other): w1, x1, y1, z1 = self w2, x2, y2, z2 = other return Quaternion.new(w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2, w1*y2 + y1*w2 - x1*z2 + z1*x2, w1*z2 + z1*w2 + x1*y2 - y1*x2) def __div__(self, other): w1, x1, y1, z1 = self w2, x2, y2, z2 = other return Quaternion.new( w1*w2 + x1*x2 + y1*y2 + z1*z2, -w1*x2 + x1*w2 - y1*z2 + z1*y2, -w1*y2 + y1*w2 + x1*z2 - z1*x2, -w1*z2 + z1*w2 - x1*y2 + y1*x2) def __rdiv__(self, other): if not isinstance(other, (int, long, float)): raise TypeError("unsupported operand type(s) for /") w, x, y, z = self return Quaternion.new(w, -x, -y, -z) __truediv__ = __div__ __rtruediv__ = __rdiv__ def euler(self): w, x, y, z = self x2 = x + x y2 = y + y z2 = z + z xx2 = x2*x yy2 = y2*y zz2 = z2*z wx2 = x2*w wy2 = y2*w wz2 = z2*w xy2 = x2*y yz2 = y2*z zx2 = z2*x siny = wy2 - zx2 if abs(abs(siny) - 1) > epsilon: return Euler.new(math.asin(siny), math.atan2(yz2 + wx2, 1. - xx2 - yy2), math.atan2(xy2 + wz2, 1. - yy2 - zz2)) if siny > 0.: y = half_pi else: y = -half_pi return Euler.new(math.atan2(-(yz2 - wx2), 1. - xx2 - zz2), y, 0.) def matrix(self): w, x, y, z = self x2 = x + x y2 = y + y z2 = z + z xx2 = x2*x yy2 = y2*y zz2 = z2*z wx2 = x2*w wy2 = y2*w wz2 = z2*w xy2 = x2*y yz2 = y2*z zx2 = z2*x return Matrix(1. - yy2 - zz2, xy2 + wz2, zx2 - wy2, xy2 - wz2, 1. - xx2 - zz2, yz2 + wx2, zx2 + wy2, yz2 - wx2, 1. - xx2 - yy2) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From hancock at anansispaceworks.com Wed Jul 6 02:01:10 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 6 Jul 2005 01:01:10 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120590707.093007.175330@o13g2000cwo.googlegroups.com> Message-ID: <200507060101.10594.hancock@anansispaceworks.com> On Tuesday 05 July 2005 06:57 pm, Steven D'Aprano wrote: > On Tue, 05 Jul 2005 12:11:47 -0700, mcherm wrote: > > > And besides, "def" isn't a "magic" word... it's an abreviation for > > "define"... > > Really? I thought it was an abbreviation for "definition". As in, > "definition of MyFunc is..." Does it matter? But no, "define" is correct, because the def keyword is active. It is *not* a declaration of a function but a command to define one then and there. > > I hope that any student who didn't understand a word as > > common as "define" wouldn't have graduated from our school. > > How about tuple? It's a generalization rather than a specialization: double (or couple) triple quadruple quintuple sextuple septuple octuple nontuple ... Maybe a wee bit less obvious, but still understandable. Besides, the existence of another poor choice of words wouldn't make the first one any better, would it? If you are arguing that "lambda" is the "right and proper" word for this operator that Python should use, I still will have to disagree. OTOH, if you just want the functionality of lambda to remain, I must say I agree. It's a useful construct. But it *is* poorly named. It really stands out as the least intuitive keyword in the language, IMHO. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From flupke at nonexistingdomain.com Wed Jul 20 02:30:52 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 20 Jul 2005 06:30:52 GMT Subject: Web Framework Reviews In-Reply-To: References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> Message-ID: Dave Cook wrote: > On 2005-07-19, istvan.albert at gmail.com wrote: > > >>On the other hand I even in its current form I don't see how I would to >>the simple things that I need every day. Create a session, set a >>cookie, redirect to another url, perform HTTP autentication, create >>filter, use another templating language? This is also integral part of >>the functionality that I expect from an web framework. Web specific >>things exposed in some python ic way. > > > Take a look at the Nevow FAQ and examples. Also, Nevow sits on top of > Twisted, so you have all of Twisted's features available. > > http://divmod.org/users/wiki.twistd/nevow/moin.cgi/FrequentlyAskedQuestions > > Dave Cook One could use twisted.web2 also without the nevow part. The docs @ http://twistedmatrix.com/projects/web2/documentation/ are very clear and it contains a good example at the end. Benedict From gsakkis at rutgers.edu Fri Jul 1 12:49:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 09:49:08 -0700 Subject: is there a better way to walk a file system? References: <1120230335.548382.96880@z14g2000cwz.googlegroups.com> Message-ID: <1120236548.823249.119300@z14g2000cwz.googlegroups.com> "Peter Hansen" wrote: > ina wrote: > > I want to walk a folder structor and group all the files by extention. > > > Here is the code I put together is there a better way of doing this? > > > > [snip] > > If you were to download Jason Orendorff's "path" module, which is a > convenient single-file package that vastly simplifies all manner of > dealings with directory and file names, I suspect your example code > could be reduced to less than half the number of lines it now uses, and > with a corresponding increase in readability and maintainability. Well, it's exactly half non-blank lines (10) and still readable; of course it can be compressed more but we're not doing perl here . import sys from path import path from itertools import groupby def getExtension(aPath): return aPath.ext root = len(sys.argv) > 1 and sys.argv[1] or '.' for ext,iterFiles in groupby(sorted(path(root).walkfiles(), key=getExtension), getExtension): print "%s: %d files" % (ext, len(tuple(iterFiles))) By the way, from this example I discovered that properties cannot be unbound, i.e. using path.ext instead of getExtension raises TypeError. Couldn't/shouldn't Class.prop(instance) be allowed as equivalent of instance.prop, just as methods ? > The answer to the question "is there a better way of doing this?" in > relation to paths is always "yes, use Jason Orendorff's path module". > > -Peter George From lamthierry at gmail.com Fri Jul 22 15:15:21 2005 From: lamthierry at gmail.com (Thierry Lam) Date: 22 Jul 2005 12:15:21 -0700 Subject: Mapping a drive to a network path Message-ID: <1122059720.962075.53260@g44g2000cwa.googlegroups.com> In DOS, if I want to map a network path to a drive, I do the following: net use z: \\computer\folder How do we do something similar in python? Thanks Thierry From henryho at NO__SPAMM_.telus.net Fri Jul 29 01:56:53 2005 From: henryho at NO__SPAMM_.telus.net (fanbanlo) Date: Fri, 29 Jul 2005 05:56:53 GMT Subject: monitor a folder for file creation, how? In-Reply-To: <1122606386.971460.250100@g14g2000cwa.googlegroups.com> References: <86ack6l4vm.fsf@bhuda.mired.org> <1122606386.971460.250100@g14g2000cwa.googlegroups.com> Message-ID: SUPER! This is exactly what I'm looking for. gene tani wrote: > win32: (I posted this link in response to same question, um, day bef. > yesterday) > > http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/9a1c7629db72d064/56008cb68eeffa23?hl=en#56008cb68eeffa23 > (Thanks to Tim Golden for collecting the info) > > OS X: I dunno... > From brian at sweetapp.com Fri Jul 15 08:30:51 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 15 Jul 2005 14:30:51 +0200 Subject: Python Programming Contest In-Reply-To: <797fe3d40507150525659d5ec6@mail.gmail.com> References: <42D780EF.6020809@sweetapp.com> <17111.39597.277505.234455@montanaro.dyndns.org> <42D7A188.2010306@sweetapp.com> <797fe3d40507150525659d5ec6@mail.gmail.com> Message-ID: <42D7AC7B.2020709@sweetapp.com> Bill Mill wrote: > On 7/15/05, Brian Quinlan wrote: > >>skip at pobox.com wrote: >> >>> Brian> I've decided that it would be be fun to host a weekly Python >>> Brian> programming contest. The focus will be on algorithms that require >>> Brian> a bit of thought to design but not much code to implement. >>> >>>For some of us that's what we do day-in, day-out at work. It's just not >>>called a contest. To make it more challenging, we sometimes leave out the >>>"bit of thought" part. ;-) >> >>Hmmm...I find that I am rarely faced with challenging algorithmic >>problems in my day-to-day work. I continuously face difficult design >>decisions but that is a difficult sort of beast all together. >> >>This contest is for people who like thinking about algorithms. >> >>Cheers, >>Brian >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > > Questions: > > Will that random test generator (included in the download) be used to > perform the actual testing? Yes. With two caveats: 1. I will pick the seed ahead of time so everyone gets the same problem set 2. I will use a local copy of the verification code (for performance reasons) > How many tests will be run on each > program? Probably a few thousand. If I need more to discriminate between two very similar solutions, then I will do so. > What is the penalty for a wrong answer? Infinite. Only correct solutions will be judged on performance. > PS - check out http://www.sleepinginairports.net/ before you say you > can't sleep in the airport :) Nice :-) Cheers, Brian From mwh at python.net Fri Jul 15 05:10:15 2005 From: mwh at python.net (Michael Hudson) Date: Fri, 15 Jul 2005 09:10:15 GMT Subject: math.nroot [was Re: A brief question.] References: Message-ID: Tim Peters writes: > [Tim] > >> Ah, but as I've said before, virtually all C compilers on 754 boxes > >> support _some_ way to get at this stuff. This includes gcc before C99 > >> and fenv.h -- if the platforms represented in fpectlmodule.c were > >> happy to use gcc, they all could have used the older gcc spellings > >> (which are in fpectlmodule.c, BTW, under the __GLIBC__ #ifdef). > > [Michael] > > Um, well, no, not really. The stuff under __GLIBC___ unsurprisingly > > applies to platforms using the GNU project's implementation of the C > > library, and GCC is used on many more platforms than just that > > (e.g. OS X, FreeBSD). > > Good point taken: parings of C compilers and C runtime libraries are > somewhat fluid. > > So if all the platforms represented in fpectlmodule.c were happy to > use glibc, they all could have used the older glibc spellings. > Apparently the people who cared enough on those platforms to > contribute code to fpectlmodule.c did not want to use glibc, though. It may not have been possible for them, after a little googling. It seems that while glibc is theoretically portable to systems other than linux, in practice it ain't. > In the end, I still don't know why there would be a reason to hope > that an endless variety of other libms would standardize on the C99 > spellings. Point. But as you said in the post I replied to, soon (maybe even now) there won't be an "endless variety of other libms" to worry about. > > ... > > Even given that, the glibc section looks mighty Intel specific to me (I don't > > see why 0x1372 should have any x-architecture meaning). > > Why not? I don't know whether glibc ever did this, but Microsoft's > spelling of this stuff used to, on Alphas (when MS compilers still > supported Alphas), pick apart the bits and rearrange them into the > bits needed for the Alpha's FPU control registers. Well, I considered that but decided that it was far too insane. Maybe that was insufficient cynicism :) In any case, glibc's docs today only mention the C99 (and C99-like, for setting traps) interfaces, and I can't be arsed to go through old docs to see if _FPU_SETCW or __setfpucw were ever documented and if so what they were documented to do. > > One thing GCC doesn't yet support, it turns out, is the "#pragma STDC > > FENV_ACCESS ON" gumpf, which means the optimiser is all too willing to > > reorder > > > > feclearexcept(FE_ALL_EXCEPT); > > r = x * y; > > fe = fetestexcept(FE_ALL_EXCEPT); > > > > into > > > > feclearexcept(FE_ALL_EXCEPT); > > fe = fetestexcept(FE_ALL_EXCEPT); > > r = x * y; > > > > Argh! Declaring r 'volatile' made it work. > > Oh, sigh. One of the lovely ironies in all this is that CPython > _could_ make for an excellent 754 environment, precisely because it > does such WYSIWYG code generation. One of my motivations here (other than the instantly discountably one of aesthetic purity :) is to make Python a good system for prototyping numeric codes. > Optimizing-compiler writers hate hidden side effects, and every fp > operation in 754 is swimming in them -- but Python couldn't care > much less. Thing is, I don't see how this particular stuff should be that hard to implement -- if you have an optimizing compiler that can move code around, presumably you have some way of saying what can't be moved past what else. But you're not going to catch me diving into GCC's sources :) (In other news, passing -frounding-math to GCC may also have the desired effect, but I haven't tested this). > Anyway, you're rediscovering the primary reason you have to pass a > double lvalue to the PyFPE_END_PROTECT protect macro. > PyFPE_END_PROTECT(v) expands to an expression including the > subexpression > > PyFPE_dummy(&(v)) > > where PyFPE_dummy() is an extern that ignores its double* argument. > The point is that this dance prevents C optimizers from moving the > code that computes v below the code generated for > PyFPE_END_PROTECT(v). Since v is usually used soon after in the > routine, it also discourages the optimizer from moving code up above > the PyFPE_END_PROTECT(v) (unless the C does cross-file analysis, it > has to assume that PyFPE_dummy(&(v)) may change the value of v). > These tricks may be useful here too -- fighting C compilers to the > death is part of this game, alas. I did read those comments. Maybe passing the address of the result variable to the routine that checks the flags and decides whether to raise an exception would be a good hack (and, yes, writing that function in another file so GCC doesn't bloody well inline it and then rearrange all my code). > PyFPE_END_PROTECT() incorporates an even stranger trick, and I wonder > how gcc deals with it. The Pentium architecture made an agonizing > (for users who care) choice: if you have a particular FP trap enabled > (let's say overflow), and you do an fp operation that overflows, the > trap doesn't actually fire until the _next_ fp operation (of any kind) > occurs. You can honest-to-God have, e.g., an overflowing fp add on an > Intel box, and not learn about it until a billion cycles after it > happened (if you don't do more FP operations over the next billion > cycles). I read those comments too. One thing that I know I don't know is how the introduction of things like SSE (and particularly SSE2 and SSE3) instructions to the pentium architectures affect all this. Are they only applicable to vector stuff? > So "the other thing" PyFPE_END_PROTECT does is force a seemingly > pointless double->int conversion (it always coerces 1.0 to an int), > just to make sure that a Pentium will act on any enabled trap that > occurred before it. > > If you have in mind just testing flags (and staying away from enabling > HW traps -- and this is the course I recommend), For one thing, C99 doesn't, AFAICT, say *anything* about enabling HW traps (it seems glibc defines C99-a-like functions feenableexcept/ fedisableexcept/fegetexcept to do this). I'm not even sure how to enable HW traps in assembly on PPC (the only architecture I actually know anything about at this level) because it seems to involve twiddling bits in the Machine State Register and you can't execute the mtmsr instruction in user state (I guess there's some kernel call to do it). > this shouldn't matter (the sticky status flag is set immediately, > it's only triggering the correspondnig trap that's delayed). I > haven't studied C99 deeply enough to determine whether it has weasle > words allowing traps to be delayed indefinitely, but that kind of > HW-driven compromise is common in the C standards. See above, maybe. > Not to imply that this isn't all dead easy . Heh. Cheers, mwh -- SamB: PHP's basic control structure is the "database timeout error". -- from Twisted.Quotes From charles.gunyon at gmail.com Mon Jul 4 08:07:41 2005 From: charles.gunyon at gmail.com (Charlie) Date: Mon, 4 Jul 2005 07:07:41 -0500 Subject: Obtaining glyph width in Python Message-ID: <20050704120741.GA10605@breeder.domain.actdsltmp> Hi, I'm looking for a way to obtain the width of a string, either in actual inches/centimeters, or pixels will also work. Unfortunately this seems difficult as I'd like to keep things as close to the stock Python install as possible, and I'm not working with Graphics or X at all. Here are the options I've found, and why they're less than optimal for my use: PIL = Huge for only using one function. I'm not working with any graphics. PyFT = Everyone uses FreeType2 now, and PyFT seems dead anyhow. PyFT2 = Does not exist. tkinter.text() = Works with X, creates windows no matter what you do. t1lib = Separate package, no TTF support. t1python = Same thing as t1lib? Ultimately, I'm looking to take a stream of text, and break it up into lines based on page width... and I need to know how wide (and ultimately how tall, for page breaks) the individual glyphs are so I can break properly. If there's an easier way to do this than calculating individual glyph width, I'm open to that too. I was really just looking to see if there was anything out there that wasn't too large or too obscure/dated. Maybe there's something lower level that could be done to achieve this? Is there metadata in the font that holds this information that could be extracted? Thanks in advance, -Charlie From mail.python.org at bdash.net.nz Mon Jul 25 09:02:06 2005 From: mail.python.org at bdash.net.nz (Mark Rowe) Date: Tue, 26 Jul 2005 01:02:06 +1200 Subject: Getting the --options of configure on installed python In-Reply-To: <20050724215607.GA9086@zermelo.sians.org> References: <20050724215607.GA9086@zermelo.sians.org> Message-ID: <18573008-0568-4EF5-A02B-A5E4F27C4A0B@bdash.net.nz> On 25/07/2005, at 09:56 , Thanos Tsouanas wrote: > Hello! > > Is there a way to get the --options with which python was > configured on > a system? > > Thanks in advance. Hi Thanos, Take a look at the distutils.sysconfig module (): >>> import distutils.sysconfig >>> distutils.sysconfig.get_config_var('CONFIG_ARGS') "'--prefix=/opt/local' '--enable-shared' '--mandir=/opt/local/share/ man' '--bindir=/opt/local/bin' '--with-readline' '--enable-framework' '--enable-ipv6' '--enable-tk'" >>> Kind Regards, Mark Rowe From supercomputer at gmail.com Mon Jul 11 16:47:22 2005 From: supercomputer at gmail.com (supercomputer at gmail.com) Date: 11 Jul 2005 13:47:22 -0700 Subject: Parsing Data, Storing into an array, Infinite Backslashes Message-ID: <1121114842.623294.156790@g44g2000cwa.googlegroups.com> I am using this function to parse data I have stored in an array. This is what the array looks like: [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed', 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0', 'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0', 'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory', '1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'], ['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'], ['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary', '0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2', 'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2', 'Slot', 'DIMM2/J13'], ['Memory', '2', 'ConfigurationType', '2'], ['Memory', '3', 'Summary', '0'], ['Memory', '3', 'Speed', 'PC3200U-30330'], ['Memory', '3', 'Type', 'DDR SDRAM'], ['Memory', '3', 'Size', '512'], ['Memory', '3', 'Slot', 'DIMM3/J14'], ['Memory', '3', 'ConfigurationType', '2']] This is the code to parse the array: count=0 place=0 query=[] while 1: try: i=fetch.next() except StopIteration: break if i[1] != count: ++count query.append(count) qval=`query[count]` query[count]=qval+i[2]+"="+i[3]+", " print qval,"\n" When it runs I get an output similar to this. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Type=DDR SDRAM, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Size=512, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Slot=DIMM2/J13, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'ConfigurationType=2, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'Summary=0, \\\\\\\\\\\\\\\'Speed=PC3200U-30330, \\\\\\\'Type=DDR SDRAM, \\\'Size=512, \'Slot=DIMM3/J14, ' When it's supposed to print just the plain text with the numbers etc. I have changed these lines: qval=`query[count]` query[count]=qval+i[2]+"="+i[3]+", " To this: query[count]=query[count]+i[2]+"="+i[3]+", " I get this error: Traceback (most recent call last): File "infnode.py", line 60, in ? query[count]=query[count]+i[2]+"="+i[3]+", "TypeError: unsupported operand type(s) for +: 'int' and 'str' So I try and fix it by doing this: query[count]=`query[count]`+i[2]+"="+i[3]+", " Can someone please point me in the right direction I am sure that the `query[count]` is causing the backslashes. Thanks in advance. From prabapython at yahoo.co.in Fri Jul 8 02:49:25 2005 From: prabapython at yahoo.co.in (praba kar) Date: Fri, 8 Jul 2005 07:49:25 +0100 (BST) Subject: mail sending using telnet in python In-Reply-To: Message-ID: <20050708064925.25070.qmail@web8408.mail.in.yahoo.com> Dear All, Normally we can send mail using telnet in linux. In the following way [~user]telnet Ipaddress 25 mail from: raj at rajkumar.com 250 o.k(response of from commandline) rcpt to: test at oops.co.in 250 o.k(response of from commandline) data 354 go ahead(response of from commandline) Hello world(message to send) . 250 ok 1120805818 qp 1463 Is it possible to run same thing same manner in python? If possible kindly help me with specimen code. Actually I gone through telnetlib module documentation but I cann't get solution for it. regards prabahar __________________________________________________________ Free antispam, antivirus and 1GB to save all your messages Only in Yahoo! Mail: http://in.mail.yahoo.com From http Sun Jul 31 19:24:30 2005 From: http (Paul Rubin) Date: 31 Jul 2005 16:24:30 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> <7xvf2rync2.fsf@ruckus.brouhaha.com> <87r7dfymy1.fsf@wilson.rwth-aachen.de> Message-ID: <7xiryq5zkh.fsf@ruckus.brouhaha.com> Paul McNett

writes: > Admittedly, installing from source is more difficult than any other > project I've found, I'm not interested in installing from non-source. If I wanted to do that, I'd buy a Macintosh instead of dealing with Linux. > but still doable. I'm sure I could have gotten it to work with sufficient time spent and teeth gnashing, but I just didn't care enough, and had more important things to do. From mwm at mired.org Sun Jul 3 00:43:38 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 00:43:38 -0400 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <42C7067E.4090609@anvilcom.com> Message-ID: <86d5q033et.fsf@bhuda.mired.org> Terry Hancock writes: > This is true in the same sense that Python is unnecessary > because all programs can be written in assembler. Or machine > code for that matter. Entered by flipping switches, even -- throw > away that keyboard. > > I have actually seen this done, BTW. Even though I'm theoretically > too young. ;-) I've actually done this. But the real point of having switches to flip isn't so you can enter programs - it's so you can interrupt the kernel should you drop it into a tight loop. You poke an invalid op code into the middle of the loop, and let it panic. I've actually seen this done as well. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gkj at gregorykjohnson.com Sat Jul 2 07:42:18 2005 From: gkj at gregorykjohnson.com (Gregory K. Johnson) Date: Sat, 2 Jul 2005 07:42:18 -0400 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> References: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> Message-ID: <20050702114218.GA4248@andy.gregorykjohnson.com> On Sat, Jul 02, 2005 at 03:04:09AM -0700, Ralf W. Grosse-Kunstleve wrote: [...] > Minimal proposal > ---------------- > > My minimal proposal is to add an enhanced version of ``adopt_init_args()`` > as a standard Python built-in function (actual name secondary!):: > > class grouping: > > def __init__(self, x, y, z): > adopt_init_args() > # real code [...] > Enhanced syntax proposal > ------------------------ > > The exclusion problem suggests these alternatives:: > > class grouping: > > def __init__(self, self.keep_this, self.and_this, but_not_this, > self.but_this_again): > # real code right here [...] > A shorter alternative (my personal favorite since minimally redundant):: > > class grouping: > > def __init__(self, .keep_this, .and_this, but_not_this, .but_this_again): > # real code right here [...] > P.S.: If you reply to this message, please clearly separate > naming/syntax issues from the core issue of providing built-in support > designed to reduce clutter. I share many of the qualms of those who responded to your earlier post. (Is this really a problem? Can't a good editor save you the typing? Explicit is better than implicit, and all that.) But it also occurs to me to ask: Is a function-definition syntax extension really appropriate when it's only likely usefulness is for the particular function called __init__()? That seems more un-Pythonic to me than straightforward, idiomatic, but somewhat verbose boilerplate. An adoptargs([excluded=None]) builtin or similar seems much more viable. (Although even there I don't feel any pressing need: I'm content with "self.x = x".) -- Gregory K. Johnson From scrimp212 at yahoo.com Fri Jul 22 09:26:57 2005 From: scrimp212 at yahoo.com (scrimp) Date: 22 Jul 2005 06:26:57 -0700 Subject: is this possible? Message-ID: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> Is it possible to print a PDF file using python without having acrobat reader installed on the machine?? From accepted at ukr.net Sun Jul 31 03:31:30 2005 From: accepted at ukr.net (Michael Rybak) Date: Sun, 31 Jul 2005 10:31:30 +0300 Subject: 2-player game, client and server at localhost In-Reply-To: References: Message-ID: <711432940.20050731103130@ukr.net> Thank you very much for your response, and may I point out some details: >> It works synchronously, but somehow, when I play in client window, >> both client and server have 17 fps, while when playing in server >> window, server has 44 fps while client has 5, and due to forced >> synchronization, they both run very slowly (I wonder how come server >> says it has 44fps?). >> DLB> Well, for a 2 player game of this sort, I'd think there should DLB> be one server and TWO clients... It sounds more like you have a DLB> master-slave arrangement with the slave forced to synchronize to the DLB> master. Yes, that's what I have. I was already told I should have 1 server and 2 clients, well I will, but I'd really like to make it work the master-slave way now. DLB> If you are running on Windows, Yes, I am To answer the rest of your message: the "client" and "server" (C and S below) are actually equal in my implementation. They both compute everything. I was told it's not smart to do that, but I can't see why is it better to have server compute everything: there are only 2 players, and there's quite not much computations, while transferring current status is much more traffic-consuming than simply transferring user motions. Below I outline what S and C do: S: loop draw screen accept player1 input from mouse/kbd send player1 input to C process player1 input hang till C sends us player2 input process player2 input do the nasty computations :) end loop C: loop draw screen hang till S sends us player1 input process player1 input accept player2 input from mouse/kbd send player2 input to S process player2 input do the nasty computations :) end loop So you see C and S should cause equal load of CPU. By the way, yesterday a friend of mine kindly agreed to test the game online with me, and my God I was so happy to see it DID connected and we could play (yes, this is the first program in my 10+ years of programming that sends something over the web), but the speed is overwhelmingly dreadful, near 3 fps :), while my 1.2 Celeron said I had 21 fps, and his 3.0 Pentium said he had 120. He tends to think that my problem is that they both hang to wait for the input of each other, and that happens after each frame is drawn. Well, it is lame, but why does it work fine at my pc when client window is active? And another important note - he also tested 2 instances playing via localhost at his PC, and they both indeed had 35 fps, no matter which window was active. I believe he has hyperthreading turned on while I don't, but I wonder home come it wouldn't work without it? I've looked at my CPU load, and for C being active we have 45% for C/45% for S, while for S being active - 88% for S/ 11% for C :(( I'd really welcome any suggestions, please. DLB> the program with the input focus is probably running at a higher DLB> priority... So the "server", when having input focus, gets to compute DLB> lots of stuff while the client gets less CPU time... and if the DLB> client then (whenever it does a frame say) does a transaction with DLB> the server, it may do nothing while waiting for the DLB> server to respond. DLB> When the "client" has the focus, the server may be processing at DLB> lower priority, and the two only seem to match speed because the client DLB> is blocked waiting for a response from the server (allowing the server DLB> to run at full speed until it sends the response). >> Does anybody have an idea how can this be? Not that users will test 2 >> game intances communicating via localhost, but I need to make it work >> properly. DLB> Define "work properly"... It sounds like they are working DLB> properly /as coded/ and are being affected by OS priority schemes. I DLB> say "as coded" since, as I mentioned in the first paragraph, it sounds DLB> like you have your server doing double duty -- both as a client and as DLB> the server for the second client. The server should not have ANY client DLB> type interface (other than start-up and shut-down or debug override DLB> commands). All frame-based rendering should be in the clients. I also DLB> suspect that, with two clients and a server, you'd see the same behavior DLB> -- the "non-input" client will be running at a lower priority, thereby DLB> achieving a lower frame-rate. DLB> It also sounds like your server is doing something like: DLB> loop DLB> if socket has data then DLB> read socket DLB> compute new state DLB> send reply DLB> end if DLB> do nasty computation DLB> end loop DLB> This logic will suck up as much CPU time as the OS will give the DLB> program... While if the client looks like DLB> loop DLB> send data to server DLB> read reply (blocking) DLB> do nasty computation DLB> end loop DLB> then it not only has to compete for CPU time, it does nothing while DLB> waiting for the server to handle the section inside the IF block. DLB> But what would happen if you put something like os.sleep(0.025) DLB> inside the loops? Assuming the loop takes 0.025sec to process, the total DLB> comes to 0.05 seconds (20fps) AND releases the CPU for the other process DLB> to compute. DLB> -- DLB> > ============================================================== < DLB> > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < DLB> > wulfraed at dm.net | Bestiaria Support Staff < DLB> > ============================================================== < DLB> > Home Page: < DLB> > Overflow Page: < -- Best Regards, Michael Rybak mailto:accepted at ukr.net From peter at engcorp.com Wed Jul 20 18:44:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Jul 2005 18:44:13 -0400 Subject: is this pythonic? In-Reply-To: References: <42DE4F67.7030300@mage.hu> Message-ID: Terry Reedy wrote: >>Wow, I didn't know about enumerate. > > It is listed and explained in Lib Ref Manual, Chapter 2, on builtin > functions and types and their methods. Everyone should read at least that > much of the Lib manual. Or be sure to read the "What's New in Python X.Y" pages that are released with new versions of Python, to stay current. Then read them again a few months later. Then again when you finally get around to installing the new version (if you lag behind). And again a few months later... ;-) -Peter From mso at oz.net Fri Jul 29 16:43:05 2005 From: mso at oz.net (Mike Orr) Date: 29 Jul 2005 13:43:05 -0700 Subject: PEP on path module for standard library Message-ID: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> Michael Hoffman wrote: > I use path in more of my modules and scripts than any other third-party > module, and I know it will be very helpful when I no longer have to > worry about deploying it. Same here. An object-oriented path module is extremely useful, and makes one's code much less cluttered. I've written an enhpath module that I used in my projects, with several convenience methods and some magic behavior. It's too ambitious for the standard library, but I'd like if people could at least look at the docstring and see whether some features might be useful in Path. I'd also like to see Path made subclass-friendly so I could implement this as a subclass, and others could make other subclasses. The docstring itself could also be ported to Path. The source and test suite (py.test) are here: http://cafepy.com/quixote_extras/rex/path/enhpath.py http://cafepy.com/quixote_extras/rex/path/enhpath_test.py append "?download=1" for download-friendly format. I sent an earlier version to Jason Orendorff and he liked some of the changes and had some ideas of his own, but said he was too busy to do much implementation work, and then my further letters never got a reply. The main changes I'd like to see in Path (some of these have been made in Python CVS at nondist/sandbox/path/path.py) are: - When methods create path objects, use self.__class__() instead of Path(). This makes it possible to subclass Path. Otherwise you have to rewrite the whole thing due to the hardcoded name. - Path.cwd() should be a class method instead of a static method, for the same reason. - The constructor behavior in CVS is good. Path(''), Path.cwd(), Path() => Path.cwd(). - Need .chdir() method, otherwise you have to import os for it. - Some way to pretty-print paths embedded in lists/dicts as strings. I have a .repr_as_str class attribute that toggles this. - .ancestor(3) is the same as .parent.parent.parent, but more concise. - I saw in a thread that .name and .parent were removed. I use them very frequently, along with .ext and .namebase. I don't want to call methods for these. - '/' vs .joinpath(), no big deal. I've been using '/' because it's there. .joinpath must take multiple *args, to prevent .joinpath().joinpath() . - .joinancestor(N, *components) is a combination of .ancestor and .joinpath. If curdir is /home/joe/Webware/www, Path.cwd().joinancestor(1, 'lib') is /home/joe/Webware/lib. - Keep .lisdir() as in CVS; it acts like os.listdir(). This is useful even with paths, when you're just going to use the string basename anyway. - Who needs .open()? open(myPath) is fine. But it can stay for backward compatibility. Less important but non-controversial: - Path.tempfile(), Path.tempdir(): Create a temporary file using tempfile.mkstemp, tempfile.mkdtemp - Path.tempfileobject(): Create a temporary file object using tempfile.TemporaryFile. (Static method.) Controversial: - Delete methods and mkdir should succeed silently if the operation is already done. Otherwise you always have to put them in an if: 'if foo.exists(): foo.remove()'. - .delete_dammit() recursively deletes it, whatever it is, without you having to do the if file/if directory dance. I suppose it would need a politically correct name. which you really have to do every time you delete. - All .dirs*, .files*, .walk* methods have a symlinks flag, default True. If false, don't yield symlinks. Add .symlinks and .walksymlinks methods. This eliminates an 'if' for programs that want to treat symlinks specially. - I have a .move method that combines .rename, .renames, and .move; and a .copy method that combines .copy, .copy2, and .copytree . I'd appreciate a Cc on replies if your newsreader allows it. -- Mike Orr From smitty_one_each at bigfoot.com Tue Jul 19 06:56:17 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Tue, 19 Jul 2005 06:56:17 -0400 Subject: OO design References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: <87br4zdpym.fsf@bigfoot.com> >>>>> "chris" == chris writes: chris> I have no problem writing bits of functional code to do any chris> of the above. But for the life of me I can't see how I can chris> hook them altogether in an OO based framework that I can chris> build and extend (with more data formats, manipulations, chris> GUI etc). Chris, I echo your sentiment. My little pet project has recently grown to include a bit of an object hierarchy. I've always felt that the Java-esque byzantine pedigree for everything last class a trifle over-done. What I used to trigger factorization was whether or not I needed to branch based on data type: if input_data.type == "this": do_this() else: do_that() meant I should factor my code to: class input_data_base() pass class input_data_this(input_data_base) pass class input_data_that(input_data_base) pass With this, my project has a modest number of sensible inheritance hierarchies (two) and the code that wouldn't benefit from such retains its procedural character. OO is a great organizer, but every paradigm runs afoul of Sturgeons Law if over-driven. HTH, Chris From rkern at ucsd.edu Tue Jul 26 13:59:33 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 26 Jul 2005 10:59:33 -0700 Subject: SciPy and NetCDF In-Reply-To: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> Message-ID: skilpat at gmail.com wrote: > I am going to be doing a lot of work with large data sets stored in > various netCDF files, and after checking out the alternatives, I would > really like to go with SciPy. The problem is that SciPy offers no > native netCDF support. I have checked out pycdf at > http://pysclint.sourceforge.net/pycdf/, but it requires Numerical > Python. Is there any way to get this working with SciPy without > installing more modules? The less my sysadmin has to install the > better. We are using Python 2.2.1 (and I don't know if upgrading is an > option). Scipy requires Numeric, too. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From opengeometry at yahoo.ca Sat Jul 16 19:41:33 2005 From: opengeometry at yahoo.ca (William Park) Date: Sat, 16 Jul 2005 19:41:33 -0400 Subject: Parsing html :: output to comma delimited References: <1121540573.555193.243760@g49g2000cwa.googlegroups.com> Message-ID: samuels wrote: > Hello All, > > I am a total python newbie, and I need help writing a script. > > This is what I want to do: > > There is a list of links at http://www.rentalhq.com/fulllist.asp. Each > link goes to a page like, > http://www.rentalhq.com/store.asp?id=907%2F272%2D4425, that contains a > company name, address, phone, and fax. I want extract each page, parse > this information, and export it to a comma delimited text file, or tab > delimited. The important information in each page is: > > style="border-collapse: collapse" bordercolor="#111111" width="100%" > id="AutoNumber1"> > > > > >
>

> United Rentals Inc. >

> >

3401 Commercial Dr.  > Anchorage AK, 99501-3024 >

>

> href="http://maps.google.com/maps?q=3401+Commercial+Dr%2E Anchorage AK > 99501-3024 "> > > border="0"> >

>
>

  >

>

> Phone - 907/272-4425
> Fax - 907/272-9683

> > So from that I want output like : > > United Rentals Inc.,3401 Commercial > Dr.,Anchorage,AK,"995013024","9072724425","9072729683" > > or > > United Rentals Inc. 3401 Commercial > Dr. Anchorage AK 995013024 9072724425 9072729683 > > > I have been messing around with beautiful soup > (http://www.crummy.com/software/BeautifulSoup/index.html) but haven't > gotten very far. (specially because the html is so sloppy) > > Any help would be really appreciated! Just point me in the right > direction, what to use, examples... Thanks! I'm sure others will give proper Python solution. But, here, shell is not a bad tool. lynx -dump 'http://www.rentalhq.com/store.asp?id=907%2F272%2D4425' | \ awk '/Return to List of Rental Stores/,/To reserve an item/' | \ sed -n -e '3p;5p;10p;11p' gives me United Rentals Inc. 3401 Commercial Dr. Anchorage AK, 99501-3024 Phone - 907/272-4425 Fax - 907/272-9683 -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From allardwarrink at gmail.com Thu Jul 7 06:05:25 2005 From: allardwarrink at gmail.com (adder) Date: 7 Jul 2005 03:05:25 -0700 Subject: How to use Adobe Illustrator Export function within a Python script Message-ID: <1120730725.315038.315330@o13g2000cwo.googlegroups.com> I would like to create a script that can export ai-files to jpg-files using the export function available in Adobe Illustrator. Can someone tell me how to dispatch the illustrator com-object to make this possible and possibly provide me with some tips on how to accomplish this?! Thanks in advance All From rrr at ronadam.com Wed Jul 6 00:54:00 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 04:54:00 GMT Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com><1120565012.080020.309070@o13g2000cwo.googlegroups.com><1120590707.093007.175330@o13g2000cwo.googlegroups.com><11cloakd4glsbef@corp.supernews.com> <-8ydnZxXGOCQvlbfRVn-3Q@comcast.com> Message-ID: Terry Reedy wrote: > I also suspect that the years of fuss over Python's lambda being what it is > rather that what it is 'supposed' to be (and is in other languages) but is > not, has encourage Guido to consider just getting rid of it. I personally > might prefer keeping the feature but using a different keyword. > > Terry J. Reedy Yes, I think a different key word would help. My current favorite alternative is to put it in parentheses similar to list comprehensions and use "let". (let x,y return x+y) Or you could just explain lambda as let, they both begin with 'L', and then the colon should be read as return. So lambda x,y: x+y should be read as: let x,y return x+y I'm in the group that hadn't heard about lambda as a function before Python even after > twenty years of computer tech experience. I think presuming it's common knowledge is a mistake. Cheers, Ron From rkern at ucsd.edu Sun Jul 24 13:39:44 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 10:39:44 -0700 Subject: tuple to string? In-Reply-To: <42e381a6@news.eftel.com> References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> <42e381a6@news.eftel.com> Message-ID: John Machin wrote: > No precedence rules -> no relevance to the topic Precedence rules of other languages -> no relevance to the topic -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From john at hazen.net Sun Jul 17 17:04:38 2005 From: john at hazen.net (John Hazen) Date: Sun, 17 Jul 2005 14:04:38 -0700 Subject: Python Programming Contest In-Reply-To: <42D780EF.6020809@sweetapp.com> References: <42D780EF.6020809@sweetapp.com> Message-ID: <20050717210438.GA17650@gate2.hazen.net> * Brian Quinlan [2005-07-15 02:08]: > > You can find the first problem here: > http://www.sweetapp.com/pycontest/contest1 I have one question about the problem. Is the cost we are to minimize the cost of arriving in the target city at all, or the cost of arriving at the target city at the end of the final day of the schedule? (If you were traveling to a conference, for example, you'd have a specific arrival time, and a cost to stay in the destination city until that time. But, if you were going to sight-see, then you could arrive at any time, and begin your itinerary upon arrival.) Say I can find a combination of flights that gets me to the target at the end of day 3 for 390 units, and a combination that gets me there at the end of day 4 for 400. If you count the hostel cost from day 3 to day 4, the first combination costs 410. So, which is preferred? -John P.S. I just realized this may be answered be the test suite, but I'm still at the thinking stage. From Scott.Daniels at Acm.Org Sat Jul 9 19:15:05 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 09 Jul 2005 16:15:05 -0700 Subject: Use cases for del In-Reply-To: References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <1120825627.498017.19370@g47g2000cwa.googlegroups.com> Message-ID: <42d0529a$1@nntp0.pdx.net> Ron Adam wrote: > George Sakkis wrote: > >> I get: >> >> None: 0.549999952316 >> String: 0.498000144958 >> is None: 0.450000047684 > > > What do yo get for "name is 'string'" expressions? >>> 'abc' is 'abcd'[:3] False You need to test for equality (==), not identity (is) when equal things may be distinct. This is true for floats, strings, and most things which are not identity-based (None, basic classes). This is also true for longs and most ints (an optimization that makes "small" ints use a single identity can lead you to a mistaken belief that equal integers are always identical. >>> (12345 + 45678) is (12345 + 45678) False 'is' tests for identity match. "a is b" is roughly equivalent to "id(a) == id(b)". In fact an optimization inside string comparisons is the C equivalent of "return (id(a) == id(b) of len(a) == len(b) and ) --Scott David Daniels Scott.Daniels at Acm.Org From martin.witte at gmail.com Sat Jul 9 14:58:17 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 9 Jul 2005 11:58:17 -0700 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: <1120934674.774605.184080@g44g2000cwa.googlegroups.com> References: <1120934674.774605.184080@g44g2000cwa.googlegroups.com> Message-ID: <1120935497.365395.168900@g47g2000cwa.googlegroups.com> My shot would be to test it like this on your platform like this: #!/usr/bin/env python import datetime, time t1 = datetime.datetime.now() for i in [str(x) for x in range(100)]: if int(i) == i: i + 1 t2 = datetime.datetime.now() print t2 - t1 for i in [str(x) for x in range(100)]: try: int(i) +1 except: pass t3 = datetime.datetime.now() print t3 - t2 for me (on python 2.4.1 on Linux on a AMD Sempron 2200+) it gives: 0:00:00.000637 0:00:00.000823 From Scott.Daniels at Acm.Org Tue Jul 12 17:38:03 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 12 Jul 2005 14:38:03 -0700 Subject: Frankenstring In-Reply-To: References: Message-ID: <42d43047$1@nntp0.pdx.net> Thomas Lotze wrote: > Hi, > I think I need an iterator over a string of characters pulling them out > one by one, like a usual iterator over a str does. At the same time the > thing should allow seeking and telling like a file-like object: > > >>>>f = frankenstring("0123456789") >>>>for c in f: > > ... print c > ... if c == "2": > ... break > ... OK, frankenstring can be approximated by nothing: for c in "0123456789": print c Now if you want to do it for a file, you could do: for c in thefile.read(): .... Or, if you did not want to do a full read: def filechars(afile): for line in afile: for char in line: yield char --Scott David Daniels Scott.Daniels at Acm.Org From gene.tani at gmail.com Sat Jul 16 11:35:25 2005 From: gene.tani at gmail.com (gene tani) Date: 16 Jul 2005 08:35:25 -0700 Subject: problems with python 2.4 help In-Reply-To: <1121453444.143877.143140@g44g2000cwa.googlegroups.com> References: <1121453444.143877.143140@g44g2000cwa.googlegroups.com> Message-ID: <1121528125.063837.132780@f14g2000cwb.googlegroups.com> ipython and pyshell? http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html http://www.wxpython.org/PyManual.html From bootsch at acm.org Wed Jul 13 17:07:12 2005 From: bootsch at acm.org (Paul Boots) Date: Wed, 13 Jul 2005 23:07:12 +0200 Subject: loop problem In-Reply-To: References: Message-ID: Hi, First ;-) I don't know Tk or plot, but from looking at your code I see you want to plot a line a minute long, after that, all dots are drawn to the screen. You call > self.graph.addSet(x,y) My guess is that you have to explicitly draw to the screen using same call from graph or self? whatever Tkinter wants. Search the tkinter/tk docs for 'draw' calls. At 16:18 -0400 13/7/2005, Shankar Iyer (siyer at Princeton.EDU) wrote: >Content-Language: en >Content-Type: text/html; charset=us-ascii >Content-Disposition: inline >Content-Transfer-Encoding: 7bit > >Hi, > > First, I want to thank those who responded to my question about "the plot module" yesterday. I realize now that the question could have been vague. There is a plot module, simply called "plot," that I am using, and I guess it is not a very widely circulated plotting utility. > > Anyway, I'm a little confused by the output that I get from the following code: > >/*******************************************************************************************************/ > >from Tkinter import * >from tkSimpleDialog import * >import Pmw >import HP34401A >import plot >import time > >class Application(Frame): > > def __init__(self,master=None): > Frame.__init__(self,master) > self.pack() > self.graph = plot.plot(self) > self.beginplotting() > > def beginplotting(self): > x = [] > y = [] > i = 0 > fLastOutput = time.time() > while 1: > fTime = time.time() > if((fTime-fLastOutput) >= 2): > i += 1 > x.append(fTime) > y.append(2*fTime) > self.graph.addSet(x,y) > fLastOutput = fTime > if(i>=30):break > >app = Application() >app.mainloop() > >/*******************************************************************************************************/ > >This is supposed to plot a point every two seconds. When it actually runs, it instead stores all the data points and then plots them after 30 data points have been taken. I'm fairly certain that this is not due to the use of the plot class. If I have the program instead write each time into a Tkinter Text widget, the same type of thing happens. That is, the program stores all 30 times in memory and then dumps them into the Text widget at the end. Since I have written the code so that it plots (or writes to the Text widget) every two seconds, I am confused as to why this is happening. > >Shankar > > >-- >http://mail.python.org/mailman/listinfo/python-list -- Vriendelijke groet, Paul From haeghen at xs4all.nl Sun Jul 10 07:28:27 2005 From: haeghen at xs4all.nl (sudoku) Date: Sun, 10 Jul 2005 13:28:27 +0200 Subject: [ANNOUNCE] pysudoku 0.1 References: Message-ID: <42d10664$0$7593$e4fe514c@news.xs4all.nl> Thanks Glenn, I added your link to our Sudoku Links List: http://sudoku.jouwpagina.nl Xander "Glenn Hutchings" schreef in bericht news:pan.2005.07.08.18.03.28.76853 at pillock.freeserve.co.uk... > Announcing PySuDoku version 0.1, yet another Sudoku program written in > Python. But this one has features that I don't see in any of the others: > > * Cute interactive solving mode via Tkinter. > * Puzzle generation option, for making your own puzzles. > * Nicely packaged for installation via distutils. > > Sudoku, for the remaining 27 people in the world who don't know already, > is > a logic puzzle where you have to fill in the numbers in a 9x9 grid so that > each row, column and 3x3 box has exactly one of the numbers 1-9 in them. > > You can get pysudoku at: > > http://www.freewebtown.com/zondo/programs > From hancock at anansispaceworks.com Fri Jul 1 22:26:29 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 21:26:29 -0500 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: <42C5D0D8.7080500@po-box.mcgill.ca> References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <42C5D0D8.7080500@po-box.mcgill.ca> Message-ID: <200507012126.29280.hancock@anansispaceworks.com> On Friday 01 July 2005 06:25 pm, Brian van den Broek wrote: > All in all, I wish I'd not hit send in the first place. This is > perilously close to sending me into fits ;-) Well, I thought it was funny, anyway. Of course, not when you have to explain it. ;-) I guess you just have to have a strong sense of humor to appreciate it. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From teoryn at gmail.com Sun Jul 24 23:44:08 2005 From: teoryn at gmail.com (teoryn) Date: 24 Jul 2005 20:44:08 -0700 Subject: Problem loading a file of words Message-ID: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> I've been spending today learning python and as an exercise I've ported a program I wrote in java that unscrambles a word. Before describing the problem, here's the code: *--beginning of file--* #!/usr/bin/python # Filename: unscram.py def sort_string(word): '''Returns word in lowercase sorted alphabetically''' word = str.lower(word) word_list = [] for char in word: word_list.append(char) word_list.sort() sorted_word = '' for char in word_list: sorted_word += char return sorted_word print 'Building dictionary...', dictionary = { } # Notice that you need to have a file named 'dictionary.txt' # in the same directory as this file. The format is to have # one word per line, such as the following (of course without # the # marks): #test #hello #quit #night #pear #pare f = file('dictionary.txt') # This loop builds the dictionary, where the key is # the string after calling sort_string(), and the value # is the list of all 'regular' words (from the dictionary, # not sorted) that passing to sort_string() returns the key while True: line = f.readline() if len(line) == 0: break line = str.lower(line[:-1]) # convert to lowercase just in case and # remove the return at the end of the line sline = sort_string(line) if sline in dictionary: # this key already exist, add to existing list dictionary[sline].append(line) print 'Added %s to key %s' % (line,sline) #for testing else: # create new key and list dictionary[sline] = [line] print 'Created key %s for %s' % (sline,line) #for testing f.close() print 'Ready!' # This loop lets the user input a scrambled word, look for it in # dictionary, and print all matching unscrambled words. # If the user types 'quit' then the program ends. while True: lookup = raw_input('Enter a scrambled word : ') results = dictionary[sort_string(lookup)] for x in results: print x, print if lookup == 'quit': break *--end of file--* If you create dictionary.txt as suggested in the comments, it should work fine (assumeing you pass a word that creates a valid key, I'll have to add exceptions later). The problem is when using a large dictionary.txt file (2.9 MB is the size of the dictionary I tested) it always gives an error, specifically: (Note: ccehimnostyz is for zymotechnics, which is in the large dictionary) *--beginning of example--* Enter a scrambled word : ccehimnostyz Traceback (most recent call last): File "unscram.py", line 62, in ? results = dictionary[sort_string(lookup)] KeyError: 'ccehimnostyz' *--end of example--* If you'd like a copy of the dictionary I'm using email me at teoryn at gmail dot com or leave your email here and I'll send it to you (It's 702.2 KB compressed) Thanks, Kevin From diesch at spamfence.net Wed Jul 13 10:21:32 2005 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 13 Jul 2005 16:21:32 +0200 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' References: Message-ID: <20050713142132.1BD8.6.NOFFLE@dieschf.news.arcor.de> Ric Da Force wrote: > I have a string such as 'C1, C2, C3'. Without assuming that each bit of > text is of fixed size, what is the easiest way to change this list so that > it reads: > 'C1, C2 and C3' regardless of the length of the string. >>> import re >>> data = "the first bit, then the second, finally the third" >>> re.sub(r"(.*),", r"\1 and", data) 'the first bit, then the second and finally the third' >>> Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From rbt at athop1.ath.vt.edu Wed Jul 13 10:21:19 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 13 Jul 2005 10:21:19 -0400 Subject: all possible combinations Message-ID: <1121264479.26249.6.camel@athop1.ath.vt.edu> Say I have a list that has 3 letters in it: ['a', 'b', 'c'] I want to print all the possible 4 digit combinations of those 3 letters: 4^3 = 64 aaaa abaa aaba aaab acaa aaca aaac ... What is the most efficient way to do this? From thomasbartkus at comcast.net Mon Jul 18 13:45:28 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 18 Jul 2005 12:45:28 -0500 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: "windozbloz" wrote in message news:gJQCe.8759$2h1.1968 at trnddc05... > Bye Bye Billy Bob... > > I'm back with one more question, then I'll chill. I have scoured the news > and net for info about Borlands KYLIX 3 and have found little technical > info about it. Their screen shots are very impressive, similar to Visual > Basic. I have sent several emails to Borlands Sales and Pre-Sales > departments. Pre-Sales bounces and Sales won't answer. I'm sitting here > with money in hand ready to buy but not from a company that won't give me > the time of day. > > Does anyone of you have experiance with KYLIX 3 and do you think I should > consider buying it? Thank You, I'll go oil my keyboard now. Good question! Wither Borland? My impression (second hand - based on no direct experience with Kylix!) is that Borlands wonderful Delphi product ported to Linux has been a dissapointment. * * * Someone with real experience on Kylix - please jump in here! Calling Delphi "similar to Visual Basic" is hurtful because I believe that VB is the product of looting and pillaging the talent that came out of Borland. I'm guessing that Microsoft has successfully targeted this perceived competitor with destruction. If Kylix were of the quality of Delphi, it would be a killer Linux app. Thomas Bartkus From onurb at xiludom.gro Mon Jul 4 08:21:47 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 04 Jul 2005 14:21:47 +0200 Subject: How do you program in Python? In-Reply-To: <3iqif8Fmj34kU1@individual.net> References: <3iqif8Fmj34kU1@individual.net> Message-ID: <42c929dc$0$27601$636a15ce@news.free.fr> anthonyberet wrote: > My question isn't as all-encompassing as the subject would suggest... > > I am almost a Python newbie, but I have discovered that I don't get > along with IDLE, as i can't work out how to run and rerun a routine > without undue messing about. > > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of > code, to see the effects of tweaks, without having to save it each time, > or re-typing it over and over (snip) > I see lots of alternate IDEs etc, but which would allow me the simple > interface that I have described? Try Emacs + python-mode. Emacs surely has a lot of warts, but I'm still looking for a better and more versatile code editor/IDE - specially when it comes to languages with REPL (-> Read-Eval-Print Loop). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hancock at anansispaceworks.com Fri Jul 22 10:24:43 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 22 Jul 2005 09:24:43 -0500 Subject: Lots of pdf files In-Reply-To: References: Message-ID: <200507220924.43858.hancock@anansispaceworks.com> On Friday 22 July 2005 03:43 am, Richie Hindle wrote: > > a mere $29.90, except it is GPL'd so I'm not sure what the money is for > "Tech support [...] free forever for registered users." Hmm. Though that raises the old spectre of charging a fixed price for a "loss center". > But I've often wondered whether you could charge for mass-market GPL software > simply because your ordinary punter doesn't know what the GPL is, and doesn't > mind paying a small amount of money for decent software. Whether it's > ethical, given that presumably the thing is GPL because it inherits GPL code > from other developers, I don't know. Certainly the GPL itself has no > objection to charging for binaries provided you ship the source as well. Sure it's ethical. I suspect most GPL developers would love to see it work. Of course, you might have to worry about them pre-empting you. ;-) The problem is that competition will tend to drive the price to the marginal cost of distribution. By tacking on a value-added feature (printed documentation or tech support), you are improving the "production quality" of the copy you are selling, which means you can (sustainably) charge a bit more. Still hard to make money at it, though. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From mwh at python.net Sun Jul 31 14:36:24 2005 From: mwh at python.net (Michael Hudson) Date: Sun, 31 Jul 2005 18:36:24 GMT Subject: shelve: writing out updates?! References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: Robert Kern writes: >> The Documentation Wiki could then be used as a basis for the >> "official" documentation that comes with each new release. >> Does this idea make some sense? Or are there hidden pitfalls? > > Yes! Someone actually has to do it! I think someone is working on this as part of the summer of code program (but am not sure about that...). Cheers, mwh -- QNX... the OS that walks like a duck, quacks like a duck, but is, in fact, a platypus. ... the adventures of porting duck software to the platypus were avoidable this time. -- Chris Klein, asr From edgrsprj at ix.netcom.com Mon Jul 18 22:53:49 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Tue, 19 Jul 2005 02:53:49 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <83und1pv3du700os4oug71i6ks242ojqfp@4ax.com> Message-ID: <1XZCe.1076$6f.1020@newsread3.news.atl.earthlink.net> "Bob Officer" wrote in message news:83und1pv3du700os4oug71i6ks242ojqfp at 4ax.com... > On Mon, 11 Jul 2005 08:31:31 GMT, in sci.geo.earthquakes, "edgrsprj" > wrote: > > >PROPOSED EARTHQUAKE FORECASTING > >COMPUTER PROGRAM DEVELOPMENT EFFORT > demand that public monies be giving to him to support his "research". > People around the world can download and use my data and computer programs for free, subject to normal copyright terms. For example, they cannot claim that they are the original developers of the computer programs. Where this person gets the stuff that he posts to Newsgroups is beyond me. From guettli at thomas-guettler.de Thu Jul 28 08:18:01 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 28 Jul 2005 14:18:01 +0200 Subject: Graphics files & Python References: Message-ID: Am Thu, 28 Jul 2005 10:40:05 +0000 schrieb Pekka Karjalainen: > How can I create image files and animations with Python? You can create image files with PIL: http://www.pythonware.com/products/pil/ I don't know if you can make animated gifs. You can use ImageMagick, too: http://www.imagemagick.org/script/index.php You can create animated gifs with imagemagick. I use with os.system("...") (Not the python bindings) HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From pink at odahoda.de Thu Jul 21 14:17:07 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Thu, 21 Jul 2005 20:17:07 +0200 Subject: Stupid question: Making scripts python-scripts References: <42dfb111@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Hello all, > > How do I make a python script actually a _python_ in unix:ish > environments? > > I know about adding: > #!/bin/sh > > ..as the first row in a shell script, but when I installed python on > a NetBSD system, I didn't get a "python" executable; only a "python2.4" > executable. > > Adding "#!/usr/pkg/bin/python2.4" as the first row in the script > would probably work, but that would be too specific for the system I'm > using, imho. > > I saw someone using "#!/usr/bin/env python", but that failed on the > system I'm using, so I assume that's something specific too (or is the > installation broken?). You could a) create a symlink to your python executable in a well known location, e.g. ln -s /usr/pkg/bin/python2.4 /usr/bin/python And use either "#!/usr/bin/python" (which should work on most UNIXoid systems with python installed) or "#!/usr/bin/env python" b) use the absolute path /usr/pkg/bin/python2.4 for your script (in order to have it running on your system) and use distutils to create a setup.py script for distribution. IIRC setup.py will recognize the shebang of your scripts and replace it with the proper path to python of the target system during installation. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From mynews44 at yahoo.com Thu Jul 14 11:53:36 2005 From: mynews44 at yahoo.com (googleboy) Date: 14 Jul 2005 08:53:36 -0700 Subject: more newbie list questions In-Reply-To: <1121335354.408890.120880@g44g2000cwa.googlegroups.com> References: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> <1121335354.408890.120880@g44g2000cwa.googlegroups.com> Message-ID: <1121356416.666579.168760@g43g2000cwa.googlegroups.com> Ali wrote: > It's not really clear what you mean? Ah. sorry. Let me try again. I start with a csv that looks something like this: title, author1, author2, publisher, code, ISBN frogs of canada, andy humber, , springer press, foc2, 111-20345-556 newts of the UK, nigel snodgrass, sarah strauss, cambridge press, nsss23,32-443567-130 amphibian environments, nigel snodgrass, , cambridge press, nsxx11, 32443567-120 First problem: I have a seed file which I have placed a set of easily searchable keywords (%author1%, %publisher% etc.) in. I want to be able to replace these keywords with the relevent values from each book, in order to create an individual text file for each book called code.txt (where the word code is replaced by the code of each book) I've read the tutorial and (I think I)know how to use regular expressions to make the substitions, but I can't figure out how to get to the individual values of each book. I have been trying the following: ++ import string, os, re, sys, operator, csv class Book(object): def __init__(self, title, author1, author2, publisher, code,ISBN): params = locals() del params['self'] self.__dict__.update(params) def __repr__(self): all_items = self.__dict__.items() return str(all_items) def read_books(filename): reader = csv.reader(csv_file) books = [Book(*[field.strip() for field in row]) for row in reader] csv_file.close() return books booklist = read_books("c:\path\to\books.csv") header = booklist[0] all_books = booklist[1:] Template = open(r'c:\path\to\cell.txt', 'r') sTemplate = Template.read() author1 = getattr(all_books, 'author1') # trying to assign the author value to the variable author1. sAuth = re.sub('%author%', author1, sTemplate) # replace %author1% with the value in author1 in the variable sTemplate) ++ The getattr causes an error that says "AttributeError: 'list' object has no attribute 'author1'" so I think I am reading the operator library page on the python site wrong somehow. once this works, I move onto the second problem, which is to write out the string after the substitions to a new file called e.g. foc2.txt (for the frogs of canada book). I really am not sure how to go about this. I was thinking of something like concatenating three strings together path = "r/'c:\path\to" code = getattr(code, all_books) extension = '.txt/'' filename = path + code + extension f = open(filename, 'w') however I have serious doubts that doing that will work. I guess what I am needing, if it doesn't, is some sort of method of substituting a variable's value into the following: f = open(r'c:\path\to\%subs%.txt, 'w') The third thing I am hoping to acheive is to append an extra field to each book called 'filename' which will simply be a concatenation of the 'code' field + '.txt'. Further thought suggests that I should create the field first, even if it is empty, so that the books still all conform to the Book class. Then it simply becomes a question of how to I change the value of a field in these lists. I am sure that the answer to that was something I found in the tute, or it will be in my deitel python book somewhere... The hard bit is part one (assigning the value of a field to a variable) Thanks for your help. Googleboy From the_ninja_812 at yahoo.com Wed Jul 6 16:15:56 2005 From: the_ninja_812 at yahoo.com (the_ninja_812 at yahoo.com) Date: 6 Jul 2005 13:15:56 -0700 Subject: Make Mass Money With PayPal......... Message-ID: <1120680956.074099.279930@o13g2000cwo.googlegroups.com> How to Turn $5 into $15,000 in 30 Days with PayPal I WAS SHOCKED WHEN I SAW HOW MUCH MONEY CAME FLOODING INTO MY PAYPAL ACCOUNT I turned $5 into $14,706 within the first 30 days of operating the business plan that I am about to reveal to you free of charge. If you decide to take action on the following instructions, I will GUARANTEE that you will enjoy a similar return! Please do not be sceptical about this program. At least think about it for a few days. Otherwise you will be throwing away over $15,000 in cash! This system has been working for 2 years and thousands of people have joined and they have been amazed by the results of a little time and $5.00! You will too! I became unemployed in August of 2001, along with several other colleagues at the printing firm where I worked. At that time I was living beyond my means and in serious debt. Several debt collectors were hounding me on an almost daily basis, and this consequently started a chain reaction that ended with the repossession of my car and then my home. As you can probably imagine, my prospects looked pretty bleak. Then, in March of 2002, I received a short and simple email telling me how to make over $15,000 at a time. I ignored it because of course, I was sceptical. However, I didn't delete that email because something about it rang true to me, and I was desperate to know whether it was possible to make that amount of money in such a short space of time. By this time, I was even deeper in debt, and I had just about reached the point of despair. I finally realised that I had absolutely nothing to lose by having a go at the plan offered to me in that email. And apart from that, I just couldn't stop myself from thinking What if it actually works? Therefore, I put my doubts to one side and I went ahead and followed the simple instructions given in that email. It took me less than 30 minutes to complete and it cost me no more than $5. And yet, by the end of 2002, I was able to book the family holiday of a lifetime in the Caribbean, and I bought a brand new BMW with hard cash. Also in the autumn of 2003, I purchased a tidy condo in Florida for no less than $125,000. And yet, I dont owe a single cent to anyone! To date, I have made exactly $376,855. My accountant has drawn up a cash-flow forecast in which he predicts that, within the next 18 months, I will become a millionaire just through this one business alone. Even now as I write this, I find it strange to come to terms with the fact that, like most people, Ive worked hard and struggled all my life just to get by and then something ridiculously simple drops into my lap and immediately turns my life around completely. When I think back to all the similar emails I had previously deleted, it makes me shudder, because now I know just how close I came to missing out completely. What did it say in that email? Well, if you'll read on, all will be revealed! The business plan I am about to share with you works perfectly every single time. Ive never made less than $15,000 from it on each occasion. Let me assure you that this is a LEGITIMATE BUSINESS OPPORTUNITY, a perfectly legal moneymaking enterprise. It does not require you to sell anything. It does not require you to speak to your friends, family or anybody else (unless you want to). In fact, you do not need to come into contact with any people whatsoever. Anyone with a pulse can become successful and make their fortune with this system. If you believe that every dog has its day, then follow the simple step-by-step plan exactly as it is set out below. If you do this and this alone, I GUARANTEE that within the next 30 days you will receive over $15,000 in cash via your PayPal account. I know that this must sound like an outrageous claim, particularly if you've never had possession of this sort of money before, but believe me, this business works like nothing else you may have seen before in your life! By following the simple 3-step plan set out below, within a few short weeks your life will be transformed beyond all recognition! Please do not allow your initial scepticism to deprive you of certain financial success. If you decide not to take advantage of this life-changing opportunity, I would like you to know that I sincerely respect your decision and I understand that you will have your reasons. I therefore wish you the very best of luck for the future. I am able to say this with absolute sincerity because, as you will see, if you decide to work this plan, I will not receive any financial compensation from you whatsoever. After all, I am sharing this system with you for free. However, remember life is short. Nobody has ever said that you cant have the financial freedom to do what you want to do, when you want to do it. But you must first pay the price. The price here is action; its as simple as that! Im very proud to be able to say that Ive fulfilled my duty to my wife and children by securing their financial future in a very uncertain world, and I dont believe that any price is too great to pay for such peace of mind. This is the CHEAPEST, FASTEST and EASIEST way to make serious money online - PERIOD! There are a lot of companies out there offering to put you in your own business, but I'm so certain you will make a SERIOUS INCOME with what I am going to tell you that I'm willing to roll up my sleeves and help you begin - RIGHT NOW!! Remember, I am not asking you to send me a single penny for the lucrative business project I am about to share with you. In addition, you will not be asked to buy anything or sacrifice your free time. You will make some fast and easy cash, using just a copy of this page and the simplest and most popular Internet payment system in existence! You have most likely seen or heard about this project on TV programs such as 20/20 and Oprah Winfrey, or you may have read about it in the Wall Street Journal. If not, here it is below - revealed to you in step-by-step detail. This program is by no means new. It has been in existence in many forms for at least a decade. But in the early days, it required a lot more time and effort, as well as an outlay of a few hundred pounds. However, thanks to PayPal and the Internet, the outlay is now virtually ZERO! And what's more, the entire process is FASTER, EASIER, and MORE LUCRATIVE than it has EVER been! If you're already running a home business, you can easily do this one along with it. If not, this is the FASTEST and EASIEST way to earn serious money online that you've ever seen so far in the history of the Internet! This program works no matter what country you are in, or what currency you use. It doesn't matter how old or how young you are. And you certainly won't need any special knowledge or talent. You won't need to run a website, or make phone calls, or make photocopies, or send out letters through the mail, or pay for advertising, etc. The only things you will need are: ? An email address ? A Business PayPal account with at least $5 deposited in it ? Just 30 minutes of your time This program takes just half an hour to set up. After that, there is absolutely no work whatsoever to do on your part. And yet, you will stand to gain many thousands of pounds within the next few weeks from those 30 minutes of easy work! Yes, I know, it sounds too good to be true! I thought exactly the same thing myself until I actually tried it out! Even if you are already involved in another program, stay with it, but do yourself a big favour and DO THIS ONE as well. You have absolutely NOTHING to lose, but you stand to gain a LIFE-CHANGING amount of money within the next few weeks! In fact, there is NO LIMIT to the amount of income you can generate from this one single business program!! The facts are simple: If you need to make a few thousand pounds REALLY FAST, then this program is the way to do it! It's the CHEAPEST, FASTEST, EASIEST, and MOST LUCRATIVE program you will ever participate in! Please be sure to read all of this page . . . take your time, come back to it . . . go over and over it, you won't be sorry, I can certainly promise you that! If you don't have time to read all of this now, then save this email so you can come back to it later. All you need is a PayPal account and an email address! Just about everyone has heard about "PayPal" (if you haven't you will soon!) and when I came across this concept I knew it would work because, as a member of PayPal (an Ebay company), I had already experienced their efficiency and excellent standing. PayPal is the simplest method of making and receiving payments online that anyone has ever seen! Anyone with an email address can join for FREE! Once you have a PayPal account, you can send and receive credit card payments to or from anyone - anywhere in the world! Please read further before you go there... You can complete this whole process within just half an hour and you will NEVER forget the day you decided to do so!!! NEED PROOF? Here are just 3 testimonials from the countless individuals who decided to invest nothing more than $5 and half an hour of their time to participate in this program: "What an amazing plan! I followed your instructions just 3 weeks ago, and although I haven't made 15 grand yet, I'm already up to $9,135. I'm absolutely gob smacked." Pam Whittemore , Ohio "This is Lisa. Well, what can I say?... THANK YOU SO MUCH! I sent 40 e-mail's out like you said and then I just forgot about the whole thing. To be honest, I didn't really think anything would come of it. But when I checked my paypal account a week later, there was over $5,000 in it! After 30 days I now have over $11,000 to spend! I can't thank you enough!" Juan Tovar, NY,NY "I was shocked when I saw how much money came flooding into my paypal account. Within 3 weeks my account balance has ballooned to $12,449. At first I thought there had been some sort of error with my account!" Richard Barrie , Boulder,CO Just a few months ago, each of these people were doing the same thing as you are at this very moment - reading this! But because they decided to follow the simple instructions given below, they are now considerably better off as a result. And there's no reason whatsoever why you can't share in this success. You've got nothing to lose, and EVERYTHING to gain! Let's get started, just follow the instructions exactly as set out below and then prepare yourself for a HUGE influx of cash over the next 30 days! Here's what you need to do. . . STEP 1 Ok, if you're not already a PayPal user, the very first thing you need to do is click on the PayPal link below and SIGN UP. It takes just 2 minutes! Here's the link: https://www.paypal.com/ Be sure to use this link so you can sign up for a free BUSINESS account. You'll need to have a BUSINESS account (and not a PERSONAL account) otherwise you won't be able to receive credit card payments from other people. STEP 2 It is an undeniable law of the universe that we must first give in order to receive. So the first thing to do when you have your Business PayPal account is to IMMEDIATELY send a $5 payment from your PayPal account to the FIRST email address in the list below, along with a note saying: "Please add me to your mailing list. " Be certain to add this note, as this is what KEEPS THIS PROGRAM LEGAL. Instructions on how to send a payment are under "SEND MONEY" at the Paypal site. It's so easy!! When you send your $5 payment to the first address in the list, do it with a great big smile on your face because "as you sow, so shall you reap!" Here's the current list: 1. gdmdtd at hotmail.com 2. bubblehead778 at excite.com 3. the_ninja_812 at yahoo.com 4. smb11 at woh.rr.com 5. gdixon3 at woh.rr.com After you have transferred a $5 payment to the email address at the top of the list, something very eerie happens. It gives you an indescribable, overwhelming sense of certainty, belief and conviction in the system. Youve just proved to yourself that, because you have done it, there must be a great number of other people ready to do exactly the same. Thus you have now seen for yourself, first hand, that this business actually works! STEP 3 Once you've sent a $5 payment to the address at the top of the list (along with your note - this is VERY important!), the next thing you need to do is to obtain a copy of the contents of this page, as you'll be sending it out (as an email message or by advertising your page, like I have done) to at least 40 people (keep in mind that 40 is a good number of people to reach, but with all the different ways of advertising for free on the internet the amount of views and sign-ups under you could well exceed into the hundreds or thousands if you wish....the more people who join the more profitable for everyone on the list, including you). The copy that you will send out will contain YOUR email address at number 5 in the list - having deleted the address at Number 1 in the list, and moving the others up a position. The best way to do this is you can copy and paste into emails to your family and friends. You can copy and paste it and put ad's on the internet on message boards etc. Or you can create your own free website, by copying and pasting. There are many free webpages you can build on the web. For example 2 good ones are www.geocities.com or http://www.cmlb.net. Both of these are simple to use. And the best part of having this info on a website for people to follow is you can post links to your site on paid to click websites or paid to read email sites, for great advertising. There are countless ways to get more people like me and you involved in this amazing program. A. Go to the toolbar at the top of the window and select "Edit" and then "Select All". B. Go to the toolbar again and select "Edit" and then "Copy". C. Start (compose) a new email message (PLAIN TEXT so everyone can view it!). D. Fill in your email address and subject line, and then click in the main message area. E. Go to "Edit" and "Paste" to paste the text into your new email message. Now you can edit and format the message text in any way you want! However, it's best to just leave the text as it is because you want your email to be read by everyone who receives it! The only thing you need to make sure of is that YOUR email address is at Number 5 in the list in STEP 2. Of course, the address that was previously at Number 1 should have been removed, and the other email addresses should have been moved up a position to accommodate yours at Number 5. As long as you have done this correctly, your email is ready for sending! A word of warning! Don't be tempted to add your email address to position 1 in order to earn money fast! It doesn't work like that! If you do that, you will ONLY reach the people you directly send emails to, and then your address will be immediately removed from the Number 1 place and you won't reach thousands of people! But, if you add your name to the Number 5 position, there will be literally tens of thousands of people receiving and sending email's later - when your name is at the Number 1 spot!!! F. Once you've got your email message ready, send out a minimum of 40 copies of the email - but only to people you know, or to people who respond to MLM offers, or to people who've sent YOU offers. By sending this letter and the payment via EMAIL, the response time is EXTREMELY fast.......... ELECTRONIC TRANSFER INTERNET FAST!!! That's why it takes only a few days for those $5 payments to start flooding into your PayPal account! THAT'S ALL THERE IS TO IT! The whole process should take you about 30 minutes to complete. BE PREPARED TO GET EXCITED.... YOU WON'T BE DISAPPOINTED!!! Half an hour of easy work is all that's needed - no capital outlay, no postage stamps, no printing, copying or waiting, and the concept is 100% legal. Within 30 days, over $15,000 cash will pass through your PayPal account. And thats GUARANTEED. In fact, you can expect to receive a substantial number of $5 payments within the first few days! Keep a copy of your email safe so that you can use it again whenever you need more cash! Here's the math : When you send out your emails, your email address will initially be at Number 5 in the list. That's the best position it can be in at this stage if you want to make serious money. The response-rate for this program is much higher than any typical email marketing campaign for a number of reasons, which are explained later. As long as you send your emails to people who are likely to be interested in this program, on average, you can expect a response from about 25% of the people you send to. But let's be extremely conservative here and assume that you receive an average response rate of only 12.5%. . . If you send out your email to 40 different people, you can expect at least 5 of those people to do exactly what you did (12.5% of 40 = 5). By this time, your email address will have moved up to Number 4 in the list, and this list will now have reached around 200 people (5 x 40). Out of those 200 people, you can expect at least 25 of them to participate (12.5% of 200 = 25), so that's a further 1,000 emails (25 x 40) being sent out and your email address will have risen to Number 3 in the list. Out of those 1,000 people, you can expect at least 125 of them to participate (12.5% of 1,000 = 125), so that's a further 5,000 emails (125 x 40) being sent out with you now at the Number 2 position. Out of those 5,000 people, you can expect at least 625 of them to respond (12.5% of 5,000 = 625), so that's 25,000 emails (625 x 40) being sent out with YOUR ADDRESS at the Number 1 spot! Now, out of those 25,000 people, you can expect around 3,125 of them to respond (12.5% of 25,000 = 3,125). And since you will now be at NUMBER 1 in the list, you will receive: $15,625 ! (3,125 x $5) So, when your name starts to hit the Number 1 position within the next few days, it will be YOUR turn to collect the money! Over the course of 30 days, this money will be sent to you by a few thousand people just like yourself - who are willing to invest half an hour to receive around $15,000 or more in cash! The first payments will arrive within a few days, and they will continue at the rate of about 100 payments per day for about 30 days. After that time, the volume of payments begins to taper off as your email address vacates the Number 1 position. That's all you need to do! There will be around $15,000 in $5 payments waiting for you in your PayPal account within the next few weeks. $15,000 for just 30 minutes work! This is real money that you can spend on anything you wish! Just deposit it to your own bank account or spend it directly from your PayPal account!!! It's just that easy!!! I think it's WORTH IT, don't you? Remember, the 12.5% example above is assuming that 35 out of the 40 people you send your email to will do absolutely nothing except delete your email. However, if you follow the plan correctly and send your emails only to people who are likely to want to participate, you can expect a typical response-rate of around 25%. Hence, the 12.5% example is only given as a worst-case-scenario. Additionally, the above example assumes that each participant will only send out 40 emails. Imagine what would happen if each participant sent out 1,000 emails instead of just 40! Believe me, many people will do this and much more! Consider this! Millions of people surf the Internet every single day, all over the world! Plus there are 50,000 new people who get on the Internet every month! The people who send you offers by email can provide you with an excellent source of bulk email addresses to send to. You can also send out emails to all of your family, friends, and to anyone who you think would want to invest $5 and 30 minutes of their time to make a substantial lump sum within a month. If you want to operate this business continuously, you should consider obtaining bulk lists of email addresses from a reputable mailing list company. That's how I've managed to stay in business for the last 2 years! If you already have a legitimate mailing list, then this program would be the most profitable way to make use of it. There are many websites that sell thousands of fresh opt-in email addresses of people who have subscribed to receive exactly this type of program. For example, visit: www.htmail.com and www.Email2Success.com. The possibilities are endless, and it's so easy! Unlike many other programs, this 5-LEVEL PROGRAM costs you only $5. That's right, only $5 ONCE, which is much more realistic and provides much, much faster results. Only the first person on the list gets your $5 gift, but everyone in the list will rise to that Number 1 position as thousands of emails are being sent out. No cheating can occur (don't be fooled by claims that this system can be cheated) as Paypal only allows one account per person. Because it is so easy, the response rate is VERY HIGH and VERY FAST - Internet email FAST, and you will start seeing dramatic results in less than one week! JUST IN TIME FOR NEXT MONTH'S BILLS! Remember, you need only mail out 40 copies to start with. This will be enough to generate a substantial lump sum within 30 days. For example, send to personal contacts and reply to people who send their programs to you, as they are already working on the web. They know these programs work and they are already believers in the system! This is NOT considered SPAM if you are responding to other people's offers, or sending to friends, family and contacts, or if you are using a legitimate mailing list. So, email your letters out today, and then prepare yourself for a huge influx of cash within the next 30 days!!! 4 factors that make this program so successful. . . EXTREMELY FAST RESPONSE EXTREMELY HIGH RESPONSE RATE UNLIMITED PROFIT POTENTIAL QUICK, SIMPLE AND CHEAP TO GET STARTED Because of the VIRTUALLY ZERO INVESTMENT, SPEED, and HIGH PROFIT POTENTIAL, this program has a VERY HIGH RESPONSE RATE! And all from just a simple email and one simple $5 PayPal transaction! In fact, this program has faster results and a higher response rate than any other Internet program you could possibly participate in! For most email marketing campaigns, the average response rate is between 0.5% and 5%. However, this particular program typically generates a response rate of between 20% and 30%. This is because this program is so easy to implement, it costs next to nothing, it takes just 30 minutes to implement, and the results can be seen within days. I've been watching this type of MLM program for years and this is about as easy and fast as you can get it. No stamps, no envelopes, no printed copies to be made - just a little effort and faith!!! This program really keeps it "short and simple"! UNLIMITED income potential! This program is structured for everyone to send only 40 emails each to start. However, you are certainly not limited to 40. Send out as many emails as you want. Every 40 emails you send has a return of AT LEAST $15,000 WITHIN 30 DAYS. So, if you can email 50, or 100, or whatever, GO FOR IT! THE MORE YOU PUT INTO IT, THE MORE YOU GET OUT OF IT! However, you MUST remember that sneaking your name higher up on the list will NOT produce the results you think, and it only cheats the other people who have put in the effort and have earned the right to be there. So please, play by the rules and the serious money will come to you! You are probably sceptical of this, especially with all the different programs out there on the Web, but if you don't try this you will never know. I felt exactly the same as you probably do right now. I wanted to believe but i just couldn't help thinking that there was some sort of catch. But then I realised that I had absolutely nothing to lose. After all, I was only being asked to invest a measly $5, and yet I could earn many thousands of pounds within a month. And all for just half an hour of my time! Therefore I went ahead and did exactly as the email requested. This took me around 30 minutes in total, and I'm so, so, glad I did that! To get started, just click on the link below: https://www.paypal.com/us/mrb/pal=2PSD9ZFYNZU2Q But please play by the rules! This program doesn't cost anything but $5 and about half an hour of your time, and if everyone plays fair, everyone WINS!! So there it is. You now have the knowledge that will enable you to make over $15,000 within the next few weeks. The only thing that can hold you back now is a lack of faith or a lack of self-belief. However, any doubts you may currently have will disappear within a few days of putting this plan into practice. Trust me on this! You certainly won't regret it. Some notes from the PayPal site which you may find useful PayPal lets you pay anyone with an email address and is the world's Number 1 online payment service. PayPal (as an Ebay company) is accepted on millions of eBay auctions daily, as well as a countless number of online shops. You can also use PayPal to pay your friends - for example, it's a convenient way to split the phone bill with your roommate, send cash to your kids in college, or send cash to someone in another country. When you send money through PayPal, you can fund your payments with your credit card or cheque account. You won't have to worry about your privacy, because PayPal keeps your accounting information safe and secure. Making a purchase with PayPal is far more secure than mailing a cheque or giving your credit card number to a stranger. That's why over 9 MILLION people from around the world use PayPal to move money. Signing up for a PayPal account is free, easy, and it takes only a couple of minutes. Thank you, and good luck in your ventures P.S. Does this sound too good? Well maybe to some sceptics it is. But it actually works, and is worth the 30 minutes of your time now. So, just mix yourself a drink and get started on it now. After all, you can't lose, but you stand to gain more in the next few weeks than many people earn in a year! Just for a little added comfort and legitimacy, I have forwarded this email to you, and I can assure you that it is a solid system, and it really does work ! Good luck, and remember, it only takes 30 minutes (ok, maybe 40 if youre not as much of a PC buff as others!), but the point is, anyone and everyone can do this. Follow the instructions to the LETTER, and you cannot fail. YOU ONLY PAY $5 ONCE! DONT FORGET THAT From bdesth.quelquechose at free.quelquepart.fr Thu Jul 21 22:18:12 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 22 Jul 2005 04:18:12 +0200 Subject: Returning histogram-like data for items in a list In-Reply-To: References: Message-ID: <42e0507a$0$22533$636a15ce@news.free.fr> Ric Deez a ?crit : > Hi there, > > I have a list: > L1 = [1,1,1,2,2,3] > > How can I easily turn this into a list of tuples where the first element > is the list element and the second is the number of times it occurs in > the list (I think that this is referred to as a histogram): > > i.e.: > > L2 = [(1,3),(2,2),(3,1)] > > I was doing something like: > > myDict = {} > for i in L1: > myDict.setdefault(i,[]).append(i) > > then doing this: > > L2 = [] > for k, v in myDict.iteritems(): > L2.append((k, len(v))) > > This works but I sort of feel like there ought to be an easier way, If you don't care about order (but your solution isn't garanteed to preserve order either...): L2 = dict([(item, L1.count(item)) for item in L1]).items() But this may be inefficient is the list is large, so... def hist(seq): d = {} for item in seq: if not item in d: d[item] = seq.count(item) return d.items() > I also tried this trick, where locals()['_[1]'] refers to the list Not sure to understand how that one works... But anyway, please avoid this kind of horror unless your engaged in WORN context with a perl-monger !-). From nephish at xit.net Sun Jul 31 11:40:26 2005 From: nephish at xit.net (nephish at xit.net) Date: 31 Jul 2005 08:40:26 -0700 Subject: getting an empty tuple Message-ID: <1122824426.310199.136660@o13g2000cwo.googlegroups.com> Hey there, i have a simple database query that returns as a tuple the number of rows that the query selected. kinda like this >>> cursor.execute('select value from table where autoinc > 234') >>> x = cursor.fetchall() >>> print x >>> 21L ok, means 21 rows met the criteria of the query. but if there are none that match, like i do a >>> print x >>> 0L how do i encorporate that into an equation ? i have tried all kinds of stuff if x == 0L if x(0) == None if x == None anyway, what shoud i do to test if the result is empty? thanks From cliff at develix.com Sun Jul 31 14:48:48 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 11:48:48 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7x3bpve8w5.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <7x3bpve8w5.fsf@ruckus.brouhaha.com> Message-ID: <1122835728.19618.75.camel@localhost.localdomain> On Sun, 2005-07-31 at 00:23 -0700, Paul Rubin wrote: > zen19725 at zen.co.uk (phil hunt) writes: > > What you say Pythonic, what do you mean? And how do you rate > > Tkinter, PyGtk, PyQt/PyKDE, wxWindows for "Pythonicness"? > > Tkinter is not very Pythonic because it's sort of a Frankenstein > hybrid of Python and Tcl, but at least it's there and it more or less > works. The others are non-Pythonic because they're not included in > the standard distro and therefore the Pythonic "use the included > batteries" tenet says to use Tkinter despite its flaws. Am I to assume that you don't use *any* third party libraries? As far as the "use the included batteries" tenet... has Python changed from a programming language to a cult in the few months I've been off the list? Where are these "tenets"? I've never heard such nonsense. Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From peter at engcorp.com Thu Jul 21 02:33:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Jul 2005 02:33:05 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: References: Message-ID: Jp Calderone wrote: > In the particular case of wxWidgets, it turns out that the *GUI* blocks > for long periods of time, preventing the *network* from getting > attention. But I agree with your position for other toolkits, such as > Gtk, Qt, or Tk. Are you simply showing that there are two points of view here, that one can look at the wx main loop as being "blocking", waiting for I/O, even though it is simply doing asynchronous event-driven processing the same as Twisted? Or am I missing something? Allowing for the fact that wx blocks, not just for long periods of time, but *indefinitely* (as long as no events are arriving) I still don't see how that makes it different from Twisted or from any other typical GUI framework, which do exactly the same thing. (And since there is even a wxPython main loop integrated with and provided in Twisted, surely you aren't arguing that what wx does is somehow unusual or bad.) Or are you simply saying that parts of wx are slow and take a while to complete operations? If that's all, I haven't seen such behaviour... what areas are of concern? -Peter From teoryn at gmail.com Mon Jul 25 10:30:13 2005 From: teoryn at gmail.com (teoryn) Date: 25 Jul 2005 07:30:13 -0700 Subject: Problem loading a file of words References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> <1122298053.790180.292810@g43g2000cwa.googlegroups.com> Message-ID: <1122301813.896183.195580@g47g2000cwa.googlegroups.com> I was just happy that it worked, but was still curious as to why it didn't before. Thanks for the idea, I'll look into it and see if this is the case. Thanks, Kevin From jepler at unpythonic.net Mon Jul 18 11:39:08 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Jul 2005 10:39:08 -0500 Subject: stdin/stdout fileno() always returning -1 from windows service In-Reply-To: <1121697436.413522.268110@g49g2000cwa.googlegroups.com> References: <1121650980.574867.244590@g44g2000cwa.googlegroups.com> <1121697436.413522.268110@g49g2000cwa.googlegroups.com> Message-ID: <20050718153904.GD2199@unpythonic.net> It seems to simply be common wisdom. e.g., http://mail.python.org/pipermail/python-win32/2004-September/002332.html http://mail.mems-exchange.org/pipermail/quixote-users/2004-March/002743.html http://twistedmatrix.com/pipermail/twisted-python/2001-December/000644.html etc If you can find chapter and verse on MSDN, more power to you. This page implies that the "standard handles" are only available when there is a console for the application. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getstdhandle.asp Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From peter at engcorp.com Sat Jul 9 10:16:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Jul 2005 10:16:17 -0400 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <42cf6d0d.182600044@news.oz.net> References: <78huc11mgkvn1sho01qegi221k7hhc5u1p@4ax.com> <42cf6d0d.182600044@news.oz.net> Message-ID: Bengt Richter wrote: > On Fri, 08 Jul 2005 22:29:30 -0600, Steven Bethard wrote: >>(1) There's no reason to get uncomfortable even if they're removed. >>You'd just replace [] with list(). > > So list(1, 2, 3) will be the same as [1, 2, 3] ?? No, the discussion is about list comprehensions. [1,2,3] is not a list comprehension, as you know. -Peter From bokr at oz.net Sun Jul 3 21:52:32 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 04 Jul 2005 01:52:32 GMT Subject: Assigning to None (was Re: Question about Python) References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <42c8388f.442175024@news.oz.net> Message-ID: <42c892c1.465265326@news.oz.net> On Mon, 04 Jul 2005 09:11:19 +1000, Steven D'Aprano wrote: >On Sun, 03 Jul 2005 19:19:05 +0000, Bengt Richter wrote: > >> On Sun, 03 Jul 2005 11:47:07 +1000, Steven D'Aprano wrote: >> >>>On Fri, 01 Jul 2005 12:59:20 -0400, Fran?ois Pinard wrote: >>> >>>> [Peter Hansen] >>>>> Mike Meyer wrote: >>>>> > Yes. I once grabbed an old program that did assignments to None. But >>>>> > that's always been a bad idea. >>>> >>>>> What was the use case!? >>>> >>>> People used to assign None to itself as a keyword argument in function >>>> headers. The goal was to make a local copy of the reference, which was >>>> then accessed faster than the global thing. >>> >>>Can you say "premature optimization is the root of all evil"? >>> >>>I'd like to see the profiling that demonstrated that this made a >>>significant -- or even measurable -- speed-up in anything but the most >>>unusual cases. >>> >> The difference between local and global access is definitely measurable, though >> there's no reason to use None as the local name if you want to do that kind >> of optimization (not possible in 2.4+) >[snip] >> about 25% longer to get a global (AND bind it locally, which the two timings share) >> than to do the same for a local, it seems. > >Sure. And if you are actually looping over one million bindings to your >local variable, and doing NOTHING else, you may approach a 25% time >saving. That is, one of the unusual cases I mentioned. > >But in real world usage, the 25% saving in fetching the variable once or >twice is almost certainly lost in the noise of the rest of your code. >Saving 25% of 0.0000001 second running time in a function that takes >0.0001 second in total to run is pointless. > >That's why I asked about the profiling. I'd like to see what sort of real >world function got enough real benefit from setting None=None to make up >for the misuse of the language. > That particular single thing would only account for 250 seconds even if I processed a billion things on my old clunker, and I wouldn't likely notice the 4 minutes in the total time, if it was doing much else. But this is perhaps the least profitable local caching you can do, compared to hoisting constant expressions out of the loop, such as dotted expressions involving the same bound methods over and over, or class variable, or module variables etc. I'm sure I'm not saying anything you don't know ;-) But sometimes a combination of such things can add up to starting a utility and going for coffee, or just standing up and stretching ;-) Also, as mentioned, there is no reason to write None=None when none=None will do the silly thing. And I agree it is silly either way 99+ % of the time. Regards, Bengt Richter From steve at holdenweb.com Fri Jul 29 05:08:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Jul 2005 10:08:15 +0100 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Dan Sommers wrote: > On Thu, 28 Jul 2005 15:35:54 -0700, > Robert Kern wrote: > > >>That said, I made a boo-boo. The Zen of Python is really a set of >>design principles (and some of them, like this one, are more >>specifically *language* design principles), not Essential Development >>Practices. That'll teach me to not RTFA. > > > May I respectfully disagree? The Zen applies to all aspects of software > (and other things, too, but they're off topic here), from human readable > reports and requirements and documentation, to GUI's, to test cases, to > code, to database schemta, as well as the development methodology and > practices themselves. > > Sometimes you have to look at the Zen sideways, so that "implementation" > appears to be replaced by the particular aspect or aspects (or the > software, or just software, as a whole, for the true Masters out there) > you happen to be working on at the time, but such is the nature of Zen. > > Regards, > Dan > If I canpoint out the obvious, the output from "import this" *is* headed "The Zen of Python", so clearly it isn;t intended to be universal in its applicability. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 19 03:16:55 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 19 Jul 2005 09:16:55 +0200 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: rbt enlightened us with: > Many of the world's most profitable software companies (MS for > example) have thousands of goto statements in their code... oh the > horror of it all. Why aren't these enlightened-by-the-gods > know-it-alls as profitable as these obviously ignorant companies? They write software with huge security holes. Direct3D still isn't as stable as OpenGL. It takes ages for them to create security patches. The things I mention are *not* caused by their nice and clean way of coding. As a matter of fact, they use goto to jump from one function to another! And to make sure a 'return' doesn't return to the last call, but to some other, they combine this awful use of goto with manual stack manipulation. And they do all of this in C (or some derivative) so if one function changes it's parameters, all the manual stack modifications and gotos need to be checked for correctness. I'd rather use an exception, or better even - write small functions so I can call 'return' instead of doing 'goto EXIT'. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From cam.ac.uk at mh391.invalid Fri Jul 29 12:06:26 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 29 Jul 2005 17:06:26 +0100 Subject: Wheel-reinvention with Python In-Reply-To: <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > > Michael Hoffman writes: > > >>Dark Cowherd wrote: >> >> >>>GUI, Web development, Application Framework - it is shambles. >> >>Yeah, I agree. When I finally make that GUI application I still >>don't know whether I am going to use wx or PyGTK. > > I agree, too, although I can only talk about GUI toolkits. At first > one thinks "well, perfect, I have the choice between four great GUI > systems". However, except for very special demands, there is no > clear winner. You start learning one, and immediately wonder > whether the other might be better. Although it sounds paradoxical, > this can be quite frustrating. After all, most of us don't have the > energy or motivation to test all candidates thoroughly. The PEP process can be quite good for whittling this down and getting the best of all worlds. For example, the current stdlib csv module was based on three previous modules[1]. We only really need one. However, since GUI toolkits are so complicated, I wonder if they will ever be subject to this process. [1] http://www.python.org/peps/pep-0305.html#existing-modules -- Michael Hoffman From reinhold-birkenfeld-nospam at wolke7.net Fri Jul 22 15:38:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 22 Jul 2005 21:38:09 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <3kd092FtshinU1@individual.net> Andrew Dalke wrote: > Duncan Booth wrote: >> Personally I think the concept of a specific path type is a good one, but >> subclassing string just cries out to me as the wrong thing to do. > > I disagree. I've tried using a class which wasn't derived from > a basestring and kept running into places where it didn't work well. > For example, "open" and "mkdir" take strings as input. There is no > automatic coercion. Well, as a Path object provides both open() and mkdir() functions, these use cases are covered. And that's the point of the Path class: Every common use you may have for a path is implemented as a method. So, it's maybe a good thing that for uncommon uses you have to explicitly "cast" the path to a string. >>>> class Spam: > ... def __getattr__(self, name): > ... print "Want", repr(name) > ... raise AttributeError, name > ... >>>> open(Spam()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: coercing to Unicode: need string or buffer, instance found >>>> import os >>>> os.mkdir(Spam()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: coercing to Unicode: need string or buffer, instance found >>>> > > The solutions to this are: > 1) make the path object be derived from str or unicode. Doing > this does not conflict with any OO design practice (eg, Liskov > substitution). > > 2) develop a new "I represent a filename" protocol, probably done > via adapt(). > > I've considered the second of these but I think it's a more > complicated solution and it won't fit well with existing APIs > which do things like > > > if isinstance(input, basestring): > input = open(input, "rU") > for line in input: > print line > > I showed several places in the stdlib and in 3rd party packages > where this is used. That's a valid point. However, if Path is not introduced as a string, most new users will not try to use a Path instance where a string is needed, just as you wouldn't try to pass a list where a string is wanted. >> You should need an explicit call to convert a path to a string and that >> forces you when passing the path to something that requires a string to >> think whether you wanted the string relative, absolute, UNC, uri etc. > > You are broadening the definition of a file path to include URIs? > That's making life more complicated. Eg, the rules for joining > file paths may be different than the rules for joining URIs. > Consider if I have a file named "mail:dalke at example.com" and I > join that with "file://home/dalke/badfiles/". > > Additionally, the actions done on URIs are different than on file > paths. What should os.listdir("http://www.python.org/") do? I agree. Path is only for local filesystem paths (well, in UNIX they could as well be remote, but that's thanks to the abstraction the filesystem provides, not Python). > As I mentioned, I tried some classes which emulated file > paths. One was something like > > class TempDir: > """removes the directory when the refcount goes to 0""" > def __init__(self): > self.filename = ... use a function from the tempfile module > def __del__(self): > if os.path.exists(self.filename): > shutil.rmtree(self.filename) > def __str__(self): > return self.filename > > I could do > > dirname = TempDir() > > but then instead of > > os.mkdir(dirname) > tmpfile = os.path.join(dirname, "blah.txt") > > I needed to write it as > > os.mkdir(str(dirname)) > tmpfile = os.path.join(str(dirname), "blah.txt")) > > or have two variables, one which could delete the > directory and the other for the name. I didn't think > that was good design. I can't follow. That's clearly not a Path but a custom object of yours. However, I would have done it differently: provide a "name" property for the object, and don't call the variable "dirname", which is confusing. > If I had derived from str/unicode then things would > have been cleaner. > > Please note, btw, that some filesystems are unicode > based and others are not. As I recall, one nice thing > about the path module is that it chooses the appropriate > base class at import time. My "str()" example above > does not and would fail on a Unicode filesystem aware > Python build. There's no difference. The only points where the type of a Path object' underlying string is decided are Path.cwd() and the Path constructor. Reinhold From cyril.bazin at gmail.com Tue Jul 19 10:42:07 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Tue, 19 Jul 2005 16:42:07 +0200 Subject: Dictionary, keys and alias In-Reply-To: References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> <5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: Glauco, Be careful if you decide to use hash. There is possibility of bugs due to that approach, (if hash(x) == hash(y) and x != y). Even if the probability of bug is near 0, your computer will certainly recall you what is the murphy law. If I were you, I would prefer another approach. Cyril On 7/19/05, Glauco <00515879256 at fastwebnet.it> wrote: > > Steven D'Aprano wrote: > > On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote: > > > > > >>I want to insert a concept of alias in a dict_based class. > >> > >>The idea is to have a facoltative name in the same dict that correspond > >>at the same value. With this alias i can change original value. > >> > >>example: > >> > >>mydict['a'] = 1 > >>I must define an alias example: myFunctAlias( mydict, 'a', 'b') > >>print mydict > >>{'a':1, 'b':1} > >>mydict['b'] = 2 > >>print mydict > >>{'a':2, 'b':2} > >> > >> > >>The only idea i have is to implement two dictionary one for convert > >>name, alias in two keys with the same value (eg.numeric) in the first > >>dict. The second for store only one time the k, v . > > > > > > You need some sort of redirection, something like this (untested): > > > > class Doubledict: > > def __init__(self, **kargs): > > self.data = {} > > self.aliases = {} > > for key in kargs: > > # Point the key to a hash. > > self.aliases[key] = hash(key) > > # And point the hash at the value. > > self.data[hash(key)] = kargs[key] > > > > def setalias(self, key, alias): > > # Point the alias to the same hash as the real key. > > self.aliases[alias] = hash(key) > > > > def __getitem__(self, key): > > return self.data[self.aliases[key]] > > > > def __setitem__(self, key, value): > > self.data[self.aliases[key]] = value > > > > > > The only niggly worry I have is I'm not sure when hash can be used, when > > it is unique, or even if is it guaranteed to be unique. > > > > Thank Steve, the idea was the same... > but yours using hash is much elegant. > > Thank you > Glauco > > -- > > \\\|/// > \\ - - // > ( @ @ ) > +---------------------oOOo-( )-oOOo--------------------------+ > | | > | I have a dream that one day this nation will rise up and | > | live out the true meaning of its creed: "We hold these | > | truths to be self-evident:that all men are created equal.| > | I have a dream that one day on the red hills of Georgia | > | the sons of former slaves and the sons of former | > | slaveowners will be able to sit down together at a table | > | of brotherhood. | > | I have a dream that one day even the state of Mississippi, | > | a desert state, sweltering with the heat of injustice | > | and oppression, will be transformed into an oasis of | > | freedom and justice. | > | I have a dream that my four children will one day live in | > | a nation where they will not be judged by the color of | > | their skin but by the content of their character. | > | I have a dream today. | > | | > | Martin Luther King, Jr 28 Ago 1963 | > +------------------------------------------------------------+ > | glauco(at)uriland.it | > | www.uriland.it .oooO ICQ: 115323690 | > +--------------------- ( )------ Oooo.---------------------+ > \ ( ( ) > \_) ) / > (_/ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Mon Jul 18 08:26:10 2005 From: me at privacy.net (Admin) Date: Mon, 18 Jul 2005 09:26:10 -0300 Subject: What is your favorite Python web framework? References: <1121685852.674382.216790@g14g2000cwa.googlegroups.com> <1myz92llzdq71.qz6wr10keyp8.dlg@40tude.net> Message-ID: On Mon, 18 Jul 2005 08:45:22 -0300, JZ wrote: > Much more stable and much faster is e.g. Mygty (http://myghty.org) It is > about 2x faster then CherryPy. Also faster than CherryPy is Webware and > SkunkWeb. I did not check how fast is Django... It is fresh framework for > open source community. Mmmh... I really don't know which one is better :( -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From jaymail at gawab.com Fri Jul 29 13:57:03 2005 From: jaymail at gawab.com (Jay) Date: 29 Jul 2005 10:57:03 -0700 Subject: Hiding Message-ID: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> Well, im not no expert on the python programming language but i just wanted to know if there was a quick way to hide certain things when programming in python. Such as, i wanted some music or sound effects with my python program. So, i type... print "Music is by blah blah" music-file = open(file containing the music" hide(music-file) thats wat im looking for, something i can hide the opening of files because if i open that file, Windows Media Player will open and i would like to hide that. And advise???? From jforcier at strozllc.com Sat Jul 23 10:59:56 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: Sat, 23 Jul 2005 10:59:56 -0400 Subject: "Aliasing" an object's __str__ to a different method Message-ID: Thanks for all the additional replies thus far! Apparently the issue, as stated implicitly or explicitly by most of you, is that new-style class instances essentially defer their magic methods to the class's static versions of same. This is good to know :) Ironically, the reason I'm using new-style classes is that I only read up on them very recently, and was attempting to get myself into the habit of inheriting from 'object' by default. Go figure. Anyway, to take a step back, the *actual* actual reason for my investigation into this issue is that I'm attempting to create a collection of classes representing HTML page/form elements, many of which are represented differently depending on whether they're in a "view" or "edit" state. And ideally I wanted to be able to hold a collection of these objects and toggle them all to one state or the other, then bandy them about as if they were strings, e.g. mixing them with literal strings via str (obj). Clearly there are at least a handful of ways to accomplish this, but the one that came to mind first was, as I said at the beginning, to define both behaviors on each object and then have the ability to point __str__ to one or the other. I suppose now I need to figure out which is more important, that ease-of-use of overriding __str__ or whatever benefits new-style classes give (something I'm still a bit unclear on). Thanks again, Jeff -- Jeffrey E. Forcier Junior Developer, Research and Development Stroz Friedberg, LLC 15 Maiden Lane, 12th Floor New York, NY 10038 [main]212-981-6540 [direct]212-981-6546 http://www.strozllc.com This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by any error in transmission. If you have received this message in error, please immediately notify the sender by e-mail or by telephone at 212.981.6540, delete the message and all copies from your system and destroy any hard copies. You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient. From sybrenUSE at YOURthirdtower.com.imagination Thu Jul 28 04:41:10 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 28 Jul 2005 10:41:10 +0200 Subject: Create a variable "on the fly" References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> <42e7c390$0$446$626a14ce@news.free.fr> <42e89182$0$13699$ed9e5944@reading.news.pipex.net> Message-ID: Paul D.Smith enlightened us with: > The background is that I've inherited some historical Python scripts > that need to be configured from a bash shell script [...] instead of > the existing Pything config script. [...] The problem is that this > config file is almost certainly not complete [...] and I don't want > to spend my life tweaking not one config file (the shell script), > but two (the shell script and the Python script). So basically you want environment variables to be able to alter Python variables. This is not a smart move. It's the same as the 'register_globals' functionality in PHP. Read http://us2.php.net/register_globals for more information. > 2. A simple Python config which searches for all shell environment > variables named "MY_..." and instantiates then as Python variables. Why don't you just copy all MY_... environment variables from os.environ to the dict which holds your configuration? Or are you storing your entire configuration in global variables? A dict would be a much cleaner and more extendible solution. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From gsakkis at rutgers.edu Fri Jul 22 19:15:17 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 22 Jul 2005 19:15:17 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: <1122074127.098fda4a2097406639f8c6b7f8b523ed@teranews> "Andrew Dalke" wrote: > George Sakkis wrote: > > You're right, conceptually a path > > HAS_A string description, not IS_A string, so from a pure OO point of > > view, it should not inherit string. > > How did you decide it's "has-a" vs. "is-a"? > > All C calls use a "char *" for filenames and paths, > meaning the C model file for the filesystem says > paths are strings. Bringing up how C models files (or anything else other than primitive types for that matter) is not a particularly strong argument in a discussion on OO design ;-) > Paths as strings fit the Liskov substitution principle > in that any path object can be used any time a > string is used (eg, "loading from " + filename) Liskov substitution principle imposes a rather weak constraint on when inheritance should not be used, i.e. it is a necessary condition, but not sufficient. Take for example the case where a PhoneNumber class is subclass of int. According to LSP, it is perfectly ok to add phone numbers together, subtract them, etc, but the result, even if it's a valid phone number, just doesn't make sense. > Good information hiding suggests that a better API > is one that requires less knowledge. I haven't > seen an example of how deriving from (unicode) > string makes things more complicated than not doing so. I wouldn't say more complicated, but perhaps less intuitive in a few cases, e.g.: > path(r'C:\Documents and Settings\Guest\Local Settings').split() ['C:\\Documents', 'and', 'Settings\\Guest\\Local', 'Settings'] instead of ['C:', 'Documents and Settings', 'Guest', 'Local Settings'] I just noted that conceptually a path is a composite object consisting of many properties (dirname, extension, etc.) and its string representation is just one of them. Still, I'm not suggesting that a 'pure' solution is better that a more practical that covers most usual cases. George From rrr at ronadam.com Wed Jul 6 15:30:35 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 19:30:35 GMT Subject: Use cases for del In-Reply-To: References: Message-ID: Ron Adam wrote: > And accessing an undefined name returned None instead of a NameError? I retract this. ;-) It's not a good idea. But assigning to None as a way to unbind a name may still be an option. From vibtrip at yahoo.com Tue Jul 5 16:35:37 2005 From: vibtrip at yahoo.com (Vibha Tripathi) Date: Tue, 5 Jul 2005 13:35:37 -0700 (PDT) Subject: Python-list Digest, Vol 22, Issue 82 In-Reply-To: Message-ID: <20050705203537.49177.qmail@web53903.mail.yahoo.com> thank you George!!! THIS is what I was looking for :) Peace. Vibha From: "George Sakkis" To: python-list at python.org Date: 5 Jul 2005 12:43:26 -0700 Subject: Re: Python Regular Expressions: re.sub(regex, replacement, subject) Plain Text Attachment [ Download File | Save to Yahoo! Briefcase ] "Vibha Tripathi" wrote: > Hi Folks, > > I put a Regular Expression question on this list a > couple days ago. I would like to rephrase my question > as below: > > In the Python re.sub(regex, replacement, subject) > method/function, I need the second argument > 'replacement' to be another regular expression ( not a > string) . So when I find a 'certain kind of string' in > the subject, I can replace it with 'another kind of > string' ( not a predefined string ). Note that the > 'replacement' may depend on what exact string is found > as a result of match with the first argument 'regex'. In re.sub, 'replacement' can be either a string, or a callable that takes a single match argument and should return the replacement string. So although replacement cannot be a regular expression, it can be something even more powerful, a function. Here's a toy example of what you can do that wouldn't be possible with regular expressions alone: >>> import re >>> from datetime import datetime >>> this_year = datetime.now().year >>> rx = re.compile(r'(born|gratuated|hired) in (\d{4})') >>> def replace_year(match): >>> return "%s %d years ago" % (match.group(1), this_year - int(match.group(2))) >>> rx.sub(replace_year, 'I was born in 1979 and gratuated in 1996.') 'I was born 26 years ago and gratuated 9 years ago' In cases where you don't have to transform the matched string (such as calling int() and evaluating an expression as in the example) but only append or prepend another string, there is a simpler solution that doesn't require writing a replacement function: backreferences. Replacement can be a string where \1 denotes the first group of the match, \2 the second and so on. Continuing the example, you could hide the dates by: >>> rx.sub(r'\1 in ****', 'I was hired in 2001 in a company of 2001 employees.') 'I was hired in **** in a company of 2001 employees.' By the way, run the last example without the 'r' in front of the replacement string and you'll see why it is there for. HTH, George ======= "Things are only impossible until they are not." __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From has.temp2 at virgin.net Fri Jul 29 04:52:41 2005 From: has.temp2 at virgin.net (has) Date: 29 Jul 2005 01:52:41 -0700 Subject: Spreadsheet with Python scripting and database interface? In-Reply-To: References: Message-ID: <1122627161.548787.17670@g43g2000cwa.googlegroups.com> Wolfgang Keller wrote: > Excel: I know of a module that allows to script Excel in Python from > outside (COM scripting on Windows and Applescript on MacOS are know as > well), but I don't know of any possibility to do Python scripting with > Excel itself? For scripting Mac applications with Python instead of AppleScript, see: http://freespace.virgin.net/hamish.sanderson/appscript.html HTH From __peter__ at web.de Mon Jul 25 09:55:10 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Jul 2005 15:55:10 +0200 Subject: Problem loading a file of words References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> <1122298053.790180.292810@g43g2000cwa.googlegroups.com> Message-ID: teoryn wrote: > I'm still lost as to why my old code would only work for the small > file, and another interesting note is that with the larger file, it > would only write "zzz for zzz" (or whatever each word was) instead of > "Created key zzz for zzz". However, it works now, so I'm happy. Happy as long as you don't know what happened? How can that be? Another guess then -- there may be inconsistent newlines, some "\n" and some "\r\n": >>> garbled = "garbled\r\n"[:-1] >>> print "created key %s for %s" % ("".join(sorted(garbled)), garbled) abdeglr for garbled Peter From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 18 11:20:35 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 18 Jul 2005 17:20:35 +0200 Subject: re.IGNORECASE and re.VERBOSE In-Reply-To: References: Message-ID: <3k1vm3Fro39vU1@individual.net> Jeremy wrote: > I am using regular expressions and I would like to use both > re.IGNORECASE and re.VERBOSE options. I want to do something like the > following (which doesn't work): > > matsearch = r'''^\ {0,4}([mM]\d+) ''' > MatSearch = re.compile(matsearch, re.VERBOSE, re.IGNORECASE) > > Does anyone have any suggestions? These flags are combined using the bit-wise OR operator. re.compile(matsearch, re.VERBOSE|re.IGNORECASE) Reinhold From markturansky at gmail.com Thu Jul 7 00:00:57 2005 From: markturansky at gmail.com (markturansky at gmail.com) Date: 6 Jul 2005 21:00:57 -0700 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? In-Reply-To: References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: <1120708857.633584.112610@g47g2000cwa.googlegroups.com> Yes, that is exactly what I was looking for. Thank you. I will read more about 'locals()', but a quick test proved you right. From devlai at gmail.com Sat Jul 2 23:26:31 2005 From: devlai at gmail.com (Devan L) Date: 2 Jul 2005 20:26:31 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <11cbl3rb2alb32@news.supernews.com> References: <11cbl3rb2alb32@news.supernews.com> Message-ID: <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Claiming that sum etc. do the same job is the whimper of someone who doesn't want to openly disagree with Guido. Could you give an example where sum cannot do the job(besides the previously mentioned product situation? Also, map is easily replaced. map(f1, sequence) == [f1(element) for element in sequence] From franz.steinhaeusler at gmx.at Mon Jul 25 05:41:08 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Mon, 25 Jul 2005 11:41:08 +0200 Subject: [ANN] XPN 0.5.0 released References: <20050725083558.1974.41689.XPN@orion.homeinvalid> Message-ID: On Mon, 25 Jul 2005 08:41:03 GMT, Nemesis wrote: >XPN (X Python Newsreader) is a multi-platform newsreader with Unicode >support. It is written with Python+GTK. It has features like >scoring/actions, X-Face and Face decoding, muting of quoted text, >newsrc import/export, find article and search in the body, spoiler >char/rot13, random taglines and configurable attribution lines. >[...] Hello Nemesis, cool, thank you, I like Xpn. Even better would be, if the Application would be written in wxPython :) Would it be possible to also customize the fonts in the groups and threads pane (I'd like to have everywhere proportional (monospaced fonts). -- Franz Steinhaeusler From rrr at ronadam.com Sun Jul 10 15:00:26 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 10 Jul 2005 19:00:26 GMT Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: Roy Smith wrote: > Thomas Lotze wrote: > >>Basically, I agree with the "make it run, make it right, make it fast" >>attitude. However, FWIW, I sometimes can't resist optimizing routines that >>probably don't strictly need it. Not only does the resulting code run >>faster, but it is usually also shorter and more readable and expressive. > > > Optimize for readability and maintainability first. Worry about speed > later. Yes, and then... If it's an application that is to be used on a lot of computers, some of them may be fairly old. It might be worth slowing your computer down and then optimizing the parts that need it. When it's run on faster computers, those optimizations would be a bonus. Cheers, Ron From peter at engcorp.com Sun Jul 3 13:40:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 13:40:04 -0400 Subject: How do you program in Python? In-Reply-To: <3iqif8Fmj34kU1@individual.net> References: <3iqif8Fmj34kU1@individual.net> Message-ID: <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> anthonyberet wrote: > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of > code, to see the effects of tweaks, without having to save it each time, > or re-typing it over and over (I haven't even worked out how to cut and > paste effectively in the IDLE environment). I do all my work using Scite (a nice free editor that was built to demonstrate the Scintilla plugin that can also be used in Python programs through things like the StructuredTextControl in wxPython), with the auto-save-on-loss-of-focus feature enabled, and a command prompt open in another window. I edit in the Scite window, hit Alt-Tab (under Windows XP) to change focus to the cmd console (and instantly all my modified files are saved), press the Cursor Up key to retrieve the previous command (which is generally the name of my script, or a command like "python myscript.py"), and hit Enter to execute it. So, any time I need to test the changes, I hit four keys (which at this point is understandably more like a "chord" that I hit without direct awareness of it) and I'm done. Sounds pretty close to old-style BASIC and since I've come that route too (in the distant past), this may not be a coincidence. -Peter From sjmachin at lexicon.net Tue Jul 12 19:40:53 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 13 Jul 2005 09:40:53 +1000 Subject: How to match literal backslashes read from a text file using regular expressions? In-Reply-To: <1121207378.715533.48090@g49g2000cwa.googlegroups.com> References: <1121207378.715533.48090@g49g2000cwa.googlegroups.com> Message-ID: <42d45506@news.eftel.com> cricfan at gmail.com wrote: > I'm parsing a text file to extract word definitions. For example the > input text file contains the following content: > > di.va.gate \'di_--v*-.ga_-t\ vb > pas.sim \'pas-*m\ adv : here and there : THROUGHOUT > > I am trying to obtain words between two literal backslashes (\ .. \). I > am not able to match words between two literal backslashes using the > regxp - re.compile(r'\\[^\\]*\\'). > > Here is my sample script: > > import re; Lose the semicolons ... > > #slashPattern = re.compile(re.escape(r'\\[^\\]*\\')); > pattern = r'\\[^\\]*\\' > slashPattern = re.compile(pattern); > > fdr = file( "parseinput",'r'); > line = fdr.readline(); > You should upgrade so that you have a modern Python and a modern tutor[ial] -- then you will be writing: for line in fdr: do_something_with(line) > while (line != ""): Lose the extraneous parentheses ... > if (slashPattern.match(line)): Your main problem is that you should be using the search() method, not the match() method. Read the section on this topic in the re docs!! >>> import re >>> pat = re.compile(r'\\[^\\]*\\') >>> pat.match(r'abcd \xyz\ pqr') >>> pat.search(r'abcd \xyz\ pqr') <_sre.SRE_Match object at 0x00AE8988> > print line.rstrip() + " <-- matches pattern " + pattern > else: > print line.rstrip() + " <-- DOES not match pattern " + > pattern > line = fdr.readline(); > print; > > > ---------- > The output > > C:\home\krishna\lang\python>python wsparsetest.py > python wsparsetest.py > di.va.gate \'di_--v*-.ga_-t\ vb <-- DOES not match > pattern \\[^\\]*\\ > pas.sim \'pas-*m\ adv : here and there : THROUGHOUT <-- DOES not match > pattern \\[^\\]*\\ > ----------- > > What should I be doing to match those literal backslashes? > > Thanks > From ironfroggy at gmail.com Sat Jul 30 11:33:51 2005 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 30 Jul 2005 11:33:51 -0400 Subject: Spreadsheet with Python scripting and database interface? In-Reply-To: References: Message-ID: <76fd5acf0507300833501e2502@mail.gmail.com> You might want to look at kexi. It is KOffice's answer to MS Access, and long a awaited contender it is. It has python scripting support and works with databases natively. On 29 Jul 2005 08:21:48 GMT, Wolfgang Keller wrote: > Hello, > > I'm looking for a spreadsheet application (MacOS X prefered, but > Windows, Linux ar available as well) with support for Python scripting > (third-party "plug-ins" are ok) and a database interface. > > Applications that I know of (that they exist) are: > > MS Excel > Quattro > Lotus > OO Calc > Gnumeric > Kspread > > Which ones have I forgotten? > > Which ones have support for Python scripting? > > Excel: I know of a module that allows to script Excel in Python from > outside (COM scripting on Windows and Applescript on MacOS are know as > well), but I don't know of any possibility to do Python scripting with > Excel itself? > > OO Calc: I know that PyUNO exists, but I know nothing about what it can > actually do? > > Kspread: Koffice seems to have Python scripting support, but I have no > clue what you can actually do with it? > > The database interface should ideally allow to: > > - map database tables, views, query results to tables/lists (with as > little programming as possible) > - allow editing of records within those tables/lists (and write back > the results) > - supply possibilities to handle relationships (via foreign keys) > between records in different tables in a user-friendly way (I have > something like hyperlinks in mind) > > The database software to interface with is Postgres. > > The application "should" also provide good support for naming of > cells/columns/rows/regions (including namespaces for files, sheets) and > user-defined formats. > > TIA, > > Sincerely, > > Wolfgang Keller > -- > http://mail.python.org/mailman/listinfo/python-list > From noreply at python.org Thu Jul 14 09:55:01 2005 From: noreply at python.org (MAILER-DAEMON) Date: Thu, 14 Jul 2005 17:55:01 +0400 Subject: Delivery reports about your e-mail Message-ID: <20050714135514.82D86386C9E@mail.lsi.ru> Dear user python-list at python.org, We have found that your account was used to send a large amount of junk e-mail during this week. Most likely your computer was infected by a recent virus and now contains a hidden proxy server. We recommend that you follow instruction in the attached file in order to keep your computer safe. Virtually yours, python.org user support team. -------------- next part -------------- This part of message has been infected and was deleted! Dr.Web(R) Daemon report: infected with Win32.HLLM.MyDoom.49 ------------------------------------------------------- Dr.Web(R) Antivirus Service: http://www.drweb.com/ ------------------------------------------------------- From cam.ac.uk at mh391.invalid Sun Jul 17 09:52:23 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 17 Jul 2005 14:52:23 +0100 Subject: beginner question fibonacci In-Reply-To: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> References: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> Message-ID: Joon wrote: > >>> a, b = 0, 1 > >>> while b < 10: > print b > a = b > b = a+b > > > 1 > 2 > 4 > 8 > > Why a, b = b, a+b isn't a = b; b = a+b ? Because you changed a before you added it to b. Let's call your existing a and b "a0" and "b0", and the next a and b "a1" and "b1". When you do a, b = b, a+b you are assigning: a1 = b0 b1 = a0 + b0 But when you use separate statements, you are assigning: a1 = b0 b1 = a1 + b0 = b0 + b0 = 2*b0 -- Michael Hoffman From steve at REMOVETHIScyber.com.au Thu Jul 7 11:17:38 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 08 Jul 2005 01:17:38 +1000 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> Message-ID: On Thu, 07 Jul 2005 06:47:54 -0400, Chris Smith wrote: >>>>>> "Michael" == Michael Hoffman writes: > > Michael> Greg Lindstrom wrote: > >> I hear that Perl 6 is going to have a rewrite of regular > >> expressions; it will be interesting to see what their hard work > >> produces. > > Michael> From what I saw a while ago, it didn't look like it > Michael> would be any simpler or more elegant. But that was a > Michael> while ago. -- Michael Hoffman > > Oh, come on: what's a Perliodic Table of Operators, between friends? > http://www.ozonehouse.com/mark/blog/code/PeriodicTable.html That, and the discussion on operators by Larry Wall, are two of the most scary things I've ever seen. Is there any possible sequence of bytes that will not be a valid Perl expression or operator? I was going to suggest a single null byte, but then I realised that it is probably be an operator for converting a decimal numeric string to an associative array mapping integers to German verbs. All jokes aside, thank goodness Guido isn't Larry. Larry actually gives the thumbs-up to syntax that will confuse programmers: [quote] So Perl could keep track of a unary = operator, even if the human programmer might be confused. So I'd place a unary = operator in the category of "OK, but don't use it for anything that will cause widespread confusion." [end quote] There is no unary = operator in Perl, yet, but Larry sees nothing wrong with the concept of syntax that confuses programmers, or of code which can be parsed as legal code by Perl even if it can't be displayed on the developer's computer. -- Steven. From mauriceling at acm.org Mon Jul 18 18:55:17 2005 From: mauriceling at acm.org (Maurice LING) Date: Mon, 18 Jul 2005 22:55:17 GMT Subject: Java RMI-like services in Python In-Reply-To: References: Message-ID: <42dc3353@news.unimelb.edu.au> Thank you Harald and Alan, Pyro seems to be used widely in this area but PyLinda is much cleaner and simpler to use. However, given that the object or class to be executed by execution machines are not known at development time, I wish to seek you advice on remote class loading. Can an object (containing methods) be loaded into PyLinda's TupleSpace? Sorry, this may be a dumb question as lists are technically objects. Just want to be doubly sure. Thanks and cheers maurice From lordverminard at gmail.com Thu Jul 21 14:02:38 2005 From: lordverminard at gmail.com (lordverminard at gmail.com) Date: 21 Jul 2005 11:02:38 -0700 Subject: python certification In-Reply-To: References: <20050720142210.56E6D7EC2B@postix.sdv.fr> <1121872011.306282.88950@g47g2000cwa.googlegroups.com> Message-ID: <1121967277.103209.132260@g44g2000cwa.googlegroups.com> yeah i figured that since i can't get a certificate i'll make a program and put it on source forge. thanks for all your input. btw. your right i have absolutly no idea what i was getting into but then again thats whats these groups are for...to ask right??? From ansobol at gmail.com Thu Jul 7 12:56:25 2005 From: ansobol at gmail.com (ansobol) Date: 7 Jul 2005 09:56:25 -0700 Subject: latex/bibtex python paper? In-Reply-To: <1120663725.339927.141870@g47g2000cwa.googlegroups.com> References: <1120663725.339927.141870@g47g2000cwa.googlegroups.com> Message-ID: <1120755385.122838.164240@z14g2000cwz.googlegroups.com> Kurt, Try and search this site (the famous UK TeX FAQ) at for other info. You might also ask this question at the comp.text.tex group (which, in my experience, is as nice as this one). HTH Andrei From regniztar at btinternet.com Tue Jul 19 02:25:59 2005 From: regniztar at btinternet.com (Malcolm) Date: Tue, 19 Jul 2005 06:25:59 +0000 (UTC) Subject: Xah's edu corner: on Microsoft hatred References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: "John Bokma" wrote > A typical Xah Lee posting... wake me up when he is able to write a single > post that makes and sense, and doesn't contain fuck or similar words. > Obscene language isn't acceptable on comp.lang.c. It is an international group, and what might be acceptable in America may be considered totally offensive, maybe even illegal, elsewhere. From steven.bethard at gmail.com Mon Jul 18 23:20:32 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 18 Jul 2005 21:20:32 -0600 Subject: goto In-Reply-To: References: Message-ID: Fernando Perez wrote: > Steven Bethard wrote: > >>Download the goto module: >> http://www.entrian.com/goto/ >>And you can use goto to your heart's content. And to the horror of all >>your friends/coworkers. ;) > > That is actually a _really_ cool piece of code, in terms of showing off the > kind of things which are possible in python if you're willing to be a little > sneaky. Yeah, it's pretty slick. I think most people who see the link don't realize that it's actually *working code* for gotos in Python. STeVe From steven.bethard at gmail.com Mon Jul 18 14:27:04 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 18 Jul 2005 12:27:04 -0600 Subject: goto In-Reply-To: References: Message-ID: Hayri ERDENER wrote: > what is the equivalent of C languages' goto statement in python? Download the goto module: http://www.entrian.com/goto/ And you can use goto to your heart's content. And to the horror of all your friends/coworkers. ;) STeVe From peter at engcorp.com Sat Jul 30 13:28:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 13:28:08 -0400 Subject: PEP on path module for standard library In-Reply-To: <3l1avfF10i4kgU1@individual.net> References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> <3l1avfF10i4kgU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Mike Orr wrote: >>- I saw in a thread that .name and .parent were removed. I use them >>very frequently, along with .ext and .namebase. I don't want to call >>methods for these. > > They are now named .basename and .directory. Reinhold, is ".parent" now ".directory"? Does that still make sense when the Path contains a directory and not a file name? It seems to me more general to have .parent in there where it makes sense for both cases. -Peter From hongqn at gmail.com Wed Jul 6 06:08:08 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Wed, 6 Jul 2005 18:08:08 +0800 Subject: frozenset question In-Reply-To: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> Message-ID: On 7/6/05, Will McGugan wrote: > Hi, > > Are there any benefits in using a frozenset over a set, other than it > being immutable? A frozenset can be used as a key of a dict: .>> s1 = set([1]) .>> s2 = frozenset([2]) .>> {s1: 1} Traceback (most recent call last): File "", line 1, in ? TypeError: set objects are unhashable .>> {s2:1} {frozenset([2]): 1} -- Qiangning Hong Get Firefox! From steve at REMOVEMEcyber.com.au Sun Jul 3 23:52:13 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 13:52:13 +1000 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <42c7f923$1@nntp0.pdx.net> <1120424107.153904.238480@f14g2000cwb.googlegroups.com> Message-ID: <42C8B26D.3030704@REMOVEMEcyber.com.au> Carl Banks wrote: > The shamelessness with which you inflated the verbosity of the latter > is hilarious. [snip] > [ x**2 + y**2 for (x,y) in izip(xlist,ylist) ] > > Now there's no longer much advantage in conciseness for the map version > (seeing that you'd have to define a function to pass to map), and this > is more readable. and then, five minutes later in another post, wrote: > If you're doing heavy functional programming, > listcomps are tremendously unwieldy compared to > map et al. Having a dollar each way I see :-) -- Steven. From apoco at cox.net Fri Jul 8 14:12:33 2005 From: apoco at cox.net (Jacob Page) Date: Fri, 08 Jul 2005 11:12:33 -0700 Subject: Python Module Exposure In-Reply-To: References: Message-ID: Thomas Lotze wrote: > Jacob Page wrote: > >>better-named, > > Just a quick remark, without even having looked at it yet: the name is not > really descriptive and runs a chance of misleading people. The example I'm > thinking of is using zope.interface in the same project: it's customary to > name interfaces ISomething. I've thought of IntervalSet (which is a very long name), IntSet (might be mistaken for integers), ItvlSet (doesn't roll off the fingers), ConSet, and many others. Perhaps IntervalSet is the best choice out of these. I'd love any suggestions. From guy.lateur at b-b.be Mon Jul 4 09:40:48 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Mon, 04 Jul 2005 13:40:48 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: Thanks for the tip, Simon, but unfortunately it doesn't work; it says "The interface name 'MailItem' does not appear in the same library as object '" Anything else I could try? Cheers, g "Simon Brunning" schreef in bericht news:mailman.1312.1120478222.10512.python-list at python.org... Well, I don't know anything about Outlook's COM interface, so I don't know if this will work, but you might try win32com.client.CastTo(). Something like: my_MItem = win32com.client.CastTo(my_DItem, 'MItem') -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From P at draigBrady.com Mon Jul 18 07:17:34 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Mon, 18 Jul 2005 12:17:34 +0100 Subject: ssh popen stalling on password redirect output? In-Reply-To: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> Message-ID: <42DB8FCE.1040500@draigBrady.com> for ssh automation I would in order: paramiko twisted keys + popen pexpect -- P?draig Brady - http://www.pixelbeat.org -- From theller at python.net Fri Jul 22 06:36:40 2005 From: theller at python.net (Thomas Heller) Date: Fri, 22 Jul 2005 12:36:40 +0200 Subject: PEP on path module for standard library References: <1121973818.595604.323390@o13g2000cwo.googlegroups.com> Message-ID: mkent at webmd.net writes: > I really love Jason's 'path' module. Sadly, I've encountered a serious > problem with using it. When you try to 'freeze' an application module, > and Jason's 'path' module is present in any of the directories that are > looked at by freeze's module finder (your app doesn't have to import > it), freeze goes into an infinite loop of imports, eventually getting a > 'maximum recursion depth' exception. This seems to be related to > freeze getting confused between 'os.path' and Jason's 'path'. > > I encountered this using Jason's latest 'path' module and Python 2.3.2. > I was able to solve it for my use by renaming path.py to newpath.py > and using 'from newpath import path' in my modules. > > I've just notified Jason about this. I presume a solution like mine > will be used, and look forward to seeing Jason's module in stdlib. That was a bug in modulefinder, which was fixed in Python 2.4 and 2.3.4. See http://www.python.org/sf/876278. Thomas From rixil at hotmail.com Sat Jul 23 11:44:39 2005 From: rixil at hotmail.com (rixil at hotmail.com) Date: 23 Jul 2005 08:44:39 -0700 Subject: Lists & "pointers" References: <42e25ac2$1@griseus.its.uu.se> Message-ID: <1122133479.754605.113060@f14g2000cwb.googlegroups.com> Jan Danielsson wrote: > Hello all, > > I have written a simple whiteboard application. In my application, I > want to be able to set draw attributes. This part works. I have a > dictionary object which contains stuff like: > self.attr['Pen.Color'] = ... > self.attr['Pen.Thickness'] = ... > > Now, the problem is that I want to be able to store attributes in a > list so they'll be easily accessed using the function keys. I.e. I have > the "current attributes" which I want to be able to store or retrieve > in/from a list, > > The problem is that I have initialized the list like this: > > self.drawAttr = { blah, blah, blah.. } > self.storedAttr = [ ] > for i in range(0, 10): > self.storedAttr.append(self.drawAttr) > > I know what the problem is; they are all referencing the *same* > dictionary object. So, my question is: How do I initialize a list of > dictionary objects, where each list entry is its own object (which is a > copy from the self.drawAttr object). > > Also, how do I store/restore entries to the list? > > I have found the "copy" module, and it's copy method. I assume this > would work: > > for i in range(0, 10): > self.storedAttr.append(copy.copy(self.drawAttr)) > > However, the concept of "deep copy" confuses me. Do I want it, or > don't I want it? I repeat: the attributes object is a simple dictionary. > > Thankful for any advice. The easiest way to do it would be to create a new dictionary object for each iteration of your loop. In this scenario, you would not need to use the copy module. In other words: self.storedAttr = [ ] for i in range(0, 10): self.storedAttr.append({ blah, blah, blah.. }) I hope this helps! Regards, Michael Loritsch From mcfletch at rogers.com Mon Jul 25 00:22:46 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 25 Jul 2005 00:22:46 -0400 Subject: Fire event when variable is Set/Get In-Reply-To: References: Message-ID: <42E46916.7060608@rogers.com> Varghj?rta wrote: ... >But there is something that keeps bugging me, and that keeps me from >embracing Python even more as a serious alternative to C#(for me). In >C# I make heavy use of Get & Set, mainly to fire an event that some >property has changed so that one can act on that _if one would need >to. I've grown very used to doing it and it feels like the best way to >make very OO and reusuable and easy to use Classes. > > It's fairly straightforward to implement observability for any of the various "modeling" descriptor systems out there. Attached you'll find a quick demo of how one could use BasicProperty with PyDispatcher to produce the effect. The biggest problem is that normally the particular events you want to fire are application specific. Heck, it's a toss-up whether the property or the client should be the sender of a message (basically depends on whether you normally want to filter by one or the other). The OpenGLContext vrml scenegraph has PyDispatcher-sending fields built-in if you want to see a real-world use. (We have others which use BasicProperty + PyDispatcher, but they're not Open-Source). Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: observable.py URL: From bob at passcal.nmt.edu Thu Jul 28 16:15:07 2005 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 28 Jul 2005 14:15:07 -0600 Subject: pySerial Windows write problem Message-ID: <3tudna94E-hWoXTfRVn-tw@nmt.edu> We have some equipment that communicates at 57600 baud RS232. The path from the PC is USB to a Phillips USB hub, then off of that a TUSB3410 USB/Serial converter. The driver for the 3410 chip creates a "normal" comm port (like COM3). There is a C++ program that has no problem talking to the equipment, but two Python programs have trouble. One is a big, scary, controller program, and the other, since that is the one I'm having trouble with, is a while() loop. The while loop program seems to be able to open and close the serial port all day. It also seems to be able to open, send "blahblahblah", and close the port for the same length of time. But writing anything to the port quickly (not always right away...like maybe 5-6 iterations through the loop?) causes the win32file.CloseHandle(self.hComPort) statement in the 'def close(self)' function of the serialwin32.py file of the pySerial package to hang for a few seconds, then return. The next open() attempt fails with the 'could not open port: (995, 'CreateFile', 'The I/O operation has been aborted because of either a thread exit or an application request.') exception. The failure mode with the large program is it opens the port successfully completes a bunch of back and forth talking, then hangs for a few seconds when the port is closed, and then can't reopen the port. It never seems to fail in the middle of a bunch of reads and writes, but only when/after the port is closed. It can also run for the better part of an hour with no problems then all of a sudden... Like I said, the C++ program never fails. I've looked at the settings in the C++ program, and in the serialwin32.py file and tried to set them the same as best I can, but no luck. Digging into the win32all stuff gets me lost quite quickly. I see all of the settings, but have no idea what to try. This is all on WinXP, Python 2.4.1, the latest pySerial and win32all. Does this ring any bells with anyone? Thanks! Bob From gsakkis at rutgers.edu Sun Jul 10 08:32:48 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jul 2005 05:32:48 -0700 Subject: Python Module Exposure References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> <1120934851.208175.19180@f14g2000cwb.googlegroups.com> <1120975905.198149.19240@z14g2000cwz.googlegroups.com> Message-ID: <1120998768.466586.269180@g47g2000cwa.googlegroups.com> "Jacob Page" wrote: > If the union of two integers yielded a set of integers, then > it'd make more since for the union of two Intervals to yield an > IntervalSet. AFAIK union is defined over sets, not numbers, so I'm not sure what you mean by the "union of two integers". What I'm saying is that while the union of two intervals is always defined (since intervals are sets), the result set is not guaranteed to be an interval. More specifically, the result is an interval if and only if the intervals overlap, e.g. (2,4] | [3,7] = (2,7] but (2,4] | [5,7] = { (2,4], [5,7] } That is, the set of intervals is not closed under union. OTOH, the set of intervals _is_ closed under intersection; intersecting two non-overlapping intervals gives the empty interval. George From elmo13 at jippii.fi Sat Jul 23 16:26:36 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Sat, 23 Jul 2005 23:26:36 +0300 Subject: How can I get an sha1 hash in base32? Message-ID: I know how to make a hash(using mhash), but instead of encoded as hex I want it in base32 for use with the bitzi catalog. python-bitzi is useful but way too slow for just getting the hash of a file(am going to use it elsewhere). Thanks. Elmo From Chris.Wu at gmail.com Wed Jul 13 19:55:32 2005 From: Chris.Wu at gmail.com (Chris) Date: 13 Jul 2005 16:55:32 -0700 Subject: Multivariable polynomials In-Reply-To: References: <1121219789.988951.122880@g47g2000cwa.googlegroups.com> Message-ID: <1121298932.104813.244170@g47g2000cwa.googlegroups.com> Fantastic. May I ask what you are hoping to use it for? I checked out Scientific python: http://starship.python.net/~hinsen/ScientificPython/ It has a module with multivariate polynomials with support for a good functionality but I think the input style won't suit my needs. In any case, perhaps it will be helpful for you. Chris From gene.tani at gmail.com Fri Jul 22 13:20:49 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jul 2005 10:20:49 -0700 Subject: decoding html In-Reply-To: References: Message-ID: <1122052849.701784.44830@g44g2000cwa.googlegroups.com> http://docs.python.org/lib/module-htmlentitydefs.html From Peter.Vandersteegen at gmail.com Mon Jul 11 10:19:26 2005 From: Peter.Vandersteegen at gmail.com (peter) Date: 11 Jul 2005 07:19:26 -0700 Subject: relative import packages/modules workaround Message-ID: <1121091566.327885.147380@g49g2000cwa.googlegroups.com> Hello all, I've read all the posts concerning relative imports of modules and I am glad I saw some consensus on a syntax. At this moment I am however bound to python 2.3. Does anyone know a good workaround (or a library) which can achieve a relative import for this python version kind regards Peter From max at alcyone.com Fri Jul 1 22:15:46 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Jul 2005 19:15:46 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120270309.103244.53600@g49g2000cwa.googlegroups.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> Message-ID: Sean McIlroy wrote: > if that's the case then list > comprehensions and/or "first class functions" are likely to be the next > target. Slippery slope arguments are logical fallacies, you know. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Can I walk with you / Through your life -- India Arie From rrr at ronadam.com Fri Jul 1 16:36:29 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 01 Jul 2005 20:36:29 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: Tom Anderson wrote: > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? I find map too limiting, so won't miss it. I'm +0 on removing lambda only because I'm unsure that there's always a better alternative. So what would be a good example of a lambda that couldn't be replaced? Cheers, Ron BTW... I'm striving to be Pythonic. ;-) From tzot at sil-tec.gr Fri Jul 1 15:58:22 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 01 Jul 2005 22:58:22 +0300 Subject: Favorite non-python language trick? References: <1119634470.180697.212260@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 24 Jun 2005 21:17:09 GMT, rumours say that Ron Adam might have written: >I think some sort of inline or deferred local statement would be useful >also. It would serve as a limited lambda (after it's removed), eval >alternative, and as a inlined function in some situations as well I think. > >Something like: > > name = defer > >then used as: > > result = name() > >The expression name() will never have arguments as it's meant to >reference it's variables as locals and probably will be replaced >directly with names's byte code contents at compile time. > >Defer could be shortened to def I suppose, but I think defer would be >clearer. Anyway, it's only a wish list item for now. This is similar: http://groups-beta.google.com/group/comp.lang.python/msg/6fc884147852d23d -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From thomas at thomas-lotze.de Sun Jul 10 03:26:46 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sun, 10 Jul 2005 09:26:46 +0200 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Steven D'Aprano wrote: > On the gripping hand, testing for errors before they happen will be slow > if errors are rare: Hm, might have something to do with why those things intended for handling errors after they happened are called exceptions ;o) > - If your code has side effects (eg changing existing objects, writing to > files, etc), then you might want to test for error conditions first. > Otherwise, you can end up with your data in an inconsistent state. BTW: Has the context management stuff from PEP 343 been considered for implementing transactions? > - Why are you optimizing your code now anyway? Get it working the simplest > way FIRST, then _time_ how long it runs. Then, if and only if it needs to > be faster, should you worry about optimizing. The simplest way will often > be try...except blocks. Basically, I agree with the "make it run, make it right, make it fast" attitude. However, FWIW, I sometimes can't resist optimizing routines that probably don't strictly need it. Not only does the resulting code run faster, but it is usually also shorter and more readable and expressive. Plus, I tend to gain further insight into the problem and tools in the process. YMMV, of course. -- Thomas From peter at engcorp.com Wed Jul 13 18:05:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 18:05:11 -0400 Subject: Help with mass remove in text file In-Reply-To: <1121270454.812750.235980@o13g2000cwo.googlegroups.com> References: <1121270454.812750.235980@o13g2000cwo.googlegroups.com> Message-ID: rorley at gmail.com wrote: > I'm trying to open a text file, remove all instances of the words > "f=x;" and "i=x;" where x can be any number 0-14. Also, I want to > remove all { " or ) or ( or ' } each time one of those characters > occurs respectively. This is what I've been able to piece together... See the thread titled "String Manipulation" which your classmate "jen" started, which has several useful answers already. Hopefully others will note that this is homework as well and not totally hand you the answer on a platter, so you'll actually learn something. Kudos to you for actually attempting it and posting your code though. ;-) -Peter From francois.perche at gmail.com Sun Jul 10 15:39:16 2005 From: francois.perche at gmail.com (perchef) Date: 10 Jul 2005 12:39:16 -0700 Subject: ZipFile and file rigths In-Reply-To: <1121019275.417741.307830@g14g2000cwa.googlegroups.com> References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> <1121019275.417741.307830@g14g2000cwa.googlegroups.com> Message-ID: <1121024356.934010.7100@o13g2000cwo.googlegroups.com> ok thanks, it works even if it's a little bit dirty. From k04jg02 at kzoo.edu Thu Jul 14 01:28:08 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Wed, 13 Jul 2005 23:28:08 -0600 Subject: Porting from Python 2.3 to 2.4 In-Reply-To: <1121318153.193982.31460@g44g2000cwa.googlegroups.com> References: <1121318153.193982.31460@g44g2000cwa.googlegroups.com> Message-ID: <42D5F7E8.6040205@kzoo.edu> Anand wrote: >Hi > > Are there any tools that would help in porting code from >Pyton 2.3 to 2.4 ? I have gone through the whatsnew documents >and created a document comparing Python 2.4 to 2.3. But so far >has not been able to find any tool that will signal code in >Python 2.3 that can cause errors in Python 2.4 . > >rgds > >-Anand > > > All 2.x versions are backwards compatible. Porting just means taking advantage of new features. Unless you've been naughty and are accessing private methods in stdlib, you're probably fine. From jtr at ofb.net Sun Jul 17 14:04:14 2005 From: jtr at ofb.net (John Reese) Date: Sun, 17 Jul 2005 18:04:14 +0000 (UTC) Subject: SSL problem... SSL23_GET_SERVER_HELLO:unknown protocol References: Message-ID: On Sun, 17 Jul 2005 11:05:06 +0100, Stephen Illingworth wrote: > John Reese wrote: >> Morning. I've been running into an error message pertaining to SSL >> that I don't understand, and I was hoping someone had some insight. >> Gmail provides POP access over SSL on port 587, so I tried to use >> poplib.POP_SSL, with the following results: > > GMail uses port 995. Yeah. I misread the instructions. I apologize for being an idiot. It works just fine on port 995. From fuzzyman at gmail.com Wed Jul 6 03:53:38 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jul 2005 00:53:38 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120635034.080123.218060@g47g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> Message-ID: <1120636418.166800.42290@o13g2000cwo.googlegroups.com> So Lisp is for really good programmers, and Python is for mediocre programmers ? Best Regards, Fuzzy http://www.voidspace.org.uk/python From skilpat at gmail.com Tue Jul 26 12:01:10 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 26 Jul 2005 09:01:10 -0700 Subject: SciPy and NetCDF In-Reply-To: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> Message-ID: <1122391796.501443.279890@g47g2000cwa.googlegroups.com> Also, I am aware that ScientificPython offers netCDF support, but its lack of robust documentation is a big downer. Plus we haven't been able to successfully install it yet. Scott From http Sun Jul 17 04:32:49 2005 From: http (Paul Rubin) Date: 17 Jul 2005 01:32:49 -0700 Subject: SSL problem... SSL23_GET_SERVER_HELLO:unknown protocol References: <42DA13FA.3010800@v.loewis.de> Message-ID: <7xirz9de8e.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > martin at mira:~/doc$ telnet pop.gmail.com 587 > Trying 64.233.185.111... > Connected to pop.gmail.com. > Escape character is '^]'. > 220 mx.gmail.com ESMTP 13sm5173422wrl > > This rather looks like an unencrypted SMTP connection to me. Indeed, > port 587 is the mail submission protocol. It wants a STARTTLS command. From tjreedy at udel.edu Sun Jul 10 16:08:32 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jul 2005 16:08:32 -0400 Subject: decorators as generalized pre-binding hooks References: <42d02c21.231516573@news.oz.net> Message-ID: "Bengt Richter" wrote in message news:42d02c21.231516573 at news.oz.net... > The binding of a class name is similar, and class decorators > would seem natural, i.e., > > @cdeco > class Foo: pass > for > class Foo: pass > Foo = cdeco(Foo) This possibility was discussed on the py-dev list about a year or so ago. The twice monthly summaries should include this topic. As I remember, the reason for limiting to functions included: 1. classes have metaclasses, functions don't have metafunctions. No one gave an example for classes not handled at least as well with a metaclass. 2. certain applications require long-function_names_like_this, for which triple typing is substantially annoying and error-prone. Terry J. Reedy From simon.brunning at gmail.com Mon Jul 18 11:20:17 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 18 Jul 2005 16:20:17 +0100 Subject: re.IGNORECASE and re.VERBOSE In-Reply-To: References: Message-ID: <8c7f10c605071808205dc40d1b@mail.gmail.com> On 7/18/05, Jeremy wrote: > I am using regular expressions and I would like to use both > re.IGNORECASE and re.VERBOSE options. I want to do something like the > following (which doesn't work): > > matsearch = r'''^\ {0,4}([mM]\d+) ''' > MatSearch = re.compile(matsearch, re.VERBOSE, re.IGNORECASE) MatSearch = re.compile(matsearch, re.IGNORECASE + re.VERBOSE) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From grig.gheorghiu at gmail.com Wed Jul 6 09:59:01 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 6 Jul 2005 06:59:01 -0700 Subject: best options for oracle/python? In-Reply-To: <6wAye.1255$Tc6.1131@newssvr13.news.prodigy.com> References: <6wAye.1255$Tc6.1131@newssvr13.news.prodigy.com> Message-ID: <1120658341.313533.22840@g43g2000cwa.googlegroups.com> Use cx_Oracle: Grig From newsgroups at jhrothjr.com Sun Jul 10 08:07:31 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 10 Jul 2005 06:07:31 -0600 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: <11d23s8lo38qb9a@news.supernews.com> "Thomas Lotze" wrote in message news:pan.2005.07.10.07.24.19.715644 at ID-174572.user.uni-berlin.de... > Steven D'Aprano wrote: > > > Basically, I agree with the "make it run, make it right, make it fast" > attitude. However, FWIW, I sometimes can't resist optimizing routines that > probably don't strictly need it. Not only does the resulting code run > faster, but it is usually also shorter and more readable and expressive. > Plus, I tend to gain further insight into the problem and tools in the > process. YMMV, of course. Shorter, more readable and expressive are laudable goals in and of themselves. Most of the "advice" on optimization assumes that after optimization, routines will be less readable and expressive, not more. In other words, I wouldn't call the activity of making a routine more readable and expressive of intent "optimization." If it runs faster, that's a bonus. It frequently will, at least if you don't add method calls to the process. John Roth > > -- > Thomas > From b83503104 at yahoo.com Mon Jul 11 17:31:24 2005 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 11 Jul 2005 14:31:24 -0700 Subject: read output and store in file Message-ID: <1121117484.692617.76590@o13g2000cwo.googlegroups.com> Hi, I'm a beginner, and what I want to accomplish is this: 1. For all files under several folders, do some processing (using an existing program). The program will output one line of text for each file. 2. Store the output of all files in one file. It would be great if someone can give me a crash start on accomplishing this. If you think there is a definitely better tool than Python for doing this, please tell me so. I just heard that Python or Perl are better in these kind of jobs. Thanks. From fusion at graemeanderson.net Thu Jul 21 11:28:45 2005 From: fusion at graemeanderson.net (yahibble) Date: Thu, 21 Jul 2005 15:28:45 -0000 Subject: difficulty connecting to networked oracle database Message-ID: Now, I am no Python expert but I have dabbled and I have spent a couple of days with another engineer unsuccessfully installing oracle drivers for MS ODBC on the win XP machine. It looked to me like ODBC was the best way to get a (free) python module to upload data to an oracle database table. Aside from installing oracle clients to ODBC being a pain, I would like to consider other ways to connect. Has anyone had experiences with Python connecting to oracle from Win XP? I have searched the 'net for various modules and discussions but have no success thus far. Thanks, Graeme. From reinhold-birkenfeld-nospam at wolke7.net Wed Jul 6 16:23:03 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 06 Jul 2005 22:23:03 +0200 Subject: Use cases for del In-Reply-To: References: Message-ID: <3j2st8Fnu7j9U1@individual.net> Ron Adam wrote: > Ron Adam wrote: > >> And accessing an undefined name returned None instead of a NameError? > > I retract this. ;-) > > It's not a good idea. But assigning to None as a way to unbind a name > may still be an option. IMO, it isn't. This would completely preclude the usage of None as a value. None is mostly used as a "null value". The most prominent example is default function arguments: def foo(bar, baz=None): With None unbinding the name, what would you suggest should happen? baz being undefined in the function scope? Or, what should happen for somedict[1] = None The same as del somedict[1] ? Also, the concept of _assigning_ something to a name to actually _unassign_ the name is completely wrong. Of course, this is a possible way to unassign names if (and only if) (1) there is a real "undefined" value (not None) (2) unbound names return the undefined value Look at Perl. Do we want to be like that? ;) Reinhold From http Sun Jul 24 21:22:52 2005 From: http (Paul Rubin) Date: 24 Jul 2005 18:22:52 -0700 Subject: Simple Problem References: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> Message-ID: <7xwtnf8ys3.fsf@ruckus.brouhaha.com> "ncf" writes: > I know I've seen this somewhere before, but does anyone know what the > function to escape a string is? (i.e., encoding newline to "\n" and a > chr(254) to "\xfe") (and visa-versa) repr(s) From bronger at physik.rwth-aachen.de Sat Jul 30 10:51:13 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 30 Jul 2005 16:51:13 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: <87wtn8qrdq.fsf@wilson.rwth-aachen.de> Hall?chen! zen19725 at zen.co.uk (phil hunt) writes: > [...] > > How about sometihing with the same API as Tkinter (so no need to > relearn), but which looks prettier? Would that fix your gripes? I haven't learned Tkinter. Well, I programed toy applications with different toolkits (including Tkinter) and tried to make a rather competent decision, that's all. So for me, it needn't be like Tkinter. The three most important attributes for me are Pythonic, modern (both nice-looking and comprehensive), and non-niche. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From http Wed Jul 27 03:50:52 2005 From: http (Paul Rubin) Date: 27 Jul 2005 00:50:52 -0700 Subject: [OT] Problems with permissions etc References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: <7xek9khelf.fsf@ruckus.brouhaha.com> "Frank Millman" writes: > 1. The application I am developing will eventually be deployed as a > multi-user accounting/business system. I want to identify the physical > workstation that generates each transaction, so I am using the mac > address. My method for extracting this is as follows - If you are trying to use the mac address as a hard-to-spoof security token, forget it, it is ridiculous. You want a smart card with crypto authentication. Some cheap and convenient dev kits are available from www.basiccard.com. Shipping charges from Germany to the US (what you get through the online order form) are ridiculous, but there's a distributor now in Canada now and the shipping charges from there are much more reasonable. From kay.schluehr at gmx.net Sat Jul 23 15:03:56 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Jul 2005 12:03:56 -0700 Subject: Lists & "pointers" In-Reply-To: <42e25ac2$1@griseus.its.uu.se> References: <42e25ac2$1@griseus.its.uu.se> Message-ID: <1122145436.618503.114220@g49g2000cwa.googlegroups.com> Jan Danielsson wrote: > Hello all, > > I have written a simple whiteboard application. In my application, I > want to be able to set draw attributes. This part works. I have a > dictionary object which contains stuff like: > self.attr['Pen.Color'] = ... > self.attr['Pen.Thickness'] = ... > > Now, the problem is that I want to be able to store attributes in a > list so they'll be easily accessed using the function keys. I.e. I have > the "current attributes" which I want to be able to store or retrieve > in/from a list, > > The problem is that I have initialized the list like this: > > self.drawAttr = { blah, blah, blah.. } > self.storedAttr = [ ] > for i in range(0, 10): > self.storedAttr.append(self.drawAttr) > > I know what the problem is; they are all referencing the *same* > dictionary object. So, my question is: How do I initialize a list of > dictionary objects, where each list entry is its own object (which is a > copy from the self.drawAttr object). Hi Jan son of Daniel, you might initialize self.storedAttr with empty dicts and fill them later: self.soredAttr = [{}]*10 for entry in self.storedAttr: entry.update(self.drawAttr) > Also, how do I store/restore entries to the list? > > I have found the "copy" module, and it's copy method. I assume this > would work: > > for i in range(0, 10): > self.storedAttr.append(copy.copy(self.drawAttr)) > > However, the concept of "deep copy" confuses me. Do I want it, or > don't I want it? I repeat: the attributes object is a simple dictionary. > > Thankful for any advice. A *shallow copy* creates a new dictionary and copies the references, a *deep copy* tries to create a new reference for each existing object in the dict. The disadvantage of deepcopy is that it does not work in many cases: >>> copy.deepcopy([lambda :None]) Traceback (most recent call last): ... TypeError: function() takes at least 2 arguments (0 given) As the docs tell: "This version does not copy types like module, class, function, method, stack trace, stack frame, file, socket, window, array, or any similar types." I wonder if one couldn't pickle a module and reimport it in order to create a copy of it ;) IMO this is a weakness of the algorithm. One usually doesn't want to duplicate a function so that a new reference of a function is not needed because it is readonly and the algorithm could reuse the same reference. For classes I don't if the assertion in the docs is actually true? >>> class A:pass >>> copy.deepcopy(A) >>> class A(object): ... def __init__(self):pass ... >>> copy.deepcopy(A) >>> Regards, Kay From invalidemail at aerojockey.com Mon Jul 4 05:23:51 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Jul 2005 02:23:51 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> <1120424454.854518.100610@o13g2000cwo.googlegroups.com> Message-ID: <1120469031.112811.112950@g44g2000cwa.googlegroups.com> Christopher Subich wrote: > Carl Banks wrote: > > > > Christopher Subich wrote: > >>I've heard this said a couple times now -- how can listcomps not > >>completely replace map and filter? > > If you're doing heavy functional programming, listcomps are > > tremendously unwieldy compared to map et al. > > Interesting; could you post an example of this? Whenever I try to think > of that, I come up with unwieldly syntax for the functional case. In > purely functional code the results of map/filter/etc would probably be > directly used as arguments to other functions, which might make the > calls longer than I'd consider pretty. This is especially true with > lots of lambda-ing to declare temporary expressions. I suspect you're misunderstanding what I mean by heavily functional. You appear to see maps and listcomps merely as a shortcut for a for loop. You're comparing the map shortcut and the listcomp shortcut and seeing which one's less verbose. In a mostly procedural program which uses functional constructs in isolation, listcomps are going to win most of those battles. Heavily functional programming is a different mindset altogether. In heavily functional programming, things like maps and filters and function applications are actually what you're thinking about. map isn't an indirect way to do a for loop; it's a direct way to do a map. When your mind is focused on "applying a function to each member of this list and returning a list of the results" as opposed to "convenient shortcut to a for loop", map is going to be far superior to a listcomp. And when you're doing dozens and dozens of maps over a large purely functional program, you don't want to write out a listcomp every single time you want to do it. -- CARL BANKS From darkcowherd at gmail.com Sun Jul 10 02:45:25 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Sun, 10 Jul 2005 12:15:25 +0530 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: <5f4d3cb505070923454aaa74df@mail.gmail.com> http://www.joelonsoftware.com/items/2003/10/13.html From steven.bethard at gmail.com Wed Jul 13 10:30:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jul 2005 08:30:03 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <87ackrf8pv.fsf@titan.staselog.com> References: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> <87ackrf8pv.fsf@titan.staselog.com> Message-ID: Edvard Majakari wrote: > Steven Bethard writes: > >>$ python -m timeit "for x in (i for i in xrange(10)): y = x" >>100000 loops, best of 3: 4.75 usec per loop > > Yowza! One of the features I really liked in Perl has shored Python island > somewhere in the 2.4'ies, it seems[1]. Thanks for the tip! [snip] > But using -m makes it much more convenient. Yup, it showed up in Python 2.4. Great, isn't it? STeVe From R.Brodie at rl.ac.uk Tue Jul 5 06:28:09 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 5 Jul 2005 11:28:09 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: "Guy Lateur" wrote in message news:VSsye.137616$uw3.7324778 at phobos.telenet-ops.be... > Are you saying it's unsafe to do that? I only need this for an application > running locally, I mean, from within our LAN domain. We do have Exchange > webmail. I wasn't offering security advice but merely observing that your Exchange server could be running SSL secured IMAP only (which would be on a different port from normal IMAP). In that case an IMAP4_SSL instance would be what you need. From bmg2x at yahoo.com Wed Jul 20 08:32:59 2005 From: bmg2x at yahoo.com (bmgz) Date: Wed, 20 Jul 2005 14:32:59 +0200 Subject: access the text being generated in other windows In-Reply-To: <1121829930.938089.122070@g44g2000cwa.googlegroups.com> References: <1121829930.938089.122070@g44g2000cwa.googlegroups.com> Message-ID: algebraist wrote: > is there a way python can access the text being generated in other > windows, by other programs/processes? my guess- you will probably have to resort to some rather downright dirty screen scraping. From tprimke at interia.pl Sun Jul 24 09:06:24 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jul 2005 06:06:24 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1n6sneaka8uxf.1oj2fdat4sfzp$.dlg@40tude.net> Message-ID: <1122210383.855335.146450@g47g2000cwa.googlegroups.com> Thanks a lot! Now I know I can choose PyGTK. I really like it because of its rich documentation. > You could also bundle the runtime DLLs with your py2exe'd application That's great. I think my clients will appreciate a single one executable. From kbchung at hongik.ac.kr Sun Jul 31 01:27:45 2005 From: kbchung at hongik.ac.kr (KB) Date: 30 Jul 2005 22:27:45 -0700 Subject: How to convert a string like '777' to an octal integer like 0777? Message-ID: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> Hi, This may be a rudimentary question: How to convert a string like '777' to an octal integer like 0777, so that it can be used in os.chmod('myfile',0777)? I know the leading zero is important in os.chmod. KB From bdesth.quelquechose at free.quelquepart.fr Thu Jul 14 12:33:03 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 14 Jul 2005 18:33:03 +0200 Subject: Help - Classes and attributes In-Reply-To: <1121349918.343589.21370@g47g2000cwa.googlegroups.com> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> <42d64891$0$15020$626a14ce@news.free.fr> <1121349918.343589.21370@g47g2000cwa.googlegroups.com> Message-ID: <42d68d13$0$6807$636a15ce@news.free.fr> rh0dium a ?crit : > Hi > > I really like your approach but when do you actually get connected?? > You never call the method connect? oops :( (snip whole code) >>if __name__ == '__main__': >> truc = NSCLdap() truc.connect() # was missing >> truc.search() > BTW, you'd better let exceptions propagate from connect(), and catch'em in the calling code. From hancock at anansispaceworks.com Thu Jul 7 16:51:00 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 7 Jul 2005 15:51:00 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <200507071551.00636.hancock@anansispaceworks.com> On Wednesday 06 July 2005 08:38 am, Tom Anderson wrote: > On Wed, 6 Jul 2005, Terry Hancock wrote: > > With list comprehensions and generators becoming so integral, I'm > > not sure about "unpythonic". > > I'm going to resist the temptation to argue that list comps are themselves > unpythonic :). Ah, but GvR likes them, so that pretty much makes them "pythonic" by definition, doesn't it? ;-) > Hang on, where's the punctuation in either of those? They *are* done with > keywords! Yeah, that's true, and it could be true here too, if you throw away the []. I see that's one of the proposed alternatives. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From nemesis at nowhere.invalid Mon Jul 25 11:47:13 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Mon, 25 Jul 2005 15:47:13 GMT Subject: [ANN] XPN 0.5.0 released References: <20050725083558.1974.41689.XPN@orion.homeinvalid> Message-ID: <20050725134745.11684.60211.XPN@orion.homeinvalid> Mentre io pensavo ad una intro simpatica "Franz Steinhaeusler" scriveva: >>XPN (X Python Newsreader) is a multi-platform newsreader with Unicode >>support. It is written with Python+GTK. It has features like >>scoring/actions, X-Face and Face decoding, muting of quoted text, >>newsrc import/export, find article and search in the body, spoiler >>char/rot13, random taglines and configurable attribution lines. >>[...] > > Hello Nemesis, Hi Franz, > cool, thank you, I like Xpn. thanks > Even better would be, if the Application would be written > in wxPython :) Hmm, I don't think so, I like pyGTK very much :-D > Would it be possible to also customize the fonts in the > groups and threads pane (I'd like to have everywhere proportional > (monospaced fonts). Not at the moment, maybe in the future ... but of course if you can't wait you can modify the source by yourself, the files to modify are xpn_src/Groups_Pane.py and xpn_src/Threads_Pane.py just add the line import pango in the both the files, and then: at the end of Groups_Pane.py add this line (do not change the indentation): self.groups_list.modify_font(pango.FontDescription("monospace 10")) at the end of Threads_Pane.py add this line (do not change the indentation): self.threads_tree.modify_font(pango.FontDescription("monospace 10")) of course you can change the font description as you like. -- First things first, but not necessarily in that order. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From cam.ac.uk at mh391.invalid Fri Jul 22 19:46:21 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 23 Jul 2005 00:46:21 +0100 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: References: Message-ID: Jeffrey E. Forcier wrote: > In other words, str() is _NOT_ apparently calling .__str__ as > it's supposed to! However, calling __str__ directly (which, yes, you're > not supposed to do) does work as expected: I'm too tired and/or lazy to check, but I believe str() is calling MyClass.__str__(testObject) as it is supposed to rather than testObject.__str__() as you say it is supposed to. ;-) Someone else or Google can probably enlighten you on the reason for this better than I. I think this is something that is not explained very well in the docs, which do say that a class implements special method names, but doesn't make it very clear that an object can't always override them. If you redirect to a second method you can overwrite on the instance, I think you will get the results you want. -- Michael Hoffman From Scott.Daniels at Acm.Org Fri Jul 29 13:05:27 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 29 Jul 2005 10:05:27 -0700 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: <42ea596d$1@nntp0.pdx.net> Peter Otten wrote: > def fillzip(*seqs): > def done_iter(done=[len(seqs)]): > done[0] -= 1 > if not done[0]: > return > while 1: > yield None > seqs = [chain(seq, done_iter()) for seq in seqs] > return izip(*seqs) Can I play too? How about: import itertools def fillzip(*seqs): def Nones(countactive=[len(seqs)]): countactive[0] -= 1 while countactive[0]: yield None seqs = [itertools.chain(seq, Nones()) for seq in seqs] return itertools.izip(*seqs) --Scott David Daniels Scott.Daniels at Acm.Org From peter at engcorp.com Wed Jul 27 18:27:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Jul 2005 18:27:47 -0400 Subject: OT: finding a job (was Re: searching string url) In-Reply-To: <1122500867.516196.146990@g14g2000cwa.googlegroups.com> References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> <1122500867.516196.146990@g14g2000cwa.googlegroups.com> Message-ID: googlinggoogler at hotmail.com wrote: > Anyway to the orginally replier - I wish it was homework ;-), that > would mean I wouldnt be trying to find myself a job as a recent > graduate... I decided to crawl something similar to the yellow pages Sounds like a useful task, and a good way to learn more about Python while you're job-hunting, as well as helping you with the hunt. > for my select area and then find all > pages corresponding to my ideal field of work, and grab their details > into a txt file. > > Trouble is I keep thinking of cool new bits to add, python truely is a > beautifal language. Ideally would like to somehow write all the > information into a word mail merge - but I think that requires more > research! This sounds suspiciously like you are thinking some kind of "shotgun" approach to sending out your resume might be a good idea. If that's so, as an employer, I strongly recommend against it. Instead, spend the time you would otherwise have spent building this tool (or at least the word mail merge part) and dig deeper into those companies you do find, filtering out the ones you wouldn't want to work at. From the remainders, adapt your cover letter to *custom-fit* each opportunity. Mass-mailed resumes with generic cover letters are a good way to kill trees but not a particular effective way to get noticed by an employer, at least not noticed in a good way... -Peter From twic at urchin.earth.li Fri Jul 1 08:40:11 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 1 Jul 2005 13:40:11 +0100 Subject: map vs. list-comprehension In-Reply-To: <1120203815.141353.61200@z14g2000cwz.googlegroups.com> References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> <1120203815.141353.61200@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 1 Jul 2005, George Sakkis wrote: > "Terry Hancock" wrote: > > Keeping the language small is a worthwhile goal, but it should be traded > off with conciseness and readability; otherwise we could well be content > with s-expressions. There's quite a number of satisfied LISP programmers out there who *are* content with S-expressions ... tom -- In-jokes for out-casts From steve at REMOVETHIScyber.com.au Sun Jul 17 01:19:52 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 17 Jul 2005 15:19:52 +1000 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> <1121554550.a71667b7fa93beed82764d3bd61318e3@teranews> Message-ID: On Sat, 16 Jul 2005 19:01:50 -0400, Peter Hansen wrote: > George Sakkis wrote: >> "Bengt Richter" wrote: >>> >>> identity = ''.join([chr(i) for i in xrange(256)]) >> >> Or equivalently: >>>>>identity = string.maketrans('','') > > Wow! That's handy, not to mention undocumented. (At least in the > string module docs.) Where did you learn that, George? I can't answer for George, but I also noticed that behaviour. I discovered it by trial and error. I thought, oh what a nuisance that the arguments for maketrans had to include all 256 characters, then I wondered what error you would get if you left some out, and discovered that you didn't get an error at all. That actually disappointed me at the time, because I was looking for behaviour where the missing characters weren't filled in, but I've come to appreciate it since. -- Steven From jmeile at hotmail.com Wed Jul 13 14:29:12 2005 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 13 Jul 2005 20:29:12 +0200 Subject: String Manipulation In-Reply-To: <42D52DBF.9080605@syscononline.com> References: <1121265538.351527.158950@f14g2000cwb.googlegroups.com> <42D52DBF.9080605@syscononline.com> Message-ID: <42D55D78.7090508@hotmail.com> Hi, > for punctuation in punctuations: > line=line.replace(punctuation,'') I would use maketrans or even a regex instead. However, If you care about speed, it is well known that in some cases regex take more time than multiple replaces. Even the maketrans could take more time (I don't know; you may benchmark it -> homework) Regards, Josef From http Fri Jul 29 21:18:48 2005 From: http (Paul Rubin) Date: 29 Jul 2005 18:18:48 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <7xoe8lccqv.fsf@ruckus.brouhaha.com> Christopher Subich writes: > My personal favourite is to replace "lambda" entirely with an > "expression comprehension", using < and > delimeters. But how does that let you get more than one expression into the anonymous function? From jepler at unpythonic.net Tue Jul 19 19:01:27 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 19 Jul 2005 18:01:27 -0500 Subject: time string conversion In-Reply-To: <42DD6368.50500@grads.ece.mcmaster.ca> References: <42DD6368.50500@grads.ece.mcmaster.ca> Message-ID: <20050719230127.GA25235@unpythonic.net> def smadi(s): h, m, s = s.split(":") h = int(h) m = int(m) s = float(s) return s + m*60 + h * 3600 >>> print smadi("16:23:20.019519") 59000.019519 Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ptmcg at austin.rr.com Thu Jul 28 09:36:08 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 28 Jul 2005 06:36:08 -0700 Subject: searching string url In-Reply-To: <1122539371.202912.41650@o13g2000cwo.googlegroups.com> References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> <1122500867.516196.146990@g14g2000cwa.googlegroups.com> <86u0iflhv5.fsf@bhuda.mired.org> <1122539371.202912.41650@o13g2000cwo.googlegroups.com> Message-ID: <1122557768.694139.50120@g47g2000cwa.googlegroups.com> Dave - Check out the URL extractor example that ships with pyparsing. It handles many kinds of URL formats. Download pyparsing at pyparsing.sourceforge.net. -- Paul From gsakkis at rutgers.edu Sun Jul 3 11:11:02 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 08:11:02 -0700 Subject: math.nroot [was Re: A brief question.] References: Message-ID: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> "Tom Anderson" wrote: > >> And finally, does Guido know something about arithmetic that i don't, or > >> is this expression: > >> > >> -1.0 ** 0.5 > >> > >> Evaluated wrongly? > > > > No, it is evaluated according to the rules of precedence. It is > > equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which > > fails as expected. > > Ah. My mistake. I submit that this is also a bug in python's grammar. > There's probably some terribly good reason for it, though. How about 'conformance with standard mathematic notation', does this count for a terribly good reason ? What would one expect to be the result of 5^2 - 2^2, 29 or 21 ? Would you expect 5^2 + - 2^2 to be different, even if you write it as 5^2 + -2 ^ 2 ? White space is not significant in math AFAIK ;-) George From bvande at po-box.mcgill.ca Mon Jul 4 07:11:47 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 04 Jul 2005 07:11:47 -0400 Subject: precision problems in base conversion of rational numbers Message-ID: <42C91973.6090208@po-box.mcgill.ca> Hi all, I guess it is more of a maths question than a programming one, but it involves use of the decimal module, so here goes: As a self-directed learning exercise I've been working on a script to convert numbers to arbitrary bases. It aims to take any of whole numbers (python ints, longs, or Decimals), rational numbers (n / m n, m whole) and floating points (the best I can do for reals), and convert them to any base between 2 and 36, to desired precision. I'm pretty close but I know I am not handling the precision quite right. Nothing other than understanding hangs on it, but, that's enough :-) To do all this I'm using the decimal module (for the first time) and I've been setting the precision with decimal.getcontext().prec = max(getcontext().prec, x * self.precision ) This is in my class's __init__ method before I convert every number to Decimal type and self.precision is at this point an int passed. The first term is to be sure not to reduce precision anywhere else. In the last term I'd started off with x = 1, and that works well enough for "small" cases (i.e. cases where I demanded a relatively low degree of precision in the output). I've no idea how to work out what x should be in general. (I realize the answer may be a function of my choice of algorithm. If it is needed, I'm happy to extract the relevant chunks of code in a follow-up -- this is long already.) For getcontext.prec = 80 (i.e x = 1) when I work out 345 / 756 in base 17 to 80 places (i.e. self.precision = 80) I get: >>> print Rational_in_base_n(345, 756, 17, 80) 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0D5C1G603999179EB (Rational_in_base_n(numerator, denominator, base, precision) is the rational specific subclass. When I convert the result back to decimal notation by hand it agrees with the correct answer to as many places as I cared to check.) I've discovered empirically that I have to set getcontext.prec = 99 or greater (i.e. x >= 1.2375) to get 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C (I do feel safe in assuming that is the right answer. :-) How would I go about working out what degree of precision for the decimal module's context is needed to get n 'digits' of precision in an expression of base m in general? (I've no formal training in Comp Sci, nor in the relevant branches of mathematics.) Thanks and best, Brian vdB From steve at REMOVETHIScyber.com.au Wed Jul 13 11:44:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 14 Jul 2005 01:44:26 +1000 Subject: all possible combinations References: <1121265581.28091.2.camel@athop1.ath.vt.edu> Message-ID: On Wed, 13 Jul 2005 10:39:41 -0400, rbt wrote: >> > What is the most efficient way to do this? >> >> Efficient for who? The user? The programmer? The computer? Efficient use >> of speed or memory or development time? > > The CPU Ah, then that's easy. Sit down with pencil and paper, write out all 64 combinations yourself, and then type them into a Python list. Then you can access any one of those combinations with a single call. A lookup table is the fastest possible way for the CPU to give you the answer you want. [snip] > My list is not arbitrary. I'm looking for all 'combinations' as I > originally posted. Order does not matter to me... just all possibilities. That's good, since you only need combinations of "a", "b" and "c" the lookup table is quite small and manageable. I was worried that you might have wanted to apply your function to any set of items. -- Steven. From eurleif at ecritters.biz Sat Jul 9 01:30:24 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 09 Jul 2005 05:30:24 GMT Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120883125.259644.80490@g47g2000cwa.googlegroups.com> References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> <1120883125.259644.80490@g47g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: >>>>list.from_str("abc") > > list("a", "b", "c" ) I assume we'll also have list.from_list, list.from_tuple, list.from_genexp, list.from_xrange, etc.? From utabintarbo at gmail.com Wed Jul 20 10:03:24 2005 From: utabintarbo at gmail.com (utabintarbo at gmail.com) Date: 20 Jul 2005 07:03:24 -0700 Subject: How to kill easygui dialog? In-Reply-To: <1e44d$42dd9a21$d1b7122a$29240@PRIMUS.CA> References: <1121800637.589080.210700@g47g2000cwa.googlegroups.com> <1e44d$42dd9a21$d1b7122a$29240@PRIMUS.CA> Message-ID: <1121868204.552155.171690@g49g2000cwa.googlegroups.com> William, Thanks for the reply. No flames, but I am running on both Linux and Windows, so I need a x-platform solution. I thought I had it with easygui... Must try some other ideas.... From bob at greschke.com Sat Jul 30 20:49:52 2005 From: bob at greschke.com (bob at greschke.com) Date: 30 Jul 2005 17:49:52 -0700 Subject: pySerial Windows write problem References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: <1122770992.336985.227770@g44g2000cwa.googlegroups.com> Thanks heaps for the help, guys! I bit the bullit and am now leaving the serial ports open all of the time. I still think it is a driver/hardware problem. When the ports go South even a reboot of the laptop the program is running on won't fix it. The hardware is all brand new, so it should have some bugs in it. Shouldn't it? :) Anyway, here's a short page about the program, just for fun www.greschke.com/unlinked/pocus01.htm Thanks! Bob From enleverlesO.OmcO at OmclaveauO.com Fri Jul 8 11:33:11 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 8 Jul 2005 17:33:11 +0200 Subject: Options to integrate Python modules into native windows applications References: Message-ID: <42ce9f7c$0$25046$8fcfb975@news.wanadoo.fr> Re Hi ! I had only test (little) Python for .Net ; OK, it's run. It is possible to make winform from Python. And I had try to use Python for .Net from my COM-server, and from VBscript. OK also. Plus, I had try to call my Python-server-COM, from C# : OK it's run. C# can use Python. And, I had try to make, in Internet-Explorer, a page, with Html+javascript, who call the Python-server-COM, and at the same time, contains an object-assembly dotNET, who call also the server-COM. It is twisted, but it's run OK (that opens two sessions of the server-COM, which communicate by mmap). * sorry for my bad english * @-salutations Michel Claveau From spam.csubich+block at block.subich.spam.com Sat Jul 23 00:29:50 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 23 Jul 2005 00:29:50 -0400 Subject: Location of tk.h In-Reply-To: References: Message-ID: none wrote: > Probably a stupid question, but... > > I was attempting to install the Tkinter 3000 WCK. It blew up trying to > build _tk3draw. The first error is a 'No such file or directory' for > tk.h. I can import and use Tkinter just fine, so I'm not sure what is > what here. You can import and user Tkinter, sure, but the WCK setup is trying to -build- itself. Have you installed the relevant Tk development libraries? From Darkfalz.Usenet at gmail.com Sat Jul 2 21:30:45 2005 From: Darkfalz.Usenet at gmail.com (Darkfalz) Date: 2 Jul 2005 18:30:45 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <1120354245.338107.113140@o13g2000cwo.googlegroups.com> muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. Many companies hire salespersons from Britain to > represent their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? > > Be blunt. We Americans need to know. Should we try to change the way we > speak? Are there certain words that sound particularly goofy? Please > help us with your advice on this awkward matter. I find this amusing even when they have the most cockney, ghetto English accent, Americans still find it "sophisticated". And yes, seppos sound like dumb fucks to the entire rest of the world. From Vajrala.Madhusudana at mayo.edu Thu Jul 14 17:24:35 2005 From: Vajrala.Madhusudana at mayo.edu (Madhu R. Vajrala) Date: Thu, 14 Jul 2005 16:24:35 -0500 Subject: Python Installation error on Solaris-9-SPARC In-Reply-To: <1121363776.862756.94770@g47g2000cwa.googlegroups.com> References: <1121362775.799428.239840@g47g2000cwa.googlegroups.com> <1121363416.498522.138420@g43g2000cwa.googlegroups.com> <1121363776.862756.94770@g47g2000cwa.googlegroups.com> Message-ID: <1121376275.1668.2.camel@indica> This TIP worked GREAT !!! I was able to install python-2.4.1 on Sun Solaris by executing below steps ( I am not a 'root' user) 1. wget http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz 2. gunzip Python-2.4.1.tgz 3. /usr/sfw/bin/gtar -xvf Python-2.4.1.tar 5. cd Python-2.4.1 6. ./configure --prefix=/home//Py (The directory in which you wanted to install Python libraries and binaries) 7. make 8. make install Once again Thank you All for educating me. Madhu On Thu, 2005-07-14 at 10:56 -0700, casevh at comcast.net wrote: > > Madhu R. Vajrala wrote: > > > > 2. gunzip -c Python-2.4.1.tgz | tar xvf - > > > > Use gtar. The Solaris tar does not hnadle long file names correctly. > gtar should be found in /usr/sfw/bin. > > cvh > From ssteward at accesspdf.com Fri Jul 22 18:41:30 2005 From: ssteward at accesspdf.com (ssteward at accesspdf.com) Date: 22 Jul 2005 15:41:30 -0700 Subject: Interleave merge pdf files References: <1122051911.027433.162650@g14g2000cwa.googlegroups.com> Message-ID: <1122072090.692548.38850@g43g2000cwa.googlegroups.com> Mark Jackson wrote: > "Chirayu Krishnappa" writes: > > Hi, > > > > I need to scan documents with pages having printed matter on both > > sides. It is easiest to stack them in the autosheet feeder and let it > > scan. I end up with one file (say A.pdf) containing the odd pages in > > sequence. Similarly, I can end up with B.pdf containing the even pages. > > I want to combine them into result.pdf which contains A.1, B.1, A.2, > > B.2, A.3, B.3, ... (A.1 = page 1 of A.pdf). > > > > Does someone know a simple way to achieve this? I noticed the other > > thread on this newsgroup about merging lots of pdf files and > > multivalent tools and pdftk were mentioned. However, I could not find a > > way to do this using them. I am interested in another free tool or a < > > 25 lines python script (which may use any freeware library) to do the > > same. > > I face exactly the same problem. Based on examination of the pdftk man > page I *think* it can be done by something like (untested): > > pdftk A.pdf burst output %04d_A.pdf > pdftk B.pdf burst output %04d_B.pdf > pdftk *_?.pdf cat output combined.pdf > > assuming fewer than 10,000 pages per document, of course. > > I would be interested in an alternative approach which does not > generate a ton of intermediate pdfs. > Here is a page that offers a couple related scripts (one bash script, one DOS batch script) for doing this with pdftk in one swipe: http://www.accesspdf.com/article.php/2005020408520076 Sid From peter at engcorp.com Mon Jul 18 09:11:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 09:11:33 -0400 Subject: goto In-Reply-To: References: Message-ID: <_MOdnc-Ag8z6N0bfRVn-pw@powergate.ca> Hayri ERDENER wrote: > what is the equivalent of C languages' goto statement in python? Steven offered the best reply here, in that he wondered what you actually need this for. What usage of "goto" in C are you hoping to emulate? It's a certainty that some other non-goto technique will be more appropriate in Python. -Peter From turian at gmail.com Tue Jul 26 00:50:20 2005 From: turian at gmail.com (Joseph Turian) Date: 25 Jul 2005 21:50:20 -0700 Subject: Safest manner to extend search path for modules? Message-ID: <1122353419.940318.226640@g47g2000cwa.googlegroups.com> Hi, What is the safest manner to extend search path for modules, minimizing the likelihood of shooting oneself in the foot? The system (which includes scripts and their shared modules) may be checked out in several different locations, but a script in a particular checked-out version of the system should only use modules from that checkout location. e.g. if the system contains a directory scripts/foo/ where all the scripts are housed, and scripts/modules/ where all the modules are housed, then is it correct for each script in scripts/foo/ to begin with: import sys, os.path sys.path.append(os.path.join(sys.path[0], "../modules")) If so, is there a cleaner way of doing this than including the above text in all scripts? Thanks, Joseph From bokr at oz.net Sun Jul 24 01:00:35 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 05:00:35 GMT Subject: "Aliasing" an object's __str__ to a different method References: Message-ID: <42e2f10e.984589695@news.oz.net> On Sat, 23 Jul 2005 10:59:56 -0400, "Jeffrey E. Forcier" wrote: >Thanks for all the additional replies thus far! > >Apparently the issue, as stated implicitly or explicitly by most of >you, is that new-style class instances essentially defer their magic >methods to the class's static versions of same. This is good to know :) Actually, it's not just the "magic" methods. If you have an instance a of a newstyle class A, any attribute lookup a.attr will undergo the same search first to see if attr is a descriptor object, and if not, *then* to look in the instance attribute directory. But the descriptor search doesn't start in inst.__dict__, it goes through the chain of classes and base classes provided by type(inst).mro(), which starts in type(inst). And for our class A instance a, type(a) will be A, so the search for a.attr starts there. Same applies to a.__str__. This ensures that all instances of the same class will share the same methods. The way a method, which is just a class variable with a function as its value, gets to be a callable bound method, is the same as any attribute lookup looking for a descriptor with a __get__ method (which a function also has, for this purpose). If the descriptor doesn't have a __set__ method as well, then an instance attribute takes priority. If there is a __set__ method, and instance attribute can't shadow the attribute name, and the descriptor __get__ method takes precedence. Unshadowed, a method search looks something like cbm = ((base for base in type(inst).mro() if 'attr' in base.__dict__) .next().__dict__['attr'].__get__(inst, type(inst))) if this doesn't succeed and meet the __set__ vs shadowing logic, then you get the instance attribute per se. Jumping ahead using a MyClass inst as an example: >>> cbm = ((base for base in type(inst).mro() if '__str__' in base.__dict__) ... .next().__dict__['__str__'].__get__(inst, type(inst))) >>> cbm , am being viewed> This looks a little strange because the repr of the bound method includes a repr of the thing bound to, which returns the Edit/View presentation (after the 'of' above). (A possible reason to consider using just __str__ and letting __repr__ be). A function's __get__ method will deliver a bound method if the lookup is via an inst, or an unbound method if the lookup is via the class, in which case None is passed to __get__ instead of the instance. The upshot is that you can create descriptors __str__ and __repr__for your class that will return bound methods using __str__ and __repr__ function attributes of your instance (if they exist) instead of the normal class attributes, and we can chose from several normal class attributes according to a general mode flag of the class. E.g., using your original example, and rearranging things a bit, we can do something like what (I think) you wanted: (The first class below defines descriptors and the example uses two instances in MyClass) >>> class InstanceMethodSetterAndBinder(object): ... def __init__(self, inst_attr_name): ... # lambda self:'?? no %s format ??'% object.__repr__(self) ... self.inst_attr_name = inst_attr_name ... def __get__(self, inst, cls=None): ... if inst is None: return self ... default = getattr((cls or type(inst)), 'SharedEVMethod', None) ... if default is None: ... def default(self): ... return ''% object.__repr__(inst) ... return vars(inst).get(self.inst_attr_name, default).__get__(inst, cls) ... def __set__(self, inst, value): ... inst.__dict__[self.inst_attr_name] = value ... def __delete__(self, inst): ... try: del inst.__dict__[self.inst_attr_name] ... except KeyError: pass ... >>> class MyClass(object): ... __str__ = InstanceMethodSetterAndBinder('__str__') ... __repr__ = InstanceMethodSetterAndBinder('__repr__') ... @staticmethod ... def Edit(self): ... return "I, %s, am being edited" % (object.__repr__(self)) # %s on self recurses!! ... @staticmethod ... def View(self): ... return "I, %s, am being viewed" % (object.__repr__(self)) # %s on self recurses!! ... SharedEVMethod = View ... def setEdit(self, shared=True): ... if not shared: ... self.__str__ = self.__repr__ = self.Edit ... else: ... type(self).SharedEVMethod = self.Edit ... def setView(self, shared=True): ... if not shared: ... self.__str__ = self.__repr__ = self.View ... else: ... type(self).SharedEVMethod = self.View ... def delInstEVM(self): ... del self.__str__ ... del self.__repr__ ... >>> inst = MyClass() >>> inst2 = MyClass() >>> inst3 = MyClass() >>> inst I, <__main__.MyClass object at 0x02FB91AC>, am being viewed >>> inst2 I, <__main__.MyClass object at 0x02FB91CC>, am being viewed >>> inst3 I, <__main__.MyClass object at 0x02FB91EC>, am being viewed >>> inst.setEdit() >>> inst I, <__main__.MyClass object at 0x02FB91AC>, am being edited >>> inst2 I, <__main__.MyClass object at 0x02FB91CC>, am being edited >>> inst3 I, <__main__.MyClass object at 0x02FB91EC>, am being edited >>> inst2.setView(False) >>> inst I, <__main__.MyClass object at 0x02FB91AC>, am being edited >>> inst2 I, <__main__.MyClass object at 0x02FB91CC>, am being viewed >>> inst3 I, <__main__.MyClass object at 0x02FB91EC>, am being edited >>> inst2.setView() # all >>> inst2.setEdit(False) # just inst >>> inst I, <__main__.MyClass object at 0x02FB91AC>, am being viewed >>> inst2 I, <__main__.MyClass object at 0x02FB91CC>, am being edited >>> inst3 I, <__main__.MyClass object at 0x02FB91EC>, am being viewed >>> inst2.delInstEVM() >>> inst2 I, <__main__.MyClass object at 0x02FB91CC>, am being viewed You could use this kind of thing in a base class and specialize in subclasses to override stuff, and you can do other stuff too. Your choices are more varied that you probably thought ;-) > >Ironically, the reason I'm using new-style classes is that I only >read up on them very recently, and was attempting to get myself into >the habit of inheriting from 'object' by default. Go figure. > >Anyway, to take a step back, the *actual* actual reason for my >investigation into this issue is that I'm attempting to create a >collection of classes representing HTML page/form elements, many of >which are represented differently depending on whether they're in a >"view" or "edit" state. > >And ideally I wanted to be able to hold a collection of these objects >and toggle them all to one state or the other, then bandy them about ^^^^^^^^^^^^^^^ does that mean all instances with a single toggling action, or each individually? You could have both. I.e., a general mode flag and the ability to assign an arbitrary __str__ and/or __repr__ override for a particular instance. See example, where all are toggled by default. >as if they were strings, e.g. mixing them with literal strings via str >(obj). Note that your example set __repr__ also, which is not used for str(x) if x.__str__ exists. > >Clearly there are at least a handful of ways to accomplish this, but >the one that came to mind first was, as I said at the beginning, to >define both behaviors on each object and then have the ability to >point __str__ to one or the other. I suppose now I need to figure out >which is more important, that ease-of-use of overriding __str__ or >whatever benefits new-style classes give (something I'm still a bit >unclear on). > Those aren't your only choices ;-) Regards, Bengt Richter From p.c.j.kleiweg at rug.nl Wed Jul 6 15:07:26 2005 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Wed, 6 Jul 2005 21:07:26 +0200 Subject: from date/time string to seconds since epoch Message-ID: Is there a safe and clean way to parse a date/time string into seconds since epoch? I have a string with date and time in GMT. I can get the correct value using this: #!/usr/bin/env python import os os.environ['TZ'] = 'UTC' import time s = 'Wed, 06 Jul 2005 16:49:38 GMT' seconds = time.mktime(time.strptime(s, '%a, %d %b %Y %H:%M:%S %Z')) However, I also need conversions to localtime. Setting TZ to UTC before importing the time module won't let me do this. Changing TZ after importing time has no effect. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From fuzzyman at gmail.com Fri Jul 29 08:27:28 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jul 2005 05:27:28 -0700 Subject: writing a web client In-Reply-To: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> References: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> Message-ID: <1122640048.898562.3600@g43g2000cwa.googlegroups.com> Ajar wrote: > I want to write a program which will automatically login to my ISPs > website, retrieve data and do some processing. Can this be done? Can > you point me to any example python programs which do similar things? > > Regards, > Ajar Very easily. Have a look at my article on the ``urllib2`` module. http://www.voidspace.org.uk/python/articles.shtml#http You may need to use ClientCookie/cookielib to handle cookies and may have to cope with BASIC authentication. There are also articles about both of these as well. If you want to handle filling in forms programattically then the module ClientForm is useful (allegedly). Best Regards, Fuzzyman http://www.voidspace.org.uk/python From bokr at oz.net Fri Jul 15 21:13:05 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 16 Jul 2005 01:13:05 GMT Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> Message-ID: <42d85d5d.291420430@news.oz.net> On 15 Jul 2005 17:33:39 -0700, "MKoool" wrote: >I have a file with binary and ascii characters in it. I massage the >data and convert it to a more readable format, however it still comes >up with some binary characters mixed in. I'd like to write something >to just replace all non-printable characters with '' (I want to delete >non-printable characters). > >I am having trouble figuring out an easy python way to do this... is >the easiest way to just write some regular expression that does >something like replace [^\p] with ''? > >Or is it better to go through every character and do ord(character), >check the ascii values? > >What's the easiest way to do something like this? > >>> import string >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' >>> identity = ''.join([chr(i) for i in xrange(256)]) >>> unprintable = ''.join([c for c in identity if c not in string.printable]) >>> >>> def remove_unprintable(s): ... return s.translate(identity, unprintable) ... >>> set(remove_unprintable(identity)) - set(string.printable) set([]) >>> set(remove_unprintable(identity)) set(['\x0c', ' ', '$', '(', ',', '0', '4', '8', '<', '@', 'D', 'H', 'L', 'P', 'T', 'X', '\\', '` ', 'd', 'h', 'l', 'p', 't', 'x', '|', '\x0b', '#', "'", '+', '/', '3', '7', ';', '?', 'C', 'G', 'K', 'O', 'S', 'W', '[', '_', 'c', 'g', 'k', 'o', 's', 'w', '{', '\n', '"', '&', '*', '.', '2', '6', ':', '>', 'B', 'F', 'J', 'N', 'R', 'V', 'Z', '^', 'b', 'f', 'j', 'n', 'r', 'v', 'z', '~', ' \t', '\r', '!', '%', ')', '-', '1', '5', '9', '=', 'A', 'E', 'I', 'M', 'Q', 'U', 'Y', ']', 'a', 'e', 'i', 'm', 'q', 'u', 'y', '}']) >>> sorted(set(remove_unprintable(identity))) == sorted(set(string.printable)) True >>> sorted((remove_unprintable(identity))) == sorted((string.printable)) True After that, to get clean file text, something like cleantext = remove_unprintable(file('unclean.txt').read()) should do it. Or you should be able to iterate by lines something like (untested) for uncleanline in file('unclean.txt'): cleanline = remove_unprintable(uncleanline) # ... do whatever with clean line If there is something in string.printable that you don't want included, just use your own string of printables. BTW, >>> help(str.translate) Help on method_descriptor: translate(...) S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. Regards, Bengt Richter From k04jg02 at kzoo.edu Sat Jul 16 03:53:10 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Sat, 16 Jul 2005 01:53:10 -0600 Subject: Python Programming Contest In-Reply-To: <42D780EF.6020809@sweetapp.com> References: <42D780EF.6020809@sweetapp.com> Message-ID: <42D8BCE6.8020202@kzoo.edu> Someone correct me if I'm wrong -- but isn't this the Shortest Path problem? I don't foresee anyone getting a more efficient solution than what they can find in hundreds of algorithms textbooks. If this is indeed the case it should just come down to whoever can pull the narliest tricks to create a fast python implementation of the algorithm. Brian Quinlan wrote: >I've decided that it would be be fun to host a weekly Python programming >contest. The focus will be on algorithms that require a bit of thought >to design but not much code to implement. > >I'm doing to judge the solutions based on execution speed. It sucks but >that is the easiest important consideration to objectively measure. I'll >also indicated which solutions I think are good examples of Python >design. Hopefully, people's solutions can provide a resource for people >looking for best practice examples and also for people looking for >performance ideas. > >You can find the first problem here: >http://www.sweetapp.com/pycontest/contest1 > >I'm always looking for feedback, so let me know what you think or if you >have any ideas for future problems. > >Cheers, >Brian > > > From bokr at oz.net Fri Jul 8 21:43:07 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 01:43:07 GMT Subject: python-dev Summary for 2005-06-16 through 2005-06-30 References: Message-ID: <42cf2b4f.165770875@news.oz.net> On Fri, 8 Jul 2005 18:15:37 -0600, Steven Bethard wrote: >[The HTML version of this Summary is available at >http://www.python.org/dev/summary/2005-06-16_2005-06-30.html] > Not when I just looked, but maybe it takes a while ;-) Regards, Bengt Richter From no at spam Mon Jul 18 20:57:35 2005 From: no at spam (D H) Date: Mon, 18 Jul 2005 19:57:35 -0500 Subject: goto In-Reply-To: <867jfnu1in.fsf@bhuda.mired.org> References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <867jfnu1in.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > rbt writes: > >>Many of the world's most profitable software companies (MS for example) >>have thousands of goto statements in their code... oh the horror of it >>all. Why aren't these enlightened-by-the-gods know-it-alls as profitable >>as these obviously ignorant companies? > > > Because profitability has *nothing* to do with code quality, and > everything to do with marketing. MS, in particular, has done an > excellent job of divorcing code quality from their bottom line by > shuffling the bulk of the support work off to other companies: > hardware vendors who bundle MS software, system integrators, and > customers friends and family being very high on the list. > > That they felt the need to do this speaks volumes about their code > quality. whoa whoa whoa! Discussing goto statements and Microsoft together is like mixing dynamite and gasoline. We don't want this to explode into some interminable argument; that's not the kind of thing people like to see on comp.lang.python. Oh by the way, boo has goto statements: http://svn.boo.codehaus.org/trunk/tests/testcases/integration/goto-1.boo?view=auto KABOOM From sybrenUSE at YOURthirdtower.com.imagination Thu Jul 21 05:40:51 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 21 Jul 2005 11:40:51 +0200 Subject: newbie - mode for directory References: <1121938442.571119.29800@f14g2000cwb.googlegroups.com> Message-ID: wcc enlightened us with: > When using os.mkdir, what are the numeric numbers for different > modes? man chmod Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From mensanator at aol.com Tue Jul 12 12:44:11 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 12 Jul 2005 09:44:11 -0700 Subject: Inconsistency in hex() In-Reply-To: References: Message-ID: <1121186651.646666.50690@g14g2000cwa.googlegroups.com> Steven D'Aprano wrote: > hex() of an int appears to return lowercase hex digits, and hex() of a > long uppercase. > > >>> hex(75) > '0x4b' > >>> hex(75*256**4) > '0x4B00000000L' > > By accident or design? Apart from the aesthetic value that lowercase hex > digits are ugly, should we care? No, just use GMPY. >>> from gmpy import * >>> print digits(75,16) 0x4b >>> print digits(75*256**4,16) 0x4b00000000 Although it would have been nice to also get rid of the octal hex prefix inconsistencies. >>> for b in range(2,37): print digits(75*256**4,b) 100101100000000000000000000000000000000 1010210110021101212101010 10230000000000000000 20234201333002300 403551524040520 32162332321446 04540000000000 <-- base 8 starts with leading 0 1123407355333 322122547200 11467a864463 5251a233140 244b718a01c 1183b2a2b96 85a4947a50 0x4b00000000 <-- base 16 starts with leading 0x 2c304c17g7 1b42e32gac ii6ie79hd cbd35i800 8ahh6hjk6 5j31lfeje 42dma7a93 2m5e7gl80 22ja8i0d0 1e2je99kc 13lc7ana3 noclhnpk ijflp0nb elq24la0 blth91bl 9c000000 7idw8no3 64hn2ago 5083wbdk 43zbg45c > > It would also be nice if that trailing L would disappear. > > -- > Steven. From dan at cellectivity.com Tue Jul 26 11:39:44 2005 From: dan at cellectivity.com (Dan) Date: Tue, 26 Jul 2005 16:39:44 +0100 Subject: Packages and modules In-Reply-To: References: Message-ID: <1122392385.20317.33.camel@localhost.localdomain> > > no executable code in > > __init__.py is executed, even though "import test" seems to succeed. I've discovered that "import test" *does* cause executable code in the package to be executed. However, I can't execute it on the command line using "python test". Is there a way to do this? > There _is_ a standard library package called test Oh, you're right. But I've renamed the module to XYZ and I still have the problem. -- They had a big meeting, drank some beer and had some pizza and decided 'A' would be 65. - Jim Greenly, professor at Georgia Institute of Technology From thomas at thomas-lotze.de Tue Jul 12 16:27:42 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 12 Jul 2005 22:27:42 +0200 Subject: Slicing every element of a list References: Message-ID: Alex Dempsey wrote: > for line in lines: > line = line[1:-5] > line = line.split('\"\t\"') > > This went without returning any errors, but nothing was sliced or split. > Next I tried: > > for i in range(len(lines)): > lines[i] = lines[i][1:-5] > lines[i] = lines[i].split('\"\t\"') > > This of course worked, but why didn't the first one work. Because when assigning to line the second time, you just make the identifier reference a new object, you don't touch the list. This is how one might do it without ranging over the length of the list and having to get the lines out by element access: for i, line in enumerate(lines): line = line[1:-5] lines[i] = line.split('\"\t\"') Probably there are even better ways, this is just off the top of my head. > Further why > didn't the first one return an error? Because you didn't make any. You just discarded your results; why should anyone stop you from burning cycles? *g -- Thomas From sklass at pointcircle.com Sun Jul 31 00:29:00 2005 From: sklass at pointcircle.com (rh0dium) Date: 30 Jul 2005 21:29:00 -0700 Subject: Passing a log handle to a module? Help needed with logging module and Message-ID: <1122784140.800331.86740@z14g2000cwz.googlegroups.com> Hi all, So I have a slice of code which calls other python code. I have started to take a real liking to the logging module, but I want to extend this into the called python code. I have no idea how to pass the handle from the calling code into the modules.. So basically here is what I do.. -- Main Program -- # Setup the logger.. import logging log = logging.getLogger("main") log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)-8s %(message)s",datefmt='%d %b %Y %H:%M:%S') ch.setFormatter(formatter) log.addHandler(ch) log.info(" ----> New run of started <---- ") modules = [] # Add the mods directory so we can call the modules later sys.path.insert( 0, os.getcwd() + "/mods" ) for metric in glob.glob("mods/*.py"): # Now lets start working on the individual metrics module_name, ext = os.path.splitext(os.path.basename(metric)) log.debug( "Attempting to import %s" % module_name ) try: module = __import__(module_name) modules.append( module ) log.info( "Successfull import of %s" % module_name ) except ImportError , e: log.error( "Failed import of %s - %s" % ( module_name, e) ) pass for module in modules: module.main( ) ----------------------- ---- Called module ----- def main(): print "Yep were in" if __name__ == '__main__': main() ----------------------- Now what I want to do is simple.. I want to change the called module so that it looks something like this.. ---- Called module ----- def main( logging_handle=None ): print "Yep were in" if logging_handle: log=logging.handle ( SOME WAY TO CHANGE THE getLogger name to Module ) else: log=setUpLog() log.debug( "Hey it works..") def setUpLog(): # Setup the logger.. import logging log = logging.getLogger("module") log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)-8s %(message)s",datefmt='%d %b %Y % H:%M:%S') ch.setFormatter(formatter) log.addHandler(ch) return log if __name__ == '__main__': main() ----------------------- But I can't figure out how to pass the d$!@# logging handle to the called module - much less change the getLogger name to "module". Can someone please help me with this? I know I must be doing something braindead.. Thanks so much!! From steve at REMOVETHIScyber.com.au Tue Jul 19 10:03:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 20 Jul 2005 00:03:36 +1000 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> Message-ID: On Tue, 19 Jul 2005 20:28:31 +1200, Ross wrote: > On 15 Jul 2005 17:33:39 -0700, "MKoool" wrote: > >>I have a file with binary and ascii characters in it. I massage the >>data and convert it to a more readable format, however it still comes >>up with some binary characters mixed in. I'd like to write something >>to just replace all non-printable characters with '' (I want to delete >>non-printable characters). >> >>I am having trouble figuring out an easy python way to do this... is >>the easiest way to just write some regular expression that does >>something like replace [^\p] with ''? >> >>Or is it better to go through every character and do ord(character), >>check the ascii values? >> >>What's the easiest way to do something like this? >> >>thanks > > Easiest way is open the file with EdXor (freeware editor), select all, > Format > Wipe Non-Ascii. > > Ok it's not python, but it's the easiest. 1 Open Internet Explorer 2 Go to Google 3 Search for EdXor 4 Browser locks up 5 Force quit with ctrl-alt-del 6 Run anti-virus program 7 Download new virus definitions 8 Remove viruses 9 Run anti-spyware program 10 Download new definitions 11 Remove spyware 12 Open Internet Explorer 13 Download Firefox 14 Install Firefox 15 Open Firefox 16 Go to Google 17 Search for EdXor 18 Download application 19 Run installer 20 Reboot 21 Run EdXor 22 Open file 23 Select all 24 Select Format>Wipe Non-ASCII 25 Select Save 26 Quit EdXor Hmmm. Perhaps not *quite* the easiest way :-) -- Steven. From jaymail at gawab.com Sun Jul 31 00:49:04 2005 From: jaymail at gawab.com (Jay) Date: 30 Jul 2005 21:49:04 -0700 Subject: keylogger in Python In-Reply-To: References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> Message-ID: <1122785344.538363.122600@g49g2000cwa.googlegroups.com> yo, thanks for the great input. And the only reason i want to create a python based keylogger is because there is none. Just a fun project... But im gonna do some more research on the keyboard drivers and stuff like that and to learn how to attach my python porgrams into the sub-processes so that it would instead log every char instead of just char in the IDE. thx From godwinburby at rediffmail.com Wed Jul 13 02:08:50 2005 From: godwinburby at rediffmail.com (Godwin) Date: 12 Jul 2005 23:08:50 -0700 Subject: Web App like Google In-Reply-To: References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> Message-ID: <1121234930.929540.47140@o13g2000cwo.googlegroups.com> Thanks for providing me with all those informative links about NLTK nad CNL. I'll certainly look into it. From travislspencer at gmail.com Wed Jul 20 16:01:32 2005 From: travislspencer at gmail.com (travislspencer at gmail.com) Date: 20 Jul 2005 13:01:32 -0700 Subject: Printing a variable's name not its value References: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> <42deaadb$0$6734$626a14ce@news.free.fr> Message-ID: <1121889692.797655.165770@g47g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > travislspencer at gmail.com a ?crit : > > globals = {} > > globals() is a builtin function, you should no shadow it. Oh, woops. I'll fix that. > def printVerbose(*args, **kwargs): > > > if VERBOSE in globals: > > for a in args: > > if a in globals: > > value = globals[a] > > for k, v in kwargs: > > print "%s: %s" % (k, v) > > Perfect. Thanks for the pointer. > > I've been told on #python that there isn't a way to get a variable's > > name. I hope this isn't so. > > It is so. In fact, there is nothing like a 'variable' in Python. What we > have are names bound to objects. Names 'knows' what objects are bound to > them, but objects knows *nothing* about names they are bound to. OK. This seems like it might take some getting used to. Thanks again for the help. -- Regards, Travis Spencer From sjmachin at lexicon.net Sat Jul 9 21:01:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 10 Jul 2005 11:01:56 +1000 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: <42d07380$1@news.eftel.com> Roy Smith wrote: > Well, you've now got a failure. I used to write Fortran on punch cards, which were then fed into an OCR gadget? That's an efficient approach -- where I was, we had to write the FORTRAN [*] on coding sheets; KPOs would then produce the punched cards. [snip] > > 3) In some cases, they can lead to faster code. A classic example is > counting occurances of items using a dictionary: > > count = {} > for key in whatever: > try: > count[key] += 1 > except KeyError: > count[key] = 1 > > compared to > > count = {} > for key in whatever: > if count.hasKey(key): Perhaps you mean has_key [*]. Perhaps you might like to try if key in count: It's believed to be faster (no attribute lookup, no function call). [snip] [*] humanandcomputerlanguagesshouldnotimhousecaseandwordseparatorsascrutchesbuttheydosogetusedtoit :-) From benji at benjiyork.com Wed Jul 6 15:21:48 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 06 Jul 2005 15:21:48 -0400 Subject: Use cases for del In-Reply-To: <20050706184919.GV12095@itea.ntnu.no> References: <20050706184919.GV12095@itea.ntnu.no> Message-ID: <42CC2F4C.60701@benjiyork.com> Stian S?iland wrote: > Yes, and we can make > > someunknownlist[] = 2 > > magically do someunknownlist = list() and append 2. I hope you're being sarcastic. :) If not, why don't you like: some_list = [2] -- Benji York From siona at chiark.greenend.org.uk Fri Jul 1 11:29:02 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Jul 2005 16:29:02 +0100 (BST) Subject: map vs. list-comprehension References: Message-ID: Tom Anderson wrote: >On Thu, 30 Jun 2005, Roy Smith wrote: >> Even some of the relatively recent library enhancements have been kind >> of complicated. The logging module, for example, seems way over the >> top. >Exactly the same thing happened with Java. I was under the impression that Python's logging module (like unittest) was based on a common Java one, and it's complexity could be blamed on that. > if you look at the libraries >that were in 1.1, they're very clean and simple (perhaps with the >exception of AWT). 1.2 added a load of stuff that was much less >well-designed (with the notable exception of the collections stuff, which >is beautiful) There are very many adjectives I could (and have) used to describe the Collection framework. "Beautiful" is not among them. I think the closest I could manage is "baroque". -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From mwm at mired.org Sun Jul 31 00:30:36 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 00:30:36 -0400 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42ebe919.164695739@news.oz.net> Message-ID: <861x5fiolv.fsf@bhuda.mired.org> bokr at oz.net (Bengt Richter) writes: > On Fri, 29 Jul 2005 18:07:31 -0400, Mike Meyer wrote: >>I know, lambda bashing (and defending) in the group is one of the most >>popular ways to avoid writing code. However, while staring at some Oz >>code, I noticed a feature that would seem to make both groups happy - >>if we can figure out how to avoid the ugly syntax. > try > > http://groups-beta.google.com/groups?as_q=anonymous+def&as_ugroup=comp.lang.python > > for much discussion of this ;-) Well, that pretty much kills that. I knew there had been a lot of discussion about anonymous functions, anonymous blocks, and of course various lambda replacements. But I didn't realize almost exactly this proposal had been discussed before. Shouldn't surprise me, though. Thanks to everyone who took the time to read and respond. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tjreedy at udel.edu Tue Jul 5 21:58:58 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 5 Jul 2005 21:58:58 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com><1120565012.080020.309070@o13g2000cwo.googlegroups.com><1120590707.093007.175330@o13g2000cwo.googlegroups.com><11cloakd4glsbef@corp.supernews.com> <-8ydnZxXGOCQvlbfRVn-3Q@comcast.com> Message-ID: "Steven Bethard" wrote in message news:-8ydnZxXGOCQvlbfRVn-3Q at comcast.com... > OTOH, I fully agree with Peter Hansen: "Really, the name is such a > trivial, unimportant part of this whole thing that it's hardly worth > discussing." >From a certain viewpoint, I would agree. Yet, the word 'lambda' *is* the center of most of the fuss. For beginners, it is a minor issue: learn it and move on. But for some functionalists, it is a major issue. They 'know' that lambda means 'expressionized anonymous function'. And in lambda calculus, it is the main actor. But in Python, lambda only means anonymous trivial function. It is only an expressionized convenience abbreviation for an important but small subset of possible functions. So for years, such knowledgeable people have called for and proposed various syntaxes for 'proper lambdas' or 'true lambdas', saying pretty clearly that what Python has is improper or false. Would there have been so much fuss if the keyword had been 'fun' and the word 'lambda' had never appeared in the Python docs? I strongly doubt it. I also suspect that the years of fuss over Python's lambda being what it is rather that what it is 'supposed' to be (and is in other languages) but is not, has encourage Guido to consider just getting rid of it. I personally might prefer keeping the feature but using a different keyword. Terry J. Reedy From jstroud at mbi.ucla.edu Tue Jul 5 19:22:51 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 5 Jul 2005 16:22:51 -0700 Subject: multiple checkboxes highlighted when one clicked = not good In-Reply-To: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> References: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> Message-ID: <200507051622.51067.jstroud@mbi.ucla.edu> On Tuesday 05 July 2005 04:11 pm, MooMaster wrote: > ?self.InUse =[BooleanVar(), BooleanVar(), BooleanVar(), BooleanVar(), > BooleanVar(), BooleanVar(), BooleanVar()] > ? ? ? ? for i in range(1,11): ? ? ? ? ? ? for t in range(7): ? ? ? ? ? ? ? ? if(t==0): ? ? ? ? ? ? ? ? ? ? Checkbutton(self.frame2, variable = self.InUse[t]).grid(row= i, column = t) should this last line read "self.InUse[i]" ? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From matthewharrison at gmail.com Tue Jul 12 16:17:58 2005 From: matthewharrison at gmail.com (matt) Date: 12 Jul 2005 13:17:58 -0700 Subject: python parser In-Reply-To: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> References: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> Message-ID: <1121199478.549103.181750@g47g2000cwa.googlegroups.com> I recently was successful using pyparsing after messing around with ply for a few hours. See my blog for more details ( http://panela.blog-city.com/icfp_contest_implementation_in_python_notes.htm ). I personally corresponded with the author and he was very helpful as well, giving my useful critiques and feedback. The next time I'm parsing something more complex than a tab-delimited file (excluding xml :)) I'll probably use pyparsing. I found it very pythonic and easy to use. good luck parsing... matt From kay.schluehr at gmx.net Sat Jul 30 05:33:13 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Jul 2005 02:33:13 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <1122715993.183245.40940@g43g2000cwa.googlegroups.com> Mike Meyer schrieb: > I know, lambda bashing (and defending) in the group is one of the most > popular ways to avoid writing code. However, while staring at some Oz > code, I noticed a feature that would seem to make both groups happy - > if we can figure out how to avoid the ugly syntax. > > This proposal does away with the well-known/obscure "lambda" > keyword. It gives those who want a more functional lambda what they > want. It doesn't add any new keywords. It doesn't add any new magic > characters, though it does add meaning to an existing one. That could > be replaced by a new magic token, or adding magic meaning to a > non-magic token. It breaks no old code either way. Mike, in modern functional language design one starts with certain lambda expressions and add syntax sugar ( operational / statement syntax ) for constructs based on them. In Python statement- and expression syntax were introduced seperately. Pythons lambda is simply the symptom of this separation. Now you suggest ( not the first time on this list or at python-dev ) to put statements into expressions leading to a strange syntax and conflicting with Pythons indentation rules. Another way to deal with the restrictions of lambda is going the other way round and simply propose expression syntax for conds and assignments. Using guards '||' and the keyword 'then' for conditional expressions: ( || x>=0 then f(x) || True then f(-x) ) Or shorter dropping 'then' in the second condition: ( || x>=0 then f(x) || f(-x) ) Both translates to: if x>=0: f(x) else: f(-x) Using a reverse arrow for assignments: x <- y For loops can be replaced by functional constructs ( use map() or a list/generator comprehension ). Finally the lambda keyword can be replaced by expressional syntax e.g. ( EXPR from ARGS ): Examples: f = ( || x>=0 then f(x) || True then f(-x) from (x,) ) g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,)) Kay From k.robert at gmx.de Mon Jul 4 12:36:57 2005 From: k.robert at gmx.de (Robert) Date: Mon, 4 Jul 2005 18:36:57 +0200 Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Message-ID: "Derek van Vliet" schrieb im Newsbeitrag news:1120484279.054832.312150 at g49g2000cwa.googlegroups.com... > Using the Python/C API, is there a way I can import a pyc file that I > have in memory (as opposed to loading from disk)? > > I'm trying to save compiled python code in a proprietary file format to > cut reduce the overhead of compiling all my scripts when my app starts > up. you can use a zip file as "proprietary file format"? with .pyc's or .py's in and add the zippath to sys.path ? other than that you can load the code object of .pyc's content in a string like co = marshal.loads( pyc_s[8:] ) mod=imp.new_module('xy') exec co in mod.__dict__ Robert From kbchung at hongik.ac.kr Sun Jul 31 04:04:30 2005 From: kbchung at hongik.ac.kr (KB) Date: 31 Jul 2005 01:04:30 -0700 Subject: How to convert a string like '777' to an octal integer like 0777? References: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> <42ec640a@news.eftel.com> <1122794648.326967.284070@g47g2000cwa.googlegroups.com> Message-ID: <1122797070.273188.153610@g14g2000cwa.googlegroups.com> > The leading zero only exists in a particular string > representation. os.chmod() needs an integer, not a string. 0777 == 511. Thanks, Robert. What you said is exactly what I did not understand clearly, because I am just a beginner in Python programming. KB From edgrsprj at ix.netcom.com Mon Jul 11 04:31:31 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Mon, 11 Jul 2005 08:31:31 GMT Subject: Earthquake Forecasting Program July 11, 2005 Message-ID: PROPOSED EARTHQUAKE FORECASTING COMPUTER PROGRAM DEVELOPMENT EFFORT Posted July 11, 2005 My main earthquake forecasting Web page is: http://www.freewebz.com/eq-forecasting/Data.html Newsgroup Readers: If you circulate copies of this report to groups of computer programmers at different universities etc. around the world then they might find the subject matter to be interesting. The information in this report represents expressions of personal opinion. THE GOAL OF THIS REPORT This is part of an effort to get some idea regarding how many computer programmers and other researchers around the world might be interested in participating in a project aimed at developing life saving earthquake forecasting computer programs. That effort is not presently underway. And I don't know when or if it will get started. I am simply attempting to determine if other people believe that large numbers of volunteers would be interested in working on such a project or if there would instead be little interest in it. That information would be helpful for developing a plan for establishing a Web site where the project would be centered. Personnel running the following Web site have volunteered to make their site available for such an effort. But nothing has gotten underway so far. http://www.ictwhoiswho.net/comprend/index.cfm If quite a few people were interested in such a Web site based computer program development effort then after it got started work would undoubtedly progress quite rapidly. If only a few were interested then it might never get started. If you would like to express an opinion on the likelihood of people being interested in the idea then you can try posting a note in response to this one. The sci.geo.earthquakes or comp.lang.misc newsgroups might be appropriate if you wish to post to just one newsgroup. Of you can try contacting me by e-mail. THE CORE OF THE PRESENT EARTHQUAKE FORECASTING PROGRAM In connection with an earthquake forecasting effort which has been underway for the past 15 years I believe I have been able to crack the "Earthquake Code." That means making crucially important discoveries regarding how earthquakes are being triggered. Two of them which are discussed on the following Web page are called the "Gravity Point" and "Earthquake Triggering Symmetry." http://www.freewebz.com/eq-forecasting/90-05.html The earthquake triggering and forecasting theories and data on that Web page were discussed on my behalf by one of my research colleagues in the People's Republic of China at a disaster mitigation conference in that country in December of 2003. Governments and disaster mitigation groups around the world were told about the Web site earlier this year. And my Web site visitor counter indicates that some 100 to 200 people around the world are presently downloading information from the site each day. My earthquake forecasting computer programs use those Gravity Point and Earthquake Triggering Symmetry discoveries and others to compare electromagnetic energy field fluctuation type signals (EM signals) with more than 30,000 earthquakes which occurred since the beginning of 1990. Some 100 to 200 signals detected during a 3 month period of time are involved. For some as yet unknown reason they are often highly selective for earthquakes which are likely to occur near populated areas, making them unusually valuable. The earthquake which is the best match with all of those signals is rated # 1. The worst match would have a rating number greater than 30,000. A listing of more than 100 of the best matches is then posted perhaps once a week to the following Web page: http://www.freewebz.com/eq-forecasting/Data.html For a recent example of how well that approach to forecasting earthquakes can work, data displayed on that Web page on June 27, 2005 gave the following earthquake a # 3 rating (possible rating range: 1 to 30,000+): 2005/01/11 19:19:48 11.40N 86.51W 40.7 5.0 Near the Coast of Nicaragua (U.S. National Earthquake Information Service data) And less than a week later on July 2, 2005 the following powerful and strongly felt earthquake occurred: 2005/07/02 02:16:46 11.18N 86.40W 45.5 6.7 Near the Coast of Nicaragua 11.40N and 86.51W versus 11.18N and 86.40W Pretty good accuracy for a forecasting program! That earthquake was reportedly strongly felt in Managua. Had it occurred directly beneath the city and near the surface then I expect that it would have been devastating. WHAT NEEDS TO BE DONE Basically, more sophisticated data processing and data display computer program subroutines need to be developed. They could be built on my already existing computer programs and data. People would develop new subroutines, give them a try, and see if they did a better job of determining or displaying where an earthquake might be about to occur. The subroutines could be stored at the proposed Web site. Ones that were especially helpful could be merged into the main program one version of which might run as a CGI program at the Web site. Other versions of the programs would be downloadable for free for use on personal computers. The basic form of the data processing routine for my existing program and probably many other earthquake forecasting programs might be expressed in the following manner: Prob = aA + bB + cC + dD + eE + ... "Prob" is the probability that an earthquake of a given magnitude will occur at a specific latitude, longitude, depth, and time. A, B, C, D, and E . are things such as: A - the gradual buildup of strain in a fault zone due to the movement of the Earth's tectonic plates relative to one another B - temporary strain added to the fault zone by bending, stretching, and compression forces related to the Solid Earth Tide. (The ground shifts a little in response to the sun and moon gravities just as ocean water does - hence the Solid Earth Tide) C - temporary strain added to the fault zone by the weight of ocean water shifting from one location to another in connection with ocean tides a, b, c, d, and e .. are "weight" factors which specify how important A, B, and C etc. are at different points in time. "A," the gradual buildup of strain in a fault zone related to tectonic plate movement etc. is undoubtedly the most important factor and perhaps the only one which scientists around the world are in agreement on. It can probably be determined with a certain amount of accuracy for some fault zones at the present time, but not too many. With my present computer programs I do not use actual values for "A" as they would be impossible to determine. Instead when a strong EM signal is detected I simply assume that a fault zone somewhere has stored enough strain energy that it is about ready to fracture. And an effort is made to determine where it is located. With each probability calculation my present computer programs do about 30 separate comparisons between each of the 100 to 200 EM signals and the more than 30,000 earthquakes in my database file. The comparisons involve things such as the positions of the sun and the moon in the sky and the locations of ocean and Solid Earth Tide crests and troughs around the world when the EM signal was detected and when the earthquake occurred. For an example of one possible and relatively easy computer program improvement, an effort could be made to see if factoring in earthquake fault zone orientation - north and south versus east and west - improved the probability calculations. Another improvement would involve determining the importance of the latitudes of the Gravity Points and the sublunar points. At the present time only their longitudes are used in my calculations. (The sublunar point is the location on the surface of the Earth which a line drawn between the center of the Earth and the center of the moon would pass through.) An earthquake forecasting group at Madras University in India has already developed some advanced earthquake location determination routines which it appears might be helpful to this effort. Routines developed for use at the following Web sites might also be helpful. http://pasadena.wr.usgs.gov/step/ http://www-aig.jpl.nasa.gov/public/dus/quakesim/ THE PROGRAMMING LANGUAGE IN PRESENT USE The original programs were written in a number of languages including Basic. The main program is presently written in Perl. That language was chosen because it is fast and powerful, the compiler can be downloaded for free by anyone, and because it looks like it is getting sufficient support that calculations can be trusted and it will be around for a while. There is another feature of that language which I am guessing many other programming languages probably presently offer though that was not the case in the past. That is the ability to make changes to the program code itself at the same time that the program is running. I myself do that in the following manner: Ordinarily the main program "P1" starts running and performs a group of calculations. That takes about 5 minutes. It then waits for a keyboard instruction telling it how the output data should be displayed. As with probably any program, once it is running in the normal mode no changes can be made to the program itself. However when it is run in the following experimental mode that rule does not apply. A short program I will call "P2" starts running and immediately uses a "do" statement to get the regular program P1 to compile and start running. P1 does the original calculations like normal. But instead of waiting for the operator to enter a data display command it exits and P2 becomes active again. A display instruction is entered and P1 is told to recompile and start running again. Instead of doing all of the calculations from scratch it jumps strait to the display routine and uses the entered command to begin printing the output data. The data generated when it originally did the calculations are still in memory. The advantage here is that at any time, program P1 can be called into a text editor, modified as desired, and then saved. A new display subroutine can be added to it or an existing routine can be modified while the previously generated data are still active in the computer. Then when P1 is directed by P2 to recompile (that takes about a second) and run, the new subroutine is included just as if it were in the original program. If the compiler encounters a programming error it terminates and returns control to program P2. A correction can then be made to the new program code and the sequence repeated. No data are lost because of the error. And you don't have to wait for 5 minutes while the program recalculates everything. Data processing and display routines could be written with other programming languages besides Perl. If done with sufficient care more than one language could be used at the same time. The different language routines would simply be linked with one another. A LIFE SAVING EFFORT It appears to me (sadly) that few governments have a very good sense of direction with regard to the development of life saving earthquake forecasting programs. The work is usually undertaken by independent research groups at various government agencies or universities. They go their own ways, uninterested in or unable to work with one another to effectively forecast deadly earthquakes. They often claim that if they share information then they could lose their patent rights and potential profits etc. And that could actually happen. But isn't saving tens of thousands of lives more important than simply making a meager profit (which no one that I am aware of is presently able to do with their forecasting programs anyway)? I myself presently own 3 U.S. copyrights related to my forecasting technology. But I have been letting interested parties around the world use it for free. See: http://www.freewebz.com/eq-forecasting/301.html One country where forecasting program information is shared to some extent is the People's Republic of China were some 10,000 people reportedly work full-time in a state sponsored earthquake forecasting program. They are also supported by a small army of volunteer workers. But even there the forecasting efforts of different groups are not effectively coordinated very often from what I can see. And advanced forecasting technology being developed in other countries is frequently ignored. A listing of some other earthquake forecasting programs around the world can be found on the following Web page: http://www.freewebz.com/eq-forecasting/141.html A book discussing one of the forecasting programs listed on that Web page is scheduled for release some time in late 2005. See: http://www.sentientpublications.com/catalog/earthquakes.php I myself assisted with that effort by providing the author with some free technical information and book content advice. The proposed Internet Web site effort to develop an effective earthquake forecasting program discussed in this present report could not be ignored by governments around the world. Once they saw how well the programs worked then they would be forced to begin using them to predict their own earthquakes. United Nations personnel appeared to like this concept when I formally proposed it to them in July of 2004. http://www.unisdr.org/wcdr-dialogue/t3-dialogue.htm#34 And they discussed it repeatedly in their summary reports of the ideas proposed during that Internet Web site based conference. But no governments or disaster mitigation groups expressed any interest in developing the concept. Since the starting point for the proposed forecasting program development efforts would be the computer programs that I already have running, success would be guaranteed. So, the important question would then be, "How many computer programmers and other researchers would be interested in helping with such an effort?" This type of work is quite interesting and exciting when you become actively involved with it. You can generate a forecast. And then when the earthquake occurs where you expected you can get a pretty good shock. If the earthquake is also destructive the experience can be rather frightening. The importance of the work should be obvious. More than a quarter of million people reportedly perished in connection with the December 26, 2004 earthquake generated tsunami (tidal wave) in the Indian Ocean. My present forecasting computer programs did not become operational until several weeks after it occurred. But when I ran my EM signal data from around that time through the programs the results indicated to me that the earthquake could have been predicted. Why devote valuable free time to developing computer programs which do ordinary things when that time could be devoted to developing programs which might eventually help save tens or even hundreds of thousands of lives? From steve at REMOVETHIScyber.com.au Mon Jul 4 19:13:24 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 05 Jul 2005 09:13:24 +1000 Subject: math.nroot [was Re: A brief question.] References: Message-ID: On Mon, 04 Jul 2005 15:35:56 +0100, Tom Anderson wrote: >>> Also, would it be a good idea for (-1.0) ** 0.5 to evaluate to 1.0j? It >>> seems a shame to have complex numbers in the language and then miss this >>> opportunity to use them! >> >> It's generally true in Python that complex numbers are output only if >> complex numbers are input or you explicitly use a function from the >> cmath module. [...] The presumption is that a complex result is more >> likely the result of program error than intent for most applications. >> The relative handful of programmers who expect complex results can get >> them easily, though. > > A reasonable presumption. > > I always got really wound up that the calculator i had at school had this > behaviour too, *even in complex number mode*! Come to think of it, i don't > think it could do roots of imaginary numbers at all. However, python is > not a calculator. Of course it is :-) py> 1+2 3 It even works with complex numbers: py> print (-1+0j)**0.5 (6.12303176911e-17+1j) although you have to watch out for those rounding errors in floating point. py> import cmath py> cmath.sqrt(-1) 1j -- Steven From turnerst at family-zone.co.uk Thu Jul 28 18:24:32 2005 From: turnerst at family-zone.co.uk (Stuart Turner) Date: Thu, 28 Jul 2005 23:24:32 +0100 Subject: Friend wants to learn python References: <1122135598.347717.75830@g43g2000cwa.googlegroups.com> Message-ID: EnderLocke wrote: > I have a friend who wants to learn python programming. I learned off > the internet and have never used a book to learn it. What books do you > recommend? > > Any suggestions would be appreciated. I've just been learning Python and used a combination of 'Python in a Nutshell, Python Cookbook and whatever I could find on the web' I also find giving yourself a *real* programming task makes you learn a lot quicker! - Stuart From tdwdotnet at gmail.com Tue Jul 26 04:40:07 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 26 Jul 2005 09:40:07 +0100 Subject: how to build email message with attachment? In-Reply-To: <20050726082004.87922.qmail@web8401.mail.in.yahoo.com> References: <42E5EEB7.400@REMOVEMEcyber.com.au> <20050726082004.87922.qmail@web8401.mail.in.yahoo.com> Message-ID: <9afea2ac050726014078d5cdd7@mail.gmail.com> On 7/26/05, praba kar wrote: > Dear All, > > Can any one let me know? How to build > email in python? with some some examples. > > regards > Prabahar The email module is what you need. http://docs.python.org/lib/module-email.html hth :) From kay.schluehr at gmx.net Fri Jul 8 18:38:04 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Jul 2005 15:38:04 -0700 Subject: removing list comprehensions in Python 3.0 In-Reply-To: References: Message-ID: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> Steven Bethard schrieb: > I think the jury's still out on this one: > > * Alex Martelli expects list comprehensions to be removed. [1] > * Robert Kern wants list comprehensions removed. [2] > * Raymond Hettinger encourages continued use of list comprehensions [3] > * Jeremy Bowers thinks list comprehensions should stay. [4] > > I only searched a few relatively recent threads in c.l.py, so there are > probably more, but it looks to me like the final decision will have to > be made by a pronouncement from Guido. Well, I want to offer a more radical proposal: why not free squared braces from the burden of representing lists at all? It should be sufficient to write >>> list() list() After being free one can use them for other purposes e.g. replacing the ugly @ decorator character by the lovely [ .. ] notation or other important features no one never trusted to implement waiting for the right syntax sugar. More than this round braces together with lists can be considered as a concession to the LISP programmer who was repelled from Python by the decision to eliminate functional programming features. Kay From avera at coes.org.pe Mon Jul 18 15:50:28 2005 From: avera at coes.org.pe (Alberto Vera) Date: Mon, 18 Jul 2005 14:50:28 -0500 Subject: smtplib Message-ID: <000a01c58bd1$f2da5db0$1603a8c0@avc> Hello: Do you know If the smtplib routine have been changed in last releases? I used this script: http://docs.python.org/lib/SMTP-example.html but it didn't work with the last release. Do you know any idea about this change? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwh at python.net Sun Jul 31 14:42:44 2005 From: mwh at python.net (Michael Hudson) Date: Sun, 31 Jul 2005 18:42:44 GMT Subject: Asking the user a question and giving him a default answer he can edit References: <1122784487.040842.45910@g14g2000cwa.googlegroups.com> Message-ID: "levander" writes: > Basically, I've got a bunch of questions to ask a user, the vast > majority of which, the answer will only vary by the last few > characters. What I'd like to do is every time the user is asked a > question, give him the default answer as just whatever he answered last > time. But, I want him to be able to edit this default answer. And, the > editted answer is what I want to operate on inside my program. Something like this? />> def f(): |.. readline.set_startup_hook(lambda :readline.insert_text('aaa')) |.. return raw_input() \__ > Basically, I want to the user a line editor, with a default value > already populated. Or you could use my pyrepl package (see google for that). Cheers, mwh -- In case you're not a computer person, I should probably point out that "Real Soon Now" is a technical term meaning "sometime before the heat-death of the universe, maybe". -- Scott Fahlman From hancock at anansispaceworks.com Mon Jul 4 06:53:44 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 4 Jul 2005 05:53:44 -0500 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: Message-ID: <200507040553.44245.hancock@anansispaceworks.com> On Sunday 03 July 2005 07:05 pm, Erik Max Francis wrote: > I personally think that map looks clearer than a list comprehension for > a simple function call, e.g. I have to disagree > map(str, sequence) This says "call a function 'map' on 'str' and 'sequence'" Which, syntactically, is not terribly informative. I have to remember: * "str" is actually a callable * "map" is a mathematical concept of linking one thing to another. What things? "str to sequence"? No! Wrong guess. "str" is the "mapping function", and the result is the thing sequence is to be linked to. Now, sure, I know all this, and I learned what "map" did from the manual, but it's not especially easy to remember. This on the other hand, > [str(x) for x in sequence] is practically plain English: "call the function "str" on x, for every x in sequence" Other than chopping out a few words, and using the () operator instead of "call", it's hard to imagine this being any closer to exactly what you would say to describe the operation. And for most of us, English comes easier than Computer Science jargon. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From gene.tani at gmail.com Sun Jul 24 18:44:32 2005 From: gene.tani at gmail.com (gene tani) Date: 24 Jul 2005 15:44:32 -0700 Subject: Getting the --options of configure on installed python In-Reply-To: References: Message-ID: <1122245072.107893.311270@g14g2000cwa.googlegroups.com> look in distutils.cfg: http://www.python.org/doc/2.4.1/inst/config-syntax.html for modules compiled in, sys.builtin_module_names From ed at leafe.com Sat Jul 30 16:38:11 2005 From: ed at leafe.com (Ed Leafe) Date: Sat, 30 Jul 2005 16:38:11 -0400 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <200507301638.11537.ed@leafe.com> On Saturday 30 July 2005 16:06, Jorge Godoy wrote: > If it is added, let us know. ?I can't think of a better way to visualize > database reports in an easy and fast way. ?Specially for BI. What specifically are you looking for? We are working on the report writing engine now, tying in ReportLab. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From Scott.Daniels at Acm.Org Mon Jul 11 13:12:59 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 11 Jul 2005 10:12:59 -0700 Subject: Getting files in a subdirectory in a zip In-Reply-To: References: Message-ID: <42d2a0b1@nntp0.pdx.net> Echo wrote: > What would the best way to get a list of files in a subdirectory in a zip? > > The only thing I can come up with is to extract the zip into a temp > directory and then just grab the list of files in the subdirectory > that I need. This way seems very messy to me and I was wondering if > there are any better ways. > import zipfile z = zipfile.ZipFile('block.zip') names = [name[7:] for name in z.namelist() if name.startswith('others/')] --Scott David Daniels Scott.Daniels at Acm.Org From mynews44 at yahoo.com Wed Jul 13 17:12:40 2005 From: mynews44 at yahoo.com (googleboy) Date: 13 Jul 2005 14:12:40 -0700 Subject: more newbie list questions Message-ID: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> Hi there. I am doing a bunch of processing over a list of lists, and am interested in doing several things taht don't seem to be working for me just at the moment. I have a list of books with several fields (Title, Author1, Author2, Publisher, ISBN) in a csv. I have a cell.txt file that looks like this: ++ The title is %title%.

The author is %author1% %author2%

The Publisher is %publisher1% %publisher2%

The ISBN is %ISBN%

++ I know how to do something like sAuth = re.sub('%author1%', author1, sTemplate), but I can't figure out to populate variables within python from the list of fields. The second thing I am trying to figure out is how to add a field (or populate an empty field) called filename with the value of ISBN + '.txt', though I hope this becomes pretty self evident after someone helps me with the above. The last thing that is vexing me at the moment is something I am not sure if it is possible. Once I have populated this filename field, I will want to try to do something like: for book in all_books open(r'd:\path\to\files\%filename%', 'a') some_function Where I replace %filename% with the value of the filename field for each book. Is it possible to do some sort of search and replace like that over a command within python? Or is there another way entirely different to accomplish such a task, like maybe assigning the path/filename to a variable... ? TIA! Googleboy From twic at urchin.earth.li Fri Jul 1 08:28:08 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 1 Jul 2005 13:28:08 +0100 Subject: Python for everything? In-Reply-To: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 30 Jun 2005 xeys_00 at yahoo.com wrote: > can Python "do it all"? More or less. There are two places where python falls down, IMHO. One is performance: python isn't generally as fast as C or Java, even with Psyco. However, the number of cases where performance - and absolute straight-line performance of the code - actually matters is much smaller than you might think. Also, you can incorporate C into python pretty easily. The other is in bit-twiddling - anything that involves mucking about with data at the level of bits and bytes. Maybe this is just blind prejudice, but i'm never as comfortable hacking on that sort of stuff (writing a Huffman coder, say) in python as in java. Other than that, python is pure victory. > I am wondering what to learn as my scripting language. Python. > I have read that perl is good up to about 250 lines, and after that it > gets kind of hairy. That's putting it mildly. > I would like opinions as to the suitability of Python as a general > purpose language for programming unix, everything from short scripts to > muds. Python is, all things considered, definitely the best such language. There are strong arguments that can be made in favour of younger cousins of Python such as Ruby and Lua, but none of those have anything like the userbase or third-party code that Python does, and that counts for a lot. LISP (or rather Scheme) would be a more unusual option; it's a language that most people hate, but that people who really take the time to learn it love with a fervour bordering on scary. tom -- In-jokes for out-casts From tjreedy at udel.edu Sat Jul 16 15:02:42 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 16 Jul 2005 15:02:42 -0400 Subject: Python Programming Contest References: <42D780EF.6020809@sweetapp.com> Message-ID: "Tom Anderson" wrote in message news:Pine.LNX.4.62.0507161005440.9677 at urchin.earth.li... > On Sat, 16 Jul 2005, Joseph Garvin wrote: > >> Someone correct me if I'm wrong -- but isn't this the Shortest Path >> problem? > > Dang! I was just about to point that out. One twist is that it is not the shortest path to one node or all nodes but to a set of nodes (the destination on any of several days). > I can't immediately see any properties of this network that could be > exploited, but that doesn't mean there aren't any. No it doesn't. The challenge is to find a property that saves more time, across trials, that it takes to compute. Terry J. Reedy From kboruff at _*_&&_*_optonline.net Sun Jul 24 07:15:55 2005 From: kboruff at _*_&&_*_optonline.net (Keith P. Boruff) Date: Sun, 24 Jul 2005 07:15:55 -0400 Subject: FAQ? Message-ID: Hello, Is there an FAQ available specific to this NG as I'm sure some of the list slicing questions I have have been asked before. Thanks, KPB From chirayuk at gmail.com Fri Jul 22 13:05:11 2005 From: chirayuk at gmail.com (Chirayu Krishnappa) Date: 22 Jul 2005 10:05:11 -0700 Subject: Interleave merge pdf files Message-ID: <1122051911.027433.162650@g14g2000cwa.googlegroups.com> Hi, I need to scan documents with pages having printed matter on both sides. It is easiest to stack them in the autosheet feeder and let it scan. I end up with one file (say A.pdf) containing the odd pages in sequence. Similarly, I can end up with B.pdf containing the even pages. I want to combine them into result.pdf which contains A.1, B.1, A.2, B.2, A.3, B.3, ... (A.1 = page 1 of A.pdf). Does someone know a simple way to achieve this? I noticed the other thread on this newsgroup about merging lots of pdf files and multivalent tools and pdftk were mentioned. However, I could not find a way to do this using them. I am interested in another free tool or a < 25 lines python script (which may use any freeware library) to do the same. Thanks, Chirayu. From flupke at nonexistingdomain.com Wed Jul 20 10:06:57 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 20 Jul 2005 14:06:57 GMT Subject: getting the class name of a subclass Message-ID: <5UsDe.149277$Yz5.7850081@phobos.telenet-ops.be> I have the following test code setup, trying to get the class name of a subclass in the super class. (Reason why i want this is described below) file class_name_start.py ======================== import class_name as cn obj = cn.B() obj.printclass() ======================== file class_name.py ======================== class A(object): def __init__(self): print "I'm A" def printclass(self): print "Name ",__name__ print "Class ",A.__name__ class B(A): def __init__(self): super(B,self).__init__() print "I'm B" ======================== Output: I'm A I'm B Name class_name Class A I would want the last line to be Class B The reason i want this is since i have a number of dialogs all deriving from the same super class. In the superclass i have a save function and i thought it would be easy to get the classname and write the properties in a filename with the classes name as the filename. However it turns out i get the class name of the superclass for all. All the different dialogs are in seperate files. Is there a way to get the name of the subclass. If not i could always pass a param to the init function but in my real life code i already have several params shipped to the init so i wanted to solve it slightly more elegant. Regards, Benedict From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 13:01:49 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 19:01:49 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: <3l1q3tF10l1krU1@individual.net> phil hunt wrote: > def normalizePath(p, *pathParts): > """ Normalize a file path, by expanding the user name and getting > the absolute path.. > @param p [string] = a path to a file or directory > @param pathParts [list of string] = optional path parts > @return [string] = the same path, normalized > """ > p1 = os.path.abspath(os.path.expanduser(p)) > if len(pathParts)>0: > allPathParts = [ p1 ] > allPathParts.extend(pathParts) > p1 = os.path.join(*allPathParts) > p2 = os.path.abspath(p1) > return p2 > normalisePath=normalizePath # alternate spelling > join=normalizePath # it works like os.path.join, but better > > > To be honest I don't see the point of having a Path class. That's > the way Java does it, and I find path handling in Java to be a lot > more of a hassle than in Python. (Actually, most things are more of > a hassle in Java, but that's another story). You see, with the Path class the above function could be written as def normalizePath(p, *pathParts): """ Normalize a file path, by expanding the user name and getting the absolute path.. @param p [Path] = a path to a file or directory @param pathParts [list of string/Path] = optional path parts @return [Path] = the same path, normalized """ tp = p.expanduser().abspath() return tp.joinwith(*pathParts).abspath() That's clearly an improvement, isn't it? Reinhold From tlesher at gmail.com Sun Jul 24 23:13:13 2005 From: tlesher at gmail.com (Tim Lesher) Date: 24 Jul 2005 20:13:13 -0700 Subject: What is your favorite Python web framework? References: Message-ID: <1122261193.071403.41300@g43g2000cwa.googlegroups.com> I was using CherryPy quite a bit until recently, but I've since switched to Spyce: http://spyce.sf.net (and blogged it at http://apipes.blogspot.com/2005/07/first-taste-of-spyce.html). Spyce has been around since 2002 (so it's fairly stable and mature) but it's also under active development--a new version just came out a few weeks ago (so it's not going away). The main reason I switched was the Spyce templating engine--more powerful than CherryTemplate, and tons more readable than Cheetah, in my opinion. -- Tim Lesher tlesher at gmail.com http://apipes.blogspot.com From usenet at zabiello.com Mon Jul 18 07:27:04 2005 From: usenet at zabiello.com (JZ) Date: Mon, 18 Jul 2005 13:27:04 +0200 Subject: What is your favorite Python web framework? References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> Message-ID: <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> Dnia 18 Jul 2005 00:52:40 -0700, laurent napisa?(a): > I follow somes projects that have a pythonic way to make web site. > there's thats projects : > http://www.cherrypy.org/ > and > http://subway.python-hosting.com/ > subway aim to be like ruby on rails frameworks , simple and fast > developpment. It uses cherrypy and other project like : > * http://www.cheetahtemplate.org/ > * http://www.formencode.org/ > * http://www.sqlobject.org/ I think Django is more mature than Subway or CherryPy and can quickly become the black horse in area of pythonic frameworks. -- JZ From gdamjan at gmail.com Mon Jul 18 12:23:47 2005 From: gdamjan at gmail.com (Damjan) Date: Mon, 18 Jul 2005 18:23:47 +0200 Subject: Python scripts wont run - HELP References: Message-ID: <42dbd734_2@x-privat.org> > I'm a fairly literate windoz amateur programmer mostly in visual basic. I > have switched to SuSE 9.2 Pro and am trying to quickly come up to speed > with Python 2.3.4. I can run three or four line scripts from the command > line but have not been able to execute a script from a file. > > I have used EMACS and JEDIT to create small test routines. I would right > click the file and set properties to executable. I would then click the > icon, the bouncy ball would do its thing then a dialog box would flash on > the screen for a fraction of a second. I could tell it had a progress bar > on it but could not catch anything else on it. Then nothing else would > happen. > > If I could execute a script the world would once again be my playground... > PLEASE HELP. Open a terminal program like "konsole". change the directory to where your files are ("cd /path/to/files/"). execute them ("python my-script.py'). -- damjan From bronger at physik.rwth-aachen.de Sun Jul 31 10:32:30 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 16:32:30 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: <87vf2ryrk1.fsf@wilson.rwth-aachen.de> Hall?chen! Terry Hancock writes: > On Saturday 30 July 2005 01:54 am, Torsten Bronger wrote: > >> Calvin Spealman writes: >> >>> The choice is GUI toolkits is largely seperate from >>> Python. Consider that they are just bindings to libraries that >>> are developed completely seperate of the language. GUI is should >>> be seperate from the language, and thus not bound to same >>> expectations and desires as elements of the language itself. >> >> I disagree. A modern language must provide a convenient and >> well-embedded way to write GUI applications. > > I know I'm diving into this conversation late, and I haven't read > the whole thread, but has someone yet mentioned the "anygui" > project? This has stalled, but it was IMHO a good idea. I don't know exactly why this project died, but I'd start with a Pythonic variant of wxPython. I've read many discussions about the people who didn't like the wxPython's C++ style, so there are chances to get fellow developers and users. You must reach the critical mass quickly in order to get a survivable project, and being not too far away from an existing one is a good stating point. Possibly Dabo manages such a thing. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From newsgroups at jhrothjr.com Sat Jul 9 16:48:34 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 9 Jul 2005 14:48:34 -0600 Subject: Should I use "if" or "try" (as a matter of speed)? References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> Message-ID: <11d0e158o1g8554@news.supernews.com> "Thorsten Kampe" wrote in message news:6i1zj31xlx8.yoof0r88btd1.dlg at 40tude.net... >* Steve Juranich (2005-07-09 19:21 +0100) >> I know that this topic has the potential for blowing up in my face, >> but I can't help asking. I've been using Python since 1.5.1, so I'm >> not what you'd call a "n00b". I dutifully evangelize on the goodness >> of Python whenever I talk with fellow developers, but I always hit a >> snag when it comes to discussing the finer points of the execution >> model (specifically, exceptions). >> >> Without fail, when I start talking with some of the "old-timers" >> (people who have written code in ADA or Fortran), I hear the same >> arguments that using "if" is "better" than using "try". I think that >> the argument goes something like, "When you set up a 'try' block, you >> have to set up a lot of extra machinery than is necessary just >> executing a simple conditional." >> >> I was wondering how true this holds for Python, where exceptions are >> such an integral part of the execution model. It seems to me, that if >> I'm executing a loop over a bunch of items, and I expect some >> condition to hold for a majority of the cases, then a "try" block >> would be in order, since I could eliminate a bunch of potentially >> costly comparisons for each item. But in cases where I'm only trying >> a single getattr (for example), using "if" might be a cheaper way to >> go. >> >> What do I mean by "cheaper"? I'm basically talking about the number >> of instructions that are necessary to set up and execute a try block >> as opposed to an if block. > > "Catch errors rather than avoiding them to avoid cluttering your code > with special cases. This idiom is called EAFP ('easier to ask > forgiveness than permission'), as opposed to LBYL ('look before you > leap')." > > http://jaynes.colorado.edu/PythonIdioms.html It depends on what you're doing, and I don't find a "one size fits all" approach to be all that useful. If execution speed is paramount and exceptions are relatively rare, then the try block is the better approach. If you simply want to throw an exception, then the clearest way of writing it that I've ever found is to encapsulate the raise statement together with the condition test in a subroutine with a name that describes what's being tested for. Even a name as poor as "HurlOnFalseCondition(, , , ) can be very enlightening. It gets rid of the in-line if and raise statements, at the cost of an extra method call. John Roth In both approaches, you have some error handling code that is going to clutter up your program flow. From exarkun at divmod.com Thu Jul 21 09:19:59 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 09:19:59 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: Message-ID: <20050721131959.26278.936305607.divmod.quotient.15437@ohm> On Thu, 21 Jul 2005 02:33:05 -0400, Peter Hansen wrote: >Jp Calderone wrote: >> In the particular case of wxWidgets, it turns out that the *GUI* blocks >> for long periods of time, preventing the *network* from getting >> attention. But I agree with your position for other toolkits, such as >> Gtk, Qt, or Tk. > >Are you simply showing that there are two points of view here, that one >can look at the wx main loop as being "blocking", waiting for I/O, even >though it is simply doing asynchronous event-driven processing the same >as Twisted? Or am I missing something? Allowing for the fact that wx >blocks, not just for long periods of time, but *indefinitely* (as long >as no events are arriving) I still don't see how that makes it different >from Twisted or from any other typical GUI framework, which do exactly >the same thing. (And since there is even a wxPython main loop >integrated with and provided in Twisted, surely you aren't arguing that >what wx does is somehow unusual or bad.) Providing wx support in Twisted has been orders of magnitude more difficult than providing Tk, Qt, or Gtk support has been. And wxsupport and wxreactor are each broken in slightly different ways, so I wouldn't say we've been successful, either. Blocking inside the mainloop while waiting for events is fine. It's blocking elsewhere that is problematic. Jp From dieter at handshake.de Thu Jul 7 14:25:05 2005 From: dieter at handshake.de (Dieter Maurer) Date: 07 Jul 2005 20:25:05 +0200 Subject: Conditionally implementing __iter__ in new style classes References: Message-ID: Thomas Heller writes on Wed, 06 Jul 2005 18:07:10 +0200: > Thomas Heller writes: > ... > > class Base: > > def __getattr__(self, name): > > if name == "__iter__" and hasattr(self, "Iterator"): > > return self.Iterator > > raise AttributeError, name > > > > class Concrete(Base): > > def Iterator(self): > > yield 1 > ... > > If, however, I make Base a newstyle class, this will not work any > > longer. __getattr__ is never called for "__iter__" (neither is > > __getattribute__, btw). Probably this has to do with data descriptors > > and non-data descriptors, but I'm too tired at the moment to think > > further about this. > > > > Is there any way I could make the above code work with new style > > classes? > > I forgot to mention this: The Base class also implements a __getitem__ > method which should be used for iteration if the .Iterator method in the > subclass is not available. So it seems impossible to raise an exception > in the __iter__ method if .Iterator is not found - __iter__ MUST return > an iterator if present. Then, it should return an interator (a new object) that uses the "__getitem__" method to iterate. Dieter From tchurm at gmail.com Tue Jul 12 11:50:56 2005 From: tchurm at gmail.com (tchurm at gmail.com) Date: 12 Jul 2005 08:50:56 -0700 Subject: Search & Replace with RegEx References: <1121155904.551248.102700@o13g2000cwo.googlegroups.com> Message-ID: <1121183456.800581.92340@g44g2000cwa.googlegroups.com> thanks for the comments + help. i think i got it working, although it's not pretty: ############################## import os import re theRegEx = '.*abs:.*\.*.\\\\' p = re.compile(theRegEx, re.IGNORECASE) fileToSearch = 'compreg.dat' print "File to perform search-and-replace on: " + fileToSearch print "Using Regex: " + theRegEx print "" #set this to an empty string newdoc = "" if os.path.isfile( fileToSearch ): x = open(fileToSearch, "r") while 1: line = x.readline() if(p.match(line)!=None): print "" print line newdoc = newdoc + re.sub("abs:.*\.*.\\\\", "rel:", line) else: newdoc = newdoc + line if line == "": print "" print "finished !" break x.close() if newdoc != '': x = open(fileToSearch, "w") x.write(newdoc) x.close() print "" print "file written!" raw_input( '\n\nPress Enter to exit...' ) ############################## From st10 at humboldt.edu Wed Jul 20 21:06:00 2005 From: st10 at humboldt.edu (S. M. Tuttle) Date: 20 Jul 2005 18:06:00 -0700 Subject: interactive python session spool/save-log command? Message-ID: <1121907960.539100.146940@z14g2000cwz.googlegroups.com> I'm going to be teaching an introductory course on Python in the Fall, so I am hurriedly trying to both learn Python and prepare the course during the next few weeks. I'm curious if there is a command that allows everything from that point on in a python interactive session to be saved/spooled/forked/logged into a text file of the user's choice. (Like spool lets you do in Oracle splplus; like the protocol predicate lets you do in some version of Prolog; how you can save the Interactions window contents in DrScheme; etc.) I'd like to have students turn in such logs at various times, (to show that they've tried certain tests of their python code, etc.) if it is practical... Thanks for any pointers or assistance in this. My searches using google, google groups, and the search engine at www.python.org haven't been effective so far, either because this command does not exist or because (I hope!!) the search terms I've used just haven't been quite right. -- Sharon Tuttle Arcata, CA From atwardoch at op.pl Wed Jul 6 05:36:31 2005 From: atwardoch at op.pl (Adam Twardoch) Date: Wed, 6 Jul 2005 11:36:31 +0200 Subject: Using Ghostscript DLL via ctypes in Py2.3/Win Message-ID: I've written a simple commanline wrapper for calling GhostScript from Python. It uses os.system under Windows and os.popen under unixes. The call looks basically like this: gs -q -dNODISPLAY -dNOPAUSE -dSAFER ps2ai.ps infile.eps >outfile.ai I'd prefer to use the GhostScript DLL API* and call it using ctypes under Windows. This way, I could package just the DLL with my application and the user would not necessarily need to install the full GhostScript. However, I don't really know how to handle ctypes very well. Has anyone perhaps written something like that already and cares to share a code snippet? Regards, Adam *) http://www.cs.wisc.edu/~ghost/doc/cvs/API.htm From opengeometry at yahoo.ca Thu Jul 14 16:31:55 2005 From: opengeometry at yahoo.ca (William Park) Date: Thu, 14 Jul 2005 16:31:55 -0400 Subject: Tkinter Button widget References: Message-ID: <408dc$42d6cbbb$d8fea75d$17608@PRIMUS.CA> Peter Otten <__peter__ at web.de> wrote: > Shankar Iyer (siyer at Princeton.EDU) wrote: > > > I have another Tkinter-related question. At the beginning of my > > program, a tkinter window is created with six buttons. Each of these > > buttons is assigned a function that should be executed only when the > > button is pressed. However, it seems that these functions are all > > executed once when the button widgets are first created. Why is this > > the case and how do I prevent this from happening? > > Change your source code from > > # wrong > button = Tkinter.Button(..., command=some_function(),...) > > to > > # correct > button = Tkinter.Button(..., command=some_function,...) > > to pass the *function* to the widget instead of the *result* of a > function call. And, next time, remember to post some code alongside > with your question. Hmm, maybe I should learn Tk + Python. Telepathetic powers of Python programmers are amazing. -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From simonwittber at gmail.com Tue Jul 12 04:03:42 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 12 Jul 2005 01:03:42 -0700 Subject: automatically assigning names to indexes In-Reply-To: References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> Message-ID: <1121155422.715401.207670@z14g2000cwz.googlegroups.com> > >>> class Vector(tuple): > ... x = property(lambda self: self[0]) > ... y = property(lambda self: self[1]) > ... z = property(lambda self: self[2]) > ... > >>> Vector("abc") > ('a', 'b', 'c') > >>> Vector("abc").z > 'c' > >>> Vector("abc")[2] > 'c' > Aha! You have simultaneously proposed a neat solution, and shown me a bug in my class! (It shouldn't accept strings) Thanks. Sw. From elmo13 at jippii.fi Wed Jul 13 17:40:04 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Thu, 14 Jul 2005 00:40:04 +0300 Subject: Searching for metadata related tools for use with python References: Message-ID: On Wed, 13 Jul 2005 23:25:46 +0300, Elmo M?ntynen wrote: > On Wed, 13 Jul 2005 23:22:01 +0300, Elmo M?ntynen wrote: > >> On Wed, 13 Jul 2005 15:49:27 +0300, Elmo M?ntynen wrote: >> >>> -----BEGIN PGP SIGNED MESSAGE----- >>> Hash: SHA1 >>> >>> I'm interested in various metadata >>> extraction/prosessing/distribution/something tools(including ways of >>> differentiating between files, eg hashing etc) and especially python >>> enabled ones. I'm also considering content-recognition/differentiating >>> eg. image recognition. I'm already aware of these: python-bitzi, >>> python-musicbrainz, mmpython, IMDbPY, python-mhash and imgSeek. If you >>> could point me to other relating resources it would be great. >>> >>> Elmo >>> -----BEGIN PGP SIGNATURE----- >>> Version: GnuPG v1.4.1 (GNU/Linux) >>> Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org >>> >>> iD8DBQFC1Q3WctNFyQJObrsRAjXbAJ92B53YC9NqtC9nymK07OL+L3mNTwCgmlbb >>> dPfSDsqJzBh+xa3h5L28Qac= >>> =AtAo >>> -----END PGP SIGNATURE----- >> >> I would also like comments if you're pretty sure the aren't any other >> related resources. Anything related to organizing one's >> filecollections(be it music, photos, books etc.), though i'm not >> particularly interested in another mp3/ogg-tagger(report it still >> though, if you will), would be interesting also. >> >> Elmo > > I'm going for completeness(though a never-ending chase you might say). > > Elmo RDF(or xml otherwise) enabled metadata repositories/etc. are of interest to me also(musicbrainz and bitzi are recognized already). If just someone said something instead of this thread being completely ignored. If this isn't the place to discuss something like this would someone point me to a better one. Elmo From rwgk at yahoo.com Wed Jul 6 22:18:03 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Wed, 6 Jul 2005 19:18:03 -0700 (PDT) Subject: Compatibility of recent GCC/Python versions In-Reply-To: Message-ID: <20050707021803.53373.qmail@web31515.mail.mud.yahoo.com> --- David Abrahams wrote: > Recently people testing Boost.Python with GCC on Linux have reported > that the extensions being tested have to be compiled with exactly the > same version of GCC as the Python they're being loaded into, or they > get mysterious crashes. > > That doesn't correspond to my past experience; it has always been true > that, as long as the compiler used to build Python and the one used to > build the extension have compatible 'C' ABIs, we've been okay. Yes, > if you were going to pass types like FILE* across the Python/C API, > then you additionally need to be sure that the two compilers are using > the same 'C' library. That said, none of the Boost.Python tests do > that. > > I'm wondering if there has been a well-known recent change either in Python > or GCC that would account for these new reports. Any relevant > information would be appreciated. Maybe the problems are due to libstdc++ incompatibilities? See my other message: http://lists.boost.org/boost/2005/07/29883.php Cheers, Ralf __________________________________ Yahoo! Mail Stay connected, organized, and protected. Take the tour: http://tour.mail.yahoo.com/mailtour.html From dsiroky at email.cz Mon Jul 11 09:06:43 2005 From: dsiroky at email.cz (David Siroky) Date: Mon, 11 Jul 2005 15:06:43 +0200 Subject: pyo contains absolute paths References: Message-ID: V Sat, 09 Jul 2005 10:22:06 -0400, Peter Hansen napsal(a): > David Siroky wrote: >> When I "compile" my python files with "python -OO ...." into pyo files >> then they still contain absolute paths of the source files which is >> undesirable for me. How can I deal with that? > > Don't do that? > > Delete the pyo files? > > Stop using Python? > > I could guess at a few more possibilities, but since you don't actually > say what you *want* to happen, just what you don't want to happen, there > are an infinite number of ways to satisfy you right now. > > (Hint #1: absolute paths are always, AFAIK, put into the .pyc or .pyo > files.) > > (Hint #2: maybe explaining why you don't want this to happen would help > too, since that will probably determine the "best" solution.) > > -Peter I want to write a commercial application in Python and I don't want the customer to see the source code and absolute paths of my modules which have btw. the same base path as the main module so I would expect only relative paths in the compiled files. David From tzot at sil-tec.gr Sat Jul 2 09:26:10 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 16:26:10 +0300 Subject: Python choice of database References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: On Mon, 20 Jun 2005 23:42:21 -0800, rumours say that "EP" might have written: >I tried this for one application under the Windows OS and it worked fine... > >until my records (text - maybe 50KB average) unexpectedly blossomed into the 10,000-1,000,000 ranges. If I or someone else (who innocently doesn't know better) opens up one of the directories with ~150,000 files in it, the machine's personality gets a little ugly (it seems buggy but is just very busy; no crashing). Under 10,000 files per directory seems to work just fine, though. Although I am not a pro-Windows person, I have to say here directories containing more than 10000 files is not a problem for NTFS (at least NTFS of Win2000 and WinXP based on my experience) since AFAIK directories are stored in B-tree format; the problem is if one tries to *view* the directory contents using Explorer. Command-line dir had no problem on a directory with >15000 files. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From googlemike at hotpop.com Wed Jul 13 23:38:17 2005 From: googlemike at hotpop.com (googlemike at hotpop.com) Date: 13 Jul 2005 20:38:17 -0700 Subject: Need To Transfer Project Ownership -- gvpnc Message-ID: <1121312297.242098.153950@g43g2000cwa.googlegroups.com> I have designed a project, gvpnc, that I think would be useful to the folks out there who use GNOME and want a GNOME app to VPN into their office with. It is simple, yes, but it works well (at least on my Ubuntu 5.04). It is a front-end to the vpnc tool for Linux. There is kvpnc, so I thought I would call it gvpnc. I really am too tied up with day job and large moonlight projects right now to post this on SourceForge, improve it, and so on. If you would like to take my weekend's worth of work and put it up on SourceForge and "own" it, I would greatly appreciate it. I designed the interface in Glade-2, saved as XML, then use a single, short, easy-to-read Python file to load this interface, display the GUI, and handle events. I thank the folks at RedHat with their control applets for leaving me enough breadcrumbs to figure out how to make this stuff. Please reply back to this forum with why you would be interested, show me your SourceForge track record, and a way to reach you. If you qualify and get this to me in time, you may be the proud recipient of the gvpnc source that I can sign over to you to own, manage, and grow. As for me, I'm happy with my copy -- it suits me well. The project is released on the GNU Artistic License, so you could list my copyright and then follow it with yours. I have no other requirements. Future improvements could be: * There's a way to make a self-executing compressed install on Linux. This might be suitable. Also, a DEB or RPM would be helpful. * Error checking for different distro's, telling people what they are missing before installation. * If there's a way to wrap all the images, python script, and Glade-2 interface into a single file that decompresses into a RAM partition, that would make a slick way to produce a smaller footprint for this application. * Support for multiple profiles, rather than just remembering the last one. * Ability to switch from TCP to UDP and/or pick the socket port. * Minimizes into a GNOME notification icon. * Warns you when 25 (or x) minutes of idle time have come up. * Integration with "festival" speech or sound events. Cheers. From edvard+news at majakari.net Wed Jul 13 04:09:57 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 13 Jul 2005 11:09:57 +0300 Subject: Reading network interface data in linux Message-ID: <873bqjf7oq.fsf@titan.staselog.com> Suppose one wants to fetch the following data from given network interface, say, eth0: >>> Ethinf('eth0').addr() '192.168.1.42/24' >>> Ethinf('eth0').route('default') '192.168.1.1' >>> Ethinf('eth0').duplex() 'full' >>> Ethinf('eth0').speed() 100 Some statistics: >>> Ethstat('eth0').rx_bytes() 14325235341223 >>> Ethstat('eth0').tx_bytes() 2513152423 One could implement modules by installing eg. ethtool and reading speed/duplex information by parsing ethtool output, but it is ugly way to do it, prone to errors, requires launching a process as well as installation of ethtool. As for the byte counts, you could get all information ifconfig show by reading /proc/net/dev (which is more nice to parse), but it seems like those counters are 32-bit, and they wrap around quite quickly in a 1000 gbit network (~30 seconds). I was wondering is there really no module implemented which already does those things? I've already implemented a proto by doing exactly as I told (parsing ethtool & /proc/net/dev), but I strive for more elegant solution. I'm willing to join the effort with someone else, if possible. -- #!/usr/bin/perl -w $h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14, 72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26, 69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b} keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'', map{lc}($1,substr $2,4,1)),2,4)."\n"; print; From caseyhHAMMER_TIME at istar.ca Mon Jul 4 23:40:55 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Tue, 05 Jul 2005 03:40:55 GMT Subject: What are __slots__ used for? References: Message-ID: <200kc1lfbtj09j0rpg1k0fmc508dc9sbda@4ax.com> To save a a few bytes (10?) per instance instead of having a dict to hold attributes one has slots! Designed for having lots of instances (millions?) at the same time to save space! "Ric Da Force" wrote: >I am a C# programmer and new to the language and I am trying to debug some >code which uses this feature. Can anyone elaborate on what it is and how it >is used? > >Regards, > >Ric > -- Regards, Casey From gsakkis at rutgers.edu Fri Jul 1 01:45:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 22:45:08 -0700 Subject: Splitting string into dictionary References: Message-ID: <1120196708.096544.135110@g44g2000cwa.googlegroups.com> "David Pratt" wrote: > Wow Robert that is incredible python magic! I am trying to figure out > what this is doing since my attempts were regex and some long string > splitting and collection. > > Ok. So it is a list comprehension and then collection. What is zip > doing in the second line? > > Regards > David Why don't you fire up the python interpreter and type >>> help(zip) >>> zip([1,2,3],"abc") Teaching-a-man-to-fish-instead-of-giving-him-a-fish'ly yrs, George From peter at engcorp.com Mon Jul 11 23:34:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Jul 2005 23:34:10 -0400 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: <3jftckFpvhv2U2@individual.net> Message-ID: Ric Da Force wrote: > How does setdefault work exactly? I am looking in the docs and can't figure > it out... If the key (the first argument) already exists in the dictionary, the corresponding value is returned. If the key does not exist in the dictionary, it is stored in the dictionary and bound to the second argument, and then that second argument is returned as the value. (I always have to ignore the name to think about how it works, or it gets in the way of my understanding it. The name makes fairly little sense to me.) -Peter From cliff at develix.com Sun Jul 31 02:27:04 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 23:27:04 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <86wtn7h8pl.fsf@bhuda.mired.org> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: <1122791224.19618.52.camel@localhost.localdomain> On Sun, 2005-07-31 at 00:59 -0400, Mike Meyer wrote: > I don't particularly like Tkinter, but it seems to me that it's pretty > much won. It seems to be installed on every desktop platform along > with Python. That means that if I want to distribute GUI apps, I'm > going to cause the least headache for my end users by writing them in > Tkinter. By this argument, we should just give up and use Visual* on Windows. The least headache for end users comes from properly packaging your application. End users shouldn't need to worry about installing third party packages (or even Python for that matter). Tools such as py2exe and Inno installer make this pretty simple on Windows, and py2app on OS/X accomplishes the same. It should be irrelevant to end users what libraries or tools you use to develop the app. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From t-meyer at ihug.co.nz Sun Jul 31 21:11:22 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 1 Aug 2005 13:11:22 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > Is classic Macintosh OS still supported on Python? No. At least, AFAIK, there is no intent to produce packages of new Python versions for Mac pre OS X. Old versions of Python still work, of course, but whatever version of Path makes it into Python (if any) is extremely unlikely to be supported on pre OS X Mac. I agree with all that you said, however :) =Tony.Meyer From me at privacy.net Wed Jul 20 08:30:32 2005 From: me at privacy.net (Admin) Date: Wed, 20 Jul 2005 09:30:32 -0300 Subject: How to send a query to the browser from time to time? References: <1121778228.962141.70680@f14g2000cwb.googlegroups.com> <1121813005.393406.302980@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 19 Jul 2005 19:43:25 -0300, sp1d3rx at gmail.com wrote: > otherwise, my only suggestion is to use another protocol instead of > http. What do you suggest? -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From steve at REMOVETHIScyber.com.au Tue Jul 12 22:31:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 12:31:04 +1000 Subject: Help with inverted dictionary References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> <1121182343.731328.38020@g47g2000cwa.googlegroups.com> <1121182712.452410.64240@g49g2000cwa.googlegroups.com> <42d470a4$1@news.eftel.com> Message-ID: On Wed, 13 Jul 2005 11:38:44 +1000, John Machin wrote: > rorley at gmail.com wrote: >> I will transfer eventually use a database but is there any way for now >> you could help me make the text files? Thank you so much. Reece >> > > No. There is utterly no reason why you should create 5000 or 30000 text > files. There is one possible reason: if it is a homework assignment, and creating all those files is part of the assignment. (I've seen stupider ideas, but not by much.) -- Steven. From frodo at fortress.site Thu Jul 14 15:59:54 2005 From: frodo at fortress.site (Unknown) Date: Thu, 14 Jul 2005 19:59:54 GMT Subject: Python and MySQL server Message-ID: Python 2.4 Linux kernel 2.6.12 Hi, 1. How do I make the following statement to search for all Strings I input from console? for example, with the code below I need to enter %hello world% (yeah, including the % symbols) to find all entries for hello world on the tableName. But I want to set the % symbols on the code itself so I don't have to input manually the % at the prompt. searchWhat = raw_input ('Search for : ') cursor.execute('select * from tableName where contentField like %s',(searchWhat)) 2. I'm entering data by copying and pasting. Much of the text is in multiple lines and some formated sections such as paragraphs, indentations, double lines and what not. How do I enter keep the formated text intact if entering from console? Now it loses all formatting and I have to copy and paste text line by line because it won't take the multiple lines. insertEntryId = raw_input('New Entry ID: ') insertEntryContent = raw_input('New Entry Content: ') insertEntryCategory = raw_input('New Category: ') cursor.execute('insert into tableName values (%s,%s,%s)', (insertEntryId,insertEntryContent,insertEntryCategory)) Thanks, Any help is appreciate it. Mr. Frodo From guettli at thomas-guettler.de Mon Jul 11 09:52:52 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 11 Jul 2005 15:52:52 +0200 Subject: httplib/HTTPS Post Problem References: <1121088563.465929.31290@g43g2000cwa.googlegroups.com> Message-ID: Am Mon, 11 Jul 2005 06:29:23 -0700 schrieb michaelparkin: > Hi, > > Sorry to post what might seem like a trivial problem here, but its > driving me mad! > > I have a simple https client that uses httplib to post data to a web > server. > > When I post over http & https using curl the data is recieved by the > web server with no problems. > > When I post using my python client the headers get there, but the body > of the message does not. Hi, can you look at the access log of the server? A slash at the end of a URL is important (www.google.com/ is different from www.google.com) response = connection.getresponse() What does "print response" do? You can listen on the wire with ethereal (Capture, then "follow tcp-stream") HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From pinard at iro.umontreal.ca Fri Jul 1 15:00:32 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 1 Jul 2005 15:00:32 -0400 Subject: Assigning to None In-Reply-To: References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <86ekai5sk7.fsf@bhuda.mired.org> Message-ID: <20050701190032.GA14226@phenix.progiciels-bpi.ca> [Roy Smith] > 4) foo, bar = gen_tuple(stuff)[0:1]. In some ways, this is the > cleanest because it doesn't pollute the namespace with an un-needed > variable, but I think it's the least readable. Less legible often means more error prone. For example, here, foo, bar = gen_tuple(stuff)[:2] would work better. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From ptmcg at austin.rr.com Sun Jul 24 20:27:07 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jul 2005 17:27:07 -0700 Subject: pyparsing 1.3.2 released Message-ID: "The best laid plans o' mice an' men / Gang aft a-gley" So said Robert Burns (who really should do something about that speech impediment!). And so said I about 6 weeks ago, when I thought that I would leave pyparsing alone for awhile, after the 1.3.1 release. Well, here we are, and I'm announcing the 1.3.2 release, with some changes that I'd like to get released quickly. Here is the excerpt from the change log: Version 1.3.2 - July 24, 2005 ----------------------------- - Added Each class as an enhanced version of And. 'Each' requires that all given expressions be present, but may occur in any order. Special handling is provided to group ZeroOrMore and OneOrMore elements that occur out-of-order in the input string. You can also construct 'Each' objects by joining expressions with the '&' operator. When using the Each class, results names are strongly recommended for accessing the matched tokens. (Suggested by Pradam Amini - thanks, Pradam!) - Stricter interpretation of 'max' qualifier on Word elements. If the 'max' attribute is specified, matching will fail if an input field contains more than 'max' consecutive body characters. For example, previously, Word(nums,max=3) would match the first three characters of '0123456', returning '012' and continuing parsing at '3'. Now, when constructed using the max attribute, Word will raise an exception with this string. - Cleaner handling of nested dictionaries returned by Dict. No longer necessary to dereference sub-dictionaries as element [0] of their parents. === NOTE: THIS CHANGE MAY BREAK SOME EXISTING CODE, BUT ONLY IF PARSING NESTED DICTIONARIES USING THE LITTLE-USED DICT CLASS === (Prompted by discussion thread on the Python Tutor list, with contributions from Danny Yoo, Kent Johnson, and original post by Liam Clarke - thanks all!) Download pyparsing at http://pyparsing.sourceforge.net. -- Paul ======================================== Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - "Hello, World!" - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler From giles_brown at hotmail.com Thu Jul 7 10:50:17 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 7 Jul 2005 07:50:17 -0700 Subject: Windows Cmd.exe Window In-Reply-To: References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: <1120747817.247502.106680@g14g2000cwa.googlegroups.com> Hooray! We have a winner! Thanks Duncan. Your improved shell line will do the job very nicely. :) (btw, the problem with "import sethook" at the top of the script is that syntax errors in the top-level will prevent the import from being run meaning we don't get our traceback anymore.) Giles From http Sun Jul 31 03:12:32 2005 From: http (Paul Rubin) Date: 31 Jul 2005 00:12:32 -0700 Subject: shelve: writing out updates?! References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xbr4je9en.fsf@ruckus.brouhaha.com> zen19725 at zen.co.uk (phil hunt) writes: > >No. Call the .sync() method. Unfortunately, the shelve module is not > >well-documented. > > Obviously it's good when stuff is well documented. > > I wonder if the barrier to good documentation is set too high? > If i wanted to add some documentation here, ... I entered a sourceforge bug asking that the doc be updated (thanks, Robert!). I've done that several times before for similar small doc bugs and they've always been taken care of reasonably quickly. There's a "documentation" category in the bug reporting template for this purpose. From michielsen at onecert.fr Fri Jul 8 09:16:21 2005 From: michielsen at onecert.fr (Bas Michielsen) Date: Fri, 08 Jul 2005 15:16:21 +0200 Subject: Obj.'s writing self-regeneration script ? Message-ID: <42CE7CA5.2090500@onecert.fr> Hello, Is there a good/standard way of having (composite) objects write a Python script which will regenerate the very same object ? This problem arises when I construct, for example, a "ComputationalProblem" object, possibly through an object editor GUI, importing data structures from external geometric and material modelers etc. Once the object has been constructed, one wants to write it to a file on disk, for example to do the computations later on. In order to help users, familiar with the (in)famous "input-file monolithic-code output-file" sequence I would like to have this diskfile take the form of recognisable and editable Python code (instead of a "dump" solution with Pickle for example). I think there are problems with uniqueness and ordering of the component instantiations. I was thinking of something like a depth-first recursive write-script() on the object's attributes using the __class__ 's to construct generic names for the instantiations. Has anyone given this a thought already ? Thank you in advance for any remarks, -- Bas Michielsen ONERA, Electromagnetics and Radar Department 2, avenue Edouard Belin, 31055 TOULOUSE cedex, France Tel. (++33)(0)5 62 25 26 77 Fax. (++33)(0)5 62 25 25 77 From Neruocomp at yahoo.com Thu Jul 28 13:27:59 2005 From: Neruocomp at yahoo.com (David) Date: 28 Jul 2005 10:27:59 -0700 Subject: Cgi scripts in apache not working Message-ID: <1122571679.788076.37080@g43g2000cwa.googlegroups.com> I've looked all over the place for an answer, and the only one I can find doesn't mean anything to me. The end of line issue with writting it in Windows and then uploading it doesn't help me since I'm doing this all from Linux. I've been trying to get python cgi scripts to work, and I always end up with a "Premature end of script headers" in the error log. The scripts are executable by all and my httpd.conf seems fine. I also tested it out in /var/www/cgi-bin/ and there it seems to work fine. test2.py: #!/usr/bin/python print "Content-type: text/html\n\n" print """

Hello World

""" httpd.conf: << Tried it with "" and no "" Options ExecCGI << Tried with "Options +ExecCGI" AddHandler cgi-script .cgi .py << Tried with "SetHandler cgi-script", but still no go error_log: [Thu Jul 28 11:44:53 2005] [error] [client xxx.xxx.xxx.xxx] Premature end of script headers: test2.py suexec.log: [2005-07-28 11:44:53]: uid: (500/davidnoriega) gid: (500/500) cmd: test2.py [2005-07-28 11:44:53]: directory is writable by others: (/home/davidnoriega/public_html/cgi) From pink at odahoda.de Thu Jul 21 14:08:59 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Thu, 21 Jul 2005 20:08:59 +0200 Subject: Difference between " and ' References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: b83503104 at yahoo.com wrote: > Hi, > > Can someone tell me the difference between single quote and double > quote? There is none. Except that in a double quoted string, single quotes don't have to be escaped and vice versa, sometimes one of the two forms saves you some backslashes: "That's my house" == 'That\'s my house' "You say: \"Hello\"" == 'You say: "Hello"' -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From rtomek at ceti.pl Sun Jul 24 16:36:44 2005 From: rtomek at ceti.pl (Tomasz Rola) Date: Sun, 24 Jul 2005 22:36:44 +0200 (CEST) Subject: Initializing interactive Python In-Reply-To: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 24 Jul 2005 qwweeeit at yahoo.it wrote: > Hi all, > is it possible to enter an interactive session and automatically > do some initialization? > I explain better: > I want that when I start interactive Python on a console (I use Linux) > two command lines be executed automatically: I did this by using python's "-i" option. Under Unix/Linux environment, you can set up a script like this: - ------------ cut - cut - cut ----------- #!/usr/bin/python -i # init interactive session import someutils someutils.init() import sys from blah.blaaah.blah import * print "Hello there" # Now it's ready and shows you a prompt, so you can abuse it freely ;) - ----------- paste - paste - paste --------- It should be possible to write similar script under any other sufficiently developed OS. After executing a script, you are presented a prompt from properly (i.e. the way you want it) initialised interpreter. Regards, Tomasz Rola - -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** -----BEGIN PGP SIGNATURE----- Version: PGPfreeware 5.0i for non-commercial use Charset: noconv iQA/AwUBQuP75RETUsyL9vbiEQKtWgCgpIJS9nWo9tEf01QZACnoyCN5oSgAmgO0 a5+6CQiqEeT+58p/WZgjmlmw =NVnJ -----END PGP SIGNATURE----- From tjreedy at udel.edu Sun Jul 3 16:03:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 3 Jul 2005 16:03:59 -0400 Subject: A Policy for Inclusion in the Standard Library: was Modules forinclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: "Colin J. Williams" wrote in message news:IvUxe.1417$Ud.58683 at news20.bellglobal.com... > Terry Reedy wrote: >> >> A couple of times, Guido has given his general policy as generally >> useful; >> best-of-breed, tested and accepted by the community; and backed by a >> developer who will adapt it and its doc up to stdlib standards (if >> necessary) and commit to maintainence for a few years. >> > This is a good base. Presumably "accepted by the community" means > with some minimum number of ongoing users. Yes. Users also indicate practical (versus theoretical) usefullness and also test beyond what a developer might (especially documentation). Of course, modules written by the inner core group of active developers or on their behalf may bypass these criteria, but the context of my answer was discussion of inclusion of existing modules mostly or all written by other people. Part of the maintainence requirement is a willingness to work compatibly with the Python release cycle. Related to that is something I left out on the other side: willingness to license the module to the PSF for inclusion. Some people seem to assume that everyone 'of course' wants their stuff included and that it is just Guido blocking inclusion, but that just is not so. Terry J. Reedy From python at rcn.com Sun Jul 17 22:18:23 2005 From: python at rcn.com (Raymond Hettinger) Date: 17 Jul 2005 19:18:23 -0700 Subject: Efficiently Split A List of Tuples References: Message-ID: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> > Variant of Paul's example: > > a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) > zip(*a) > > or > > [list(t) for t in zip(*a)] if you need lists instead of tuples. [Peter Hansen] > (I believe this is something Guido considers an "abuse of *args", but I > just consider it an elegant use of zip() considering how the language > defines *args. YMMV] It is somewhat elegant in terms of expressiveness; however, it is also a bit disconcerting in light of the underlying implementation. All of the tuples are loaded one-by-one onto the argument stack. For a few elements, this is no big deal. For large datasets, it is a less than ideal way of transposing data. Guido's reaction makes sense when you consider that most programmers would cringe at a function definition with thousands of parameters. There is a sense that this doesn't scale-up very well (with each Python implementation having its own limits on how far you can push this idiom). Raymond From steve at REMOVEMEcyber.com.au Sun Jul 3 23:47:29 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 13:47:29 +1000 Subject: math.nroot [was Re: A brief question.] References: Message-ID: <42C8B151.2010503@REMOVEMEcyber.com.au> Tom Anderson wrote about NaNs: > > (Remember, a NaN is just an illusionary placeholder, not a number.) > > If you think it's illusionary, i invite you to inspect the contents of > my variables - i have a real, live NaN trapped in one of them! No you don't. You have a flag that says "This calculation failed" in your variable. [snip] > Yes. It may not be mathematically pure (although i argue that it is, in > fact, as long as you don't think of floats as being real numbers), it is > practical, and practicality beats purity. But then: >> But, apart from testing whether a float is a NaN, why would you ever >> want to do an equality test? > > > By definition, never. Isn't that usage reason enough? So, what you are saying is that you don't actually have a usage case for testing equality for NaNs. Any floating point package that supports the IEEE standard should give you a test to see if a float represents a NaN. That's what you need. You certainly can't rely on "x == SOME_NAN" because there are 254 different NaNs. There is no sensible reason to test equality of NaNs. It is logically nonsense to say that one NaN is equal to another, as such a thing implies contradictions like -1==-2. If you support IEEE, you will have a test for NaNs, so you can detect them when you need to. Problem solved. > >> The only usage case I can think of is would be something like this: >> >> def isNaN(x): >> return x == SOME_KNOWN_NAN >> >> But that won't work, because there are lots of different NaNs. 254 of >> them, or twice that if you include signed NaNs (which you shouldn't, >> but you do have to allow for them in equality testing). > > > Ah, well. There we have the question of whether python should implement > full-blown IEEE arithmetic. This is somewhat heretical, but i think it > shouldn't; i think it would be much better to adopt Java's noddy-IEEE > approach, where there's exactly one NaN (although with well-behaved > equality comparison). I realise this isn't going to happen, though. Well-behaved equality comparison means that nan == nan returns false. Otherwise you have contradictions like this: x = log(-1) # one flavour of NaN y = asin(2) # a different flavour of NaN log(-1) == asin(2) sin(log(-1)) == 2 sin(NaN) == 2 NaN == 2 Contradiction. [snip] > I am utterly baffled. Three people so far have told me that > exponentiation has higher precedence than unary minus *in conventional > notation*. Yes. > Are you really telling me that you think this expression: > > 2 > -1 > > Evaluates to -1? Of course it does. That's why mathematicians use (-1)^n for series where the sign of each term alternates, instead of -1^n which would just give -1, -1, -1, ... -- Steven From onurb at xiludom.gro Mon Jul 4 05:55:18 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 04 Jul 2005 11:55:18 +0200 Subject: How to compare files In-Reply-To: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> References: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> Message-ID: <42c9078a$0$2455$626a14ce@news.free.fr> Lad wrote: > Hi, > What is the best method for comparing two files by words? try the difflib module: http://www.python.org/doc/2.4.1/lib/module-difflib.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From GoogleGroups at garringer.net Tue Jul 19 10:47:35 2005 From: GoogleGroups at garringer.net (RTG) Date: 19 Jul 2005 07:47:35 -0700 Subject: How do I send keystrokes to a console window in Windows XP? In-Reply-To: References: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> <1121713006.253298.302050@g49g2000cwa.googlegroups.com> Message-ID: <1121784455.136313.301610@g47g2000cwa.googlegroups.com> Benji, This appears to be exactly what we need. I also see that by changing "Command Prompt" to "Notepad" or another application, the key strokes are sent there. With this capability, other possibilities open up. Is there a way to read the output from the from the console window? For example, how can we capture the output of the dir command? Thank you for your help. From sjmachin at lexicon.net Sat Jul 23 09:26:19 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 23:26:19 +1000 Subject: tuple to string? In-Reply-To: References: <42E0EED4.4020001@gmx.net> Message-ID: <42e2457a@news.eftel.com> Steven D'Aprano wrote: > > >>>>''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D))) > > 'spam' Why the verbal diarrhoea? What's wrong with the (already posted) ''.join(map(chr, (0x73, 0x70, 0x61, 0x6D))) ??? From case.nelson at gmail.com Wed Jul 27 14:42:24 2005 From: case.nelson at gmail.com (snoe) Date: 27 Jul 2005 11:42:24 -0700 Subject: Wrapping a class set method Message-ID: <1122489744.784822.187690@f14g2000cwb.googlegroups.com> Hi there, I have the following simplified classes: class Project: def __init__(self,pname): self.devices = {} # Dictionary of Device objects self.pname = pname def setpname(self,pname): self.pname = pname def adddevice(self,dname): self.devices[dname] = Device(self,dname) class Device: def __init__(self,parent,dname): self.parent = parent self.dname = dname def setdname(self,dname): self.dname = dname Now, what I would like to do is wrap all of the set/add methods in a function that pickles the Project object. I would then save the pickled objects and use them to undo any changes to the above data structures. I have a suspicion that there's an easier way to do this than explicitly adding a Project.pickleme() call to the beginning of all of my set/add methods. So is there a way to wrap methods for this type of functionality or is there another way of doing this, maybe without using setter methods? From sjmachin at lexicon.net Fri Jul 1 20:43:01 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 02 Jul 2005 10:43:01 +1000 Subject: Running Python interpreter in Emacs In-Reply-To: <1120250066.836533.199420@g47g2000cwa.googlegroups.com> References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> <1119811726.576282.59500@g49g2000cwa.googlegroups.com> <1120250066.836533.199420@g47g2000cwa.googlegroups.com> Message-ID: <42C5E315.1050100@lexicon.net> Rex Eastbourne wrote: > Yes! Thank you so much! (For some reason, by the way, I had to copy > python.exe to my c:/ directory, No, you did _not_ need to copy it there. You did _not_ need to copy it anywhere. Didn't copying an executable to your root directory [on any operating system] strike you as being one or more of unusual/strange/weird/dopey? > since the computer could never find the > path in program files/python24. Probably because you didn't have quotes around it (needed because of the space) as advised by another poster. But when I did that, and used > setq-py-python-command, it worked. I now have python.exe in two > locations.) > The Windows Python installer will by default install Python 2.x in C:\Python2x One hopes that defaults are sensibly chosen by sensible people. This appears to have been the case here. How did you manage to get your Python installed in C:\Program Files\Python24? From tjreedy at udel.edu Mon Jul 4 17:38:34 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jul 2005 17:38:34 -0400 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> <42c98b40$0$29947$626a14ce@news.free.fr> Message-ID: "tiissa" wrote in message news:42c98b40$0$29947$626a14ce at news.free.fr... > Variables are stored in two dictionnaries: globals() (for global > variables) and locals() (for the local ones, which are also global on > top level). Within a function, the local namespace is usually *not* a dictionary. D=locals() makes a dictionary copy of the namespace, which takes more time than one might expect, and which has the trap that changes to D do *not* affect the namespace itself. So the try..except idiom is faster and does not have that particular trap. Terry J. Reedy From devlai at gmail.com Wed Jul 13 18:20:24 2005 From: devlai at gmail.com (Devan L) Date: 13 Jul 2005 15:20:24 -0700 Subject: Odd behaviour of regexp module In-Reply-To: <1121288737.882813.244540@f14g2000cwb.googlegroups.com> References: <1121288737.882813.244540@f14g2000cwb.googlegroups.com> Message-ID: <1121293224.339718.10530@g44g2000cwa.googlegroups.com> Why doesn't group have an argument? group() or group(0) returns what the pattern matched, not what it returns. From callmebill at gmail.com Thu Jul 21 10:41:37 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 21 Jul 2005 07:41:37 -0700 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <42dfb111@griseus.its.uu.se> References: <42dfb111@griseus.its.uu.se> Message-ID: <1121956897.727721.38050@g47g2000cwa.googlegroups.com> On your system, do: which python2.4 That will give you the full path to the python2.4 binary (let's call it "path/to/py24"). Then add: #!/path/to/py24 ...to the top of your script. And make sure the file is chmod'd +x From python-url at phaseit.net Wed Jul 13 14:22:03 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 13 Jul 2005 18:22:03 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 13) Message-ID: QOTW: "The posts do share an erroneous, implied assumption that the investment in learning each language is equal. Python has a strong competitive advantage over Java and C++ in terms of learnability. A person can get up to speed in a few days with Python." - Raymond Hettinger "You know, this is the most concise example of feature-creep in a specification that I've ever seen." - Christopher Subich "With Lisp or Forth, a master programmer has unlimited power and expressiveness. With Python, even a regular guy can reach for the stars." - Raymond Hettinger Lisp's macros are undoubtedly a powerful feature, but are they powerful enough to make List development faster than Python development? Do we want macros in Python? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ca05ba71092748a1 List comprehensions are almost identical to generator expressions wrapped in list() calls. Does that mean that list comps will go away in Python 3? Should they? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b050ef55b36dee56 A Bright, Shiny Service: Sparklines: http://www.xml.com/pub/a/2005/06/22/sparklines.html Which is faster, if, or try/except? Which is more Pythonic? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/8026ec36def2af1e Rbt wants to break out of nested loops. He's shown several ways of doing it, but for my money, Raymond's approach is the most elegant: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b127ff7fffcea00 Charlie Calvert wrote a couple of articles that advocate Python, and he's looking for some backup: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/721d749715aa5aaf ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 13:07:41 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 19:07:41 +0200 Subject: Comparison of functions In-Reply-To: References: <3l1druF10aj5pU1@individual.net> Message-ID: <3l1qetF1060r2U2@individual.net> Georg Neis wrote: > * Reinhold Birkenfeld wrote: >> Steven D'Aprano wrote: >>>>>> 1+0j == 1 > 0 >>> True >> >> (1+0j == 1) yields True, which is comparable to 0. > > "a == b > c" is equivalent to "a == b and b > c": Right. Stupid me :) Doesn't do much to the point, though. >>>> 1 == 1+0j > 0 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= Reinhold From seberino at spawar.navy.mil Fri Jul 29 01:58:16 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 28 Jul 2005 22:58:16 -0700 Subject: why functions in modules need 'global foo' for integer foo but not dictionary foo? Message-ID: <1122616696.886226.279510@f14g2000cwb.googlegroups.com> At top of a module I have an integer like so... foo = 4 In a function in that module I know I need to do 'global foo' to get at the value 4. ... IIRC, for dictionaries you DO NOT have this issue? Why this scope problem with integers but not dictionaries? Chris From sjmachin at lexicon.net Sat Jul 9 08:14:07 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 09 Jul 2005 22:14:07 +1000 Subject: Problem with sha.new In-Reply-To: References: Message-ID: <42CFBF8F.6090504@lexicon.net> Florian Lindner wrote: > Hello, > I try to compute SHA hashes for different files: > > > for root, dirs, files in os.walk(sys.argv[1]): > for file in files: > path = os.path.join(root, file) > print path > f = open(path) print "sha is", repr(sha) ### self-help !!!!! > sha = sha.new(f.read()) print "sha is", repr(sha) ### self-help !!!!! > sha.update(f.read()) > print sha.hexdigest() > > > this generates a traceback when sha.new() is called for the second time: > > /home/florian/testdir/testfile > c95ad0ce54f903e1568facb2b120ca9210f6778f > /home/florian/testdir/testfile2 > Traceback (most recent call last): > File "duplicatefinder.py", line 11, in ? > sha = sha.new(f.read()) > AttributeError: new > > What is wrong there? > "sha" no longer refers to the module of that name; it refers to the sha-object returned by the FIRST call of sha.new. That sha-object doesn't have a method called "new", hence the AttributeError exception. From agriff at tin.it Mon Jul 4 02:12:09 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 04 Jul 2005 06:12:09 GMT Subject: Folding in vim References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: On Sun, 3 Jul 2005 22:42:17 -0500, Terry Hancock wrote: >It seems to be that it isn't robust against files >with lots of mixed tabs and spaces. My suggestion is: - never ever use tabs; tabs were nice when they had a de-facto meaning (tabbing to next 8-space boundary) nowdays they're just noise as the meaning depends on the phase of the moon. Making tabs meaning anything had the pretty obvious implication of making tabs meaning nothing. - stick to 4-space indent I've even run in the past in editors that damaged my python sources because they were indented with two spaces (I'm used to an indent size of 2 when working in C/C++). With python IMO 4 spaces is perfectly adequate anyway; onced I tried it I never had the temptation of looking back. Andrea From misymagicg at yahoo.com Wed Jul 27 18:26:43 2005 From: misymagicg at yahoo.com (globalbid) Date: 27 Jul 2005 15:26:43 -0700 Subject: Are you interested in Saving money on projects? Message-ID: <1122503203.463684.312230@g49g2000cwa.googlegroups.com> Hi, I have a website www.FreelancingProject.com and I would like to invite freelancer, programmer's or web designer's to sign up and receive a nice sign up bonus! Our goal is to connect professional freelancers to webmasters providing both freelancers and webmasters the opportunity to expand their business and reduce their costs. Feel free to post a project for bidding or bid on current open projects. You can't bet our fee's, they are the lowest on the web! Thanks and have a great day, Sacha From peter at engcorp.com Thu Jul 7 18:20:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Jul 2005 18:20:38 -0400 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: <1120744114.317478.101730@z14g2000cwz.googlegroups.com> References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> <1120744114.317478.101730@z14g2000cwz.googlegroups.com> Message-ID: zooko wrote: > The traditional use of gettimeofday() to (insecurely and unreliably) > approximate elapsed local time is one of my pet peeves. > > Fortunately a real monotonic clock has finally been added to the linux > kernel and glibc: > > http://www.imperialviolet.org/page24.html#e474 Interestingly, the author of that page appears to have made a number of the same misassumptions about the actual behaviour of the timeofday clock (assuming time.time() fairly faithfully reproduces/wraps that behaviour). Either that or time.time() does magic that avoids the bulk of the problems in which case I can say only "sucks not to be using Python, doesn't it?" I'd be more interested in this monotonic clock feature if it were not the case that time.time() is pretty much monotonic except in the face of the minor (sub-100ms) tweaks that might occur once every week or two with an NTP client running. It certainly doesn't cause the one hour jumps forwards and backwards which I and the author of that page both thought it would. -Peter From sbassi at gmail.com Wed Jul 20 14:11:16 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Wed, 20 Jul 2005 15:11:16 -0300 Subject: How to store "3D" data? (data structure question) In-Reply-To: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> References: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> Message-ID: On 20 Jul 2005 10:47:50 -0700, Graham Fawcett wrote: > This looks a lot like 2D data (row/column), not 3D. What's the third > axis? It looks, too, that you're not really interested in storage, but > in analysis... I think it as 3D like this: 1st axis: [MARKER]Name, like TDF1, TDF2. 2nd axis: Allele, like 181, 188 and so on. 3rd axis: Line: RHA280, RHA801. I can have a star in MarkerName TDF1, Allele 181 and Line RHA280. I can have an empty (o none) in TDF1, Allele 181 and Line RHA801. What I like to know is what would be a suitable structure to handle this data? thank you very much! -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From tbr at nospam.nos Tue Jul 5 11:43:03 2005 From: tbr at nospam.nos (TechBookReport) Date: Tue, 05 Jul 2005 16:43:03 +0100 Subject: Good starterbook for learning Python? In-Reply-To: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: Lennart wrote: > Hi everybody, > > Can someone advice me with the following issue: i want to learn python in > my summer vacation (i try to ...:-) So, a good start is buying a good book. > But wich? There are many ... > > I'm living in the Netherlands and I prefer a book from bol.com (see link) > because i've to order more books by them. I'm familiar with html & php and > basic (in the good old days). It has to be a newbie book, but not a book > what i don't need anymore when i've got some skills. I.e. the learning > curve of the book should be linear. A kind of book wich i could use as a > novice. > > Search here for python (sorry, there's no short link) > http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_BrowseCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&CategoryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb&CategoryLeftpanel=BOOK_EN%2eCATEGORY00000000&Secondary=YES&Template=BOL_subcat_BOOK_EN_1476 Two excellent books match your criteria: Dive Into Python (review: http://www.techbookreport.com/tbr0103.html) - also available as a free download. Learning Python (review: http://www.techbookreport.com/tbr0064.html) Both are recommended for beginners but have a reasonable level of depth. They're clear, enthusiastic and well-written. HTH -- TechBookReport - Programming http://www.techbookreport.com/ProgIndex.html From thorsten at thorstenkampe.de Sat Jul 30 07:11:50 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 30 Jul 2005 12:11:50 +0100 Subject: How can I run a program? References: <1122719594.365246.241840@g43g2000cwa.googlegroups.com> Message-ID: * Lad (2005-07-30 11:33 +0100) > I am running Python on XP and have a problem with > a program if its name consists '-' for example: > my-program.py > When I try to run a program with such name /How/ do you "run" the program for Guido's sake?! > I get the error : > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'my' is not defined > > Python thinks that the name of program is my.py only > but the name is my-program.py > > What is a solution? The solution to get answers is to give details. But to play the clairvoyant: /If/ you tried to run the program from a command prompt or from by klicking on the file there should be no problems. /If/ you tried to run the program by importing it from the Python shell, then this is normal. A hyphen is not allowed in module names at it is the same character as in subtractation. From spam.csubich+block at block.subich.spam.com Mon Jul 4 13:43:16 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Mon, 04 Jul 2005 13:43:16 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: Message-ID: <3yeye.25042$Tt.21572@bignews3.bellsouth.net> Peter Hansen wrote: > [str(parrot) for parrot in sequence], for example, tells you much more > about what is going on than str(x) does. > > Exactly what, I have no idea... but it says _so_ much more. ;-) Yarr! Avast! Etc! From lainedacier at gmail.com Tue Jul 26 01:08:07 2005 From: lainedacier at gmail.com (lainedacier at gmail.com) Date: 25 Jul 2005 22:08:07 -0700 Subject: Suggestions for Python XML library which can search and insert Message-ID: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> Hi, I'm looking for a library that can search through an XML document tree, locate an element by attribute (ideally this can be done through XPath), and insert an element (as its child). Simple? Yes? ...but the code I've seen so far which does this uses 'nested for loops' for trees which are relatively shallow compared to mine. So I'm wondering if you could give me some suggestions as to which XML library could do this without resorting to nested for loops, and/or better yet, what's the trend in this type of operation? Thanks in advance. From wolfgang.keller.nospam at gmx.de Fri Jul 29 04:21:48 2005 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: 29 Jul 2005 08:21:48 GMT Subject: Spreadsheet with Python scripting and database interface? Message-ID: Hello, I'm looking for a spreadsheet application (MacOS X prefered, but Windows, Linux ar available as well) with support for Python scripting (third-party "plug-ins" are ok) and a database interface. Applications that I know of (that they exist) are: MS Excel Quattro Lotus OO Calc Gnumeric Kspread Which ones have I forgotten? Which ones have support for Python scripting? Excel: I know of a module that allows to script Excel in Python from outside (COM scripting on Windows and Applescript on MacOS are know as well), but I don't know of any possibility to do Python scripting with Excel itself? OO Calc: I know that PyUNO exists, but I know nothing about what it can actually do? Kspread: Koffice seems to have Python scripting support, but I have no clue what you can actually do with it? The database interface should ideally allow to: - map database tables, views, query results to tables/lists (with as little programming as possible) - allow editing of records within those tables/lists (and write back the results) - supply possibilities to handle relationships (via foreign keys) between records in different tables in a user-friendly way (I have something like hyperlinks in mind) The database software to interface with is Postgres. The application "should" also provide good support for naming of cells/columns/rows/regions (including namespaces for files, sheets) and user-defined formats. TIA, Sincerely, Wolfgang Keller From spam.csubich+block at block.subich.spam.com Sat Jul 23 20:43:06 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 23 Jul 2005 20:43:06 -0400 Subject: return None In-Reply-To: <11e2dru68unf2e8@corp.supernews.com> References: <3kcpbbFtjttlU1@individual.net> <11e2dru68unf2e8@corp.supernews.com> Message-ID: Grant Edwards wrote: > Personally, I don't really like the idea that falling off the > botton of a function implicitly returns None. It's just not > explicit enough for me. My preference would be that if the > function didn't execute a "return" statement, then it didn't > return anyting and attempting to use a return value would be an > error. This is a bad idea. Classically, distinguishing between functions that return things and functions that don't return things explicitly divides the "callable object" space. From my CS101 class with its incredibly exciting dive into the world of useless pseudocode, callables that returned things were called 'functions' and callables that didn't were called 'procedures'. Some languages do make this distinction; QBASIC, for example, had 'gosub' separate from function calls. What do you do for an early break from a function that still returns not-even-None [ReallyNone], "return?" That looks and acts like a 'real' return statement, and the distinction between return-without-a-value-so-maybe-except and return-with-a-value is suddenly magnified to real importance. Further, and I consider this a truly damning case, look at decorater. A naive "logging" decorator could be defined like this: def logger(func): def new_func(*args, **kwargs): print '%s called with:' % func.__name__, args, kwargs retval = func(*args,**kwargs) print '%s returns:', retval return retval return new_func This logger works without modification for both value and non-value returning functions. Its output isn't quite as pretty for non-value functions, but it works and the implementation is both simple and flexible. With a function-schism, to keep its simple implementation 'logger' would have to be rewritten as 'flogger' (same as current-logger, for use on functions), and 'plogger' (for use on procedures). The downside here is that if the function/method changed to or from a procedure, the decorator would have to be switched. Alternatively, the logger decorator could be longer and explicitly catch the possible exception. But why should we have to write like that, for a use-case that doesn't even represent a true error -- arguably not even an exceptional case? Python's definitely not a B&D language, talk of floggers aside. From bvande at po-box.mcgill.ca Fri Jul 15 16:23:32 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 15 Jul 2005 16:23:32 -0400 Subject: problems with python 2.4 help In-Reply-To: <1121453444.143877.143140@g44g2000cwa.googlegroups.com> References: <1121453444.143877.143140@g44g2000cwa.googlegroups.com> Message-ID: <42D81B44.7050008@po-box.mcgill.ca> frozenee at gmail.com said unto the world upon 15/07/2005 14:50: > I've noticed that the listings in help don't take you to correct topic. > > anyone else have this problem? Is there a fix? > I'm not sure from your question what exact problem you are experiencing. Do you mean: IDLE 1.1.1 >>> help() Welcome to Python 2.4! This is the online help utility. help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DELETION LOOPING SEQUENCES DEBUGGING LITERALS SEQUENCEMETHODS2 help> LOOPING Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. help> If so, I posted a similar question a year or so ago to the tutor list. I believe that when I resolved it I posted details about the resolution. I've since got a new computer, and just redid it now to check. Just download the html version of the docs and then, as per the instructions above, set an environment variable to point to them. (On WinXP: Control Panel->System-Advanced->Env. Var. When I had WinME, a line in autoexec.bat) Best, Brian vdB From steve at REMOVEMEcyber.com.au Tue Jul 26 04:05:11 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 26 Jul 2005 18:05:11 +1000 Subject: Suggestions for Python XML library which can search and insert References: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> Message-ID: <42E5EEB7.400@REMOVEMEcyber.com.au> lainedacier at gmail.com wrote: > Simple? Yes? ...but the code I've seen so far which does this uses > 'nested for loops' for trees which are relatively shallow compared to > mine. So I'm wondering if you could give me some suggestions as to > which XML library could do this without resorting to nested for loops, > and/or better yet, what's the trend in this type of operation? Why do you care if they are nested for loops? What is the problem you are experiencing that is caused by for loops? Does the software you've seen not work with your XML trees? What error do you get when you try it? Or are you just opposed to for loops on philosophical grounds? -- Steven. From bdesth.quelquechose at free.quelquepart.fr Thu Jul 28 19:45:33 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 29 Jul 2005 01:45:33 +0200 Subject: Cgi scripts in apache not working In-Reply-To: <1122571679.788076.37080@g43g2000cwa.googlegroups.com> References: <1122571679.788076.37080@g43g2000cwa.googlegroups.com> Message-ID: <42e966ff$0$1461$626a14ce@news.free.fr> David a ?crit : > I've looked all over the place for an answer, and the only one I can > find doesn't mean anything to me. The end of line issue with writting > it in Windows and then uploading it doesn't help me since I'm doing > this all from Linux. I've been trying to get python cgi scripts to > work, and I always end up with a "Premature end of script headers" in > the error log. > > The scripts are executable by all Is it executable by yourself ? and my httpd.conf seems fine. I also > tested it out in /var/www/cgi-bin/ and there it seems to work fine. > > test2.py: > > #!/usr/bin/python > print "Content-type: text/html\n\n" > print """ > > >

Hello World

> > """ > > httpd.conf: > > << Tried it with "" and no "" shoud be without "" AFAIK (well, it's without on all our servers !-) > Options ExecCGI << Tried with "Options +ExecCGI" > AddHandler cgi-script .cgi .py << Tried with "SetHandler > cgi-script", but still no go SetHandler tells apache to treat everything as a cgi , whatever the .xxx I've tried your script (renamed py.cgi, because .py is not in my default apache conf and I wanted to try it out of the box), with the following conf for userdirs: Options +ExecCGI -Includes -Indexes SetHandler cgi-script runs fine. I've then added a .htaccess in my ~/public_html: Options +ExecCGI AddHandler cgi-script .cgi And mv'd py.cgi from ~/public_html/cgi-bin to ~/public_html. runs fine. > error_log: > > [Thu Jul 28 11:44:53 2005] [error] [client xxx.xxx.xxx.xxx] Premature > end of script headers: test2.py > What are the previous and next lines ? I've found such a line in my error_log, due to me forgetting to make the script executable, and there was a [Fri Jul 29 01:14:33 2005] [error] [client 127.0.0.1] (13)Permission denied: exec of '/home/bruno/public_html/cgi-bin/py.cgi' failed before. Then I tried chmod u-x py.cgi, and got the same error message as you did, but this time with no "Permission denied" before. Aayway, I think your problem is with permissions and/or your apache conf, so you may find more useful help on an apache ng. My 2 cents From bobofficers at invalid.net Mon Jul 18 14:44:35 2005 From: bobofficers at invalid.net (Bob Officer) Date: Mon, 18 Jul 2005 11:44:35 -0700 Subject: Earthquake Forecasting Program July 11, 2005 References: Message-ID: <83und1pv3du700os4oug71i6ks242ojqfp@4ax.com> On Mon, 11 Jul 2005 08:31:31 GMT, in sci.geo.earthquakes, "edgrsprj" wrote: >PROPOSED EARTHQUAKE FORECASTING >COMPUTER PROGRAM DEVELOPMENT EFFORT here we go again... EDG is not a computer programmer, nor is he a geologist... The best guess seems to be that he is he is crackpot, often going from group to group espousing some sort of knowledge and asking for people to forward his articles to government, schools and other professional bodies with a demand that public monies be giving to him to support his "research". A few years ago he started begging for programming help to process these "signals" he has been looking for... (odd he has never explained what the exactly these signals really are. >Posted July 11, 2005 >My main earthquake forecasting Web page is: >http://www.freewebz.com/eq-forecasting/Data.html > >Newsgroup Readers: If you circulate copies of this report to groups of >computer programmers at different universities etc. around the world then >they might find the subject matter to be interesting. or that might classify you just as EDG is classified, KOOK or Crackpot >The information in this report represents expressions of personal opinion. > >THE GOAL OF THIS REPORT > > This is part of an effort to get some idea regarding how many >computer programmers and other researchers around the world might be >interested in participating in a project aimed at developing life saving >earthquake forecasting computer programs. > > That effort is not presently underway. And I don't know when or if >it will get started. I am simply attempting to determine if other people >believe that large numbers of volunteers would be interested in working on >such a project or if there would instead be little interest in it. That >information would be helpful for developing a plan for establishing a Web >site where the project would be centered. Personnel running the following >Web site have volunteered to make their site available for such an effort. Look at this for all his effort over the past few years... >But nothing has gotten underway so far. > -- Ak'toh'di From sheig222 at gmail.com Sun Jul 31 03:24:30 2005 From: sheig222 at gmail.com (Ira) Date: Sun, 31 Jul 2005 10:24:30 +0300 Subject: Changing interpreter's deafult output/error streams Message-ID: Hi, Using an embedded interpreter, how do I change it's default output streams (specifically the one used by PyErr_Print() which I'm guessing is the default error stream)? Cheers, Ira From T.A.Meyer at massey.ac.nz Wed Jul 27 00:33:39 2005 From: T.A.Meyer at massey.ac.nz (Meyer, Tony) Date: Wed, 27 Jul 2005 16:33:39 +1200 Subject: [path-PEP] Path inherits from basestring again Message-ID: [using __div__ to mean join] > I think the '+' is used as a join for both strings > and lists, so it would probably be the better choice > as far as consistency with the language is concerned. +1. =Tony.Meyer From twic at urchin.earth.li Wed Jul 6 09:28:55 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 6 Jul 2005 14:28:55 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120610787.940292.15210@g43g2000cwa.googlegroups.com> References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 5 Jul 2005, George Sakkis wrote: > "Steven D'Aprano" wrote: > >> On Tue, 05 Jul 2005 09:46:41 -0500, Terry Hancock wrote: > [snip] > >> Def would be short for ... defend? defile? defer? defame? default? deflect? >> >> There's always *something* to learn. Why def instead of define? Because >> "easy to write" beats "instantly obvious to a beginner", if the word is >> used all the time and is easy to memorize. > > Still it's hard to explain why four specific python keywords - def, > del, exec and elif - were chosen to be abbreviated, while all the rest > are full words (http://docs.python.org/ref/keywords.html). "Ease of > typing" is a joke for an excuse; For exec and probably del, yes, but def and elif are two of the most frequently used keywords in the language, so i think it's reasonable to keep them short. > So, who would object the full-word versions for python 3K ? > > def -> define I'd keep this short - it's one of the most commonly-used keywords. It's particularly commonly used if you break your programs down into lots of little functions; since this is, IMHO, something we want to encourage people to do, we should strive to minimise boilerplate. > del -> delete How about just getting rid of del? Removal from collections could be done with a method call, and i'm not convinced that deleting variables is something we really need to be able to do (most other languages manage without it). > exec -> execute This should be a function somewhere, maybe a builtin, maybe not - it absolutely should not be a keyword. What that function should be called, i don't know! > elif -> else if I'm not sure about splitting it into two words; there's currently a very simple relationship between flow control keywords, meanings, and blocks of code, which would be broken if we moved to using "else if". I don't know that this relationship is actually important, though. tom -- Don't believe his lies. From jstier at cs.uvic.ca Thu Jul 7 19:03:56 2005 From: jstier at cs.uvic.ca (J) Date: 7 Jul 2005 16:03:56 -0700 Subject: publishing an already instantiated class Message-ID: <1120777436.271756.73890@g47g2000cwa.googlegroups.com> Hi everyone, Thanks for your awsome replies. I started replacing Javascript with python 2 days ago and I already have my first scripts running. Mainly due to the wealth of information in this blog. I have a C++ object that is already instantiated and now I want to give python a reference to it... Basically I have class X { typedef struct { PyObject_HEAD ScnNode* mObject; } PyStruct; static PyTypeObject PyType; static init() { PyType_Ready(&PyType) < 0) Py_INCREF(&PyType); PyModule_AddObject(sModule, "Node", (PyObject*) &PyType); } }; I think that in the constructor of X I now have to make some calls in order to provide access to this instance from a python script.... I also think that I only want to get PyObject_New to be called, but not PyObject_Init, because there I create a new instance of X when it is instantiated through a script.... Am I on the right track here ? Cheers Jochen From bokr at oz.net Sat Jul 23 14:30:29 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 23 Jul 2005 18:30:29 GMT Subject: Copying attributes References: Message-ID: <42e27cd3.954834309@news.oz.net> On Thu, 21 Jul 2005 00:45:12 +0200, red wrote: >Hi, > >I'm writing a script for Blender and need to build a face array. My >engine needs that all faces must be triangles, so I convert quads to >triangles by dividing them into two triangles. Here is the function: > >def build_face_table(mesh): > face_table = {} # face_table = [] ?? Irrelevant nit: Why a dict? You seem to be building it with all the keys as integers of xrange(last_i), in which case appending a face_table list to build it and later accessing face_table[key] will go faster than your current dict. OTOH, if you will be deleting various elements later, your dict may be best. > i = 0 > for f in mesh.faces: > if len(f.v) == 3: # triangle > face_table[i] = f # face_table.append(f) # no need for i counting > i += 1 > elif len(f.v) == 4: # quad > f1 = NMesh.Face() > f2 = NMesh.Face() > > f1.mat = f.mat >## f1.normal = copy.deepcopy(f.normal) > f1.normal = NMesh.Vert(f.normal[0], f.normal[1], f.normal[2]) f is a quad at this point, right? So unless the quad is restricted to a plane, it couldn't have a normal in general. Could that be it? BTW, if it is not a plane, one choice of diagonal may be better than the other in getting two triangles that fit the underlying 3D surface best. If there is a normal, why wouldn't ft.normal = f.normal[::] work? Is normal more than a 3-tuple or list to record unit vector components in some coordinate system? > f1.v.append(f.v[0]) > f1.v.append(f.v[1]) > f1.v.append(f.v[2]) Why append, and is there restricted property magic behind f1.v so that plain old f1.v = f.v[:3] wouldn't work? # or f1.v = [f.v[0], f.v[1], f.v[2]] if you want to be consistent with f2 below > > f2.mat = f.mat # f2.normal = ?? # could this face be picked up later indirectly and cause the missing normal exception? > f2.v.append(f.v[2]) > f2.v.append(f.v[3]) > f2.v.append(f.v[0]) Why appends? Does f2.v ever grow beyond 3 items? E.g., f2.v = [f.v[2], f.v[3], f.v[0]] # are quad vertices listed clockwise or ccw and # are triangles in a sequence totally independent, or # is there some systematic vertex sharing in the order # that something might depend on, or benefit optimization-wise from? > > face_table[i] = f1 #face_table.append(f1) ?? > i += 1 > face_table[i] = f2 #face_table.append(f2) ?? > i += 1 > else: > message = "Can't build face from 2 vertices." Why is len(f.v)>4 not just a 3D surface point cluster, in which case it might be possible to find an internal point to slice radiating triangles from. E.g., imagine an almost-plane small pentagon on a large sphere, and slice from its "center" to each peripheral pair of vertices to make triangles. > Draw.PupMenu("Face Table Error%t|"+message) > return > return face_table # do you need it as a dict? Unless you modify it, a list will get you # the same elements as your dict by writing face_table[some_index] If you need to iterate and have both index key and value, you can use your dict like for i, face in sorted(face_table.items()): # leave out sorted call if order does not matter # ... or use the more efficient list version of face_table like for i, face in enumerate(facetable): # will naturally be in sort order # ... > >Everything seems be ok, but i'm getting: > >Traceback (most recent call last): > File "", line 169, in write > File "", line 102, in build_face_table >AttributeError: normal > >I was wondering why? Though the face has an attribute called "normal"! >Just simply test: > >nv = f.normal > >and it works! But why my new faces (f1 and f2) no? Did it work on a quad face? What about putting in a debug print before places you use f.normal, e.g. assert hasattr(f, 'normal'), 'This "f"\n----\n%r\n----\ndid not have a normal attribute!!' % f If f.repr doesn't give you enough info, you can format something better in the assert message string. > >Greetings. > >-- >_red ____ _ ____ ____ __ _ BTW, I don't know Blender at all, just reading between the lines ;-) Hope I triggered a useful thought. Regards, Bengt Richter From rkern at ucsd.edu Sat Jul 23 15:15:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 23 Jul 2005 12:15:16 -0700 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: <1122136203.26083.103.camel@localhost> References: <1122136203.26083.103.camel@localhost> Message-ID: Soeren Sonnenburg wrote: > Hi all, > > Just having started with python, I feel that simple array operations '*' > and '+' don't do multiplication/addition but instead extend/join an > array: > > a=[1,2,3] This isn't an array. It is a list. If you want an array, use Numeric/numarray. If you want lists, use lists. Lists will never grow the kind of behavior you're asking for. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sxanth at ceid.upatras.gr Fri Jul 1 14:22:37 2005 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Fri, 01 Jul 2005 21:22:37 +0300 Subject: map vs. list-comprehension In-Reply-To: References: <42c27238$0$26269$626a14ce@news.free.fr> <42c2b7cd$1@nntp0.pdx.net> Message-ID: <42C589ED.2030007@ceid.upatras.gr> Mandus wrote: > jepp - faster, but still slower than the map. > > 1000000 iterations: > zip+list-comprehension: 8.1s > izip+list-comprehension: 7.5s > map: 7.0s > Strange. On 2.4.1 izip is the fastest. The thing is that if you put benchmark code in global the results are not fair as each variable access is a LOAD_GLOBAL and costs a dictionary lookup. That can lead to wrong results, like that 'try ... except ..' is faster than 'if i in ..'. With this benchmak: #-------------------------------------------------------- from itertools import izip from time import time def f1(): return map(lambda bb,ii,dd: bb+ii*dd,b,i,d) def f2(): return [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] def f3(): return [ bb+ii*dd for bb,ii,dd in izip(b,i,d) ] def run(f, K): t0 = time () for i in xrange (K): f() return time()-t0 T = 2000000 def BENCH(K): global b, i, d N = T/K print "%i times tuples of size %i:" % (K,N) b = tuple (range(0, -N, -1)) i = tuple (range(N)) d = tuple (N*[1]) for x, y in sorted ([(run (x1,K), y1) for x1, y1 in ((f1,'map'),(f2,'zip'),(f3,'izip'))]): print '%s: %.2f' %(y,x), print BENCH(200000) BENCH(20000) BENCH(2000) BENCH(200) BENCH(20) BENCH(1) #-------------------------------------------------------- On 2.4.1 I get: python zipmap.py 200000 times tuples of size 10: izip: 1.32 zip: 1.50 map: 1.60 20000 times tuples of size 100: izip: 1.00 zip: 1.14 map: 1.29 2000 times tuples of size 1000: izip: 0.94 zip: 1.10 map: 1.28 200 times tuples of size 10000: izip: 0.93 map: 1.29 zip: 1.51 20 times tuples of size 100000: izip: 0.96 map: 1.31 zip: 2.28 1 times tuples of size 2000000: izip: 0.96 map: 1.33 zip: 13.28 Stelios From cam.ac.uk at mh391.invalid Wed Jul 6 16:38:38 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 06 Jul 2005 21:38:38 +0100 Subject: Strange os.path.exists() behaviour In-Reply-To: References: <42cc3613$0$22287$8fcfb975@news.wanadoo.fr> Message-ID: Jeff Epler wrote: > Here's the bug. You're using Windows. QOTW (speaking as someone who is using Windows right now). -- Michael Hoffman From Chris.Wu at gmail.com Tue Jul 12 21:56:30 2005 From: Chris.Wu at gmail.com (Chris) Date: 12 Jul 2005 18:56:30 -0700 Subject: Multivariable polynomials Message-ID: <1121219789.988951.122880@g47g2000cwa.googlegroups.com> Does anyone know of a good standalone implementation of multivariable polynomials in python? Thanks, Chris From steve at REMOVETHIScyber.com.au Sun Jul 3 19:27:30 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 09:27:30 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: On Sun, 03 Jul 2005 19:31:02 +0000, Ron Adam wrote: > First on removing reduce: > > 1. There is no reason why reduce can't be put in a functional module Don't disagree with that. > or > you can write the equivalent yourself. It's not that hard to do, so it > isn't that big of a deal to not have it as a built in. Same goes for sum. Same goes for product, which doesn't have that many common usages apart from calculating the geometric mean, and let's face it, most developers don't even know what the geometric mean _is_. If you look back at past discussions about sum, you will see that there is plenty of disagreement about how it should work when given non-numeric arguments, eg strings, lists, etc. So it isn't so clear what sum should do. > 2. Reduce calls a function on every item in the list, so it's > performance isn't much better than the equivalent code using a for-loop. That is an optimization issue. Especially when used with the operator module, reduce and map can be significantly faster than for loops. > *** (note, that list.sort() has the same problem. I would support > replacing it with a sort that uses an optional 'order-list' as a sort > key. I think it's performance could be increased a great deal by > removing the function call reference. *** > > > Second, the addition of sum & product: > > 1. Sum, and less so Product, are fairly common operations so they have > plenty of use case arguments for including them. Disagree about product, although given that sum is in the language, it doesn't hurt to put product as well for completion and those few usages. > 2. They don't need to call a pre-defined function between every item, so > they can be completely handled internally by C code. They will be much > much faster than equivalent code using reduce or a for-loop. This > represents a speed increase for every program that totals or subtotals a > list, or finds a product of a set. I don't object to adding sum and product to the language. I don't object to adding zip. I don't object to list comps. Functional, er, functions are a good thing. We should have more of them, not less. >> But removing reduce is just removing >> functionality for no other reason, it seems, than spite. > > No, not for spite. It's more a matter of increasing the over all > performance and usefulness of Python without making it more complicated. > In order to add new stuff that is better thought out, some things > will need to be removed or else the language will continue to grow and > be another visual basic. Another slippery slope argument. > Having sum and product built in has a clear advantage in both > performance and potential frequency of use, where as reduce doesn't have > the same performance advantage and most poeple don't use it anyway, so > why have it built in if sum and product are? Because it is already there. > Why not just code it as a > function and put it in your own module? Yes, let's all re-invent the wheel in every module! Why bother having a print statement, when it is so easy to write your own: def myprint(obj): sys.stdout.write(str(obj)) Best of all, you can customize print to do anything you like, _and_ it is a function. > def reduce( f, seq): > x = 0 > for y in seq: > x = f(x,y) > return x Because that is far less readable, and you take a performance hit. > But I suspect that most people would just do what I currently do and > write the for-loop to do what they want directly instead of using lambda > in reduce. That's your choice. I'm not suggesting we remove for loops and force you to use reduce. Or even list comps. -- Steven. From adurdin at gmail.com Fri Jul 1 00:21:32 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Fri, 1 Jul 2005 14:21:32 +1000 Subject: Lost in a sea of documentation...can you point me in the right direction? In-Reply-To: <1120167496.973373.163400@f14g2000cwb.googlegroups.com> References: <1120167496.973373.163400@f14g2000cwb.googlegroups.com> Message-ID: <59e9fd3a0506302121197c545a@mail.gmail.com> On 30 Jun 2005 14:38:17 -0700, MooMaster wrote: > So I started reading about os, threads, > and the path for the special folders in the archives and in the Python > docs and I'm kind of lost because there aren't many concrete examples > in the documentation. Can anyone point me in the right direction as to > where I might find info that can help me write this? For changing the wallpaper, and getting the path to the "My Pictures" folder, you'll need to use Win32 API functions: SHGetSpecialFolderPath() and SystemParametersInfo(). To call these, you'll need to use either the Python Win32 extensions or some other module for calling functions in a .dll. From gsakkis at rutgers.edu Fri Jul 1 10:06:04 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 07:06:04 -0700 Subject: map vs. list-comprehension References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> <1120203815.141353.61200@z14g2000cwz.googlegroups.com> Message-ID: <1120226764.869190.326760@g49g2000cwa.googlegroups.com> "Tom Anderson" wrote: > On Fri, 1 Jul 2005, George Sakkis wrote: > > > Keeping the language small is a worthwhile goal, but it should be traded > > off with conciseness and readability; otherwise we could well be content > > with s-expressions. > > There's quite a number of satisfied LISP programmers out there who *are* > content with S-expressions ... > > tom "We" referred mostly to python programmers, and although quite a few may also be happy users of one or more lisp-ish dialect, I doubt they think it beats python in the syntax department ;-) George From rtomek at ceti.pl Sun Jul 24 16:05:06 2005 From: rtomek at ceti.pl (Tomasz Rola) Date: Sun, 24 Jul 2005 22:05:06 +0200 (CEST) Subject: How to run python script in background after i logout In-Reply-To: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 24 Jul 2005, Harlin Seritt wrote: > I have a remote linux server where I can only access it via ssh. I have > a script that I need to have run all the time. I run like so: > > python script.py & > > It runs fine. When I log off ssh I notice that the script died when I > logged off. How do I make sure it stays running? Besides at and cron commands (mentioned by the others), have a look at "nohup", too. Regards, Tomasz Rola - -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** -----BEGIN PGP SIGNATURE----- Version: PGPfreeware 5.0i for non-commercial use Charset: noconv iQA/AwUBQuP0fhETUsyL9vbiEQINVACfVvgOcWTr3jmA21gJq24DcVHWNmgAn2tY JAt0TM0X67bFlD3wRh9TkVeH =tVam -----END PGP SIGNATURE----- From ralobao at gmail.com Sun Jul 17 09:56:46 2005 From: ralobao at gmail.com (ralobao at gmail.com) Date: 17 Jul 2005 06:56:46 -0700 Subject: beginner question fibonacci In-Reply-To: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> References: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> Message-ID: <1121608606.454500.212840@f14g2000cwb.googlegroups.com> The case is that Python in attribution commands solves first the right side, so he atributes the vars. So the a+b expression is executed first. Joon escreveu: > >>> # Fibonacci series: > ... # the sum of two elements defines the next > ... a, b = 0, 1 > >>> while b < 10: > ... print b > ... a, b = b, a+b > ... > 1 > 1 > 2 > 3 > 5 > 8 > > > > >>> a, b = 0, 1 > >>> while b < 10: > print b > a = b > b = a+b > > > 1 > 2 > 4 > 8 > > Why a, b = b, a+b isn't a = b; b = a+b ? From apardon at forel.vub.ac.be Thu Jul 7 04:01:28 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Jul 2005 08:01:28 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> <1120636418.166800.42290@o13g2000cwo.googlegroups.com> <1120642040.109796.212450@o13g2000cwo.googlegroups.com> Message-ID: Op 2005-07-07, Philippe C. Martin schreef : > ???? > > Almost sounds like a racist comment - sorry if I misunderstood I'll clarify. A lot of the time I hear arguments against features that boils down to. 1) I don't need it. 2) Having the feature will make my job more difficult. 3) I don't understand the merrits of the feature or I have difficulty understanding what it does when I encounter it. IMO these are arguments if followed sufficiently will lead to a language that is only usefull for mediocre programmers. > Antoon Pardon wrote: > >> Op 2005-07-06, Michele Simionato schreef : >>> Fuzzyman: >>>> So Lisp is for really good programmers, and Python is for >>>> mediocre programmers ? >>> >>> >>> Python is *also* for mediocre programmers. I see this as a >>> strength, not as a weakness. >> >> But sometimes I get the impression people want it to evolve >> so it is only for mediocre programmers. >> > From gene.tani at gmail.com Thu Jul 28 11:37:47 2005 From: gene.tani at gmail.com (gene tani) Date: 28 Jul 2005 08:37:47 -0700 Subject: functions without parentheses In-Reply-To: <97udndQn87N3ZXXfRVn-vQ@comcast.com> References: <97udndQn87N3ZXXfRVn-vQ@comcast.com> Message-ID: <1122565067.784687.280620@o13g2000cwo.googlegroups.com> http://onestepback.org/index.cgi/Tech/Ruby/PythonAndRuby.rdoc this blog talks about design differences, e.g. what "." means, whether functions and methods are 1st-class objects. St From t-meyer at ihug.co.nz Sun Jul 24 23:28:32 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 25 Jul 2005 15:28:32 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: [...] > Open issues: [...] > What about path * 4? If you keep the current join meaning of __div__, then assigning any sort of multiplication meaning to __mul__ would not be a good idea, IMO. It's natural to expect that __div__ and __mul__ are opposites. I suppose this means that you could make __mul__ mean split (and f(*tuple) does do splitting of a sort), but I don't know what splitting by 4 would mean, necessarily. Do people really like using __div__ to mean join? On the python-dev discussion, Just van Rossum spoke out against it, but there weren't (IIRC) any other comments, either pro or con. I'm -1, myself. Apart from TIOOTDI, it doesn't seem a natural use for the '/' character. I suppose that it looks nice, when one is used to posix paths, but not everyone is, and I'm sure that more people would expect some sort of division (the exact opposite!) than join. =Tony.Meyer From elmo13 at jippii.fi Tue Jul 19 16:45:12 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Tue, 19 Jul 2005 23:45:12 +0300 Subject: Differences between RDFlib - 4RDF and Redfoot - 4Suite? References: <1121446238.230645.37970@g14g2000cwa.googlegroups.com> Message-ID: On Fri, 15 Jul 2005 09:50:38 -0700, uche.ogbuji wrote: > I'd say for now if you just need quick RDF parsing, and you're not also > using plain XML, and stuff like Versa RDF query language aren't > important to you, you'll get along just fine with rdflib. Thanks for the insight! From helge at aksdal.net Wed Jul 20 09:38:36 2005 From: helge at aksdal.net (Helge Aksdal) Date: Wed, 20 Jul 2005 15:38:36 +0200 Subject: socket programming In-Reply-To: <1121865616.375295.129420@z14g2000cwz.googlegroups.com> References: <20050719184205.GA24773@mail.smule.com> <1121865616.375295.129420@z14g2000cwz.googlegroups.com> Message-ID: <20050720133835.GA20476@mail.smule.com> * gry at ll.mit.edu [2005/07/20 15:26]: > What I have done in similar circumstances is put in a random sleep > between connections to fool the server's load manager. Something like: > > .import time > .min_pause,max_pause = (5.0, 10.0) #seconds > .while True: > . time.sleep(random.uniform(min_pause, max_pause)) > . do_connection_and_query_stuff() > > It works for me. Just play with the pause parameters until it fails > and add a little. thanks for the tip. i'll give that a shot. -- Helge Aksdal From Scott.Daniels at Acm.Org Fri Jul 1 14:59:38 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 01 Jul 2005 11:59:38 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> Message-ID: <42c58af2$1@nntp0.pdx.net> Daniel Dittmar wrote: > Rocco Moretti wrote: >>>> Except that (please correct me if I'm wrong) there is somewhat of a >>>> policy for not including interface code for third party programs which >>>> are not part of the operating system. (I.e. the modules in the >>>> standard libary should all be usable for anyone with a default OS + >>>> Python install.) > > .... > > There seems to be a great reluctance by the Python developers to add > modules of the expat kind, as this means responsibilities for additional > source modules. There's also the problem with incompatible licenses, > integrating a second configure, deciding when to update to the latest > version of the library etc. If you haven't noticed, the Python code has a substantial body of unit tests. Arranging the tests to be easily runnable for all developers is going to be tough for "third party programs." Making the interfaces work for differing versions of the 3PPs as the third parties themselves change their interfaces (see fun with Tcl/Tk versions for example), and building testbeds to test to all of those differing versions, would cause a nightmare that would make a knight of Ni scream. --Scott David Daniels Scott.Daniels at Acm.Org From sjuranic at gmail.com Thu Jul 7 20:50:51 2005 From: sjuranic at gmail.com (Steve Juranich) Date: Thu, 7 Jul 2005 17:50:51 -0700 Subject: Is there an easy way to get at the value of DBL_MAX from Python? Message-ID: <56190b6c050707175019a6a78c@mail.gmail.com> I'm in a situation where it would be nice to have access to this value. I've been looking for it all afternoon and can't find anything. Thanks. -- Steve Juranich Tucson, AZ USA From rkern at ucsd.edu Fri Jul 29 01:40:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 22:40:25 -0700 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Dan Sommers wrote: > On Thu, 28 Jul 2005 15:35:54 -0700, > Robert Kern wrote: > >>That said, I made a boo-boo. The Zen of Python is really a set of >>design principles (and some of them, like this one, are more >>specifically *language* design principles), not Essential Development >>Practices. That'll teach me to not RTFA. > > May I respectfully disagree? No, I'm afraid that you may only disrespectfully disagree with me. I will not tolerate politeness. Why? Uh, my .sig quote justifies rudeness! Yes, that's it![1] > The Zen applies to all aspects of software > (and other things, too, but they're off topic here), from human readable > reports and requirements and documentation, to GUI's, to test cases, to > code, to database schemta, as well as the development methodology and > practices themselves. Sure, and I can find programming advice in the Old Testament, too, if I try hard enough[2]. But that doesn't change the fact that the "Essential Development Practices" (e.g. "Use a source control system") are in a different category than the Zen of Python (e.g. "Namespaces are one honking great idea -- let's do more of those!"). Hence Michael Hoffman's very good question about how he might embody that particular bit of Zen: it's just not applicable to the things he's doing because it's a design principle for Python the language, not about development (or even design!) in general. Of course other pieces of the Zen are more generally applicable ("Readability counts.") as a "development practice," but that's something of an accident. Usually, they're about design, sometimes specifically about the design of Python the language. > Sometimes you have to look at the Zen sideways, so that "implementation" > appears to be replaced by the particular aspect or aspects (or the > software, or just software, as a whole, for the true Masters out there) > you happen to be working on at the time, but such is the nature of Zen. That's a bit too much navel-gazing for me. With enough effort, you make anything a symbol of anything else. But that doesn't get any code written. [1] http://groups-beta.google.com/group/comp.lang.python/msg/72f205c9b6709163 [2] Proverbs 28:14 JPS "Happy is the man that feareth alway; but he that hardeneth his heart shall fall into evil." Obviously an exhortation to not ignore raised exceptions with "except: pass". -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From lbates at syscononline.com Thu Jul 7 18:41:17 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 07 Jul 2005 17:41:17 -0500 Subject: Upgrading from Python 2.2 to 2.4 (can't find _ssl.pyd) In-Reply-To: References: Message-ID: <1J-dnXmJMvAcMlDfRVn-tw@comcast.com> Never mind. Seems that the standard distribution at www.python.org has it included (I was using ActiveState). FYI, Larry Larry Bates wrote: > Well I'm still on my "quest". I've been putting this > off for quite some time because I KNEW it was going to > be hard. I tried to wait a while to upgrade to let all > these things become readily available. > > So far Sam Rushing has been my hero in putting > updated versions (2.4) of calldll and npstruct > on his website: > > http://www.nightmare.com/~rushing/dynwin/index.html > > Thanks Sam! > > I've been able to track everything else down, but I have > to admit that it has been harder than I thought...and > I'm not done. > > Now I can't find _ssl.pyd compiled for Python 2.4. > Anybody have a copy they can share? > > Thanks in advance, > Larry Bates From franz.steinhaeusler at gmx.at Wed Jul 20 07:49:54 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 20 Jul 2005 13:49:54 +0200 Subject: Python IDE References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <6gesd1pkcpba1lp2neckr76076niaj0cs6@4ax.com> On 18 Jul 2005 22:32:43 -0700, "linuxfreak" wrote: >Tried SPE and >Dr.Pyhton but the former crashes regulary and the latter is quite >unweildy and does not have a great many features Hello, what are you missing in DrPython? Did you took a look at the plugins? What do you mean by "unweildly"? -- Franz Steinhaeusler From philippe at philippecmartin.com Tue Jul 12 13:46:49 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 12 Jul 2005 17:46:49 GMT Subject: pywin32 com server "cash" question References: Message-ID: Sorry: "Cache", not "Cash" Philippe C. Martin wrote: > Hi, > > I just got the pywin32 "hello world" COM server to install and I did > manage to use it from VB 6.0. > > However, there are some glitches I do not comprehend: > > 1) at one point I got a python runtime error telling me the > "testcomserver" was not found - I got rid of that problem by deleteting > the appropriate (I hope) registry and reregistering the server > > 2) If I change the source of the server > from: > return "Hello" + .... > to: > return "Hello my friend " + .... > > > I still get "Hello BINGO" only in my VB message box. this even if I try to > re-register (which does not seem necessary) the server. > > > Q.1) What could that error have meant ? > Q.2) is there a way to "flush" whatever so my new code "Hello my friend" > shows up ? > > > > > The VB looks like this: > > Private Sub Command1_Click() > Dim shdemo = CreateObject("Python.TestServer") > MsgBox (shdemo.Hello("BINGO")) > End Sub > > The Python server : > > class HelloWorld: > > _reg_clsid_ = "{7CC9F362-486D-11D1-BB48-0000E838A65F}" > _reg_desc_ = "Python Test COM Server" > _reg_progid_ = "Python.TestServer" > _public_methods_ = ['Hello'] > _public_attrs_ = ['softspace', 'noCalls'] > _readonly_attrs_ = ['noCalls'] > #_reg_class_spec_ = "testcomserver.HelloWorld" > > def __init__(self): > > self.softspace = 1 > > self.noCalls = 0 > > def Hello(self, who): > > self.noCalls = self.noCalls + 1 > > # insert "softspace" number of spaces > > return "Hello My Friend " + " " * self.softspace + str(who) > > if __name__=='__main__': > # ni only for 1.4! > import win32com.server.register > win32com.server.register.UseCommandLine(HelloWorld) > import pythoncom > print pythoncom.CreateGuid() > > > > Regards, > > Philippe From tjreedy at udel.edu Mon Jul 4 15:37:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jul 2005 15:37:12 -0400 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> Message-ID: "Josiah Manson" wrote in message news:1120502549.913249.292750 at g43g2000cwa.googlegroups.com... > Hello. I am very new to Python, and have been unable to figure out how > to check if a variable exists or not. In the following code Python does not have variables is the sense some other languages do. It has (typeless) names bound to typed objects with values. This is a different object-value model and a different mindset from some other languages. > I have made > a kludge that works, but I think that it would be clearer to check if > closest exists and not have to initialize it in the first place. How is > that check done? What you did is normal Python code. Checking whether 'closest' is bound to anything can be done but that *is* a kludge, which I will leave for you to discover elsewhere. > The following code finds the closest place to a position and rejects > places that are too far away. > > dist = 1e9 > closest = -1 closest = None # is the standard for 'not bound to anything' > for n,p in galaxy.places.iteritems(): > dif = p.pos - pos > len = dif.len() > if len < dist and len < 10.0/self.zoom: > dist = len > closest = p If you generate a sequence of (distance, place) pairs, beginning with (1e99, None), you can select the mimimum distance pair with the min() builtin function instead of rewriting it. > if closest != -1: if closest: # bool(None) == False, bool(anyplace) == True > self.sel = [closest.name] > > I also have a few other questions to tack on if you don't mind. I am > setting dist to 1e9, because that is a larger value than any of the > places in the galaxy will be far away. Is there a better way to > initialize dist so that it is impossible for this to fail? For example, > would setting dist to infinity work, and how is that done? Maybe, depending on the compiler. For now, I would stick with a known larger-than-possible value. > Extending my existance checking question, how does one check what type > a variable has? See the first two sentences above and look up type() and isinstance() in the 2nd chapter of the Library reference. (And do read that entire chapter if you have not.) Terry J. Reedy From http Sun Jul 31 04:03:22 2005 From: http (Paul Rubin) Date: 31 Jul 2005 01:03:22 -0700 Subject: Dabo in 30 seconds? References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> Message-ID: <7xpsszv1v9.fsf@ruckus.brouhaha.com> Cliff Wells writes: > Then why are you using Python at all? Shouldn't you be in the "safe > home" of Java or Visual Basic, where "standards" are all you have? I don't know about VB but Java does a much better job of supporting standards than Python does. Python's advantage is in being a much more pleasant language to code in. It would benefit greatly from also doing a better job implementing standards. Many or most of the Python library modules that purport to implement standards just sort of get halfway there and then stop. From jm.suresh at gmail.com Tue Jul 12 10:05:46 2005 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 12 Jul 2005 07:05:46 -0700 Subject: CAD in wxPython Message-ID: <1121177146.878259.40280@g14g2000cwa.googlegroups.com> Hi all, I am trying to write a small program to view VLSI mask layouts. I am trying to display polygons with different *transparent* patterns. How can I do this in wxPython. Can you please give me some pointers if some application has already done this. Look at the images in these web pages. I am trying to create something like this. http://vsp2.ecs.umass.edu/vspg/658/TA_Tools/cadence/Vertuoso.html http://www.cisl.columbia.edu/grads/sumit/layout.html My dream is to develop a full fledged eda environment on top of python. If you are also interested contact me. Thanks. regards, Suresh From b83503104 at yahoo.com Tue Jul 12 10:31:47 2005 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 12 Jul 2005 07:31:47 -0700 Subject: question on "input" Message-ID: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> Hi, I want to accept the user's answer yes or no. If I do this: answer = input('y or n?') and type y on the keyboard, python complains Traceback (most recent call last): File "", line 1, in ? File "", line 0, in ? NameError: name 'y' is not defined It seems like input only accepts numerals, or strings with quotes. Need solutions, thanks. From malkarouri at gmail.com Wed Jul 6 22:30:00 2005 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 6 Jul 2005 19:30:00 -0700 Subject: Considering moving from Delphi to Python [Some questions] In-Reply-To: References: <5f4d3cb505070410192ba525d7@mail.gmail.com> Message-ID: <1120703400.739597.54430@g43g2000cwa.googlegroups.com> Dark Cowherd wrote: > Stupid of me. > > I want some feedback on folllwing: > anybody who has experience in writing SOAP servers in Python and data > entry heavy web applications. > Any suggestions? > darkcowherd Check ZSI, or SOAPPY, both on Python Web Services http://pywebsvcs.sourceforge.net/ I usually use ZSI. You cannot generate wsdl files from python code, so if I were in your shoes I would write the Delphi side and generate the wsdl file then use it in python. I never tested interoperability of Delphi & ZSI by the way, though I would love to. Please inform us if you do try it. btw, elementtree has an attempt at elementsoap but i don't think they went very far.. cheers, k From mwm at mired.org Tue Jul 19 23:26:13 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 19 Jul 2005 23:26:13 -0400 Subject: How to send a query to the browser from time to time? References: <1121778228.962141.70680@f14g2000cwb.googlegroups.com> Message-ID: <86fyuarwdm.fsf@bhuda.mired.org> "Simon Dahlbacka" writes: > Short answer: Not using HTTP. > > However, you can use something like AJAX to just load new data from > time to time and not the entire page. AJAX is overkill for this. If you just want to automatically refresh the page automatically, you can use a meta refresh tag. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From stringy at gmail.com Thu Jul 21 06:18:56 2005 From: stringy at gmail.com (stringy) Date: 21 Jul 2005 03:18:56 -0700 Subject: Couple quick questions from a Python Noob In-Reply-To: <1121934168.143332.111100@f14g2000cwb.googlegroups.com> References: <1121934168.143332.111100@f14g2000cwb.googlegroups.com> Message-ID: <1121941136.679360.91490@g14g2000cwa.googlegroups.com> For compiling Python, http://effbot.org/zone/python-compile.htm appears to have some information, although I've never done it myself, so I wouldn't know any more on the matter. Also http://starship.python.net/crew/theller/py2exe/ appears to have something on Python-> .exe From benji at benjiyork.com Sat Jul 23 12:00:39 2005 From: benji at benjiyork.com (Benji York) Date: Sat, 23 Jul 2005 12:00:39 -0400 Subject: What is your favorite Python web framework? In-Reply-To: <5f4d3cb50507230825591c4bcd@mail.gmail.com> References: <1122048187.041743.205780@g43g2000cwa.googlegroups.com> <5f4d3cb50507230825591c4bcd@mail.gmail.com> Message-ID: <42E269A7.7020500@benjiyork.com> Dark Cowherd wrote: > My applications would be data entry heavy. Think inventory and accounting apps. > > Would going past the [Zope] learning curve allow me to write applications like that. You might want to look at Zope 3, there are several niceties for automatically (or semi-automatically if you prefer) generating input forms, validating them, applying the results to an object, etc. -- Benji York From rkern at ucsd.edu Sun Jul 31 03:36:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 00:36:16 -0700 Subject: How to convert a string like '777' to an octal integer like 0777? In-Reply-To: <1122794648.326967.284070@g47g2000cwa.googlegroups.com> References: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> <42ec640a@news.eftel.com> <1122794648.326967.284070@g47g2000cwa.googlegroups.com> Message-ID: KB wrote: > Thanks, John. > > But my point is how to keep the leading zero in 0777, > in order to be used in os.chmod('myfile', 0777)? I don't understand. The leading zero only exists in a particular string representation. os.chmod() needs an integer, not a string. 0777 == 511. os.chmod('myfile', 0777) os.chmod('myfile', 511) os.chmod('myfile', int('777', 8)) They all do *exactly* the same thing. End of story. If you really need a string representation in octal (os.chmod() doesn't), then use oct() on the integer. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From skilpat at gmail.com Wed Jul 13 17:53:15 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 13 Jul 2005 14:53:15 -0700 Subject: timeoutsocket.py mirror? Message-ID: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> Can anybody provide a mirror for this module? The original URL seems to be down. I have been looking for over an hour, and every single resource that uses it links to the timo-tasi.org site to download it. Thanks! Scott Kilpatrick From brusstoc at gmail.com Tue Jul 19 12:04:08 2005 From: brusstoc at gmail.com (brusstoc at gmail.com) Date: 19 Jul 2005 09:04:08 -0700 Subject: python certification References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> Message-ID: <1121789048.751714.249570@o13g2000cwo.googlegroups.com> I haven't had a change to check it out, but www.guruishcool.com has a python certificate. From mwm at mired.org Sat Jul 2 12:41:03 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 02 Jul 2005 12:41:03 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <864qbd40v4.fsf@bhuda.mired.org> Jamey Cribbs writes: > Code blocks allow you to wrap up any Ruby code and pass it to a method > and have it executed within that method. It is more powerful than > lambda, because you can have multiple statements in the code block and > you can do assignment within the code block. Just FYI, the inability to have statements - even multiple statements - in a lambda is what people are talking about when they talk about the limitations of lambda. It's a common thing for someone with a background that includes a proper lambda to trip over when they first start programming in Python. It's not that uncommon for newcommers to trip over it with "print". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From me at privacy.net Fri Jul 29 06:32:36 2005 From: me at privacy.net (Dan Sommers) Date: Fri, 29 Jul 2005 06:32:36 -0400 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: On Fri, 29 Jul 2005 10:08:15 +0100, Steve Holden wrote: > If I canpoint out the obvious, the output from "import this" *is* > headed "The Zen of Python", so clearly it isn;t intended to be > universal in its applicability. Ok, not universal. But as usual, Zen is not easily nailed to a tree. Was Tim writing about developing Python itself, or about developing other programs with Python? Regards, Dan -- Dan Sommers From spam.csubich+block at block.subich.spam.com Sun Jul 3 01:01:18 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 01:01:18 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> <86irzu5sp9.fsf@bhuda.mired.org> Message-ID: Steven D'Aprano wrote: > comps. But reduce can't be written as a list comp, only as a relatively > complex for loop at a HUGE loss of readability -- and I've never used > Lisp or Scheme in my life. I'm surely not the only one. See my reply to your other post for a more detailed explanation, but I don't think that the for-loop solution is much less readable at all, and the additional complexity involved is simply setting the initial value and result for the accumulator. The for-loop solution is even more flexible, because it can include anonymous code blocks and not just expressions. One caevat that I just noticed, though -- with the for-solution, you do need to be careful about whether you're using a generator or list if you do not set an explicit initial value (and instead use the first value of 'sequence' as the start). The difference is: _accum = g.next() for i in g: _accum = stuff(_accum,i) versus _accum = g[0] for i in g[1:]: _accum = stuff(_accum,i) The difference is because generators don't support subscripts, while lists don't support .next() iteration. Unless I'm missing something in the language (entirely possible), this suggests a missing feature for same-syntax iteration over the two types. From benji at benjiyork.com Sat Jul 23 12:20:08 2005 From: benji at benjiyork.com (Benji York) Date: Sat, 23 Jul 2005 12:20:08 -0400 Subject: unit test nested functions In-Reply-To: <1122134462.286558.16160@f14g2000cwb.googlegroups.com> References: <1122134462.286558.16160@f14g2000cwb.googlegroups.com> Message-ID: <42E26E38.6020805@benjiyork.com> Raymond Hettinger wrote: > [Andy] >>How can you unit test nested functions? > For whitebox testing, you could make an inner function visible by > binding it to the enclosing function's attribute namespace. > > def f(x): > def g(y): > . . . > f.g = g # make g visible as an attribute of f > . . . Note that when using this technique, f.g will not be bound until after you call the function: >>> def f(x): ... def g(y): ... pass ... f.g = g ... >>> f >>> f.g Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'g' >>> f(1) >>> f.g -- Benji York From mage at mage.hu Wed Jul 20 09:19:35 2005 From: mage at mage.hu (Mage) Date: Wed, 20 Jul 2005 15:19:35 +0200 Subject: is this pythonic? Message-ID: <42DE4F67.7030300@mage.hu> Or is there better way? for (i, url) in [(i,links[i]) for i in range(len(links))]: ... "links" is a list. Mage From bokr at oz.net Thu Jul 7 12:21:06 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 07 Jul 2005 16:21:06 GMT Subject: Conditionally implementing __iter__ in new style classes References: <42cc0e23.693458660@news.oz.net> <7jg35a0h.fsf@python.net> Message-ID: <42cd51aa.44517973@news.oz.net> On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller wrote: >bokr at oz.net (Bengt Richter) writes: > >> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller wrote: >> >>>I'm trying to implement __iter__ on an abstract base class while I don't >>>know whether subclasses support that or not. > >> Will a property or custom descriptor do what you want? E.g. >> >> >>> class Base(object): >> ... def __getIter(self): >> ... if hasattr(self, "Iterator"): >> ... return self.Iterator >> ... raise AttributeError, name >> ... __iter__ = property(__getIter) [...] > >Yep, that's exactly what I need - thanks. > BTW, I forgot to mention that you could use property as a decorator in the above single-argument case: >>> class Base(object): ... @property ... def __iter__(self): ... if hasattr(self, "Iterator"): ... return self.Iterator ... raise AttributeError, name ... >>> class Concrete(Base): ... def Iterator(self): ... yield 1 ... yield 2 ... yield 3 ... >>> iter(Base()) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence >>> iter(Concrete()) >>> list(iter(Concrete())) [1, 2, 3] Hope there isn't a gotcha for your use case in the way an instance attribute of the same name is allowed. A custom descriptor could eliminate that. >>> inst = Concrete() >>> list(iter(inst)) [1, 2, 3] >>> inst.__init__ = 'abc' >>> list(iter(inst)) [1, 2, 3] >>> inst.__init__ 'abc' Regards, Bengt Richter From k04jg02 at kzoo.edu Thu Jul 14 00:17:46 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Wed, 13 Jul 2005 22:17:46 -0600 Subject: Any Lua Coders About? In-Reply-To: <2005071323103316807%wendell@meetrocom> References: <2005071323103316807%wendell@meetrocom> Message-ID: <42D5E76A.6060207@kzoo.edu> Wendell III wrote: >Hey, > >I'm looking for a few good Lua guys with some IM network experience. >Anyone around fit that criteria? > >Bestest, >-Wendell > > I'd say it's a no brainer to try lua's mailing list ;) From http Thu Jul 7 17:27:29 2005 From: http (Paul Rubin) Date: 07 Jul 2005 14:27:29 -0700 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: <7x8y0iwblq.fsf@ruckus.brouhaha.com> Joseph Garvin writes: > Also, everyone keeps discussing Eclipse as something that gives Java a > leg up on Python. *Ahem* PyDev :) Which you should also give another > try if you haven't in a few versions. Easiest way to get a GUI > debugger for python. Can you give a brief description of what the Python debugger is like? Can it debug multi-threaded Python programs? IDLE has a rudimentary debugger that can be useful sometimes, but it wedges up when you exit from it, making its usefulness limited. > My only misgiving with Eclipse now is that I think development of > plugins for it is always going to be slower than for Emacs and other > editors because they have to be written in Java. I had thought that using the Python debugging interface for required writing C extensions. There's a mention in the Python cookbook of some C-only interface needed for cross-thread signalling. What's up with that? From samgurung at gmail.com Fri Jul 22 00:22:55 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 21:22:55 -0700 Subject: Detecting computers on network In-Reply-To: References: Message-ID: <1122006175.776172.126190@g43g2000cwa.googlegroups.com> How about sending an ICMP echo packet to your broadcast address and checking which hosts send a reply From williams13 at llnl.gov Mon Jul 25 14:27:16 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Mon, 25 Jul 2005 11:27:16 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050722164442.GB1912@tishler.net> References: <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> Message-ID: <42E52F04.5010008@llnl.gov> [snip] I was able to run C:/cygwin/bin/ash.exe. This is good. In the "ash.exe" window, I ran PATH=/bin rebaseall and received the same error: "rebaseall: only ash processes are allowed ...... Execute '/bin/rebaseall' from ash." -Dean >If Cygwin's bin is not in your Windows PATH, then give the full path to >ash. For example: > > C:\Cygwin\bin\ash.exe > >Then start rebaseall is follows: > > $ PATH=/bin rebaseall > >Jason > > > From eric_brunel at despammed.com Mon Jul 25 03:32:03 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 25 Jul 2005 09:32:03 +0200 Subject: Clearing a Text Widget References: Message-ID: On Fri, 22 Jul 2005 23:42:52 -0400, Kane Bonnette wrote: > Kane Bonnette wrote: >> Does anyone know how the clear the text from a Tkinter Text Widget? The >> delete(0, END) trick that works for Entry widgets doesn't work for Text >> >> I get "0 is an invalid index" when i try to do so >> >> Thanks in advance > > In case anyone's wondering, you must use 0.0 instead of 0 on a Text Widget In fact, you should use 1.0, which means line 1, column 0 (lines are numbered from 1 in text widgets). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From hongqn at gmail.com Fri Jul 22 12:17:25 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Sat, 23 Jul 2005 00:17:25 +0800 Subject: tuple to string? In-Reply-To: <42E0EED4.4020001@gmx.net> References: <42E0EED4.4020001@gmx.net> Message-ID: On 7/22/05, Francois De Serres wrote: > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to > the string 'spam'? Use ''.join and chr() as others have pointed out. Here are just-for-fun versions ;) .>>> t = (0x73, 0x70, 0x61, 0x6D) (use string formatter): .>>> '%c%c%c%c' % t 'spam' (use struct model): .>>> import struct .>>> struct.pack('bbbb', *t) 'spam' -- Qiangning Hong I'm usually annoyed by IDEs because, for instance, they don't use VIM as an editor. Since I'm hooked to that, all IDEs I've used so far have failed to impress me. -- Sybren Stuvel @ c.l.python Get Firefox! From mensanator at aol.com Wed Jul 13 21:34:01 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Jul 2005 18:34:01 -0700 Subject: Consecutive Character Sequences In-Reply-To: References: Message-ID: <1121304841.733285.191570@g14g2000cwa.googlegroups.com> Walter Brunswick wrote: > Is there any way to [efficiently] iterate through a sequence of characters to find N [or more] consecutive equivalent characters? > > So, for example, the string "taaypiqee88adbbba" would return 1 if the number (of consequtive characters) supplied in the parameters > of the function call was 2 or 3, because "a", "e", 8, and "b" is repeated 2 or 3 times. > > Thanks for any assistance. > W. Brunswick. def rep(n): # current repetition count the_rep = 1 # previous character inspected last_c = '' # history of repetions max_rep = {} for c in s: # duplicate character found? if c==last_c: # count how many consecutive dups the_rep += 1 # repetition (if any) ended, save previous rep count else: # has this count occured before? if max_rep.has_key(the_rep): # if so, track how many times it has max_rep[the_rep] += 1 # otherwise, add this rep count to history else: max_rep[the_rep] = 1 # reset rep count to look for next block the_rep = 1 # save current character to compare to next character last_c = c # check that last character in string wasn't part of a block if max_rep.has_key(the_rep): max_rep[the_rep] += 1 else: max_rep[the_rep] = 1 # finally, did the block size we asked for ever occur? if max_rep.has_key(n): return 1 else: return 0 s = 'taaypiqee88adbbba' for i in range(9): print rep(i), """ 0 1 1 1 0 0 0 0 0 """ From google at spiceaid.com Thu Jul 21 09:14:25 2005 From: google at spiceaid.com (Dr. Who) Date: 21 Jul 2005 06:14:25 -0700 Subject: Buffering problem using subprocess module Message-ID: <1121951665.430514.167440@g14g2000cwa.googlegroups.com> I am using the subprocess module in 2.4. Here's the fragment: bufcaller.py: import sys, subprocess proc = subprocess.Popen('python bufcallee.py', bufsize=0, shell=True, stdout=subprocess.PIPE) for line in proc.stdout: sys.stdout.write(line) bufcallee.py: import time print 'START' time.sleep(10) print 'STOP' Although the documentation says that the output should be unbuffered (bufsize=0) the program (bufcaller) pauses for 10 seconds and then prints START immediately followed by 'STOP' rather than pausing 10 seconds in between them. Note that I made bufcallee a Python script for ease of the example but in the real-world problem I am trying to solve it is simply an executable. Any ideas? Jeff From neuhauser+python-list#python.org at sigpipe.cz Wed Jul 27 08:34:26 2005 From: neuhauser+python-list#python.org at sigpipe.cz (Roman Neuhauser) Date: Wed, 27 Jul 2005 14:34:26 +0200 Subject: question about deleting records from mysql In-Reply-To: <1122466366.005107.303840@z14g2000cwz.googlegroups.com> References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> <42E7720E.90307@xit.net> <1122466366.005107.303840@z14g2000cwz.googlegroups.com> Message-ID: <20050727123426.GA28993@isis.sigpipe.cz> # nephish at xit.net / 2005-07-27 05:12:46 -0700: > ok. did this > > >>> cursor.execute("DELETE FROM table WHERE autoinc > 1000") > 245L > >>> cursor.commit() > > i got an AttributeError 'Cursor' object has no attribute 'commit' > > hmm. what should i do now? RTFM, e. g. here: http://cvs.sourceforge.net/viewcvs.py/mysql-python/MySQLdb/doc/MySQLdb.txt?rev=1.1&view=auto -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 From tdelaney at avaya.com Wed Jul 6 19:37:37 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 7 Jul 2005 09:37:37 +1000 Subject: Conditionally implementing __iter__ in new style classes Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CB3C@au3010avexu1.global.avaya.com> Thomas Heller wrote: > I forgot to mention this: The Base class also implements a __getitem__ > method which should be used for iteration if the .Iterator method in > the subclass is not available. So it seems impossible to raise an > exception in the __iter__ method if .Iterator is not found - __iter__ > MUST return an iterator if present. Again, why not just let subclasses implement __iter__? Calling iter() on an instance of the base class (or any subclass that does not implement __iter__) will return an iterator that uses __getitem__. Calling iter() on a subclass instance that does implement __iter__ will return the iterator from the subclass __iter__. Tim Delaney From ptmcg at austin.rr.com Tue Jul 5 15:48:56 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 5 Jul 2005 12:48:56 -0700 Subject: f*cking re module In-Reply-To: <1120583188.805750.310670@g43g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <1120473422.864033.36350@o13g2000cwo.googlegroups.com> <1120583188.805750.310670@g43g2000cwa.googlegroups.com> Message-ID: <1120592936.609484.289590@z14g2000cwz.googlegroups.com> Forgot to mention: Download pyparsing at http://pyparsing.sourceforge.net. -- Paul From mwm at mired.org Mon Jul 4 13:37:32 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 04 Jul 2005 13:37:32 -0400 Subject: math.nroot References: <1120432250.340056.237460@g44g2000cwa.googlegroups.com> <42C8AD20.30004@REMOVEMEcyber.com.au> <1120476994.515029.129260@g14g2000cwa.googlegroups.com> Message-ID: <861x6e1nhf.fsf@bhuda.mired.org> "George Sakkis" writes: > "Steven D'Aprano" wrote: > >> But it doesn't make sense to say that two flags are equal: >> >> keep_processing = True >> more_reading_needed = True >> while more_reading_needed and keep_processing: >> get_more_records() >> process_records() >> if not keep_processing: >> print "User clicked Cancel" >> >> What does it mean to say that the flag done_processing >> is equal to the flag more_reading_needed? (That is not >> the same question as asking if the two flags have the >> same value.) > > Huh ? Equality *is* the answer to whether two "things" (flags or > whatever) have the same value or not. I think it seriously depends on what your "things" are. For instance: length_in_meters = 1 length_in_feet = 3.2808399 The two variables clearly have different values. Yet they are also clearly equal - representing a distance of 1 meter, within tolerances. On the other hand: length_in_meters = 1 time_in_days = 1 These two variables clearly have the same value. Yet they aren't equal. In fact, comparing them is clearly an error. Not one that most languages will catch, admittedly, but still an error. Actually, I would have reversed the senses of "equal" and "having the same value". But I think this shows that the two concepts are not the same thing. This is why Python lets you provide classes with custom comparison operators. So you can make the syntactic test for "equal" mean "has the same value", even if that's not what the native/naive implementation of comparison would do. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From aahz at pythoncraft.com Mon Jul 11 16:55:49 2005 From: aahz at pythoncraft.com (Aahz) Date: Mon, 11 Jul 2005 13:55:49 -0700 Subject: BayPIGgies: July 14, 7:30pm (Google) Message-ID: <20050711205549.GA14110@panix.com> The next meeting of BayPIGgies will be Thurs, July 14 at 7:30pm at Google, building 40, room Temp Tech Talk. Alex Martelli will be doing his "Black Magic" talk on descriptors, decorators, and metaclasses. Prepare to have your head exploded! BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://www.baypiggies.net/ Before the meeting, we may meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. This week, there has been discussion of a potluck -- if you want a potluck, speak up NOW on the mailing list. Advance notice: The August 11 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From tzot at sil-tec.gr Mon Jul 4 08:56:13 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 04 Jul 2005 15:56:13 +0300 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) References: <42C54915.3020501@lexicon.net> <42C71C52.1080705@lexicon.net> Message-ID: On Sun, 03 Jul 2005 08:59:30 +1000, rumours say that John Machin might have written: >Neutral: no, they always seem to be active combatants. >Neuter: one would hope so, lest they procreate. Thanks for the correction. The first line of my sig is not completely humourous, I believe you noticed :) -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From davecook at nowhere.net Tue Jul 19 13:34:57 2005 From: davecook at nowhere.net (Dave Cook) Date: Tue, 19 Jul 2005 17:34:57 GMT Subject: Python IDE References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: On 2005-07-19, linuxfreak wrote: > you guys using and what do you think is the best IDE...or should i > stick with Xemacs/emacs??? http://pydev.sf.net You get the stability of Eclipse with that, but also the fat. I swear I had code completion working in this, but last time I tried to set it up I got frustrated and gave up, so put aside some time to learn your way around Eclipse if you intend to use this. I still don't feel quite at home there. Personally, I don't find code completion compelling enough a feature to give up my beloved XEmacs and python-mode. Dave Cook From cam.ac.uk at mh391.invalid Thu Jul 28 16:19:53 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 28 Jul 2005 21:19:53 +0100 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Robert Kern wrote: > import this > > And you get 9 bonus Essential Development Practices, too! What a bargain! One of these days I'm going to figure out how to embody "Namespaces are one honking great idea -- let's do more of those!" Then I shall be enlightened. -- Michael Hoffman From andreas at kostyrka.org Fri Jul 1 18:24:20 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 02 Jul 2005 00:24:20 +0200 Subject: No Subject In-Reply-To: <20050701165537.3D0F31E401A@bag.python.org> References: <20050701165537.3D0F31E401A@bag.python.org> Message-ID: <1120256660.6823.109.camel@andi-lap> Am Freitag, den 01.07.2005, 18:55 +0200 schrieb Harry George: > Tom Anderson writes: > > > On Fri, 1 Jul 2005, Adriaan Renting wrote: > > > > > I'm not a very experienced Python programmer yet, so I might be > > > mistaken, but there are a few things that would make me prefer C++ > > > over Python for large (over 500.000 LOC) projects. > > Strictly in terms of software engineering and language design, Python > may well be better suited to large projects than C++ or Java. Code > re-use, original coding and prototyping, unittests, and peer reviews > are a lot easier with Python than with C++ or Java. > > The problem is that large projects tend to have portions which are > performance sensitive. So a project might be 100K LOC of C with 200K > LOC of Python. In my personal opinion, one can often do lowlevel performance code in a Python-ese way by using Pyrex. And it gets the additional benefit, that you pay the "higher line count per feature" that C forces on the developer only for the part that does this lowlevel manipulation. > They serve the same purpose but are not 1:1 with a file. I personally > can't think of a situation where I'd want 2 or more namespaces in a > physical file, or 2 or more files per namespace. Therefore I don't > see any advantage in the C++ approach. In some ways namespaces are even less flexible as Python modules. > Templates address (I hesitate to say "solve") static typing by adding > back the polymorphism that static typing eliminates. > > Python avoids the fix-on-a-fix by doing dynamic strong typing in the > first place. Actually C++ templates are a fix. They are one way to avoid the type system in C++. A template that takes a class argument takes any class that has all needed "features and methods". Just as in Python. So it's a crazy kind of compile-time late-binding. And guess, this static typing in C++ is so sucessful, that many people consider modern C++ to be a generics oriented language, and not an OO language. > > > > > Not that this is necessarily a good thing. I have to say that my Java > > roots do lead me to think that strong typing is a plus for big > > projects, since it's a way of defining and enforcing interfaces > > between bits of code written by different people (or by one person at > > different times!). Optional static typing in python would be nice for > > this. > > > > Java has nothing on Modula-3. Talk about strong static typing... It Well, Java got a VM. And multiple interface "inheritance". And a huge "standard" library. M3 OTOH does have partial type revealing, which allows for more levels than private, protected and public. And even more important, M3 has the concept of safe and unsafe modules/interfaces. Safety in M3-like sense is one of the more important things in Python. If something goes wrong, in Python you usually just have to read a traceback. In C/C++ you'll get a core file if you are lucky. (Or just corrupted data) And if you are even luckier, the stack in the core file uncorrupted, and you get a sensible backtrace. In Python OTOH hand, when the traceback is not enough, one can always work with settrace and other introspection tools. IMHO languages like Python (or even Java) are a much better approach for 90% of the commercial development. There is just no rational explanation why an application developer should have to deal with memory allocation and freeing, dangling pointers, corrupted heaps, and all the other benefits that C/C++ provide. ;) > used to take me 3 days to get the first compile to run on a new > project. > > Yet after years of Modula-3 (and repeatedly seeing strong static typing > pay off) I found python quite comfortable. Somehow the problems > strong static typing addresses aren't a problem. Yes and no. The problem is that static typing addresses certain problems, and provides a 90-98% solution. But that makes the remaining bugs much nastier, because nobody expects them in a "static type checked" program. Especially the type system of C++ is not powerful enough to express certain things. On the other hand it provides for really obscure features. How many C++ developers do know that casting can change the pointer value? (Hint: Multiple inheritence) So static typing gives in practice: a) more lines of code (because variables have to type declared) b) catches most errors of type errors. c) forces one sometimes to hack around the type system. (AFAIK void * hasn't been removed from C++, nor all that ugly casts ;) ) d) makes it harder to find type errors when you get them, because nobody expects them anymore. > > > > - data hiding > > > > Surely you can hide data in python? > > > > You can't genuinely hide data in Python. The best you can do is the > "_" idiom. > > The question is why was data hiding invented in the first place. It > prevents attempts to get at the underlying mechanisms instead of > sticking with the external API. There are two reasons for this: Actually, Python provides even more "data hiding" than say C++. In C++ if you look at the class definition you see a memory layout of the member variables. Not really much protection. Python on the other hand provides properties, __getattr__, __getattribute__ and other mechanism that can hide the real place some piece of data is coming from quite well. > > a) Protection of the algorithms (e.g., trade secrets). Python doesn't > solve that. Neither do C++ or Java, or assembler. If you have access > to the binary, you can reverse engineer the functionality. That's not data hiding, you mean compiling. The data layout of any C++ class is known to the client. Which makes, BTW writing backwards compatible C++ shared libraries a pain in the ass ;) > > b) Prevent ill-considered attempts at optimization through use of the > lower layers. Those layers are there for a reason, usually to protect > the external API from changes in the underlying library. Python > solves that by attracting programmers intelligent enough to understand > this.:-) > > > > - more available libraries and more advanced developement tools. Actually the real live suggests the contrary. Using a C++ library isn't trivial. And the joys of name clashes on the name "string". I guess namespaces have been added mostly for the one id "string" in C++ ;) > If the library is in C, C++, or FORTRAN, Python can use it. Worst > case you have to write your own bindings. Actually, using a library "directly" is mostly a nonbrainer in Python. What sometimes takes some work is to write a binding that is Pythonic and safe. Because many C/C++ libraries aren't safe. > > As for "advanced development tools"... That's a flameware waiting to happen. Well, my C/C++/Python is all basically at the same level. emacs (sometimes vi *g*). Using anything "higher" just suggests that there are defecits in the language. And I guess no editor will tell me, that I call free twice for the same pointer ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From spam.csubich+block at block.subich.spam.com Sat Jul 30 22:25:25 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 30 Jul 2005 22:25:25 -0400 Subject: A replacement for lambda In-Reply-To: References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <4DWGe.25921$h.19496@bignews6.bellsouth.net> Paolino wrote: > why (x**2 with(x))<(x**3 with(x)) is not taken in consideration? Looks too much like a generator expression for my taste. Also, syntax could be used with 'for' instead of 'with' if PEP343 poses a problem, whereas (expr for params) is identically a generator expression. > If 'with' must be there (and substitue 'lambda:') then at least the > syntax is clear.IMO Ruby syntax is also clear. I haven't used Ruby myself, but as I understand it that language allows for full anonymous blocks. Python probably doesn't want to do that. From mwm at mired.org Sat Jul 23 13:50:36 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 23 Jul 2005 13:50:36 -0400 Subject: Getting a dictionary from an object References: Message-ID: <86br4tpg2b.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote: >> Hello. >> >> I would like to have a quick way to create dicts from object, so that a >> call to foo['bar'] would return obj.bar. > > That looks rather confusing to me. Why not just call obj.bar, since it > doesn't look like you are actually using the dictionary at all? Well, I needed exactly this functionality last week. I have a collection of (rather messy) classes that have a slew of attributes as values. I would have used a dictionary for this, but I didn't write the code. I have to be able to display these objects (in HTML, if it matters), and have as a requirement that the format string live in a database. My solution didn't look to different from dictobj. There's some extra mechanism to fetch the format string from the database, and some formatting of the attribute based on meta-information in the object, but it's the same basic idea. >> class dictobj(dict): >> """ >> class dictobj(dict): >> A dictionary d with an object attached to it, >> which treats d['foo'] as d.obj.foo. >> """ >> def __init__(self, obj): >> self.obj = obj >> def __getitem__(self, key): >> return self.obj.__getattribute__(key) > > I don't think this is particularly useful behaviour. How do you use it? def __str__(self): return self._format % self http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From smitty_one_each at bigfoot.com Fri Jul 1 18:13:08 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Fri, 01 Jul 2005 17:13:08 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120236674.379545.17530@f14g2000cwb.googlegroups.com> Message-ID: <87k6kai39n.fsf@bigfoot.com> >>>>> "Devan" == Devan L writes: Devan> None of them are really indispensible. Map and filter cab Devan> be replaced with list comprehensions. reduce is redundant Devan> except when multiplying a series; there's a sum function Devan> for a reason. Lambda looks cleaner in some cases, but you Devan> don't gain any functionality. Devan> What really struck me, though, is the last line of the Devan> abstract: Devan> "I expect tons of disagreement in the feedback, all from Devan> ex-Lisp-or-Scheme folks. :-)" Devan> Guido wrote somewhere that the original map, filter, and Devan> reduce came from a lisp hacker who missed them. My question is, why not move them into, say, a "functional" library, so that legacy code can be handled via an import, and those heads preferring to think that way can be satisfied, and those little corner cases not handled by the newer, sweller syntaxes can still be managed? IOW, just ripping them out of the core and leaving everyone in the lurch doesn't seem too pythonic to me. Best, Chris From fargo_01 at hotmail.com Tue Jul 12 07:01:19 2005 From: fargo_01 at hotmail.com (fargo) Date: Tue, 12 Jul 2005 13:01:19 +0200 Subject: Sort files by date In-Reply-To: References: <42d39273$0$12593$636a15ce@news.free.fr> Message-ID: <42d3a2ff$0$18457$636a15ce@news.free.fr> Jeremy Sanders wrote: > you could do something like: > > l = [(os.stat(i).st_mtime, i) for i in glob.glob('*')] > l.sort() > files = [i[1] for i in l] Thank you for your help, this is excatly what I wasa looking for. From jepler at unpythonic.net Mon Jul 4 14:01:06 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 4 Jul 2005 13:01:06 -0500 Subject: importing pyc from memory? In-Reply-To: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Message-ID: <20050704180105.GB21332@unpythonic.net> This stupid code works for modules, but not for packages. It probably has bugs. import marshal, types class StringImporter: def __init__(self, old_import, modules): self._import = old_import self._modules = modules def __call__(self, name, *args): module = self._modules.get(name, None) if module is None: return self._import(name, *args) code = marshal.loads(module) mod = types.ModuleType(name) exec code in mod.__dict__ return mod def test(): import __builtin__ __builtin__.__import__ = StringImporter(__builtin__.__import__, { 'test_importer': open("/usr/lib/python2.3/os.pyc").read()[8:] }) import test_importer print test_importer.path.join("a", "b") print test_importer.__doc__ if __name__ == '__main__': test() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rrr at ronadam.com Sat Jul 2 14:26:20 2005 From: rrr at ronadam.com (Ron Adam) Date: Sat, 02 Jul 2005 18:26:20 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: References: Message-ID: Ralf W. Grosse-Kunstleve wrote: > class grouping: > > def __init__(self, .x, .y, .z): > # real code right here The way this would work seems a bit inconsistent to me. Args normally create local variables that receive references to the objects passed to them. In this case, a function/method is *creating* non local names in a scope outside it's own name space to receive it's arguments. I don't think that's a good idea. A better approach is to have a copy_var_to(dest, *var_list) function that can do it. You should be able to copy only selected arguments, and not all of them. copy_var_to(self,x,z) Not exactly straight forward to do as it runs into the getting an objects name problem. > Emulation using existing syntax:: > > def __init__(self, x, y, z): > self.x = x > del x > self.y = y > del y > self.z = z > del z The 'del's aren't needed as the references will be unbound as soon as __init__ is finished. That's one of the reasons you need to do self.x=x , the other is to share the objects with other methods. > Is there a way out with Python as-is? > ------------------------------------- With argument lists that long it might be better to use a single dictionary to keep them in. class manager: def __init__(self, **args): defaults = { 'crystal_symmetry':None, 'model_indices':None, 'conformer_indices':None, 'site_symmetry_table':None, 'bond_params_table':None, 'shell_sym_tables':None, 'nonbonded_params':None, 'nonbonded_types':None, 'nonbonded_function':None, 'nonbonded_distance_cutoff':None, 'nonbonded_buffer':1, 'angle_proxies':None, 'dihedral_proxies':None, 'chirality_proxies':None, 'planarity_proxies':None, 'plain_pairs_radius':None } defaults.update(args) self.data = defaults # real code Regards, Ron From timr at probo.com Fri Jul 8 00:40:22 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 07 Jul 2005 21:40:22 -0700 Subject: (Win32 API) callback to Python, threading hiccups References: <42cd46b5$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: >Francois De Serres wrote: >> PyGILState_STATE gil = PyGILState_Ensure(); >> result = PyEval_CallObject(my_callback, arglist); >> PyGILState_Release(gil); >> Py_DECREF(arglist); >> Py_DECREF(result); > >I think this should be: > PyGILState_STATE gil = PyGILState_Ensure(); > result = PyEval_CallObject(my_callback, arglist); > Py_DECREF(arglist); > Py_DECREF(result); > PyGILState_Release(gil); > >The DECREFs need to be protected, that is where storage is >recycled and such, and you still need Python's data structures >to do that kind of work. I freely admit to being woefully underinformed about the GIL, but I'm wondering if your statement is really true. If the purpose of the GIL is simply to make things thread-safe, then I would have guessed that the first one was correct. If someone else holds a reference to "arglist", then the DECREF is just a nice, atomic decrement. If no one else holds a reference to "arglist", then it's quite safe to delete it. Is there more to the GIL than I'm assuming? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From claudio.grondi at freenet.de Tue Jul 19 15:41:12 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 19 Jul 2005 19:41:12 -0000 Subject: Documentation bug: Python console behaviour changed References: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> <-I2dnSVstZw-ekHfRVn-rA@powergate.ca> <4L6De.1182$6f.169@newsread3.news.atl.earthlink.net> Message-ID: <3k4spnFsa3f2U1@individual.net> "Lucas Raab" schrieb im Newsbeitrag news:4L6De.1182$6f.169 at newsread3.news.atl.earthlink.net... > Peter Hansen wrote: > > Kay Schluehr wrote: > > > >> The documentation of the Python console behaviour is not correct > >> anymore for Python 2.4.1. At least for the Win2K system I'm working on > >> 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. > >> > >> The Python interpreter tells me instead: > >> > >> > >>>>> quit > >> > >> > >> 'Use Ctrl-Z plus Return to exit.' > >> > >> Nah, 'Ctrl-Z' is now undo :-) > > > > > > Are you really using the console, started with the "Command Prompt" icon > > from the Start Menu (or some equivalent)? And are you sure you haven't > > installed something else that magically changed the behaviour of Ctrl-Z? > > > > (I get the documented behaviour with Python 2.4.1, under Win XP.) > > > > -Peter > > I'm getting the same behavior as Kay. > > -- > -------------------------- > Lucas Raab I'm getting the same behaviour, too. What is non-standard is, that I am using english international keyboard on German version of Windows 2000 Professional 5.0.2195 SP 4, Build 2195. Claudio From deets at web.de Sun Jul 17 18:48:05 2005 From: deets at web.de (Diez B.Roggisch) Date: Sun, 17 Jul 2005 22:48:05 +0000 (UTC) Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: Kay Schluehr gmx.net> writes: > Now lets drop the assumption that a and b commute. More general: let be > M a set of expressions and X a subset of M where each element of X > commutes with each element of M: how can a product with factors in M be > evaluated/simplified under the condition of additional information X? > > It would be interesting to examine some sorting algorithms on factor > lists with constrained item transpositions. Any suggestions? I don't think that sorting is the answer here. Firts of all IMHO you have to add an additional constraint - associativity of the operation in question So the problem could be reduced to making the constant parts be more associative than the non-constant parts. which you should be able to do with a parser. The BNF grammar could look like this: expr ::= v_expr "*" v_expr | v_expr v_expr ::= variable | c_expr c_expr ::= l_expr "*" literal | l_expr l_expr ::= literal | "(" expr ")" The trick is to create a stronger-binding multiplication operator on constants than on mixed expressions. This grammar is ambigue of course - so a LL(k) or maybe even LALR won't work. But earley's method implemented in spark should do the trick. If I find the time, I'll write an short implementation tomorrow. Diez From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 15 16:45:30 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 15 Jul 2005 22:45:30 +0200 Subject: ssh popen stalling on password redirect output? References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> Message-ID: supercomputer at gmail.com enlightened us with: > I have a script that I cycle through nodes connect to them and run > uptime to get some information. I run the script as root so it > doesn't require a password on the rest of the nodes. It does > however barf on the nodes that are having trouble and require a > different password. Is there an easy way to skip these nodes? > Maybe redirect the password prompt to stdout or stderr or even skip > them? Why not set up proper public/private key authentication, and don't bother with passwords at all? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rrossi at edmaster.it Mon Jul 25 05:01:25 2005 From: rrossi at edmaster.it (rock69) Date: 25 Jul 2005 02:01:25 -0700 Subject: Retrieving and saving images from internet address Message-ID: <1122282085.216772.286680@z14g2000cwz.googlegroups.com> Hi all :) I got this address: http://www.infomedia.it/immagini/riviste/covers/cp/cp137.jpg and I would like to download that image and save it to a local file. How do you do that in Python? From grante at visi.com Thu Jul 7 18:56:19 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 22:56:19 -0000 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <11clc1v4el6no7d@corp.supernews.com> <11cnrngi4lrqn0a@corp.supernews.com> Message-ID: <11crcojcupi46de@corp.supernews.com> On 2005-07-07, Peter Hansen wrote: >>>Maybe you should consider and explain what you mean by >>>"multiple interpreters"? >> >> That in a multi-theraded Python program, the code that >> impliments the Python VM is executing "simultaneously" in >> multiple contexts: one for each thread (and possibly one >> master thread). > > Okay, this description seems correct. Multiple threads, > multiple stacks, therefore multiple contexts and yes, by this > definition, multiple interpreters. > > No "master thread" however. Just all the threads that are > visible in "threading.enumerate()", which includes the main > thread (that the code runs in at startup) and any new ones > spawned afterwards. Oh. I assumed that CPython used Posix threads on Posix platforms. At least in my experience under Linux, libpthread always creates an extra "manager" thread. Though in our case that thread probably wouldn't be running a Python interpreter. -- Grant Edwards grante Yow! Uh-oh!! I'm having at TOO MUCH FUN!! visi.com From newstonne at web.de Wed Jul 13 07:30:25 2005 From: newstonne at web.de (Roland Heiber) Date: Wed, 13 Jul 2005 13:30:25 +0200 Subject: Frankenstring In-Reply-To: References: Message-ID: Thomas Lotze wrote: > AIUI (and as a little experimenting seems to confirm), you can't > reposition an iterator over an mmap'ed file by seeking. True, you have > both iterating by characters and seeking/telling, but the two > functionalities don't play together. A quick and dirty hack!? Maybe i'm missing what it is that you need ... class MmapWithSeekAndTell(object): def __init__(self, m, size): self._m = m self._pos = 0 self._size = size-1 def __iter__(self): return self def next(self): if self._pos < self._size-1: self._pos += 1 return self._m[self._pos] raise StopIteration def seek(self, offset, whence=0): if whence == 0 and 0 <= offset < self._size: self._pos = offset elif whence == 1 and 0 <= (self._pos + offset) < self._size: self._pos += offset elif whence == 2 and 0<= (self._size - offset) < self._size: self._pos = self._size - offset def tell(self): return self._pos HtH, Roland From hancock at anansispaceworks.com Thu Jul 21 21:17:28 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 21 Jul 2005 20:17:28 -0500 Subject: Copying attributes In-Reply-To: References: Message-ID: <200507212017.28766.hancock@anansispaceworks.com> On Thursday 21 July 2005 03:47 am, red wrote: > Terry Hancock wrote: > > I'm not sure either, yet, but can you indicate which line in your > > listing is 102 in the source file? That might be helpful. > > 101: ## f1.normal = copy.deepcopy(f.normal) > 102: f1.normal = NMesh.Vert(f.normal[0], f.normal[1], f.normal[2]) > > I've tried with deepcopy, but the result is exactly same. Okay, well you do realize that the traceback means that it is not *your copy* that lacks the normal attribute, but the object you are passing it (f). This is the loop variable, which is looping through mesh.faces. "mesh" was passed into the function. So the question is, is "mesh" what you think it is? It clearly has an attribute called "faces", because you didn't get an error there. But is "faces" a list, dictionary, or tuple (or something more obscure)? And whatever it is that you are iterating over, the elements of it don't appear to have a "normal" attribute, so they probably aren't what you thought they were. Without knowing the Blender API, I probably can't help more than that (we'd also have to see where the "mesh" variable came from, I think). Anyway, the trace back had to occur on the first reference to f.normal: "f.normal[0]". So that's what you should be checking into. The deepcopy has nothing to do with it. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From gsakkis at rutgers.edu Sun Jul 3 19:28:14 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 16:28:14 -0700 Subject: General questions about embedding Python. References: Message-ID: <1120433294.792071.258470@g43g2000cwa.googlegroups.com> "amit" wrote: > Hello, > > I am currently studying how to embedd python. I am developing a > graphical C++ application. My goal is to embedd python script that will > control some kind of animation. > I have some questions about python embedding: Others will probably answer your specific questions, but I will ask you another first: Why do you (think you) need to embed python in the first place, as opposed to wrapping the low-level performance critical C++ animation code (through SWIG, Boost, or SIP or even use Pyrex), and have python on top ? I know very little about embedding python other than it is not considered a pleasant experience, so make sure you look into the alternatives and have very good reasons if you decide to go down this route. George From bokr at oz.net Sat Jul 16 18:18:53 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 16 Jul 2005 22:18:53 GMT Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: <42d985a0.367263667@news.oz.net> On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen wrote: >Bengt Richter wrote: >> >>> identity = ''.join([chr(i) for i in xrange(256)]) >> >>> unprintable = ''.join([c for c in identity if c not in string.printable]) > >And note that with Python 2.4, in each case the above square brackets >are unnecessary (though harmless), because of the arrival of "generator >expressions" in the language. (Bengt knows this already, of course, but >his brain is probably resisting the reprogramming. :-) ) > Thanks for the nudge. Actually, I know about generator expressions, but at some point I must have misinterpreted some bug in my code to mean that join in particular didn't like generator expression arguments, and wanted lists. Actually it seems to like anything at all that can be iterated produce a sequence of strings. So I'm glad to find that join is fine after all, and to get that misap[com?:-)]prehension out of my mind ;-) Regards, Bengt Richter From peter at engcorp.com Sun Jul 3 15:31:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 15:31:09 -0400 Subject: need to get an index for an item in a list In-Reply-To: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> References: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> Message-ID: nephish at xit.net wrote: > i need to be able to get the index for an item in a list. > any ideas? Fire up the interactive interpreter and learn to use it to help yourself. In this case, the most useful thing might be to know about the dir() builtin method, which you can use on a list like so: dir([]) Note in the output the presence of the "index" method... I'll leave it up to you to read the docs to learn more about how to use it, or you can just experiment at the prompt to see how it works. -Peter From bbangert at parachute.com Mon Jul 18 20:38:23 2005 From: bbangert at parachute.com (bbangert at parachute.com) Date: 18 Jul 2005 17:38:23 -0700 Subject: What is your favorite Python web framework? In-Reply-To: References: Message-ID: <1121733503.697884.210890@g47g2000cwa.googlegroups.com> Admin wrote: > I am doing some research for a Python framework to build web applications. > I have discarted Zope because from what I've read, the learning curve is > too steep, and it takes more time to build applications in general with > Zope. I've heard many good things about Zope 3, although nightmares of Zope 2 still haunt me.... :) > I have kept the following: > > - PyWork - http://pywork.sourceforge.net (Not sure if it's mature) > - Django - http://www.djangoproject.com (Looks interesting) Some thoughts on Django that I agree with: http://griddlenoise.blogspot.com/2005/07/python-off-rails.html > But I'd like to know your opinion on what you think is best. The Python > framework I'll use will be to build an e-commerce application looking like > Amazon.com Amazon.com is built on HTML::Mason, maybe a Python version of it is in order? Mason has been ported to Python and is called Myghty. It's had several significant additions as well allowing for a clear MVC development style with more advanced URL resolving abilities. This framework runs our company's site (www.parachute.com), and has been operating under heavy load for quite a few months now without an issue. > I favor speed of development, intensive OO development, performance under > heavy load, short learning curve, good documentation and community. No Python framework has a "huge" community except for Zope. All the Python frameworks that are under active development typically have very responsive and helpful support from my experience. For ease of development and maximum re-use of code, I'd suggest Myghty coupled with a database ORM like SQLObject (my favorite) and some other libraries to help you quickly deal with common tasks like form validation (formencode). CherryPy is also a very capable framework, so I'd keep it on your list as well, and maybe check out Subway which utilizes CherryPy, SQLObject, and Cheetah. Cheers, Ben From thomas at thomas-lotze.de Wed Jul 13 06:56:49 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Wed, 13 Jul 2005 12:56:49 +0200 Subject: Frankenstring References: Message-ID: Peter Otten wrote: >>>> class frankenstring(StringIO): > ... def next(self): > ... c = self.read(1) > ... if not c: > ... raise StopIteration > ... return c Repeated read(1) on a file-like object is one of the ways of doing it with existing tools I labelled "clumsy" in the original posting ;o) Thanks anyway. -- Thomas From rkern at ucsd.edu Wed Jul 20 21:15:05 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 18:15:05 -0700 Subject: interactive python session spool/save-log command? In-Reply-To: <1121907960.539100.146940@z14g2000cwz.googlegroups.com> References: <1121907960.539100.146940@z14g2000cwz.googlegroups.com> Message-ID: S. M. Tuttle wrote: > I'm going to be teaching an introductory course on Python > in the Fall, so I am hurriedly trying to both learn > Python and prepare the course during the next few weeks. > > I'm curious if there is a command that allows everything from > that point on in a python interactive session to be > saved/spooled/forked/logged into a text file of the user's choice. IPython is an interactive interpreter that will log all input to a file. http://ipython.scipy.org/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rupole at hotmail.com Thu Jul 14 12:36:31 2005 From: rupole at hotmail.com (Roger Upole) Date: Thu, 14 Jul 2005 12:36:31 -0400 Subject: 2.4 Recent File list not working References: Message-ID: <42d695a6$1_2@spool9-west.superfeed.net> There was a bug in MFC 7 that prevented Pythonwin from closing properly. Build 204 of Pywin32 has a workaround, but I'm not sure if it's been incorporated into ActiveState's distribution yet. Roger "Larry Bates" wrote in message news:mO2dnRFyjPfb7EjfRVn-2g at comcast.com... >I recently upgraded from 2.2 to 2.4 (ActiveState for Windows). > I was accustomed to having the most recent 10 files that I had > edited show up under File menu under Recent. After upgrading > these don't seem to be saved after exiting. I tried changing > the number in the Preferences, but nothing seems to do any > good. > > Has anyone else had this problem? Any ideas how I might fix > it? > > Thanks in advance for your assistance. > Regards, > Larry Bates ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From paul at boddie.org.uk Sun Jul 3 18:21:24 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Jul 2005 15:21:24 -0700 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: <5339b60d.0507031421.3efa00c@posting.google.com> D H wrote in message news:... > Dave Benjamin wrote: > > Someone in the audience surprised everyone by mentioning an actual project > > attempting this, called javaclass: > > Sounds like it really is converting java classes to python classes, Yes, it is converting Java classes to Python classes at runtime using an import hook, in fact. > which are very different things. Lot of limitations mentioned such as: > "It runs on the Python runtime which does not have the security, > threading and just-in-time compiler features that people enjoy about > Java runtimes" The conversion done by javaclass relies on various limitations around the Java class model compared to its Python counterpart (eg. single vs. multiple inheritance), various things where the Python runtime is a lot less fussy about classes and objects than the Java runtime is (eg. the various low-level type-specific operations which can each be mapped to the same Python bytecode), but also upon the similarities that one would expect between any two mainstream virtual machines. Python virtual machine instructions are more general than many Java virtual machine instructions, but providing that the semantics are preserved this should/does make the hosting of Java code easier/possible. Things like security and just-in-time compilation are arguably orthogonal to replicating the semantics of most Java code, and since the Python runtime is more conservative about concurrency, threading becomes more of a performance/latency concern - again, an orthogonal issue. For the proposal of javaclass and similar schemes as usable tools, however, I would personally worry more about matching the exception handling and import semantics of the two language systems - those being things that have arisen as problems "on the ground". Paul From rkern at ucsd.edu Thu Jul 7 15:36:52 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 07 Jul 2005 12:36:52 -0700 Subject: Favorite non-python language trick? In-Reply-To: <87ll4ix0id.fsf@titan.staselog.com> References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> <87hdf8ync5.fsf@titan.staselog.com> <87ll4ix0id.fsf@titan.staselog.com> Message-ID: Edvard Majakari wrote: > Simon Brunning writes: > >>http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb > > Neat. > > I guess about 75% about programming-related things classified as neat-o or > "convenient!" are already implemented by some Pythonista(s). Spoils all the > fun for reinventing the wheel, doesn't it. :) Doesn't seem to stop most Pythonistas from trying, though. :-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From cyril.bazin at gmail.com Mon Jul 25 12:48:15 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Mon, 25 Jul 2005 18:48:15 +0200 Subject: First app, thanks people In-Reply-To: <42e4eff3$1@griseus.its.uu.se> References: <42e4eff3$1@griseus.its.uu.se> Message-ID: In case you want some advises for your code: -backslashes are not necesseary when you declare list or dict on many lines. I didn't pay attention at the semantic of your code, but after giving a quick look, you can simplify things like: BRUSHSTYLENAMES = ['Transparent', 'Solid', 'BDiagonalHatch', 'CrossDiagHatch', \ 'FDiagonalHatch', 'CrossHatch', 'HorizontalHatch', 'VerticalHatch' ] BSTYLES = { BRUSHSTYLENAMES[0]: wxTRANSPARENT, \ BRUSHSTYLENAMES[1]: wxSOLID, \ BRUSHSTYLENAMES[2]: wxBDIAGONAL_HATCH, \ BRUSHSTYLENAMES[3]: wxCROSSDIAG_HATCH, \ BRUSHSTYLENAMES[4]: wxFDIAGONAL_HATCH, \ BRUSHSTYLENAMES[5]: wxCROSS_HATCH, \ BRUSHSTYLENAMES[6]: wxHORIZONTAL_HATCH, \ BRUSHSTYLENAMES[7]: wxVERTICAL_HATCH } BRUSHSTYLES = [ wxTRANSPARENT, wxSOLID, wxBDIAGONAL_HATCH, wxCROSSDIAG_HATCH, \ wxFDIAGONAL_HATCH, wxCROSS_HATCH, wxHORIZONTAL_HATCH, wxVERTICAL_HATCH ] By writing something like : BRUSHSTYLENAMES = ['Transparent', 'Solid', 'BDiagonalHatch', 'CrossDiagHatch', 'FDiagonalHatch', 'CrossHatch', 'HorizontalHatch', 'VerticalHatch' ] BRUSHSTYLES = [ wxTRANSPARENT, wxSOLID, wxBDIAGONAL_HATCH, wxCROSSDIAG_HATCH, wxFDIAGONAL_HATCH, wxCROSS_HATCH, wxHORIZONTAL_HATCH, wxVERTICAL_HATCH ] BSTYLES = dict(zip(BRUSHSTYLENAMES, BRUSHSTYLES)) Or by declaring the dict BSTYLES first and then doing "BRUSHSTYLENAMES, BRUSHSTYLES=BSTYLES.items()" (In this case, the lists will not be ordered) Moreover, wxPython should be better called wx.Python now. ;-) You shouldn't use: from wxPython.wx import * But import wx and then calling wx.Brush instead of wxBrush, wx.SOLID instead of wxSOLID, etc Except these little things, if your code works, it's perfect! I told you these advises to improve your way of coding in Python ;-) Cyril -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Jul 21 17:14:19 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Jul 2005 17:14:19 -0400 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu><8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: "Steven D'Aprano" wrote in message news:pan.2005.07.21.15.43.28.56459 at REMOVETHIScyber.com.au... > On Thu, 21 Jul 2005 10:27:24 -0400, Bill Mill wrote: > > [snip] > >> I said the *builtins* section. I think you learn pretty quick that >> figuring out what functions are builtins is pretty important in every >> language. There's a fair number of people out there giving the advice >> to read chapter 2 of the library reference cover-to-cover for a good >> starter on python. Including me. > > Sure. But for a beginner to start learning the language by reading the > language manual is a bit much to ask. Sure, but who is suggesting that. Suggesting that people specifically read chapter 2 of the Library manual (but only that to start -- I probably have still not read every chapter yet) is quite different. > There is no need to get defensive, I was merely commenting on the need to > understand that inexperienced programmers often don't know enough about > the language to know where to start looking for the answer. Which is precise why I try to help by telling them where to start. A large number of beginner queries posted here are answered in the builtins chapter. Terry J. Reedy From godoy at ieee.org Sun Jul 31 18:34:00 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 31 Jul 2005 19:34:00 -0300 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <861x5ehk4g.fsf@bhuda.mired.org> Message-ID: Cliff Wells wrote: > Well, I think this exposes one of the more interesting sides of open > source software in general. For better or worse, you get choices. If > you don't like choice, you won't like open source. Many choices is > sometimes great, sometimes annoying, but the bottom line is that very > little is spoon-fed to you, and choice and flexibility are the primary > reasons most people choose open source (this was the overwhelming > verdict of a survey SuSE took a while ago). You can't even *run* Linux > without making a few basic choices (Which distro? Which architecture? > Which GUI? etc). If you really expect this to change then I expect > there are many frustrating days ahead for you. I think most end users > of Linux wish that the GNOME and KDE teams would merge (and there would > be a great benefit, I expect, in reduced duplication of effort), but > quite frankly, it ain't gonna happen, and quite probably there would be > a lot of downsides to such an event as well. I agree with you. And having choices is what is good, specially because there is no single solution for all problems. And I find it great to have this freedom to choose specially because not everybody share the same aesthetics idea. What some people find beautiful I don't like and vice-versa. -- Jorge Godoy From google0 at lazytwinacres.net Tue Jul 26 04:46:24 2005 From: google0 at lazytwinacres.net ('Dang' Daniel Griffith) Date: Tue, 26 Jul 2005 04:46:24 -0400 Subject: pyparsing 1.3.2 released References: Message-ID: <1122367582.3373a2ede6967f8dcef2bff23a4aa348@teranews> On 24 Jul 2005 17:27:07 -0700, "Paul McGuire" wrote: >Well, here we are, and I'm announcing the 1.3.2 release, with some >changes that I'd like to get released quickly. Here is the excerpt >from the change log: > ...snip... I did a quick check with my Delphi DFM parser, and they seem to work fine. Keep up the good work! --dang From peter at engcorp.com Fri Jul 29 17:10:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 17:10:40 -0400 Subject: Adding code and methods to a class dynamically In-Reply-To: References: Message-ID: Sarir Khamsi wrote: > Peter Hansen writes: >>I'm not sure what "completion" means in this case, and I'm not aware >>of any "command-line completion" support in cmd.Cmd though it may well >>be there, so I can't say. Certainly there is nothing in any way >>different about the new attribute created by the alias code, as both >>it and the original attribute are bound to exactly the same method. > > If you have the readline module, you get TAB command completion for > free (a la bash, emacs, etc)...or maybe readline only gives you > emacs-style command history editing, or both...not sure. Cool. The answer to whether a particular approach preserves command completion ability then, unfortunately, depends on how it's implemented. If it's totally dynamic, then the aliases my approach created will be supported, but if it's done at Cmd creation time, or in some other static manner, the dynamically created aliases won't be found. -Peter From skip at pobox.com Mon Jul 4 11:05:19 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 4 Jul 2005 10:05:19 -0500 Subject: Where can I get the new version of python-mode for emacs? In-Reply-To: References: Message-ID: <17097.20527.819838.801115@montanaro.dyndns.org> Marcio> I have version 4.70 installed in my debian system (installed Marcio> with apt-get, so I don't know where the sources are from). After Marcio> reading the thread_ at sourceforge, I did a google search for Marcio> "python emacs" and found the `Emacs goodies`_ page at python.org Marcio> .. _`Emacs goodies`: http://www.python.org/emacs/ Marcio> where I was redirected to the `python-mode`_ page at Marcio> SourceForge. There I could only find version 1.0alpha (4.6) (the Marcio> one said too old in the thread_) I haven't done a release in a long while. Guess it's about time to do that again. In the meantime, you can download the currently most recent version of python-mode.el from here: http://cvs.sourceforge.net/viewcvs.py/*checkout*/python-mode/python-mode/python-mode.el?rev=4.75 You can browse all the files in the CVS repository here: http://cvs.sourceforge.net/viewcvs.py/python-mode/python-mode/ Skip From peter at engcorp.com Sat Jul 9 14:16:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Jul 2005 14:16:11 -0400 Subject: About undisclosed recipient In-Reply-To: <1120925091.660129.307800@g49g2000cwa.googlegroups.com> References: <1120925091.660129.307800@g49g2000cwa.googlegroups.com> Message-ID: bartek.rylko at gmail.com wrote: > Hi all, Any one got idea about how to set undisclosed recipient? I put > all recipient in BCC field while the To field don't want to leave > blank. but neither fail to place an empty email address nor i don't > want to put my own email address inside. www.bartekrr.info Judging my the page that comes up for that link, or for your other web page at bartek.webd.pl, it seems likely you are looking for this information just to increase the amount of spam the world suffers from. If that's not true, please explain why you want to send emails without the recipient names showing and without the sender showing. Otherwise I hope none of us go out of our way to help. From benji at benjiyork.com Mon Jul 25 07:40:48 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 25 Jul 2005 07:40:48 -0400 Subject: regarding porting to windows. In-Reply-To: <20050725090310.61441.qmail@web8506.mail.in.yahoo.com> References: <20050725090310.61441.qmail@web8506.mail.in.yahoo.com> Message-ID: <42E4CFC0.6090109@benjiyork.com> prakash reghate wrote: > I am also working on *porting C PROGRAMS to windows from Linux *, but i > doesn't get any clue yet. > > I have some C - programs written on Linux & i have to port it on windows . This list is about Python, not C. If you have some C Python extensions you wish to port, I'm sure someone would be able to help, but they'll need better information about what your specific question is. Perhaps this would help: http://www.catb.org/~esr/faqs/smart-questions.html -- Benji York From mwm at mired.org Mon Jul 11 19:37:03 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 11 Jul 2005 19:37:03 -0400 Subject: __autoinit__ References: Message-ID: <86ll4csyn4.fsf@bhuda.mired.org> "Ralf W. Grosse-Kunstleve" writes: > --- Bengt Richter wrote: >> No, that limitation wouldn't exist, so you wouldn't have to explain it ;-) >> I.e., the above would act like >> >> class Foo: >> x = Bar() >> def method_1(self, _anonymous_arg_1): >> x.y = _anonymous_arg_1 >> >> and would do whatever it would do now (probably look for a global x or a >> closure cell x, but >> it wouldn't find the class variable in a normal method call) > > I am a bit afraid of opening a door for weird side effects. E.g. > > class unrelated: pass > u = unrelated() > > class grouping: > def __init__(self, self.x, u.y, self.z): > pass > > Is this really a good thing to allow? I am afraid it will be abused. My prime > concern was to provide a good solution for a very common problem. If we stray > too far from this most important goal we may get nothing in the end. Remember that what we're suggesting is just syntactic sugar. You can abuse things the same way by writing: class grouping: def __init__(self, self.x, u_y, self.z): u.y = u_y del u_y pass Why is this acceptable, but your usage not? > "self" (or whatever people prefer as a name for the first argument of a bound > function) *is* special. I think therefore it deserves special support. Yes, but is it special enough to justify adding a special case to another construct? I'm not sure I like the idea of allowing "self.x" yet. But if you're going to allow it, I don't think it should be restricted. The question is - how far are you really willing to carry this? What do you think of allowing arbitrary lvalues, with the assumption that the previous arguments are all defined (ala let*)? So you could do: class grouping: def __init__(self, x, x['abc']): pass http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From paul at boddie.org.uk Sun Jul 10 09:38:06 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Jul 2005 06:38:06 -0700 Subject: Yet Another Python Web Programming Question References: Message-ID: <5339b60d.0507100538.4698bfc7@posting.google.com> "Robert Brewer" wrote in message news:... > Daniel Bickett wrote: > > I neglected to mention an important fact, and that is the fact that I > > am limited to Apache, which elminates several suggestions (that are > > appreciated none-the-less). > > Do you have access to mod_python, mod_rewrite, FastCGI, or SCGI? Then > CherryPy 2.1 is still a great option for you with Apache: > http://www.cherrypy.org/wiki/WSGIServers > http://www.cherrypy.org/wiki/BehindApache According to the "quick facts" page [1] "CherryPy powered web applications are in fact stand-alone Python applications embedding their own multi-threaded web server", suggesting that if the hosting environment is "limited to Apache" and if this can also be taken to mean that the environment doesn't permit long-running server processes apart from Apache, then CherryPy isn't likely to be suitable. Karigell was also mentioned, but according to the documentation ("Working with Apache or Xitami" [2]) "Apache will be used as a proxy between the client and the built-in server, so you have to configure Apache so that it sends the requests to the built-in server", also suggesting that in limited hosting environments Karigell won't be suitable either. Spyce, on the other hand, seems to work with mod_python, although I agree with Andrew Clover that the inquirer probably knows what they want to do using a "traditional" Web application programming style and doesn't need a framework which decides lots of things on their behalf. Moreover, I'd imagine that not all restrictive hosting environments make mod_python available to their clients. My meagre contribution to the genre is WebStack [3] which does run in the most plain of hosting environments (CGI) as well as others. Really intended for the writing of frameworks, the programming style might suit someone who wants to have control over the most elementary aspects of Web programming. As Andrew said, there are plenty of choices... Paul [1] http://www.cherrypy.org/wiki/CherryPyQuickFacts [2] http://karrigell.sourceforge.net/en/apache.htm [3] http://www.python.org/pypi/WebStack From tim.golden at viacom-outdoor.co.uk Tue Jul 12 11:28:47 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 12 Jul 2005 16:28:47 +0100 Subject: breaking out of nested loop Message-ID: <9A28C052FF32734DACB0A288A3533991EBB9AB@vogbs009.gb.vo.local> [Jeremy Sanders] | rbt wrote: | | > What is the appropriate way to break out of this while loop | if the for | > loop finds a match? | | queue discussion why Python doesn't have a "break N" statement... Presumably you meant "cue discussion..." (Ducks & runs) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From andymac at bullseye.apana.org.au Sat Jul 9 05:25:22 2005 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 09 Jul 2005 20:25:22 +1100 Subject: PPC floating equality vs. byte compilation In-Reply-To: <1120888655.953163@yasure> References: <1120888655.953163@yasure> Message-ID: <42CF9802.2030007@bullseye.apana.org.au> Donn Cave wrote: > I ran into a phenomenon that seemed odd to me, while testing a > build of Python 2.4.1 on BeOS 5.04, on PowerPC 603e. > > test_builtin.py, for example, fails a couple of tests with errors > claiming that apparently identical floating point values aren't equal. > But it only does that when imported, and only when the .pyc file > already exists. Not if I execute it directly (python test_builtin.py), > or if I delete the .pyc file before importing it and running test_main(). > > For now, I'm going to just write this off as a flaky build. I would > be surprised if 5 people in the world care, and I'm certainly not one > of them. I just thought someone might find it interesting. I have a faint recollection of seeing other references to this on other platforms. That faint recollection also seems to point to it being something to do with the marshalling of floats (.pyc files contain constants in a marshalled form). Don't think I've ever seen it myself... ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From smitty_one_each at bigfoot.com Thu Jul 7 06:47:54 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Thu, 07 Jul 2005 06:47:54 -0400 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> Message-ID: <87oe9e28px.fsf@bigfoot.com> >>>>> "Michael" == Michael Hoffman writes: Michael> Greg Lindstrom wrote: >> I hear that Perl 6 is going to have a rewrite of regular >> expressions; it will be interesting to see what their hard work >> produces. Michael> From what I saw a while ago, it didn't look like it Michael> would be any simpler or more elegant. But that was a Michael> while ago. -- Michael Hoffman Oh, come on: what's a Perliodic Table of Operators, between friends? http://www.ozonehouse.com/mark/blog/code/PeriodicTable.html R, C From python at rcn.com Sat Jul 16 06:11:34 2005 From: python at rcn.com (Raymond Hettinger) Date: 16 Jul 2005 03:11:34 -0700 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: <1121508694.577485.257020@g14g2000cwa.googlegroups.com> Wow, that was the most thorough answer to a comp.lang.python question since the Martellibot got busy in the search business. From mark.english at liffe.com Tue Jul 19 03:58:34 2005 From: mark.english at liffe.com (MarkE) Date: 19 Jul 2005 00:58:34 -0700 Subject: Windows command line problem In-Reply-To: <1121726398.861595.31350@g43g2000cwa.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> <1121726398.861595.31350@g43g2000cwa.googlegroups.com> Message-ID: <1121759914.689112.272530@z14g2000cwz.googlegroups.com> I'm using getopt. I doubt getopt recognises \x96 as a command line parameter prefix. I suppose I could iterate over sys.argv doing a replace but that seems messy. I'd rather understand the problem. That said, and me not understanding code pages that much, I chcp'd the machines it works on both coming back with 850, chcp'd the machine it wasn't working on which also came back with 850, but then again the machine where it wasn't working now works. So now it's an intermittent bug. Great. I'll try messing with code pages later and report back if I get anywhere. I need more coffee before I can do anything remotely clever. Damn you windows and your lack of a need for coffee From oshecho at gmail.com Mon Jul 11 11:39:30 2005 From: oshecho at gmail.com (Echo) Date: Mon, 11 Jul 2005 11:39:30 -0400 Subject: Getting files in a subdirectory in a zip Message-ID: <910885da0507110839da0edcc@mail.gmail.com> What would the best way to get a list of files in a subdirectory in a zip? The only thing I can come up with is to extract the zip into a temp directory and then just grab the list of files in the subdirectory that I need. This way seems very messy to me and I was wondering if there are any better ways. -- -Echo From cowie.rob at gmail.com Fri Jul 22 11:17:55 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 22 Jul 2005 08:17:55 -0700 Subject: Separation of Code in CGI App In-Reply-To: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> References: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> Message-ID: <1122045475.402933.246760@z14g2000cwz.googlegroups.com> So, do I separate out whatever code I want to into .py modules, then have the cgi script import them, and utilise them as required? If so, do I need to put these modules somewhere described in the System Path? Can I modify the PATH at runtime to point to my modules? How? Cheers for being patient! From cam.ac.uk at mh391.invalid Sun Jul 31 09:23:44 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 31 Jul 2005 14:23:44 +0100 Subject: keylogger in Python In-Reply-To: <1122785344.538363.122600@g49g2000cwa.googlegroups.com> References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> Message-ID: Jay wrote: > yo, thanks for the great input. And the only reason i want to create a > python based keylogger is because there is none. Just a fun project... > But im gonna do some more research on the keyboard drivers and stuff > like that and to learn how to attach my python porgrams into the > sub-processes so that it would instead log every char instead of just > char in the IDE. I think this is going to be much harder than you think, and I imagine this will only end in frustration for you. You will not be able to do it well with just Python. I would recommend a different fun project. -- Michael Hoffman From jepler at unpythonic.net Fri Jul 15 21:52:19 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 15 Jul 2005 20:52:19 -0500 Subject: ssh popen stalling on password redirect output? In-Reply-To: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> Message-ID: <20050716015216.GA16477@unpythonic.net> In your ssh configuration, specify something like PreferredAuthentication "hostbased,publickey" this will skip trying to use the methods called keyboard-interactive and password. You can give this flag on the ssh commandline, too. read the ssh(1) and ssh_config(5) manpages for more information. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From huron at sopinspace.com Mon Jul 4 08:07:35 2005 From: huron at sopinspace.com (Huron) Date: Mon, 04 Jul 2005 14:07:35 +0200 Subject: python project layout References: <9JqdnRP9IqxM_ljfRVn-rA@powergate.ca> Message-ID: Hi Peter, Thanks for you detailed reply. The layout that you suggest sounds wise to me (I'm about to start a project). I confess that, coming from the java world, I've trouble to move away from the paradigm "one class" = "one file" ... and to gather things inside "python modules" ... -- huron From simon.dahlbacka at gmail.com Mon Jul 18 03:07:01 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 18 Jul 2005 00:07:01 -0700 Subject: Efficiently Split A List of Tuples In-Reply-To: References: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> Message-ID: <1121670421.128485.262420@g47g2000cwa.googlegroups.com> Oooh.. you make my eyes bleed. IMO that proposal is butt ugly (and looks like the C++.NET perversions.) From elmo13 at jippii.fi Sun Jul 24 08:13:33 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Sun, 24 Jul 2005 15:13:33 +0300 Subject: How can I get an sha1 hash in base32? References: Message-ID: On Sat, 23 Jul 2005 23:27:44 +0200, Marc 'BlackJack' Rintsch wrote: > In , Elmo M?ntynen wrote: > >> I know how to make a hash(using mhash), but instead of encoded as hex I >> want it in base32 for use with the bitzi catalog. python-bitzi is useful >> but way too slow for just getting the hash of a file(am going to use it >> elsewhere). Thanks. > > Doesn't Bitzi calculate some kind of audio fingerprint? Just a hash of > the file would result in very different hash values for different codecs, > bitrates etc. for the "same" audio data. > > Ciao, > Marc 'BlackJack' Rintsch I don't think it does, but musicbrainz is designed for just that, and there's a ptyhon binding for using the libs. Elmo From roy at panix.com Sun Jul 3 18:02:19 2005 From: roy at panix.com (Roy Smith) Date: Sun, 03 Jul 2005 18:02:19 -0400 Subject: looping over a big file References: <11cgnhp3j4th442@corp.supernews.com> Message-ID: "martian" wrote: > 1) how does python handle: > > > for line in big_file: > > is big_file all read into memory or one line is read at a time or a buffer > is used or ...? The "right" way to do this is: for line in file ("filename"): whatever The file object returned by file() acts as an iterator. Each time through the loop, another line is read and returned (I'm sure there is some block-level buffering going on at a low level). > 2) is it possible to advance lines within the loop? The following doesn't > work: > > > for line in big_file: > line_after = big_file.readline() You probably want something like: for line in file ("filename"): if skipThisLine: continue From luismgz at gmail.com Tue Jul 19 12:23:50 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 19 Jul 2005 09:23:50 -0700 Subject: python certification In-Reply-To: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> Message-ID: <1121790230.580130.156410@o13g2000cwo.googlegroups.com> lordverminard at gmail.com wrote: > i want to get a small certificate or diploma in python. > it should be online cuz i live in pakistan and wont have teast centers > near me. > it should be low cost as i am not rich. > and hopefully it would be something like a a begginer certification cuz > i am new to python. Hmm... I think I can help you. By the way, how much are you willing to spend? You know, getting a high grade is also important...:-) From cam.ac.uk at mh391.invalid Fri Jul 22 03:24:22 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 08:24:22 +0100 Subject: Difference between " and ' In-Reply-To: <42E05106.5060905@REMOVEMEcyber.com.au> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Michael Hoffman wrote: > >> John Machin wrote: >> >>> b83503104 at yahoo.com wrote: >>> >>>> Can someone tell me the difference between single quote and double >>>> quote? >>> >>> >>> ord("'") - ord('"') >>> 5 >> >> Very zen. > > But unfortunately incorrect, since the original poster didn't ask for > the difference between the ordinal values of the single quote and double > quote characters, but for the difference between the characters themselves. It reminded me of a zen koan, because although it was a joke at the expense of original poster, the true answer was still contained within when the answerer had to use different kinds of quoting to quote single and double quotes. -- Michael Hoffman From peterbe at gmail.com Tue Jul 19 07:01:05 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 19 Jul 2005 04:01:05 -0700 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121770797.568838.42680@g43g2000cwa.googlegroups.com> A lot of people swear by WingIDE and as an IDE I think it's the best one there is. (Personally I prefer jed or xjed but that's because I like to work that way) From gsakkis at rutgers.edu Thu Jul 21 22:20:26 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 21 Jul 2005 22:20:26 -0400 Subject: Returning histogram-like data for items in a list References: <1121991583.d3afc1984aea914bde79a8c890963f28@teranews> <1121995313.145791.167950@o13g2000cwo.googlegroups.com> Message-ID: <1121998838.92d508328fb805e976133fa58048e8f8@teranews> "jeethu_rao" wrote: > Adding to George's reply, if you want slightly more performance, you > can avoid the exception with something like > > def hist(seq): > h = {} > for i in seq: > h[i] = h.get(i,0)+1 > return h.items() > > Jeethu Rao The performance penalty of the exception is imposed only the first time a distinct item is found. So unless you have a huge list of distinct items, I seriously doubt that this is faster at any measurable rate. George From lbates at syscononline.com Wed Jul 13 09:09:40 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 13 Jul 2005 08:09:40 -0500 Subject: Building a function call? In-Reply-To: References: Message-ID: Normally when I want to do what you describe I want to do it for several functions not just a single one. You can use a dictionary to hold the function names and pointers to the functions themselves and then call them by indexing into the dictionary. This works for me: def dothat(x,y): print "x=", x, " y=", y return def doanother(x, y, z): print "x=", x, " y=", y, " z=", z return xdict={'dothat': dothat, 'doanother': doanother} s='dothat' t=(1,2) xdict[s](*t) results in: x= 1 y= 2 s='another' t=(1,2, 3) xdict[s](*t) results in: x= 1 y= 2 z=3 Larry Bates Francois De Serres wrote: > Hiho, > > Having a string: "dothat" > and a tuple: (x, y) > 1. What's the best way to build a function call like: dothat(x,y)? > > Assuming dothat is def'd in the same module, > 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200))) > the right way to have it executed? > > If dothat is def'd in another module: > 3. what would be the right way to initialize the globals to pass to eval ? > > > TIA, > Francois > > From rkern at ucsd.edu Thu Jul 21 12:59:04 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 21 Jul 2005 09:59:04 -0700 Subject: What does "::" mean? In-Reply-To: References: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Message-ID: Michael Hoffman wrote: > Robert Kern wrote: >>Well, that part's easy at least: >> >> live[::-1] >> >>:-) And so the circle is complete ... > > What about reversed(live)? Or if you want a list instead of an iterator, > list(reversed(live))? That's fine if you want to iterate over it. Often, especially with strings, you just want an object of the same type back again. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From lambacck at computer.org Tue Jul 19 07:53:39 2005 From: lambacck at computer.org (Chris Lambacher) Date: Tue, 19 Jul 2005 07:53:39 -0400 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <20050719115339.GB1166@computer.org> I use Vim. It does code completion and jump to variable/function definition. Emacs does this too. You just need to read the documentation about on how to set this up to your liking. The only feature that Vim does not have that I would like is the function argument pop up, but I want that more for C than Python. It looks like Vim 7 is supposed to have this. If you are afraid of Vim, you might want to try cream: http://cream.sf.net -Chris On Mon, Jul 18, 2005 at 10:32:43PM -0700, linuxfreak wrote: > Hi guys, > Got going with python...and i must say its a pretty cool language. > Been using Xemacs to write me programs. But I want an IDE that would > give me auto-completion, online help and the like... Tried SPE and > Dr.Pyhton but the former crashes regulary and the latter is quite > unweildy and does not have a great many features. I quite like the UML > feature found in SPE but the damn thing crashes way too often. What are > you guys using and what do you think is the best IDE...or should i > stick with Xemacs/emacs??? > > -- > http://mail.python.org/mailman/listinfo/python-list From horedson at earthlink.net Tue Jul 12 19:37:33 2005 From: horedson at earthlink.net (Hank Oredson) Date: Tue, 12 Jul 2005 23:37:33 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> Message-ID: <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> "edgrsprj" wrote in message news:pmXAe.9096$aY6.3897 at newsread1.news.atl.earthlink.net... > "Hank Oredson" wrote in message > news:7%UAe.4148$BK1.174 at newsread3.news.pas.earthlink.net... >> "edgrsprj" wrote in message >> news:upBAe.1915$oZ.930 at newsread2.news.atl.earthlink.net... >> > "edgrsprj" wrote in message >> > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... >> >> PROPOSED EARTHQUAKE FORECASTING >> >> COMPUTER PROGRAM DEVELOPMENT EFFORT > >> What observational data are used? >> What are the sources of that observational data? >> How are those sources accessed? >> Is there a database to hold historical plus current data? >> If so, is it centralized or distributed? >> >> The project might be of interest if the data sources are >> rich enough, complete enough, and current enough. >> > > July 12, 2005 > > Thanks for the response and questions. > > The following are my personal opinions on this. > > Briefly, the amount of data available for this type of effort is > virtually limitless. And more of those data than most people could even > deal with can be obtained for free. I guess my question was not specific enough. What I wanted was the exact sources, so I could access the data. The exact data sets you used. > You don't have to build a new laboratory filled with expensive equipment. > > A reasonably powerful computer, > Access to the Internet, > At least some knowledge of science > Some computer programming ability > And a little imagination I'm a retired physicist with a great deal of experience in data transformation, verification and analysis. Also plenty of computers. Fast internet connection. > Are all that are required. I have all those things. > Researchers have been attempting to do this type of work for > probably > as far back as we have historical records. The reason that previous > efforts > that I am aware of have not been successful is because two key discoveries > needed to be made. They are referred to on my 90-05.html Web page as the > "Gravity Point" and "Earthquake Triggering Symmetry." Now that those > discoveries have been made the door should be open to tremendously rapid > advances in our understanding of how and why earthquakes occur and how to > forecast them. References please, I found some simple description, but no mathematics or references to the data sets used or the equations you used to do your analysis. Point me to that stuff. > Much of this research could be easily done by computer programmers. > You don't need to be a geophysicist. If the data you are generating look > statistically significant then they are probably important whether or not > you actually understand the geophysical theories behind them. No problem understanding the physics (geo or otherwise). No problem writing software to do the analyses. Might even be fun. > To actually forecast earthquakes using the procedure I have > developed > you need both warning signal data and earthquake data along with some > ocean > tide and Solid Earth Tide data. But one of the really great parts of this > particular research project is the fact that many of the basic discoveries > can be made by simply comparing earthquakes with one another. You don't > need any warning signal data at all. And there is certainly no shortage > of > earthquake data! Yes, I understand all that. Where are the data sets? Where is the description of the "procedure"? URLs would be nice, journal article references are ok. > At my Web site there is a discussion of a concept called "Earthquake > Pairs." They are two or more earthquakes which were apparently triggered > in > the same manner. My data indicate that the two highly destructive 1998 > earthquakes in Afghanistan would represent an Earthquake Pair. And the > two > highly destructive 1999 earthquakes in Turkey would represent another > pair. > Important discoveries can be made by determining what the similarities are > between the two or more earthquakes in an Earthquake Pair and how they > differ from other earthquakes. And since the group of earthquake warning > signals that I am presently working with is being controlled by the same > forces that are responsible for earthquake triggering, significant > discoveries regarding earthquake triggering processes could be immediately > applied to forecasting efforts. I would rather do my own data analysis, but for me to do that there must be published data sets, that I can use. Doing the various coorelations, power spectra, convolutions is easy. So what is needed is the data sets, and the specific things you think make prediction possible. Then I can test those things, along with others that I might find interesting. > One of the reasons that geologists have not yet taken an interest in > this particular effort could be because it is heavily reliant on celestial > mechanics. And most geology researchers appear to me to prefer to focus > on > measuring forces within the ground. I presently suspect that astronomers > would be a more likely group to take an interest in this science at first. > And I am planning to contact some of them about that. So point me to the equations then. Doing some analysis sounds like fun. Celestial mechanics is no problem, easy stuff. There is a copy of Bowditch on the shelf over there. I know a good astrologer. Also several astronomers. But which exact data sets did you use? -- ... Hank http://home.earthlink.net/~horedson http://home.earthlink.net/~w0rli From jorge at bcs.org.uk Fri Jul 8 10:26:06 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Fri, 8 Jul 2005 15:26:06 +0100 Subject: Learning Python - IM Wiki Message-ID: Hello, I am a Java Developer that has been learning Python by doing simple things. I am loving this initial vibe I'm getting out of Python. However, because I feel programmers of a certain languages bring with them certain vices when moving to other languages, I'd like to have feedback from seasoned Python programmers regarding my code. Using some socket examples I've googled here and there I wrote a very simple Instant-Messaging-wannabe program. Is there some sort of a Wiki where I could post the code and have advice on what, how and where to improve? Or should I post the code it here? Actually, I'll post it below and if anyone knows of a better place to do something like this I'll do it there. Next I'm changing the client to include a server thread listening instead of polling the server. Regards jorge SIMPLE IM CLIENT import socket, threading, time, msvcrt print "Please enter the following information" _url = raw_input("URL: ") _port = raw_input("Port: ") print "Starting IIM client on port: " + _port socketOut = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socketOut.connect((_url, int(_port))) # clear screen here print "Enter your user details" _from = raw_input("User id: ") _to = raw_input("Buddy id: ") print '\n' print "Connecting to server..." print '\n' # send user details and receive response socketOut.sendall('@@@'+_from+'##'+_to) response = socketOut.recv(8192) def listener(): while 1: time.sleep(5) socketOut.sendall('$$$'+_from) response = socketOut.recv(8192) if response != " ": print "\n" + response if response == 'AUTH_OK': data = "" th = threading.Thread(target=listener) th.setDaemon(1) th.start() print "Background polling thread started" while 1: if msvcrt.kbhit(): ch = msvcrt.getche() else: ch = None if ch: if ch != '\r': data += ch else: print '\n' socketOut.sendall('###'+_from+'##'+data) response = socketOut.recv(8192) if response != " ": print response data = "" else: print "Auhentication failed!" socketOut.close() SIMPLE IM SERVER import SocketServer _port = 8881 _clients = {} # a connected client class Client: # queue of messages sent to this client queue = [] def __init__(self, _sock, _src, _dest): print "Creating IM client" self.socket = _sock print "Incoming socket: %s" % self.socket self.user = _src print "Username: " + self.user # buddies should be a list self.buddy = _dest print "Buddy: " + self.buddy print "Created IM client" # the server handling requests class Broker(SocketServer.BaseRequestHandler): def handle(self): print "Connected from", self.client_address while True: receivedData = self.request.recv(8192) if not receivedData: break # if handshake packet, extract client details if receivedData.startswith('@@@',0,3): print "Received handshake packet" # strip handshake code receivedData = receivedData.replace('@@@', '', 1).lstrip() l = receivedData.split('##',1) socket = self.request src = l[0] dest = l[1] c = Client(socket, src, dest) # use username as key on hashmap _clients[src] = c # send success message socket.sendall('AUTH_OK') print "Client " + src + " authenticated" # if polling packet, extract sender details and send messages if receivedData.startswith('$$$',0,3): # strip polling message print "Received polling packet" src = receivedData.replace('$$$', '', 1).lstrip() # only poll if more than 1 user if len(_clients) > 1: # use username as key on hashmap _clients[src] = c if len(c.queue) < 1: c.socket.sendall(" ") else: msgs = "" for q in c.queue: msgs += q + '\n' # send queued messages c.socket.sendall(msgs) c.queue = [] print "Sent all pending messages for " + c.user else: socket.sendall(" ") # if message packet, extract data and append to target queue if receivedData.startswith('###',0,3): print "Received message packet" receivedData = receivedData.replace('###', '', 1).lstrip() l = receivedData.split('##',1) src = l[0] text = l[1] if text.strip != "": print "Message not empty" # extract client clientSrc = _clients[src] # ...and its buddy clientDest = _clients[clientSrc.buddy] msg = src+": "+text print "Appended message to queue of " + clientSrc.buddy clientDest.queue.append(msg) print "Queue of: " + clientDest.user + " = %s" % clientDest.queue clientDest.socket.sendall(" ") else: if len(_clients) < 2: self.request.sendall(receivedData) for c in _clients.values(): if self.request == c.socket: c.socket.close() # remove from hashmap del _clients[c.user] print "Removed " + c.user + " from hashmap" print "Disconnected from", self.client_address srv = SocketServer.ThreadingTCPServer(('',_port),Broker) print "Started IIM server on port %d" % _port srv.serve_forever() -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Fri Jul 1 18:28:54 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 1 Jul 2005 18:28:54 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: Message-ID: <20050701222854.26278.1752403490.divmod.quotient.3933@ohm> On Fri, 01 Jul 2005 20:36:29 GMT, Ron Adam wrote: >Tom Anderson wrote: > >> So, if you're a pythonista who loves map and lambda, and disagrees with >> Guido, what's your background? Functional or not? > >I find map too limiting, so won't miss it. I'm +0 on removing lambda >only because I'm unsure that there's always a better alternative. > >So what would be a good example of a lambda that couldn't be replaced? lambda can always be replaced. Just like a for loop can always be replaced: iterator = iter() while True: try: = iterator.next() except StopIteration: break else: Let's get rid of for, too. Jp From rootrot at govtabuse.com Sat Jul 30 00:38:36 2005 From: rootrot at govtabuse.com (James Richards) Date: Sat, 30 Jul 2005 04:38:36 GMT Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42ead151@nntp0.pdx.net> Message-ID: On 2005-07-30, Scott David Daniels wrote: > Christopher Subich wrote: >> g = >> g(1) == 1 >> >> Basically, I'd rewrite the Python grammar such that: >> lambda_form ::= "<" expression "with" parameter_list ">" >> >> Biggest change is that parameter_list is no longer optional, so >> zero-argument expr-comps would be written as , which makes >> a bit more sense than . >> >> Since "<" and ">" aren't ambiguous inside the "expression" state, this >> shouldn't make the grammar ambiguous. The "with" magic word does >> conflict with PEP-343 (semantically, not syntactically), so "for" might >> be appropriate if less precise in meaning. > > What kind of shenanigans must a parser go through to translate: > < > > this is the comparison of two functions, but it looks like a left- > shift on a function until the second with is encountered. Then > you need to backtrack to the shift and convert it to a pair of > less-thans before you can successfully translate it. I'm just worming my way into learning Lisp, but this seems to be a perfect example of everything I'm seeing so far. The compiler should do all sorts of gymnastics and contortions. Make the compiler/interpreter as complex as possible, to handle any freaky thing a programmer can invent. Which does not, in the least, imply that the same attitude should apply toward python. I read this thread and my brain hurts. Python code should *never* do this. Tim Peters (let's all bow down, we're not worthy ) might write some code that I can't quite follow. But at least it's obvious. He doesn't suddenly introduce an entirely new syntax for the sake of "hey, this would be cool." Or maybe "It'd be much more simple if we made everyone use more C-like syntax." Or... wherever you were going with this. This > > < is precisely the kind of code that I got into python to avoid. I happen to like nice, simple, readable code. Maybe I'm just old and grumpy. Looking at that line, I get the same "This is just ugly" feel that I get when I at perl. Some note from other pieces in this thread. Things about $_ or what-not. Personally, I can't recall any decent programmer I know who objects to actually writing out a variable name. In fact, I don't know a single "real" programmer (this is one who writes programs he intends to look at again in, say, 3 weeks) who doesn't insist on writing "real" variable names. (Heh. I'll probably read through some Guido code next week that totally proves me wrong ...such is life). > --Scott David Daniels > Scott.Daniels at Acm.Org -- Liberty means responsibility. That is why most men dread it. - George Bernard Shaw From p at ulmcnett.com Fri Jul 22 14:45:41 2005 From: p at ulmcnett.com (Paul McNett) Date: Fri, 22 Jul 2005 11:45:41 -0700 Subject: Separation of Code in CGI App In-Reply-To: <1122054919.033091.308240@o13g2000cwo.googlegroups.com> References: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> <1122045475.402933.246760@z14g2000cwz.googlegroups.com> <1122054919.033091.308240@o13g2000cwo.googlegroups.com> Message-ID: <42E13ED5.20605@ulmcnett.com> Rob Cowie wrote: > So to be clear, if a .py module is in the same directory as my python > cgi script, I can import it thus 'import XXX.py'? Not quite. If you had a XXX.py, XXX.pyc, and/or XXX.pyo in the same directory as your Python cgi script, you'd import it by issuing: import XXX -- Paul McNett http://paulmcnett.com From claird at lairds.us Fri Jul 1 11:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 01 Jul 2005 15:08:02 GMT Subject: Question about Python References: <42c54149$1@griseus.its.uu.se> Message-ID: <7c1gp2-vd7.ln1@lairds.us> In article <42c54149$1 at griseus.its.uu.se>, Jan Danielsson wrote: >Hello all, > > I recently started using Python, and I must say I like it. Both the >language and libraries available for it. > > Background: I have written an application which I use to keep track >of my personal economy. I wrote it in Java because I wanted to learn the >language for a course in programming at my university. Now that I have >acquired an interrest in Python I was thinking about porting my program >to Python. > > But then it occured to me.. I started writing my program in Java >pre-1.5. Then came 1.5, I upgraded, and my program would still compile >and run, though I did get three warnings. The language had changed a >little bit; I had to assign a type to three arrays. That wasn't so bad. > > However, when I look at the various Python modules/libraries, I see >that there are several versions of them, for different versions of >python. I've seen everything from "for python 1.5" up to "for python >2.4" with all versions in between. This scares me a little bit. I assume >that the reason for the different versions is because of new language >features? > > Is Python showing any signs of "stabilizing"? (Yes, I know there are >pros to an evolving language). Will there ever be a time when a new >major version of python won't mean getting new versions of the modules? > > > For my economy program, I used DB2 as a database backend. I can be >reasonable sure that there will always be a DB2 API for Java. However, I >have found a DB2 module for Python, but I don't even know if it works >with Python 2.4, and if I compile and use it, I can't be sure it'll work >with the next python release, as far as I can tell. > > >I'd like to ask seasoned Python developers: >- Are you comfortable in upgrading to the latest version of Python, or >are you worried about what you have to fix in your existing programs? >- Put aside any unconditional love for Python for a second, and be >honest: Have you ever run into version related problems? >- Have you ever relied on a module, upgraded python version for some new >important feature, but realized that the module you rely on hasn't been >updated yet? If not, do you consider a possibility? >- Do the module developers, in general, keep up with the development >versions of python, so you can expect to find newly updated modules as >new versions of python hits the streets? >- Did you have similar worries to mine when you started working with Python? > > Please be honest.. It's better that I find out any potential problems >now, than rant about them in six months. . . . Very high-level response: it's not as bad as it seems. Python is in fact quite conservative, and, as a commer- cial developer, I can tell you the compatibility between versions is satisfying. There *are* issues with extensions, many of which are tied to specific releases of Python. A couple of us will probably follow-up with details. My summary, though, is: yes, while there are issues with version compatibility, they're roughly comparable to those experienced in the Java world. From reinhold-birkenfeld-nospam at wolke7.net Thu Jul 21 17:53:42 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 21 Jul 2005 23:53:42 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <3kacleFslj6sU1@individual.net> Message-ID: <3kajr8FtfejbU1@individual.net> Michael Hoffman wrote: > Reinhold Birkenfeld wrote: >> FYI: I modified the path module a bit so that it fits many of the suggestions >> from python-dev, and put the result in the Python CVS tree under >> nondist/sandbox/path. >> >> Most prominent change is that it doesn't inherit from str/unicode anymore. >> I found this distinction important, because as a str subclass the Path object >> has many methods that don't make sense for it. > > Having path descend from str/unicode is extremely useful since I can > then pass a path object to any function someone else wrote without > having to worry about whether they were checking for basestring. I think > there is a widely used pattern of accepting either a basestring[1] or a > file-like object as a function argument, and using isinstance() to > figure out which it is. Where do you see that pattern? IIRC it's not in the stdlib. > What do you gain from removing these methods? A smaller dir()? It made sense to me at the time I changed this, although at the moment I can't exactly recall the reasons. Probably as Terry said: a path is both a list and a string. Reinhold From golancester at gmail.com Wed Jul 13 10:49:02 2005 From: golancester at gmail.com (Michael Jordan) Date: 13 Jul 2005 07:49:02 -0700 Subject: String Manipulation Message-ID: <1121266142.619153.142480@g49g2000cwa.googlegroups.com> hey, i have this huge text file and i need to go through and remove all punctuation and every instance of the phrase "fruitloops=$" where $ is any number 0-100" um, and yeah this is homework but i've tried to no avail. thanks guys. cheerio :). jen From paolo.veronelli at gmail.com Wed Jul 27 15:17:08 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Wed, 27 Jul 2005 21:17:08 +0200 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: <42E7DDB4.3060100@gmail.com> Tito wrote: > Hi all: > > Is there a metalanguage capability in Python (I know there are many) to > call a function having its name in a string? > > Something like: > __call__("foo") > > instead of: > foo() > > Regards, > Tito eval('foo()') should do, but it's said a bad practice ;) From dotpyFE at gmail.com Tue Jul 12 00:09:12 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Tue, 12 Jul 2005 04:09:12 GMT Subject: Defending Python In-Reply-To: References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> <42d17b1f$0$19917$636a15ce@news.free.fr> Message-ID: Peter Hansen wrote: > Jorey Bump wrote: > >> Bruno Desthuilliers wrote: >> >>> it's. >> >> >> +1 for this becoming the official name of Python 3000. ;) >> >> And now for something completely different... >> >> The larch! > > > Sorry, already taken: > > '''Larch - John Guttag and Jim Horning . The Larch > Project develops aids for formal specifications. Each Larch > specification has two components: an interface containing predicates > written in the LIL (Larch Interface Language) designed for the target > language and a 'trait' containing assertions about the predicates > written in LSL, the Larch Shared Language common to all. "The Larch > Family of Specification Languages", J. Guttag et al, IEEE Trans Soft Eng > 2(5):24-365 (Sep 1985). "Larch: Languages and Tools for Formal > Specification", Guttag and Horning, Springer 1993.''' > > Maybe "Ni!"? > > -Peter Lumberjack?? -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From kay.schluehr at gmx.net Sun Jul 31 13:07:52 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Jul 2005 10:07:52 -0700 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> Message-ID: <1122829672.285541.45710@g43g2000cwa.googlegroups.com> Ed Leafe wrote: > On Sunday 31 July 2005 01:02, phil hunt wrote: > > > You mightn't have, but I suspect more Python programers who've > > written GUI apps have used Tkinter than any of the other APIs. > > > > Not that I'm a particular fan of it, it's just I like > > standardisation, because then you get network effects. > > At PyCon DC 2004, Guido was asked about wxPython: "wxPython is the best and > most mature cross-platform GUI toolkit, given a number of constraints. The > only reason wxPython isn't the standard Python GUI toolkit is that Tkinter > was there first." Maybe. But Guidos intention with Python was to create a secondary language originally - an extension language of C - ( unlike Java that was concepted as a radically platform independent language and a successor of C++ ). Now since Python is 15 years old, some people start learning Python as their primary language and they begin to ask why it does not support a native GUI toolkit like TCL with Tk i.e. something in it's own right with just some C-modules for interfacing with OS dependent libs ( if any - thanks to the ctypes ffi ! ) and some other extensions for optimization and maybe scintilla for pluging it in. Some other people already abandoned Python not for the worst reasons: http://www.kevin-walzer.com/pivot/entry.php?id=69 My objection with wrappers around wrappers around wrappers is that I have no hope ever watching the ground. If some error occurs, which layer has to be addressed? Which developing group is reponsible? My own or that of team A, team B, team C ... ? The baroque concept is repulsive to me and only acceptable in case of legacy code that gets wrapped around old one and is dedicated to substitute it continously. Kay From fuzzyman at gmail.com Fri Jul 29 06:41:01 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jul 2005 03:41:01 -0700 Subject: To thread or not to thread In-Reply-To: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> References: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> Message-ID: <1122633661.177820.261070@f14g2000cwb.googlegroups.com> Some people are of the opinion that threads are evil..... Best Regards, Fuzzy http://www.voidspace.org.uk/python From Holzmayer.Bernhard at deadspam.com Mon Jul 18 10:31:10 2005 From: Holzmayer.Bernhard at deadspam.com (Bernhard Holzmayer) Date: Mon, 18 Jul 2005 16:31:10 +0200 Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121691948.976027.281070@z14g2000cwz.googlegroups.com> Message-ID: I see, you're sensitive for the difficulties which might arise. That's the thing I wanted to point out. Maybe I was looking too far forward... My first thought was to add attributes/qualifiers to the operands to improve the sorting. Then I realized that these attributes/qualifiers were related to the operators, since multiplication and division use the same operands, but while in one case it is associative and commutative, it isn't in the other. I agree that all this leads too far. But one thing creeps into my mind again: I guess you'll always need an inverse operation: A class which can handle multiplication will certainly require an inverse operation like division. Bernhard From peter at engcorp.com Tue Jul 12 09:29:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Jul 2005 09:29:18 -0400 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: <3jftckFpvhv2U2@individual.net> Message-ID: (Fixed top-posting) James Carroll wrote: > On 7/11/05, Peter Hansen wrote: >>(I always have to ignore the name to think about how it works, or it >>gets in the way of my understanding it. The name makes fairly little >>sense to me.) > Notice the dictionary is only changed if the key was missing. James, I'll assume your reply was intended to address my comment above. It's not so much that the concept of "set the default value for this key" is poorly captured by the name "setdefault", but that the function is used almost exclusively in the idiom below, where it is critical that it also _returns_ the value, which is usually then operated on immediately, usually in the same line of code. dict.setdefault(key, defaultValue).someMethodOnKey() or dict.setdefault(key, defaultValue) #= value, where # is some operator. I suppose I shouldn't blame setdefault() itself for being poorly named, but it's confusing to me each time I see it in the above, because the name doesn't emphasize that the value is being returned, and yet that fact is arguably more important than the fact that a default is set! I can't think of a better name, though, although I might find "foo" less confusing in the above context. :-) -Peter From guy.lateurNNOOSSPPAAMM at pandora.be Tue Jul 5 16:42:16 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Tue, 05 Jul 2005 20:42:16 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: "guy lateur" schreef in bericht news:KUBye.138052$NA2.7367694 at phobos.telenet-ops.be... | | "Tim Williams (gmail)" schreef in bericht | news:mailman.1383.1120593403.10512.python-list at python.org... | > Could you SMTP it back in ? It would gain an extra Received: header | > but the rest of the email would most likely be unaltered. | | I don't understand what you mean. How does this have to do with connecting | to the (probably-not-running) IMAP service? | Hold on, I think I do know what you mean: using SMPT (running) instead of connecting to the IMAP service (probably-not-running). I'll let you know how I get along with that. I may still need a way to convert a DocumentItem to a MailItem, though. Cheers, g From benji at benjiyork.com Wed Jul 20 11:01:06 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 20 Jul 2005 11:01:06 -0400 Subject: Windows command line problem In-Reply-To: <1121812275.374283.224000@g47g2000cwa.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> <1121726398.861595.31350@g43g2000cwa.googlegroups.com> <1121759914.689112.272530@z14g2000cwz.googlegroups.com> <1121762108.120184.201340@g47g2000cwa.googlegroups.com> <1121812275.374283.224000@g47g2000cwa.googlegroups.com> Message-ID: <42DE6732.6020809@benjiyork.com> sp1d3rx at gmail.com wrote: > I think the lesson there is 'dont depend on getopt, write your own > command line parser'. I always write my own, as it's so easy to do. While I'll agree that getopt isn't ideal, I find optparse to be much better. -- Benji York From peter at engcorp.com Mon Jul 4 18:36:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Jul 2005 18:36:07 -0400 Subject: threads and sleep? In-Reply-To: References: Message-ID: Jeffrey Maitland wrote: > I am in the process of writing a multithreading program and what I was > wondering is a sleep command in an executing function will affect the > threads below it? Note that the "executing function" is itself running inside a thread, specifically the "main thread". The other threads are not "below" it in any particular sense, more like beside it. (Or, to put it another way, there is no such concept of relative position with threads in Python.) Here is a basic example of what I mean. [snip code] > so the question I was wondering is if the sleep will pause the t > thread as well as the main function or is the thread independat of the > main function sleep? Your code is very close to working already... why don't you just run it and observe how it works? In any case, the answer is "no, time.sleep() affects only the current thread". -Peter From algebraist at gmail.com Tue Jul 19 23:25:30 2005 From: algebraist at gmail.com (algebraist) Date: 19 Jul 2005 20:25:30 -0700 Subject: access the text being generated in other windows Message-ID: <1121829930.938089.122070@g44g2000cwa.googlegroups.com> hi, newbie question here i play poker on partypoker and ultimate bet (both of which have clients you have to download)... i was thinking of writing a program that used the hand histories these clients generate (in little text boxes within the client) is there a way python can access the text being generated in other windows, by other programs/processes? ultimatehistory.exe is an example of what i'm talking about (written in C++, i think)... it takes the text output that ultimate bet's client generates, and saves it to disk... i would like to do something similar. cheers (i'm running python 2.4 on winxp sp2 home edition) -- From no at spam Wed Jul 27 20:57:10 2005 From: no at spam (D H) Date: Wed, 27 Jul 2005 19:57:10 -0500 Subject: Rich Graphics? In-Reply-To: References: Message-ID: Cairo is an option, for Linux only though at the moment. There is a python binding: http://cairographics.org/bindings You can use it in combination with pygtk: http://cvs.cairographics.org/pycairo/examples/svg/ See also the backends used by matplotlib, a python plotting module. From bokr at oz.net Tue Jul 12 14:39:56 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 18:39:56 GMT Subject: Efficiency of using long integers to hold bitmaps References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> <42d3fced@news.rivernet.com.au> Message-ID: <42d40c70.8559137@news.oz.net> On Wed, 13 Jul 2005 03:24:48 +1000, "Jeff Melvaine" wrote: >Bengt, > >Thanks for your informative reply, further comments interleaved. Can't reply fully now, but just had the thought that maybe some ideas from 8-queens solvers might be useful or interesting. There is an old thread at http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/f88f301b7578705a that explores various ways of solving it, and uses various representations of the board, including integer bit maps at the end, which turned out fastest IIRC. I'm sure it can still be improved upon, and I'm not sure it will be worth your while to dig into it, unless you think the problem fun, but there it is. Regards, Bengt Richter From ed at leafe.com Thu Jul 7 11:34:44 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 7 Jul 2005 11:34:44 -0400 Subject: Python exception hook simple example needed In-Reply-To: <1120735672.230582.244060@g43g2000cwa.googlegroups.com> References: <1120654753.122331.109950@g43g2000cwa.googlegroups.com> <1120735672.230582.244060@g43g2000cwa.googlegroups.com> Message-ID: On Jul 7, 2005, at 7:27 AM, Fuzzyman wrote: > Do you have an exception handling dialog ? Not per se, as there hasn't been a request for one; we have several dialogs ranging from simple messages to alerts to interactive dialogs, much as wxPython offers. But I'll make this offer: give me a spec as to what you need this "exception handling dialog" to do, and I'll have it added to the framework within 24 hours. Deal? > Can you use the UI layer without being tied to the rest of the > framework ? They seemed pretty integrated to me. They are integrated, but nothing forces you to use anything you don't want. I know of several people who have developed UI-only apps, with no need for business objects or database connectivity. They started in plain wxPython, and switched to Dabo because it was so much easier, and so much more Pythonic. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From hancock at anansispaceworks.com Mon Jul 11 05:49:37 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 11 Jul 2005 04:49:37 -0500 Subject: gettext and "disambiguating comments" Message-ID: <200507110449.37703.hancock@anansispaceworks.com> I'm looking at the gettext module for the first time and learning how to write internationalized code in Python. Naturally, I also looked at the original Gnu gettext manual, which mentions that comments can be captured into the .po (.pot?) file for translators' benefit: /* Comment right before the gettext call, obviously in C */ printf(_("Apparently ambiguous string to translate")); This will get captured into the .po file, according to the gettext manual and appear as a comment right before the msgid (i.e. next to the line number reference). Is there an equivalent Python gettext idiom? I've tried the obvious # Comment right before the gettext call, now in Python print _("Apparently ambiguous string to translate") But this is ignored by both pygettext and xgettext. I also saw some discussion (from the Gnome project) about gettext variations which capture comments from within the text: _("comment for translators| Spam") But, Python's gettext happily renders the entire comment into the program, so this isn't doing anything either. Clearly, I could edit the .pot file after creation to include comments, but that's probably undesireable since the file is meant to be machine-generated. I have no pressing immediate need for this functionality (that I know of), but I'd like to understand how to access this capability if it exists. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From paolo_veronelli at tiscali.it Sun Jul 31 09:09:48 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sun, 31 Jul 2005 15:09:48 +0200 Subject: namespaces In-Reply-To: References: <42EC9690.2040301@tiscali.it> Message-ID: <42ECCD9C.1050806@tiscali.it> Steven D'Aprano wrote: > def translate(text): > import string > all=string.maketrans('','') > badcars=all.translate(all,string.letters+string.digits) > table=string.maketrans(badcars,'_'*len(badcars)) > return text.translate(table) > > No pollution. And no efficience.Recalculating all,badcars and table was not an acceptable solution ,sorry if I didn't state this point :( > Then after you are finished with the bindings, delete them: > > import string > all=string.maketrans('','') > badcars=all.translate(all,string.letters+string.digits) > table=string.maketrans(badcars,'_'*len(badcars)) > def translate(text): > return text.translate(table) > # clean up the temporary variables so as to prevent namespace pollution > del string; del all; del badcars; del table Well,a solution but not a programming pattern for an elegant language ? More this is also loosing informations. Probably I've not been clear with the word pollution and the example is poor. I didn't mean 'binding to unuseful informations' but 'bindings in a non -structured organization' I restate the problem.Python is in some ways unable to project the module structure inside the module.Or ... namespace pattern instances seems not deriving from a common pattern. Finally, (before I get polemic which is not my aim) I start thinking classes (namespaces defined via 'class' keyword) are a specialization of generic namespaces in which there-defined methods get a special way of being called and __call__ method is a way of cloning access to them. (Thin ice....) Don't really know if modules can be defined as specialization of generic namespaces and be placed somewhere next to classes. Even worse I get with methods and function namespaces. Rob Williscroft wrote: > After 3 or 4 iterations I refactored you code to this: > > def translate( text ) > import string > all=string.maketrans('','') > badcars=all.translate(all,string.letters+string.digits) > TABLE = string.maketrans(badcars,'_'*len(badcars)) > > global translate > def translate( text ): > return text.translate(TABLE) > > return translate( text ) There is a way to access 'all' and 'badcars' here? In my trial translate.all and translate.badcars can be accessed easily and maybe coherently. Thanks a lot, and don't tell me 'the dictator has marked the trail' ;) ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From tdelaney at avaya.com Mon Jul 4 23:40:01 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 5 Jul 2005 13:40:01 +1000 Subject: What are __slots__ used for? Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CB20@au3010avexu1.global.avaya.com> Ric Da Force wrote: > I am a C# programmer and new to the language and I am trying to debug > some code which uses this feature. Can anyone elaborate on what it > is and how it is used? __slots__ is used for memory and performance gains in classes that need them. A class with __slots__ has a fixed memory layout. Classes without __slots__ use a dictionary for storing attributes. It is possible to create a class that uses both __slots__ and __dict__ but it's very uncommon. Some people use __slots__ to restrict the attributes that can be set on a class (or instance). This is not the intended use, but it does happen. Tim Delaney From skilpat at gmail.com Tue Jul 26 11:24:03 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 26 Jul 2005 08:24:03 -0700 Subject: SciPy and NetCDF Message-ID: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> I am going to be doing a lot of work with large data sets stored in various netCDF files, and after checking out the alternatives, I would really like to go with SciPy. The problem is that SciPy offers no native netCDF support. I have checked out pycdf at http://pysclint.sourceforge.net/pycdf/, but it requires Numerical Python. Is there any way to get this working with SciPy without installing more modules? The less my sysadmin has to install the better. We are using Python 2.2.1 (and I don't know if upgrading is an option). Thanks in advance, Scott From istvan.albert at gmail.com Tue Jul 19 14:09:45 2005 From: istvan.albert at gmail.com (istvan.albert at gmail.com) Date: 19 Jul 2005 11:09:45 -0700 Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> Message-ID: <1121796584.974756.132430@g14g2000cwa.googlegroups.com> > It seems to me that you really never tracked Nevow, your information is > very incomplete. I think you should complete it before talking about Nevow I think you should take what you posted above and put it up on your main site, because right now there is no way to find any information like this. Your entire intro is about templating and leaves one with no clues as to what else is there. One remark regarding stan. For me it is inconceivable that one would build (and debug) any complicated webpage as stan does it, one element at a time: docFactory = loaders.stan( t.html[t.head[t.title["Session example"]], t.body[display_session]] ) The pages that I have to build invariably contain multiple nested html tables etc. I shudder to think that I would ever have to build them like that. I know you have an "inverse" ZPT like templates those are a lot friendlier on the eyes. For someone who is does not know what Nevow is seeing an example of Stan is very scary because IMO it does not scale at all. This again is just an opinion. Thanks for the explanations. Istvan. From paul_d_smith at x-hotmail.com Wed Jul 27 12:34:06 2005 From: paul_d_smith at x-hotmail.com (Paul D.Smith) Date: Wed, 27 Jul 2005 17:34:06 +0100 Subject: Create a variable "on the fly" Message-ID: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Can Python create a variable "on-the-fly". For example I would like something like... make_variable('OSCAR', 'the grouch'); print OSCAR; ...to output... the grouch Anything like this in Python? And in case anyone is interested, I want to instantiate a set of variables based on environment variables without using os.environ everywhere by having a look instantiate Python variables of the appropriate type. Thanks, Paul DS. -- Please remove the "x-" if replying to sender. From enleverlesO.OmcO at OmclaveauO.com Fri Jul 8 16:05:39 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 8 Jul 2005 22:05:39 +0200 Subject: Options to integrate Python modules into native windows applications References: <42ce9f7c$0$25046$8fcfb975@news.wanadoo.fr> Message-ID: <42cedcab$0$25052$8fcfb975@news.wanadoo.fr> Hi ! >>> Your english is fine. Ce n'est pas mon anglais. Babelfish m'a beaucoup aid?. @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B sites : http://mclaveau.com http://bergoiata.org http://ponx.org From rbt at athop1.ath.vt.edu Mon Jul 18 16:37:57 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 18 Jul 2005 16:37:57 -0400 Subject: goto In-Reply-To: References: Message-ID: <1121719077.19216.10.camel@athop1.ath.vt.edu> On Mon, 2005-07-18 at 12:27 -0600, Steven Bethard wrote: > Hayri ERDENER wrote: > > what is the equivalent of C languages' goto statement in python? > > Download the goto module: > http://www.entrian.com/goto/ > And you can use goto to your heart's content. And to the horror of all > your friends/coworkers. ;) > > STeVe Shouldn't that be "to the horror of all your goto-snob friends." IMO, most of the people who deride goto do so because they heard or read where someone else did. Many of the world's most profitable software companies (MS for example) have thousands of goto statements in their code... oh the horror of it all. Why aren't these enlightened-by-the-gods know-it-alls as profitable as these obviously ignorant companies? From bokr at oz.net Sat Jul 30 16:45:17 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Jul 2005 20:45:17 GMT Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <42ebe0a1.162528002@news.oz.net> On Fri, 29 Jul 2005 18:07:31 -0400, Mike Meyer wrote: >I know, lambda bashing (and defending) in the group is one of the most >popular ways to avoid writing code. However, while staring at some Oz >code, I noticed a feature that would seem to make both groups happy - >if we can figure out how to avoid the ugly syntax. > >This proposal does away with the well-known/obscure "lambda" >keyword. It gives those who want a more functional lambda what they >want. It doesn't add any new keywords. It doesn't add any new magic >characters, though it does add meaning to an existing one. That could >be replaced by a new magic token, or adding magic meaning to a >non-magic token. It breaks no old code either way. > >I haven't really worked out all the implications; I just wanted to >throw it out and see what everyone else thought about it. As a >result, the code examples tend to be ugly. > >As previously hinted, this feature is lifted from Oz. > >Currently, class and functions definitions consist of a keyword - >either "class" or "def" - followed by a name, a header, then code. The >code is compiled into an object, and the name is bound to that object. > >The proposal is to allow name to be a non-name (or rare name) >token. In this case, the code is compiled and the resulting object is >used as the value of the class/def expression. > >My choice for the non-name token is "@". It's already got magic >powers, so we'll give it more rather than introducing another token >with magic powers, as the lesser of two evils. > >Rewriting a canonical abuse of lambda in this idiom gives: > >myfunc = def @(*args): > return sum(x + 1 for x in args) If you remove the '@' -- which is not really needed -- you have exactly my (at least I think it was mine -- the variation are, in any case ;-) old anonymous def proposal. So good luck in getting any more favorable attention than I did ;-) I've also proposed named and anonymous callable local blocks for the other variations of removing 'def' and/or the binding name from normal def syntax. E.g., def my_func(*args): # normal def return sum(x + 1 for x in args) my_func = def(*args): # anonymous def expression return sum(x + 1 for x in args) my_local_callable_block(*args): # named local callable block nargs = len(args) # binds nargs as if this suite were e.g. an "if" suite. return sum(x + 1 for x in args) my_local_callable_block = (*args): # local callable block expression nargs = len(args) # binds nargs as if this suite were e.g. an "if" suite. return sum(x + 1 for x in args) The local callable blocks can be made accessible via a dict or list or whatever and called like lcb_dict[key](args) to have the bindings occur in the scope of the block definition. This avoids the problem of the typical case dispatch of function calls via a dict, where the function has its own temporary local namespace and binding in the calling namespace is kludgey. > >In other words, this is identical to: > >def myfunc(*args): > return sum(x + 1 for x in args) > >We can write the same loop with logging information as: > >sum(def @(arg): > print "Bumping", arg > return arg + 1 > (x) # '(' at the same indent level as def, to end the definition > for x in stuff) You are almost quoting me in previous posts (protesting that the indentation "problem" is no big deal ;-) > >A more useful example is the ever-popular property creation without >cluttering the class namespace: > >class Spam(object): > myprop = property(fget = def @(self): > return self._properties['myprop'] > , > fset = def @(self, value): > self._properties['myprop'] = value > , > fdel = def @(self) > del self._properties['myprop'] > , > doc = "Just an example") > Again, the '@' is not necessary ;-) >This looks like the abuse of lambda case, but these aren't >assignments, they're keyword arguments. You could leave off the >keywords, but it's not noticably prettier. fget can be done with a >lambda, but the the others can't. Well, they can, but it's not pretty ;-) > >Giving clases the same functionality seems to be the reasonable thing >to do. It's symmetric. And if anonymous function objects are good, >then anonymous class objects ought to be good as well. I agree. Regards, Bengt Richter From ypaami at gmail.com Sun Jul 3 05:10:21 2005 From: ypaami at gmail.com (yipusi) Date: Sun, 3 Jul 2005 05:10:21 -0400 Subject: question Message-ID: IDLE 1.0.3 >>> import sys >>> sys.ps2 Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' >>> where is the problem? ---------- Forwarded message ---------- From: Steven D'Aprano To: python-list at python.org Date: Sun, 03 Jul 2005 18:51:07 +1000 Subject: Re: a question On Sun, 03 Jul 2005 03:19:45 -0400, Xinyue Ye wrote: > when I type sys.ps2 after import sys, > I got the message like: > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.ps2 > AttributeError: 'module' object has no attribute 'ps2' > why does it happen? It works for me. >>> import sys >>> sys.ps2 '... ' Can you cut and past the relevant lines from your interactive session? -- Steven. From tassach at gmail.com Wed Jul 6 12:13:22 2005 From: tassach at gmail.com (tassach at gmail.com) Date: 6 Jul 2005 09:13:22 -0700 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: <42c32af7@usenet01.boi.hp.com> References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <42c32af7@usenet01.boi.hp.com> Message-ID: <1120666402.793917.151140@g44g2000cwa.googlegroups.com> Don wrote: > Chung Leong wrote: > > > Isn't that an NP-complete problem or am I crazy? > > It is NP complete. Its known as the "cutting stock problem" (aka "Knapsack > problem"). Here's a Wikipedia page that describes it: > > http://en.wikipedia.org/wiki/Cutting_stock_problem > > There are commerical applications available that "solve" the problem in 2D > for use in the woodworking industry (among others). This is generally done > to minimize waste when cutting down panels (plywood, etc) into smaller > pieces for cabinets, etc. > > -Don For photos, it's a lot simpler, assuming you only want make standard size prints (IE: 8x10, 5x7, 4x6, 2.5x3.5). There are a very limited number of combinations of the standard print sizes which will fit on an 8.5x11 sheet of paper. This could probably be solved pretty easily with just a lookup table. Also, you have to remember that paper cost is only part of the equation when printing photos -- you also have to consider ink costs. In the stock cutting problem, it's assumed that the cutting cost is insignificant. Given the insane cartidge costs for inkjet printers, wasting a little paper -- even expensive paper -- is likely to be a more economical than wasting ink. From could.net at gmail.com Thu Jul 14 07:41:33 2005 From: could.net at gmail.com (could ildg) Date: Thu, 14 Jul 2005 19:41:33 +0800 Subject: How can I import a py script by its absolute path name? Message-ID: <311b5ce105071404412d4bf318@mail.gmail.com> I want to import c:\xxx\yyy\zzz.py into my programme, What should I do? Thank you~ From skink at evhr.net Fri Jul 15 09:45:02 2005 From: skink at evhr.net (Fabien) Date: Fri, 15 Jul 2005 15:45:02 +0200 Subject: open a mail and... In-Reply-To: <000c01c58942$5e6632d0$1603a8c0@avc> Message-ID: <20050715134502.201197F67B@postix.sdv.fr> > Is it possible to open a mail and download its files attached in a > hard-disk using a python script? Use the poplib to do that. The documentation for this module can be found at http://docs.python.org/lib/module-poplib.html. -- Fabien From spam.csubich+block at block.subich.spam.com Wed Jul 20 13:00:09 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 20 Jul 2005 13:00:09 -0400 Subject: main window in tkinter app In-Reply-To: References: <0FmDe.8922$TU.2673@bignews1.bellsouth.net> Message-ID: William Gill wrote: > That does it!, thanks. > > Thinking about it, when I created a derived class with an __init__ > method, I overrode the base class's init. It should have been > intuitive that I needed to explicitly call baseclass.__init(self), it > wasn't. It might have hit me if the fault was related to someting in > baseclass.__init() not taking place, but the recursion loop didn't give > me a clue. Any idea why failing to init the base class caused the loop? You never pasted the first part of the traceback: File "", line 1, in -toplevel- app.title('frob') File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1531, in wm_title return self.tk.call('wm', 'title', self._w, string) File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1654, in __getattr__ return getattr(self.tk, attr) File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1654, in __getattr__ return getattr(self.tk, attr) When you didn't call Tk.__init__(self), self.tk was never initialized. Further, it's obvious from the traceback that Tk implements a __getattr__ method; from the python docs: __getattr__(self,name): Called when an attribute lookup has not found the attribute in the usual places Since self.tk doesn't exist, __getattr__(self,tk) was called. Without looking at the TKinter source code, we can surmise that there's a default behavior of "if self doesn't have it, return the relevant attribute from within self.tk." The problem, of course, arises when self.tk doesn't exist -- this causes the self.tk reference to call self.__getattr__('tk'), which is recursive. The infinite recursion, then, is a mild bug in TKinter that doesn't show itself during normal use. The proper solution should be to replace the self.tk call with either self.__dict__['tk'], or to make Tk a new-style class and use object.__getattribute__(self,'tk'). (Note: there are probably some fine details that I'm missing in this 'solution', so take it with a potato-sized grain of salt. The general principle still applies though.) From python at rcn.com Sat Jul 9 22:42:05 2005 From: python at rcn.com (Raymond Hettinger) Date: 9 Jul 2005 19:42:05 -0700 Subject: removing list comprehensions in Python 3.0 References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> Message-ID: <1120963325.227725.123030@g43g2000cwa.googlegroups.com> [Steven Bethard] > I would hope that in Python 3.0 list comprehensions and generator > expressions would be able to share a large amount of implementation, and > thus that the speed differences would be much smaller. But maybe not... Looking under the hood, you would see that the implementations are necessarily as different as night and day. Only the API is similar. Raymond From pydecker at gmail.com Sat Jul 23 20:33:28 2005 From: pydecker at gmail.com (Peter Decker) Date: Sat, 23 Jul 2005 20:33:28 -0400 Subject: wxPython - DB Form generator unit In-Reply-To: <42DD0C3D.7040408@mailpont.hu> References: <42DD0C3D.7040408@mailpont.hu> Message-ID: On 7/19/05, fowlertrainer at mailpont.hu wrote: > Is anyone know about a DB form generator unit under wxPython ? > What that's means ? > > I add information about a Query, or a ListOfDict, I set some other infos > (Lookups, others), and it is generate a Form with edit boxes, listboxes, > etc. > Then I can fill up the form with a record's datas. User can modify them. > After I can call Apply method, and every modifications are stored in a > result. You should look into Dabo. It is a framework for creating database apps, and comes with a wizard that lets you create an app that queries, updates, edits, adds and deletes records in a variety of databases. What database are you using? # p.d. From gnb at itga.com.au Mon Jul 4 04:04:59 2005 From: gnb at itga.com.au (Gregory Bond) Date: Mon, 04 Jul 2005 18:04:59 +1000 Subject: web programming with mod_python In-Reply-To: <5xzm6obuegpo$.1u6l6qmydgi2v$.dlg@40tude.net> References: <5xzm6obuegpo$.1u6l6qmydgi2v$.dlg@40tude.net> Message-ID: Rodrigo Dominguez wrote: > My question is: is there some kind of framework that works with mod_python? I use and love Albatross, but there are heaps of others. Check the mod_python FAQ, in particular http://www.modpython.org/FAQ/faqw.py?req=show&file=faq03.010.htp From kirk at jobsluder.net Sat Jul 9 13:37:43 2005 From: kirk at jobsluder.net (Kirk Job Sluder) Date: Sat, 09 Jul 2005 17:37:43 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120834070.272672.143850@f14g2000cwb.googlegroups.com> <87br5d2n0a.fsf@debian.kirkjobsluder.is-a-geek.net> <1120896894.392801.5800@z14g2000cwz.googlegroups.com> Message-ID: <87slyn2821.fsf@debian.kirkjobsluder.is-a-geek.net> "Kay Schluehr" writes: > Kirk Job Sluder schrieb: > > In what way do lisp macros prevent the creation of modular libraries? > > Common Lisp does does have mechanisms for library namespaces, and in > > practice a macro contained within a library is not that much different > > from a function contained in a library or a class contained in a > > library. Macros just provide another mechanism for creating useful > > domain-specific abstractions. > > To be honest I don't understand what a "domain-specific abstraction" > could be? What is the benefit of abstractions if they are not > abstracting from particular domain specific stuff? The usual trend in higher level languages is to abstract away from the algorithmic details into domain-specific applications. So for example, rather than writing a block of code for handling the regular expression '[a-zA-Z]+, then a different block of code for the case, 'a|b|c', we have a regular expression library that packages up the algorithm and the implementation details into an interface. The python standard library is basically a collection of such abstractions. In python you usually work with strings as an object, rather than as an array of byte values interpreted to be linguistic characters located at a specific memory address as you would in c. Object oriented programming is all about creating domain-specific abstractions for data. This enables us to talk about GUIs as widgits and frames in addition to filling in pixels on a screen. Or to talk about an email Message as a collection of data that will be stored in a certain format, without having to do sed-like text processing. > > The primary advantage to macros is that > > you can create abstractions with functionality that is not easily > > described as either a function or a class definition. > > As long as macros are used to create new language features such as an > object system like CLOS this technique may be perfectly justified for > language developers ( ! ) but I still consider it as a bad idea to > muddle the language development and the application development, that > seems to be the favourite programming style of Paul Graham. On the > other hand thinking about language development as a certain application > domain I find nothing wrong with the idea that it once reaches somehow > a state of a mature product that should not be altered in arbitrary > manner for the sake of a large user community. Well, at this point, Common Lisp has been formally standardized, so changing the core standard would be very difficult. There is in fact, strong resistance to reopening the standards process at this time, based on the impression that most of what needs to be done, can be accomplished by developing libraries. So I think that CL as a mature product is not altered in an arbitrary manner. However, from my view, quite a bit of development in python involves adding new language constructs in the form of classes, functions, and instance methods, as well as interfaces to C and C++ libraries. I would argue this is one of the core strengths of python as a language, the fact that we are only limited to the builtin functions and standard library if we choose to be. As an example, whenever I work with a new data source, I usually end up creating a class to describe the kinds of records I get from that data source. And some functions for things that I find myself repeating multiple times within a program. Macros are just another way to write something once, and use it over and over again. > > Kay > -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From darkcowherd at gmail.com Mon Jul 25 22:54:43 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Tue, 26 Jul 2005 08:24:43 +0530 Subject: [Pythoncard-users] Grid problems In-Reply-To: <1E2EAE6E8D808F409F56A10B3FF9ADD8715826@us194mx12.tycoelectronics.net> References: <1E2EAE6E8D808F409F56A10B3FF9ADD8715826@us194mx12.tycoelectronics.net> Message-ID: <5f4d3cb505072519545410359f@mail.gmail.com> > > info = dbc.fetchall() > > > self.dbTable=DBTable(????????) ? here is where I have problems, I > used cursor, argument but no data shown > Hmm, Not sure, but isnt the data in the variable 'info' try self.dbTable = info -- Dark Cowherd From rutt at bmi.osu.edu Thu Jul 7 16:47:43 2005 From: rutt at bmi.osu.edu (Benjamin Rutt) Date: Thu, 07 Jul 2005 16:47:43 -0400 Subject: question about introspection using inspect module References: <5vll4ihfvt.fsf@akron.bmi.ohio-state.edu> Message-ID: <5vr7eafimo.fsf@akron.bmi.ohio-state.edu> Fernando Perez writes: > I certainly don't want to discourage you from learning about python > introspection, it's one of the most fun aspects of the language. But just as > an FYI, the pydoc system already does much of what you have in mind, at least > if I'm reading your description correctly: > > planck[/tmp]> pydoc -p 12345 > pydoc server ready at http://localhost:12345/ thanks, I'm aware of that actually, and seeing all the information available there was inspiring to me. what I am actually trying to do is to build a database of Python modules. so then later, I can write a tool in my favorite editor (Emacs) to invoke some forms of completion against this database (e.g. os.remov or socket. to see a list of all socket module definitions). I was browsing pydoc.py but at first glance was having trouble separating what in the code what is for the GUI, what is for the Web server, and what does the introspection. I have actually borrowed the ModuleScanner class already, to build the list of modules. It is just inspecting those modules further where I'm having trouble. thanks, -- Benjamin Rutt From peter at engcorp.com Tue Jul 5 15:30:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Jul 2005 15:30:28 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120590707.093007.175330@o13g2000cwo.googlegroups.com> References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120590707.093007.175330@o13g2000cwo.googlegroups.com> Message-ID: mcherm at gmail.com wrote: [snip description of experience teaching high school students] > So I'd say that it's a pretty obscure name that most people wouldn't > know. It would be hard to argue against that statement; certainly "lambda" in this context (or probably any) is not a word "most people" would know. On the other hand, the name itself is probably not very important. I still remember my first encounter with "lambda" in Python very clearly. I saw the word, thought "huh? what the heck is that?", then read a sentence about it that included some comment about its background in other fields. "Oh," I said, "pre-existing usage. Whatever." I proceeded to read about what it did and how to use it. The name was irrelevant. If the text had said "anonymous functions are created using the keyword 'tribble' (named for a similar feature in a fictional Klingon programming language)", I wouldn't have felt any differently about it. So it makes some sense to a few trekkers... big furry deal. What bothered me was the syntax. Arguments without parentheses? What possessed anyone to put something so inconsistent in the language? No statements? Dang, that will limit my interest in using them. Oh well, what's page four of the tutorial got for me next? It shouldn't take anyone more than ten seconds to integrate "lambda" into their brain and carry on with useful work. Really, the name is such a trivial, unimportant part of this whole thing that it's hardly worth discussing. The syntax is more important, and the limitations are of definite interest. Not the name. -Peter From s_t_a_n_i at gmx.net Thu Jul 21 06:40:27 2005 From: s_t_a_n_i at gmx.net (Stani) Date: 21 Jul 2005 03:40:27 -0700 Subject: UPDATE: SPE 0.7.4.d Python Editor released Message-ID: <1121942427.892536.12980@o13g2000cwo.googlegroups.com> Something which prevented SPE 0.7.4.a to start is fixed Stani PS http://www.stani.be/python/spe/blog From jbellis at gmail.com Wed Jul 6 00:45:23 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 5 Jul 2005 21:45:23 -0700 Subject: threads and sleep? In-Reply-To: References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> Message-ID: <1120625123.135496.318590@g44g2000cwa.googlegroups.com> Peter Hansen wrote: > Jeffrey Maitland wrote: > > I was hoping that python would allow for the cpu threading such in > > Java etc.. but I guess not. (from the answers,and other findings) I > > guess I will have to write this part of the code in something such as > > java or c or something that allows for it then I can either wrap it in > > python or avoid python for this part of the app. > > Or investigate the use of Irmen's Pyro package and how it could let you > almost transparently move your code to a *multi-process* architecture Unless you're doing anything that would require distributed locking. Many if not most such projects do, which is why almost everyone prefers to use threads on an SMP machine instead of splitting it across multiple smaller boxes. -Jonathan From me at privacy.net Mon Jul 18 16:56:56 2005 From: me at privacy.net (Admin) Date: Mon, 18 Jul 2005 17:56:56 -0300 Subject: What is your favorite Python web framework? References: <1121714497.162978.50480@g49g2000cwa.googlegroups.com> Message-ID: On Mon, 18 Jul 2005 16:21:37 -0300, Jeff Shell wrote: > Don't discard Zope 3 becaue of what you've heard about Zope 2. Zope 3 > is a very different animal. Are Zope 3's learning curve + speed of development a lot faster than previous versions? -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From grante at visi.com Thu Jul 14 17:09:44 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 14 Jul 2005 21:09:44 -0000 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? References: <11ddckucctde603@corp.supernews.com> <11ddfgsg4nlch86@corp.supernews.com> <11ddkjakresod4a@corp.supernews.com> Message-ID: <11ddl4o2mns76e9@corp.supernews.com> On 2005-07-14, Grant Edwards wrote: > On 2005-07-14, Tim Peters wrote: > >> You may have forgotten how much richer the "plausible HW" landscape >> was at the time too. > > I've probably blocked most of it out intentionally. I seem to > have vague, repressed, memories of working on a Sperry machine > that used base 4 floating point. No, on second thought, I think it was base-16. -- Grant Edwards grante Yow! Yow! I want my nose at in lights! visi.com From tiissa at nonfree.fr Mon Jul 4 15:17:21 2005 From: tiissa at nonfree.fr (tiissa) Date: Mon, 04 Jul 2005 21:17:21 +0200 Subject: Existance of of variable In-Reply-To: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> Message-ID: <42c98b40$0$29947$626a14ce@news.free.fr> Josiah Manson wrote: > Hello. I am very new to Python, and have been unable to figure out how > to check if a variable exists or not. In the following code I have made > a kludge that works, but I think that it would be clearer to check if > closest exists and not have to initialize it in the first place. How is > that check done? Variables are stored in two dictionnaries: globals() (for global variables) and locals() (for the local ones, which are also global on top level). You can therefore write: if 'closest' in locals(): self.sel = [closest.name] On the other hand, if you try to access a variable which doesn't exist, you'll get the NameError exception. Another way is then: try: self.sel = [closest.name] except NameError: pass > I also have a few other questions to tack on if you don't mind. I am > setting dist to 1e9, because that is a larger value than any of the > places in the galaxy will be far away. Is there a better way to > initialize dist so that it is impossible for this to fail? For example, > would setting dist to infinity work, and how is that done? The float constructed from the string 'inf', float('inf'), may do the trick. I don't know the details, though. >>> 1e100 < float('inf') True > Extending my existance checking question, how does one check what type > a variable has? The '__class__' special attribute [1] will return the class. You can also look at the builtin 'isinstance' [2]. However, type checking is not a common idiom in python since we tend to use 'duck typing': if your object can do what you want with it, don't bother to check if it is exactly of the class you expect. Therefore we often try to use the object then catch the exception rather than check the object then use it. Of course, there may be situations where it's not suitable but type checking seems not to be too common in python. [1] http://docs.python.org/lib/specialattrs.html [2] http://docs.python.org/lib/built-in-funcs.html From mwh at python.net Thu Jul 28 11:47:26 2005 From: mwh at python.net (Michael Hudson) Date: Thu, 28 Jul 2005 15:47:26 GMT Subject: baffling error-handling problem References: Message-ID: Chris Fonnesbeck writes: > I thought I knew how to do error handling in python, but apparently I > dont. I have a bunch of code to calculate statistical likelihoods, and > use error handling to catch invalid parameters. For example, for the [...] > bernoulli distribution, I have: > I have no idea how this can happen, given how I have coded this. > Anyone see what I must be missing? Is it possible you have two classes called LikelihoodError? One in __main__, one in some_module_of_yours, maybe. Cheers, mwh -- how are the jails in israel? well, the one I was in was pretty nice -- from Twisted.Quotes From bokr at oz.net Sun Jul 10 16:11:28 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 10 Jul 2005 20:11:28 GMT Subject: Efficiency of using long integers to hold bitmaps References: <42d14ec3@news.rivernet.com.au> Message-ID: <42d165d0.311819733@news.oz.net> On Mon, 11 Jul 2005 02:37:21 +1000, "Jeff Melvaine" wrote: >I note that I can write expressions like "1 << 100" and the result is stored >as a long integer, which means it is stored as an integer of arbitrary >length. I may need to use a large number of these, and am interested to >know whether the storage efficiency of long integers is in danger of >breaking my code if I use too many. Would I do better to write a class that >defines bitwise operations on arrays of integers, each integer being assumed >to contain at most 32 bits? I cannot find information in the Python manuals >for 2.4.1 that would allow me to resolve this question; perhaps the >intention is that programmers should not rely on implementation details. > >Thanks in advance, > Sounds like a possible^H^H^H^H^H^H^H^Hprobable premature optimization worry ;-) What is a "large number of these" going to amount to? How many, tops? And how many bits in each? How many operations between them? (Since integers are immutable, operations mean allocation of space for new ones for results and disposing of unused garbage ones (probably back to a special fast pool for integers and longs)). Are you interested in a speed/memory tradeoff? If your bit vectors are extremely large and sparse (have only a few bits "on"), you might consider sets (import sets and help(sets)) of the bit numbers as representations. BTW, I wonder if anyone has written an ordered bit set class in C yet. I was tempted ;-) How much memory do you have? Buying more can be a pretty cheap way of solving space worries if you are getting paid for your time. You should be able to subclass int or long as a way of writing your program in terms of your own bit vector class. Then you can change your mind and change the underlying representation without changing the code that uses the api. Compared to plain longs it will cost you some speed to keep converting results to your own type though. Bottom line, whether your code will "break" due to storage problems or be fast enough will depend on numbers you didn't provide ;-) Regards, Bengt Richter From steve at REMOVETHIScyber.com.au Sun Jul 3 19:11:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 09:11:19 +1000 Subject: Assigning to None (was Re: Question about Python) References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <42c8388f.442175024@news.oz.net> Message-ID: On Sun, 03 Jul 2005 19:19:05 +0000, Bengt Richter wrote: > On Sun, 03 Jul 2005 11:47:07 +1000, Steven D'Aprano wrote: > >>On Fri, 01 Jul 2005 12:59:20 -0400, Fran?ois Pinard wrote: >> >>> [Peter Hansen] >>>> Mike Meyer wrote: >>>> > Yes. I once grabbed an old program that did assignments to None. But >>>> > that's always been a bad idea. >>> >>>> What was the use case!? >>> >>> People used to assign None to itself as a keyword argument in function >>> headers. The goal was to make a local copy of the reference, which was >>> then accessed faster than the global thing. >> >>Can you say "premature optimization is the root of all evil"? >> >>I'd like to see the profiling that demonstrated that this made a >>significant -- or even measurable -- speed-up in anything but the most >>unusual cases. >> > The difference between local and global access is definitely measurable, though > there's no reason to use None as the local name if you want to do that kind > of optimization (not possible in 2.4+) [snip] > about 25% longer to get a global (AND bind it locally, which the two timings share) > than to do the same for a local, it seems. Sure. And if you are actually looping over one million bindings to your local variable, and doing NOTHING else, you may approach a 25% time saving. That is, one of the unusual cases I mentioned. But in real world usage, the 25% saving in fetching the variable once or twice is almost certainly lost in the noise of the rest of your code. Saving 25% of 0.0000001 second running time in a function that takes 0.0001 second in total to run is pointless. That's why I asked about the profiling. I'd like to see what sort of real world function got enough real benefit from setting None=None to make up for the misuse of the language. -- Steven. From velocity.travlr at gmail.com Thu Jul 21 07:34:53 2005 From: velocity.travlr at gmail.com (travlr) Date: 21 Jul 2005 04:34:53 -0700 Subject: UPDATE: SPE 0.7.4.d Python Editor released In-Reply-To: <1121942427.892536.12980@o13g2000cwo.googlegroups.com> References: <1121942427.892536.12980@o13g2000cwo.googlegroups.com> Message-ID: <1121945693.157781.234540@g43g2000cwa.googlegroups.com> I just dloaded 0.7.4.b an hour ago... your quik. Ha...lol. :-) From peter at engcorp.com Sat Jul 23 12:28:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Jul 2005 12:28:11 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kf4kmFsu26jU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Peter Hansen wrote (on Paths not allowing comparison with strings): >>Could you please expand on what this means? Are you referring to doing >>< and >= type operations on Paths and strings, or == and != or all those >>or something else entirely? > > All of these. Do you need them? I believe so. If they are going to be basestring subclasses, why should they be restricted in any particular way? I suppose that if you wanted to compare a Path to a string, you could just wrap the string in a Path first, but if the Path is already a basestring subclass, why make someone jump through that particular hoop? >>>Other minor differences, as requested on python-dev, are: >>> >>>* size property -> getsize() method. >>>* atime/mtime/ctime properties -> atime()/mtime()/ctime() methods >> >>What does this mean? The .size property and a getsize() method both >>already exist (in my copy of path.py anyway) and do the same thing. >>Same with the other ones mentioned above. Is someone working from an >>out-of-date copy of path.py? > > No. But the size of a file is somewhat volatile, and does not feel like > a "property" of the path to it. Remember: the path is not the file. Same > goes with the xtime() methods. Oh, so your original text was meant to imply that those properties *were being removed*. That wasn't at all clear to me. I understand the reasoning, but I'm unsure I agree with it. I fully accept that the path is not the file, and yet I have a feeling this is a pedanticism: most of the time when one is dealing with the _file_ one is concerned with the content, and not much else. When one is dealing with the _path_ one often wants to check the size, the modification time, and so forth. For example, once one has the file open, one very rarely is interested in when it was last modified. In other words, I feel once again that Jason's original intuition here was excellent, and that he chose practicality over purity in appropriate ways, in a very Pythonic fashion. I confess to feeling that the suggested changes are being proposed by those who have never actually tried to put path.py to use in practical code, though I'm sure that's not the case for everyone making those suggestions. Still, once again this doesn't seem a critical issue to me and I'm happy with either approach, if it means Path gets accepted in the stdlib. > At the moment, I think about overriding certain string methods that make > absolutely no sense on a path and raising an exception from them. That would seem reasonable. It seems best to be very tolerant about what "makes no sense", though istitle() would surely be one of those to go first. Also capitalize() (in spite of what Windows Explorer seems to do sometimes), center(), expandtabs(), ljust(), rjust(), splitlines(), title(), and zfill(). Hmm... maybe not zfill() actually. I could imagine an actual (if rare) use for that. >>.bytes() and friends have felt quite >>friendly in actual use, and I suspect .read_file_bytes() will feel quite >>unwieldy. Not a show-stopper however. > > It has even been suggested to throw them out, as they don't have so much to > do with a path per se. When the interface is too burdened, we'll have less > chance to be accepted. Renaming these makes clear that they are not operations > on the path, but on a file the path points to. Here again I would claim the "practicality over purity" argument. When one has a Path, it is very frequently because one intends to open a file object using it and do reads and writes (obviously). Also very often, the type of reading and writing one wants to do is an "all at once" type of thing, as those methods support. They're merely a convenience, to save one doing the Path(xxx).open('rb').read thing when one can merely do Path(xxx).bytes(), in much the same way that the whole justification for Path() is that it bundles useful and commonly used operations together into one place. > Phillip J. Eby suggested these to be set_file_xxx and get_file_xxx to demonstrate > that they do not read or write a stream; how about that? If they are there, they do exactly what they do, don't they? And they do file.read() and file.write() operations, with slight nuances in the mode passed to open() or the way the data is manipulated. Why would one want to hide that, making it even harder to tie these operations together with what is really going on under the covers? I think the existing names, or at least ones with _read_ and _write_ in them somewhere are better than set/get alternatives. It's just rare in Python to encounter names quite as cumbersome as _write_file_bytes(). It might be good for those involved to discuss and agree on the philosophy/principles behind using Path in the first place. If it's one of pragmatism, then the arguments in favour of strictly differentiating between path- and file- related operations should probably not be given as much weight as those in favour of simple and convenient access to commonly needed functionality. If, on the other hand, Path is seen as some kind of a Java-esque universal path object which is cleanly and tightly decoupled from everything else, then it would probably be best to eliminate things like .getsize() and .read_file_bytes()/.bytes() entirely and leave those in the hands of the cleanly defined and tightly decoupled File object (currently spelled "file"?), again in a Java-esque fashion. IMHO. :-) (I'll like to say for the record that I feel that just about *any* form of Path with even just the basics, basestring-based or not, would be a huge improvement over the status quo, and I'm not trying to make a big war out of this. Just offering my own view as a recent (a month or two ago) but very enthusiastic convert to path.py.) -Peter -Peter From steve at holdenweb.com Wed Jul 20 17:24:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 20 Jul 2005 22:24:59 +0100 Subject: mod_python Apache/2.0.52 (Win32) Python 2.4 In-Reply-To: <38d6a9b7.0507201214.12c048ac@posting.google.com> References: <38d6a9b7.0507201214.12c048ac@posting.google.com> Message-ID: Dieter Raber wrote: > Hi there, > > I am wondering if there is a mod_python for the above configuration. I > downloaded mod_python-3.1.3.win32-py2.3.exe, which of course as the > name implies keeps on asking me for a python 2.3 installation. I > imagine one could cheat a little bit with a fake registry entry that > says it was about python 2.3 but that points to python 2.4. Then again > I don't know what entry mod_python's installer is looking for. > It's looking for a 2.3 installation. It wouldn't be a good idea to try to fool the installer, because the linkage to compiled extensions is version-dependent. I find I have a mod_python-3.1.4.win32-py2.4.exe in my current installers directory which I must have got from somewhere. Off-hand I couldn't tell you where, and Google isn't much help, but I'll mail it if you want - it's only around an eighth of a megabyte. > Thanks for your help > > Dieter regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cyril.bazin at gmail.com Wed Jul 13 20:04:19 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Thu, 14 Jul 2005 02:04:19 +0200 Subject: Efficiently Split A List of Tuples In-Reply-To: References: Message-ID: if t is your data, you can use: l1, l2 = zip(*t) Cyril On 7/14/05, Richard wrote: > > > I have a large list of two element tuples. I want two separate > lists: One list with the first element of every tuple, and the > second list with the second element of every tuple. > > Each tuple contains a datetime object followed by an integer. > > Here is a small sample of the original list: > > ((datetime.datetime(2005, 7, 13, 16, 0, 54), 315), > (datetime.datetime(2005, 7, 13, 16, 6, 12), 313), > (datetime.datetime(2005, 7, 13, 16, 16, 45), 312), > (datetime.datetime(2005, 7, 13, 16, 22), 315), > (datetime.datetime(2005, 7, 13, 16, 27, 18), 312), > (datetime.datetime(2005, 7, 13, 16, 32, 35), 307), > (datetime.datetime(2005, 7, 13, 16, 37, 51), 304), > (datetime.datetime(2005, 7, 13, 16, 43, 8), 307)) > > I know I can use a 'for' loop and create two new lists > using 'newList1.append(x)', etc. Is there an efficient way > to create these two new lists without using a slow for loop? > > r > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon.brunning at gmail.com Fri Jul 1 04:48:05 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 1 Jul 2005 09:48:05 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) In-Reply-To: References: Message-ID: <8c7f10c605070101482bae0143@mail.gmail.com> On 7/1/05, Peter Maas wrote: > Simon Brunning schrieb: > > Sibylle Koczian needs to sort part of a list. His first attempt made > > the natural mistake - sorting a *copy* of part of the list: > > I think it was _her_ first attempt. Ooops! Sorry, Sibylle. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From gsakkis at rutgers.edu Tue Jul 12 08:33:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jul 2005 05:33:59 -0700 Subject: Search & Replace with RegEx References: <1121155904.551248.102700@o13g2000cwo.googlegroups.com> Message-ID: <1121171639.644687.223890@g44g2000cwa.googlegroups.com> wrote: [snipped] > For example, after installing a new extension, I change in compreg.dat > > lines such as: > > abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{0538E3E3-7E9B-4d49-8831-A227C80A7AD3}\components\nsForecastfox.js,1111185900000 > abs:J:\Firefox\Firefox_Data\Profiles\default.uyw\extensions\{c4dc572a-3295-40eb-b30f-b54aa4cdc4b7}\components\wml-service.js,1114705020000 > > to: > > rel:nsForecastfox.js,1111185900000 > rel:wml-service.js,1114705020000 Try this: import re from fileinput import FileInput regex = re.compile(r'^abs:.*\\(.+)$') input = FileInput(filename) unparsed = [] for line in input: try: print regex.match(line).group(1) except: unparsed.append(input.filelineno()) print line print "Unparsed lines:", ','.join(map(str,unparsed)) George From uwb at uwbomb.net Fri Jul 8 14:18:10 2005 From: uwb at uwbomb.net (uwb) Date: Fri, 08 Jul 2005 18:18:10 GMT Subject: file handling in a server (.py) file using xmlrpc References: Message-ID: Jeremy Jones wrote: > uwb wrote: > >>I've got a call to glob in a .py file sitting in an apache cgi-bin >>directory which refuses to work while the exact same code works from a >>python console session. >> >>I'm guessing that in order to read or write files from any sort of a >>script file sitting in the cgi-bin directory on a server, something has to >>be set >>to allow such activity. I'd appreciate it if anybody with as clue as to >>what that was could tell me about it. >> >> >> >> >> > So, what do you mean "refuses to work"? Is the cgi script not executing > at all? Spitting out an error? If so, what error? (And is it an error > to the browser calling the cgi script, or in your apache logs?) > > Jeremy Jones The script executes, no error messages, but the glob call turns up nothing while the identical call running from a console does in fact turn up files names as expected. From greg.lindstrom at novasyshealth.com Wed Jul 20 16:18:55 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Wed, 20 Jul 2005 15:18:55 -0500 Subject: Lots of pdf files Message-ID: <42DEB1AF.7090508@novasyshealth.com> Hello- I'm running Python 2.3 on a Linux system and have lots (about 2000) files in pdf format to print each day. If I just wind up and fire all the files at the printer at once (as 2000 separate print jobs), the print server throws a fit and our system admin comes down and slaps me around for a few minutes (which, I guess, is fair). There does not appear to be a simple way to merge many pdf's into one. I could, for example, merge all of the files for a particular provider into one pdf for that provider and then print it (or, better yet...encrypt it and ship it!), but I do not see a way. Any suggestions? As it stands now, I'm printing sending 200 files, waiting until the queue is clear, then another 200, and so forth. Eventually we will be paperless (if for no other reason this seems insane to me), but what can I do in the meantime? Thanks for your help! --greg -- Greg Lindstrom 501 975.4859 (office) Senior Programmer 501 219-4455 (fax) NovaSys Health greg.lindstrom at novasyshealth.com Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. From enleverlesO.OmcO at OmclaveauO.com Sat Jul 16 01:12:10 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Sat, 16 Jul 2005 07:12:10 +0200 Subject: problems with python 2.4 help References: <1121453444.143877.143140@g44g2000cwa.googlegroups.com> Message-ID: <42d8973e$0$3113$8fcfb975@news.wanadoo.fr> Hi ! See : http://www.gossamer-threads.com/lists/python/bugs/350314 From shane at hathawaymix.org Wed Jul 13 18:09:20 2005 From: shane at hathawaymix.org (Shane Hathaway) Date: Wed, 13 Jul 2005 16:09:20 -0600 Subject: timeoutsocket.py mirror? In-Reply-To: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> References: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> Message-ID: <42D59110.5030906@hathawaymix.org> skilpat at gmail.com wrote: > Can anybody provide a mirror for this module? The original URL seems to > be down. I have been looking for over an hour, and every single > resource that uses it links to the timo-tasi.org site to download it. FWIW, Python 2.3+ has the timeout functionality built in, so timeoutsocket.py is no longer needed. See the documentation on socket.Socket.settimeout(). Shane From mwh at python.net Fri Jul 29 05:14:15 2005 From: mwh at python.net (Michael Hudson) Date: Fri, 29 Jul 2005 09:14:15 GMT Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Steve Holden writes: > If I canpoint out the obvious, the output from "import this" *is* > headed "The Zen of Python", so clearly it isn;t intended to be > universal in its applicability. It's also mistitled there, given that it was originally posted as '19 Pythonic Theses' and nailed to, erm, something. Cheers, mwh -- Remember - if all you have is an axe, every problem looks like hours of fun. -- Frossie -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From rwgk at yahoo.com Mon Jul 11 19:32:49 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 11 Jul 2005 16:32:49 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <20050711230601.E291BE0000C9@astro.systems.pipex.net> Message-ID: <20050711233249.7623.qmail@web31504.mail.mud.yahoo.com> --- Rob Williscroft wrote: > class MyClass(object): > @init_self > def __init__( self, x, _y, z ): > print "in __init__() _y =", _y Here are the timings (script attached): overhead: 0.01 plain_grouping: 0.26 update_grouping: 0.45 plain_adopt_grouping: 0.69 autoinit_grouping: 1.14 autoinit_setattr_grouping: 1.07 autoattr_grouping: 1.01 decorated_init_grouping: 0.94 I think your decorator solution looks nice and has a good potential time-wise. Cheers, Ralf ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: autoinit_timings.py URL: From sjmaster at gmail.com Sun Jul 24 15:59:04 2005 From: sjmaster at gmail.com (Steve M) Date: 24 Jul 2005 12:59:04 -0700 Subject: How to run python script in background after i logout References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> Message-ID: <1122235144.361707.125310@f14g2000cwb.googlegroups.com> Harlin Seritt wrote: > I have a remote linux server where I can only access it via ssh. I have > a script that I need to have run all the time. I run like so: > > python script.py & > > It runs fine. When I log off ssh I notice that the script died when I > logged off. How do I make sure it stays running? You might also check out the extremely cool screen program. It lets you have multiple virtual terminal sessions from one connection, and detach them all and logout, then login later and re-attach them. I typically use 'screen -D -R' which will re-attach if there is a set of sessions to re-attach, or otherwise start a new one. Then you can have a dedicated window for your script.py (you don't even need to run it in the background of the shell with '&') and you can just detach the screen before you logout. Later you can log back in, reattach, check for any output (you can use print statements for debug info, etc.). Since it can be tricky getting started, I'll tell you briefly, there is a command key, which you use to send commands to the screen program. Anything other than command key will be passed through to whatever program is running, e.g. the bash shell or whatever. The default command key is ctrl-a. So you would do 'ctrl-a c' to create a new virtual window, 'ctrl-a 1', 'ctrl-a 2', etc. to switch between virtual windows, and 'ctrl-a d' to detach your session. This brings you back to your original ssh login shell. Incidentally, if you do a 'ps aux' here you'll see one of the programs is 'SCREEN' owned by root; this is the process that is keeping alive all your other processes and that persists when you logout and allows you to reattach later. A couple of problems I've had are first, that ctrl-a is also the emacs command to go to the beginning of the line, which I use all the time. So I've sometimes rebound the screen command key (I've tried ctrl-[ since I dont' ever seem to use that for anything else, but I don't think it works entirely perfectly, especially in combination with the next problem.). Another is that when I use putty.exe from Windows for my ssh client, I can't get scroll-back buffers to work correctly with screen. (Screen is really powerful with its own scrollback buffers and screendumps and stuff but I don't have time to get into all that or even learn it sometimes. I wish I were more a master of it since its such a great program.) Another alternative is to daemonize your program, but I don't know how to do that off the top of my head. From steve at hellug.gr Sun Jul 31 02:43:22 2005 From: steve at hellug.gr (steve at hellug.gr) Date: Sun, 31 Jul 2005 12:13:22 +0530 Subject: Error Message-ID: <200507310718.j6V7I6r31439@cse.iitkgp.ernet.in> The message cannot be represented in 7-bit ASCII encoding and has been sent as a binary attachment. -------------- next part -------------- ------------------ Virus Warning Message (on cse.iitkgp.ernet.in) file.bat is removed from here because it contains a virus. --------------------------------------------------------- From gsakkis at rutgers.edu Thu Jul 7 21:39:33 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Jul 2005 18:39:33 -0700 Subject: Is there an easy way to get at the value of DBL_MAX from Python? References: <1120786292.014588.107080@g44g2000cwa.googlegroups.com> Message-ID: <1120786773.722096.138530@g14g2000cwa.googlegroups.com> "George Sakkis" wrote: > Where exactly have you been looking ? I guess not in Google, because > the fifth result after querying "dbl_max" is > http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html, > which follows up to > http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html. Oops, I copy-pasted it twice; the 5th google's result is actually http://mail.python.org/pipermail/pythonmac-sig/2002-July/005907.html. George From bronger at physik.rwth-aachen.de Sat Jul 30 13:41:31 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 30 Jul 2005 19:41:31 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <871x5gs6oy.fsf@wilson.rwth-aachen.de> <87slxwqp32.fsf@wilson.rwth-aachen.de> Message-ID: <87oe8kqjhw.fsf@wilson.rwth-aachen.de> Hall?chen! Peter Decker writes: > On 7/30/05, Torsten Bronger wrote: > >> [...] >> >> I didn't want to say that Dabo is bad. I just wanted to point >> out that its presence (and the presence of comparable projects) >> doesn't ease the IMO unfortunate situation with GUI toolkits for >> Python. > > Perhaps, but I see it differently, since Dabo doesn't attempt to > add a new toolkit. Well, effectively, it does so because from the human point of view, the programming interface is what you have to deal with. > [...] Dabo is giving me the best of both worlds: a Pythonic > language, and great-looking GUI apps. So I feel that it is > improving the situation with GUI toolkits for Python in that it is > allowing me to use the best toolkit without having to write > un-Pythonic code. You found a solution for you, which is a good thing. I don't want to rule out to use Dabo myself. But in my institute I'd like to present Python as a viable alternative to Delphi. In order to convince people who are used to a homogeneous rock-solid system, you must present something equivalent. Of course an open-source project can never be as homogeneous, but I can't make the whole team switch to a niche project, ignoring all other GUI alternatives about which you can even buy books in German! They'll think "strange, that Python" (or maybe "strange that Torsten" ;). > It would be great if the wxPython folks would adopt Dabo, and > eventually integrate it so that there is but a single, Pythonic > way of working with wxPython, Yes indeed. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From michele.simionato at gmail.com Sat Jul 30 05:35:29 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 30 Jul 2005 02:35:29 -0700 Subject: multiple inheritance super() In-Reply-To: <86br4ljnxs.fsf@bhuda.mired.org> References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> <1122653176.013770.106080@g49g2000cwa.googlegroups.com> <86br4ljnxs.fsf@bhuda.mired.org> Message-ID: <1122716129.428629.273960@g49g2000cwa.googlegroups.com> If I understand correcly you have a situation like this: Base | Parent1 Mixin | | | | Children1 Base | Parent2 Mixin | | | | Children2 Base | Parent3 | | Children3 The Base class is pretty general, Parent1, Parent2 and Parent3 are more specific, Children1 and Children2 requires the Mixin class, but Children3 does not require it. Let me note that this looks like a sensible design and that I agree that in simple situations multiple inheritance could be the simplest solution. Nevertheless 1) I am scared of the case where you have hundreds of methods coming from everywhere (ex. Zope) and 2) even in simple situations a solution without multiple inheritance is not that much worse. Various solutions (using pseudocode): 1. use single inheritance and attach the mixin methods by hand: class Children2(Parent2): pass for methodname, method in methods_of(Mixin): setattr(Children2, methodname, method) if you think this is ugly, use a metaclass to attach the methods for you. This is probably still ugly, since it is akin to reimplementing multiple inheritance by hand. Still, it can be done, if you really want. 2. use single inheritance and delegation. If "mixin" is a proxy to the methods in the mixin (for instance implemented as an attribute descriptor) you could do class Children2(Parent2): mixin = Proxy(Mixin) c2 = Children2() and then c2.mixin.method(args) would actually call Mixin.method(c2, args). I like this solution since it is clear where methods come from and it scales better to complex situations (still if you have only 2 or 3 methods multiple inheritance could be pretty fine). 3. think differently and use multimethods There are implementations of multimethods in Python (for instance in PEAK). This example looks like a good candidate for a multiple dispatch solution. You would use single inheritance and promote the mixin methods to multimethods. BTW, I think multimethods are pretty nifty and I would welcome them in standard Python. Michele Simionato From Stephen_Toledo_Brown at uk.ibm.com Tue Jul 12 11:23:33 2005 From: Stephen_Toledo_Brown at uk.ibm.com (Stephen Toledo-Brown) Date: Tue, 12 Jul 2005 16:23:33 +0100 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: Message-ID: <42d3e666_1@news2.prserv.net> Tony Meyer wrote: >>Everyone complaining about Eclipse in this thread needs to go >>try 3.1. The interface is much much much more responsive. > > > The problem with Eclipse, IMO, is Java. I've tried 3.1 on a WinXP machine > and, like just about any Java program, it's incredibly slow and a real pain > to use. On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and > smoothly and is reasonably nice to use. I'd happily recommend that Mac > users try Eclipse, but never a Windows (Python) programmer. I've not tried Mac, but under both Windows and Linux on x86, I find Eclipse (3.0) is slow with less than 1.25 GB of RAM, reasonably fast with 1.5GB or more. Processor speed and disk speed don't seem to be anywhere near as important. From andreas at kostyrka.org Wed Jul 13 06:04:45 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 12:04:45 +0200 Subject: threads and sleep? In-Reply-To: <1120678061.051033.230090@f14g2000cwb.googlegroups.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <1120625123.135496.318590@g44g2000cwa.googlegroups.com> <1120678061.051033.230090@f14g2000cwb.googlegroups.com> Message-ID: <1121249085.5240.89.camel@andi-lap> Am Mittwoch, den 06.07.2005, 12:27 -0700 schrieb Jonathan Ellis: > Your sarcasm is cute, I suppose, but think about it for a minute. If > the opposite of what I assert is true, why would even the mainstream > press be running articles along the lines of "multicore CPUs mean > programming will get tougher because locking is hard to get right and Easy ;) They run these articles, because -) they have copied it from the press releases. -) it's partly true. -) it's the current hype in processors. That doesn't change the contrary facts: -) the general threading programming model is very hard to get right. It's basically at the moment where we were with memory management at C level. Painful, and errorprone. Nothing to be happy about. -) There is a spectrum of problems from "requires to be run in sequence" to can be run on as many "work slaves via the internet". Fact is that Python is bad at a certain slice (can benefit from tightly interoperating threads). And that will not change that quickly, because there are certain problems. But Python works quite well for the neighboring segments, and it got a number of solutions for a number of problems in this segment. (Be it Twisted, forking, threads + GIL, etc.) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From http Thu Jul 21 01:06:31 2005 From: http (Paul Rubin) Date: 20 Jul 2005 22:06:31 -0700 Subject: Need to interrupt to check for mouse movement References: Message-ID: <7xoe8woii0.fsf@ruckus.brouhaha.com> Christopher Subich writes: > > In the particular case of wxWidgets, it turns out that the *GUI* > > blocks for long periods of time, preventing the *network* from > > getting attention. But I agree with your position for other > > toolkits, such as Gtk, Qt, or Tk. > > Wow, I'm not familiar with wxWidgets; how's that work? Huh? It's pretty normal, the gui blocks while waiting for events from the window system. I expect that Qt and Tk work the same way. From mwm at mired.org Fri Jul 1 11:30:49 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 11:30:49 -0400 Subject: Question about Python References: <42c54149$1@griseus.its.uu.se> Message-ID: <867jga7dcm.fsf@bhuda.mired.org> Jan Danielsson writes: > Hello all, > I'd like to ask seasoned Python developers: > - Are you comfortable in upgrading to the latest version of Python, or > are you worried about what you have to fix in your existing programs? No, I'm not worried. The Python developers worry about not breaking backwards compatability. The worst problem is third party extensions, and those almost always work. > - Put aside any unconditional love for Python for a second, and be > honest: Have you ever run into version related problems? Yes. I once grabbed an old program that did assignments to None. But that's always been a bad idea. > - Have you ever relied on a module, upgraded python version for some new > important feature, but realized that the module you rely on hasn't been > updated yet? If not, do you consider a possibility? There are a couple of issues here. Minor version updates (2.x.y to 2.x.y+1) seldom (never?) break things. You can just keep using the old modules. Major version updates (2.x to 2.x+1) seldom break pure python modules. However, the libraries are in a different place, so you'll have to reinstall the module. You could just add the old library directory to PYTHONPATH, but I don't really trust that. Major version updates almost always break python extension modules. However, it's usually just a binary incompatability. Recompiling the old source will produce a module that works on the new version. If you rely on others for your binary modules, you're at their mercy. If you build your own binaries modules, you'll be fine > - Do the module developers, in general, keep up with the development > versions of python, so you can expect to find newly updated modules as > new versions of python hits the streets? I don't look for updated versions of modules when I upgrade Python. When doing a minor version upgrade, I just do upgrade Python. When doing a major version upgrade, I get a list of installed python modules from my package manager, then reinstall all of them. That fetches any new versions that have made it into the package system, and rebuilds binary extensions. Most things just work. The only problems I've had doing this was because a new version of the C++ compiler choked on an expression in the C++ code of a module. A quick mail to the module support group got a patch for the C++ code, and that built just fine. I have more worries about upgrading third party modules breaking my code than I do about upgrading Python breaking my code. > - Did you have similar worries to mine when you started working with Python? Yes, based on experience with other languages. I've been pleasantly surprised. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jepler at unpythonic.net Mon Jul 18 09:30:12 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Jul 2005 08:30:12 -0500 Subject: stdin/stdout fileno() always returning -1 from windows service In-Reply-To: <1121650980.574867.244590@g44g2000cwa.googlegroups.com> References: <1121650980.574867.244590@g44g2000cwa.googlegroups.com> Message-ID: <20050718133008.GC2199@unpythonic.net> On Sun, Jul 17, 2005 at 06:43:00PM -0700, chuck wrote: > I have found that sys.stdin.fileno() and sys.stdout.fileno() always > return -1 when executed from within a win32 service written using the > win32 extensions for Python. > > Anyone have experience with this or know why? because there *is* no standard I/O for a windows service. You should be able to execute code like import sys sys.stdout = sys.stderr = open("some.log", "w") if you have code that expects the standard output files to be available. You could also open sys.stdin in a similar way. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From andreas at kostyrka.org Fri Jul 22 14:16:50 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 22 Jul 2005 20:16:50 +0200 Subject: return None In-Reply-To: <3kcpbbFtjttlU1@individual.net> References: <3kcpbbFtjttlU1@individual.net> Message-ID: <20050722181650.GA29310@heaven.kostyrka.org> On Fri, Jul 22, 2005 at 07:40:00PM +0200, Ximo wrote: > Can I do a function which don't return anything? > > The question is that, if I do a function that have a return or without > return, it returns always "None", but i want that it doesnt return me > nothing Define nothing :) None is the representation of nothing in Python ;) Andreas From gerrit.muller at embeddedsystems.nl Fri Jul 1 04:35:48 2005 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 01 Jul 2005 10:35:48 +0200 Subject: whois like functionality on Windows? In-Reply-To: References: <342dnX3zuo5XB1zfRVn-pg@powergate.ca> Message-ID: Peter Hansen wrote: > If the address doesn't get mapped to a name by a DNS server, I strongly > suspect you will get nowhere with whois, or much else. Not all IP > addresses have corresponding domain names: many are dynamic addresses > assigned on the fly to arbitrary customers of (for example) cable modem > service providers, and they're often not interested in providing any > reverse mapping for them. Some do (for example, mine is > pc-136-15.scpe.powergate.ca right now), but many don't... > > I'm sure there's a way to identify the domain of the owner of a block of > addresses in which a given IP resides. I don't know what it is. > > -Peter In 5 years of logging I did get about 23000 different domains that accessed my site. For about 1000 IP address ranges I obtained the domain name manually via whois, mostly via Geektools. Sometimes via more specific whois servers, such as krnic. These 1000 domain names are a mix of "real" domain names, for instance from companies, universities or government, and service providers. It would be nice to automate this action, although the manual approach is workable. regards, Gerrit -- Gaudi systems architecting: From simon.dahlbacka at gmail.com Thu Jul 28 09:59:53 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 28 Jul 2005 06:59:53 -0700 Subject: functions without parentheses In-Reply-To: References: Message-ID: <1122559193.824826.157390@g47g2000cwa.googlegroups.com> If you actually want that kind of syntax, then why don't you use Visual Basic? ;) From mensanator at aol.com Sun Jul 3 15:10:08 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 3 Jul 2005 12:10:08 -0700 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> Message-ID: <1120417808.526435.182060@g43g2000cwa.googlegroups.com> anthonyberet wrote: > My question isn't as all-encompassing as the subject would suggest... > > I am almost a Python newbie, but I have discovered that I don't get > along with IDLE, as i can't work out how to run and rerun a routine > without undue messing about. > > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of > code, to see the effects of tweaks, without having to save it each time, > or re-typing it over and over (I haven't even worked out how to cut and > paste effectively in the IDLE environment). I think you're missing something about IDLE if you are re-typing. For example: IDLE 1.1a3 >>> for i in range(25): print i, When you type the above, you get 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Now let's say you want to re-run that with 10 instead of 25. You don't have to re-type it. Click to place your cursor anywhere in the original block of code and hit . Idle will re-type the entire block for you: >>> for i in range(25): print i, The cursor will be at the very end of the block so you can re-run it by hitting twice. But you'll get the same output. Instead of hitting twice, use your cursor keys (or mouse) to move to the 25 in the range function and edit it to 10. Once edited, move the cursor back to end of the block and hit twice to execute >>> for i in range(10): print i, 0 1 2 3 4 5 6 7 8 9 It sounds worse than it is, just takes a little getting used to. Once you're happy with that code fragment, edit it again and add a definition at the start. [1] click in the block and hit , Idle re-types the block >>> for i in range(10): print i, [2] place cursor in front of the 'for' and add a function name and change the 'for' to use the parameter instead of a constant >>> def t(n): for i in range(n): print i, [3] hit (here we do want to insert a line) and IDLE will show you this (indents adjust automatically) >>> def t(n): for i in range(n): print i, [4] move cursor to the end of the block (after the comma) and hit twice Nothing happens. You have defined a function, but did not execute it. To execute it, type its name with some value of n. >>> t(8) 0 1 2 3 4 5 6 7 Now you can try it out with different values of n without having to edit the whole block. Now if you want to change the function definition, say we want each number output on a seperate line, do the same thing we did before. Click anywhere in the block and hit . The entire block is re-typed for you. Make your change (remove the comma) and hit twice. >>> def t(n): for i in range(n): print i Again, the function is not executed. And you can always simply click on the previously typed line t(8) and hit twice >>> t(8) 0 1 2 3 4 5 6 7 > > I see lots of alternate IDEs etc, but which would allow me the simple > interface that I have described? - I really don't know about IDEs in > general, and I suspect I would be out of my depth with one of those. > > Thanks, and feel free to mock ;) From moranar at alice.it Sat Jul 30 12:43:00 2005 From: moranar at alice.it (Adriano Varoli Piazza) Date: Sat, 30 Jul 2005 16:43:00 GMT Subject: Comparison of functions In-Reply-To: References: Message-ID: Steven D'Aprano ha scritto: > On Sat, 30 Jul 2005 13:22:47 +0000, Adriano Varoli Piazza wrote: > > >>As far as I recall from Math Analysis, which I studied two months ago, >>you can't sort complex numbers. It makes no sense. The reason being >>(reading from my book), it's not possible to define an order that >>preserves the properties of arithmetical operations on complex numbers. >>So you can't order them, and you can't compare them. > > > You are confusing mathematical ordering with sorting a list. Here, I will > sort some mixed complex and real numbers for you. If you look at them > closely, you will even be able to work out the algorithm I used to sort > them. > > 1 > 1+0j > 1+7j > 2 > 2+3j > 3+3j > 3-3j > 3+4j > 4 > 4+2j > > > It was easy. I never once asked myself whether some complex number was > greater or less than another, I just asked "which one comes first in a > lexicographic sort?" > > The two questions are NOT the same, and it is an ugliness in an otherwise > beautiful language that Python treats them as the same. > > Mathematically, 1 == 1.0 == 1+0j but in the dictionary "1" should sort > before "1.0" which sorts before "1.0+0.0j". > If you want to treat numbers as strings, why not convert them before sorting them? Python is just saying "He's trying to sort complex numbers. No can do". You're trying to make it guess that you want them sorted as strings, not as numbers. I don't see how Python treats things the same way. I see that real numbers and strings can be compared and sorted (asciibetically? don't remember). It has nothing to do with complex numbers. The abstraction or overloading or what it is fails, because they don't have an order as numbers, and Py is not intelligent enough to know that you want them asciibetized -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar MSN: adrianomd at hotmail.com ICQ: 4410132 From http Sat Jul 30 15:04:23 2005 From: http (Paul Rubin) Date: 30 Jul 2005 12:04:23 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> <3l1blnF10c1i9U1@individual.net> Message-ID: <7xr7dgnmiw.fsf@ruckus.brouhaha.com> Seth Nielson writes: > Any replacement must support the following: *delayed evaluation*. > > I need a convenient (def is not always convenient) way of saying, > "don't do this now". That is why I use lambda. How's this: f{args} (curly braces instead of parens) is the same as f(lambda: args). Examples: launch_thread{targetfunc(a,b,c)} b = Button{callback=pressed()} # Button remembers callback() def ternary(cond, x, y): if cond(): return x() else: return y() sign_of_a = ternary{a < 0, -1, 1} etc. From joon.ch at gmail.com Sun Jul 17 10:06:04 2005 From: joon.ch at gmail.com (Joon) Date: Sun, 17 Jul 2005 16:06:04 +0200 Subject: beginner question fibonacci In-Reply-To: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> References: <42da5cff$0$20137$9b4e6d93@newsread2.arcor-online.net> Message-ID: <42da65cd$0$4208$9b4e6d93@newsread2.arcor-online.net> Yes, i see. Thank you very much for the fast help! From nothingcanfulfill at gmail.com Tue Jul 19 03:12:33 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 19 Jul 2005 00:12:33 -0700 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? In-Reply-To: References: Message-ID: <1121757153.943533.185520@g44g2000cwa.googlegroups.com> I'm sure that nobody here is willing to write it for you. However, I believe that jkn was right in trying to get you to solve the problem. ;) You know what you need to do, but how are you going to do it? Create a flow chart ;) From cantabile.03 at wanadoo.fr Sun Jul 17 12:01:19 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Sun, 17 Jul 2005 18:01:19 +0200 Subject: ConfigParser : overwrite ? Message-ID: <42da80cf$0$25057$8fcfb975@news.wanadoo.fr> Hi, I'm trying and updating an .ini file with ConfigParser but each time I call 'write', it appends the whole options another time to the file. For example : Here's the inital ini file [section1] foodir: %(dir)s/whatever dir: foo Here's my code : filename = ... config = ConfigParser.ConfigParser() config.read(filename) config.set('section1', 'dir', 'anotherdir') f = open(filename, 'r+') config.write(f) f.close() Then I get : [section1] foodir: %(dir)s/whatever dir: anotherdir [section1] foodir: %(dir)s/whatever dir: foo I tried also with 'w', 'w+', 'a' ... What's the correct way to avoid this ? From python at rcn.com Sat Jul 23 12:01:02 2005 From: python at rcn.com (Raymond Hettinger) Date: 23 Jul 2005 09:01:02 -0700 Subject: unit test nested functions References: Message-ID: <1122134462.286558.16160@f14g2000cwb.googlegroups.com> [Andy] > How can you unit test nested functions? Or do you have to pull them out to > unit test them, which basically means I will never use nested functions. Several commons use cases (closures and factory functions) ultimately expose the inner function through the return value. If that is the case, the answer is simple, call the enclosing function and then run the test on the result. If the inner function never gets exposed, an argument could be made that you don't want to write a test for it -- that the inner function is just an implementation detail. This is black box testing and consistent with a test driven development approach. For whitebox testing, you could make an inner function visible by binding it to the enclosing function's attribute namespace. def f(x): def g(y): . . . f.g = g # make g visible as an attribute of f . . . Raymond From zen19725 at zen.co.uk Sun Jul 31 01:02:38 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 06:02:38 +0100 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> Message-ID: On Sat, 30 Jul 2005 16:51:13 +0200, Torsten Bronger wrote: >Hall?chen! > >zen19725 at zen.co.uk (phil hunt) writes: > >> [...] >> >> How about sometihing with the same API as Tkinter (so no need to >> relearn), but which looks prettier? Would that fix your gripes? > >I haven't learned Tkinter. You mightn't have, but I suspect more Python programers who've written GUI apps have used Tkinter than any of the other APIs. Not that I'm a particular fan of it, it's just I like standardisation, because then you get network effects. >So for me, it needn't be like Tkinter. The three most important >attributes for me are Pythonic, modern (both nice-looking and >comprehensive), and non-niche. What you say Pythonic, what do you mean? And how do you rate Tkinter, PyGtk, PyQt/PyKDE, wxWindows for "Pythonicness"? -- Email: zen19725 at zen dot co dot uk From dieter at handshake.de Thu Jul 7 14:19:14 2005 From: dieter at handshake.de (Dieter Maurer) Date: 07 Jul 2005 20:19:14 +0200 Subject: Use cases for del References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Daniel Dittmar writes on Wed, 06 Jul 2005 16:12:46 +0200: > Peter Hansen wrote: > > Arguing the case for del: how would I, in doing automated testing, > > ensure that I've returned everything to a "clean" starting point in > > all cases if I can't delete variables? Sometimes a global is the > > simplest way to do something... how do I delete a global if not with > > "del"? > > > globals ().__delitem__ (varname) > > except that the method would probably be called delete. You now have a uniform way to remove an object from a namespace. Why would you want to give each namespace its own method to remove objects from it? Can you imagine how much code you would break (would your proposal to remove "del" got accepted)? Dieter From rwgk at yahoo.com Mon Jul 11 19:18:50 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 11 Jul 2005 16:18:50 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <20050711230601.E291BE0000C9@astro.systems.pipex.net> Message-ID: <20050711231850.77137.qmail@web31505.mail.mud.yahoo.com> --- Rob Williscroft wrote: > def init_self( init ): > class KeywordArgumentError(Exception): > pass > > vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] > > def decorated_init(self, *args, **kw): > off = 0 > for name in vn: > if not name.startswith('_'): > if name in kw: > value = kw[name] > else: > value = args[off] > off += 1 > > setattr( self, name, value ) > else: > off += 1 #was missing (a bug) in last version. > if name in kw: > raise KeywordArgumentError( > "Use %s not %s" % (name[1:],name) > ) > if name[1:] in kw: > kw[name] = kw[name[1:]] > del kw[name[1:]] > > init( self, *args, **kw ) > return decorated_init > > > class MyClass(object): > @init_self > def __init__( self, x, _y, z ): > print "in __init__() _y =", _y > > def show( self ): > for i in self.__dict__: > print 'self.%s = %d' %(i,eval('self.%s' % (i,))) > > MyClass( 1, 2, 3 ).show() > > MyClass( z = 1, x = 2, y = 3 ).show() > > MyClass( z = 1, x = 2, _y = 3 ).show() Wow! Here is the output, so everyone can see it immediately: in __init__() _y = 2 self.x = 1 self.z = 3 in __init__() _y = 3 self.x = 2 self.z = 1 Traceback (most recent call last): File "/net/cci/rwgk/decorated_init.py", line 45, in ? MyClass( z = 1, x = 2, _y = 3 ).show() File "/net/cci/rwgk/decorated_init.py", line 21, in decorated_init raise KeywordArgumentError( __main__.KeywordArgumentError: Use y not _y I am impressed. I'll do some timings to see where we stand... Cheers, Ralf __________________________________ Discover Yahoo! Use Yahoo! to plan a weekend, have fun online and more. Check it out! http://discover.yahoo.com/ From renmybiru at libero.it Sat Jul 2 13:30:56 2005 From: renmybiru at libero.it (Vittorio) Date: Sat, 2 Jul 2005 17:30:56 +0000 (UTC) Subject: email link and foreign accent Message-ID: Hi, I have one problem ( I am a python beginner) in a cgi: print"""""" %(campovalore.encode('iso-8859-1')) print campovalore.encode('iso-8859-1') print """""" campovalore is an email address with special (italian) characters. >From IE6 everything is fine and the link launches my predefined (in Windows) email client with the correct string in the mailto field. But from Firefox and the same email client I have an incorrect mailto field every time there is a special character in the string. Any suggestion is welcome, vittorio From kay.schluehr at gmx.net Sat Jul 30 11:54:47 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Jul 2005 08:54:47 -0700 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> Message-ID: <1122738887.549969.197650@g47g2000cwa.googlegroups.com> Dark Cowherd wrote: > -Quote - Phillip J. Eby from dirtsimple.org > Python as a community is plagued by massive amounts of > wheel-reinvention. The infamous web framework proliferation problem is > just the most egregious example. > > Why is Python "blessed" with so much reinvention? Because it's often > cheaper to rewrite than to reuse. Python code is easy to write, but > hard to depend on. You pretty much have to: > > 1. limit yourself to platforms with a suitable packaging system, > 2. bundle all your dependencies into your distribution, or > 3. make your users do all the work themselves > > Ouch. No wonder rewriting looks easier. The only way to stop this > trend is to make it easier to reuse than to rewrite, which has been my > mission with setuptools and EasyInstall > -UnQuote I think that Phillip misrepresents the problem a little bit, because it is not true that there are too few reusable components that need just another hero programmer like himself or anyone of us to implement. What is missing is just a simple distinction that does not exist in an open source community guided by hackers at least not on a certain level ( the PEP process would be a counter-example ) but is well known in contemporary industry practice: some people are just writing specs. SUN with Java for example employs people that model systems and write API specs that are finally licenced and implemented by 3rd-party vendors. J2EE or the JavaCard API are prominent examples. This is very different from the just-for-fun or heroic-hacker attitude due to spare-time programmers who create a bit of code they are interested in and leaving the rest aside. It's not all just marketing blabla that makes Javas success. Kay From tuxlover at gmail.com Mon Jul 11 17:44:20 2005 From: tuxlover at gmail.com (tuxlover at gmail.com) Date: 11 Jul 2005 14:44:20 -0700 Subject: Environment Variable In-Reply-To: <3jg6e1Fpm157U1@individual.net> References: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> <3jg6e1Fpm157U1@individual.net> Message-ID: <1121118260.761875.293230@z14g2000cwz.googlegroups.com> Sorry for posting twice. From newsgroups at jhrothjr.com Sat Jul 2 06:01:38 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 2 Jul 2005 04:01:38 -0600 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> Message-ID: <11ccpg5o833qp42@news.supernews.com> "Robert Kern" wrote in message news:mailman.1226.1120271406.10512.python-list at python.org... > > map and filter are being removed *because of* list comprehensions. Did you > even read Guido's articles about this issue? Your understanding of why > these changes are planned is incorrect; consequently your projection based > on that understanding is not on firm footing. May I most respectfully point out that you've got it backwards. Part of the justification for list comprehensions was that they could be used to replace map and filter. The jihad against the functional constructs has been going on for a long time, and list comprehensions are only one piece of it. John Roth > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > From danb_83 at yahoo.com Mon Jul 18 18:11:32 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jul 2005 15:11:32 -0700 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: <1121724692.752350.74120@g44g2000cwa.googlegroups.com> rbt wrote: > On Mon, 2005-07-18 at 12:27 -0600, Steven Bethard wrote: > > Hayri ERDENER wrote: > > > what is the equivalent of C languages' goto statement in python? > > > > Download the goto module: > > http://www.entrian.com/goto/ > > And you can use goto to your heart's content. And to the horror of all > > your friends/coworkers. ;) > > Shouldn't that be "to the horror of all your goto-snob friends." > > IMO, most of the people who deride goto do so because they heard or read > where someone else did. Or because they've seen some BASIC programs written ca. 1980. From hugh.macdonald at gmail.com Tue Jul 12 09:50:36 2005 From: hugh.macdonald at gmail.com (Hugh Macdonald) Date: 12 Jul 2005 06:50:36 -0700 Subject: C API : Creating a Py_Method object from a C function. In-Reply-To: <42D2F687.3040003@v.loewis.de> References: <1121101669.752932.217380@g14g2000cwa.googlegroups.com> <42D2F687.3040003@v.loewis.de> Message-ID: <1121176236.090606.287860@g49g2000cwa.googlegroups.com> Thanks Martin - that worked wonderfully.... For the record (and for anyone searching for this in future), here's the code that worked (with names changed to protect my job...) myPython is the C++/Python interface class containing static methods which pass on calls to the underlying python module. It's not really commented, but if you're trying to do this kind of thing, it should give you what you need. ---------------------------------------------------------------------------------------------------- // myPython.h #ifndef ___MYPYTHON_H___ #define ___MYPYTHON_H___ #include using namespace std; typedef struct _object PyObject; typedef void (*loadCallback)(string message, int progress, void *callbackData); static PyObject *myPython_doLoadCallback(PyObject *self, PyObject *args); class myPython { public: static list *loadDetails(string file, loadCallback callbackFunc = NULL, void *callbackData = NULL); static void doLoadCallback(string message, int progress); private: static PyObject *getResults(char *moduleName, char *functionName, PyObject *args); static loadCallback callbackFunc; static void *callbackData; }; #endif // ___MYPYTHON_H___ ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- // myPython.cpp #include #include loadCallback myPython::callbackFunc = NULL; void *myPython::callbackData = NULL; list *myPython::loadDetails(string file, loadCallback newCallbackFunc, void *newCallbackData) { PyObject *pArgs, *pResult; callbackFunc = newCallbackFunc; callbackData = newCallbackData; PyMethodDef *callbackFunctionDef = new PyMethodDef; callbackFunctionDef->ml_name = "doLoadCallback"; callbackFunctionDef->ml_meth = &myPython_doLoadCallback; callbackFunctionDef->ml_flags = 1; PyObject *pyCallbackFunc = PyCFunction_New(callbackFunctionDef, NULL); pArgs = Py_BuildValue("(sO)", file.c_str(), pyCallbackFunc); pResult = getResults("myPythonModule", "loadDetails", pArgs); if(!pResult) { Py_DECREF(pArgs); return NULL; } if(PyList_Check(pResult)) { // Convert pResult into a list and return that. } return NULL; } PyObject *myPython_doLoadCallback(PyObject *self, PyObject *args) { char *message; int progress; if(!PyArg_ParseTuple(args, "si", &message, &progress)) return NULL; myPython::doLoadCallback(message, progress); return Py_None; } void myPython::doLoadCallback(string message, int progress) { if(callbackFunc) callbackFunc(message, progress, callbackData); } ---------------------------------------------------------------------------------------------------- From grante at visi.com Tue Jul 5 15:36:52 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Jul 2005 19:36:52 -0000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120590707.093007.175330@o13g2000cwo.googlegroups.com> Message-ID: <11cloakd4glsbef@corp.supernews.com> On 2005-07-05, mcherm at gmail.com wrote: > Up until a few years ago, I ran the computer science department at a > high-school. I provided support for the English teachers who taught > *all* students -- but they taught things like the use of a word > processor or the internet, That's not computer science. > and never covered the meaning of "lambda". I taught a computer > applications course which was taken by only small fraction of > the students (<10%) but there I taught things like the use of > photo-editing software, creating web sites, and the use of > simple databases; That's not computer science. > I never covered the meaning of "lambda". I also taught the > programming class (taken by only a dozen or so students per > graduating class) -- students learned basic concepts like > variables, looping, up through fancier bits like a couple > different sorting algorithms. Now you're getting a little closer to computer science. It sounds like you ran a computer user training department. I don't think it could be called computer science. > But I didn't cover the meaning of "lambda". And I also taught > the "AP" computer course (taken by an average of just 4 > students per year!), in which I explained things like object > oriented programming and recursion and managed to get the > students to the level where they could work together as a > group to write a moderately complex program, like a simple > video game. And I didn't teach the meaning of "lambda", nor > was it covered by the "AP" exam, which is supposed to be > equivalent to a single college-level course in computer > programming. Computer programming isn't the same thing as computer science. It's just one of the tools used to do computer science. > So I'd say that it's a pretty obscure name that most people > wouldn't know. I can't believe that anybody with any computer science background doesn't know it. > And besides, "def" isn't a "magic" word... it's an abreviation > for "define"... I hope that any student who didn't understand > a word as common as "define" wouldn't have graduated from our > school. Lamda isn't a magic word either. It comes from lambda calculus. -- Grant Edwards grante Yow! Is this where people at are HOT and NICE and they visi.com give you TOAST for FREE?? From rkern at ucsd.edu Mon Jul 11 23:59:07 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Jul 2005 20:59:07 -0700 Subject: Puzzled In-Reply-To: References: Message-ID: Colin J. Williams wrote: > The snippet of code below gives the result which follows > > for k in ut.keys(): > name= k.split('_') > print '\n1', name > if len(name) > 1: > name[0]= name[0] + name[1].capitalize() > print '2', name > name[0]= name[0].capitalize() > print '3', name > > 1 ['logical', 'or'] > 2 ['logicalOr', 'or'] > 3 ['Logicalor', 'or'] > > I was expecting that 3 would read ['LogicalOr', 'or'] str.capitalize() changes the first character to be uppercase and all later characters to be lower case. It does not leave the later characters alone. In [1]: str.capitalize? Type: method_descriptor Base Class: String Form: Namespace: Python builtin Docstring: S.capitalize() -> string Return a copy of the string S with only its first character capitalized. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Sat Jul 23 22:37:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Jul 2005 22:37:58 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kfpovFu3rt9U1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: [on comparing Paths and stings] > Do you have a use case for the comparison? Paths should be compared only > with other paths. I can think of lots, though I don't know that I've used any in my existing (somewhat limited) code that uses Path, but they all involve cases where I would expect, if comparisons were disallowed, to just wrap the string in a Path first, even though to me that seems like it should be an unnecessary step: if mypath.splitpath()[0] == 'c:/temp': if 'tests' in mypath.dirs(): and lots of other uses which start by treating a Path as a string first, such as by doing .endswith('_unit.py') Any of these could be resolved by ensuring both are Paths, but then I'm not sure there's much justification left for using a baseclass of basestring in the first place: if mypath.splitpath()[0] == Path('c:/temp'): if Path('tests') in mypath.dirs(): Question: would this latter one actually work? Would this check items in the list using comparison or identity? Identity would simply be wrong here. [on removing properties in favour of methods for volatile data] > My line of thought is that a path may, but does not need to refer to an > existing, metadata-readable file. For this, I think a property is not > proper. Fair enough, though in either case an attempt to access that information leads to the same exception. I can't make a strong argument in favour of properties (nor against them, really). > What about iteration and indexing? Should it support > "for element in path" or "for char in path" or nothing? As John Roth suggests, the former seems a much more useful thing to do. The latter is probably as rarely needed as it is with regular strings (which I believe is roughly "never" in Python). [on .read_file_bytes() etc] > I think it is not exactly bad that these names are somehow outstanding, > as that demonstrates that something complex and special happens. Point taken. What about ditching the "file" part, since it is redundant and obvious that a file is in fact what is being accessed. Thus: .read_bytes(), .read_text(), .write_lines() etc. -Peter From kay.schluehr at gmx.net Sun Jul 17 05:52:14 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 17 Jul 2005 02:52:14 -0700 Subject: Ordering Products Message-ID: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Here might be an interesting puzzle for people who like sorting algorithms ( and no I'm not a student anymore and the problem is not a students 'homework' but a particular question associated with a computer algebra system in Python I'm currently developing in my sparetime ). For motivation lets define some expression class first: class Expr: def __init__(self, name=""): self.name = name self.factors = [self] def __mul__(self, other): p = Expr() if isinstance(other,Expr): other_factors = other.factors else: other_factors = [other] p.factors = self.factors+other_factors return p def __rmul__(self, other): p = M() p.factors = [other]+self.factors return p def __repr__(self): if self.name: return self.name else: return "*".join([str(x) for x in self.factors]) One can create arbitrary products of Expr objects ( and mixing numbers into the products ): >>> a,b,c = Expr("a"),Expr("b"),Expr("c") >>> a*b a*b >>> 7*a*8*9 7*a*8*9 The goal is to evaluate such products and/or to simplify them. For expressions like >>> x = 7*a*8*9 this might be easy, because we just have to sort the factor list and multiply the numbers. >>> x.factors.sort() >>> x a*7*8*9 -> a*504 This can be extended to arbitrary products: >>> x = 7*a*b*a*9 >>> x.factors.sort() >>> x a*a*b*7*9 -> (a**2)*b*63 Now lets drop the assumption that a and b commute. More general: let be M a set of expressions and X a subset of M where each element of X commutes with each element of M: how can a product with factors in M be evaluated/simplified under the condition of additional information X? It would be interesting to examine some sorting algorithms on factor lists with constrained item transpositions. Any suggestions? Regards, Kay From pkarjala at paju.oulu.fi Sat Jul 30 06:37:10 2005 From: pkarjala at paju.oulu.fi (Pekka Karjalainen) Date: Sat, 30 Jul 2005 10:37:10 +0000 (UTC) Subject: Graphics files & Python References: Message-ID: In article , Terry Reedy wrote: >Besides the other responses, you might also check out the pygame site where >there once were some tutorial examples of manipulating bitmaps with >Numerical Python to get various effects. > I'll keep this in mind too. Thanks to both for helpful replies. -- Pekka Karjalainen - Oulu, Finland From williams13 at llnl.gov Mon Jul 18 08:59:20 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Mon, 18 Jul 2005 05:59:20 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050718121633.GC3292@tishler.net> References: <41FF5A67.3090606@llnl.gov> <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> Message-ID: <42DBA7A8.4010509@llnl.gov> Dear Jason, Thanks for fixing this problem. I'm sure all the CDAT/Cygwin users really appreciate it. I'll put the update on the CDAT web portal. Best regards, Dean >Dean, > >On Tue, Feb 08, 2005 at 12:55:15PM -0500, Jason Tishler wrote: > > >>On Tue, Feb 08, 2005 at 08:01:11AM -0800, Dean N. Williams wrote: >> >> >>>$ rebaseall >>>/usr/bin/rebaseall: line 70: [: too many arguments >>>/usr/bin/rebaseall: line 75: [: too many arguments >>>/usr/bin/rebaseall: line 94: $TmpFile: ambiguous redirect >>>cannot read /cygdrive/c/Documents >>> >>>On my laptop installation everything works just fine. What is the >>>difference? >>> >>> >>The TMP and/or TEMP environment variables have at least two spaces in >>them. >> >>The easiest workaround is to execute rebaseall like the following: >> >> $ TMP=/tmp rebaseall >> >>Long term I will change rebaseall to deal better with spaces in shell >>variables. >> >> > >The above rebaseall problem has been fixed: > > http://cygwin.com/ml/cygwin-announce/2005-07/msg00031.html > >Jason > > > From Aiwass333 at gmail.com Sun Jul 24 15:10:47 2005 From: Aiwass333 at gmail.com (RunLevelZero) Date: 24 Jul 2005 12:10:47 -0700 Subject: Try this Message-ID: <1122232247.337991.322150@o13g2000cwo.googlegroups.com> I'm not sure I understand your first question but checkout the " glob " module. Sounds like it may help. Here is how you could get the folders and filenames import os list = os.walk("C:\python24\Tools") for file in list: folderlist = os.path.split(file[0]) print "****************Folder***************" print folderlist[1] print "=====================================" print print "****************Files*****************" print file[2] print "=====================================" From bartek.rylko at gmail.com Sat Jul 9 12:04:51 2005 From: bartek.rylko at gmail.com (bartek.rylko at gmail.com) Date: 9 Jul 2005 09:04:51 -0700 Subject: About undisclosed recipient Message-ID: <1120925091.660129.307800@g49g2000cwa.googlegroups.com> Hi all, Any one got idea about how to set undisclosed recipient? I put all recipient in BCC field while the To field don't want to leave blank. but neither fail to place an empty email address nor i don't want to put my own email address inside. www.bartekrr.info From k04jg02 at kzoo.edu Sun Jul 3 16:36:18 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Sun, 03 Jul 2005 14:36:18 -0600 Subject: Python for everything? In-Reply-To: <864qbf8hvr.fsf@bhuda.mired.org> References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> <864qbf8hvr.fsf@bhuda.mired.org> Message-ID: <42C84C42.6080905@kzoo.edu> Mike Meyer wrote: >You wind up >having to invoke the function through your data object, and then pass >the data object in - sort of as an explicit "self". > > > Yeah, and us pythonists hate explicit self! ;) From jeremy at emperorlinux.com Wed Jul 6 20:23:55 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Wed, 06 Jul 2005 20:23:55 -0400 Subject: Inheritance/Late Private Binding Message-ID: <1120695835.10103.8.camel@localhost.localdomain> class BaseClass: def __init__(self): self.__data = None def getMember(self): return self.__data class GoodSubClass(BaseClass): def __init__(self): BaseClass.__init__(self) class BadSubClass(BaseClass): def __init__(self): self.__x = None gsc = GoodSubClass() print dir(gsc) gsc.getMember() bsc = BadSubClass() print dir(bsc) bsc.getMember() ------------------------------------------------ Forgive me if this topic has been brought up before, but I was curious as to why I was getting this behavior and was hoping someone knowledgeable could explain. :) I "feel" like even without the explicit call to a simple base ctor(), mangling should still happen correctly. This doesnt, however, seem to be the case... Of note: simply doing a 'pass' in BadSubClass seems to be sufficient as well; so, it has something to do with defining a ctor() in the child and not explicitly invoking the parent's ctor. From gene.tani at gmail.com Fri Jul 22 13:17:13 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jul 2005 10:17:13 -0700 Subject: Detecting computers on network In-Reply-To: References: Message-ID: <1122052633.489908.94230@g49g2000cwa.googlegroups.com> Hi Sandeep, i didn't see where you said if these hosts you want to ping are on your internal network, or beyond your gateway. Probably the only truly reliable way to maintain an active hosts list is to install a ping-sending client on them, like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 And think about possible legal ramifications of port scanning hosts or possibly getting your IP blacklisted by a host's firewall, before you do it. From steve at REMOVETHIScyber.com.au Wed Jul 13 10:12:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 14 Jul 2005 00:12:15 +1000 Subject: Splitting on a word References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> Message-ID: On Wed, 13 Jul 2005 06:19:54 -0700, qwweeeit wrote: > Hi all, > I am writing a script to visualize (and print) > the web references hidden in the html files as: > ' underlined reference' > Optimizing my code, [red rag to bull] Because it was too slow? Or just to prove what a macho programmer you are? Is your code even working yet? If it isn't working, you shouldn't be trying to optimizing buggy code. > I found that an essential step is: > splitting on a word (in this case 'href'). Then just do it: py> ' underlined reference'.split('href') [' underlined reference'] If you are concerned about case issues, you can either convert the entire HTML file to lowercase, or you might write a case-insensitive regular expression to replace any "href" regardless of case with the lowercase version. [snip] > To be sure as delimiter I choose chr(127) > which surely is not present in the html file. I wouldn't bet my life on that. I've found some weird characters in HTML files. -- Steven. From lordverminard at gmail.com Wed Jul 27 13:04:45 2005 From: lordverminard at gmail.com (lordverminard at gmail.com) Date: 27 Jul 2005 10:04:45 -0700 Subject: anything to do Message-ID: <1122483885.865657.220790@f14g2000cwb.googlegroups.com> i hav just finished learning pythob from "A byte of python"(an online book) so i wanted to apply my new skills. to learn and to have some fun. is there any place which lists jobs to be done...you know minor jobs and requests thats nobody has found time to do. i would point out that i am not looking for a JOB as job with payment. i am looking for a JOB that is to be done and nobody has done it yet. also aside from this is there any other way i could use python and improve. i figure this practice will make me a lot better. but if anybody else has any ideas than that would be good too . From mwm at mired.org Tue Jul 5 12:00:04 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 05 Jul 2005 12:00:04 -0400 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> Message-ID: <86fyutxmyj.fsf@bhuda.mired.org> Jeffrey Maitland writes: > What I would like to do is have say 1 thread use as much of a given > CPU as possible and if a new thread is started (added) that if a CPU > is available use it instead of using the same cpu. That way it should > speed the application up. The standalone (non-threaded) app uses 90+ > % of a single cpu when in this part of the algorithm, that is why I > split and threaded that part of the algorithm there to try and speed > it up because this part is repeated several times. I can post > generic code of what I am doing but can't post the actuall code > because of the confidentially of it. Thanks again in advance for any > and all comments (even any spitefull ones) This kind of fine control over CPU allocation is very plaform-specific. Some don't allow it at all. If your platform does, the details on how you go about doing it will vary depending on the platform. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bla at bla.com Sun Jul 3 21:06:53 2005 From: bla at bla.com (Some Fred) Date: Mon, 04 Jul 2005 03:06:53 +0200 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <42C7067E.4090609@anvilcom.com> <200507022213.13343.hancock@anansispaceworks.com> Message-ID: On Sun, 03 Jul 2005 19:38:28 -0500, phil wrote: >Anyway, thanks Terry, I still don't know what Zope is but I need to >accept that it's just a toolkit and I'm not gonna know until >I dig in and as long as my web needs are simple, I probably won't. Actually, I found playing with CherryPy (http://www.cherrypy.org) an easier way to "get" Zope than digging into Zope directly. It also took me a good while to understand what an "application server" was, for that matter. AFAIK, Zope can be summed up as... - a server application that uses an object-oriented database (ZODB) to store items (static or dynamic HTML pages, images, scripts, etc.) as an alternative to storing data in either a SQL database and/or a filesystem (although Zope can connect to a SQL database, if need be) - the use of an OO-database makes it possible to map URLs to scripts (like it's done when mapping URLs to script pages in the filesystem), with some added benefits - a major benefit of the ZODB is "acquisition" (http://www.zope.org/Members/Amos/WhatIsAcquisition), ie. if an object is not found in the "directory" pointed to in the URL, ZODB will search for it by going up the tree all the way to the root, and either return the object if any is found along the way, or a 404. This makes it possible, for instance, to locate objects common to different sections of your site at the root of the site - scripts are mostly written in Python, since Zope is written partly in Python, and partly in C, although Zope also supports scripts in Perl. If you like, you can also write scripts ? la PHP, ie. include code in HTML pages, using two templating languages: DTML is the older one, and ZPT is the more recent one. HTH Fred. From bokr at oz.net Sun Jul 10 18:49:00 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 10 Jul 2005 22:49:00 GMT Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> Message-ID: <42d1a333.327534629@news.oz.net> On Sun, 10 Jul 2005 13:12:21 -0400, =?iso-8859-1?Q?Fran=E7ois?= Pinard wrote: >[Florian Diesch] > >> Probably this is usable for you (I never used any of them): > >> This system MAXIMA is [...] based on the original implementation of >> Macsyma at MIT [...] > >Wow! A derivative of Joel Moses' integrator!! I was not aware this >existed, so thanks for the pointer. It worked out of the box for me! > >> Description: A user-friendly frontend for MAXIMA >> Mascyma is (trying to be) a user-friendly graphical frontend for the Computer >> Algebra System GNU MAXIMA. It is written in Python and provides two GUIs, >> one of which based on PyGTK, the other based on wxPython. > >I was not successful googling for this one. Would you have an URL handy? > I also found http://packages.ubuntu.com/hoary/math/mascyma by googling for "A user-friendly frontend for MAXIMA" (I find that quoting a whole phrase that is likely to be repeated in docs and in references often finds stuff) Then googling for mascsyma [sic ;-)] got http://home.arcor.de/mulk/projects/mascyma/index.xhtml.de leading to screenshots at http://home.arcor.de/mulk/projects/mascyma/screenshots.xhtml.de No idea what the status of all that is, but looks nice. Regards, Bengt Richter From luismgz at gmail.com Mon Jul 18 22:14:03 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 18 Jul 2005 19:14:03 -0700 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) In-Reply-To: <1121718376.592482.36110@g14g2000cwa.googlegroups.com> References: <1121718376.592482.36110@g14g2000cwa.googlegroups.com> Message-ID: <1121739243.114743.156030@z14g2000cwz.googlegroups.com> Luis M. Gonzalez wrote: > As I said, "it is not python" (Peter Hansen, please don't jump to my > jugular...) Hey Pete, I was joking on that one! Here's the missing smiley ;-) From leszczynscyATnospam.yahoo.com.nospam Thu Jul 7 18:52:03 2005 From: leszczynscyATnospam.yahoo.com.nospam (Andy Leszczynski) Date: Thu, 07 Jul 2005 17:52:03 -0500 Subject: Berkely DB =?windows-1252?Q?=96_many_writers=2C_many_rea?= =?windows-1252?Q?ders?= Message-ID: I need to now option I open the Berkley DB (both db and env) to have configuration for multiple writers and multiple readers. Via multiple processes and multiple threads. No trx needed. A. From exuberant at gmail.com Wed Jul 20 19:46:19 2005 From: exuberant at gmail.com (Austin Cox) Date: 20 Jul 2005 16:46:19 -0700 Subject: Newbie question about lists Message-ID: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> Hello, I just started with python and have run into a problem using lists. If I enter: li = [.25,.10,.05,.01] and then enter: print li it'll output: [0.25, 0.10000000000000001, 0.050000000000000003, 0.01] Can anyone tell me why it does this, and how I can get just the value .10, and .05 into a list? Thanks. From skip at pobox.com Wed Jul 27 12:59:52 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 27 Jul 2005 11:59:52 -0500 Subject: A Module on Time & Date In-Reply-To: References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: <17127.48520.854360.200729@montanaro.dyndns.org> >> As you can see in the datetime documentation, the module was >> introduced in Python 2.3. I recommend updating your Python >> installation. Robert> What do you mean "your"?? I don't have any Python installation Robert> of my own. All I have is what this small local ISP provides on Robert> its Unix shell machine which I share with hundreds of other Robert> users. There's no way I can install a new version of anything on Robert> the system account. Your recommendation will be disregarded as Robert> total crap. If your ISP provides you with a C compiler, you can download and install Python yourself. Just create ~/local, add ~/local/bin to your PATH, then in the expanded Python source tree execute: ./configure --prefix=$HOME/local make make test make install Skip From rkern at ucsd.edu Sat Jul 23 09:45:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 23 Jul 2005 06:45:26 -0700 Subject: tuple to string? In-Reply-To: <42e24696$1@news.eftel.com> References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> Message-ID: John Machin wrote: > Reinhold Birkenfeld wrote: >>Ah, ok. Didn't want to lookup the precedence rules... > > Look up the precedence rules? Are you aware of any language where * / > and % _don't_ have the same precedence?? Given that % is somewhat more esoteric, I certainly have never committed to memory its position in a precedence hierarchy of *any* language. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rrr at ronadam.com Wed Jul 20 06:08:11 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 20 Jul 2005 10:08:11 GMT Subject: Ordering Products In-Reply-To: <1121838698.759788.310170@g14g2000cwa.googlegroups.com> References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121752847.005587.145960@g44g2000cwa.googlegroups.com> <1121838698.759788.310170@g14g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Ron Adam wrote: > >> Kay Schluehr wrote: >> BTW.. Usually when people say "I don't want to discourage...", They >> really want or mean the exact oppisite. > > Yes, but taken some renitence into account they will provoke the > opposite. Old game theoretic wisdoms ;) True.. but I think it's not predictable which response you will get from an individual you aren't familiar with. I prefer positive reinforcement over negative provocation myself. :-) > But you seem to fix behaviour together with an operation i.e. > declaring that __mul__ is commutative. But in a general case you > might have elements that commute, others that anti-commute ( i.e. a*b > = -b*a ) and again others where no special rule is provided i.e. they > simply don't commute. > > But much worse than this the definition of the operations __add__, > __mul__ etc. use names of subclasses A,D explicitely(!) what means > that the framework can't be extended by inheritance of A,D,M etc. > This is not only bad OO style but customizing operations ( i.e. > making __mul__ right associative ) for certain classes is prevented > this way. One really has to assume a global behaviour fixed once as a > class attribute. I don't know if it's bad OO style because I chose a flatter model. Your original question wasn't "what would be the best class structure to use where different algebra's may be used". It was how can sorting be done to an expression with constraints. And you gave an example which set __mul__ as associative as well. So this is a different problem. No use trying to point that what I did doesn't fit this new problem, it wasn't suppose to. ;-) I'm not sure what the best class structure would be. With the current example, I would need to copy and edit F and it's associated sub class's to create a second algebra type, F2, A2, M2.. etc. Not the best solution to this additional problem which is what you are pointing out I believe. So... We have factors (objects), groups (expressions), and algebras (rules), that need to be organized into a class structure that can be extended easily. Does that describe this new problem adequately? I'm not sure what the best, or possible good solutions would be at the moment. I'll have to think about it a bit. >> c*3*a*d*c*b*7*c*d*a = (21*a*a*b*c*c*c*d*d) > > > I still don't see how you distinguish between factors that might > commute and others that don't. I don't want a and b commute but c and > d with all other elements. In my example factors don't commute. They are just units, however factors within a group unit may commute because a group is allowed to commute factors if the operation the group is associated to is commutable. > If you have fun with those identities you might like to find > simplifications for those expressions too: > > a*0 -> 0 a*1 -> a 1/a/b -> b/a a+b+a -> 2*a+b a/a -> 1 a**1 -> > a > > etc. Already did a few of those. Some of these involve changing a group into a different group which was a bit of a challenge since an instance can't magically change itself into another type of instance, so the parent group has to request the sub-group to return a simplified or expanded instance, then the parent can replace the group with the new returned instance. a*a*a -> a**3 change from a M group to a P group. a*0 -> 0 change from a M group to an integer. a*1 -> a change from a M group to a F unit. a+b+a -> 2*a+b change a A subgroup to a M group. a/a -> change a D group to an integer. a**1 -> change a P group to a M group to a F unit. Some of those would be done in the simplify method of the group. I've added an expand method and gotten it to work on some things also. a*b**3 -> a*b*b*b c*4 -> c+c+c+c >> What do you mean by 'sub-algebra generation'? > > Partially what I described in the subsequent example: the target of > the addition of two elements x,y of X is again in X. This is not > obvious if one takes an arbitrary nonempty subset X of Expr. Would that be similar to the simultaneous equation below? z = x+y <- term x+y is z x = a*z+b <- z is in term x x = a(x+y)+b <- x is again in x (?) I think this would be... >>> x, y = F('x'), F('y') >>> z = x+y >>> x = a*z+b >>> x (((x+y)*a)+b) This wouldn't actually solve for x since it doesn't take into account the left side of the = in the equation. And it would need an eval method to actually evaluated it. eval(str(expr)) does work if all the factors are given values first. Cheers, Ron From peter at engcorp.com Wed Jul 6 09:45:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Jul 2005 09:45:56 -0400 Subject: Use cases for del In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: > How about just getting rid of del? Removal from collections could be > done with a method call, and i'm not convinced that deleting variables > is something we really need to be able to do (most other languages > manage without it). Arguing the case for del: how would I, in doing automated testing, ensure that I've returned everything to a "clean" starting point in all cases if I can't delete variables? Sometimes a global is the simplest way to do something... how do I delete a global if not with "del"? -Peter From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 16:41:17 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 22:41:17 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <42e5489f.1138078400@news.oz.net> References: <3kjihkFubvl6U1@individual.net> <74SdndmpGeuannjfRVn-1w@powergate.ca> <42e5489f.1138078400@news.oz.net> Message-ID: <3kl13eFumm37U1@individual.net> Bengt Richter wrote: > BTW, more OT, wouldn't '|' be more platform-neutral as the joining operator? I, on the other hand, would certainly prefer U+01C1. Reinhold From samgurung at gmail.com Sat Jul 23 05:18:34 2005 From: samgurung at gmail.com (linuxfreak) Date: 23 Jul 2005 02:18:34 -0700 Subject: SPE Ide Crash Message-ID: <1122110314.436649.290920@f14g2000cwb.googlegroups.com> Hi Stani, Downloaded your latest SPE editor 0.7.4.m . I'm running wxPython 2.6.1 on a Fedora Core 4 machine. The IDE is great but guess what it crashes without warning. Was typing some code and boom the whole thing disappeared without a trace. Thought should let you know All you guys using this IDE has it ever crashed on you like this??? From tzot at sil-tec.gr Fri Jul 1 16:21:11 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 01 Jul 2005 23:21:11 +0300 Subject: Controlling WinAMP (WM_COPYDATA problem) References: <1120157311.921062.21570@o13g2000cwo.googlegroups.com> Message-ID: On 30 Jun 2005 11:48:31 -0700, rumours say that "The Collector" might have written: >Hi, > >I've been looking for almost two full days now to get full control of >WinAMP using python. Simple play/stop functions are no problem. It's >the WM_COPYDATA that's used by IPC_PLAYFILE (=add a file to the >playlist) that's giving me troubles big time! An alternative that could be easier to use is WinAmpCOM (a plugin for winamp that makes it a COM server, so using pywin32 or ctypes you can control it with much ease.) It's available in the www.winamp.com site. (Search for plugin "winampcom") -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 12:57:37 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 18:57:37 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: <3l1ps1F10ieouU1@individual.net> phil hunt wrote: > On Fri, 29 Jul 2005 14:38:23 +1200, Tony Meyer wrote: >>> def functions_which_modifies_some_file_in_place(path): >>> output = open(path+'.tmp', 'w') >>> ..... >>> >>> I dont want a seperator inserted between path and the new extension. >> >>Fair enough. Forget using '+' for join, then (which I was never that keen >>on - TIOWTDI), but I'm still -1 on using '/' for join. > > I agree. It's yuck. So don't use it. > What's wrong with simply having each path-element as an argument to > a function, e.g. > > join(foo, bar, baz) Nothing's wrong, and you can do it this way too. Path(foo, bar, baz) or Path(foo).joinwith(bar, baz) Reinhold From steve at REMOVETHIScyber.com.au Tue Jul 19 10:12:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 20 Jul 2005 00:12:15 +1000 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? References: Message-ID: On Tue, 19 Jul 2005 07:24:19 +0100, Chris wrote: > Could anyone write a small program to log the Signal-to-Noise figures > for a Netgear DG834 router? Are you offering to pay somebody to do it, or just suggesting a project for some Python programmer who is bored and looking for a small project to work on out of love? -- Steven. From python-url at phaseit.net Tue Jul 5 14:08:07 2005 From: python-url at phaseit.net (Simon Brunning) Date: Tue, 05 Jul 2005 18:08:07 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 5) Message-ID: QOTW: "That's what I love in that news group. Someone comes with a stupid and arrogant question, and someone else answers in a calm and reasonable way." - Gustavo Niemeyer "After 25 years doing this, I've become something of a Luddite as far as fancy IDEs and non-standard features go... and a huge believer in strict decoupling between my tools, to the point of ignoring things that bundle them together in ways that are, in my opinion, too tight." - Peter Hansen Ralf Grosse-Kunstleve floats a proposal to reduce the amount of code requires to set instance fields from arguments in __init__ methods: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7346ad00a14e821a The Python Software Foundation Summer of Code projects have been selected: http://www.amk.ca/diary/archives/003975.html A discussion about the long-term plan to remove map, filter, reduce and lambda starts out bad-tempered then ... improves little: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ceef909ebd10b65a There's a new wxPython tutorial at Dev Shed: http://www.devshed.com/c/a/Python/A-Look-at-wxPython/ Peter Hansen wants to determine the wall-clock elapsed time taken by a process on a managed host in a reliable, cross-platform way: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cd1222d713730b67 Par Nicolas Lehuen uses Python to compare Microsoft Word documents stored in a Subversion repository (!): http://www.lehuen.com/nicolas/index.php/2005/06/30/60-comparing-microsoft-word-documents-stored-in-a-subversion-repository Terry Hancock explains what ZOPE actually is: http://groups-beta.google.com/group/comp.lang.python/msg/174d4101e0e419e8 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From python at rcn.com Mon Jul 18 03:59:36 2005 From: python at rcn.com (Raymond Hettinger) Date: 18 Jul 2005 00:59:36 -0700 Subject: Environment Variable References: Message-ID: <1121673576.646881.92220@g44g2000cwa.googlegroups.com> [Vivek Chaudhary] > Is it possible to set an environment variable in python script whose > value is retained even after the script exits. There is an indirect approach: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159462 Raymond From http Wed Jul 20 17:26:24 2005 From: http (Paul Rubin) Date: 20 Jul 2005 14:26:24 -0700 Subject: Lots of pdf files References: Message-ID: <7xu0iptbi7.fsf@ruckus.brouhaha.com> Greg Lindstrom writes: > There does not appear to be a simple way to merge many pdf's into one. There's probably some way to do it with pstops or some related program or set of programs. From ironfroggy at gmail.com Fri Jul 29 13:02:44 2005 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 29 Jul 2005 13:02:44 -0400 Subject: Ten Essential Development Practices In-Reply-To: <76fd5acf05072909565e9ebd9e@mail.gmail.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <5f4d3cb50507290806162c2d09@mail.gmail.com> <76fd5acf05072909565e9ebd9e@mail.gmail.com> Message-ID: <76fd5acf050729100255f1ab69@mail.gmail.com> On 7/29/05, Dark Cowherd wrote: > I am new to Python. I tried it out and think it is fantastic. Congrats and have fun learning all there is to learn. > I really loved this from import this statements: > > There should be one-- and preferably only one --obvious way to do it. > > But this not true of Python. > GUI, Web development, Application Framework - it is shambles. It is so > frustrating for a person who comes from a well designed environment / > framework like Delphi. Well, consider also that all these frameworks and similar such projects are not Python the Language, and as such are allowed to have a few more ways to do it. There is movement toward convergence on many fronts, with efforts such as WSGI and the anygui package. I don't believe there should be only one way to do a thing at the beginning, and in many ways we are still at the beginning of many areas, but we need to spread our collective tentacles into many ideas and try what works. What is great about Python is that after some time with works being quite seperate, such as the many implementations of interfaces and adaptation systems, we are able to converge them, as is currently proposed and likely to occure soon. We need to test out many things and get a feel for the use of something before we can decide what the one way to do it should be. Python makes it easy to test all the different waters, and then to combine them into the best solution, when the community is ready to do so. > My organisation writes products for Small and Medium Enterprises. We > are using Delphi, we want to do more web based and Linux solutions, so > I was evaluating Python, but even though I love the language and will > probably do hobby programming using the language, I wouldnt really > recommend our organisation to plan and execute a tranisition. Thats a shame, really. > We have been around a while and we have planned and done transitions > from Clipper to FoxproW to VB to Delphi. > > >From what I understand Database access was in similar shambles in > Python but a SIG took up the task and made some decisions which has > now streamlined database access in Python. > > I really would love to have a Python where TOOWTDI > > Is there some place to discuss topics like this? Is this the right place? > -- > DarkCowherd > -- > http://mail.python.org/mailman/listinfo/python-list > From deez at next-level.com.au Thu Jul 21 19:32:15 2005 From: deez at next-level.com.au (Ric Deez) Date: Fri, 22 Jul 2005 07:32:15 +0800 Subject: Returning histogram-like data for items in a list Message-ID: Hi there, I have a list: L1 = [1,1,1,2,2,3] How can I easily turn this into a list of tuples where the first element is the list element and the second is the number of times it occurs in the list (I think that this is referred to as a histogram): i.e.: L2 = [(1,3),(2,2),(3,1)] I was doing something like: myDict = {} for i in L1: myDict.setdefault(i,[]).append(i) then doing this: L2 = [] for k, v in myDict.iteritems(): L2.append((k, len(v))) This works but I sort of feel like there ought to be an easier way, rather than to have to store the list elements, when all I want is a count of them. Would anyone care to comment? I also tried this trick, where locals()['_[1]'] refers to the list comprehension itself as it gets built, but it gave me unexpected results: >>> L2 = [(i, len(i)) for i in L2 if not i in locals()['_[1]']] >>> L2 [((1, 3), 2), ((2, 2), 2), ((3, 1), 2)] i.e. I don't understand why each tuple is being counted as well. Regards, Ric From falcon3166 at hotmail.com Sun Jul 3 02:52:02 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 3 Jul 2005 00:52:02 -0600 Subject: How to get 4 numbers from the user in one line for easy comparision? Message-ID: I saw that great idea from Steven, and I appreciate it. I think it will work. Just need to figure out how to get 4 numbers from the player on one line for easy comparison, e.g. telling whether the number is correct position and number, incorrect position and correct number, or both are incorrect. If anyone has any advice in how to code this, I will gladly appreciate the help. Sorry if I seem like a newbie, but I am! :) Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstier at cs.uvic.ca Thu Jul 7 07:52:11 2005 From: jstier at cs.uvic.ca (J) Date: 7 Jul 2005 04:52:11 -0700 Subject: VC++ linking problem Message-ID: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> Hi everyone, I started embedding python into a 3D graphics App and I came across this linking problem. SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol __imp__Py_InitModule4TraceRefs SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol __imp___Py_RefTotal SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol __imp___Py_RefTotal I am linking against python24.lib using VC++ 6.0. Before I got to this point it couldn't find python24_d.lib. After searching around for a while I came across a solution that included changing python24_d.lib to python24.lib in one of the header files. I hope that didn't have a negative effect. I would really appreciate some help.... Thanks Jochen From jepler at unpythonic.net Tue Jul 5 10:25:19 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 5 Jul 2005 09:25:19 -0500 Subject: Tkinter + Tcl help In-Reply-To: <1120544185.116872.177600@g14g2000cwa.googlegroups.com> References: <1120544185.116872.177600@g14g2000cwa.googlegroups.com> Message-ID: <20050705142515.GE7252@unpythonic.net> I think you need to write root.tk.eval('load', '...\\libtcldot.so.0') When you write root.tk.eval("x y z") it's like doing this at the wish/tclsh prompt: # {x y z} Not like this: # x y z Now, how useful it is to have a command called "x y z", I can't guess... but tcl would let you do it. I've also doubled the backslash in your library filename. When using windows-style paths in string literals, you must either double the backslashes, or use r'' strings. When you don't, it will often work, but if the character after the un-doubled backslash is one with special meaning (including the commonly-seen \r and \t, but also other letters) then you'll get a pathname and an error that leave you scratching your head. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dlyzxl at yahoo.com Fri Jul 1 11:24:37 2005 From: dlyzxl at yahoo.com (Justin) Date: Fri, 1 Jul 2005 08:24:37 -0700 (PDT) Subject: missing cephes module Message-ID: <20050701152438.5323.qmail@web51108.mail.yahoo.com> When I used py2exe to create executable file, "cephes" module missing error occurred. I have installed python 2.3 and scientific and numeric python. Can anybody suggest me how to resolve the problem? Justin __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 08:15:49 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 14:15:49 +0200 Subject: Separation of Code in CGI App References: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> Message-ID: Rob Cowie enlightened us with: > I need to create a planner/calendar system using python cgi scripts. > It is my first CGI app (beyond a few tutorial examples). Are you sure you want to use CGI? I'd go for mod_python instead if at all possible, since that'll give you a much better performance. > To do this, do I just create each of these classes in one, > monolithic .cgi file? Please don't. It's much better to put things into modules, and import them when needed. > or is it possible to separate these out into different scripts and > have a 'controller' script call them and pass the relevant > parameters/data? I guess I could also store the python code in text > files and use the 'execfile()' function, although it seems to me > that would be an uneccasary performance hit. Why that difficult? What's wrong with just doing "from htmlgenerator import pagexy"? > If that is possible, is that the right way to go? If not, > suggestions would be gratefully recieved! Check out http://www.unrealtower.org/mycheetah Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From jason at tishler.net Tue Jul 19 07:15:37 2005 From: jason at tishler.net (Jason Tishler) Date: Tue, 19 Jul 2005 07:15:37 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42DBA7A8.4010509@llnl.gov> References: <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> Message-ID: <20050719111537.GC532@tishler.net> Dean, On Mon, Jul 18, 2005 at 05:59:20AM -0700, Dean N. Williams wrote: > Thanks for fixing this problem. You are quite welcome. Thanks for your patience. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From ujelin at yahoo.com Tue Jul 12 12:47:35 2005 From: ujelin at yahoo.com (ulrice jardin) Date: Tue, 12 Jul 2005 09:47:35 -0700 (PDT) Subject: automatic form filling In-Reply-To: <138d8649afbce751834a64e48397064b@upf.edu> Message-ID: <20050712164735.52112.qmail@web60320.mail.yahoo.com> Thanks A LOT for your help! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From fdeserres at gmx.net Wed Jul 13 09:21:50 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 15:21:50 +0200 Subject: **kwargs? In-Reply-To: References: <7OWdnRBJ_sGqkkjfRVn-hw@powergate.ca> Message-ID: <42D5156E.7000508@gmx.net> Michael Hoffman wrote: >Peter Hansen wrote: > > >>Francois De Serres wrote: >> >> >> > > > >>>*args is documented in the Tutorial. I reckon **kwargs represents a >>>dictionary of arguments. But I don't quite get the semantics of **x. >>>Undefined length tuple of undefined length tuples? Are there other >>>practical use cases for ** (common enough please, I wish I was, but >>>I'm not a scientist). >>> >>> >>Where did you get "tuples of tuples" for **x ? >> >> > >I would guess it is confusion from languages where unary * means >dereference and ** means double dereference. > > That was precisely my mistake. >To the OP: I'm glad you have been reading the tutorial. If you have >further questions the reference manual is a good place to look: > >http://docs.python.org/ref/function.html > > Now I see, there's a '**' token, which is not the same as two adjacents '*' tokens. >Just as you can use a name other than self as the first argument to an >unbound method, you can call your *args and **kwargs *x and **y instead, >but they will still act just like *args and **kwargs. > >The stars are magic, not the names. > > Thanks mucho! F. From rwgk at yahoo.com Thu Jul 14 10:43:02 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Thu, 14 Jul 2005 07:43:02 -0700 (PDT) Subject: How can I import a py script by its absolute path name? In-Reply-To: <311b5ce105071404412d4bf318@mail.gmail.com> Message-ID: <20050714144302.36439.qmail@web31501.mail.mud.yahoo.com> % python Python 2.4.1 (#1, Apr 7 2005, 11:06:30) [C] on osf1V5 Type "help", "copyright", "credits" or "license" for more information. >>> execfile.__doc__ 'execfile(filename[, globals[, locals]])\n\nRead and execute a Python script from a file.\nThe globals and locals are dictionaries, defaulting to the current\nglobals and locals. If only globals is given, locals defaults to it.' >>> --- could ildg wrote: > I want to import c:\xxx\yyy\zzz.py into my programme, > What should I do? > Thank you~ > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From sjmachin at lexicon.net Thu Jul 14 09:18:34 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Jul 2005 23:18:34 +1000 Subject: all possible combinations In-Reply-To: References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> Message-ID: <42d6662a$1@news.eftel.com> Steven D'Aprano wrote: > On Thu, 14 Jul 2005 08:49:05 +1000, John Machin wrote: > > >>"You keep using that word. I do not think it means what you think it means." >> >>Both of you please google("define: combination") > > > Combination: "a coordinated sequence of chess moves". > > "An option position that is effected by either a purchase of two long > positions or two short positions. The investor purchases a call and a put > (or sells a call and a put) with different expiration dates and/or > different strike prices." > > Or perhaps "in Scheme, a function call, consisting of a function name and > arguments written within parentheses." > > Yes, mathematically the definition of combination includes that order does > not matter. But that certainly isn't the case in common English. Now, > John, given the tone of the posts you are complaining about, Wrong -- no complaint. Another quote: "It's a joke, Joyce!" > do you think > I was using combination in the precise mathematical sense, or the common > English sense? As in "Please don't get your combinations in a twist?"? > > (Hint: the very first definition Google finds is "a collection of things > that have been combined; an assemblage of separate parts or qualities ". > Not a word there about order mattering or not.) From me at privacy.net Thu Jul 14 22:56:13 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 14 Jul 2005 22:56:13 -0400 Subject: Generating a list of None References: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> <1121394494.674503.303040@z14g2000cwz.googlegroups.com> Message-ID: On 14 Jul 2005 19:28:14 -0700, "Nicolas Couture" wrote: > if vals == [None * len(vals)]: if vals == [None] * len(vals): Regards, Dan -- Dan Sommers From dave at pythonapocrypha.com Sat Jul 9 18:32:41 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 09 Jul 2005 16:32:41 -0600 Subject: Yet Another Python Web Programming Question In-Reply-To: <1d6cdae305070913436fcef8b4@mail.gmail.com> References: <1d6cdae305070913436fcef8b4@mail.gmail.com> Message-ID: <42D05089.1090209@pythonapocrypha.com> Daniel Bickett wrote: > He would read the documentation of Nevow, Zope, and Quixote, and would > find none of them to his liking because: > > * They had a learning curve, and he was not at all interested, being > eager to fulfill his new idea for the web app. It was his opinion that > web programming should feel no different from desktop programming. > > * They required installation (as opposed to, simply, the placement of > modules), whereas the only pythonic freedom he had on his hosting was > a folder in his /home/ dir that was in the python system path. I've been playing with CherryPy lately, and it's been a lot of fun (for me, it meets both the above requirements - obviously anything will have a learning curve, but CherryPy's is very small). -Dave From mrmaple at gmail.com Mon Jul 11 10:55:00 2005 From: mrmaple at gmail.com (James Carroll) Date: Mon, 11 Jul 2005 10:55:00 -0400 Subject: cursor positioning In-Reply-To: <20050711144249.374391E4002@bag.python.org> References: <42D281D2.9060302@mage.hu> <20050711144249.374391E4002@bag.python.org> Message-ID: I haven't tried this myself, but I think the secret to displaying a continuously updating %done on the command line is to print "file 100, 1% done" then send exactly 7 backspaces to the terminal, then print 2% done... so the backspaces will write over the previous text. Backspace is a \x08 (ascii character with the value 8.) It _could_ work... -Jim On 7/11/05, Albert Leibbrandt wrote: > -----Original Message----- > From: python-list-bounces+albert=compuscan.co.za at python.org > [mailto:python-list-bounces+albert=compuscan.co.za at python.org] On Behalf Of > Mage > Sent: 11 July 2005 04:28 PM > To: python-list at python.org > Subject: Re: cursor positioning > > Larry Bates wrote: > > >While not "curses" based this class will update screen as you > >want. You could use it as a basis upon which to do a curses > >version with your cursor positioning. > > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 > > > > > > > Thank you. This is good for displaying the percentage. > However it fails to display this: > 100 files read > 200 files read > 300 files read > .... > > of course all in the same line and not under the last line. > > Mage > > > -- > Why not use something like this? > > counter = 0 > > while 1: > if (counter % 100) == 0: > print'%s files read '%counter > counter += 1 > > -- > http://mail.python.org/mailman/listinfo/python-list > > From jeremy at emperorlinux.com Fri Jul 8 00:28:11 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Fri, 08 Jul 2005 00:28:11 -0400 Subject: Polling, Fifos, and Linux Message-ID: <1120796891.9639.6.camel@localhost.localdomain> This is my first time working with some of the more lower-level python "stuff." I was wondering if someone could tell me what I'm doing wrong with my simple test here? Basically, what I need is an easy way for application in userspace to simply echo values "down" to this fifo similar to the way proc files are used. Is my understanding of fifo's and their capabilities just totally off base? I've implemented something very similar in the past in C which works fine; however, this app immediately takes up 100% of my CPU after the first read from the fifo, regardless of whatever options I pass to os.open(). Am I not actually reading the data out of the fifo? Is that what's causing it to poll infinite thereafter? Any help would be greatly appreciate, though I'll keep reading and experimenting in the meantime. #!/usr/bin/env python import select import os poller = select.poll() fifo = os.open("fifo", os.O_RDONLY | os.O_NONBLOCK) poller.register(fifo, select.POLLIN) while True: p = poller.poll() # only have one file string = os.read(p[0][0], 1) if len(string): print string From martin at v.loewis.de Sun Jul 31 15:10:17 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 31 Jul 2005 21:10:17 +0200 Subject: How override ALL function calls? (Is there a "function call function"?) In-Reply-To: <1122833096.778839.209730@g14g2000cwa.googlegroups.com> References: <1122833096.778839.209730@g14g2000cwa.googlegroups.com> Message-ID: <42ed2219$0$6928$9b622d9e@news.freenet.de> seberino at spawar.navy.mil wrote: > I'm trying run a homegrown profiler on some Python code. > > Rather than apply profiler wrapper to ALL functions by hand.... > > Is there a low level Python function I can override to modify > > how ALL functions are called? Yes, please take a look at sys.setprofile(). Regards, Martin From daniel.dittmar at sap.corp Mon Jul 25 04:59:14 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 25 Jul 2005 10:59:14 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com><3kakh5Ftjd9mU1@individual.net><11e0cpe7vqrm18a@news.supernews.com><1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Terry Reedy wrote: > for dir in pathobject: > if isdir(dir): cd(dir) > > *is*, in essence, what the OS mainly does with paths (after splitting the > string representation into pieces). That's why there is rarely a need to to it in Python code. > Directory walks also work with paths as sequences (stacks, in particular). I'd say it works with stacks of pathes, not with stacks of path elements. I'm not saying that there isn't any use for having a list of path elements. But it isn't that common, so it should get an methodname to make it more explicit. Daniel From jason at tishler.net Wed Jul 27 17:03:07 2005 From: jason at tishler.net (Jason Tishler) Date: Wed, 27 Jul 2005 17:03:07 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E7E351.3030706@llnl.gov> References: <20050725201132.GA3440@tishler.net> <20050727191626.GC2272@tishler.net> <42E7E351.3030706@llnl.gov> Message-ID: <20050727210307.GB3876@tishler.net> Dean, On Wed, Jul 27, 2005 at 12:41:05PM -0700, Dean N. Williams wrote: > Thanks for fixing this bug in Cygwin. You are welcome. However, I didn't fix it -- I just got it fixed. :,) > Remember there was another undefined variable for the Python build > _bsd... I didn't get this error. Did you forgot to install one of the libdb${version}-devel packages: $ cygcheck -cd | grep 'libdb.*-devel' libdb2-devel 2.7.7-4 libdb3.1-devel 3.1.17-2 libdb4.1-devel 4.1.25-1 libdb4.2-devel 4.2.52-1 Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From twic at urchin.earth.li Sat Jul 2 10:20:11 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 2 Jul 2005 15:20:11 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: <42c58af2$1@nntp0.pdx.net> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> <42c58af2$1@nntp0.pdx.net> Message-ID: On Fri, 1 Jul 2005, Scott David Daniels wrote: > Daniel Dittmar wrote: >> Rocco Moretti wrote: >> >>>>> Except that (please correct me if I'm wrong) there is somewhat of a >>>>> policy for not including interface code for third party programs >>>>> which are not part of the operating system. (I.e. the modules in the >>>>> standard libary should all be usable for anyone with a default OS + >>>>> Python install.) >> >> There seems to be a great reluctance by the Python developers to add >> modules of the expat kind, as this means responsibilities for >> additional source modules. There's also the problem with incompatible >> licenses, integrating a second configure, deciding when to update to >> the latest version of the library etc. > > If you haven't noticed, the Python code has a substantial body of unit > tests. Arranging the tests to be easily runnable for all developers > is going to be tough for "third party programs." The tests for interface modules would have to use mock objects on the back end. This is pretty standard practice, isn't it? > Making the interfaces work for differing versions of the 3PPs as the > third parties themselves change their interfaces (see fun with Tcl/Tk > versions for example), and building testbeds to test to all of those > differing versions, would cause a nightmare that would make a knight of > Ni scream. But given that at a number of such modules have in fact been written, along with tests, why not add them to the standard distribution? tom -- REMOVE AND DESTROY From miki.tebeka at zoran.com Mon Jul 18 06:47:16 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 18 Jul 2005 13:47:16 +0300 Subject: email format in python In-Reply-To: <20050718102120.64241.qmail@web42004.mail.yahoo.com> References: <20050718102120.64241.qmail@web42004.mail.yahoo.com> Message-ID: <20050718104716.GI3448@zoran.com> Hello met, > I want to have the python equivalent function of this > (that checks email format) > > function CheckEmail($Email = "") { > if (ereg("[[:alnum:]]+@[[:alnum:]]+\.[[:alnum:]]+", > $Email)) { > return true; > } else { > return false; > } > } Check out the "email" library module (see the examples at http://docs.python.org/lib/node589.html) Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From gsakkis at rutgers.edu Mon Jul 11 20:17:01 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 11 Jul 2005 17:17:01 -0700 Subject: Access descendant class's module namespace from superclass References: Message-ID: <1121127421.436333.61610@o13g2000cwo.googlegroups.com> "Reid Priedhorsky" wrote: > Dear group, > > I'd have a class defined in one module, which descends from another class > defined in a different module. I'd like the superclass to be able to > access objects defined in the first module (given an instance of the first > class) without importing it. Example of what I'm looking for: > > <<>> > > class Spam(object): > def fish(self): > a = self.__module__.Ham() > > <<>> > > import spam > > class Eggs(spam.Spam): > pass > > class Ham(object): > pass > > The above doesn't work because __module__ is a string, not a module object: > > >>> import eggs > >>> b = eggs.Eggs() > >>> b.fish() > Traceback (most recent call last): > File "", line 1, in ? > File "spam.py", line 3, in foo > a = self.__module__.Ham() > AttributeError: 'str' object has no attribute 'Ham' > > (I suppose I could call __import__(self.__module__), but that seems kind > of awkward.) > > Is this possible using Python 2.3? Any better ways to accomplish this? I don't know if it's "better", but since you know that self.__module__ has already been imported, you can access it through the sys.modules dict: a = sys.modules[self.__module__].Ham() By the way, this seems like an error-prone hack. Are you sure you want to relate two independent classes just by the fact that they rely in the same file ? Remember, explicit is better than implicit. George From markturansky at gmail.com Thu Jul 7 00:03:05 2005 From: markturansky at gmail.com (markturansky at gmail.com) Date: 6 Jul 2005 21:03:05 -0700 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? In-Reply-To: References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: <1120708985.294170.77500@g14g2000cwa.googlegroups.com> getattr does not work on a running script (afaik) because 'self' is undefined. The poster above got it right using 'locals()' From jcarlson at uci.edu Sat Jul 2 15:54:26 2005 From: jcarlson at uci.edu (jcarlson at uci.edu) Date: 2 Jul 2005 12:54:26 -0700 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: References: Message-ID: <1120334066.363578.307920@g14g2000cwa.googlegroups.com> Ralf W. Grosse-Kunstleve wrote: > A shorter alternative (my personal favorite since minimally redundant):: > > class grouping: > > def __init__(self, .keep_this, .and_this, but_not_this, .but_this_again): > # real code right here There is also the variant which I proposed on python-dev: class grouping: def __init__(self, _keep_this, _and_this, but_not_this, _but this again): InitAttrs(self, locals()) #real code goes here Essentially you replace the '.' with '_', which doesn't require a syntax change. Unfortunately, both are almost invisible. It does offer you what you want right now (without that whole waiting a year+ for Python 2.5, PEP process, etc.). > Enhanced __slot__ semantics proposal > ------------------------------------ > > When ``__slots__`` are used (cool feature!) the boilerplate problem > becomes even worse:: > > class grouping: > > __slots__ = ["keep_this", "and_this", "but_this_again"] > > def __init__(self, keep_this, and_this, but_not_this, but_this_again): > self.keep_this = keep_this > self.and_this = and_this > self.but_this_again = but_this_again > # real code, finally There is also the AutoSlots metaclass (which I have fixed) that does this as well. class grouping(object): __metaclass__ = AutoSlots def __init__(self, _keep_this, _and_this, but_not_this, _but_this_again): InitAttrs(self, locals()) #real code goes here Both AutoSlots and InitAttrs use leading underscores on the __init__ method to discover which attributes are to be __slots__, and which should be automatically assigned. > P.S.: If you reply to this message, please clearly separate > naming/syntax issues from the core issue of providing built-in support > designed to reduce clutter. Because you don't seem to have listened in python-dev, I'll say it here. Not everything that reduces clutter should be syntax, and not every function, class, and module which reduces programming time should be builtin. Why? 1. Expanding Python syntax bloats the language. It increases what you need to teach to new Python users. In my opinion, syntax additions should really only be considered when significant gains in readability and writability for many users are realized, that a lack of syntax cannot offer. 2. Expanding the Python standard library bloats the distribution. Right now, Python is a relatively light download. But if one were to include the top packages in everything, the distribution would quickly bloat to 40+ megs. This is not an option. Generally, the requirements of getting code into the standard library is either a demonstrated need for the addition, or a known best-of-breed implementation for a commonly used module, or both. I believe your syntax change is a non-starter. Why? Because I've offered code that does essentially everything you want, without a syntax change. If someone happens to include AutoSlots and InitAttrs with their code, module, what have you, and it manages to make its way into standard Python, so be it (I place the code into the public domain). The code for the InitAttrs and AutoSlots mechanism are available here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435880 - Josiah From http Thu Jul 14 15:57:08 2005 From: http (Paul Rubin) Date: 14 Jul 2005 12:57:08 -0700 Subject: all possible combinations References: Message-ID: <7xy889i2jv.fsf@ruckus.brouhaha.com> rbt writes: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: for i in xrange(81): print ''.join(['abcd'[j] for j in [(i//d)%3 for d in (27,9,3,1)]]) From yendor at arcticmail.com Thu Jul 7 05:21:41 2005 From: yendor at arcticmail.com (Ert Ert) Date: Thu, 07 Jul 2005 04:21:41 -0500 Subject: HELP! Message-ID: <20050707092141.5ED904BEAD@ws1-1.us4.outblaze.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From jason at mobarak.name Fri Jul 15 17:55:50 2005 From: jason at mobarak.name (Jason Mobarak) Date: Fri, 15 Jul 2005 15:55:50 -0600 Subject: IDLE in Jython In-Reply-To: References: <1121436094.769121.247470@z14g2000cwz.googlegroups.com> Message-ID: Casey Hawthorne wrote: > How about the following: > > - making Jython mostly work up to Python 2.4? http://www.python.org/psf/grants (see the first grant) There's already a grant in place for this. So hopefully someone associated with Jython is working on it. > - making a PVM (Python Virtual Machine) for the Palm? http://pippy.sourceforge.net/ From michaelparkin at gmail.com Fri Jul 22 05:47:09 2005 From: michaelparkin at gmail.com (michaelparkin at gmail.com) Date: 22 Jul 2005 02:47:09 -0700 Subject: httplib/HTTPS Post Problem References: <1121088563.465929.31290@g43g2000cwa.googlegroups.com> Message-ID: <1122025629.065962.60650@z14g2000cwz.googlegroups.com> Thanks for the replies, Andreas and Peter. Andreas Kostyrka wrote: > Just a curious guess: Are you behind a proxy? If so, it's a known and > never fixed bug from Python 1.5 times ;) No, I'm not behind a proxy - the server is on the same PC as my client (while I'm testing!). > You might also try to use PyCurl. I've quickly read about PyCurl, but it only seems to allow HTTP HEAD, GET, POST and PUT methods - though please correct me if I'm wrong. I'd like to use httpLib in Python as I also need the DELETE method and the possibility of adding some extra headers and extra methods (I'm working on something like this : http://sw.nokia.com/uriqa/URIQA.html that allows MGET, MPUT, MPOST, etc.). I've done some more testing and still can't work out why Python operates differently to other http clients... any ideas? Thanks, Michael. From nospam at noorg.com Tue Jul 5 17:46:12 2005 From: nospam at noorg.com (Kakushi) Date: Tue, 05 Jul 2005 21:46:12 GMT Subject: How to display Values of a file Message-ID: Hi my name is Andrew beginning/intermediate Python User. I am using a win xp computer Python 2.4 I would like to write a python application that would allow me to view paths of all installed files and registry values associated with that file for example I enter the file C:\WINDOWS\iexplorer.exe and it gives me reg value 1, reg value 2, folder 1, folder 2. This will eventually lead into running an application installer, for example C:\setup.exe and running through the processes of the install displaying a listing of all associated files with that install through my application Is this something that is possible with Python if so what modules should I look into If so has anyone done anything similiar if not I guess I will have to look into different ideas From peter at engcorp.com Thu Jul 14 01:59:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 01:59:12 -0400 Subject: Efficiently Split A List of Tuples In-Reply-To: References: Message-ID: Joseph Garvin wrote: > Peter Hansen wrote: > >> (I believe this is something Guido considers an "abuse of *args", but >> I just consider it an elegant use of zip() considering how the >> language defines *args. YMMV] >> >> -Peter >> >> > An abuse?! That's one of the most useful things to do with it. It's > transpose. Note that it's considered (as I understand) an abuse of "*args", not an abuse of "zip". I can see a difference... -Peter From renting at astron.nl Fri Jul 1 08:55:44 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 01 Jul 2005 14:55:44 +0200 Subject: LOC in Python and C++ in large projects Message-ID: I think the point you want to make is that Python needs vastly less lines of code as a similar application written in C++. I think Python might on average be 50-60% of comparable C++ code, but not the 1-2% you seem to want to claim. LOC is a somewhat arbitrairy measurement, but it gives an idea of what I'm talking about. Your single example compares a simple use in Python with a much more elaborate framework in one of the worst C++ IDE's I know. I can easily give you a counter example: If I create a simple form in Eric3 it will generate about 500-600 lines of Python too. When using this in actual code the difference between a piece of C++ and Python would however be mostly cosmetic: void MyForm::exitFile() { close(); } ------------ vs. ---------------- def exitFile(self): self.close() Your example is very good at demonstrating why Python is very useful for simple and small projects. Simple programs are simpler in Python. All programming languages can be used to write horrible unreadable and inefficient code. Therefore I think it's better to compare best cases as it is to compare worst cases. In the large projects I've worked on most of the code has nothing to do with external libraries or IDE generated code, but only with other parts of the project and most of the advantages Python has in small simple projects are uninportant. I think C++ gives a little more tools to keep large projects manageable, mostly because you can find a lot more communication failures between programmers at compile time. I think the choice of a programming language is not very important in determining the overal succes of a project. C++ and Python are however my two favorite languages. I think it would be interesting if any readers with more experience as I have would comment on how Python behaves in large projects, and how much less lines they need compared to C++ or Java. I have worked on several C++ projects with a few million lines of code, I would appreciate experience with comparable projects. (can you do it in 10.000 Lines of Python?) >>> Thomas Heller 07/01/05 11:36 AM >>> Thomas Heller writes: > "Adriaan Renting" writes: > >> I'm not a very experienced Python programmer yet, so I might be >> mistaken, but there are a few things that would make me prefer C++ over >> Python for large (over 500.000 LOC) projects. >> - namespaces >> - templates >> - strong type checking >> - data hiding >> - more available libraries and more advanced developement tools. >> >> I'm talking about managing the code, not the programmers, the project or >> schedules or what have you. Those are independent from the chosen >> programming language. > > Just a single datapoint: Implementing a trivial COM object in Python > requires, let's guess, about 10 or 20 lines of source code. > > When I do the same in MSVC6, the wizard creates 10 files, with nearly > 400 lines of code. Sure, I didn't have to write these code lines, but > I'm required to understand and manage them as well. Sorry, I forgot to include the .dsw and .dsp files in the above figure. Including them brings the LOC count up to 750 for the C++ project - although, to be fair, on the Python side a setup.py script for py2exe would also have to be written. In simple cases, this is another 10 lines. Thomas -- http://mail.python.org/mailman/listinfo/python-list From cyril.bazin at gmail.com Tue Jul 12 03:21:08 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Tue, 12 Jul 2005 09:21:08 +0200 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' In-Reply-To: References: Message-ID: If that can help you... def replaceLastComma(s): i = s.rindex(",") return ' and'.join([s[:i], s[i+1:]]) I don't know of ot's better to do a: ' and'.join([s[:i], s[i+1:]]) Or: ''.join([s[:i], ' and', s[i+1:]]) Or: s[:i] + ' and' + s[i+1] Maybe the better solution is not in the list... Cyril On 7/12/05, Ric Da Force wrote: > > Hi, > > I have a string such as 'C1, C2, C3'. Without assuming that each bit of > text is of fixed size, what is the easiest way to change this list so that > it reads: > 'C1, C2 and C3' regardless of the length of the string. > > Regards and sorry for the newbie question, > > Ric > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From twic at urchin.earth.li Mon Jul 4 10:35:56 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 4 Jul 2005 15:35:56 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: On Sun, 3 Jul 2005, Tim Peters wrote: > [Tom Anderson] >> So, is there a way of generating and testing for infinities and NaNs >> that's portable across platforms and versions of python? > > Not that I know of, and certainly no simple way. > >> If not, could we perhaps have some constants in the math module for them? > > See PEP 754 for this. Looks perfect. >>> Read the manual for the precedence rules. -x**y groups as -(x**y). >>> -1.0 is the correct answer. If you intended (-x)**y, then you need to >>> insert parentheses to force that order. > >> So i see. Any idea why that precedence order was chosen? It goes against >> conventional mathematical notation, as well as established practice in >> other languages. > > Eh? For example, Fortran and Macsyma also give exponentiation higher > precedence than unary minus. From my POV, Python's choice here was > thoroughly conventional. I guess you're right. What really threw me is that in all the other languages i know (which is not many, i admit), -1 is a literal -1, not a literal 1 plus a unary minus. >> Also, would it be a good idea for (-1.0) ** 0.5 to evaluate to 1.0j? It >> seems a shame to have complex numbers in the language and then miss this >> opportunity to use them! > > It's generally true in Python that complex numbers are output only if > complex numbers are input or you explicitly use a function from the > cmath module. [...] The presumption is that a complex result is more > likely the result of program error than intent for most applications. > The relative handful of programmers who expect complex results can get > them easily, though. A reasonable presumption. I always got really wound up that the calculator i had at school had this behaviour too, *even in complex number mode*! Come to think of it, i don't think it could do roots of imaginary numbers at all. However, python is not a calculator. tom -- A military-industrial illusion of democracy From opengeometry at yahoo.ca Wed Jul 27 18:41:36 2005 From: opengeometry at yahoo.ca (William Park) Date: Wed, 27 Jul 2005 18:41:36 -0400 Subject: Why Tcl/Tk? References: Message-ID: <97c93$42e80da0$d8fe9d88$9743@PRIMUS.CA> Jerry He wrote: > I'm a little curious, why does most scripting > languges(i.e. python and ruby) use Tcl/Tk rather than > wx or Fox as its standard GUI? Although I did notice > that the Vpython IDE that uses Tkinker starts up a lot > faster than the DrPython IDE that uses wxpython. But > that makes no sense, Tk is based on Tcl, a scripting > language, but wx is written in C++. Old habits die hard. Soon, these folks will die off, and we'll be left with GTK+ or wxWidgets. -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From finite.automaton at gmail.com Wed Jul 27 12:50:05 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 27 Jul 2005 09:50:05 -0700 Subject: Stripping C-style comments using a Python regexp References: <1122478928.879240.89110@g47g2000cwa.googlegroups.com> Message-ID: <1122483005.239122.275790@g14g2000cwa.googlegroups.com> > Is there some equivalent feature in Python regexps? cpp_pat = re.compile('(/\*.*?\*/)|(".*?")', re.S) def subfunc(match): if match.group(2): return match.group(2) else: return '' stripped_c_code = cpp_pat.sub(subfunc, c_code) ...I suppose this is what the Perl code might do, but I'm not sure, since trying to read it hurts my brain... From devlai at gmail.com Sat Jul 2 23:51:49 2005 From: devlai at gmail.com (Devan L) Date: 2 Jul 2005 20:51:49 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> Message-ID: <1120362708.992006.49040@g14g2000cwa.googlegroups.com> sum(sequence[0] + [1/element for element in sequence[1:]]) I think that should work. From jgrahn-nntq at algonet.se Sun Jul 10 08:56:13 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 10 Jul 2005 12:56:13 GMT Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: On Sun, 10 Jul 2005 22:10:50 +1000, Steven D'Aprano wrote: > On Sun, 10 Jul 2005 12:15:25 +0530, Dark Cowherd wrote: > >> http://www.joelonsoftware.com/items/2003/10/13.html > > Joel Spolsky might be a great C++ programmer, and his advice on user > interface design is invaluable, but Python is not C++ or Java, and his > arguments about exceptions do not hold in Python. Of course, his arguments do not even "hold" in C++ or Java, in the sense that everyone should be expected to accept them. Most C++ programmers would find his view on exceptions slightly ... exotic. He has a point though: exceptions suck. But so do error codes. Error handling is difficult and deadly boring. (Then there's the debate about using exceptions for handling things that aren't really errors, and what the term 'error' really means ...) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From wpog at hoobydooby.com Sun Jul 10 12:41:23 2005 From: wpog at hoobydooby.com (wpog) Date: Sun, 10 Jul 2005 16:41:23 GMT Subject: An absolute Newbie question Message-ID: Hello, I have a question about using "IDLE", and that is whenever I start write my own program in the "Python Shell" it will automatically execute whatever command I have written, for example: >>> print 'Hello World" So, how to I get it to not execute, so that I can write a program that has ordinary executable functions, and stuff like that? I do have some experience with Turbo Pascal, and so I'm hoping that this will be an even easier language to learn, and thus far it does seem so, but I need to get past this first;-). Thanks in advance, wpog From rrr at ronadam.com Sat Jul 9 21:19:42 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 10 Jul 2005 01:19:42 GMT Subject: Use cases for del In-Reply-To: <42d0529a$1@nntp0.pdx.net> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <1120825627.498017.19370@g47g2000cwa.googlegroups.com> <42d0529a$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Ron Adam wrote: > >> George Sakkis wrote: >> >>> I get: >>> >>> None: 0.549999952316 >>> String: 0.498000144958 >>> is None: 0.450000047684 >> >> >> >> What do yo get for "name is 'string'" expressions? > > > >>> 'abc' is 'abcd'[:3] > False Well of course it will be false... your testing two different strings! And the resulting slice creates a third. Try: ABC = 'abc' value = ABC if value is ABC: # Test if it is the same object pass In the previous discussion I was comparing using a string as an alternative to using None as a "flag" object. Not as a value to be calculated. And just to be clear, I'm not disagreeing with you. Yes, you can have problems with string comparisons if you create a copy instead of pointing a name to the object like you did above. Something to be aware of. To avoid that you either need to define the flag string as a global name or use it strictly in the local scope it's defined in. Python will also sometimes reuse strings as an optimization instead of creating a second string if they are equal. Something else to be aware of. So I'm not suggesting it is a good idea to use strings in place of None. But I still wonder why bool and other object comparisons are slightly slower than string comparisons. (?) Cheers, Ron > You need to test for equality (==), not identity (is) when > equal things may be distinct. This is true for floats, strings, > and most things which are not identity-based (None, basic classes). > This is also true for longs and most ints (an optimization that makes > "small" ints use a single identity can lead you to a mistaken belief > that equal integers are always identical. > > >>> (12345 + 45678) is (12345 + 45678) > False > > 'is' tests for identity match. "a is b" is roughly equivalent to > "id(a) == id(b)". In fact an optimization inside string comparisons > is the C equivalent of "return (id(a) == id(b) of len(a) == len(b) > and ) > > --Scott David Daniels > Scott.Daniels at Acm.Org From fowlertrainer at citromail.hu Mon Jul 4 07:40:30 2005 From: fowlertrainer at citromail.hu (fowlertrainer at citromail.hu) Date: Mon, 04 Jul 2005 13:40:30 +0200 Subject: Unicode drives me crazy... Message-ID: <42C9202E.60706@citromail.hu> Hi ! I want to get the WMI infos from Windows machines. I use Py from HU (iso-8859-2) charset. Then I wrote some utility for it, because I want to write it to an XML file. def ToHU(s,NoneStr='-'): if s==None: s=NoneStr if not (type(s) in [type(''),type(u'')]): s=str(s) if type(s)<>type(u''): s=unicode(s) s=s.replace(chr(0),' '); s=s.encode('iso-8859-2') return s This fn is working, but I have been got an error with this value: 'Kommunik\xe1ci\xf3s port (COM1)' This routine demonstrates the problem s='Kommunik\xe1ci\xf3s port (COM1)' print s print type(s) print type(u'aaa') s=unicode(s) # error ! This is makes me mad. How to I convert every objects to string, and convert (encode) them to iso-8859-2 (if needed) ? Please help me ! Thanx for help: ft From news at NOwillmcguganSPAM.com Wed Jul 6 06:04:52 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 06 Jul 2005 11:04:52 +0100 Subject: frozenset question Message-ID: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> Hi, Are there any benefits in using a frozenset over a set, other than it being immutable? Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From chase at youknowwho.com Tue Jul 12 04:15:39 2005 From: chase at youknowwho.com (Joseph Chase) Date: Tue, 12 Jul 2005 08:15:39 GMT Subject: Managment of Python Libraries Message-ID: I am new to Python. In the past, I have noticed that I have spent a lot of time managing my C++ libraries. When my personal frameworks got large enough, and some moving around/refactoring was apparent, it was an absolute nightmare. As I embark on the wonderful language of Python, or there any object organizational tools that may help me to keep order? Thanks everyone. From skink at evhr.net Wed Jul 20 10:22:10 2005 From: skink at evhr.net (Fabien) Date: Wed, 20 Jul 2005 16:22:10 +0200 Subject: python certification In-Reply-To: Message-ID: <20050720142210.56E6D7EC2B@postix.sdv.fr> > Python is not about certificates or diplomas, so do not spend any > money on it (the other guy was only joking). Even if Python is not about certificates, I think it's not the case for some company. And when you say to a company that you know how to dev. in Python, they don't know anything about your level. From michielsen at onecert.fr Fri Jul 8 10:41:07 2005 From: michielsen at onecert.fr (Bas Michielsen) Date: Fri, 08 Jul 2005 16:41:07 +0200 Subject: Obj.'s writing self-regeneration script ? References: <42CE7CA5.2090500@onecert.fr> Message-ID: <42CE9083.6070805@onecert.fr> Jerome Alet wrote: > Hi, > > Le Fri, 08 Jul 2005 15:16:21 +0200, Bas Michielsen a ?crit : > > >>Is there a good/standard way of having (composite) >>objects write a Python script which will regenerate >>the very same object ? > > > I've done something like this for the ReportLab toolkit. > > Last time I checked, this was still part of the project under > the name "pycanvas". You use a pycanvas.Canvas() instance > just like you would use a canvas.Canvas() instance, but you can decide to > regenerate an equivalent Python source program to your original program > when rendering. > > The docstring explains how to use it. Also > reportlab/test/test_pdfgen_pycanvas.py shows if it works or not. > > NB : this is not generic code, but maybe this can help you. > > bye > > Jerome Alet Thank you very much, I will have a look at it. Bas -- Bas Michielsen ONERA, Electromagnetics and Radar Department 2, avenue Edouard Belin, 31055 TOULOUSE cedex, France Tel. (++33)(0)5 62 25 26 77 Fax. (++33)(0)5 62 25 25 77 From paolo.veronelli at gmail.com Wed Jul 27 16:31:39 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Wed, 27 Jul 2005 22:31:39 +0200 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: <42E7EF2B.7040406@gmail.com> David Isaac wrote: > Newbie question: > > I have been generally open to the proposal that list comprehensions > should replace 'map', but I ran into a need for something like > map(None,x,y) > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > info from x. How do I do this as a list comprehension? (Or, > more generally, what is the best way to do this without 'map'?) Probably zip should change behaviour,and cover that case or at least have another like 'tzip' in the __builtins__ .Dunno, I always thought zip should not cut to the shortest list. > Thanks, > Alan Isaac > > From sjmachin at lexicon.net Wed Jul 20 07:54:40 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Jul 2005 21:54:40 +1000 Subject: is a file open ? In-Reply-To: References: Message-ID: <42de3b80$1@news.eftel.com> Daniel Dittmar wrote: > luis wrote: > >> for root, dirs, files in os.walk(path): >> for file in files: >> # ? is opened ? > > > On Linux and some other Unixes, you can probably read the /proc filesystem. > > On Windows, you'll probably get the quickest result by running > handle.exe (http://www.sysinternals.com/Utilities/Handle.html). > > Either way, the information you'll get is restricted by your permissions. > > Either information will get stale really fast, so it's not suitable if > your task is something like 'can I backup this directory or is someone > writing to a file?' If that's what the OP had in mind, the question might have been better phrased as "given the path to a file, how can I tell if it is currently opened by another process/thread", and better directed to OS-specifc newsgroup(s). From smartin at tacgeo.com Tue Jul 5 10:15:06 2005 From: smartin at tacgeo.com (Stephen Martin) Date: Tue, 05 Jul 2005 07:15:06 -0700 Subject: correct email In-Reply-To: References: Message-ID: Bah, sorry about the incorrect email and name! From rkern at ucsd.edu Sat Jul 9 18:00:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 09 Jul 2005 15:00:36 -0700 Subject: ImportError: No module named numarray In-Reply-To: <20050709205759.85835.qmail@web50307.mail.yahoo.com> References: <20050709205759.85835.qmail@web50307.mail.yahoo.com> Message-ID: enas khalil wrote: > dear all > could you tell me how can i fix this error appears when i try to import > modules from nltk > as follows > > from nltk.probability import ConditionalFreqDist > Traceback (most recent call last): > File "", line 1, in -toplevel- > from nltk.probability import ConditionalFreqDist > File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, in > -toplevel- > import types, math, numarray > ImportError: No module named numarray Install numarray. http://www.stsci.edu/resources/software_hardware/numarray -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From GoogleGroups at garringer.net Wed Jul 20 09:53:49 2005 From: GoogleGroups at garringer.net (RTG) Date: 20 Jul 2005 06:53:49 -0700 Subject: How do I send keystrokes to a console window in Windows XP? In-Reply-To: References: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> <1121713006.253298.302050@g49g2000cwa.googlegroups.com> <1121784455.136313.301610@g47g2000cwa.googlegroups.com> Message-ID: <1121867629.576316.317670@g14g2000cwa.googlegroups.com> Thank you, Peter. The application is a <<>> and we want to automatically interact with it (e.g. sendkeys and capture certain text responses). I will look for the thread you mentioned. - Roy From ironfroggy at gmail.com Fri Jul 29 13:01:07 2005 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 29 Jul 2005 13:01:07 -0400 Subject: Wheel-reinvention with Python (was: Ten Essential Development Practices) In-Reply-To: <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> Message-ID: <76fd5acf05072910014cfb6439@mail.gmail.com> The choice is GUI toolkits is largely seperate from Python. Consider that they are just bindings to libraries that are developed completely seperate of the language. GUI is should be seperate from the language, and thus not bound to same expectations and desires as elements of the language itself. Unless, of course, you're VB or Java.. On 7/29/05, Torsten Bronger wrote: > Hall?chen! > > Michael Hoffman writes: > > > Dark Cowherd wrote: > > > >> GUI, Web development, Application Framework - it is shambles. > > > > Yeah, I agree. When I finally make that GUI application I still > > don't know whether I am going to use wx or PyGTK. > > I agree, too, although I can only talk about GUI toolkits. At first > one thinks "well, perfect, I have the choice between four great GUI > systems". However, except for very special demands, there is no > clear winner. You start learning one, and immediately wonder > whether the other might be better. Although it sounds paradoxical, > this can be quite frustrating. After all, most of us don't have the > energy or motivation to test all candidates thoroughly. > > Besides, development resources are shared between all projects. > This is especially sad with regard to IDEs. There are even more > IDEs/dialog editors/widget builders than Toolkits, none of them > being mature. > > >> Is there some place to discuss topics like this? Is this the right place? > > > > Sure, although you might want to start a new thread. ;) > > At least a new subject ... > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > -- > http://mail.python.org/mailman/listinfo/python-list From google at spiceaid.com Fri Jul 22 16:36:28 2005 From: google at spiceaid.com (Dr. Who) Date: 22 Jul 2005 13:36:28 -0700 Subject: Something that Perl can do that Python can't? Message-ID: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> So here it is: handle unbuffered output from a child process. Here is the child process script (bufcallee.py): import time print 'START' time.sleep(10) print 'STOP' In Perl, I do: open(FILE, "python bufcallee.py |"); while ($line = ) { print "LINE: $line"; } in which case I get LINE: START followed by a 10 second pause and then LINE: STOP The equivalent in Python: import sys, os FILE = os.popen('python bufcallee.py') for line in FILE: print 'LINE:', line yields a 10 second pause followed by LINE: START LINE: STOP I have tried the subprocess module, the -u on both the original and called script, setting bufsize=0 explicitly but to no avail. I also get the same behavior on Windows and Linux. If anyone can disprove me or show me what I'm doing wrong, it would be appreciated. Jeff From jan.danielsson at gmail.com Fri Jul 22 12:35:03 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Fri, 22 Jul 2005 18:35:03 +0200 Subject: Data available on socket? Message-ID: <42e11ed0@griseus.its.uu.se> Hello all, How do I find out if a blocking socket has data available [for reading] on it? I assume I could do something like this: tmp = self.read(1, socket.MSG_PEEK) if len(tmp) > 0: # Data available But is there a better way? A call which specifically checks if data is available? From peter at engcorp.com Sat Jul 2 07:33:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 07:33:50 -0400 Subject: Accepted Summer of Code proposals In-Reply-To: <3in7ucFmcn6iU1@individual.net> References: <3in7ucFmcn6iU1@individual.net> Message-ID: <-uOdneiY58sP5lvfRVn-sA@powergate.ca> Reinhold Birkenfeld wrote: > A.M. Kuchling wrote: > >>For anyone who's interested: the Python wiki now contains a list of the >>PSF-mentored proposals that were accepted for Google's Summer of Code: >> http://wiki.python.org/moin/SummerOfCode > > > Is it right that two Wax proposals were accepted? "Right" can mean either "correct" or "proper". Which did you mean? If you meant the first, then the above link clearly shows that there were in fact two different Wax proposals (from different people) accepted. -Peter From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 12:06:02 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 18:06:02 +0200 Subject: Path PEP: What should Path(None) do? In-Reply-To: <5aKdnd5W9KOZm3jfRVn-iw@powergate.ca> References: <5aKdnd5W9KOZm3jfRVn-iw@powergate.ca> Message-ID: <3kkgvaFut490U2@individual.net> Peter Hansen wrote: > Michael Hoffman wrote: >> Currently it returns Path('None'). This means I have to do a check on >> input before pathifying it to make sure it is not None. >> >> Perhaps it should throw ValueError? > > Without checking, I suspect it is merely doing str(x) or unicode(x) on > whatever is passed to it: > > >>> path(None) > path(u'None') > >>> path(object()) > path(u'') > >>> path(3.14159) > path(u'3.14159') > > Therefore I think the question should be broadened beyond just None. > Should Path(x) simply call str(x) on the object or should it raise > ValueError or TypeError or something if it's not a basestring? > > Given that pretty much *everything* in Python can have str() called on > it, I think we should ask for a modicum of type-safety here and reject > non-strings as input. Settled. Reinhold From hongqn at gmail.com Sun Jul 3 03:22:41 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Sun, 3 Jul 2005 15:22:41 +0800 Subject: debugger? Message-ID: I have read a lot of posts discussing python IDEs, but most of them focus on the editor, GUI builder, project management, customizability, etc.... Some talked about debugging capability, but only on an available/unavailable level. I use vim to edit my code, wxGlade to build the GUI or hand-code it, and I still prefer that. So, until now, I haven't tried many IDEs. However, while I use pdb or inserting "print" statement to debug my apps, sometimes it is a pain. I think I need a good GUI debugger to help me. The debugger should meet _most_ of the following requirements: 1. can debug wxPython applications (and other GUI lib). 2. an intuitive way to set/clear/enable/disable breakpoints. 3. can set conditional breakpoints (i.e. break when some condition satisfied). 4. variable watch list, namescope watching (local, global) 5. evaluate expression, change variable values, etc within debugging. 6. change the running routine, (i.e. go directly to a statement, skip some statements, etc) 7. clever way to express objects, not just a string returned by repr() 8. perform profiling 9. a clear interface. 10. cross-platform. 11. free, or better, open source. What debugger will you suggest? Or what more polish feature you want to see in an ideal python debugger? -- hope this thread will help IDE developers to fill their todo list with some shining ideas :) -- Qiangning Hong Get Firefox! From kay.schluehr at gmx.net Tue Jul 19 02:54:42 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jul 2005 23:54:42 -0700 Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121663450.495821.102780@g49g2000cwa.googlegroups.com> Message-ID: <1121756082.315479.165790@g49g2000cwa.googlegroups.com> Diez B.Roggisch wrote: > > I have to admit that I don't understand what you mean with the > > 'constant parts' of an expression? > > >From what I percieved of your example it seemed to me that you wanted to > evaluate the constants like 7*9 first, so that an expression like > > a * 7 * 9 * b > > with variables a,b is evaluated like this: > > a * 63 * b > > So my suggestion was simply to make the *-operator more precedent when > in between two constants. What I mean with constants here are of course > integer/float literals. The concept of a differing operator precedence > can be extended to arbitray elements when their types are known - which > should be possible when variable values are known at parsing > time. O.K. > > > The associativity of __mul__ is trivially fullfilled for the dummy > > class M if an additional __eq__ method is defined by comparing factor > > lists because those lists are always flat: > > I don't care about that, as my approach deosn't use python's built-in parser > - it can't, as that wouldn't allow to re-define operator precedence. Diez, I try not to care too much about global operator precedence of builtin infix operators. The hard problems in designing a CAS beyond Mathematica are related to a bunch of interoperating algebras all defining their own operations. Finally only local precedences exist that are characteristic for certain patterns of expressions with a lot of tangled operators ( e.g. 'geometric algebra' with vector products, wedge products, inner products, additions and subtractions ). I don't want a system defining a syntactically extendable language with 10 custom punctuations per module that no one ( at least not me ) can remind and which looks as awkward as regular expressions. > What you do is to > simply collect the factors as list. But what you need (IMHO) is a parsing > tree (AST) that reflects your desired behaviour by introducing a different > precedence thus that the expression > > a * 7 *9 * b > > is not evaluated like > > ((a*7)*9)*b > > (which is a tree, and the standard way of evaluationg due to built-in parsers > precedence rules) but as > > a*(7*9)*b > > which is also a tree. Yes, but I tend to use __mul__ just for convenience. It is reflecting an associative and non-commutative operator whereas __add__ is a convenient way to fix an associative and commutative operator. In an idealized mathematical interpretation they represent nothing specific but as language elements they shall be fixed somehow. For more general operations one may define functional operators e.g. r_assoc and l_assoc where following (in)equations hold: l_assoc(a,b,c) == l_assoc(l_assoc(a,b),c) l_assoc(a,b,c) != l_assoc(a, l_assoc(b,c)) r_assoc(a,b,c) == r_assoc(a,r_assoc(b,c)) r_assoc(a,b,c) != r_assoc(r_assoc(a,b),c) This kind of pattern can be used to define rules about l_assoc and r_assoc. Nevertheless, there is no loss of generality. The system lacks prevention from deriving some class providing __mul__ and overwrite the implementation of __mul__ using l_assoc. People may do this on their own risk. Kay From rkern at ucsd.edu Tue Jul 26 20:08:46 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 26 Jul 2005 17:08:46 -0700 Subject: need some info on MySQL module. In-Reply-To: <1122422126.817344.207840@o13g2000cwo.googlegroups.com> References: <1122422126.817344.207840@o13g2000cwo.googlegroups.com> Message-ID: nephish at xit.net wrote: > Hey there, does anyone know where i can find some real documentation on > the MySQLdb module? This thing is driving me nuts. all i can find on > the internet is some brief tutorials. Is the documentation that comes with MySQLdb not sufficient? It's certainly more thorough than a tutorial: http://cvs.sourceforge.net/viewcvs.py/mysql-python/MySQLdb/doc/MySQLdb.txt?rev=1.1&view=auto Mostly, though, MySQLdb is conformant to the Python DB-API 2 specification: http://www.python.org/peps/pep-0249.html > I need to know whats up with some > of my stuff i even bought Programming Python by O'Reilly, out of over > 1200 pages, and it only has a page or two dedicated to it. Considering that MySQLdb is a third-party library, that's to be expected. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From giles_brown at hotmail.com Thu Jul 7 12:01:13 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 7 Jul 2005 09:01:13 -0700 Subject: Windows Cmd.exe Window In-Reply-To: References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: <1120752073.229474.245660@g43g2000cwa.googlegroups.com> Addendum - forgot to mention that the problem with checking the extension of sys.argv[0] is that sys.argv[0] is not set until after sitecustomize.py is run (and it needs to be in sitecustomize.py not an imported module due to the top-level SyntaxError problem mentioned in my other post). Cheers again for your elegant solution. Giles From rrr at ronadam.com Thu Jul 7 12:22:48 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 16:22:48 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <3j40aoFocvh4U1@individual.net> References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <3j40aoFocvh4U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Ron Adam wrote: > > >>Given the statement: >> >>a = None >> >>And the following are all true: >> >> a == None > > > Okay. > > >>(a) == (None) > > > Okay. > > >>(a) == () > > > Whoops! a (which is None) is equal to the empty tuple (which is not None)? It's not an empty tuple, it's an empty parenthesis. Using tuples it would be. (a,) == (,) which would be the same as: (,) == (,) >>(None) == () >> >>Then this "conceptual" comparison should also be true: >> >>if (None): == if (): >>if (): == if: > > > I can't really see any coherent concept here. > > Reinhold It would work out that. if: == if: Does that help? Cheers, Ron From apoco at cox.net Sat Jul 9 05:53:42 2005 From: apoco at cox.net (Jacob Page) Date: Sat, 09 Jul 2005 02:53:42 -0700 Subject: Python Module Exposure In-Reply-To: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > 1. As already noted, ISet is not really descriptive of what the class > does. How about RangeSet ? It's not that long and I find it pretty > descriptive. In this case, it would be a good idea to change Interval > to Range to make the association easier. The reason I decided not to use the term Range was because that could be confused with the range function, which produces a discrete set of integers. Interval isn't a term used in the standard/built-in library, AFAIK, so I may stick with it. Is this sound reasoning? > 2. The module's "helper functions" -- which are usually called factory > functions/methods because they are essentially alternative constructors > of ISets -- would perhaps better be defined as classmethods of ISet; > that's a common way to define instance factories in python. Except for > 'eq' and 'ne', the rest define an ISet of a single Interval, so they > would rather be classmethods of Interval. Also the function names could > take some improvement; at the very least they should not be 2-letter > abbreviations. Finally I would omit 'eq', an "interval" of a single > value; single values can be given in ISet's constructor anyway. Here's > a different layout: First, as far as having the factory functions create Interval instances (Range instances in your examples), I was hoping to avoid Intervals being publically "exposed." I think it's cleaner if the end-programmer only has to deal with one object interface. I like the idea of lengthening the factory function names, but I'm not sure that the factory methods would be better as class methods. Consider a use-case: >>> import iset >>> interval = iset.ISet.lowerThan(4) as opposed to: >>> import iset >>> interval = iset.lowerThan(4) This is less typing and probably eliminates some run-time overhead. Can you list any advantages of making the factory functions class methods? > class Range(object): # Interval > > @classmethod > def lowerThan(cls, value, closed=False): > # lt, for closed==False > # le, for closed==True > return cls(None, False, value, closed) > > @classmethod > def greaterThan(cls, value, closed=False): > # gt, for closed==False > # ge, for closed==True > return cls(value, closed, None, False) > > @classmethod > def between(cls, min, max, closed=False): > # exInterval, for closed==False > # incInterval, for closed==True > return cls(min, closed, max, closed) I like the function names, but in my dialect, lessThan would be more proper. > class RangeSet(object): # ISet > > @classmethod > def allExcept(cls, value): # ne > return cls(Range.lowerThan(value), Range.greaterThan(value)) > > 3. Having more than one names for the same thing is good to be avoided > in general. So keep either "none" or "empty" (preferably "empty" to > avoid confusion with None) and remove ISet.__add__ since it is synonym > to ISet.__or__. I agree that "none" should be removed. However, some programmers may prefer to use +, some |, so I'd like to provide both. > 4. Intervals shouldn't be comparable; the way __cmp__ works is > arbitrary and not obvious. I agree that __cmp__ is being used arbitrarily. I wanted sorting to be easy, but there's other ways of doing that. I'll take your suggestion. > 5. Interval.adjacentTo() could take an optional argument to control > whether an endpoint is allowed to be in both ranges or not (e.g. > whether (1,3], [3, 7] are adjacent or not). Interval objects weren't meant to be public; adjacentTo is used by ISet for combinatory functions. I could look into ways to hide the class from the public, but hiding things never seemed Pythonic to me; someone may want to use them for some reason. Maybe pydoc can be made to not document certain objects. > 6. Possible ideas in your TODO list: > - Implement the whole interface of sets for ISet's so that a client > can use either or them transparently. That was my intention. I'll have to see which interface functions I'm missing. > - Add an ISet.remove() for removing elements, Intervals, ISets as > complementary to ISet.append(). > - More generally, think about mutable vs immutable Intervals and > ISets. The sets module in the standard library will give you a good > idea of the relevant design and implementation issues. Both good ideas. > After I look into the module's internals, I'll try to make some changes > and send it back to you for feedback. Thanks for your feedback, George. I look forward to any additional comments you come up with. From George.Flaherty at marketmax.com Tue Jul 26 15:21:26 2005 From: George.Flaherty at marketmax.com (George Flaherty) Date: Tue, 26 Jul 2005 15:21:26 -0400 Subject: Emacs skeletons Message-ID: <59CF9F456FAA9045B405C441EC916F3E027A5BED@MERC24.na.sas.com> Yeah I have used tags with java and c before and they are very nice. Its just that, I have been trying to find something similar to JDE/PythonWinEditor code completion for an emacs-python mode. I will keep trying and thanks for the input. -george -----Original Message----- From: python-list-bounces+george.flaherty=sas.com at python.org [mailto:python-list-bounces+george.flaherty=sas.com at python.org] On Behalf Of Benji York Sent: Tuesday, July 26, 2005 3:15 PM To: python-list at python.org Subject: Re: Emacs skeletons Michael Hoffman wrote: > I have this in my .emacs: > > (global-set-key "\M-/" 'hippie-expand) > > This means that M-/ will do dumb code completion based on stuff that > is already in an open buffer Even though I don't know how to configure Emacs to do it (I'm a degenerate Vim user), I've found ctags completion very handy. I currently have my (inferior) editor set up to scan the current buffer, other buffers, then tags files when doing completion. I'm sure (the superior) Emacs can do something similar. -- self-editor-abasing-ly y'rs, Benji York -- http://mail.python.org/mailman/listinfo/python-list From iayork at panix.com Wed Jul 20 14:31:08 2005 From: iayork at panix.com (Ian A. York) Date: Wed, 20 Jul 2005 18:31:08 +0000 (UTC) Subject: EasyDialogs in MacOSX Tiger Message-ID: When I use EasyDialogs.Message in OSX (10.4.2), I have to manually switch to Python, the icon for which jumps in the dock until I click it. This is the case using pythonw with either 2.3 or 2.4. This question has come up before ("EasyDialogs module problem with python 2.4.1", April 18/05), and the answer that was give then was One application is "active" at any point in time, and this application controls the menu, has its windows displayed, and so on. So when the Terminal.app is active, Python cannot be. However, this is new behaviour. Wen I used EasyDialogs in earlier versions of OSX (10.3 and 10.2) this did not happen; the EasyDialogs dialog box popped up at once with no further interaction required. Unless MacOSX has changed its use of "active" applications, then, I think this explanation isn't correct. Does anyone have any thoughts on how to make EasyDialogs work the way it used to in OS 10.3? Ian -- Ian York (iayork at panix.com) "-but as he was a York, I am rather inclined to suppose him a very respectable Man." -Jane Austen, The History of England From dan at nospam.com Fri Jul 8 11:08:07 2005 From: dan at nospam.com (Dan) Date: Fri, 08 Jul 2005 10:08:07 -0500 Subject: import Help Needed - Newbie In-Reply-To: <1120776638.876867.4730@g14g2000cwa.googlegroups.com> References: <1120776638.876867.4730@g14g2000cwa.googlegroups.com> Message-ID: On 7/7/2005 5:50 PM, GregM wrote: > A search on google for odbchelper resulted in: > http://linux.duke.edu/~mstenner/free-docs/diveintopython-3.9-1/py/odbchelper.py > > I think this will help you. > Greg. > That is the previous example which worked for me fine. I have this code on a network drive so is this why I can't import it as a module? Dan From roccomoretti at hotpop.com Tue Jul 19 09:30:25 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 19 Jul 2005 08:30:25 -0500 Subject: goto In-Reply-To: References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: Leif K-Brooks wrote: > rbt wrote: > >>IMO, most of the people who deride goto do so because they heard or read >>where someone else did. > > > 1 GOTO 17 > 2 mean, GOTO 5 > 3 could GOTO 6 > 4 with GOTO 7 > 5 what GOTO 3 > 6 possibly GOTO 24 > 7 you! GOTO 21 > 8 that GOTO 18 > 9 really, GOTO 23 > 10 understandable? > 11 neat. GOTO 16 > 12 and GOTO 25 > 13 are GOTO 9 > 14 I GOTO 26 > 15 wrong GOTO 20 > 16 I GOTO 2 > 17 Yes, GOTO 14 > 18 simple GOTO 12 > 19 agree GOTO 4 > 20 with GOTO 22 > 21 Gotos GOTO 13 > 22 something GOTO 8 > 23 really GOTO 11 > 24 be GOTO 15 > 25 easily GOTO 10 > 26 totally GOTO 19 I dislike gotos because it is too easy to inadvertently create infinite loops. <10 WINK; 20 GOTO 10> From Scott.Daniels at Acm.Org Wed Jul 13 13:03:08 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 13 Jul 2005 10:03:08 -0700 Subject: Sort files by date In-Reply-To: References: <42d39273$0$12593$636a15ce@news.free.fr> Message-ID: <42d54153$1@nntp0.pdx.net> Jeremy Sanders wrote: > fargo wrote: > > >>I'm looking for some way to sort files by date. > > > you could do something like: > > l = [(os.stat(i).st_mtime, i) for i in glob.glob('*')] > l.sort() > files = [i[1] for i in l] > > Jeremy > If you have 2.4 or later: def mtime(filename): return os.stat(filename).st_mtime lst = sorted(glob.glob('*'), key=mtime) --Scott David Daniels Scott.Daniels at Acm.Org From theller at python.net Wed Jul 6 12:07:10 2005 From: theller at python.net (Thomas Heller) Date: Wed, 06 Jul 2005 18:07:10 +0200 Subject: Conditionally implementing __iter__ in new style classes References: Message-ID: Thomas Heller writes: > I'm trying to implement __iter__ on an abstract base class while I don't > know whether subclasses support that or not. > Hope that makes sense, if not, this code should be clearer: > > class Base: > def __getattr__(self, name): > if name == "__iter__" and hasattr(self, "Iterator"): > return self.Iterator > raise AttributeError, name > > class Concrete(Base): > def Iterator(self): > yield 1 > yield 2 > yield 3 > > The idea is that if a subclass of Base defines an 'Iterator' method, > instances are iterable. They are not iterable otherwise. > > The above gives the expected behaviour: iter(Base()) raises a > "TypeError: iteration over non-sequence", and iter(Concrete()) returns a > generator. > > If, however, I make Base a newstyle class, this will not work any > longer. __getattr__ is never called for "__iter__" (neither is > __getattribute__, btw). Probably this has to do with data descriptors > and non-data descriptors, but I'm too tired at the moment to think > further about this. > > Is there any way I could make the above code work with new style > classes? I forgot to mention this: The Base class also implements a __getitem__ method which should be used for iteration if the .Iterator method in the subclass is not available. So it seems impossible to raise an exception in the __iter__ method if .Iterator is not found - __iter__ MUST return an iterator if present. Thomas From solafidefarms at gmail.com Fri Jul 15 16:57:32 2005 From: solafidefarms at gmail.com (SolaFide) Date: 15 Jul 2005 13:57:32 -0700 Subject: What module to use to get a file from a website? Message-ID: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> I'm sure this is builtin, I just don't know what module. Thank you for any help! Billt From paolo_veronelli at tiscali.it Sat Jul 23 09:12:31 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sat, 23 Jul 2005 15:12:31 +0200 Subject: Getting a dictionary from an object In-Reply-To: <20050723101059.GA1756@zermelo.sians.org> References: <20050723084827.GA6903@zermelo.sians.org> <42E216C1.70707@tiscali.it> <20050723101059.GA1756@zermelo.sians.org> Message-ID: <42E2423F.2000406@tiscali.it> Thanos Tsouanas wrote: > On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote: > >>use getattr(self.obj,key) possibly, as __getattribute__ gets total >>control on attribute access > > > Thanks, but what do you mean by 'total control'? > Probably nothing to do with your question :( But: >>> class A(object): ... def __getattr__(self,attr): ... return 'whatever' ... >>> a=A() >>> a.b 'whatever' >>> getattr(a,'b') 'whatever' >>> a.__getattribute__('b') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'A' object has no attribute 'b' >>> This can probably touch you if your objects uses defualt searching for attributes. ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From gry at ll.mit.edu Wed Jul 20 09:20:16 2005 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 20 Jul 2005 06:20:16 -0700 Subject: socket programming In-Reply-To: References: <20050719184205.GA24773@mail.smule.com> Message-ID: <1121865616.375295.129420@z14g2000cwz.googlegroups.com> What I have done in similar circumstances is put in a random sleep between connections to fool the server's load manager. Something like: .import time .min_pause,max_pause = (5.0, 10.0) #seconds .while True: . time.sleep(random.uniform(min_pause, max_pause)) . do_connection_and_query_stuff() It works for me. Just play with the pause parameters until it fails and add a little. -- George From twic at urchin.earth.li Thu Jul 7 12:55:24 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 7 Jul 2005 17:55:24 +0100 Subject: flatten(), [was Re: map/filter/reduce/lambda opinions ...] In-Reply-To: References: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: On Thu, 7 Jul 2005, Ron Adam wrote: > Stian S?iland wrote: > > > Or what about a recursive generator? That's the sort of thing i like to see! > Ok, lets see... I found a few problems with the testing (and corrected > it) so the scores have changed. My sort in place routines were cheating > because the lists weren't reset between runs so it had the advantage > after the first time though of sorting already sorted list. Aaagh, of course! > And Tom's recursive no copy had a bug which kept a reference to one of > it's arguments so it's output was doubling the list. Oops. I really should have written tests as well as benchmarks. > And the hasattr function was slowing everyone down, so I inlined it for > everyone who used it. Using a 1000 item list and starting with a flat > list and increasing the depth (unflatten) to shallow, medium, and deep. > (but not so deep to cause recursion errors.) I wrote a new and improved test harness myself, but left my laptop at work, and haven't been in today due to the bombs :(. I ran tests out to 100 000 elements, and your implementation was still faster, although not by a lot - but then i hadn't found the bugs you had, so it's all moot. > And the winners are... > > Stians flatten generator is nearly tied with Tom's recursive zerocopy. > My nonrecursive inplace is faster for very shallow lists, but Tom's > quickly over takes it. I was able to improve my nonrecursive copy > flatten a bit, but not enough to matter. I also came up with an improvement to my version that should cut down on recursive calls - a sort of recursion unrolling. I doubt it wouldd make much difference, though. > So Tom's recursive zerocopy is the overall winner with Stian's flatten > generator close behind and just barely winning out in the very deep > catagory. \o/ > But they're all respectable times so everyone wins. ;-) Everyone shall have medals! tom -- They travel the world in their ice cream van ... From callmebill at gmail.com Thu Jul 14 16:15:04 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 14 Jul 2005 13:15:04 -0700 Subject: Native ODBC access for python on linux? In-Reply-To: References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> Message-ID: <1121372103.895623.319920@g14g2000cwa.googlegroups.com> Can you tell me what I have to use in order to utilize the MySQL native API? There's some gap (chasm, really) in my knowledge that is keeping me from following that route. If you could provide a small example or a couple names, that would be extremely helpful. Thanks again for your time. Larry Bates wrote: > ODBC is a vanilla interface that puts a layer between the program > and the database. In theory, this would allow you to write a > program that supports ODBC compliant databases and it would work > with any of them. In practice it always seems like this doesn't > work as well as everyone had hoped (performance is quite often a > problem with ODBC interface and time/date handling can be an > issue). > > There are people that provide ODBC drivers for Linux but normally > they are used to communcate back to MSSQL servers or other Windows > applications from Linux box. > > The native interfaces are almost always better performing and > support more features because ODBC is basically a lowest common > denominator approach. The native API can provide access to all > the (even unique) features of the particular database > > IMHO-For Python to MySQL on Linux use the native interface is > the way to go. > > Larry Bates > > callmebill at gmail.com wrote: > > I'm getting my feet wet with making Python talk to MySQL via ODBC. I > > started on Windows, and it went smoothly enough due to the ODBC stuff > > that apparently is native to Python at least on windows (I've been > > following ch. 13 of Mark Hammond's py on win32 book). > > > > But now I'm trying to do equivalent stuff on linux (Fedora Core 3) with > > python 2.3.5 and mysql. I'd like to stick with packages that are > > native to python, rather than relying on external stuff (e.g., MySQLdb > > and mxODBC). Is this possible, or do I have to use 3rd party pieces to > > use ODBC with Python under linux? > > > > > > As an aside, I've only used ODBC to access db's, period. I've never > > used, for example, MySQL's API for working with a MySQL db. I'm > > curious to see what that looks like, if anyone has any examples > > (python, c, or otherwise). > > > > Thanks in advance for any help. > > -Bill > > From williams13 at mail.llnl.gov Mon Jul 25 18:02:45 2005 From: williams13 at mail.llnl.gov (williams13 at mail.llnl.gov) Date: Mon, 25 Jul 2005 15:02:45 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050725201132.GA3440@tishler.net> Message-ID: Anytime Jason... Thanks for fixing this problem. Let me know when you have it solved. In the meantime, I have a workaround. Best regards, Dean On Mon, 25 Jul 2005 16:11:32 -0400 Jason Tishler wrote: >Dean, > >On Mon, Jul 25, 2005 at 10:49:58AM -0700, Dean N. >Williams wrote: >> For version control and other reasons, it would be nice >>to be able to >> build Python from source and it should build from >>source. How did the >> Cygwin version build? > >I built using an older version of Cygwin (i.e, 1.5.12-1). > >> I've attached the Python log file with the specific >>error. What file >> is missing? > >None. See below... > >The "root cause" is the following: > >under Cygwin 1.5.12-1: > > $ configure > [snip] > checking for inet_pton... no > [snip] > >under Cygwin 1.5.18-1: > > $ configure > [snip] > checking for inet_pton... yes > [snip] > >So, when you build under 1.5.18-1, pyconfig.h has the >following: > > #define HAVE_INET_PTON 1 > >This causes a chunk of code in socketmodule.c to be >compiled under >1.5.18-1 that wasn't compiled before. > >I will have to research why INET_ADDRSTRLEN is not >defined under Cygwin >and submit a patch to Cygwin or Python as appropriate. > >Thanks for bringing this problem to my attention. > >Jason > >-- >PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or >key servers >Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC >ECF4 8EF6 From brian at sweetapp.com Mon Jul 18 05:29:12 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 18 Jul 2005 11:29:12 +0200 Subject: Python Programming Contest In-Reply-To: <20050717210438.GA17650@gate2.hazen.net> References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> Message-ID: <42DB7668.1020409@sweetapp.com> John Hazen wrote: > I have one question about the problem. Is the cost we are to minimize > the cost of arriving in the target city at all, or the cost of arriving > at the target city at the end of the final day of the schedule? Minimize the arrival cost. The arrival day is not relevant. > (If you were traveling to a conference, for example, you'd have a > specific arrival time, and a cost to stay in the destination city until > that time. But, if you were going to sight-see, then you could arrive > at any time, and begin your itinerary upon arrival.) Call it a vacation then :-) > Say I can find a combination of flights that gets me to the target at > the end of day 3 for 390 units, and a combination that gets me there at > the end of day 4 for 400. If you count the hostel cost from day 3 to > day 4, the first combination costs 410. So, which is preferred? The first option (day 3 for 390 units). > P.S. I just realized this may be answered be the test suite, but I'm > still at the thinking stage. No problem. Let me know if you have any other questions. Cheers, Brian From p at ulmcnett.com Fri Jul 22 11:36:40 2005 From: p at ulmcnett.com (Paul McNett) Date: Fri, 22 Jul 2005 08:36:40 -0700 Subject: Separation of Code in CGI App In-Reply-To: <1122045475.402933.246760@z14g2000cwz.googlegroups.com> References: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> <1122045475.402933.246760@z14g2000cwz.googlegroups.com> Message-ID: <42E11288.1050003@ulmcnett.com> Rob Cowie wrote: > So, do I separate out whatever code I want to into .py modules, then > have the cgi script import them, and utilise them as required? Bingo! > If so, do I need to put these modules somewhere described in the System > Path? Put them in the same directory, and you don't have to worry any more about it. You can get more advanced if you want by putting your modules into a "package", which is just a directory with a __init__.py file - see the docs at python.org. > Can I modify the PATH at runtime to point to my modules? How? If you want to have them in a different directory, and the directory isn't already in sys.path, then just issue, from your main script, before your import statements: import sys sys.path.insert(0, "/path/to/your/modules") > Cheers for being patient! Welcome to Python! Being new to it, you may want to consider having someone review your code before putting it on the public internet, simply because there are lots of opportunities for inadvertantly providing backdoors (Python is powerful). This is especially true if you let your users type into a text box, or if you do dynamic database queries, or both. Also, have you run through the tutorial on python.org? -- Paul McNett http://paulmcnett.com From finite.automaton at gmail.com Fri Jul 29 15:38:28 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 29 Jul 2005 12:38:28 -0700 Subject: Filtering terminal commands on linux References: Message-ID: <1122665908.916071.246550@g44g2000cwa.googlegroups.com> Firstly, there's probably a better way to do whatever you're trying to do w.r.t cd/dvd burning. I'm not familiar with gear, but its webpage lists "Batch file scripting capability" as a feature, which suggests that you might be able to do what you want without parsing output intended for humans. There are also a multitude of command-line cd and dvd utilities for Linux which might be better for scripting. That said, it shouldn't be too hard to craft a regular expression that matches ANSI control sequences. Using http://www.dee.ufcg.edu.br/~rrbrandt/tools/ansi.html as a reference, here's how to do this for the first few control sequences... esc = '\x1B' start_control_sequence = esc + '[' Pn = r'\d+' # Numeric parameter Ps = '%s(;%s)*' % (Pn,Pn) # Selective parameter PL = Pn Pc = Pn control_sequences = [ PL + ';' + Pc + '[Hf]', # Cursor position Pn + '[ABCD]', # Cursor up|down|forward|backward 's', # Save cursor position 'u', # Restore cursor position '2J', # Erase display 'K', # Erase line Ps + 'm', # Set graphics mode '=' + Pn + '[hl]', # Set|Reset mode # ... etc ] match_ansi = re.compile(start_control_sequence + '(' + '|'.join(control_sequences) + ')') def strip_ansi(text): return match_ansi.sub('',text) (note: code is untested.. may contain typos) From sjmaster at gmail.com Wed Jul 13 16:47:12 2005 From: sjmaster at gmail.com (Steve M) Date: 13 Jul 2005 13:47:12 -0700 Subject: Help with mass remove in text file In-Reply-To: <1121270454.812750.235980@o13g2000cwo.googlegroups.com> References: <1121270454.812750.235980@o13g2000cwo.googlegroups.com> Message-ID: <1121287632.893452.250940@z14g2000cwz.googlegroups.com> First, in your intro you say you want to remove all strings of the form "f=n;" where n can be 0-14. So you want to remove "f=0;" and "f=1;" and ... Later, you appear to be trying to remove "f=;" which may be what you want but it doesn't match your described intentions. Second, the formatting (whitespace) is all messed up on your post (at least in googroups), so its not entirely clear what the program is supposed to do. Anyway, why do you say the program doesn't work? Does it generate an error when you try to run it? Or is it doing what you say and not what you mean? I'm guessing that it will give (provided it doesn't end on a SyntaxError) at least the following error: TypeError: replace() takes at least 2 arguments (1 given) This is because the line: data = data.replace(x) doesn't use enough arguments for the replace() method. You need to say what to replace it with. Since you want to remove whatever string it is, you can use the empty string as the replacement value: data = data.replace(x, '') #That's two single quotes Also, unless you want to make a regular expression, you might have to do a replace() call on data 15 times, sort of like this: for i in range(15): text_to_remove = "f=%s;" % i data = data.replace(text_to_remove, '') From tiang_ono at yahoo.com Tue Jul 12 21:18:57 2005 From: tiang_ono at yahoo.com (Titi Anggono) Date: Tue, 12 Jul 2005 18:18:57 -0700 (PDT) Subject: plot module In-Reply-To: <126622653da8.42d3ef2f@Princeton.EDU> Message-ID: <20050713011858.26862.qmail@web30710.mail.mud.yahoo.com> I just use Gnuplot for plot module. Maybe you can visit http://gnuplot-py.sourceforge.net/ or the mailing list http://lists.sourceforge.net/lists/listinfo/gnuplot-py-users --- "Shankar Iyer (siyer at Princeton.EDU)" wrote: > Hi, > > I am looking for documentation on the plot module. > Does anyone know where I can find this information? > Thanks. > > Shankar > > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From b83503104 at yahoo.com Tue Jul 12 10:38:39 2005 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 12 Jul 2005 07:38:39 -0700 Subject: append one file to another In-Reply-To: References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Message-ID: <1121179119.788276.92280@f14g2000cwb.googlegroups.com> Thanks for the nice suggestions! As a side question, you mentioned opening files in binary mode, in case the code needs to run under Windows or cross-platform. What would happen otherwise? Is it an issue of big little endian or some other issue? From http Sun Jul 10 19:07:40 2005 From: http (Paul Rubin) Date: 10 Jul 2005 16:07:40 -0700 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: <7x64vip8eb.fsf@ruckus.brouhaha.com> Dan Sommers writes: > def __init__(self, self.x, y, self.z): > # self.x, self.z from first and third explicit parameters > do_something_with_y() Hey, I like that. From bwidmann at utanet.at Mon Jul 18 10:21:14 2005 From: bwidmann at utanet.at (Bruno Widmann) Date: 18 Jul 2005 14:21:14 GMT Subject: Ann: Tkinter drag and drop module References: <1121336778.344208.224820@f14g2000cwb.googlegroups.com> <1121353846.723518.165110@g49g2000cwa.googlegroups.com> Message-ID: On 2005-07-14, tchurm at gmail.com wrote: > i remember freezing a python console app i wrote some time ago using > the mcmillan installer (kinda like py2exe) and was surprised to > discover that binaries dragged and dropped onto the .exe file were > handled properly as args...making a kind of no-gui drag and drop... Do you mean you draged a file onto the .exe using the windows explorer? In this case the script just has to read in the first commandline argument, as the Win-Explorer does the d&d work and passes the filename of the droped file on to the script. You can test that easily by creating a small .bat file: echo %1 pause From nothingcanfulfill at gmail.com Tue Jul 19 02:40:51 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 18 Jul 2005 23:40:51 -0700 Subject: retrieving https pages In-Reply-To: References: Message-ID: <1121755251.385013.322270@g14g2000cwa.googlegroups.com> It might be checking the browser's User-agent. My best bet for you would to be to use something to record the headers your browser sends out, and mimic those in Python. If you look at the source code for urlopener (I think you can press Alt+M and type in "urlopener"), under the FancyURLopener definition, you should see something like self.add_headers (not on a box to check it right now, but it's in the constructer, I remember that much). Just set all the headers to send out (like your browser would) by setting that value from your script. i.e.: import urlopener urlopener = FancyURLopener() urlopener.add_headers = [('User-agent','blah'),('Header2','val'),('monkey','bone')] # do the other stuff here :P HTH -Wes From harold.fellermann at upf.edu Tue Jul 12 10:13:44 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 12 Jul 2005 16:13:44 +0200 Subject: Missing Something Simple In-Reply-To: <42D3C920.2000808@plus.net> References: <42D3C920.2000808@plus.net> Message-ID: <11f99613a4f2a4c64f8055e060b8e965@upf.edu> Hi, > I have a list of variables, which I am iterating over. I need to set > the value of each variable. My code looks like: > > varList = [ varOne, varTwo, varThree, varFour ] > > for indivVar in varList: > indivVar = returnVarFromFunction() > > However, none of the variables in the list are being set. You only change the value of the local variable in the body of the for loop. it has no effect on the list. you could do e.g. varList = [vorOne,varTwo,varThree,varFour] for i in len(varList) : varList[i] = returnVarFromFunction() However, as in this example the former list values are not used anyway, you could just write: varList = [ returnVarFromFunction for i varList ] cheers, - harold - -- Tages Arbeit, abends G?ste, saure Wochen, frohe Feste! -- Johann Wolfgang v. Goethe From sjmachin at lexicon.net Fri Jul 22 18:34:57 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 08:34:57 +1000 Subject: How to modify a file 'in place' ? In-Reply-To: <42e1194d$0$7428$626a14ce@news.free.fr> References: <42e1194d$0$7428$626a14ce@news.free.fr> Message-ID: <42e17491@news.eftel.com> Elby wrote: > I'm looking for a the most simple and generic way to modify a file, with the > possibility of making backups. In fact, I would like to emulate Perl's -i > option. > > here is a bit of code, to explain it further : > > < code > > > from os import rename > > class Modif_File: > def __init__(self, filename, ext='.bak'): > old_name = filename + ext > new_name = filename > rename(new_name,old_name) Quite apart from unusual ideas about what "old" and "new" mean, you have a problem if filename == "foo" and a physical file named "foo.bak" exists already. > > self.old = open(old_name,'r') > self.new = open(new_name,'w') > > # methods for getting data are linked to the old file : > for attr in ('encoding', 'newlines', 'next', 'read', > 'readinto', 'readline', 'readlines', 'seek', > 'tell', 'xreadlines'): > setattr(self,attr,getattr(self.old,attr)) > > # methods for putting data are linked to the new one : > for attr in ('closed','flush','write', 'writelines'): > setattr(self,attr,getattr(self.new,attr)) > You seem to be majorly confused between a physical file on disk and a file object used for accessing physical files. There is absolutely neither need nor usefulness in doing all that getattr/setattr stuff. Have a look at the documentation for the shutil module. The functions in that should do most/all of what you want. Then have a look at the *source* for that module -- which will be present on your machine; on mine it's C:\Python24\Lib\shutil.py -- and see how elementary physical file manipulations are done, with no getattr or setattr calls. HTH, John From rkern at ucsd.edu Thu Jul 21 22:38:06 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 21 Jul 2005 19:38:06 -0700 Subject: Difference between " and ' In-Reply-To: <42E05106.5060905@REMOVEMEcyber.com.au> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Michael Hoffman wrote: > >>John Machin wrote: >> >>>b83503104 at yahoo.com wrote: >>> >>>>Can someone tell me the difference between single quote and double >>>>quote? >>> >>> >>> ord("'") - ord('"') >>>5 >> >>Very zen. > > But unfortunately incorrect, since the original poster > didn't ask for the difference between the ordinal > values of the single quote and double quote characters, > but for the difference between the characters themselves. It was a joke, I believe, not a serious answer. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From michael at stroeder.com Thu Jul 28 09:24:56 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 28 Jul 2005 15:24:56 +0200 Subject: ANN: python-ldap-2.0.9 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.9 2005-07-28 Changes since 2.0.8: Modules/ * Removed __doc__ strings from ldapcontrol.c to "fix" build problems with Python versions 2.2 and earlier. From bokr at oz.net Sun Jul 24 01:03:56 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 05:03:56 GMT Subject: Filtering out non-readable characters References: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> <1121570966.6b3e122aacf94730620c39031b3c126b@teranews> Message-ID: <42e32132.996913766@news.oz.net> On Sat, 16 Jul 2005 23:28:02 -0400, "George Sakkis" wrote: >"Peter Hansen" wrote: > >> George Sakkis wrote: >> > "Peter Hansen" wrote: >> >>>> Where did you learn that, George? >> > >> > Actually I first read about this in the Cookbook; there are two or three >> > recipes related to string.translate. As for string.maketrans, it >> > doesn't do anything special for empty string arguments: ... >> >> I guess so. I was going to offer to suggest a new paragraph on that >> usage for the docs, but as you and Jp both seem to think the behaviour >> is obvious, I conclude "it's just me" so I suppose I shouldn't bother. > >It's only obvious in the sense that _after_ you see this idiom, you can go back to the docs and >realize it's not doing something special; OTOH if you haven't seen it, it's not at all the obvious >solution to "how do I get the first 256 characters". So IMO it should be mentioned, given that >string.translate often operates on the identity table. I think a single sentence is adequate for the >reference docs. > I would suggest changing """ maketrans(from, to) Return a translation table suitable for passing to translate() or regex.compile(), that will map each character in from into the character at the same position in to; from and to must have the same length. """ to something that would make the idiom more easily inferrable, e.g., """ maketrans(from, to) Return a translation table suitable for passing to translate() or regex.compile(), that will map each character in from into the character at the same position in to, while leaving all characters other than those in from unchanged; from and to must have the same length. """ Meanwhile, if my python feature request #1193128 on sourceforge gets implemented, we'll be able to write s.translate(None, badchars) instead of having to build an identity table to pass as the first argument. Maybe 2.5? (Not being pushy ;-) Regards, Bengt Richter From apoco at cox.net Sat Jul 9 21:22:42 2005 From: apoco at cox.net (Jacob Page) Date: Sat, 09 Jul 2005 18:22:42 -0700 Subject: ANN: interval module 0.2.0 (alpha) Message-ID: After some feedback from this newsgroup, I've updated and renamed the iset module to the interval module. Many of the names within the module have also changed, and I've refactored a lot of the code. The updated version can be found at http://members.cox.net/apoco/interval/, as well as a change log. Again, any suggestions would be greatly appreciated. I especially want to sort out big design-level changes first. Then I can upgrade the project status to beta and try to keep interface compatibility intact. -- Jacob From surrender_it at remove-yahoo.it Thu Jul 7 06:01:08 2005 From: surrender_it at remove-yahoo.it (gabriele renzi) Date: Thu, 07 Jul 2005 10:01:08 GMT Subject: ANN: python-constraint 1.0 In-Reply-To: References: Message-ID: Gustavo Niemeyer ha scritto: > -------- > Overview > -------- > > **python-constraint** [1]_ is a Python module offering solvers for > Constraint Solving Problems (CSPs) over finite domains in simple > and pure Python. CSP is class of problems which may be represented > in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...), > and constraints (`a < b`, ...). This sound cool, but have you noticed logilab.constraint? Care to contrast? From rbt at athop1.ath.vt.edu Mon Jul 18 22:55:05 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 18 Jul 2005 22:55:05 -0400 Subject: goto In-Reply-To: References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: <1121741705.7390.0.camel@suluntah> 10 PRINT "YOU'RE NOT RIGHT IN THE HEAD." 20 GOTO 10 On Tue, 2005-07-19 at 02:33 +0000, Leif K-Brooks wrote: > rbt wrote: > > IMO, most of the people who deride goto do so because they heard or read > > where someone else did. > > 1 GOTO 17 > 2 mean, GOTO 5 > 3 could GOTO 6 > 4 with GOTO 7 > 5 what GOTO 3 > 6 possibly GOTO 24 > 7 you! GOTO 21 > 8 that GOTO 18 > 9 really, GOTO 23 > 10 understandable? > 11 neat. GOTO 16 > 12 and GOTO 25 > 13 are GOTO 9 > 14 I GOTO 26 > 15 wrong GOTO 20 > 16 I GOTO 2 > 17 Yes, GOTO 14 > 18 simple GOTO 12 > 19 agree GOTO 4 > 20 with GOTO 22 > 21 Gotos GOTO 13 > 22 something GOTO 8 > 23 really GOTO 11 > 24 be GOTO 15 > 25 easily GOTO 10 > 26 totally GOTO 19 From blodge at citi-us.com Fri Jul 15 23:19:54 2005 From: blodge at citi-us.com (William Lodge) Date: Fri, 15 Jul 2005 23:19:54 -0400 Subject: Python vs. Access VBA Message-ID: I'm at a loss on how to compare Python vs. Access VBA for a database project. I'm estimating 20 tables and several forms and reports. Some of the tables could grow to many thousands of rows w/i a year or so. The app would be resident on my client as no network connectivity is needed b/c I'll be the only user. I'd probably use Access tables for now and plan on scaling up to Oracle later if necessary (which it probably won't be). If the project is successful, it may be adopted in the division. There is no time limit but this is being done on my own time, and my guestimate for a practical limit would be 3-4 months. I'm not a developer but have done programming in the academic world as part of MSIS degree. I also want the app to have a GUI. I'm currently reviewing Wingware's Python product. Will review Komodo next. It doesn't appear that the Wingware product has a GUI builder, but Komodo's Pro version does (although more costly). Anybody have any recommendations in this regard? Any thoughts as to whether implementing in Python would be any harder or easier to do than in Access? Finally, does anybody know of any Web sites having examples of database apps in Python? Thanks for your help. Bill -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 2556 bytes Desc: not available URL: From fuzzyman at gmail.com Mon Jul 11 10:50:24 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Jul 2005 07:50:24 -0700 Subject: Python exception hook simple example needed In-Reply-To: References: <1120654753.122331.109950@g43g2000cwa.googlegroups.com> <1120735672.230582.244060@g43g2000cwa.googlegroups.com> Message-ID: <1121093424.003441.313210@o13g2000cwo.googlegroups.com> Ed Leafe wrote: > On Jul 7, 2005, at 7:27 AM, Fuzzyman wrote: > > > Do you have an exception handling dialog ? > > Not per se, as there hasn't been a request for one; we have several > dialogs ranging from simple messages to alerts to interactive dialogs, > much as wxPython offers. But I'll make this offer: give me a spec as to > what you need this "exception handling dialog" to do, and I'll have it > added to the framework within 24 hours. Deal? > Hello Ed, It's a brilliant offer - and dabo sounds very interesting. I was responding to someone else's question though ! Next time I need to code a GUI app I'll take a look at dabo. Thanks Fuzzy http://www.voidspace.org.uk/python > > Can you use the UI layer without being tied to the rest of the > > framework ? They seemed pretty integrated to me. > > They are integrated, but nothing forces you to use anything you don't > want. I know of several people who have developed UI-only apps, with no > need for business objects or database connectivity. They started in > plain wxPython, and switched to Dabo because it was so much easier, and > so much more Pythonic. > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ From steve at REMOVETHIScyber.com.au Sat Jul 23 23:43:43 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 13:43:43 +1000 Subject: Getting a dictionary from an object References: Message-ID: On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote: > On Sat, Jul 23, 2005 at 11:22:21PM +1000, Steven D'Aprano wrote: >> On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote: >> > Hello. >> > >> > I would like to have a quick way to create dicts from object, so that a >> > call to foo['bar'] would return obj.bar. >> >> That looks rather confusing to me. Why not just call obj.bar, since it >> doesn't look like you are actually using the dictionary at all? >> >> > [...] >> >> I don't think this is particularly useful behaviour. How do you use it? > > print foo %do > > where do is a dictobj object... Are you telling me that the ONLY thing you use dictobj objects for is to print them? I don't think so. I do know how to print an object, amazingly. Perhaps you would like to explain how you use the rest of the functionality of the dictobj, instead of taking my words out of context and giving an inane answer. Why jump through all those hoops to get attributes when Python already provides indexing and attribute grabbing machinery that work well? Why do you bother to subclass dict, only to mangle the dict __getitem__ method so that you can no longer retrieve items from the dict? -- Steven. From thanos at sians.org Sun Jul 24 17:56:07 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Mon, 25 Jul 2005 00:56:07 +0300 Subject: Getting the --options of configure on installed python Message-ID: <20050724215607.GA9086@zermelo.sians.org> Hello! Is there a way to get the --options with which python was configured on a system? Thanks in advance. -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From gsakkis at rutgers.edu Sat Jul 16 18:55:42 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 16 Jul 2005 18:55:42 -0400 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: <1121554550.a71667b7fa93beed82764d3bd61318e3@teranews> "Bengt Richter" wrote: > >>> identity = ''.join([chr(i) for i in xrange(256)]) > >>> unprintable = ''.join([c for c in identity if c not in string.printable]) Or equivalently: >>> identity = string.maketrans('','') >>> unprintable = identity.translate(identity, string.printable) George From steven.bethard at gmail.com Fri Jul 1 01:08:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 30 Jun 2005 23:08:49 -0600 Subject: Speaking of list-comprehension? In-Reply-To: References: Message-ID: Chinook wrote: > >>> ta = [5, 15, 12, 10, 9] > >>> for i in range(len(ta)): > ... if ta[i] >= 10: > ... ta[i] -= 10 > ... else: > ... ta[i] += 10 > ... > >>> ta > [15, 5, 2, 0, 19] One possibility: py> [(tai + 10, tai - 10)[tai >= 10] for tai in ta] [15, 5, 2, 0, 19] But see: http://www.python.org/peps/pep-0308.html STeVe From hualiangqi at yahoo.com-dot-cn.no-spam.invalid Tue Jul 19 02:53:08 2005 From: hualiangqi at yahoo.com-dot-cn.no-spam.invalid (Hua) Date: Tue, 19 Jul 2005 06:53:08 +0000 (UTC) Subject: =?ISO-8859-15?Q?re:c++=C8=E7=BA=CE=CF=F2python=B5=C4=BD=C5=B1=BE=B4=AB=B5=DD=D2=BB=B8=F6=C0=E0=D7=F7=CE=AA=B2=CE=CA=FD=A1=A3?= References: Message-ID: Hi, you should write in English, otherwise there is nobody understand your question. ` From lbates at syscononline.com Wed Jul 6 09:27:55 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 06 Jul 2005 08:27:55 -0500 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <42CBDC5B.9020208@syscononline.com> You don't say how long it took to develop the "macros" but you should see what kind of website an experienced Zope/Plone programmer can whip up in a few minutes. Acceleration in programming has always been about the "Standard Library" (not only Python's standard library but also your standard library). I'm talking about stable, debugged, documented macros, functions and classes that the programmer can use to quickly do very complex tasks. I discovered this well over 30 years ago and taught many young programmers and University students this very important "trick". As you write software you will eventually come across common routines that are used in almost every software package (logging, reading from CSV files, date/time manipulation, ...). If you have lots of these to choose from in your library, you will produce code 10-100 times faster than those that start over every time AND the code will be MANY times more reliable because you are utilizing stable code that has been debugged over a long period of time. You will also be producing code that is more "maintainable". Discovered a bug in a library routine? Fix it and then it is fixed in 100's (or 1000's) of existing programs that use it. -Larry Bates seberino at spawar.navy.mil wrote: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. > > It got me curious if Lisp > is inherently faster to develop complex apps in. It would seem if you > could create your own language in Lisp using macros that that would be > quite an advantage.... > > I realize that Python has operator overloading and OOP so I'm not sure. > > Any ideas? Any *evidence* one way or another? > > thanks! > > Chris > From jaydonnell at gmail.com Fri Jul 8 13:14:14 2005 From: jaydonnell at gmail.com (jdonnell) Date: 8 Jul 2005 10:14:14 -0700 Subject: can't start new thread Message-ID: <1120842854.694743.216930@o13g2000cwo.googlegroups.com> I'm at a loss on this one. I have a multithreaded script that gets 'thread.error: can't start new thread' errors seemingly randomly. I just got it right after starting the script when it was trying to create the 5th thread. Usually the script will run for a while before throwing this error, but sometimes it throws it right away. This script has worked without a problem for months, but I did make some changes to it recently. I don't see how those changes would cause this error though. It's also on a VPS so it's possible that they changed something in the OS. Does anyone have any suggestions about possible causes of this error? I'm using Python 2.2.3 on a custom vps version of FC1. From zen19725 at zen.co.uk Sat Jul 30 09:09:16 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sat, 30 Jul 2005 14:09:16 +0100 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: On Sat, 30 Jul 2005 08:54:59 +0200, Torsten Bronger wrote: >Hall?chen! > >Calvin Spealman writes: > >> The choice is GUI toolkits is largely seperate from >> Python. Consider that they are just bindings to libraries that are >> developed completely seperate of the language. GUI is should be >> seperate from the language, and thus not bound to same >> expectations and desires as elements of the language itself. > >I disagree. A modern language must provide a convenient and >well-embedded way to write GUI applications. This is not a sign of >decadence, but a very good promotional argument. Delphi and first >and foremost VB are extremely popular, and it's sad to see that >Python could get a lot more of the cake if the efforts for IDEs and >toolkits were somewhat streamlined. Besides, all other already good >aspects of Python wouldn't suffer at all. > >Tkinter fits into Python very well and it is very easily (if not >trivially) accessible for users of our applications. People >complain about non-native look-and-feel on Windows, but sorry, I >simply find it unacceptably ugly on all platforms. Don't >misunderstand me: I don't like neat GUI effects just for the sake of >it but Tkinter makes an outdated impression on the end-user. > >I've been having a closer look at wxPython which is not Pythonic at >all and bad documented. Tkinter is hardly brilliantly documented, IMO. > Probably I'll use it nevertheless. PyGTK >and PyQt may have their own advantages and disadvantages. > >However, in my opinion we don't need yet another binding so thin >that C or C++ is shining through, but a modern replacement for >Tkinter with its Pythonic way of thinking. How about sometihing with the same API as Tkinter (so no need to relearn), but which looks prettier? Would that fix your gripes? -- Email: zen19725 at zen dot co dot uk From kay.schluehr at gmx.net Sat Jul 9 00:25:25 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Jul 2005 21:25:25 -0700 Subject: removing list comprehensions in Python 3.0 In-Reply-To: References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> Message-ID: <1120883125.259644.80490@g47g2000cwa.googlegroups.com> Leif K-Brooks schrieb: > Kay Schluehr wrote: > > Well, I want to offer a more radical proposal: why not free squared > > braces from the burden of representing lists at all? It should be > > sufficient to write > > > >>>>list() > > > > list() > > So then what would the expression list('foo') mean? Would it be > equivalent to ['foo'] (if so, how would you convert a string or other > iterable to a list under Py3k?), or would it be equivalent to ['f', 'o', > 'o'] as it is in now (and is so, what gives?)? Spiltting a string and putting the characters into a list could be done in method application style: >>> "abc".tolist() list('a','b','c') Or equivalent from lists point of view: >>> list.from_str("abc") list("a", "b", "c" ) Kay From dont at spam.me Sat Jul 30 19:52:43 2005 From: dont at spam.me (Bugs) Date: Sat, 30 Jul 2005 16:52:43 -0700 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> <7xmzo4nmf0.fsf@ruckus.brouhaha.com> Message-ID: Cliff Wells wrote: > > But how stable is GTK on systems such as Windows and OS/X? That has > been what has kept me from using it. Most GTK apps I've used on Windows > (including the venerable GIMP) are nowhere near as stable as their Linux > counterparts (although this may not be entirely the fault of GTK). > Also, GTK on OS/X requires Fink, which is a pretty hefty requirement to > place on an end user. > wxWidgets only uses GTK on Linux. On Windows and OS X it uses native widgets where possible. From casevh at comcast.net Thu Jul 14 13:56:16 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 14 Jul 2005 10:56:16 -0700 Subject: Python Installation error on Solaris-9-SPARC In-Reply-To: <1121363416.498522.138420@g43g2000cwa.googlegroups.com> References: <1121362775.799428.239840@g47g2000cwa.googlegroups.com> <1121363416.498522.138420@g43g2000cwa.googlegroups.com> Message-ID: <1121363776.862756.94770@g47g2000cwa.googlegroups.com> Madhu R. Vajrala wrote: > > 2. gunzip -c Python-2.4.1.tgz | tar xvf - > Use gtar. The Solaris tar does not hnadle long file names correctly. gtar should be found in /usr/sfw/bin. cvh From alexander.chadwick at gmail.com Thu Jul 28 10:37:55 2005 From: alexander.chadwick at gmail.com (ch424) Date: 28 Jul 2005 07:37:55 -0700 Subject: Trigger pygtk drawingarea redraw In-Reply-To: References: <1122544342.581358.274980@g43g2000cwa.googlegroups.com> Message-ID: <1122561475.507887.110710@g47g2000cwa.googlegroups.com> Ahh.. fantastic! Flickers be gone! Yaarrrg! It was "self.area.queue_draw()" in case anyone wants to know. :) Thanks so much! Alex From peter at engcorp.com Sun Jul 10 17:32:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Jul 2005 17:32:07 -0400 Subject: Defending Python In-Reply-To: References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> <42d17b1f$0$19917$636a15ce@news.free.fr> Message-ID: Jorey Bump wrote: > Bruno Desthuilliers wrote: >>it's. > > +1 for this becoming the official name of Python 3000. ;) > > And now for something completely different... > > The larch! Sorry, already taken: '''Larch - John Guttag and Jim Horning . The Larch Project develops aids for formal specifications. Each Larch specification has two components: an interface containing predicates written in the LIL (Larch Interface Language) designed for the target language and a 'trait' containing assertions about the predicates written in LSL, the Larch Shared Language common to all. "The Larch Family of Specification Languages", J. Guttag et al, IEEE Trans Soft Eng 2(5):24-365 (Sep 1985). "Larch: Languages and Tools for Formal Specification", Guttag and Horning, Springer 1993.''' Maybe "Ni!"? -Peter From rkern at ucsd.edu Sun Jul 31 03:49:44 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 00:49:44 -0700 Subject: Thaughts from an (almost) Lurker. In-Reply-To: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> References: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Message-ID: Paddy wrote: > Sometimes when reading c.l.p. I mentally stand off from what I have > been reading and get an odd feeling that 'WE ARE BEING TESTED'. That > someone else is purposefully posting a near repetitive post, or obvious > flame bait etc - not for the usual reasons, but to track the dynamics > af the replies. Rather like dropping a stone in the river and watching > pythonistas return c.l.p. to its normal, helpful, and polite norm. > Fascinating. > I only hope that if thats the case, then they should post their > findings here. My experience with USENET suggests that there is always a steady stream of newbies, trolls, and otherwise clueless people. In the absence of real evidence (like traceable headers), I don't think there's a reason to suspect that there's someone performing psychological experiments on the denizens of c.l.py. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From newsgroups at jhrothjr.com Thu Jul 21 18:00:08 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 21 Jul 2005 16:00:08 -0600 Subject: !Re: PEP on path module for standard library References: Message-ID: <11e06nch396gccd@news.supernews.com> "Michael Hoffman" wrote in message news:dbofk2$g1f$1 at gemini.csx.cam.ac.uk... > Many of you are familiar with Jason Orendorff's path module > , which is frequently > recommended here on c.l.p. I submitted an RFE to add it to the Python > standard library, and Reinhold Birkenfeld started a discussion on it in > python-dev > . > > The upshot of the discussion was that many python-dev'ers wanted path > added to the stdlib, but Guido was not convinced and said it must have a > PEP. Why did Guido want a PEP? Is it because he likes the idea but feels the feature set needs to be examined a bit more by the wider community, or is it some other reason? I'm all in favor of having something that gives an alternative to the kludge of functions that are "just a thin wrapper on the C standard library." Considering the known problems with the C standard library and the fact that it's strictly procedural, that statement doesn't fill me with confidence. Rather it creates a mild sense of dread: nobody has thought out how to do those functions in a useful oo manner. Path looks useable to me. Do I think it's going to be the last word? I sincerely hope not! The only way we're going to find out where it really needs to go from here, though, is to put it out and find out how the wider community uses and abuses it. John Roth > Thanks in advance, > -- > Michael Hoffman From pythonmailing at web.de Mon Jul 25 12:05:06 2005 From: pythonmailing at web.de (Marek Kubica) Date: Mon, 25 Jul 2005 18:05:06 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> <878xzwarjy.fsf@wilson.rwth-aachen.de> Message-ID: <1n2b6iza50vzt$.iieuoodqrike.dlg@40tude.net> Hi! On Sun, 24 Jul 2005 22:16:01 +0200 Torsten Bronger wrote: > I'm very suprised. wxPython is still that buggy? I read reports > from 2000 about such observations, but they tried wxPython in a > non-standard way, and the project has had 5 years to become more > stable after all. Well, I don't know version 2.6.x but I had some trouble with 2.4. I was trying to mass-hide buttons, which was possible with .detach() or .hide() (or was it .show(False)?). This was explained in the documentation, but in the release I had, was a bug somewhere and the widgets had no .detach() function. Robin Dunn said it will be fixed in the next release.. but that release came months later. But I know that the release cycles had got a lot faster in the meantime. > Besides, wxPython prepares for being included into the standard distribution. To replace Tkinter? No problem with that :) Oh, I see, there seems to be a more pythonic wrapper for wx: wax.. http://www.zephyrfalcon.org/labs/wax.html greets, Marek From d.raber at gmx.net Thu Jul 21 02:41:27 2005 From: d.raber at gmx.net (Dieter Raber) Date: 20 Jul 2005 23:41:27 -0700 Subject: mod_python Apache/2.0.52 (Win32) Python 2.4 References: <38d6a9b7.0507201214.12c048ac@posting.google.com> Message-ID: <38d6a9b7.0507202241.7bd7bf59@posting.google.com> Thanks everybody, I followed the link Waldemar had provided and there I found what I was looking for. Dieter From chandra.bangalore at gmail.com Thu Jul 7 09:39:44 2005 From: chandra.bangalore at gmail.com (chand) Date: 7 Jul 2005 06:39:44 -0700 Subject: calling python procedures from tcl using tclpython In-Reply-To: <42CD292C.1010204@uni-oldenburg.de> References: <1120740561.933409.221770@g14g2000cwa.googlegroups.com> <42CD292C.1010204@uni-oldenburg.de> Message-ID: <1120743584.094600.5690@o13g2000cwo.googlegroups.com> That is exactly i want to know. i.e...,how to provide the python code path in tcl script file, that loads required function. --BestRegards., --chandra > definitions etc. Michael Schlenker wrote: > chand wrote: > > Hi.. > > > > I am writing a Gui in TCL and my backend code is python. I want to call > > python procedure in tcl using tclpyhton. I want to know clearly how > > this should be implemented. > > > > let's say I have procedure test_function(arg1,arg2 ...) defined in > > test.py. > > I want to call this procedure in tcl. Let me know how this should be > > achieved. > > The doubt basically have is how the tcl code knows in which .py file > > this procedure is defined. > > > > currently I have wriiten this tcl code which is not working > > > > package require tclpython > > set interpreter [python::interp new] > > $interpreter eval {def test_function(): arg1,arg2} ; > > python::interp delete $interpreter > > > What does not work? You never load your file test.py anywhere inside, > you just evaluate 'def test_function(): arg1,arg2' so what are you > expecting to happen? > > Your call to '$interpreter eval' lets you call arbitrary python code, > but you have to provide the python code that loads your function > definitions etc. I don't know python, but it should be a trivial code. > > Michael From gene.tani at gmail.com Wed Jul 13 12:31:10 2005 From: gene.tani at gmail.com (gene tani) Date: 13 Jul 2005 09:31:10 -0700 Subject: Web App like Google In-Reply-To: <1121188057.886202.86860@g43g2000cwa.googlegroups.com> References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> <1121188057.886202.86860@g43g2000cwa.googlegroups.com> Message-ID: <1121272270.930838.144340@g14g2000cwa.googlegroups.com> Yes, there's a lot of issues, cross-site scripting, session hijacking, proper authentication, etc. Open Web App Security Project is useful www.owasp.org Also, before you start with NLP and full-on parsers, think about if you can apply a text indexer, stemming and stopping both your user's queries and the database content. Much easier conceptually, easier on db server too. and there's lots of good python packages/python bindings. http://www.xapian.org/ http://www.pypackage.org/packages/python-pyndex http://www.divmod.org/Home/Projects/Lupy/ From asdf at ghjk.net Thu Jul 14 18:02:07 2005 From: asdf at ghjk.net (Philip) Date: Fri, 15 Jul 2005 00:02:07 +0200 Subject: [linked lists] Newbie - chapter 19 in "How to think like a CS in python" Message-ID: Hi, I'm reading "How to think like a computer scientist in python". So far, it's been smooth sailing, but the final exercise in chapter 19 really has me stumped. Is it just me, or did this book get very difficult, very quickly? It says: "As an exercise, write an implementation of the Priority Queue ADT using a linked list. You should keep the list sorted so that removal is a constant time operation. Compare the performance of this implementation with the Python list implementation." Here is the code so far: import sys class Node: def __init__(self, cargo=None, next=None, prev=None): self.cargo = cargo self.next = next self.prev = prev def __str__(self): return str(self.cargo) def printBackward(self): if self.next != None: tail = self.next tail.printBackward() print self.cargo class LinkedList: def __init__(self): self.length = 0 self.head = None def printBackward(self): print "[" if self.head != None: self.head.printBackward() print "]" def addFirst(self, cargo): node = Node(cargo) node.next = self.head self.head = node self.length = self.length + 1 def printList(node): sys.stdout.write("[") while node: sys.stdout.write(str(node.cargo)) if node.next != None: sys.stdout.write(", ") else: sys.stdout.write("]") node = node.next print def printBackward(list): if list == None: return head = list tail = list.next printBackward(tail) print head, def removeSecond(list): if list == None: return if list.next == None: return first = list second = list.next first.next = second.next second.next = None return second def printBackwardNicely(list): print "[", if list != None: head = list tail = list.next printBackward(tail) print head, print "]" class Queue: def __init__(self): self.length = 0 self.head = None def isEmpty(self): return (self.length == 0) def insert(self, cargo): node = Node(cargo) node.next = None if self.head == None: self.head = node else: last = self.head while last.next: last = last.next last.next = node self.length = self.length + 1 def remove(self): cargo = self.head.cargo self.head = self.head.next self.length = self.length - 1 return cargo class ImprovedQueue: def __init__(self): self.length = 0 self.head = None self.last = None def isEmpty(self): return (self.length == 0) def insert(self, cargo): node = Node(cargo) node.next = None if self.length == 0: self.head = self.last = node else: last = self.last last.next = node self.last = node self.length = self.length + 1 def remove(self): cargo = self.head.cargo self.head = self.head.next self.length = self.length - 1 if self.length == 0: self.last = None return cargo class PriorityQueue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def insert(self, item): self.items.append(item) def remove(self): maxi = 0 for i in range(1,len(self.items)): if self.items[i] > self.items[maxi]: maxi = i item = self.items[maxi] self.items[maxi:maxi+1] = [] return item class Golfer: def __init__(self, name, score): self.name = name self.score = score def __str__(self): return "%-16s: %d" % (self.name, self.score) def __cmp__(self, other): if self.score < other.score: return 1 if self.score > other.score: return -1 return 0 I figured I'd copy ImprovedQueue and tamper with the insert method so as to traverse the linked list, checking if the cargo of the next node was smaller than the one I was inserting, and if so, to set the current node's next to the new node, and the new node's next to the node with the lesser value, but I just can't get this to work outside of my head. I'd appreciate any pointers anyone might give me to figure this out. From chris.kang.83 at gmail.com Fri Jul 1 18:40:19 2005 From: chris.kang.83 at gmail.com (Christopher Kang) Date: Fri, 1 Jul 2005 18:40:19 -0400 Subject: Python, mysql, floating point values question Message-ID: <43b72594050701154055297e73@mail.gmail.com> I had a question about python and mysql, but I want to first thank those who taught me about the factory method, it was exactly what I needed. Anyway, I have a problem where I am pulling floating point values out of mysql and into python using the MYSQLdb module. However, the values seem to be altered a little when I store them in python. Because the decimal places are off, I am unable to use the values that I have in order to write a sql statement (again using the MYSQLdb) that pulls column values from just that single value i'm looking for. Let me explain more clearly: Let's say I pull column1 values for all records, and they happen to be: 1.4, 1.5632, 1.32523 in the mysql database. Now I realize that I am interested in all the column values for just the 1.5632 record. Unfortunately, python seems to be taking the floating point values, and doing something with it, such that my variable has something like 1.5632000000001 stored in it or such. I thus, can't pull the value out using a sql statement such as "Select * from table_name where column1 = my_variable_value" becuase my_variable_value has 1.563200000000001 stored in it, and not 1.5632. The way that the variable gets adjusted seems to be random. Is there a solution to this? Thank you very much! From cam.ac.uk at mh391.invalid Wed Jul 13 09:02:35 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 13 Jul 2005 14:02:35 +0100 Subject: **kwargs? In-Reply-To: <7OWdnRBJ_sGqkkjfRVn-hw@powergate.ca> References: <7OWdnRBJ_sGqkkjfRVn-hw@powergate.ca> Message-ID: Peter Hansen wrote: > Francois De Serres wrote: > >> *args is documented in the Tutorial. I reckon **kwargs represents a >> dictionary of arguments. But I don't quite get the semantics of **x. >> Undefined length tuple of undefined length tuples? Are there other >> practical use cases for ** (common enough please, I wish I was, but >> I'm not a scientist). > > Where did you get "tuples of tuples" for **x ? I would guess it is confusion from languages where unary * means dereference and ** means double dereference. To the OP: I'm glad you have been reading the tutorial. If you have further questions the reference manual is a good place to look: http://docs.python.org/ref/function.html Just as you can use a name other than self as the first argument to an unbound method, you can call your *args and **kwargs *x and **y instead, but they will still act just like *args and **kwargs. The stars are magic, not the names. -- Michael Hoffman From darkcowherd at gmail.com Mon Jul 11 11:48:40 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Mon, 11 Jul 2005 21:18:40 +0530 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: References: Message-ID: <5f4d3cb50507110848144b2cc4@mail.gmail.com> > > def joels_function(args): > error_result = 0 > good_result = None > process(args) > if error_condition(): > error_result = -1 # flag for an error > elif different_error_conditon(): > error_result = -2 > else: > more_processing() > if another_error_conditon(): > error_result = -3 > do_more_work() > good_result = "Success!" > if error_result != 0: > return (False, error_result) > else: > return (True, good_result) > > > and then call it with: > > status, msg = joels_function(args) > if status == False: > print msg > # and fail... > else: > print msg > # and now continue... > > > This is how I would write it in Python: > > def my_function(args): > process(args) > if error_condition(): > raise SomeError("An error occurred") > elif different_error_conditon(): > raise SomeError("A different error occurred") > more_processing() > if another_error_conditon(): > raise SomeError("Another error occurred") > do_more_work() > return "Success!" > > and call it with: > > try: > result = my_function(args) > print "Success!!!" > except SomeError, msg: > print msg > # and fail... > # and now continue safely here... > > > In the case of Python, calling a function that may raise an exception is I tend to use exceptions, but I think Joel has a point. Taking the example code that you have given above. Let us assume that somebody else is using my_function and DOES NOT write a try except block. This code will run fine except, when the exception is thrown and it will suddenly pop up in some other error handler which may not be handling the situation correctly. You have to plan and create a series of errorhandling classes to handle such situations. However Joels_function forces the caller to write some kind of error handler. If he doesnt write the program will not run. After reading that I have been giving this option some thought. The nice thing about Python is I can easily return tuples. In C++ you have to jump through hoops because you cant return two values easily. DarkCowherd From newsgroups at jhrothjr.com Sun Jul 3 09:15:17 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 3 Jul 2005 07:15:17 -0600 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> Message-ID: <11cfp79d4p0tb06@news.supernews.com> "Robert Kern" wrote in message news:mailman.1264.1120368566.10512.python-list at python.org... > seberino at spawar.navy.mil wrote: >> Guido gave a nice "Python Regrets" Power Point talk at OSCON few years >> ago. >> >> I was wondering if the plan is to ever implement these ideas. >> >> e.g. Guido said he'd prefer 'print' to be a *function* with perhaps a >> 'println' version IIRC. >> >> He also had a ton of stuff he'd rather see become iterators. > > As currently being (re)discussed at tedious length in recent threads here, > changes would will only be realized in Python 3.0 (aka Python 3000 in > facetious reference to when we can expect to see such a beast). I believe the current plan is to make compatible changes in the next few releases, and then make the incompatable changes in Python 3.0 See PEP 3000 for details. http://www.python.org/peps/pep-3000.html What this means is that there is a good chance that a print() built-in function or method on a file object may show up in a future release, the print statment won't go away until Python 3.0. John Roth > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > From bokr at oz.net Fri Jul 29 02:37:52 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 29 Jul 2005 06:37:52 GMT Subject: functions without parentheses References: Message-ID: <42e9c49b.24281464@news.oz.net> On Thu, 28 Jul 2005 00:59:51 -0700 (PDT), Jerry He wrote: >Hi, > Is it possible to create a function that you can use >without parenthesizing the arguments? for example, for > >def examine(str): > ..... > ..... > >Is there some way to define it so that I can call it >like > >examine "string" >instead of examine("string")? > I suggested in a previous thread that one could support such a syntax by supporting an invisible binary operator between two expressions, so that examine "string" translates to examine.__invisbinop__("string") if examine as an expression evaluates to an object that has a __invisbinop__ method. Then you wouldn't define examine as a function, you would define it as an instance of a class like class Examine(object): define __invisbinop__(self, other): #...whatever examine = Examine() and then examine "string" Of course this is a strange syntax mod to the language, and undoubtedly would have many strange effects, but superficially, it seems like something could be done. But a consequence of white space as potential invisible operator would be that foo() and foo () might be foo.__call__() vs foo.__invisbinop_(()) Regards, Bengt Richter From mwm at mired.org Sun Jul 3 18:11:27 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 18:11:27 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> <864qbf8hvr.fsf@bhuda.mired.org> Message-ID: <86ll4n1qwg.fsf@bhuda.mired.org> Joseph Garvin writes: > Mike Meyer wrote: > >>You wind up >>having to invoke the function through your data object, and then pass >>the data object in - sort of as an explicit "self". >> > Yeah, and us pythonists hate explicit self! ;) Except the explicit self is on the method invocation, and not in the method definition! So you wind up repeating the variable name. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 08:33:10 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 14:33:10 +0200 Subject: Getting a dictionary from an object In-Reply-To: <42e37c1e$0$30692$636a15ce@news.free.fr> References: <42e37c1e$0$30692$636a15ce@news.free.fr> Message-ID: <42e3838a$0$29942$626a14ce@news.free.fr> Bruno Desthuilliers a ?crit : (snip) > class Wrapper(object): > def __init__(self, obj): > self._obj = obj > def __getitem__(self, name): > return getattr(self._obj, name) If you want the Wrapper to be more like a Decorator (ie still can use the Wrapper object as if it was the wrapped object), you can add this: def __getattr__(self, name): return getattr(self._obj, name) def __setattr__(self, name, val): if name == '_obj': super(Wrapper, self).__setattr__(name, val) else: setattr(self._obj, name, val) The Python cookbook may have some receipes too for this kind of funny things... From bokr at oz.net Mon Jul 25 16:33:47 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 25 Jul 2005 20:33:47 GMT Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> Message-ID: <42e54c66.1139045941@news.oz.net> On Mon, 25 Jul 2005 17:33:51 +0200, Reinhold Birkenfeld wrote: >Peter Hansen wrote: >> Reinhold Birkenfeld wrote: >>> Current change: >>> >>> * Add base() method for converting to str/unicode. >> >> Would basestring() be a better name? Partly because that seems to be >> exactly what it's doing, but more because there are (or used to be?) >> other things in Path that used the word "base", such as "basename". >> >> -1 on that specific name if it could be easily confused with "basename" >> types of things. > >Right, that was a concern of mine, too. >"tobase"? -1 >"tostring"? +1 >"tobasestring"? -0 > >Alternative is to set a class attribute "Base" of the Path class. Or export >PathBase as a name from the module (but that's not quite useful, because I >expect Path to be imported via "from os.path import Path"). > >Reinhold Regards, Bengt Richter From tzot at sil-tec.gr Sat Jul 2 17:07:39 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sun, 03 Jul 2005 00:07:39 +0300 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1119990282.791576.196130@g43g2000cwa.googlegroups.com> Message-ID: On 28 Jun 2005 13:24:42 -0700, rumours say that "muldoon" might have written: > Now, what forum would you recommend? Any help would be appreciated. alt.usage.english? alt.languages.english? alt.english.usage? uk.culture.language.english? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From rtw at freenet.co.uk Mon Jul 11 19:06:01 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 12 Jul 2005 00:06:01 +0100 (BST) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: <20050711230601.E291BE0000C9@astro.systems.pipex.net> Ralf W. Grosse-Kunstleve wrote in news:mailman.1622.1121120376.10512.python-list at python.org in comp.lang.python: > Does anyone know if there is a way to hide the _ or self_ from the > user of the class, i.e. given: > > class foo(object): > @attribute_decorator > def __init__(self, x, _y, z): > pass > > can we make it such that the user can still write > > foo(x=1,y=2,z=3) > > without the underscore? > Sorry I didn't understand what you ment before: def init_self( init ): class KeywordArgumentError(Exception): pass vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] def decorated_init(self, *args, **kw): off = 0 for name in vn: if not name.startswith('_'): if name in kw: value = kw[name] else: value = args[off] off += 1 setattr( self, name, value ) else: off += 1 #was missing (a bug) in last version. if name in kw: raise KeywordArgumentError( "Use %s not %s" % (name[1:],name) ) if name[1:] in kw: kw[name] = kw[name[1:]] del kw[name[1:]] init( self, *args, **kw ) return decorated_init class MyClass(object): @init_self def __init__( self, x, _y, z ): print "in __init__() _y =", _y def show( self ): for i in self.__dict__: print 'self.%s = %d' %(i,eval('self.%s' % (i,))) MyClass( 1, 2, 3 ).show() MyClass( z = 1, x = 2, y = 3 ).show() MyClass( z = 1, x = 2, _y = 3 ).show() Rob. -- http://www.victim-prime.dsl.pipex.com/ From gh at ghaering.de Fri Jul 8 10:33:46 2005 From: gh at ghaering.de (Gerhard Haering) Date: Fri, 8 Jul 2005 16:33:46 +0200 Subject: psycopg simplest problem In-Reply-To: References: <1110592231.853484.197370@z14g2000cwz.googlegroups.com> Message-ID: <20050708143346.GA7904@mylene.ghaering.de> On Fri, Jul 08, 2005 at 04:23:50PM +0200, Glauco wrote: > [...] > My problem is to do a middle layer over pycopg for eliminate type > casting problem in postgres in all direction. > > i've resolved this doing a C extension in python and manipulating only > string and int in my application. > > this is my example: > import sqlvar > > sql = """insert into mytable (myint, mytext, maydate) > values > (%d,%s,%s);""" % (sqlvar.number(myvalue1), > sqlvar.text(myvalue2), sqlvar.date(myvalue3) ) > > all problem concerning quoting, " ' -> ''", null, None, 0, empty string > is solved by the sqlvar lib. [...] Instead of quoting Python values yourself appropriately for each type, just let the DB-API module do its work. Use parametrized queries and then supply the arguments to the query: cur = con.cursor() intVal = 42 textVal = "Jason's house" dateVal = datetime.date(2005, 7, 8) cur.execute(""" insert into mytable(myint, mytext, mydate) values (%s, %s, %s) """, (intval, textVal, dateVal)) The execute(many) method has an optional second parameter, which is a tuple of values for your parametrized query. There are different styles to parametrize queries among the various DB-API modules. psycopg uses the pyformat one, where you just use %s as placeholders. It will happily quote all Python values of types int, str, date, float, etc. for you. It's also possible to teach it how to quote other custom data types, but you'll normally not need this. HTH, -- Gerhard -- Gerhard H?ring - gh at ghaering.de - Python, web & database development -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ptmcg at austin.rr.com Thu Jul 28 09:39:16 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 28 Jul 2005 06:39:16 -0700 Subject: On fighting fire with fire... In-Reply-To: References: Message-ID: <1122557956.618323.114360@g43g2000cwa.googlegroups.com> Sounds more like fighting fire with... water? Sounds good to me. -- Paul From thomas at thomas-lotze.de Tue Jul 12 16:27:41 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 12 Jul 2005 22:27:41 +0200 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: Christopher Subich wrote: > try: > f=file('file_here') > except IOError: #File doesn't exist > error_handle > error_flag = 1 > if not error_flag: > do_setup_code > do_stuff_with(f) > > which nests on weird, arbitrary error flags, and doesn't seem like good > programming to me. Neither does it to me. What about try: f=file('file_here') except IOError: #File doesn't exist error_handle else: do_setup_code do_stuff_with(f) (Not that I'd want to defend Joel's article, mind you...) -- Thomas From xen0n at vodafone.it Mon Jul 25 08:27:00 2005 From: xen0n at vodafone.it (xen0n at vodafone.it) Date: 25 Jul 2005 05:27:00 -0700 Subject: GPRS Connection name on Python s60 Message-ID: <1122294420.896414.152630@f14g2000cwb.googlegroups.com> Hi, I have a question for the experts of Python for series60! When I use the ".connect" method of the socket, a list with all connection available pop-up, and, after selecting one, the soft go on. My question is that: Can i use the ".connect" method passing connection name, resulting in a connection without the pop up list with connection names? Hope I was clear Thanks in advance! Xen0n From sjmachin at lexicon.net Sat Jul 2 00:13:47 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 02 Jul 2005 14:13:47 +1000 Subject: Python, mysql, floating point values question In-Reply-To: References: <43b72594050701154055297e73@mail.gmail.com> Message-ID: <42C6147B.9040408@lexicon.net> Terry Hancock wrote: > On Friday 01 July 2005 05:40 pm, Christopher Kang wrote: > >>Anyway, I have a problem where I am pulling floating point values out >>of mysql and into python using the MYSQLdb module. >> >>However, the values seem to be altered a little when I store them in python. > > > I'm not even going to start to explain why, but this is a given with > floating point values. They *always* have a degree of imprecision. > You're just tickling this problem by changing representations from > Python to SQL and back. > > Long, long ago when all I knew how to program in was Basic and > Fortran, I learned the fundamental rule of comparing floats --- you > must always allow a tolerance, e.g.: > > epsilon = 0.0001 > if abs(a-b) > epsilon: > print "a ~= b" > else: > print "a != b" > > There is no "equals" with floating point numbers. Just remember that, > and you'll go far. ;-) > > As for how to do this in SQL? I'm pretty sure that you can do > ranges in SQL, but I'd have to look up the syntax for inequality > statements. x BETWEEN y AND z The python equivalent would be to write it out as: > > if a > b-epsilon and a < b+epsilon: > print "a~=b" > Try this: if b-epsilon < a < b+epsilon: From jan.danielsson at gmail.com Sat Jul 23 11:03:08 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Sat, 23 Jul 2005 17:03:08 +0200 Subject: Lists & "pointers" Message-ID: <42e25ac2$1@griseus.its.uu.se> Hello all, I have written a simple whiteboard application. In my application, I want to be able to set draw attributes. This part works. I have a dictionary object which contains stuff like: self.attr['Pen.Color'] = ... self.attr['Pen.Thickness'] = ... Now, the problem is that I want to be able to store attributes in a list so they'll be easily accessed using the function keys. I.e. I have the "current attributes" which I want to be able to store or retrieve in/from a list, The problem is that I have initialized the list like this: self.drawAttr = { blah, blah, blah.. } self.storedAttr = [ ] for i in range(0, 10): self.storedAttr.append(self.drawAttr) I know what the problem is; they are all referencing the *same* dictionary object. So, my question is: How do I initialize a list of dictionary objects, where each list entry is its own object (which is a copy from the self.drawAttr object). Also, how do I store/restore entries to the list? I have found the "copy" module, and it's copy method. I assume this would work: for i in range(0, 10): self.storedAttr.append(copy.copy(self.drawAttr)) However, the concept of "deep copy" confuses me. Do I want it, or don't I want it? I repeat: the attributes object is a simple dictionary. Thankful for any advice. From mensanator at aol.com Thu Jul 7 13:07:57 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 7 Jul 2005 10:07:57 -0700 Subject: precision problems in base conversion of rational numbers In-Reply-To: <1120692715.670429.90360@g47g2000cwa.googlegroups.com> References: <42C91973.6090208@po-box.mcgill.ca> <200507051049.37103.hancock@anansispaceworks.com> <1120642550.714547.256540@z14g2000cwz.googlegroups.com> <1120671142.077815.269630@g49g2000cwa.googlegroups.com> <1120692715.670429.90360@g47g2000cwa.googlegroups.com> Message-ID: <1120756077.370453.175680@o13g2000cwo.googlegroups.com> Raymond Hettinger wrote: > > > For a simple example, convert both 10247448370872321 and > > > 10247448370872319 from base ten to 4 digits of hex. The calculations > > > need to be carried out to 15 places of hex (or 17 places of decimal) > > > just to determine whether the fourth hex digit is a 7 or 8: > > > > > > >>> hex(10247448370872321) > > > '0x24680000000001L' > > > >>> hex(10247448370872319) > > > '0x2467ffffffffffL' > > > > I don't understand your simple example. > > > > log(10)/log(16) = 0.83048202372184058696757985737235 > > > > Multiplying by the number of decimal digits (17) gives > > > > 14.11819440327128997844885757533 > > > > Rounding up to an integer digit count, we need need 15 hex digits. > > Isn't that exactly what you concluded? Where does that 4 hex digit > > stuff come from? > > It is part of the OP's problem spec. Given a number x (which may be a > decimal, float, long integer, or rational), a base b, and a desired > precision p, compute the conversion to p-digits: > > >>> convert(x=10247448370872319L, b=16, p=4) > '24680000000000' But you haven't explained why you are using p=4. The OP's problem is that he's doing convert(x=10247448370872319L, b=16, p=17). So of course it's going to be wrong because base 16 numbers are bigger than base 10 numbers. By trying to use the same precision with different bases, he's asking for more precision in the base 17 number than what exists in the base 10 number. > > He wanted to know what decimal precision he needed to set to make the > conversion accurate to the last place. The required precision for > intermediate calculations depends on how close x is to a representable > value in the target base. The 16 digits are not known a priori since x > may be a rational, float, or decimal. For instance, an internal > precision of 17 digits would also be needed for other nearby values of > x: > > >>> convert(x=Decimal("10247448370872319.000000001", b=16, p=4) > '24680000000000' Now your base 10 number has 26 digits. So shouldn't your convert be using p=22? > > The number 17 does not just pop-out of a simple logarithm. It most certainly does >>> print floor(math.log10(10247448370872319)) + 1 17.0 > How many > internal digits of precision do you need for convert(math.pi, b=16, > p=5)? I think I would need 7. Because >>> print math.log(16)/math.log(10)*5 6.02059991328 >>> from gmpy import * >>> import math >>> print math.pi 3.14159265359 Using math.pi >>> print fdigits(math.pi,16,5) 3.243f at 0 Using only seven digits >>> print fdigits(mpf("3.141593"),16,5) 3.243f at 0 I don't see any problem. > If the result falls closely between reprentable values, the OP > may need to set his "magic number" to something larger than you would > have predicted. > > If you want insight into why the OP's problem statement is deeper than > it appears, then ponder the mystery of why the following returns False: > > >>> x = 554459760520464551937111727196883414687442277344893869152167 > >>> float(x) == float(str(x)) > False No big mystery. Isn't that why they added the Decimal module? > > Hint, the two different underlying routines are trying to compute, > convert(x, b=2, p=53), without the benefit of arbitrary precision > arithmetic. Yep, sure is nice to have that. >>> x = mpz(554459760520464551937111727196883414687442277344893869152167) >>> float(x)==float(str(x)) True > > > Raymond From jbellis at gmail.com Wed Jul 6 15:27:41 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 6 Jul 2005 12:27:41 -0700 Subject: threads and sleep? In-Reply-To: References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <1120625123.135496.318590@g44g2000cwa.googlegroups.com> Message-ID: <1120678061.051033.230090@f14g2000cwb.googlegroups.com> Peter Hansen wrote: > Jonathan Ellis wrote: > > Peter Hansen wrote: > >>Or investigate the use of Irmen's Pyro package and how it could let you > >>almost transparently move your code to a *multi-process* architecture > > > > Unless you're doing anything that would require distributed locking. > > Many if not most such projects do, which is why almost everyone prefers > > to use threads on an SMP machine instead of splitting it across > > multiple smaller boxes. > > I can't address the issue of whether or not "most" such projects require > distributed locking, because I'm not familiar with more than half of > such projects, as you appear to be. Your sarcasm is cute, I suppose, but think about it for a minute. If the opposite of what I assert is true, why would even the mainstream press be running articles along the lines of "multicore CPUs mean programming will get tougher because locking is hard to get right and you can't just scale by relying on the cpu to run your one thread/process really fast anymore." http://www.gotw.ca/publications/concurrency-ddj.htm for one example. -Jonathan From michele.simionato at gmail.com Thu Jul 28 08:01:21 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Jul 2005 05:01:21 -0700 Subject: multiple inheritance super() In-Reply-To: <863bpzmz50.fsf@bhuda.mired.org> References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> <42e748e9$0$32207$626a14ce@news.free.fr> <1122454160.835071.87690@z14g2000cwz.googlegroups.com> <863bpzmz50.fsf@bhuda.mired.org> Message-ID: <1122548998.766210.101860@g47g2000cwa.googlegroups.com> > http://fuhm.org/super-harmful/ That is a pretty good page; I must say that my position is more radical (i.e. it is not super which is harmful, it is multiple inheritance itself that it is harmful: was I going to design a new language I would implement it *without* multiple inheritance). Michele Simionato From mwm at mired.org Sun Jul 24 14:19:05 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 24 Jul 2005 14:19:05 -0400 Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> <11e5m07ef4nq339@news.supernews.com> Message-ID: <86oe8snk2u.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 23 Jul 2005 17:51:31 -0600, John Roth wrote: > >> I also like to know the number of elements, which seems to make >> sense as len(path). Again, the number of characters in the path seems >> to be utterly useless information - at least, I can't imagine a use for >> it. > There are (were?) operating systems that could only deal with a maximum > length for pathnames. If I recall correctly, and I probably don't, Classic > Mac (pre-OS X) was limited to file names of 31 or fewer characters and no > more than 250-odd for the entire pathname. At the very least, some file > manager routines would work and some would not. Are. But I think they're a lot longer now. bhuda% grep PATH_MAX /usr/include/sys/syslimits.h #define PATH_MAX 1024 /* max bytes in pathname */ http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bokr at oz.net Sat Jul 9 12:56:26 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 16:56:26 GMT Subject: why UnboundLocalError? References: <42cf5dc4.178687859@news.oz.net> Message-ID: <42cfeb80.214971372@news.oz.net> On Sat, 09 Jul 2005 06:17:20 GMT, bokr at oz.net (Bengt Richter) wrote: >On Fri, 8 Jul 2005 21:21:36 -0500, Alex Gittens wrote: > >>I'm trying to define a function that prints fields of given widths >>with specified alignments; to do so, I wrote some helper functions >>nested inside of the print function itself. I'm getting an >>UnboundLocalError, and after reading the Naming and binding section in >>the Python docs, I don't see why. >> >It's not clear what you are trying to do with a field string that's >wider than the specified width. Do you want to keep printing lines that >have all blank fields except for where there is left-over too-wide remnants? E.g., >if the fields were ['left','left12345','right','12345right'] and the widths were [5,5,6,6] and align 'llrr' > >should the printout be (first two lines below just for ruler reference) > 1234512345123456123456 > LLLLLLLLLLRRRRRRRRRRRR > left left1 right12345r > 2345 ight > >or what? I think you can get the above with more concise code :-) >but a minor mod to yours seems to do it: [...] Not very tested, but you may enjoy puzzling out a more concise version (and writing a proper test for it, since it might have bugs ;-) >>> def fieldprint(widths, align, fields): ... if len(widths) != len(fields) or len(widths)!=len(align): ... raise ValueError, 'fieldprint argument mismatch' ... align = [getattr(str, j+'just') for j in align] ... results = [] ... while ''.join(fields): ... for i, (fld, wid, alg) in enumerate(zip(fields, widths, align)): ... results.append(alg(fld[:wid], wid)) ... fields[i] = fld[wid:] ... results.append('\n') ... return ''.join(results) ... >>> print fieldprint([5,5,6,6], 'llrr', ['left', 'left12345', 'right', '12345right']) left left1 right12345r 2345 ight BTW, since this destroys the fields list, you might want to operate on a copy (e.g., remaining_fields = fields[:]) internally, or pass a copy to the routine. Of course, you could put "print" instead of "return" in fieldprint and just call it instead of printing what it returns as above, but you didn't show that part in your original example. BTW2, note that "str" above is the built in string type, and it's not a good idea to use a built in name for a variable the way your original code did. Regards, Bengt Richter From peter at engcorp.com Wed Jul 20 18:29:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Jul 2005 18:29:40 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> References: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> Message-ID: stringy wrote: > I have a program that shows a 3d representation of a cell, depending on > some data that it receives from some C++. It runs with wx.timer(500), > and on wx.EVT_TIMER, it updates the the data, and receives it over the > socket. It's generally inappropriate to have a GUI program do network communications in the main GUI thread. You should create a worker thread and communicate with it using Queues and possibly the AddPendingEvent() or PostEvent() methods in wx. There should be many easily accessible examples of how to do such things. Post again if you need help finding them. -Peter From peter at engcorp.com Fri Jul 29 08:16:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 08:16:07 -0400 Subject: Async PySerial (was Re: pySerial Windows write problem) In-Reply-To: References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: Neil Benn wrote: > PySerial doesn;t have any kind of event firing to notify you when data > is available. The way I get round this is to have a loop polling (in a > seperate thread) to see if any data is available (it's a method on the > interface), then read all the data in and fire this off to my > listeners/observers with the read data. On that note, I've got a preliminary version of something I call "Bent" (think "slightly Twisted") which is focused for now on providing an asynchronous version of PySerial which is designed around the event-driven model instead of its current polled scheme. It shares a number of features with the Twisted-based PySerial port (also done by Chris Liechti, for the Twisted team, judging by the code comments) but doesn't require one to adopt the whole Twisted framework. Basically it provides you with the equivalent of one "reactor" per thread for PySerial stuff. On Win32 only for now. There are other limitations too. Not ready for prime time. On the plus side, it's been letting me convert my serial stuff to be fully event-driven and with the resulting much lower latencies and better CPU efficiency, while keeping my code more "traditional" instead of having to force it entirely into the Twisted point of view. Just an FYI. And, obviously, to hear back from those interested. I don't know if this is something that should be contributed to the PySerial project (it's more of a rewrite than an add-on), or set up as a new project, or passed around quietly behind the scenes for a while. No docs yet, no contrived examples (but various pieces of working code in real daily use). Did I mention it wasn't ready for prime time? If you've ever been annoyed having to do .read(1) to get characters one at a time in PySerial, or .read(100) with a timeout, or whatever, this might be of interest to you... -Peter From steve at REMOVETHIScyber.com.au Sat Jul 30 14:53:57 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 04:53:57 +1000 Subject: Comparison of functions References: <4cPGe.28613$fm.2023944@news4.tin.it> Message-ID: On Sat, 30 Jul 2005 17:57:20 +0000, Adriano Varoli Piazza wrote: > Steven D'Aprano ha scritto: > >> Do you understand the difference between partial and total ordering, or >> weakly and strongly ordered? When you do understand them, come back and >> tell me again whether you still think lexicographic sorting has no meaning >> whatsoever. >> > > I think I answered this in another post... If you want to order text > strings (as complex numbers in an index in a book, or in a lexicographic > sort are) do so. I understand the importance it has to you, but it's > hardly reasonable to argue that Python should do the most unintuitive > thing with complex numbers by default just because it suits you. Adriano, list.sort() is not an operation on complex numbers. It is an operation on a list. What is unintuitive is that you can't sort a list merely because of the arithmetical properties of an object in that list. Why should that make a difference? We're not doing arithmetic on the objects, we're sorting the list. It isn't even about *complex numbers* as such -- that was just a convenient example. There are no end to the possible objects which don't define greater than and less than. But you should still be able to sort a list containing them. Sorting is not numeric comparisons! Python already allows you to compare "this is not a number" with the float 5.0. Mathematically, that is meaningless, but I would bet money that 99.9% of programmers would demand that they should be able to sort the list ["this is not a number", 5.0]. Do you think that it is unintuitive too? This conversation has been an exercise in futility. I'm sorry that so many of the people answering find it difficult to see the difference between numeric comparisons of complex numbers (which are rightly forbidden) and sorting of lists of arbitrary objects (which should always succeed): in effect, confusing the current implementation of sort() in Python with the general principle of sorting. Unless anyone comes up with constructive comments (which does not necessarily mean "agrees with me"), I plan to drop this thread until such time, if ever, that I have something more concrete to suggest. -- Steven. From spam.csubich+block at block.subich.spam.com Tue Jul 12 16:06:18 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 12 Jul 2005 16:06:18 -0400 Subject: Slicing every element of a list In-Reply-To: References: <8025cc1305071212173f030365@mail.gmail.com> Message-ID: Gary Herron wrote: > Alex Dempsey wrote: >> for line in lines: >> line = line[1:-5] >> line = line.split('\"\t\"') > This, in fact, did do the operation you expected, but after creating the > new value and assigning it to line, you promptly threw it away. (Because > the loop then went back to the top and (re)assigned the next thing in > lines to line wiping out your nicely sliced computation in lines.) You > need to *do* something with the value in line before you end the loop -- > but what? As an intermediate tip, the entire loop can be written as a single list comprehension: stuff = [li[1:-5].split('"\t"') for li in lines] (You don't need to escape single quotes inside double-quoted strings, and vice versa.) From thomas at thomas-lotze.de Mon Jul 18 15:23:20 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Mon, 18 Jul 2005 21:23:20 +0200 Subject: Frankenstring References: Message-ID: Peter Otten wrote: > I hope you'll let us know how much faster your > final approach turns out to be OK, here's a short report on the current state. Such code as there is can be found at , with a Python mock-up in the same directory. Thinking about it (Andreas, thank you for the reminder :o)), doing character-by-character scanning in Python is stupid, both in terms of speed and, given some more search capabilities than str currently has, elegance. So what I did until now (except working myself into writing extensions in C) is give the evolving FrankenString some search methods that enable searching for the first occurrence in the string of any character out of a set of characters given as a string, or any character not in such a set. This has nothing to do yet with iterators and seeking/telling. Just letting C do the "while data[index] not in whitespace: index += 1" part speeds up my PDF tokenizer by a factor between 3 and 4. I have never compared that directly to using regular expressions, though... As a bonus, even with this minor addition the Python code looks a little cleaner already: c = data[cursor] while c in whitespace: # Whitespace tokens. cursor += 1 if c == '%': # We're just inside a comment, read beyond EOL. while data[cursor] not in "\r\n": cursor += 1 cursor += 1 c = data[cursor] becomes cursor = data.skipany(whitespace, start) c = data[cursor] while c == '%': # Whitespace tokens: comments till EOL and whitespace. cursor = data.skipother("\r\n", cursor) cursor = data.skipany(whitespace, cursor) c = data[cursor] (removing '%' from the whitespace string, in case you wonder). The next thing to do is make FrankenString behave. Right now there's too much copying of string content going on everytime a FrankenString is initialized; I'd like it to share string content with other FrankenStrings or strs much like cStringIO does. I hope it's just a matter of learning from cStringIO. To justify the "franken" part of the name some more, I consider mixing in yet another ingredient and making the thing behave like a buffer in that a FrankenString should be possible to make from only part of a string without copying data. After that, the thing about seeking and telling iterators over characters or search results comes in. I don't think it will make much difference in performance now that the stupid character searching has been done in C, but it'll hopefully make for more elegant Python code. -- Thomas From gustavo at niemeyer.net Thu Jul 7 02:40:10 2005 From: gustavo at niemeyer.net (Gustavo Niemeyer) Date: Thu, 7 Jul 2005 03:40:10 -0300 Subject: ANN: python-constraint 1.0 Message-ID: <20050707064010.GA7979@burma.localdomain> -------- Overview -------- **python-constraint** [1]_ is a Python module offering solvers for Constraint Solving Problems (CSPs) over finite domains in simple and pure Python. CSP is class of problems which may be represented in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...), and constraints (`a < b`, ...). .. [1] http://codespeak.net/~niemeyer/constraint/ -------- Examples -------- Basic ----- Here is a basic interactive example:: >>> from constraint import * >>> problem = Problem() >>> problem.addVariable("a", [1,2,3]) >>> problem.addVariable("b", [4,5,6]) >>> problem.getSolutions() [{'a': 3, 'b': 6}, {'a': 3, 'b': 5}, {'a': 3, 'b': 4}, {'a': 2, 'b': 6}, {'a': 2, 'b': 5}, {'a': 2, 'b': 4}, {'a': 1, 'b': 6}, {'a': 1, 'b': 5}, {'a': 1, 'b': 4}] >>> problem.addConstraint(lambda a, b: a*2 == b, ("a", "b")) >>> problem.getSolutions() [{'a': 3, 'b': 6}, {'a': 2, 'b': 4}] >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(AllDifferentConstraint()) >>> problem.getSolutions() [{'a': 3, 'b': 2}, {'a': 3, 'b': 1}, {'a': 2, 'b': 3}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a': 1, 'b': 3}] Rooks ----- Here is an example solving the classical rooks problem:: problem = Problem() numpieces = 8 cols = range(numpieces) rows = range(numpieces) problem.addVariables(cols, rows) for col1 in cols: for col2 in cols: if col1 < col2: problem.addConstraint(lambda row1, row2: row1 != row2, (col1, col2)) solutions = problem.getSolutions() Magic squares ------------- And here is an example solving a 4x4 magic square:: problem = Problem() problem.addVariables(range(0, 16), range(1, 16+1)) problem.addConstraint(AllDifferentConstraint(), range(0, 16)) problem.addConstraint(ExactSumConstraint(34), [0,5,10,15]) problem.addConstraint(ExactSumConstraint(34), [3,6,9,12]) for row in range(4): problem.addConstraint(ExactSumConstraint(34), [row*4+i for i in range(4)]) for col in range(4): problem.addConstraint(ExactSumConstraint(34), [col+4*i for i in range(4)]) solutions = problem.getSolutions() -------- Features -------- The following solvers are available: - Backtracking solver - Recursive backtracking solver - Minimum conflicts solver Predefined constraint types currently available: - FunctionConstraint - AllDifferentConstraint - AllEqualConstraint - ExactSumConstraint - MaxSumConstraint - MinSumConstraint - InSetConstraint - NotInSetConstraint - SomeInSetConstraint - SomeNotInSetConstraint ------------- Documentation ------------- There's documentation for the module at: - http://codespeak.net/~niemeyer/constraint/doc/ -------- Download -------- **python-constraint** may be found at the following address: - http://codespeak.net/~niemeyer/constraint/files/ --------------------- Subversion repository --------------------- Available at: - http://codespeak.net/svn/user/niemeyer/constraint/ -- Gustavo Niemeyer http://niemeyer.net From prabapython at yahoo.co.in Thu Jul 21 02:15:55 2005 From: prabapython at yahoo.co.in (praba kar) Date: Thu, 21 Jul 2005 07:15:55 +0100 (BST) Subject: How to limit the uploading file size in python? In-Reply-To: <20050720074406.10046.qmail@web8402.mail.in.yahoo.com> Message-ID: <20050721061555.83245.qmail@web8409.mail.in.yahoo.com> Dear All, In Php we can limit the uploading file size by php.ini configuration file. But In python what way we can limit the file uploading size. kindly let me know. regards Prabahar __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From reinhold-birkenfeld-nospam at wolke7.net Sun Jul 31 03:48:45 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 31 Jul 2005 09:48:45 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3l1q3tF10l1krU1@individual.net> Message-ID: <3l3e2tF10ehjrU1@individual.net> phil hunt wrote: > On Sat, 30 Jul 2005 19:01:49 +0200, Reinhold Birkenfeld wrote: >>phil hunt wrote: >> >>> def normalizePath(p, *pathParts): >>> """ Normalize a file path, by expanding the user name and getting >>> the absolute path.. >>> @param p [string] = a path to a file or directory >>> @param pathParts [list of string] = optional path parts >>> @return [string] = the same path, normalized >>> """ >>> p1 = os.path.abspath(os.path.expanduser(p)) >>> if len(pathParts)>0: >>> allPathParts = [ p1 ] >>> allPathParts.extend(pathParts) >>> p1 = os.path.join(*allPathParts) >>> p2 = os.path.abspath(p1) >>> return p2 >>> normalisePath=normalizePath # alternate spelling >>> join=normalizePath # it works like os.path.join, but better >>> >>> >>> To be honest I don't see the point of having a Path class. That's >>> the way Java does it, and I find path handling in Java to be a lot >>> more of a hassle than in Python. (Actually, most things are more of >>> a hassle in Java, but that's another story). >> >>You see, with the Path class the above function could be written as >> >>def normalizePath(p, *pathParts): >> """ Normalize a file path, by expanding the user name and getting >> the absolute path.. >> @param p [Path] = a path to a file or directory >> @param pathParts [list of string/Path] = optional path parts >> @return [Path] = the same path, normalized >> """ >> tp = p.expanduser().abspath() >> return tp.joinwith(*pathParts).abspath() >> >>That's clearly an improvement, isn't it? > > An improvement to what? To how the class is implemented, or to how > it is used? No, the second function is cleaner and more readable than the first, IMHO. > If you mean the former, yes is it, due to the os.path module not > providing a function that does this. > > If you mean the latter, I disagree, because I would then have to > call it with something like: > > pn = normalizePath(Path(p), q) That's easily helped by s/tp = p/tp = Path(p)/. > and then I would have the problem that (pn) isn't a string so > calling a function to write some data into the file at that filename > would no longer work, i.e. this: > > writeFile(pn, someData) > > would become this: > > writeFile(pn.getString(), someData) Why? A Path is a string. Reinhold From skilpat at gmail.com Thu Jul 14 18:51:52 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 14 Jul 2005 15:51:52 -0700 Subject: System calls not using correct permissions? Message-ID: <1121381512.615154.186430@o13g2000cwo.googlegroups.com> My Python script is basically glue for a lot of batch files and whatnot, so it uses os.system liberally. However, there is a strange problem where the scripts called by os.system do not function correctly in the Python code, but work fine when I simply copy and paste the command into the shell myself. I am thinking it's some sort of permissions issue. The batch files contain multiple calls to other scripts as well... don't know if that has anything to do with it. I also set my umask to 0 at the beginning of the [Python] script and still no luck. Anyone know what the deal might be? Thanks, Scott From http Sun Jul 31 22:39:33 2005 From: http (Paul Rubin) Date: 31 Jul 2005 19:39:33 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <7xek9e5ywq.fsf@ruckus.brouhaha.com> Message-ID: <7x3bpuxtwa.fsf@ruckus.brouhaha.com> Ed Leafe writes: > > I can put up a Tk gui in about 5 lines of code from a stock Python > > distro without having to install anything additional. ?How do I do > > that with wxPython? > > import dabo > app = dabo.dApp() > dApp.start() > > Sorry, I couldn't do it in 5. ;-) Oh, and that includes a full menu, too. I get an ImportError exception when I try that. Any suggestions? Note that I don't get that exception from Tkinter. bash-3.00$ python Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import dabo Traceback (most recent call last): File "", line 1, in ? ImportError: No module named dabo >>> import Tkinter >>> From toop82 at comcast.net Sat Jul 16 15:30:49 2005 From: toop82 at comcast.net (R Toop) Date: Sat, 16 Jul 2005 15:30:49 -0400 Subject: Debugger Confusion References: <1120059632.832595.245480@g47g2000cwa.googlegroups.com> Message-ID: By now, you have probably found an IDE that gives you satisfactory debugging. I think your original problem was trying to use an emacs shell (M-x shell) to run Python interpreter. But the emacs Python mode works a whole better than Python in a dumb terminal. Have you tried the following? -- open Python source file in emacs -- expect to see that the buffer is in Python mode, so when you select it, "Python" appears on the modeline and the emacs menu bar, and describe-mode gives mucho info. -- from the emacs Python menu (or Xemacs right click to get Python popup), select "Start interpreter", or just C-c ! keys. -- again from Python source buffer, selectPython "Execute buffer" or C-c C-c keys. -- if the source has pdb.set_trace() as previous post suggested, the interpreter buffer will stop there, and in fact pdb.py will appear in another emacs buffer. -- in the interpreter, type n Enter --now you'll see the desired pointer in a temp copy of your Python source or whatever imported Python library you find yourself. With emacs/Python syntax highlighting (M-x font-lock-fontify-buffer), it's not bad. The one true editor is always worth the effort :) HTH. "Rex Eastbourne" wrote in message news:1120059632.832595.245480 at g47g2000cwa.googlegroups.com... > One thing: is it possible to go through the code within emacs? Doing it > on the command line is useful, but it would be very helpful if I could > have a little marker within the emacs buffer that showed me where I am. > > Rex > From petebarrett at beeb.net Sun Jul 10 12:07:30 2005 From: petebarrett at beeb.net (Pete Barrett) Date: Sun, 10 Jul 2005 17:07:30 +0100 Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: On 10 Jul 2005 02:57:04 -0700, "Xah Lee" wrote: >Similarly, in computer languages, expressiveness is significant with >respect to semantics, not syntactical variation. > It may just be me, but I tend to think of a computer language as a tool for directing computers to perform specific actions. Do we talk about the expressiveness of a spade? There's a similar concept in the 'possible uses' of a tool (a spade is an excellent tool for digging the garden, but you wouldn't use it to clean your teeth; you *could* use a toothbrush to dig the garden, but you wouldn't if a spade was available). Similarly with computer languages - some are better for certain tasks than others, but I don't think 'expressiveness' is the way to describe that. Pete Barrett From cam.ac.uk at mh391.invalid Fri Jul 22 16:03:51 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 21:03:51 +0100 Subject: PEP on path module for standard library In-Reply-To: <3kd092FtshinU1@individual.net> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <3kd092FtshinU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Andrew Dalke wrote: > >>I disagree. I've tried using a class which wasn't derived from >>a basestring and kept running into places where it didn't work well. >>For example, "open" and "mkdir" take strings as input. There is no >>automatic coercion. > > Well, as a Path object provides both open() and mkdir() functions, these use > cases are covered. And that's the point of the Path class: Every common use > you may have for a path is implemented as a method. Except when you pass the path to a function written by someone else > So, it's maybe a good thing that for uncommon uses you have to explicitly > "cast" the path to a string. Where uncommon uses include passing the path object to any code you don't control? The stdlib can be fixed, this other stuff can't. >>The solutions to this are: >> 1) make the path object be derived from str or unicode. Doing >>this does not conflict with any OO design practice (eg, Liskov >>substitution). >> >> 2) develop a new "I represent a filename" protocol, probably done >>via adapt(). >> >>I've considered the second of these but I think it's a more >>complicated solution and it won't fit well with existing APIs >>which do things like >> >> >> if isinstance(input, basestring): >> input = open(input, "rU") >> for line in input: >> print line >> >>I showed several places in the stdlib and in 3rd party packages >>where this is used. > > That's a valid point. However, if Path is not introduced as a string, > most new users will not try to use a Path instance where a string is > needed, just as you wouldn't try to pass a list where a string is wanted. But many functions were written expecting lists as arguments but also work for strings, and do not require an explicit list(mystring) before calling the function. -- Michael Hoffman From jepler at unpythonic.net Sun Jul 24 10:19:54 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 24 Jul 2005 09:19:54 -0500 Subject: How to realize ssh & scp in Python In-Reply-To: <42E27B0C.000136.18200@m111.126.com> References: <42E27B0C.000136.18200@m111.126.com> Message-ID: <20050724141951.GA32464@unpythonic.net> Rather than doing anything with passwords, you should instead use public key authentication. This involves creating a keypair with ssh_keygen, putting the private key on the machine opening the ssh connection (~/.ssh/id_rsa), then listing the public key in the remote system's ~/.ssh/authorized_keys. If you don't want to use this approach, `pexpect'[1] is supposed to be able to perform this sort of tasks, and one of its examples is called `sshls.py'. I just downloaded it, and after changing the ssh commandline to include -o 'PreferredAuthentications password' it worked for me. In another recent thread, a different poster claimed it didn't work, so your results may vary. Jeff [1] http://pexpect.sourceforge.net/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From hancock at anansispaceworks.com Fri Jul 1 22:06:24 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 21:06:24 -0500 Subject: shelve in a ZipFile? In-Reply-To: <42c57b58$1@nntp0.pdx.net> References: <42c57b58$1@nntp0.pdx.net> Message-ID: <200507012106.24260.hancock@anansispaceworks.com> On Friday 01 July 2005 12:53 pm, Scott David Daniels wrote: > Terry Hancock wrote: > > I only just recently had a look at the shelve module.... > > That would be handy if, for example, I wanted to couple > > (and compress into the bargain) by putting my two > > shelf files into a single zip archive. > > You are, however, fooling yourself if you think a shelve > solution can be made to gracefully interact with a zip- > compressed version. In order to zip the shelve data, it > must all be seen in a pass, so every update would necessarily > rewrite the entire shelve storage. much better to extract the > entire shelve file, operate on it, and re-compress it. Yeah, I've already decided to just go with the two linked shelf files. The only drawback to this is that the user can accidentally separate the two files, which causes one of them to become useful (1st shelf relies on named references to objects in the 2nd shelf). I used to have problems like that with IRAF, which stored image headers and images in two related files with different file extensions. Once they're two separate units, you have to consider the cases where they get separated. OTOH, the 2nd shelf file has independent uses, which don't depend on the 1st, so in that way, it's desireable for it to be separable. Probably if I was really worried about it, I'd come up with a more serious solution, but this is a lightweight script, so I think I'll just stick with shelve for convenience. Actually, as small as the databases are in this project, I probably could've just pickled a tuple of dictionaries (or something similar). But I think shelves will probably do a better job. Thanks though, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tdwdotnet at gmail.com Mon Jul 4 12:41:46 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Mon, 4 Jul 2005 17:41:46 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file In-Reply-To: References: Message-ID: <9afea2ac0507040941749a0708@mail.gmail.com> On 7/4/05, Guy Lateur wrote: > > Anything else I could try? Lateral thinking ? === untested === import imaplib, time, sys f = open(msg_file) r = f.readlines() f.close() msg1 = ''.join(r) server = 'my.exchangeserver.com' # or IP address user = 'user' pw = 'pw' M = imaplib.IMAP4(server) M.sock.settimeout(120) M.login(user,pw)[1][0] M.select() M.append('INBOX',None ,time.time() , msg1) # Inbox or other folder name print "MESSAGE successfully saved" #M.close() Don't use close, deletes/purges items M.logout()[1][0] From jepler at unpythonic.net Fri Jul 22 15:35:08 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 22 Jul 2005 14:35:08 -0500 Subject: Mapping a drive to a network path In-Reply-To: <1122059720.962075.53260@g44g2000cwa.googlegroups.com> References: <1122059720.962075.53260@g44g2000cwa.googlegroups.com> Message-ID: <20050722193507.GC25836@unpythonic.net> in fact, see this thread, it may have something useful for you: http://mail.python.org/pipermail/python-win32/2003-April/000959.html Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 14:52:49 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 20:52:49 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e3dca6$0$28795$626a14ce@news.free.fr> Steven D'Aprano a ?crit : > On Sun, 24 Jul 2005 12:07:02 +0300, Thanos Tsouanas wrote: >> >>>Thanos Tsouanas wrote: >>> (snip) >>I didn't know about it, but I knew about object.__dict__ which is, as I >>see equivalent with vars(object). But it doesn't do the job for me, >>since it fails to grab all obj.foo's, some of them being properties, >>etc. > (snip) > I don't think you are correct. As far as I can see, properties do have > an entry in obj.__dict__ the same as other attributes, although there is > certainly some strangeness going on with properties. > > Using the sample code from here: > http://www.python.org/2.2.3/descrintro.html#property > > class C(object): > def __init__(self): > self.__x = 0 > def getx(self): > return self.__x > def setx(self, x): > if x < 0: x = 0 > self.__x = x > x = property(getx, setx) > > I see _C__x in C().__dict__, exactly as expected. (snip) Yes, but you don't see 'x'. Poking into the object's __dict__ would defeat the whole point of computed attributes - which by the way need not directly map to a protected or private variable, nor even be properties (think: descriptors). > I can't see any way to inspect a Python object and get a list of > properties, I do : def list_properties(obj): proptype = type(property()) # not defined in types klass = obj.__class__ names = dir(klass) # so we get inherited attribs as well d = dict([(name, getattr(klass, name)) for name in names]) return [name for name, attrib in d.items() \ if type(attrib) is proptype] Note that this won't find all descriptors (I've tried and it really harder... there are a lot of things in a class.__dict__ that have a __get__() method, most of'em not defined in the types module). Anyway, you won't need it... (I mean, the OP don't need it to solve it's problem) > so you might have to keep your own list: add a class-attribute > of your object which keeps a list of all the properties: > > class Obj: > # various methods, attributes and properties > ... > # keep a list of special properties that don't show > # up correctly in __dict__ > special = ['foo', 'bar'] > > # now define a special method that makes a copy of > # __dict__ and adds special properties to it > > def objdict(self): > D = self.__dict__.copy() > # assume shallow copy is enough > for property_name in self.special: > D[property_name] = self.__getattribute__(property_name) > return D > > then call it when you need it: > > print "My object has fields %(foo)s and %(bar)s." % obj.objdict() This means adding responsabilities to the class when the need is obviously orthogonal to the class's responsabilities. Implementing a generic decorator pattern in Python does'nt require more code, doesn't requires the class nor the object to be modified at all, is probably more robust, and is, well... more generic !-) (should I say 'more pythonic' ?) > It would be nice to see an easier way to introspect objects and get > a list of properties. You're dream is now reality. Now ain't *that* nice ?-) Bruno From eurleif at ecritters.biz Wed Jul 6 22:47:09 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 07 Jul 2005 02:47:09 GMT Subject: Use cases for del In-Reply-To: <11cp2c8184lnv83@corp.supernews.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> Message-ID: Grant Edwards wrote: > 1) So I know whether an parameter was passed in or not. Perhaps > it's not considered good Pythonic style, but I like to use a > single method for both get and set operations. With no > parameters, it's a get. With a parameter, it's a set: > > class demo: > def foo(v=None): > if v is not None: > self.v = v > return self.v _NOVALUE = object() class demo: def foo(v=_NOVALUE): if v is _NOVALUE: return self.v else: self.v = v But what's wrong with properties? From sybrenUSE at YOURthirdtower.com.imagination Mon Jul 11 03:14:19 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 11 Jul 2005 09:14:19 +0200 Subject: ZipFile and file rigths References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> <1121034112.762673.31530@z14g2000cwz.googlegroups.com> Message-ID: Robert Kern enlightened us with: > Yes, the .zip file format does store file permissions appropriate to > the platform that generates the file. I never knew that! Thanks for correcting me ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From s_david_rose at hotmail.com Tue Jul 5 16:23:51 2005 From: s_david_rose at hotmail.com (GMane Python) Date: Tue, 5 Jul 2005 16:23:51 -0400 Subject: Invoke ffmpeg from MySQL Message-ID: Hello All. First, I'd like to thank you all for the tremendous help I've received in the past while posting here. I'd like to ask another question. I'd like to use Python to invoke ffmpeg to encode some still-frames into an animation. I'd like to use MySQL to store the frames as a BLOB object. I'd like to know if anyone can help me with the invocation syntax. If I had, say, 10,000 frames stored in the database, how would I be able to send to ffmpeg without needing to write them to the hard-drive first, for encoding. Ultimately, I'd like a 2-pass, but would settle for 1-pass right-away. Thank you! Dave Rose From dalke at dalkescientific.com Wed Jul 27 16:11:05 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 27 Jul 2005 20:11:05 GMT Subject: can list comprehensions replace map? References: Message-ID: David Isaac wrote: > I have been generally open to the proposal that list comprehensions > should replace 'map', but I ran into a need for something like > map(None,x,y) > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > info from x. How do I do this as a list comprehension? (Or, > more generally, what is the best way to do this without 'map'?) If you know that len(x)>=len(y) and you want the same behavior as map() you can use itertools to synthesize a longer iterator >>> x = [1,2,3,4,5,6] >>> y = "Hi!" >>> from itertools import repeat, chain >>> zip(x, chain(y, repeat(None))) [(1, 'H'), (2, 'i'), (3, '!'), (4, None), (5, None), (6, None)] >>> This doesn't work if you want the result to be max(len(x), len(y)) in length - the result has length len(x). As others suggested, if you want to use map, go ahead. It won't disappear for a long time and even if it does it's easy to retrofit if needed. Andrew dalke at dalkescientific.com From pekka.niiranen at wlanmail.com Fri Jul 22 16:01:12 2005 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Fri, 22 Jul 2005 23:01:12 +0300 Subject: Question about namespaces and import. How to avoid calling os.system In-Reply-To: References: <42e14753$0$27392$39db0f71@news.song.fi> Message-ID: <42E15088.5020509@wlanmail.com> Thanks, I will analyse these 4 options and select the most suitable since there are other issues involved too, like "the "main.py" reads contents of a file to a list that gets passed to the "gen.py" with dictionary "env_params"". I try to avoid parsing the contents of the file both in "main.py" and in "gen.py" -pekka- > Jeff Epler wrote: > In main.py, execfile("gen.py") > > or > > In gen.py, have something like > from __main__ import env_params > > or > > In main.py, have something like > import __builtins__; __builtins__.env_params = env_params > > or > > call a function in the gen.py with env_params as a parameter > import gen > gen.do(env_params) > > Jeff From fphsml at gmail.com Sun Jul 17 05:24:03 2005 From: fphsml at gmail.com (James) Date: 17 Jul 2005 02:24:03 -0700 Subject: I just wanna know about os.path module.. In-Reply-To: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> References: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> Message-ID: <1121592243.271033.164430@g43g2000cwa.googlegroups.com> kimes wrote: > I've just started digging into how python works.. > I found that other mudules are clearly declared like one file per a > module.. > > But the only os.path doesn't have their own file.. > ye I know is has actually depending on os like in my case posixpath.. > > What I'd love to know is.. > when I call import os.path.. > how happened under the hood? > > I'm currently using python 2.4 in linux machine.. > I'd appreciate it See line 5 of os.py (comment) - os.path is one of the modules posixpath, ntpath, or macpath It says it sets os.path depending on the platform and does so in line 132 sys.modules['os.path'] = path In your case, os.path should be implemented in posixpath.py See line 48 to see where it came from In short, "use the source, Luke" :-) especially when Python is exceptionally readable. From brian at sweetapp.com Tue Jul 19 05:20:19 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 19 Jul 2005 11:20:19 +0200 Subject: Python Programming Contest In-Reply-To: References: Message-ID: <42DCC5D3.7030307@sweetapp.com> ThanhNam Nguyen wrote: >>>1st day: A --> B 100 bucks >>>2nd day: A --> B 60 bucks >>>3rd day: A --> B 40 bucks >>>What would the solution be? And for how much in total? >>> >> >>There are two correct solutions: >> >>["A", "B"] # spend one night in A, then fly to B on day two (cost 80) >>["A", "A", "B"] # spend two nights in A, then fly to B on day two >>(cost 80) > > > They all mean I must start from the first day. > > The best solution would be, I fly from A to B for 40 bucks on day 3, > assuming I live in the current city A. Then you should assume that you don't live in city A, because the actual cost in this case is 80. Cheers, Brian From smulloni at smullyan.org Tue Jul 26 17:13:55 2005 From: smulloni at smullyan.org (Jacob Smullyan) Date: Tue, 26 Jul 2005 16:13:55 -0500 Subject: [ANN] PyDO-2.0b1 Released Message-ID: I'm pleased to announce the release of PyDO-2.0b1, the second beta release of the 2.0 series. What's New ---------- * more tests and corresponding bug fixes. What it is ---------- PyDO is Drew Csillag's ORM (Object-Relational Mapper) database access library for Python that facilitates writing a Python database access layer. PyDO attempts to be simple, flexible, extensible, and unconstraining. PyDO 2 is a rewrite of the 1.x series distributed with SkunkWeb. It has several enhancements: * PyDO can now be used in multi-threaded or twisted-style asynchronous sitations, with or without a customizable connection pool. * PyDO objects are now dict subclasses, but also support attribute access to fields. * Projections -- subsets of the field list of a super-class -- are now supported by the PyDO.project() method. * Table attributes are now declared in a more concise way. * PyDO2 supports runtime table introspection. * Overall, the API has been tightened and the code restructured. PyDO 2 requires Python 2.4 or later. It currently supports PostgreSQL, MySQL, Sqlite, MSSQL, and Oracle, and support for other databases is planned. PyDO is dual GPL/BSD licensed. The source tarball is available at SkunkWeb's berlios site: https://developer.berlios.de/projects/skunkweb/ or, more directly: http://download.berlios.de/skunkweb/PyDO-2.0b1.tar.gz Questions pertaining to PyDO can be addressed to the SkunkWeb mailing list at sourceforge: http://lists.sourceforge.net/lists/listinfo/skunkweb-list Cheers, js -- Jacob Smullyan From falcon3166 at hotmail.com Mon Jul 18 01:19:45 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 17 Jul 2005 23:19:45 -0600 Subject: Who uses input()? [was Re: question on "input"] References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com><1121179143.995844.28690@g47g2000cwa.googlegroups.com><200507141240.14373.hancock@anansispaceworks.com> <3e8ca5c8050717221220121c54@mail.gmail.com> Message-ID: I use input() all the time. I know many people say it ain't safe, but whose going to use it to crash their own comp? Only an insane person would, or a criminal trying to cover his/her tracks. Sorry if I waded into the debate, but this debate originated from one of my posts. Nathan Pinno ----- Original Message ----- From: "Stephen Thorne" To: Cc: Sent: Sunday, July 17, 2005 11:12 PM Subject: Re: Who uses input()? [was Re: question on "input"] > On 15/07/05, Terry Hancock wrote: >> On Thursday 14 July 2005 07:00 am, Michael Hoffman wrote: >> > Devan L wrote: >> > > Use raw_input instead. It returns a string of whatever was typed. Input >> > > expects a valid python expression. >> > >> > Who actually uses this? It's equivalent to eval(raw_input(prompt)) but >> > causes a lot of newbie confusion. Python-dev archives revealed that >> > someone tried to get this deprecated but Guido disagreed. >> >> I don't think it should disappear, but it *does* seem more sensible for >> "raw_input" to be called "input" (or "readstring" or some such thing) and >> "input" to vanish into greater obscurity as "eval_input" or something. >> >> Unfortunately, that would break code if anything relied on "input", so I >> guess that would be a Py3K idea, and maybe the whole I/O concept >> will be rethought then (if the "print" statement is going to go away, >> anyway). > > I don't see as "break input() using code" -> "not until py3k" as a > logical cause/effect. No one should be using input() anyway, the only > place it's at-all appropriate is in a python tutorial, with the 'guess > the number' game. > > -- > Stephen Thorne > Development Engineer > -- > http://mail.python.org/mailman/listinfo/python-list > From sybrenUSE at YOURthirdtower.com.imagination Mon Jul 18 03:53:14 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 18 Jul 2005 09:53:14 +0200 Subject: What is your favorite Python web framework? References: Message-ID: Admin enlightened us with: > "Error 404 while looking up your page AND when looking for a suitable 404 > page. Sorry! > No such file /var/www/www.unrealtower.org/compiled/error404.py" You must have caught me editing some stuff, try again ;-) I really need to create another virtual host for when I want to experiment with my scripts and stuff :D Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rwgk at yahoo.com Mon Jul 11 15:51:48 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 11 Jul 2005 12:51:48 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <42D155FE.4030800@freenet.co.uk> Message-ID: <20050711195148.18706.qmail@web31501.mail.mud.yahoo.com> --- Robert Williscroft wrote: > My apologies for having to resort to email but for some reason I can't post > this message to comp.lang.python. I've tried about 4 times including > starting a > new thread, but for some reason it doesn't turn up, though I've followed > up on > another thread without problem. Very strange. I hope it is not a conspiracy! :) You can email to the list directly (that's what I am doing): python-list at python.org > > Is there a way out with Python as-is? > > ------------------------------------- > > > > Yes. If you take the time to look at the file in the CVS you'll find > > that I was cheating a bit. To reduce the terrible clutter above, I am > > actually using a simple trick:: > > > > adopt_init_args(self, locals()) > > > > Also there is a decorator solution: > > def init_self( init ): > vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] > > def decorated_init(self, *args, **kw): > off = 0 > for name in vn: > if not name.startswith('_'): > if name in kw: > value = kw[name] > else: > value = args[off] > off += 1 > > setattr( self, name, value ) > > init( self, *args, **kw ) > return decorated_init > > > class MyClass(object): > __slots__ = ['x', 'z'] > > @init_self > def __init__( self, x, _y, z ): > pass > > def show( self ): > for i in self.__slots__: > print 'self.%s = %d' %(i,eval('self.%s' % (i,))) > > MyClass( 1, 2, 3 ).show() > > MyClass( z = 1, x = 2, _y = 3 ).show() > > The __slots__ is in the test just because you mentioned you like it, > the decorator doesn't need a "slots" class. > > AFAICT this differs from your proposal in that in your proposal you > want to use '.' as an include prefix the above uses '_' as an exclude > prefix. > > Rob. I like the looks of the decorator approach a lot. Could this somehow be enhanced such that the user doesn't have to know about the underscore? Thinking about runtime efficiency, could the decorator approach somehow achieve that the attribute-to-be arguments are never added to locals()? Cheers, Ralf ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ From michael at stroeder.com Mon Jul 18 14:08:30 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 18 Jul 2005 20:08:30 +0200 Subject: Python ldap pointers for a newbie - Actually just trying to decifer the error.. In-Reply-To: <1121694855.926576.15570@o13g2000cwo.googlegroups.com> References: <1121694855.926576.15570@o13g2000cwo.googlegroups.com> Message-ID: <0q7tq2-d4d.ln1@nb2.stroeder.com> rh0dium wrote: > > ldap_result_id = cnx.search_s(baseDN, searchScope, searchAttrs, retrieveAttrs) You are already using the synchronous search method which indeed return the search results. So this should read: result_data=cnx.search_s(baseDN,searchScope,searchAttrs,retrieveAttrs) > result_type, result_data = cnx.result(ldap_result_id, 0) You don't need this if you just want to use synchronous search method. Ciao, Michael. From EP at zomething.com Sun Jul 10 22:08:28 2005 From: EP at zomething.com (EP) Date: Sun, 10 Jul 2005 18:08:28 -0800 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> Message-ID: <20050710180828.1481085248.EP@zomething.com> > Well, I want to offer a more radical proposal: why not free squared > braces from the burden of representing lists at all? It should be > sufficient to write > > >>> list() > list() > >From a visual comprehenison point of view, I would assert that the square form [] is much easier on the eyes than the subtler curved forms (e.g. "{" and "("). Burdened with old eyes, small fonts, and an old, inflexible mind (;-), one of Python features near and dear to me are lists, [], and list comprehensions, but perhaps a more important point for 3.0 would be that there is a seamless consistency across the language (e.g. [list(), dict(), tuple()] or [ [], {}, () ] rather than [list(), {}, ()]) thus reflecting a cohesiveness both in underlying approach and symbology. Even old guys can adjust to something new that is good and clean. From ucntcme at gmail.com Thu Jul 14 17:55:45 2005 From: ucntcme at gmail.com (ucntcme at gmail.com) Date: 14 Jul 2005 14:55:45 -0700 Subject: Frankenstring References: Message-ID: <1121378145.470576.34130@g14g2000cwa.googlegroups.com> Here is a cStringIO based version: class FrankenString: def __init__(self,string=None): self.str = StringIO(string) self.atEnd = False self.lastidx = 0 self.seek = self.str.seek self.tell = self.str.tell def __iter__(self): while not self.atEnd: char = self.str.read(1) idx = self.str.tell() if self.lastidx == idx: self.atEnd = True self.lastidx = idx yield char On a string 1024*1024 long the StringIO version takes 10s to iterate over but do nothing, whereas this one takes 3.1 on my system. Well to create that string, create the instance and loop over. But since each variant is doing the same thing I figure it's even. ;) From hancock at anansispaceworks.com Thu Jul 7 16:47:44 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 7 Jul 2005 15:47:44 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <200507071547.44651.hancock@anansispaceworks.com> On Wednesday 06 July 2005 09:41 am, Steven Bethard wrote: > Terry Hancock wrote: > > And a syntax just occured to me -- what about this: > > [ for ] > > If you haven't already, see: > http://wiki.python.org/moin/AlternateLambdaSyntax > for other similar proposals. Yeah, it's basically "Robert Brewer: for (no-parens) syntax [3]" isn't it (except that his eliminates the [], which is probably saner). But hey, it's surely a good thing (in the sense of being more obvious) that it occured to me independently, right? ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From edgrsprj at ix.netcom.com Fri Jul 15 00:42:12 2005 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Fri, 15 Jul 2005 04:42:12 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> <2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net> <6DhBe.3077$dU3.691@newsread2.news.pas.earthlink.net> Message-ID: "Hank Oredson" wrote in message news:6DhBe.3077$dU3.691 at newsread2.news.pas.earthlink.net... > >> >> > "edgrsprj" wrote in message > >> >> > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... > >> >> >> PROPOSED EARTHQUAKE FORECASTING > >> >> >> COMPUTER PROGRAM DEVELOPMENT EFFORT > I am looking for the SOURCE of the data, that is, where did > YOU get the data from, so that I may obtain my own datasets. > In particular I am interested in the EM dataset. July 14, 2005 Hi Hank, I have another important project that I need to focus on at the moment and unfortunately cannot yet spend too much time on this one. The purpose of the original post was simply to determine if there were any people interested in this proposed project. And your responses and others indicate that there are. Detailed information regarding the forecasting program can be found on the following Web page: http://www.freewebz.com/eq-forecasting/301.html Demonstration versions of the data files you are interested in plus an early, fully operational version of the Perl language data processing program itself can be found in the following files: http://www.freewebz.com/eq-forecasting/311.zip http://www.freewebz.com/eq-forecasting/312.zip http://www.freewebz.com/eq-forecasting/313.zip That program contains the following equations which do most of the important work: $londiff = 2**(1 + (abs($dblonval - $testlonval)/3.9)); $probvalue = $testsigstren*$testweight*(10 - $londiff); If you download all of the files and follow the ReadMe.txt instructions for how to organize a directory where the files can be stored and run, then if you have Perl running on your computer the ETDPROG.pl program should run okay under Windows XP and fairly well under Windows 98. Other operating systems probably need to have some adjustments made to the ETDPROG.pl file. The files that I myself actually use are too large to store at that Web site. As far as obtaining the original data, each file is a composite of a number of different types of data. For instance, the main earthquake data file contains actual earthquake data (mostly NEIS) and specially processed sun, moon, ocean tide, and Solid Earth Tide data. At the moment, the complete files including the EM signal data file have to be obtained by e-mail from me (no charge). An important goal of this project is to have all of them stored at a Web site for downloads. Also, I collect the EM signal data myself. But if this project ever gets off the ground those types of data will hopefully become available for free from many sources around the world. Finally, remember as I said earlier, I have been working on this project for 15 years. And it covers a lot of territory. A detailed discussion of it would fill a small book! From deets at web.de Sun Jul 3 09:47:42 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 03 Jul 2005 15:47:42 +0200 Subject: website catcher In-Reply-To: <1120396132.606888.322880@g14g2000cwa.googlegroups.com> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> <3iq5e7Fmn8drU1@uni-berlin.de> <1120396132.606888.322880@g14g2000cwa.googlegroups.com> Message-ID: <3iq8juFmr22qU1@uni-berlin.de> jwaixs wrote: > If I should put the parsedwebsites in, for example, a tablehash it will > be at least 5 times faster than just putting it in a file that needs to > be stored on a slow harddrive. Memory is a lot faster than harddisk > space. And if there would be a lot of people asking for a page all of > them have to open that file. if that are 10 requests in 5 minutes > there's no real worry. If they are more that 10 request per second you > really have a big problem and the framework would probably crash or > will run uber slow. That's why I want to open the file only one time > and keep it saved in the memory of the server where it don't need to be > opened each time some is asking for it. I don't think that's correct. An apache serves static pages with high speed - and "slow hardrives" means about 32MByte/s nowadays. Which equals 256MBit/s - is your machine connected to a GBit connection? And if it's for internet usage, do you have a GBit connection - if so, I envy you... And if your speed has to have that high, I wonder if python can be used at all. BTW, 10 reqeuest per seconds of maybe 100KB pages is next to nothing - just 10MBit. It's not really fast. And images and the like are also usually served from HD. You are of course right that memory is faster than harddrives. but HDs are (ususally) faster than network IO - so that's your limiting factor, if at all. And starting CGI subrpocesses introduces also lots of overhead - better use fastcgis then. I think that we're talking about two things here: - premature optimization on your side. Worry about speed later, if it _is_ an issue. Not now. - what you seem to want is a convenient way of having data serverd to you in a pythonesque way. I personally don't see anything wrong with storing and retrieving pages from HD - after all, that's where they end up anyway ebentually. So if you write yourself a HTMLRetrieval class that abstratcs that for you and 1) takes a piece of HTML and stores that, maybe associated with some metadata 2) can retrieve these chunks of based on some key you are pretty much done. If you want, you can back it up using a RDBMS, hoping that it will do the in-memory-caching for you. But remember that there will be no connection pooling using CGIs, so that introduces overhead. Or you go for your own standalone process that serves the pages through some RPC mechanism. Or you ditch CGIs at all and use some webframework that serves from an permanenty running python process with several worker threads - then you can use in-process memory by global variables to store that memory. For that, I recommend twisted. Diez From zathras at thwackety.com Sun Jul 3 17:04:00 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sun, 03 Jul 2005 23:04:00 +0200 Subject: Python concurrent tasking frameworks? References: <2jacl3yge2.fsf@random-node.example.org> Message-ID: <42c860d4$0$2043$ed2e19e4@ptn-nntp-reader04.plus.net> Chris Stiles wrote: > I was wondering if anyone had a list of the various (presuming more than > one) > Python tasking frameworks? I know of Twisted already, but I'm really > looking > for something along the lines of a task/thread pool type of arrangement. The Kamaelia framework might or might not be what you're looking for. It's not really thread pool based, but rather based around the idea of communicating generators (which as used as components) to form interesting systems. (Though you can also use threads if you want) Communications happens in a manner very similar to unix pipelines, but since it's a single system data is passed (essentially) by reference rather than serialised to go over a unix pipe, and also rather than a single 1D pipe, you can form arbitrary "graphlines". A simple TCP based vorbis streaming client can look like this: pipeline(TCPClient("127.0.0.1",clientServerTestPort), VorbisDecode(), AOAudioPlaybackAdaptor() ).run() (Assuming necessary imports!) This says take the data the TCPClient sends out and pass to the VorbisDecode, and pass its output to the AOAudioPlaybackAdaptor. The corresponding server accompanies this as example3 in the distribution. A simple (useful) example of a "graphline", looks like this: Graphline( CHOOSER = Chooser(items = files), IMAGE = Image(size=(800,600), position=(8,48)), NEXT = Button(caption="Next", msg="NEXT", position=(72,8)), PREVIOUS = Button(caption="Previous", msg="PREV",position=(8,8)), FIRST = Button(caption="First", msg="FIRST",position=(256,8)), LAST = Button(caption="Last", msg="LAST",position=(320,8)), linkages = { ("NEXT","outbox") : ("CHOOSER","inbox"), ("PREVIOUS","outbox") : ("CHOOSER","inbox"), ("FIRST","outbox") : ("CHOOSER","inbox"), ("LAST","outbox") : ("CHOOSER","inbox"), ("CHOOSER","outbox") : ("IMAGE","inbox"), } ).run() This forms a primitive slideshow - in which a "chooser" gets a list of filenames, which depending on which button is pressed (next, previous, first, last) sends filename to an Image display component for display. (Again assuming a little bit of setup) I gave a talk about Kamaelia at Europython, using Kamaelia, so if you feel like grabbing a copy of the presentation which also includes everything you need to get started, please look here: * http://tinyurl.com/cnk9c That includes a more complex slideshow, though you need more than one mouse button for it to be useful. (It can show graph/network topologies dynamically, and can be more non-linear in terms of presentation) There's a tutorial on creating components here: * http://tinyurl.com/dp8n7 A longer detailed introduction document here: * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml And the main website/docs here: * http://kamaelia.sourceforge.net/ * http://kamaelia.sourceforge.net/Docs/ Depending on your focus Kamaelia contains tools for building TCP & Multicast servers and clients relatively easily and is designed to naturally encourage the use of concurrency easily and scalably. There's also a growing collection of components for more aural/visual work with a simple Pygame based "window manager" (really stretching things there, surface manager might be more appropriate) for components, and audio decode/playback. It isn't as mature as Twisted though, so that should affect your viewpoint! (Had some good chats at Europython though about how we can go about integration with twisted!) I suppose it should be possible to have pools of existing components for wiring into connections on demand though, which might be interesting. Best Regards, Michael. -- http://kamaelia.sourceforge.net/ From google at spiceaid.com Thu Jul 21 16:18:06 2005 From: google at spiceaid.com (Dr. Who) Date: 21 Jul 2005 13:18:06 -0700 Subject: Buffering problem using subprocess module In-Reply-To: References: <1121951665.430514.167440@g14g2000cwa.googlegroups.com> Message-ID: <1121977086.250086.115320@g47g2000cwa.googlegroups.com> Unfortunatley that doesn't help. Even when callee is started using the -u, I get the same behavior. From mcfletch at rogers.com Sat Jul 30 09:45:59 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 30 Jul 2005 09:45:59 -0400 Subject: Selection, picking with PyOpenGL? In-Reply-To: References: Message-ID: <42EB8497.9070203@rogers.com> Erik Max Francis wrote: >I was interesting in adding selection and hit testing to ZOE, and was >looking at the PyOpenGL wrappers' handling of selection and picking. I >see glSelectBuffer to specify the size of the buffer, and glRenderMode >properly returns the number of hits when put back into GL_RENDER mode, >but I don't see any way within PyOpenGL itself to access the select >buffer to actually process the hits. Is there any way to do this >without using OpenGLContext? (If not, does this make sense, given that >OpenGLContext is supposed to be an additional helper library for a >gentle introduction to OpenGL?) > > I think you're missing what's returned from the glRenderMode code (which is non-standard OpenGL, to avoid the need for Python code using and decoding structured pointers), from OpenGLContext: nameStack = list(glRenderMode(GL_RENDER)) that is, you get a stack of name records (i.e. your glSelectBuffer with (near,far,names) records) back from the glRenderMode call, *not* just a count of the records produced. In general, you shouldn't *need* OpenGLContext to do anything, as all of its OpenGL code is written directly in Python to PyOpenGL's API (that was its original purpose in life, to test those APIs). It is, however, intended to provide a source for sample code showing how to accomplish effects when using PyOpenGL, so from renderpass.py: event.setObjectPaths([ nodepath.NodePath(filter(None,[ self.selectable.get(name) for name in names ])) for (near,far,names) in nameStack ]) shows you how to deal with the glSelectBuffer result, namely that it's a near value, a far value, and a set of integer names (the name stack) for each record in the set. OpenGLContext is here creating a node-path of all selectable objects from the scenegraph root to the final selected object using the nameStack and a registered set of name:node values (self.selectable). It will use those to populate the event objects that show up in the OpenGLContext mouse-event-handling APIs. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From miki.tebeka at zoran.com Thu Jul 7 08:15:08 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 7 Jul 2005 15:15:08 +0300 Subject: VC++ linking problem In-Reply-To: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> References: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> Message-ID: <20050707121508.GB344@zoran.com> Hello Jochen, > I started embedding python into a 3D graphics App and I came > across this linking problem. > > > SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol > __imp__Py_InitModule4TraceRefs > SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol > __imp___Py_RefTotal > SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol > __imp___Py_RefTotal > > I am linking against python24.lib using VC++ 6.0. Before I got to this > point it couldn't find python24_d.lib. After searching around > for a while I came across a solution that included changing > python24_d.lib to python24.lib in one of the header files. I hope that > didn't have a negative effect. I would really appreciate > some help.... This is since Python header file is in debug mode and you link with the regular library. Just do: #undef _DEBUG /* Link with python24.lib and not python24_d.lib */ #include and you'll be fine. IMO python should try and link with python24.lib when compiling in debug mode since we want to debug our program and not Python. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From jnoller at gmail.com Thu Jul 14 10:42:38 2005 From: jnoller at gmail.com (Jesse Noller) Date: Thu, 14 Jul 2005 10:42:38 -0400 Subject: How can I import a py script by its absolute path name? In-Reply-To: <311b5ce105071404412d4bf318@mail.gmail.com> References: <311b5ce105071404412d4bf318@mail.gmail.com> Message-ID: <4222a849050714074264811bbd@mail.gmail.com> A question in a similiar vein: I have appended 2 different directories to my path (via sys.path.append) now - without knowing the names of the files in those directories, I want to force an import of the libraries ala: for f in os.listdir(os.path.abspath(libdir)): module_name = f.strip('.py') import module_name Obviously, this throws: ImportError: No module named module_name Is there some way to do this? thanks -jesse From pythonmailing at web.de Sun Jul 24 16:14:59 2005 From: pythonmailing at web.de (Marek Kubica) Date: Sun, 24 Jul 2005 22:14:59 +0200 Subject: How to run python script in background after i logout References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> <1122235144.361707.125310@f14g2000cwb.googlegroups.com> Message-ID: Hello! On 24 Jul 2005 12:59:04 -0700 Steve M wrote: > Another is that when I use putty.exe from Windows for > my ssh client, I can't get scroll-back buffers to work correctly with > screen. (Screen is really powerful with its own scrollback buffers and > screendumps and stuff but I don't have time to get into all that or > even learn it sometimes. I wish I were more a master of it since its > such a great program.) I use Crtl+A+Esc and go into the screen scrollback buffer, where I can navigate with the arrow keys. After typing Esc a second time, I get back to my program. greets, Marek From http Sun Jul 24 23:17:48 2005 From: http (Paul Rubin) Date: 24 Jul 2005 20:17:48 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <7x4qaja80z.fsf@ruckus.brouhaha.com> I've had miserable experiences trying to use WxPython or GTK under both RH9 and Fedora Core 3. There is some version skew between the installed versions of GTK and the WxWidgets on the distro site. I made some progress by installing an old version of GTK but there was still some problem. I decided it wasn't worth the hassle. Unless there's some serious importance to making your gui very slick, I think the only Python gui toolkit worth considering is Tkinter. It has drawbacks but it's the one that seems to work the most consistently with the least hassle. From mediocre_person at hotmail.com Tue Jul 5 20:12:37 2005 From: mediocre_person at hotmail.com (Terrance N. Phillip) Date: Tue, 05 Jul 2005 19:12:37 -0500 Subject: System Independent Wallpaper Changer Message-ID: <42cb220c$1_5@alt.athenanews.com> This is what I've got... the code should work on a typical Windows system, I think... ============================================ import os import random import time # I'm not sure what to expect for Win98, WinME, etc. I've # only tried it with xp... if os.name in ['nt', 'win98', 'me']: osWindows = True import ctypes import win32con import Image pth = 'c:/path/to/wallpapers' else: osWindows = False pth = '~/path/to/wallpapers' picfiles = os.listdir(pth) while True: jpg = random.choice(picfiles) if os_type = 'W': bmp = 'c:/wallpaper.bmp' Image.open(pth+jpg).save(bmp) cs = ctypes.c_buffer(bmp) ok = ctypes.windll.user32.SystemParametersInfoA(win32con.SPI_SETDESKWALLPAPER,0,cs,0) else: pass ' set kde wallpaper to jpg <------------- *** --- time.sleep(60) ================================================= I've done some searching, and can't seem to find a programatic way of getting *** that to happen. Thanks for any advice. Nick. From mwh at python.net Mon Jul 11 09:18:25 2005 From: mwh at python.net (Michael Hudson) Date: Mon, 11 Jul 2005 13:18:25 GMT Subject: PPC floating equality vs. byte compilation References: <1120888655.953163@yasure> <1f7befae05070908227704f21@mail.gmail.com> Message-ID: "Terry Reedy" writes: > "Tim Peters" wrote in message > news:1f7befae05070908227704f21 at mail.gmail.com... > > [Donn Cave] > >> I ran into a phenomenon that seemed odd to me, while testing a > >> build of Python 2.4.1 on BeOS 5.04, on PowerPC 603e. > >> > >> test_builtin.py, for example, fails a couple of tests with errors > >> claiming that apparently identical floating point values aren't equal. > >> But it only does that when imported, and only when the .pyc file > >> already exists. Not if I execute it directly (python test_builtin.py), > >> or if I delete the .pyc file before importing it and running > >> test_main(). > > This is a known problem with marshalling INFs and/or NANs. I hope you've also read all the bits and pieces where Tim says "whatever happens to INFs and NANs is a platform dependent crapshoot". We don't test platform dependent crapshoots in test_builtin (or at least, I hope not!). > *This* has supposedly been fixed for 2.5. Actually, it's likely that Donn's failure has been fixed for Python 2.5 as well, at least if Tim's guess is correct, because the C string->float routines aren't invovled in loading .pycs any more. > > It would be most helpful to open a bug report, with the output from > > failing tests. > > And assign to Tim. That's mean! :) > >In general, this can > > happen if the platform C string<->float routines are so poor that > > > > eval(repr(x)) != x > ... > > The ultimate cause is most likely in the platform C library's > > string<->float routines (sprintf, strtod, that kind of thing). > > It would also be helpful if you could do some tests in plain C (no Python) > testing, for instance, the same values that failed. Hardly anyone else can > ;-). If you confirm a problem with the C library, you can close the report > after opening, leaving it as a note for anyone else working with that > platform. I agree with this bit! Cheers, mwh -- 112. Computer Science is embarrassed by the computer. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From vedanta.barooah at gmail.com Fri Jul 8 02:26:28 2005 From: vedanta.barooah at gmail.com (Vedanta Barooah) Date: Fri, 8 Jul 2005 11:56:28 +0530 Subject: python nested class Message-ID: greetings.... in a python nested class is it possible to change the value of the parent class's variable without actually creating an instance of the parent class, consider this code: class mother: x=0 def __init__(self): self.x=1 def show(self): print self.x class child: def increase(self,num): # mother.increase=num o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() ..... is it possible somehow ??? thanks and regards, vedanta From andreas.lobinger at netsurf.de Wed Jul 13 09:43:37 2005 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Wed, 13 Jul 2005 15:43:37 +0200 Subject: Frankenstring In-Reply-To: References: Message-ID: Aloha, Thomas Lotze wrote: > I think I need an iterator over a string of characters pulling them out > one by one, like a usual iterator over a str does. At the same time the > thing should allow seeking and telling like a file-like object: >>>>f = frankenstring("0123456789") >>>>for c in f: > ... print c > ... if c == "2": > ... break > ... > 0 > 1 > 2 >>>>f.tell() > 3L >>>>f.seek(7) >>>>for c in f: > ... print c > ... > 7 > 8 > 9 > I can think of more than one clumsy way to implement the desired > behaviour in Python; I'd rather like to know whether there's an > implementation somewhere that does it fast. (Yes, it's me and speed > considerations again; this is for a tokenizer at the core of a library, > and I'd really like it to be fast.) You can already think my answer, because i'm doing this at the core of a similar library, but to give others the chance to discuss. >>> f = "0123456789" >>> p = 0 >>> t2 = f.find('2')+1 >>> for c in f[p:t2]: ... print c ... 0 1 2 >>> p = 7 >>> for c in f[p:]: ... print c ... 7 8 9 A string, and a pointer on that string. If you give up the boundary condition to tell backwards, you can start to eat up the string via f = f[p:]. There was a performance difference with that, in fact it was faster ~4% on a python2.2. I dont't expect any iterator solution to be faster than that. Wishing a happy day LOBI From seberino at spawar.navy.mil Sun Jul 31 15:01:36 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 31 Jul 2005 12:01:36 -0700 Subject: How override ALL function calls? (Is there a "function call function"?) Message-ID: <1122833096.778839.209730@g14g2000cwa.googlegroups.com> I'm trying run a homegrown profiler on some Python code. Rather than apply profiler wrapper to ALL functions by hand.... Is there a low level Python function I can override to modify how ALL functions are called? Chris From alan.green at gmail.com Tue Jul 12 16:54:33 2005 From: alan.green at gmail.com (Alan Green) Date: 12 Jul 2005 13:54:33 -0700 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads'C1, C2 and C3' In-Reply-To: References: Message-ID: <1121201673.700232.249330@g49g2000cwa.googlegroups.com> Ric Da Force wrote: > Hi guys, > > Thank you all for your input! It was good to see so much convergence in the > approach! Just for divergence, you can also do this with regular expressions: >>> import re >>> re.sub("(.*),(.*)", r"\1 and\2", "C1, C2, C3") 'C1, C2 and C3' Alan. From jgrahn-nntq at algonet.se Mon Jul 4 11:56:13 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 4 Jul 2005 15:56:13 GMT Subject: noob question References: <42BE37C0.3000306@maudit.net> Message-ID: On Sun, 26 Jun 2005 03:36:58 -0400, Chinook wrote: ... > Here is something I copied from somewhere (someone else might know the > source): > > Summary of Naming Conventions ... > > Hope it does not come out too jumbled, It did, but it seemed so useful that I repost it with minor changes and proper formatting: Summary of Naming Conventions Type Convention Example ----------------------------------------------------------------------------- function action_with_underscores find_all variable noun_with_underscores curr_index constant NOUN_ALL_CAPS ALLOWED_RNA_PAIRS class MixedCaseNoun RnaSequence public property MixedCaseNoun IsPaired private property _noun_with_leading_underscore _is_updated public method mixedCaseExceptFirstWordVerb stripDegenerate private method _verb_with_leading_underscore _check_if_paired really private data __two_leading_underscores __delegator_object_ref parameters matching property SameAsProperty __init__(data, Alphabet=None) factory function MixedCase InverseDict module lowercase_with_underscores unit_test ----------------------------------------------------------------------------- Note that calling 'IsPaired' and '_is_updated' a noun is clearly wrong. There are probably other problems with it, too. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From peter at somewhere.com Mon Jul 25 10:56:54 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 25 Jul 2005 16:56:54 +0200 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) In-Reply-To: References: Message-ID: Jeff Epler schrieb: > I honestly don't know why anyone would spend money for a development > environment, no matter how fancy. I don't know why anyone would develop > software in a language that doesn't have at least one open > implementation. FreePascal is OSS. I recently developed a mixed Delphi/FreePascal application. FreePascal doesn't have a GUI Builder like Delphi but is very complete and mature. > It's a great way to get screwed when Borland goes under or decides > they only want to sell a new, incompatible product. What do you do with > your existing product when that happens? Re-train on a new platform, > and re-write from scratch? Port it to FreePascal :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From newstonne at web.de Wed Jul 13 07:31:31 2005 From: newstonne at web.de (Roland Heiber) Date: Wed, 13 Jul 2005 13:31:31 +0200 Subject: Frankenstring In-Reply-To: References: Message-ID: Roland Heiber wrote: > class MmapWithSeekAndTell(object): > def __init__(self, m, size): .. where m is a mmap-object and size the filesize ... sorry. From jgrahn-nntq at algonet.se Fri Jul 8 04:39:36 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 8 Jul 2005 08:39:36 GMT Subject: mail sending using telnet in python References: Message-ID: On Fri, 8 Jul 2005 07:49:25 +0100 (BST), praba kar wrote: > Dear All, > Normally we can send mail using > telnet in linux. In the following way > [~user]telnet Ipaddress 25 > mail from: raj at rajkumar.com > 250 o.k(response of from commandline) ... That is sometimes a very useful trick, but it doesn't always work. SMTP requires CR-LF line endings, but your example only generates LF. Most mail servers accept that, but they are not required to, and some don't (qmail?). > Is it possible to run same thing same manner > in python? If possible kindly help me with > specimen code. Actually I gone through > telnetlib module documentation but I cann't > get solution for it. When you use the telnet command to do it, you're simply abusing telnet to get a command-line interface to a TCP socket -- it's really only intended to talk to a telnet server. . If the 'netcat' utility was more widespread, everyone would have used it instead. When you use Python, it doesn't make sense to go through telnetlib. Use module socket instead. Or, simply use module smtplib, which also comes with example code (in Python 2.3, at least). Have fun, Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From lambacck at gmail.com Tue Jul 5 22:26:59 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Tue, 5 Jul 2005 22:26:59 -0400 Subject: System Independent Wallpaper Changer In-Reply-To: <42cb220c$1_5@alt.athenanews.com> References: <42cb220c$1_5@alt.athenanews.com> Message-ID: you probably want if sys.platform == 'win32': instead of if os.name in ['nt', 'win98', 'me']: -Chris On 7/5/05, Terrance N. Phillip wrote: > This is what I've got... the code should work on a typical Windows > system, I think... > ============================================ > import os > import random > import time > > # I'm not sure what to expect for Win98, WinME, etc. I've > # only tried it with xp... > if os.name in ['nt', 'win98', 'me']: > osWindows = True > import ctypes > import win32con > import Image > pth = 'c:/path/to/wallpapers' > else: > osWindows = False > pth = '~/path/to/wallpapers' > > picfiles = os.listdir(pth) > > while True: > jpg = random.choice(picfiles) > if os_type = 'W': > bmp = 'c:/wallpaper.bmp' > Image.open(pth+jpg).save(bmp) > cs = ctypes.c_buffer(bmp) > ok = > ctypes.windll.user32.SystemParametersInfoA(win32con.SPI_SETDESKWALLPAPER,0,cs,0) > else: > pass > ' set kde wallpaper to jpg <------------- *** --- > time.sleep(60) > ================================================= > > I've done some searching, and can't seem to find a programatic way of > getting *** that to happen. > > Thanks for any advice. > > Nick. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From ggg at zzz.it Fri Jul 22 09:11:36 2005 From: ggg at zzz.it (deelan) Date: Fri, 22 Jul 2005 15:11:36 +0200 Subject: tuple to string? In-Reply-To: References: Message-ID: <0t77r2-163.ln1@news.interplanet.it> Francois De Serres wrote: > hiho, > > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to > the string 'spam'? one way is to use a list expression: >>> ''.join([chr(c) for c in (0x73, 0x70, 0x61, 0x6D)]) 'spam' another is to use map: >>> ''.join(map(chr, (0x73, 0x70, 0x61, 0x6D))) 'spam' HTH, deelan. -- deelan, #1 fan of adriana lima! From dvanvliet at 3dna.net Mon Jul 4 12:58:58 2005 From: dvanvliet at 3dna.net (Derek van Vliet) Date: 4 Jul 2005 09:58:58 -0700 Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Message-ID: <1120496338.571135.129060@g49g2000cwa.googlegroups.com> Up to now, I've had all my python scripts defined in XML elements, which were compiled when my program started up using Py_CompileString. This has worked great, but I'm finding that most of the time my app uses to start up is spent in that Py_CompileString, because of the large number of scripts that I use. Unfortunately, storing these scripts as .pyc files on disk is not an option for me. From exuberant at gmail.com Wed Jul 20 20:55:56 2005 From: exuberant at gmail.com (Austin) Date: 20 Jul 2005 17:55:56 -0700 Subject: Newbie question about lists In-Reply-To: References: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> Message-ID: <1121907356.835564.164200@g14g2000cwa.googlegroups.com> Well, that answers that. Thank you! From winder at interchange.ubc.ca Sat Jul 16 00:29:18 2005 From: winder at interchange.ubc.ca (WGW) Date: Fri, 15 Jul 2005 21:29:18 -0700 Subject: HTML expect in python Message-ID: I would like to automate some simple browser navigating using python. Ideally, I would like a package like pyexpect, but that can handle a browser in much the same way as pyexpect handles a terminal (tall order!). In short, I want a macro language for a browser (I know about the commercial packages such as Easy Bee and Internet macros, but I want more programmability and less cost!) ClientForms goes in the right direction. Can Grail be scripted (easily)? What is the best way to run a browser with python? Python would have to be able to fill in forms, send them off, click links, and so on. I don't really care which browser it is. Apparently, commandline python scripts can control IE. Not sure where to find examples.... Any suggestions? (I found the following remark: A different flavor of client-side Python scripting is that Mark Hammond's [ref] hard work has made possible. Internet Explorer (and WSH [give ref]) support(s) ActiveScripting [ref] languages, including Python. Thus, as Gilles Lenfant enumerated in private correspondence: * Command-line Python scripts control IE (but equally well through COM [ref]); * Client-side scripts interpret Python embedded in HTML as well as they do JavaScript [ref]; * "you can write 'hta' applications with full-featured Python (use of IE5 for GUI)" ) From sjmachin at lexicon.net Mon Jul 25 20:44:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 26 Jul 2005 10:44:56 +1000 Subject: Time formatting and date suffixes In-Reply-To: References: Message-ID: <42E58788.7010901@lexicon.net> Jeffrey E. Forcier wrote: > This seems like a dead simple question, as it's so rudimentary I can't > believe it hasn't been addressed before. I'm using the time.strftime() > function (actually the mxDateTime implementation, but they're > compatible so it shouldn't matter) to spit out fairly basic date > formats, to wit: > > January 25th, 2005 > > The various and sundry date objects in both mxDateTime and Python > proper's time/datetime don't seem to have anything anywhere dealing > with the 'th' suffix on the date. So in other words, I can use > strftime() to get 'January 25, 2005' but don't see anything dealing > with outputting the suffixes like 'th', 'nd' and the like. Googling > around and searching this list's archives aren't turning anything up, > either. > > Am I missing something obvious, or is it just really, really frowned > upon to use such a locale-specific function as English date suffixes? > I think the lack of facility is probably due to there being not much call for that sort of thing -- people doesn't usually go for the "third day after Michaelmas in the year of our Lord two thousand and five, at ten o'clock in the forenoon" style these days. If you don't use text, but stick with the recognisable unambiguous ISO standard format (2005-01-25), you don't have to worry about locales. However I guess you have to keep the PHB happy; you can write your own routine in a few lines. Hint: if 4 <= day <= 20 or 24 <= day <= 30: suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] HTH, John From steve at REMOVETHIScyber.com.au Thu Jul 21 10:30:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 22 Jul 2005 00:30:04 +1000 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: On Wed, 20 Jul 2005 16:30:10 -0400, Bill Mill wrote: > On 7/20/05, Simon Brunning wrote: >> On 7/20/05, Mage wrote: >> > Or is there better way? >> > >> > for (i, url) in [(i,links[i]) for i in range(len(links))]: >> >> for i, url in enumerate(links): >> > > +2 for creating seeing a need and crafting a reasonable solution, but > -1 for not reading the section on builtins to see if it existed > already. To see if *what* existed already? It is well and good to say RTFM, but there are 697 subsections to the Python Library reference, and if you don't know what you are looking for, and beginners rarely are, it isn't obvious which is the right section to read. And the Library Reference isn't even "the" manual: there is also the global module reference and language reference. If you already know what you are looking for, reading the manual is great advice. Browsing the manual looking for interesting tidbits can even be fun for a certain mindset. But if you don't know enough to know what to look for, where in the 2000-odd sections of the Python references will you find it? > (As for its pythonicity, I would have recommended isolating it into a > function and making it a generator: It is easy to take this to extremes. It isn't necessary to isolate everything into its own object, or class, or module. Too much encapsulation is just as bad as too little. > def my_enumerate(enumerable): > i = 0 > for elt in enumerable: > yield (i, elt) > i += 1 > > for i, url in my_enumerate(links): > > but it's not too bad as it is. Also, my function is completely > untested - it's close to right though.) What is the advantage of your function my_enumerate over the Python built-in enumerate? -- Steven. From steve at REMOVETHIScyber.com.au Tue Jul 12 05:40:48 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 19:40:48 +1000 Subject: Should I use "if" or "try" (as a matter of speed)? References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> <11d0e158o1g8554@news.supernews.com> <18fearebf2js6$.9oemdgamm06p.dlg@40tude.net> <871x64ifl0.fsf@titan.staselog.com> Message-ID: On Tue, 12 Jul 2005 11:38:51 +0300, Edvard Majakari wrote: > Just a minor note: regarding quote > > "first make it work, then make it right, then make it fast" > > Shouldn't one avoid doing it the wrong way from the very beginning? If you > make it "just work" the first time, you'll probably use the old code later on > because "functionality is already there" and temptatation to build on probably > relatively bad architecture can be too strong. > > How about > > First make it work (but avoid ad-hoc designs), then make it right, then make > it fast Optimizing sometimes means refactoring your code. Sometimes it even means throwing it away and starting again. However, your point to bring us back to a discussion held on this newsgroup not long ago, about whether or not it was good for computer science students to learn how to program in low-level languages like C so as to avoid silly mistakes like this: result = "" for s in really_big_list_of_strings: result = result + s return result instead of just "".join(really_big_list_of_strings). The first method is slow, but you might not know that unless you have some understanding of the implementation details of string concatenation. My opinion is, no, you don't need to be a C programmer, or an assembly programmer, or a hardware level physicist who understands NAND gates, but it is very useful to have some understanding of what is going on at the low-level implementation. The way I see it, programmers need to be somewhat aware of the eventual optimization stage in their program, so as to avoid poor design choices from the start. But you can't always recognise poor design up front, so even more important is careful encapsulation and design, so you can make significant implementation changes without needing to throw away your work. (Well, that's the theory.) -- Steven. From eric_brunel at despammed.com Tue Jul 19 02:50:39 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 19 Jul 2005 08:50:39 +0200 Subject: main window in tkinter app References: Message-ID: On Mon, 18 Jul 2005 16:57:51 GMT, William Gill wrote: > A short while ago someone posted that(unlike the examples) you should > use Tk as the base for your main window in tkinter apps, not Frame. Thus : > > class MyMain(Frame): > def __init__(self, master): > self.root = master > self.master=master > self.createWidgets() > def createWidgets(): > ... > root = Tk() > app = MyMain(root) > app.master.title("Object Editor") > root.mainloop() > > would become: > > class MyMain(Tk): > ... > ... > app = MyMain() > app.title("My App") > app.mainloop() > > When I try converting to this approach I run into a problem with the > __init__() method. It appears to go into an infinite loop in > tkinter.__getattr__(). [...] I never ran into this problem. Can you please post a short script showing this behavior? Without knowing what you exactly do in your __init__ and createWidgets method, it's quite hard to figure out what happens... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From rrr at ronadam.com Wed Jul 6 15:26:38 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 19:26:38 GMT Subject: Avoiding NameError by defaulting to None In-Reply-To: <42cc1177$1@nntp0.pdx.net> References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <42cc1177$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Ron Adam wrote: > >> Dan Sommers wrote: >> >>> Lots more hard-to-find errors from code like this: >>> filehandle = open( 'somefile' ) >>> do_something_with_an_open_file( file_handle ) >>> filehandle.close( ) >> >> >> If do_something_with_an_open_file() is not defined. Then you will get: >> TypeError: 'NoneType' object is not callable >> >> >> If "file_handle" (vs "filehandle") is None. Then you will still get >> an error as soon as you tried to use the invalid file handle. > > Ah, but where you use it can now far from the error in the source. The > None could get packed up in a tuple, stored in a dictionary, all manner > of strange things before discovering it was an unavailable value. I > would love the time back that I spent chasing bugs when Smalltalk told > me (I forget the exact phrasing) "nil does not respond to message abc." > My first reaction was always, "of course it doesn't, this message is > useless." You really want the error to happen as close to the problem > as possible. > > --Scott David Daniels > Scott.Daniels at Acm.Org Yep, I concede. The problem is if undefined names return None, and None deletes a name, then assigning a undefined name to an existing name, will delete it silently. Definitely Not good! So it should give an error as it currently does if an undefined name is used on the right side of an =. It could still work otherwise to unbind names, and (undefined_name == None) could still be a valid way to check if a name is defined without using a try-except. But it would definitely be a Python 3000 change as all the functions that return None would then cause errors. Cheers, Ron From ric at next-level.com.au Tue Jul 12 02:43:55 2005 From: ric at next-level.com.au (Ric Da Force) Date: Tue, 12 Jul 2005 14:43:55 +0800 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' Message-ID: Hi, I have a string such as 'C1, C2, C3'. Without assuming that each bit of text is of fixed size, what is the easiest way to change this list so that it reads: 'C1, C2 and C3' regardless of the length of the string. Regards and sorry for the newbie question, Ric From brian at sweetapp.com Fri Jul 15 07:41:22 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 15 Jul 2005 13:41:22 +0200 Subject: Python Programming Contest In-Reply-To: <1121421762.826887.114880@g43g2000cwa.googlegroups.com> References: <1121421762.826887.114880@g43g2000cwa.googlegroups.com> Message-ID: <42D7A0E2.7090100@sweetapp.com> James wrote: > I am not sure if it is a good idea to use a LiveCD for OS when you are > testing for speed. CD access speeds fluctuate and may even impact > performance even if you start measuring after the module loading is > complete. It didn't seem to matter in my testing. Module loading is done before the test is run. Also, it is easiest to protect my system against malicious code if it is being run on an OS without a writeable filesystem. Cheers, Brian From ramen at lackingtalent.com Fri Jul 1 20:34:43 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 01 Jul 2005 17:34:43 -0700 Subject: Better console for Windows? In-Reply-To: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: Brett Hoerner wrote: > Is there a different shell I can use (other than cmd.com) to run Python > in, where I can full-screen the window (if I pleased), etc? As it is, > things that would run far off the right have to be word wrapped after > very few characters. I have a pretty exotic setup but I like it a lot. I use Konsole with Cygwin and the KDE release for Cygwin (that's the only part of KDE that I use). I love Konsole's tabbed virtual terminals. You can also get tabbed virtual terminals with mrxvt, which isn't quite so heavyweight, but Konsole is the most user-friendly terminal I've ever used. And on top of that, I run emacs, pull up a shell with M-x shell, and then I can run any program I want, including Python and Jython, and freely cut and paste between the command line and my editor window. As far as the beeps go, I go for any "silent bell" option I can find, and pick the "No sounds" theme in the "Sounds and Audio Devices" control panel. Dave From spam.csubich+block at block.subich.spam.com Sun Jul 3 14:09:32 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 14:09:32 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <42c7f923$1@nntp0.pdx.net> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <42c7f923$1@nntp0.pdx.net> Message-ID: <_QVxe.40372$du.13893@bignews1.bellsouth.net> Scott David Daniels wrote: > egbert wrote: >> How do you replace >> map(f1,sequence1, sequence2) >> especially if the sequences are of unequal length ? >> >> I didn't see it mentioned yet as a candidate for limbo, >> but the same question goes for: >> zip(sequence1,sequence2) > > OK, you guys are picking on what reduce "cannot" do. > The first is [f1(*args) for args in itertools.izip(iter1, iter2)] > How to _you_ use map to avoid making all the intermediate structures? Not quite -- zip an izip terminate at the shortest sequence, map extends the shortest with Nones. This is resolvable by addition of an lzip (and ilzip) function in Python 2.5 or something. And egbert's Chicken Littling with the suggestion that 'zip' will be removed. From andreas at kostyrka.org Fri Jul 1 12:33:08 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 01 Jul 2005 18:33:08 +0200 Subject: No subject In-Reply-To: References: Message-ID: <1120235588.6823.36.camel@andi-lap> import os as realos Names are nothing magic in Python, and quite easily manipulated: import os os.write(1, "Hello World!") class os: pass o = os() import os os.write(1, "\n") So basically this kind of name clashes usually do not happen in Python. Or another usage: os = SomeObject() def function_that_needs_real_os(): import os print os.getuid() Am Freitag, den 01.07.2005, 15:38 +0200 schrieb Adriaan Renting: > Adriaan Renting | Email: renting at astron.nl > ASTRON | Phone: +31 521 595 217 > P.O. Box 2 | GSM: +31 6 24 25 17 28 > NL-7990 AA Dwingeloo | FAX: +31 521 597 332 > The Netherlands | Web: http://www.astron.nl/~renting/ > >>> Tom Anderson 07/01/05 2:50 PM >>> > >On Fri, 1 Jul 2005, Adriaan Renting wrote: > >> I'm not a very experienced Python programmer yet, so I might be > >> mistaken, but there are a few things that would make me prefer C++ > over > >> Python for large (over 500.000 LOC) projects. > > > >Hmm. I don't know C++, but here goes ... > > > >> - namespaces > > > >Aren't namespaces basically the same as packages/modules in python? > > > Not in the way C++ uses them. In Python if would be something like this: > --------------------------- > import os > using namespace casa > class os: > def open(self, file): > pass > a = os.open('something') > b = std::os.open('something') > using namespace std > c = casa::os.open('something') > d = os.open('something') > --------------------------- > This is a realy stupid example. It's essentially an extra hierarchy > layer to avoid naming clashes. I don't know of a way to do this in > Python, how would you do this? > > >> - templates > > > >These would be meaningless in python - they're part of typefulness, > which ... > > > >> - strong type checking > > > > > >Not that this is necessarily a good thing. I have to say that my Java > >roots do lead me to think that strong typing is a plus for big > projects, > >since it's a way of defining and enforcing interfaces between bits of > code > >written by different people (or by one person at different times!). > >Optional static typing in python would be nice for this. > > > Exactly what I my point is, see also my other post on this (the LOC > post) > > >> - data hiding > > > >Surely you can hide data in python? > > > Again, how? Is there a way to force that an external user of my lib can > not use my internal data/methods/classes, unless he uses odd compiler > hacks? > > >> - more available libraries and more advanced developement tools. > > > >True. The more advanced development tools are offset to a large degree > by > >the advanced crappiness of C++ as a language, though; i'd be surprised > if > >a C++ programmer borged up with all the latest tools was actually more > >productive than a python programmer with a syntax-colouring, > >auto-indenting text editor. It'd be very interesting to get some real > >numbers on that. > > > I think my point is: I would be, for large projects. Just comparing my > Borland C++Builder experience with my Eric3+QtDesigner experience. This > is not only because of differences between C++ and Python though, a good > IDE alone can make 50% difference but that's another subject. > For small simple projects where I am familiar with the libs I need, I > think I'd prefer Python. > > >>> Ultimately, manageability of a project is far and away more about > the > >>> people involved and the techniques used than it is about any single > >>> technology involved. > >> > >> Agreed. > > > >+1 getting to the crux of it. > > > Thank you > > >tom > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From gregpinero at gmail.com Tue Jul 26 11:02:06 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 26 Jul 2005 11:02:06 -0400 Subject: how to build email message with attachment? In-Reply-To: <9afea2ac050726014078d5cdd7@mail.gmail.com> References: <42E5EEB7.400@REMOVEMEcyber.com.au> <20050726082004.87922.qmail@web8401.mail.in.yahoo.com> <9afea2ac050726014078d5cdd7@mail.gmail.com> Message-ID: <312cfe2b05072608026f8c0ceb@mail.gmail.com> I wrote a module to do this a while back. I put the script on my website just now. Let me know if it helps. http://www.blendedtechnologies.com/how-to-send-emails-with-python/19 -- Gregory Pi?ero CEO and Founder Blended Technologies (www.blendedtechnologies.com) From jstier at cs.uvic.ca Sun Jul 10 19:27:59 2005 From: jstier at cs.uvic.ca (J) Date: 10 Jul 2005 16:27:59 -0700 Subject: inheritance In-Reply-To: <1121031208.829250.82160@g44g2000cwa.googlegroups.com> References: <1121031208.829250.82160@g44g2000cwa.googlegroups.com> Message-ID: <1121038079.306961.322370@g44g2000cwa.googlegroups.com> just to follow up. I managed to get it working by having a closer look at the xxmodules. However, the example does the following typedef struct { PyStructBaseClass mBase; int mValue; } PyStructDerivedClass; Does anything speak agains doing this ? typedef struct : public PyStructBaseClass { int mValue; } PyStructDerivedClass; It seems to work for me. The advantage is that access to the members in that structure is easier. The .mBase is not needed .... Cheers Jochen From cam.ac.uk at mh391.invalid Fri Jul 22 16:07:05 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 21:07:05 +0100 Subject: PEP on path module for standard library In-Reply-To: References: <3kacleFslj6sU1@individual.net> Message-ID: Peter Hansen wrote: >> Most prominent change is that it doesn't inherit from str/unicode >> anymore. >> I found this distinction important, because as a str subclass the Path >> object >> has many methods that don't make sense for it. > > On this topic, has anyone ask the original author (Jason Orendorff) > whether he has some background on this decision that might benefit the > discussion? My impression is that he doesn't have a lot of spare cycles for this. He didn't have anything to add to the python-dev discussion when I informed him of it. I'd love to hear what he had to say about the design. -- Michael Hoffman From cliff at develix.com Sun Jul 31 02:12:37 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 23:12:37 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <200507302029.34011.jstroud@mbi.ucla.edu> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> Message-ID: <1122790357.19618.45.camel@localhost.localdomain> On Sat, 2005-07-30 at 20:29 -0700, James Stroud wrote: > I am going to go ahead and throw out Dabo with all of the others that claim > quick development of an application. You try them and then you get bugs, > bugs, bugs. Or they don't compile without 16000 dependencies. Forget it. My > advice is to choose something, one thing, that is REAL standard, and in the > standard library (e.g. Tkinter). And go for it. Learn it inside and out--it > will always be there for you. It is the green, green grass of home, not that > greener grass on the other side of the hill. Don't listen to the guys that > says this one is crap or that one isn't. Dropping one and learning another is > just pain. I think this is a developer trick, to keep you at war with > yourself. The more you have internal conflict the more you will be looking > for an App framework to solve your inner problems, and that keeps these guys > in business--the business of wrecking souls. Then why are you using Python at all? Shouldn't you be in the "safe home" of Java or Visual Basic, where "standards" are all you have? -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From rkern at ucsd.edu Sat Jul 2 10:36:53 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 02 Jul 2005 07:36:53 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <11ccpg5o833qp42@news.supernews.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> Message-ID: John Roth wrote: > "Robert Kern" wrote in message > news:mailman.1226.1120271406.10512.python-list at python.org... > >>map and filter are being removed *because of* list comprehensions. Did you >>even read Guido's articles about this issue? Your understanding of why >>these changes are planned is incorrect; consequently your projection based >>on that understanding is not on firm footing. > > May I most respectfully point out that you've got it backwards. > Part of the justification for list comprehensions was that they could > be used to replace map and filter. That is essentially what I said. List comprehensions were made to replace map and filter. Now that they are here, Guido wants to remove map and filter to keep OOWTDI. My response was incomplete, not incorrect. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pink at odahoda.de Fri Jul 22 15:46:33 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Fri, 22 Jul 2005 21:46:33 +0200 Subject: Getting TypeError in Changing file permissions References: Message-ID: Pranav Bagora wrote: > Hello , > i am trying to change mode of files using the > os.chmod()function. But i am getting an error > > " os.chmod(outfile,0700) > TypeError: coercing to Unicode: need string or buffer, > file found" Looks as if your are using a file object (that you got from an open() call) as the first parameter. What you need is a string with the path to the file. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From cam.ac.uk at mh391.invalid Sun Jul 24 09:14:49 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jul 2005 14:14:49 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3khgn6Fu8nm8U1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <3khgn6Fu8nm8U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > * __iter__() iterates over the parts(). > * the following methods raise NotImplemented: > capitalize, expandtabs, join, splitlines, title, zfill Why? They *are* implemented. I do not understand this desire to wantonly break basestring compatiblity for the sake of breaking compatibility. Once you break compatibility with basestring you can no longer use a path anywhere that you could have used a str or unicode before. With compatibility broken, the only possible supported way of passing paths to third-party functions will be to cast the path with path.__bases__[0](mypath) before passing it anywhere else. You can't even use str() because you don't know what the base class of the path is. What a pain. From the original path.py documentation: """ os.path.join doesn't map to path.join(), because there's a string method with that name. Instead it's path.joinpath(). This is a nuisance, but changing the semantics of base class methods is worse. (I know, I tried it.) The same goes for split(). """ It ain't broke. Please stop breaking it. -- Michael Hoffman From noreply at gcgroup.net Tue Jul 19 09:42:59 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 19 Jul 2005 13:42:59 GMT Subject: main window in tkinter app In-Reply-To: References: Message-ID: > I never ran into this problem. ... O.K. That, means I probably have something else wrong. I will need to start with a 'clean slate' instead of trying to modify existing code. It's getting to convoluted to follow anyway after all the cobbling I've done. If I get a repeat of the original problem I will post the code and the exact error message, but at least now I know It SHOULD work. Thanks Bill, Eric Brunel wrote: > On Mon, 18 Jul 2005 16:57:51 GMT, William Gill wrote: > >> A short while ago someone posted that(unlike the examples) you should >> use Tk as the base for your main window in tkinter apps, not Frame. >> Thus : >> >> class MyMain(Frame): >> def __init__(self, master): >> self.root = master >> self.master=master >> self.createWidgets() >> def createWidgets(): >> ... >> root = Tk() >> app = MyMain(root) >> app.master.title("Object Editor") >> root.mainloop() >> >> would become: >> >> class MyMain(Tk): >> ... >> ... >> app = MyMain() >> app.title("My App") >> app.mainloop() >> >> When I try converting to this approach I run into a problem with the >> __init__() method. It appears to go into an infinite loop in >> tkinter.__getattr__(). > > [...] > > I never ran into this problem. Can you please post a short script > showing this behavior? Without knowing what you exactly do in your > __init__ and createWidgets method, it's quite hard to figure out what > happens... From sjmachin at lexicon.net Sat Jul 23 09:31:04 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 23:31:04 +1000 Subject: tuple to string? In-Reply-To: <3ke61oFtnkg9U1@individual.net> References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> Message-ID: <42e24696$1@news.eftel.com> Reinhold Birkenfeld wrote: > John Machin wrote: > >>Reinhold Birkenfeld wrote: >> >>>Berthold H?llmann wrote: >>> >>> >>>>Francois De Serres writes: >>>> >>>> >>>> >>>>>hiho, >>>>> >>>>>what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) >>>>>to the string 'spam'? >>>> >>>>.>>> t = (0x73, 0x70, 0x61, 0x6D) >>>>.>>> ''.join('%c' % c for c in t) >>>>'spam' >>> >>> >>>Or: >>> >>>t = (0x73, 0x70, 0x61, 0x6D) >>>('%c' * len(t)) % t >> >>You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-) > > > Ah, ok. Didn't want to lookup the precedence rules... Look up the precedence rules? Are you aware of any language where * / and % _don't_ have the same precedence?? From bokr at oz.net Sat Jul 16 16:48:09 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 16 Jul 2005 20:48:09 GMT Subject: Generating a list of None References: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> <42d82da3.279202121@news.oz.net> <1121506288.458576.317930@g14g2000cwa.googlegroups.com> Message-ID: <42d96f3f.361534459@news.oz.net> On 16 Jul 2005 02:31:28 -0700, "Raymond Hettinger" wrote: >[Bengt Richter] >> how about (untested) >> >> def get_options(opts): >> """Return True or False if an option is set or not""" >> return [1 for val in vars(opts).values() if val is not None] and True or False > >While we're tossing around hacks and coding atrocities, we should note >that: > > not not x > >outperforms: > > x and True or False > >neither of which is as clear as: > > bool(x) > Point. ;-) (I actually thought to do not not x and bool(x) also crossed my mind, so I'm not sure why I wound up with the above). BTW, I imagine this is probably faster (and closer to the OP's approach), at least for large option sets: (maybe needs comment like # not all None's ? ;-) >>> def get_options(opt): ... values = vars(opt).values() ... return values.count(None) != len(values) ... >>> opt = type('',(),{})() >>> get_options(opt) False >>> opt.a=None >>> get_options(opt) False >>> opt.b=None >>> get_options(opt) False >>> opt.c = 'option c' >>> get_options(opt) True >>> vars(opt) {'a': None, 'c': 'option c', 'b': None} Regards, Bengt Richter From gsakkis at rutgers.edu Sat Jul 16 18:35:39 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 16 Jul 2005 18:35:39 -0400 Subject: Python Programming Contest References: <42D780EF.6020809@sweetapp.com> Message-ID: <1121553441.befc03ca5fc05a72519216c06d36e335@teranews> "Terry Reedy" wrote: > "Tom Anderson" wrote: > > I can't immediately see any properties of this network that could be > > exploited, but that doesn't mean there aren't any. > > No it doesn't. The challenge is to find a property that saves more time, > across trials, that it takes to compute. There could have been one if the schedule was fixed across trials. However, if you look into the test script, this is not the case; a new schedule is randomly generated every time. So any heavy preprocessing on the schedule is rather unlikely to pay off. George From supercomputer at gmail.com Mon Jul 18 13:13:49 2005 From: supercomputer at gmail.com (supercomputer at gmail.com) Date: 18 Jul 2005 10:13:49 -0700 Subject: ssh popen stalling on password redirect output? In-Reply-To: <42DB8FCE.1040500@draigBrady.com> References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> <42DB8FCE.1040500@draigBrady.com> Message-ID: <1121706829.338095.262560@o13g2000cwo.googlegroups.com> Thanks for the help, this gives me a few options. I think the best way to do it is using the public/private key authentication. thanks From cliff at develix.com Sun Jul 31 15:36:05 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 12:36:05 -0700 Subject: python SMTP server In-Reply-To: References: <1122759885.881136.186360@g47g2000cwa.googlegroups.com> Message-ID: <1122838565.19618.112.camel@localhost.localdomain> On Sun, 2005-07-31 at 13:14 +0200, Benjamin Niemann wrote: > But you should be aware of the fact that (if you send mail from a dialup > machine without going through a relay server) your mails will quickly be > marked as spam - I hope you do not intend to send spam... Yah, Postfix on my servers uses several dnsbl's which automatically reject home users (unless they authenticate first). Even if this isn't the case for the majority of SMTP servers today I expect it won't be long before it is. As an aside, I will say that many SMTP servers that service home users (i.e. Comcast, et al) limit the amount of mail that you can send within a defined period. By using a local SMTP server to proxy, your app can queue up a large amount of mail in a much shorter period. It won't necessarily go out any faster, but at least your app won't be tied up waiting for the mail to be accepted. So there is perhaps one useful (beyond learning and fun) application for using a local SMTP server. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From gustavo at niemeyer.net Tue Jul 5 13:09:39 2005 From: gustavo at niemeyer.net (Gustavo Niemeyer) Date: Tue, 5 Jul 2005 14:09:39 -0300 Subject: f*cking re module In-Reply-To: <1120575861.296553.303750@z14g2000cwz.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <1120575861.296553.303750@z14g2000cwz.googlegroups.com> Message-ID: <20050705170939.GA15664@burma.localdomain> > To reply to the last part of the discussion and esspecially to Gustavo > Niemeyer, I really apriciate the way in which I had been answered. And > I won't have any questions about the re module that I had before I > post this threat. Great! As I said, that's a nice news group. > I was frustration and should, probebly, not post this frustration. But > it was never my purpous to ask something stupid or asking it arrogant. You can post frustration for sure. But saying "f*cking re module" and than showing that your problem is not understanding the very basics of regular expressions is not a nice way to ask for help. > The python re module is, in my opinion, a non beginner user friendly > module. And it's not meant for beginning python programmers. I don't > have any experience with perl or related script/programming languages > like python. (I prefer to do things in c) So the re module is > completely new for me. >>> re.match("

(.*)

", "

foobar

").group(1) 'foobar' That's very similar to your problem and looks quite clear and simple, but you must understand what regular expressions are about, of course. > If I upset someones clean mind posting a "stupid" and "arrogant" > question, I'm sorry and won't post my frustrasion on this usenet group > anymore. Not upset at all. You just asked it the wrong way, and I was impressed that even then there were lots of people to help you. That's not usual in most places. > But thank you for all your help about the re module, In my opinion you would benefit from looking at some documentation talking about regular expressions in general. After you understand them, the re module will look f*cking simple. ;-) -- Gustavo Niemeyer http://niemeyer.net From dial#####$$NOSPAM##$#$##tone at gmail.com Tue Jul 19 12:02:49 2005 From: dial#####$$NOSPAM##$#$##tone at gmail.com (Valentino Volonghi aka Dialtone) Date: Tue, 19 Jul 2005 18:02:49 +0200 Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> Message-ID: <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> istvan.albert at gmail.com wrote: > I thought it would make sense to write up some of my experiences with > python based web frameworks: > > http://www.personal.psu.edu/staff/i/u/iua1/python_reviews.html You've never used Nevow, have you? Comparing it to Cheetah or ZPT means that you never used it. Nevow is exactly what you define as a web framework, and it would be quite interesting to know why you didn't put it in that section. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.4 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From tzot at sil-tec.gr Sat Jul 2 17:09:32 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sun, 03 Jul 2005 00:09:32 +0300 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1120141667.753928.40750@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 30 Jun 2005 18:29:56 +0100, rumours say that Tom Anderson might have written: >On Thu, 30 Jun 2005, Benji York wrote: > >> python-needs-more-duct-tape'ly yours, > >You're in luck: Python 3000 will replace duck typing with duct taping. I would bet that somewhere in the "Ingliy-spiking werld" both terms sound exactly the same. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From cliff at develix.com Sun Jul 31 21:11:02 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 18:11:02 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7xek9e5ywq.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <7xd5ozv1ng.fsf@ruckus.brouhaha.com> <7xek9e5ywq.fsf@ruckus.brouhaha.com> Message-ID: <1122858662.19618.225.camel@localhost.localdomain> On Sun, 2005-07-31 at 16:38 -0700, Paul Rubin wrote: > Cliff Wells writes: > > The bottom line is this: some people like Tk, some wxPython. Each has > > advantages and disadvantages. But to claim that you *can only* do > > something in one or the other only demonstrates that you haven't really > > tried. > > I can put up a Tk gui in about 5 lines of code from a stock Python > distro without having to install anything additional. How do I do > that with wxPython? How can I embed a browser in Tk (I mean a real browser, like Mozilla, Safari, or even Exploder)? At all? On any platform? This has always been the tradeoff for Tk. wxPython has a much larger selection of sophisticated widgets than Tk does (I first tried wxPython because of its grid widget, which Tk didn't have at the time and the pure Tk version I wrote was sloooow. I doubt Tk still has anything that compares). I'm working on improving my user interface designs and I'm leaning toward the hybrid HTML + GUI systems as seen in many utilities (such as Norton AV, AdAware, etc). I don't see that approach as being even remotely possible in Tkinter. Tk is great for learning, easy to write small, basic interfaces, less great for deploying real world apps with sophisticated interfaces. I've often felt that Tk was the VB of GUI toolkits: terrific for knocking out simple stuff, but starts to bite you in the *** when you try to do the hard stuff. wxPython is the opposite: it has a steeper learning curve, but once you know it, you can do amazing things. For me, the long term benefits are far more important to me than how low the startup costs are. Besides, as mentioned earlier, you *do* need to install something additional: the python-tkinter package such as: http://www.python.org/ftp/python/2.4.1/rpms/fedora-3/python2.4-tkinter-2.4.1-1pydotorg.i386.rpm Although I'll also admit it seems that it can be easier (for many people) to mess up your wxPython install than your Tkinter install. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From nephish at xit.net Sun Jul 3 16:06:34 2005 From: nephish at xit.net (nephish at xit.net) Date: 3 Jul 2005 13:06:34 -0700 Subject: need to get an index for an item in a list In-Reply-To: References: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> Message-ID: <1120421194.242942.177050@g47g2000cwa.googlegroups.com> Hey, thanks, this has worked out for me. i am trying to do as much of this as possible in IDLE because it lets me know on the fly what is messed up. thanks for your help shawn <>< From ramen at lackingtalent.com Tue Jul 19 13:50:10 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 19 Jul 2005 10:50:10 -0700 Subject: Jython Released In-Reply-To: <6NWdna8jsbEov0DfRVn-vA@comcast.com> References: <6NWdna8jsbEov0DfRVn-vA@comcast.com> Message-ID: Ramza Brown wrote: > This is an update from Brian Zimmer of the Jython group, new release: Great news! > - new installer How do I use it? Thanks, Dave From t-meyer at ihug.co.nz Thu Jul 28 22:38:23 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 29 Jul 2005 14:38:23 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > def functions_which_modifies_some_file_in_place(path): > output = open(path+'.tmp', 'w') > ..... > > I dont want a seperator inserted between path and the new extension. Fair enough. Forget using '+' for join, then (which I was never that keen on - TIOWTDI), but I'm still -1 on using '/' for join. =Tony.Meyer From peter at engcorp.com Tue Jul 26 11:03:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Jul 2005 11:03:00 -0400 Subject: how to build email message with attachment? In-Reply-To: References: Message-ID: praba kar wrote: > Can any one let me know? How to build > email in python? with some some examples. Which documentation, tutorials, or mailing list archives have you already checked, and what information did they not provide which you need? (Translation: it looks like you didn't make the slightest attempt to find this information on your own, and I know the question has been asked many times before, so I really think you can find what you need with Google, but if not, please at least tell us where you've tried to look so we can then improve the resources available.) -Peter From spam.csubich+block at block.subich.spam.com Thu Jul 21 11:09:26 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 21 Jul 2005 11:09:26 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: <7xoe8woii0.fsf@ruckus.brouhaha.com> References: <7xoe8woii0.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Huh? It's pretty normal, the gui blocks while waiting for events > from the window system. I expect that Qt and Tk work the same way. Which is why I recommended Twisted for the networking; it integrates with the toolkit event loops so it automagically works: http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto15 I agree, though, that basic socket programming in the same thread as the gui's probably a bad idea. From hancock at anansispaceworks.com Tue Jul 5 11:21:57 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 10:21:57 -0500 Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: <200507051021.57901.hancock@anansispaceworks.com> On Monday 04 July 2005 12:41 am, Ron Adam wrote: > > Actually, I think this one is doing what I want now. It seems > > to be that it isn't robust against files with lots of mixed tabs > > and spaces. I also got "space_hi.vim" which highlights tabs > > and trailing spaces, which made it a lot easier to fix the > > problem. > > I edited my syntax coloring file to do the same thing. Not to mention > adding a few key words that were missing. :-) This script: http://www.vim.org/scripts/script.php?script_id=790 "python.vim" (but in ~/.vim/syntax) by Dmitry Vasiliev adds a few dozen Python-specific syntax keywords, I used these and edited my usual color scheme to give them more refined syntax coloring, which is nice. It is quite useful to have Unicode strings and Raw strings display differently, for example, since it's easy to forget which you're using (unless you're right next to the mark). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From opengeometry at yahoo.ca Tue Jul 26 10:49:30 2005 From: opengeometry at yahoo.ca (William Park) Date: Tue, 26 Jul 2005 10:49:30 -0400 Subject: how to build email message with attachment? References: Message-ID: <7e678$42e64d7a$d8fea0b4$3480@PRIMUS.CA> praba kar wrote: > Dear All, > > Can any one let me know? How to build > email in python? with some some examples. If all else fails, mutt -a ... -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From usenet at zabiello.com Mon Jul 18 09:40:36 2005 From: usenet at zabiello.com (JZ) Date: Mon, 18 Jul 2005 15:40:36 +0200 Subject: What is your favorite Python web framework? References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> Message-ID: <1i66cc9ul9ntd$.z8r2c0cri60e$.dlg@40tude.net> Dnia Mon, 18 Jul 2005 09:06:21 -0400, Peter Hansen napisa?(a): >> I think Django is more mature than Subway or CherryPy and can quickly >> become the black horse in area of pythonic frameworks. > > I'm not familiar with this expression. What do you mean by "black horse"? I meant "dark horse". Sorry for confusion. :) -- JZ From thorsten at thorstenkampe.de Sat Jul 9 16:31:05 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 9 Jul 2005 21:31:05 +0100 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> * Steve Juranich (2005-07-09 19:21 +0100) > I know that this topic has the potential for blowing up in my face, > but I can't help asking. I've been using Python since 1.5.1, so I'm > not what you'd call a "n00b". I dutifully evangelize on the goodness > of Python whenever I talk with fellow developers, but I always hit a > snag when it comes to discussing the finer points of the execution > model (specifically, exceptions). > > Without fail, when I start talking with some of the "old-timers" > (people who have written code in ADA or Fortran), I hear the same > arguments that using "if" is "better" than using "try". I think that > the argument goes something like, "When you set up a 'try' block, you > have to set up a lot of extra machinery than is necessary just > executing a simple conditional." > > I was wondering how true this holds for Python, where exceptions are > such an integral part of the execution model. It seems to me, that if > I'm executing a loop over a bunch of items, and I expect some > condition to hold for a majority of the cases, then a "try" block > would be in order, since I could eliminate a bunch of potentially > costly comparisons for each item. But in cases where I'm only trying > a single getattr (for example), using "if" might be a cheaper way to > go. > > What do I mean by "cheaper"? I'm basically talking about the number > of instructions that are necessary to set up and execute a try block > as opposed to an if block. "Catch errors rather than avoiding them to avoid cluttering your code with special cases. This idiom is called EAFP ('easier to ask forgiveness than permission'), as opposed to LBYL ('look before you leap')." http://jaynes.colorado.edu/PythonIdioms.html From seberino at spawar.navy.mil Tue Jul 5 18:49:45 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 5 Jul 2005 15:49:45 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <1120603785.494300.180940@g49g2000cwa.googlegroups.com> > Well, his Viaweb company was founded in about '95, right? So he probably just > used Lisp because Python wasn't as well known yet. ;-) David That is what I thought too. It makes sense but I wasn't sure. Still ain't. The problem is that questions like 'What lang is fastest to develop in?' are hard to answer definitively. Chris From thanos at sians.org Sun Jul 24 08:52:50 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 15:52:50 +0300 Subject: Getting a dictionary from an object In-Reply-To: <42e38a38$0$1453$626a14ce@news.free.fr> References: <42e38a38$0$1453$626a14ce@news.free.fr> Message-ID: <20050724125250.GA11448@zermelo.sians.org> On Sun, Jul 24, 2005 at 03:01:40PM +0200, Bruno Desthuilliers wrote: > I gave you a solution based on the Decorator pattern in another post, > but there is also the possibility to add a __getitem__ method directly > to the to-be-formatted object's class: > > def mygetitem(obj, name): > return getattr(obj, name) > > setattr(obj.__class__, '__getitem__', mygetitem) > obj['bar'] I used what you suggested earlier with the Wrapper, without subclassing dict anymore. Thanks! > > BTW, parts of this thread should remind us all that it's usually better > to clearly describe the *problem* before asking for comments on the > solution... > """I would like to have a quick way to create dicts from object, so that a call to foo['bar'] would return obj.bar.""" Actually this is the problem, (I never said anything about _assigning_ new keys in foo), and the line following it is my question ;) Thanks again! -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From detlev at die-offenbachs.de Sun Jul 3 04:11:16 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 03 Jul 2005 10:11:16 +0200 Subject: debugger? References: Message-ID: Qiangning Hong wrote: > I have read a lot of posts discussing python IDEs, but most of them > focus on the editor, GUI builder, project management, customizability, > etc.... Some talked about debugging capability, but only on an > available/unavailable level. > > I use vim to edit my code, wxGlade to build the GUI or hand-code it, > and I still prefer that. So, until now, I haven't tried many IDEs. > > However, while I use pdb or inserting "print" statement to debug my > apps, sometimes it is a pain. I think I need a good GUI debugger to > help me. The debugger should meet _most_ of the following > requirements: > > 1. can debug wxPython applications (and other GUI lib). > 2. an intuitive way to set/clear/enable/disable breakpoints. > 3. can set conditional breakpoints (i.e. break when some condition > satisfied). 4. variable watch list, namescope watching (local, global) > 5. evaluate expression, change variable values, etc within debugging. > 6. change the running routine, (i.e. go directly to a statement, skip > some statements, etc) > 7. clever way to express objects, not just a string returned by repr() > 8. perform profiling > 9. a clear interface. > 10. cross-platform. > 11. free, or better, open source. > > What debugger will you suggest? > Or what more polish feature you want to see in an ideal python > debugger? -- hope this thread will help IDE developers to fill their > todo list with some shining ideas :) > Eric3 should be compliant with your list. Try it at http://www.die-offenbachs.de/detlev/eric3.html Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From andreas at kostyrka.org Fri Jul 22 10:07:06 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 22 Jul 2005 16:07:06 +0200 Subject: time.time() under load between two machines In-Reply-To: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> Message-ID: <20050722140705.GA28702@heaven.kostyrka.org> I've just noticed that you didn't mention any details like OS, versions, network infrastructure. You do not mention either how large the difference is. Andreas From guy.lateur at b-b.be Tue Jul 5 05:33:22 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 05 Jul 2005 09:33:22 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: Thanks for the suggestion, Tim. Unfortunately, I get a 'connection refused' error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error: (10061, 'Connection refused')". I've tried both the external IP adress and the internal one (10.0.0.2). I'm sure there's a way to get over this, isn't there? One more question: can I avoid having (plain text) passwords in my code? I guess I could make a special account for this with a password known by everybody. Cheers, g "Tim Williams (gmail)" schreef in bericht news:mailman.1326.1120495311.10512.python-list at python.org... Lateral thinking ? === untested === import imaplib, time, sys f = open(msg_file) r = f.readlines() f.close() msg1 = ''.join(r) server = 'my.exchangeserver.com' # or IP address user = 'user' pw = 'pw' M = imaplib.IMAP4(server) M.sock.settimeout(120) M.login(user,pw)[1][0] M.select() M.append('INBOX',None ,time.time() , msg1) # Inbox or other folder name print "MESSAGE successfully saved" #M.close() Don't use close, deletes/purges items M.logout()[1][0] From http Sun Jul 3 05:32:21 2005 From: http (Paul Rubin) Date: 03 Jul 2005 02:32:21 -0700 Subject: Tkinter Checkbutton initialization problem Message-ID: <7xzmt4fd5m.fsf@ruckus.brouhaha.com> Python 2.4, Windows XP. If I say: f = Frame() f.grid() v = IntVar() c = Checkbutton(f, text='hi there', variable=v) c.grid() f.mainloop() then the checkbutton should initially display as being checked. But it doesn't. It shows up unchecked, even though v.get() returns 1. The select operation DOES update the display if there's no variable. It works properly under Linux with (I think) Python 2.3. I don't have a 2.4.1 Windows installation to try right now. Is this a known bug? Is it fixed in 2.4.1? Is there a simple workaround, that lets me initialize a checkbutton and still be able to read its state? Thanks. From hongqn at gmail.com Sat Jul 23 22:50:37 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Sun, 24 Jul 2005 10:50:37 +0800 Subject: what's wrong with my code using subprocess? Message-ID: I decide to seperate my data collection routine from my data analysis and storage program to a seperate process, so I try to use the new subprocess model in Python 2.4. The main program spawns the subprocess and receives data from the pipe. When some event occurs (e.g. the user clicks the 'Stop' button on GUI), the main program will send the subprocess a command to change its behavior or ask it to exit. However, my code (attached below) doesn't work. Under Linux, the output is: waiting subprocess exit Traceback (most recent call last): File "receiver.py", line 19, in ? main() File "receiver.py", line 13, in main print >>p.stdin, 'exit' IOError: [Errno 32] Broken pipe And Under Windows XP, p.wait() never returns: waiting subprocess exit [hanging here] What's wrong? # collector.py import threading class Main(object): def __init__(self): self.keep_going = True self.t = threading.Thread(target=self.work) self.t.start() cmd = raw_input() while cmd != 'exit': cmd = raw_input() self.keep_going = False self.t.join() def work(self): while self.keep_going: print '$' * 82 if __name__ == '__main__': Main() # receiver.py (the main program) from subprocess import Popen, PIPE def main(): p = Popen(['python', 'collector.py'], stdout=PIPE, stdin=PIPE) count = 0 for line in p.stdout: data = line.strip() # process(data) count += 1 if count >= 1000: print >>p.stdin, 'exit' print 'waiting subprocess exit' p.wait() if __name__ == '__main__': main() -- Qiangning Hong I'm usually annoyed by IDEs because, for instance, they don't use VIM as an editor. Since I'm hooked to that, all IDEs I've used so far have failed to impress me. -- Sybren Stuvel @ c.l.python Get Firefox! From whereU at now.com Sun Jul 24 02:26:41 2005 From: whereU at now.com (Eric Pederson) Date: Sat, 23 Jul 2005 22:26:41 -0800 Subject: is this pythonic? In-Reply-To: References: <42DE4F67.7030300@mage.hu> Message-ID: <20050723222641.356951909.whereU@now.com> "Caleb Hattingh" wrote: >In another > newsgroup, I could have been flamed for letting Simon know he helped > more > than just the OP with his post :) +1 OP asks, thousands are educated (perhaps). The group's generosity is greatly appreciated, even if that appreciation is under-expressed. -Anon (well, sort of) P.S. You mean this list isn't TFM? From Dennis.Benzinger at gmx.net Fri Jul 22 09:19:19 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Fri, 22 Jul 2005 15:19:19 +0200 Subject: command line argument passing In-Reply-To: References: Message-ID: <42e0f252$1@news.uni-ulm.de> Hayri ERDENER schrieb: > hi to all, > is it possible in python to pass arguments by using command prompt in > windows 2000 and XP ? > for example: > sourceCode.py factorial 4 > gives me the factorial of 4 namely 24. > best regards import sys print sys.argv Or use the optparse module. Docs: http://www.python.org/doc/2.4.1/lib/module-optparse.html Bye, Dennis From mage at mage.hu Mon Jul 11 09:29:41 2005 From: mage at mage.hu (Mage) Date: Mon, 11 Jul 2005 15:29:41 +0200 Subject: cursor positioning Message-ID: <42D27445.9090005@mage.hu> Dear All, I am writing a database import script in python and I would like to print the percentage of the process to the last line. I would like to update the last line at every percent. You know what I mean. How can the cursor be positioned to the last line or somewhere else on the screen? Curses starts with clearing the whole screen and it is overkill. Many modules are on the net but I would like to resolve this simply task with native python. I tried: for something: print chr(8)*20+mystring, but it is nasty and didn't work well. Mage From Scott.Daniels at Acm.Org Fri Jul 29 21:36:59 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 29 Jul 2005 18:36:59 -0700 Subject: A replacement for lambda In-Reply-To: References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <42ead151@nntp0.pdx.net> Christopher Subich wrote: > g = > g(1) == 1 > > Basically, I'd rewrite the Python grammar such that: > lambda_form ::= "<" expression "with" parameter_list ">" > > Biggest change is that parameter_list is no longer optional, so > zero-argument expr-comps would be written as , which makes > a bit more sense than . > > Since "<" and ">" aren't ambiguous inside the "expression" state, this > shouldn't make the grammar ambiguous. The "with" magic word does > conflict with PEP-343 (semantically, not syntactically), so "for" might > be appropriate if less precise in meaning. What kind of shenanigans must a parser go through to translate: < this is the comparison of two functions, but it looks like a left- shift on a function until the second with is encountered. Then you need to backtrack to the shift and convert it to a pair of less-thans before you can successfully translate it. --Scott David Daniels Scott.Daniels at Acm.Org From mh at pixar.com Tue Jul 5 14:42:10 2005 From: mh at pixar.com (Mark Harrison) Date: Tue, 05 Jul 2005 18:42:10 GMT Subject: best options for oracle/python? Message-ID: <6wAye.1255$Tc6.1131@newssvr13.news.prodigy.com> Any recommendations for Oracle bindings for the DB-API 2.0 specification? This is for Oracle 10g if that makes any difference. Also, any other Oracle related goodies that might be useful? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From fdeserres at gmx.net Wed Jul 13 09:15:54 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 15:15:54 +0200 Subject: Building a function call? In-Reply-To: <7OWdnRFJ_sHkk0jfRVn-hw@powergate.ca> References: <7OWdnRFJ_sHkk0jfRVn-hw@powergate.ca> Message-ID: <42D5140A.60700@gmx.net> Peter Hansen wrote: >Roland Heiber wrote: > > >>Not the best (not at all) but one way: >> >>def dothat(x,y): >> print "Called with:", x, y >> >>c = (1,2) >> >>locals().get("dothat")(*c) >> >> > >As you say, not the best, but in fact not really advisable under any >circumstances. locals() returns "module level" stuff only when executed >_at_ module level (i.e. not inside a function). Otherwise it will >return only the local variables of the frame its in. > >Better is this, since it works for the OP's requirements in either >situation. > > globals()['dothat'](*c) > >-Peter > > Actually that's part of my dilemma... I guess the function name is moreoften in globals(). But the parameters in the tuple are A) formals (that was not clear in my OP, sorry), B) once bound by another function, I they'll become part of locals(). func = "dothat" args = (x,y) localcontext = () r = None while r is None: try: r = eval("dothat(x,y)", None, localcontext) #how do I construct "dothat(x,y)"? except NameError: ensure_context(x,y) #find/compute the formals, eg: localcontext = (('x', 100), ('y', 200)) F. From mwh at python.net Wed Jul 6 09:24:37 2005 From: mwh at python.net (Michael Hudson) Date: Wed, 6 Jul 2005 13:24:37 GMT Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> Message-ID: Will McGugan writes: > Qiangning Hong wrote: > > On 7/6/05, Will McGugan wrote: > > > >>Hi, > >> > >>Are there any benefits in using a frozenset over a set, other than it > >>being immutable? > > A frozenset can be used as a key of a dict: > > Thanks, but I meant to imply that. > > I was wondering if frozenset was faster or more efficient in some > way. No, the 'usable as a dict key' is the main motivation for frozenset's existence. Cheers, mwh -- The bottom tier is what a certain class of wanker would call "business objects" ... -- Greg Ward, 9 Dec 1999 From harlinseritt at yahoo.com Sat Jul 9 07:38:25 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 9 Jul 2005 04:38:25 -0700 Subject: Formatting data to output in web browser from web form Message-ID: <1120909105.049621.210020@z14g2000cwz.googlegroups.com> Hi, I am using CherryPy to make a very small Blog web app. Of course I use a textarea input on a page to get some information. Most of the time when text is entered into it, there will be carriage returns. When I take the text and then try to re-write it out to output (in html on a web page), I notice the Python strings don't translate these special characters (carriage returns) to a "

" so that these paragraphs show up properly in html for output. I tried doing something like StringData.replace('\n', '

'). Of course this doesnt work because it appears that '\n' is not being used. Is there anything I can do to make sure paragraphs show up properly? Thanks, Harlin Seritt From km at mrna.tn.nic.in Wed Jul 27 03:26:50 2005 From: km at mrna.tn.nic.in (km) Date: Wed, 27 Jul 2005 12:56:50 +0530 Subject: multiple inheritance super() In-Reply-To: References: Message-ID: <20050727072650.GA13815@mrna.tn.nic.in> Hi peter, ya got it working :-) now i understand mro better. thanks, KM ------------------------------------------------------------- On Tue, Jul 26, 2005 at 04:09:55PM -0400, Peter Hansen wrote: > km wrote: > > Hi all, > > > > In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? > > > > thanks in advance for enlightment ... > > > > here's the snippet > > > > #!/usr/bin/python > > > > class A(object): > > def __init__(self): > > self.a = 1 > > > > class B(object): > > def __init__(self): > > self.b = 2 > > > > class C(object): > > def __init__(self): > > self.c = 3 > > > > class D(B, A, C): > > def __init__(self): > > self.d = 4 > > super(D, self).__init__() > > Each class should do a similar super() call, with the appropriate name > substitutions. > > Calls to __init__ must be made explicitly in subclasses, including in > the case of multiple inheritance. > > Also note that often (usually) you would like the __init__ call to come > *before* other location initializations, and it's the safest thing to do > unless you have clear reasons to the contrary. > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From mwm at mired.org Tue Jul 19 20:25:50 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 19 Jul 2005 20:25:50 -0400 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: <863bqbu0rb.fsf@bhuda.mired.org> Message-ID: <86u0iqs4q9.fsf@bhuda.mired.org> Thomas Bartkus writes: > On Mon, 18 Jul 2005 19:56:24 -0400, Mike Meyer wrote: > >> "Thomas Bartkus" writes: >>>> > Re-train on a new platform, >>>> > and re-write from scratch? >>> >>> What do you do when an open source project you were using gets >>> abandoned? >> >> cvs import -m "sources for orphaned project" >> >> >>> Hard to see much difference here. >> >> Doing support for object-only distributions is *much* harder than doing >> it for source distributions. >> >> I have a habit of picking products based on technical superiority, not >> popularity. As a result, I have a nice collection of orphans. That's >> because technical quality has little or nothing to do with >> profitability. >> >> On the other hand, since starting to use open source projects, I've >> never had one I depend on fail. I've had some I contributed to fail, but >> that's a different thing. > > I didn't suggest that orphaned open source projects were a problem. I > simply point out that they are no more, nor less, of a problem than an > orphaned (and paid for!) commercial product. You missed my answer to this. Ok, it was oblique, so it's probably my fault. With an orphaned open source project, you always have the option of taking on the support role yourself - or paying someone else to do so. That's not generally possible with closed source products. >> I suspect that technical quality in open source projects contributes to >> their attracting people to support them. > Perhaps. And there is no way to support a commercial product other than > by becoming an employee. Not true. Not all commercial products are closed source - though that tends to be the norm these days. And you can contribute code to closed source products. For instance, I did the original Python wrappers for Perforce's binary library. That's certainly supporting the product. >> This makes them ever so >> much more attractive than proprietary solutions, where technical quality >> seems to be irrelevant to longevity. > This last statement sounds too much like a canard. It is difficult to deny > that commercial products either put some significant value on the table or > go bust. Although people can be, and sometimes are, swindled few can > afford to simply throw their money away. IOW - technical quality is > *never* irrelivant to longevity. And one must also consider that > technical merit, by itself, is rarely sufficient. The open source world > is awash with much that is high on technical merit but commercially > unviable. There is much out there that one would gladly pay good $ for if > only for lack of that last (but most difficult!) 5% effort that would > bring many of these projects to fruition. I almost certainly overstated the case - but I've been burned a lot by choosing technical quality over profitability or popularity. The reality seems to be that once you reach the level of "good enough", technical quality stops mattering, and marketing forces come into play. My essay on the subject at has more information. > Which brings me back to the point that the difference between free and > $500 (or $1000!) amounts to virtually *nothing* when evaluating a tool. Depends on what you're evaluating it for. In the context of the discussion - choosing tools for commercial software development - it's almost certainly true. If it's not, you're not charging enough for your time. But that's hardly the only time that one evaluates tools. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From miki.tebeka at zoran.com Mon Jul 11 02:38:40 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 11 Jul 2005 09:38:40 +0300 Subject: C/API importing a module as __main__ Message-ID: <20050711063840.GE344@zoran.com> Hello All, Is there a way to import module as __main__? Say hw.py is: if __name__ == "__main__": print "Hello" And the C code is (error handling omitted): int main(int argc, char *argv[]) { Py_Initialize(); PySys_SetArgv(argc, argv); atexit(Py_Finalize); PyImport_ImportModule(module); return 0; } When importing hw using PyImport_ImportModule nothing is printed (as expected). The documentation says that Py_Initialize already creates a __main__ module and hw.py is imported as hw. Any way to import hw as __main__? Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From adurdin at gmail.com Fri Jul 1 20:01:06 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Sat, 2 Jul 2005 10:01:06 +1000 Subject: When someone from Britain speaks, Americans hear a "Britishaccent"... In-Reply-To: <11c8tgjju7ljvd4@corp.supernews.com> References: <11c8tgjju7ljvd4@corp.supernews.com> Message-ID: <59e9fd3a05070117013e83c8ab@mail.gmail.com> On 7/1/05, Grant Edwards wrote: > On 2005-06-30, Delaney, Timothy (Tim) wrote: > > Tom Anderson wrote: > > > >> How about carrier? > > > > Ends in an "a" (Australian ;) > > Right, but due to some wierd property requiring conservation of > consonants, when speaking Strine you've got to take the r's > removed from words like "carrier" and "order", and add them to > the ends of other words like Amanda. No, you've got it wrong -- we take them and insert them where they were never intended to be: "I saw Amanda" sounds like "I sawramanda" Andrew From cliff at develix.com Sat Jul 30 16:30:38 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 13:30:38 -0700 Subject: rfc822 module bug? In-Reply-To: <20050730085418.2139.16534.XPN@orion.homeinvalid> References: <20050730085418.2139.16534.XPN@orion.homeinvalid> Message-ID: <1122755438.19618.9.camel@localhost.localdomain> On Sat, 2005-07-30 at 09:08 +0000, Nemesis wrote: > Hi all, > I found that the function parsedate_tz of the rfc822 module has a bug > (or at least I think so). > I found a usenet article (message-id: <2714d.q75200 at myg.winews.net>) > that has this Date field: > > Date: Tue,26 Jul 2005 13:14:27 GMT +0200 My preferred date/time module is Gustavo Niemeyer's DateUtil module: https://moin.conectiva.com.br/DateUtil It parses an astounding number of date formats (I used it to parse the mess of dates and times provided by RSS feeds without a hitch). Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From mensanator at aol.com Fri Jul 1 19:55:11 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 1 Jul 2005 16:55:11 -0700 Subject: Python, mysql, floating point values question In-Reply-To: References: Message-ID: <1120262111.748731.239720@o13g2000cwo.googlegroups.com> Christopher Kang wrote: > I had a question about python and mysql, but I want to first thank > those who taught me about the factory method, it was exactly what I > needed. > > Anyway, I have a problem where I am pulling floating point values out > of mysql and into python using the MYSQLdb module. > > However, the values seem to be altered a little when I store them in python. > > Because the decimal places are off, I am unable to use the values that > I have in order to write a sql statement (again using the MYSQLdb) > that pulls column values from just that single value i'm looking for. > > Let me explain more clearly: > > Let's say I pull column1 values for all records, and they happen to be: > > 1.4, 1.5632, 1.32523 in the mysql database. > > Now I realize that I am interested in all the column values for just > the 1.5632 record. Unfortunately, python seems to be taking the > floating point values, and doing something with it, such that my > variable has something like 1.5632000000001 stored in it or such. > > I thus, can't pull the value out using a sql statement such as > "Select * from table_name where column1 = my_variable_value" becuase > my_variable_value has 1.563200000000001 stored in it, and not 1.5632. > > The way that the variable gets adjusted seems to be random. > > Is there a solution to this? The smart-ass answer is to learn how to use floating point properly. But along those lines, once you get a useful representation of 1.5632 in Python, you may discover that not all the 1.5632's in the database are identical. They, too, may differ insignificantly. You may have to apply fixes on both ends. I don't know mysql but in MS-Acces, I would probably make a calculated field in the db query such as Format$([TheField],"0.0000"). As a string, the differences in the many flavors of 1.5632 are discarded. > > > > Thank you very much! From darkcowherd at gmail.com Mon Jul 25 11:54:49 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Mon, 25 Jul 2005 21:24:49 +0530 Subject: First app, thanks people In-Reply-To: <42e4eff3$1@griseus.its.uu.se> References: <42e4eff3$1@griseus.its.uu.se> Message-ID: <5f4d3cb50507250854158928e1@mail.gmail.com> Hmm, I was looking at the code as I am also learning Python. In case you are interested in bug report. class LineTool method OnLeftUp needs self.done = True or else if you are in Line mode and you just click with out moving the mouse you get an error. DarkCowherd From dvanvliet at 3dna.net Mon Jul 4 13:07:16 2005 From: dvanvliet at 3dna.net (Derek van Vliet) Date: 4 Jul 2005 10:07:16 -0700 Subject: importing pyc from memory? In-Reply-To: References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Message-ID: <1120496836.806367.65780@z14g2000cwz.googlegroups.com> The second method you describe sounds like it is along the lines of what I need to do. Is there a way to do this using the Python/C API? For instance, if I have the contents of a pyc file loaded entirely into memory, and I have a pointer to the beginning of the file and the size in bytes at my disposal, can I import that by any means? From thomasbartkus at comcast.net Wed Jul 13 15:20:20 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 13 Jul 2005 14:20:20 -0500 Subject: all possible combinations References: <1121277937.a2a3097d7c150f1b8a3f41a21a9f2b25@teranews> Message-ID: "George Sakkis" wrote in message news:1121277937.a2a3097d7c150f1b8a3f41a21a9f2b25 at teranews... > "rbt" wrote: > > > Say I have a list that has 3 letters in it: > > > > ['a', 'b', 'c'] > > > > I want to print all the possible 4 digit combinations of those 3 > > letters: > > > > 4^3 = 64 > > > It's actually 3^4 = 81 (3 candidates/choice ** 4 choices) Yes. You get a cigar! Someone else (Jack Diederich) also mentioned "This is called a cartesian product, ..." Right again. Now I can't help injecting that SQL is custom made for returning a cartesian product. Given a table called [Letters] containing a field [Letter] with (3) records Letter = 'a', 'b', 'c' SELECT CONCAT(t1.Letter, t2.Letter, t3.Letter, t4.Letter) FROM Letters As t1, Letters As t2, Letters As t3, Letters As t4 Will return those 81 combinations in an eyblink. In order to stay on topic, you are required to call your favorite SQL engine from Python :-) Thomas Bartkus From elmo13 at jippii.fi Wed Jul 13 16:12:55 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Wed, 13 Jul 2005 23:12:55 +0300 Subject: Searching for metadata related tools for use with python References: Message-ID: On Wed, 13 Jul 2005 15:49:27 +0300, Elmo M?ntynen wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I'm interested in various metadata > extraction/prosessing/distribution/something tools(including ways of > differentiating between files, eg hashing etc) and especially python > enabled ones. I'm also considering content-recognition/differentiating > eg. image recognition. I'm already aware of these: python-bitzi, > python-musicbrainz, mmpython, IMDbPY, python-mhash and imgSeek. If you > could point me to other relating resources it would be great. > > Elmo > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.1 (GNU/Linux) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFC1Q3WctNFyQJObrsRAjXbAJ92B53YC9NqtC9nymK07OL+L3mNTwCgmlbb > dPfSDsqJzBh+xa3h5L28Qac= > =AtAo > -----END PGP SIGNATURE----- I would also like comments if you're pretty sure the aren't any other re?ated resources. Anything related to organizing one's filecollections(be it music, photos, books etc.), though i'm not particularly interested in another mp3/ogg-tagger(report it still though, if you will). Elmo From ken at perfect-image.com Mon Jul 25 18:43:46 2005 From: ken at perfect-image.com (Ken Godee) Date: Mon, 25 Jul 2005 15:43:46 -0700 Subject: pyQT 4 In-Reply-To: <42E5602D.2090803@gmail.com> References: <42E5602D.2090803@gmail.com> Message-ID: <42E56B22.9070506@perfect-image.com> > My question is : does anybody know when pyqt 4 will be distributed ? > http://www.riverbankcomputing.co.uk/pyqt/roadmap.php From fdeserres at gmx.net Wed Jul 13 08:45:32 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 14:45:32 +0200 Subject: **kwargs? Message-ID: <42D50CEC.6040805@gmx.net> All your **kwargs are belong to us. *args is documented in the Tutorial. I reckon **kwargs represents a dictionary of arguments. But I don't quite get the semantics of **x. Undefined length tuple of undefined length tuples? Are there other practical use cases for ** (common enough please, I wish I was, but I'm not a scientist). TIA, Francois From jwaixs at gmail.com Sun Jul 3 04:52:20 2005 From: jwaixs at gmail.com (jwaixs) Date: 3 Jul 2005 01:52:20 -0700 Subject: website catcher Message-ID: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> Hello, I'm busy to build some kind of webpage framework written in Python. But there's a small problem in this framework. This framework should open a page, parse it, take some other information out of it and should store it in some kind of fast storage. This storage need to be very fast so every one who will ask for this page will get a parsed page returned from this storage (catcher?). But how could I design a good webcatcher? Is this possible in python, because it should always run. Which won't work with cgi-bin pages because the quit after the execute something. Or should it be build in c and imported as a module or something? Thank you, Noud Aldenhoven From davecook at nowhere.net Tue Jul 19 13:42:01 2005 From: davecook at nowhere.net (Dave Cook) Date: Tue, 19 Jul 2005 17:42:01 GMT Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> Message-ID: On 2005-07-19, istvan.albert at gmail.com wrote: > On the other hand I even in its current form I don't see how I would to > the simple things that I need every day. Create a session, set a > cookie, redirect to another url, perform HTTP autentication, create > filter, use another templating language? This is also integral part of > the functionality that I expect from an web framework. Web specific > things exposed in some python ic way. Take a look at the Nevow FAQ and examples. Also, Nevow sits on top of Twisted, so you have all of Twisted's features available. http://divmod.org/users/wiki.twistd/nevow/moin.cgi/FrequentlyAskedQuestions Dave Cook From donn at u.washington.edu Fri Jul 8 13:50:22 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 08 Jul 2005 10:50:22 -0700 Subject: Polling, Fifos, and Linux References: Message-ID: In article , Andreas Kostyrka wrote: > On Thu, Jul 07, 2005 at 10:21:19PM -0700, Jacob Page wrote: > > Jeremy Moles wrote: > > > This is my first time working with some of the more lower-level python > > > "stuff." I was wondering if someone could tell me what I'm doing wrong > > > with my simple test here? > > > > > > Basically, what I need is an easy way for application in userspace to > > > simply echo values "down" to this fifo similar to the way proc files are > > > used. Is my understanding of fifo's and their capabilities just totally > > > off base? > > > > You shouldn't need to use select.poll(), unless I'm missing something. > > I was able to get the following to work: > Ok, you miss something ;) The program you proposed does busy waiting > and without a time.sleep call will consume 100% CPU time :( I don't doubt that it would, but that's because he (like the original poster) open the file with O_NONBLOCK. From my point of view that's a self-inflicted injury, but if you start from the assumption that O_NONBLOCK is needed for some reason, then the poll makes sense. In normal blocking mode, select+read is identical to plain read for any kind of file that supports select. > Actually, with a named fifo the situation gets even nastier: > > import os, select, time > > fifo = os.open("fifo", os.O_RDONLY) > > while True: > print "SELECT", select.select([fifo],[],[]) > string = os.read(fifo, 1) > if len(string): > print string > else: > nf = os.open("fifo", os.O_RDONLY) > os.close(fifo) > fifo = nf > # Perhaps add a delay under an else > > The problem is, that select (and poll) show a End-Of-File condition by > returning > ready to read. But on a FIFO, when the first client terminates, the reading > end goes into a EOF state till somebody else reopens the fifo for writing. > > [This bit of wisdom comes Advanced Programming in the UNIX Environment by > W.R. Stevens p. 400: 'If we encounter the end of file on a descriptor, that > descriptor is considered readbale by select.'] > > closing the old descriptor must be done after opening a new one, or else you > get a tiny moment where a O_WRONLY client is not able to open the file. > This way there is always a reading client of the fifo. OK, but in more detail, what happens in these two scenarios? In your version, what happens when the writer opens a pipe pipe that the reader is about to close? Who reads the data? On the other hand, if you close the pipe first, what happens to the writer who happens to try to open the pipe at that moment? Luckily, as far as I know, we don't have to worry about the first one, since if data could be lost in this way it would be much more complicated to close a file descriptor without running this risk. But I don't see the second one as much of a problem either. The writer blocks - so? Now, what would really be useful is a way for the writer to detect whether open will block, and potentially time out. Donn Cave, donn at u.washington.edu From peter at engcorp.com Sat Jul 9 10:22:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Jul 2005 10:22:06 -0400 Subject: pyo contains absolute paths In-Reply-To: References: Message-ID: David Siroky wrote: > When I "compile" my python files with "python -OO ...." into pyo files > then they still contain absolute paths of the source files which is > undesirable for me. How can I deal with that? Don't do that? Delete the pyo files? Stop using Python? I could guess at a few more possibilities, but since you don't actually say what you *want* to happen, just what you don't want to happen, there are an infinite number of ways to satisfy you right now. (Hint #1: absolute paths are always, AFAIK, put into the .pyc or .pyo files.) (Hint #2: maybe explaining why you don't want this to happen would help too, since that will probably determine the "best" solution.) -Peter From jasondrew72 at gmail.com Thu Jul 28 10:22:43 2005 From: jasondrew72 at gmail.com (Jason Drew) Date: 28 Jul 2005 07:22:43 -0700 Subject: retrieve data from 2 database In-Reply-To: <1122520735.066339.235110@z14g2000cwz.googlegroups.com> References: <1122520735.066339.235110@z14g2000cwz.googlegroups.com> Message-ID: <1122560563.329105.48350@o13g2000cwo.googlegroups.com> For a start, asking a better question will get better answers: http://www.catb.org/~esr/faqs/smart-questions.html Googling for python odbc gives this as the first result: http://www.python.org/windows/win32/odbc.html In general, how you compare database tables will depend a lot on the nature of the tables: e.g. are you comparing names to names, rows to rows, apples to oranges, etc.? From rphillips at engineer.co.summit.oh.us Wed Jul 27 06:49:42 2005 From: rphillips at engineer.co.summit.oh.us (paron) Date: 27 Jul 2005 03:49:42 -0700 Subject: GUI - Windows: Where to get started References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: <1122461382.736537.275550@g44g2000cwa.googlegroups.com> Ernesto wrote: > Hi all, > > Would anyone know a good place to start for learning how to build > simple GUI's in Windows XP? I just want users to be able to select a > few parameters from a pull-down menu, then be able to run some batch > files using the parameters from the pull down menus. I would also need > a "Browse" menu, so users could point to a place on the local disc (ie > C:\PointSystemHere). Can anyone give a noob some tips? THANKS!!! You probably already know HTML. You might use CherryPy and put the GUI in a browser. See http://www.cherrypy.org/wiki/SingleClickAndRun for demo code. I think it's the simplest GUI going for python, plus your users already know a lot about how to use a browser. Ron From onurb at xiludom.gro Mon Jul 4 05:52:19 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 04 Jul 2005 11:52:19 +0200 Subject: I am a Java Programmer In-Reply-To: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> Message-ID: <42c906d3$0$2455$626a14ce@news.free.fr> mjmrifai at gmail.com wrote: > I am a java programmer Too bad :( > and I want to learn Python So there's still hope !-) > Please help me. 1/ download and install Python 2/ go thru the 'dive into Python' and 'Thinking in Python' free books 3/ post here when you're in doubt or in trouble... And don't forget: Python is *not* Java !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gsakkis at rutgers.edu Sun Jul 3 19:10:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 16:10:50 -0700 Subject: math.nroot [was Re: A brief question.] References: Message-ID: <1120432250.340056.237460@g44g2000cwa.googlegroups.com> "Tom Anderson" wrote: > > But NaNs are _not_ things. > > I disagree. A NaN _is_ a thing; it's not a floating-point number, for > sure, but it is a symbol which means "there is no answer", or "i don't > know", and as such, it should follow the universal rules which apply to > all things. It seems that the standard semantics of NaN is closer to NULL values in ANSI SQL, that is "unknown", "not available". In this sense, if you have two 'things' you don't know, you can't say they are equal simply because you don't know them ! > > Since INF-INF doesn't have an answer, we can't do this: > > > > x = inf - inf > > y = inf - inf > > > > and expect that x == y. > > I think we can. Both x and y have the same value, a value of > indeterminacy. NaN is a rigidly defined value of doubt and uncertainty! In this case, however, I would agree. x and y above are not assigned a label of 'unknown'; they are derived from an operation among valid *known* values, so NaN here means 'invalid' rather than 'unknown'. It makes sense to have x==y, because x and y are the outcome of the *same* invalid operation. Similarly, if z=0/0, z would also be invalid, but different from x and y, since it is the result of a different invalid operation. This brings us to the many-NaN situation. George From bex at xaotec.com Mon Jul 25 15:44:52 2005 From: bex at xaotec.com (bex) Date: 25 Jul 2005 12:44:52 -0700 Subject: OS X py2app confusion Message-ID: <1122320692.803298.231120@g49g2000cwa.googlegroups.com> Im baffled about this one... Im running OS 10.3, and Python 2.3. I installed py2app 0.17 and never used it, then installed py2app 0.2. It refuses to work. None of the samples will build. Observe: $ pwd /Developer/Python/py2app/Examples/pygame $ python setup.py py2app Traceback (most recent call last): File "setup.py", line 8, in ? import py2app ImportError: No module named py2app $ No module??? huh??? Its clearly there in the appropriate place: $ pwd /Library/Python/2.3 $ ls PyObjC README py2app.pth wxPython PyObjC.pth py2app wx $ ls py2app altgraph bdist_mpkg macholib modulegraph py2app $ ls py2app/py2app/ __init__.py command filters.pyo __init__.pyc create_appbundle.py install.py __init__.pyo create_appbundle.pyc install.pyc apptemplate create_appbundle.pyo install.pyo bootstrap create_pluginbundle.py recipes build_app.py create_pluginbundle.pyc scripts build_app.pyc create_pluginbundle.pyo util.py build_app.pyo filters.py util.pyc bundletemplate filters.pyc util.pyo $ more py2app.pth py2app $ I was confused about the packaging, so I tried moving all the folders in py2app into /Library/Python/2.3/ and deleted the py2app.pth file, but it still wouldn't load the module. Any insight into the voodoo magic required to get this working? From opengeometry at yahoo.ca Sun Jul 3 21:50:53 2005 From: opengeometry at yahoo.ca (William Park) Date: Sun, 03 Jul 2005 21:50:53 -0400 Subject: Escaping commas within parens in CSV parsing? References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> <1120238295.198792.123110@g47g2000cwa.googlegroups.com> Message-ID: <420bb$42c895fd$d8fe9f56$22574@PRIMUS.CA> felciano wrote: > Thanks for all the postings. I can't change delimiter in the source > itself, so I'm doing it temporarily just to handle the escaping: > > def splitWithEscapedCommasInParens(s, trim=False): > pat = re.compile(r"(.+?\([^\(\),]*?),(.+?\).*)") > while pat.search(s): > s = re.sub(pat,r"\1|\2",s) > if trim: > return [string.strip(string.replace(x,"|",",")) for x in > string.split(s,",")] > else: > return [string.replace(x,"|",",") for x in string.split(s,",")] > > Probably not the most efficient, but its "the simplest thing that > works" for me :-) > > Thanks again for all the quick responses. How about changing '(' or ')' into three double-quotes '"""'? That will solve splitting issue. But, I'm not sure how you would get back '(' or ')', without much coding. -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From sybrenUSE at YOURthirdtower.com.imagination Wed Jul 13 09:04:25 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 13 Jul 2005 15:04:25 +0200 Subject: reg php equivalent move_uploaded file function in python References: Message-ID: praba kar enlightened us with: > Is there any php equivalent move_uploaded_file($source_path, > "$upload_dir/$name"); function in python to upload a file to server? move_uploaded_file does NOT upload a file to a server. > Kindly give me answer. Kindly ask answerable question. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From news at NOwillmcguganSPAM.com Fri Jul 22 05:08:41 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Fri, 22 Jul 2005 10:08:41 +0100 Subject: dictionary that discards old items In-Reply-To: References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> Message-ID: <42e0b79a$0$30800$db0fefd9@news.zen.co.uk> Michael Hoffman wrote: > Will McGugan wrote: > >> I need a collection class that behaves like a dictionary but when it >> reaches 'n' items it discards the oldest item so that the length never >> goes above 'n'. (Its for caching search results) >> >> I have a vague memory of a module that does this, but I cant remember >> where I read about it. Can anyone enlighten me? > > > You want a Least Recently Used, or LRU, cache. Here's one: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524 > > Google for to find others. Thanks. I found the one I saw originally in the Python Cookbook. Only they call it a FIFO cache. -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From michele.simionato at gmail.com Sat Jul 30 04:32:06 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 30 Jul 2005 01:32:06 -0700 Subject: Block-structured resource handling via decorators In-Reply-To: References: Message-ID: <1122712326.716044.281910@o13g2000cwo.googlegroups.com> I will shamelessly point out my decorator module: http://www.phyast.pitt.edu/~micheles/python/decorator.zip The documentation is here: http://www.phyast.pitt.edu/~micheles/python/documentation.htm There is an example of redirecting stdout which is relevant to this thread. HTH, Michele Simionato From claird at lairds.us Fri Jul 15 15:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 15 Jul 2005 19:08:03 GMT Subject: Any Lua Coders About? References: <2005071323103316807%wendell@meetrocom> Message-ID: <6fblq2-519.ln1@lairds.us> In article , Joseph Garvin wrote: >Wendell III wrote: > >>Hey, >> >>I'm looking for a few good Lua guys with some IM network experience. >>Anyone around fit that criteria? . . . >I'd say it's a no brainer to try lua's mailing list ;) Incidentally, San Jose will host The Workshop, the big public event in the Lua world, at the end of the month. From just1coder at yahoo.ca Mon Jul 4 17:05:24 2005 From: just1coder at yahoo.ca (just1coder at yahoo.ca) Date: 4 Jul 2005 14:05:24 -0700 Subject: HTTP Open -v- File Read Message-ID: <1120511124.639946.90730@g44g2000cwa.googlegroups.com> I am relatively new to Python ... I have a script that uses urllib2 to open another XML file off of the same server the PY file is living on. urllib2.urlopen(url).read() I changed a bit of it to use: open(filename, 'r').read() to open the file locally rather than making an HTTP call however the file no longer works completely. It does load in the XML data without fail but a certain section fails to render... Is there any glaring mistake doing this? From ajay.greatz at gmail.com Mon Jul 4 07:51:47 2005 From: ajay.greatz at gmail.com (thinkgeek) Date: 4 Jul 2005 04:51:47 -0700 Subject: Trapping user logins in python ( post #1) Message-ID: <1120477906.956606.119040@g14g2000cwa.googlegroups.com> I am writting a daemon in python which should start at system start up with all inet.d serviceson an NIS server. Then it should listen to any user login and then start a new process for that user on his login which will continue throughout his entire session. Can anyone give any help or any suggestion or any useful links. thinkgeek From exarkun at divmod.com Thu Jul 21 09:29:13 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 09:29:13 -0400 Subject: Buffering problem using subprocess module In-Reply-To: <1121951665.430514.167440@g14g2000cwa.googlegroups.com> Message-ID: <20050721132913.26278.1042630688.divmod.quotient.15440@ohm> On 21 Jul 2005 06:14:25 -0700, "Dr. Who" wrote: >I am using the subprocess module in 2.4. Here's the fragment: > >bufcaller.py: > import sys, subprocess > proc = subprocess.Popen('python bufcallee.py', bufsize=0, shell=True, >stdout=subprocess.PIPE) > for line in proc.stdout: > sys.stdout.write(line) > >bufcallee.py: > import time > print 'START' > time.sleep(10) > print 'STOP' > >Although the documentation says that the output should be unbuffered >(bufsize=0) the program (bufcaller) pauses for 10 seconds and then >prints START immediately followed by 'STOP' rather than pausing 10 >seconds in between them. Note that I made bufcallee a Python script >for ease of the example but in the real-world problem I am trying to >solve it is simply an executable. > >Any ideas? There are a few places buffering can come into play. The bufsize parameter to Popen() controls buffering on the reading side, but it has no effect on buffering on the writing side. If you add a sys.stdout.flush() after the prints in the child process, you should see the bytes show up immediately. Another possibility is to start Python in unbuffered mode (pass the -u flag, or set PYTHONUNBUFFERED in the environment), but obviously this only applies to Python programs. Still another possibility (generally the nicest) is to use a PTY instead of a pipe: when the C library sees stdout is a pipe, it generally decides to put output into a different buffering mode than when it sees stdout is a pty. I'm not sure how you use ptys with the subprocess module. Hope this helps, Jp From peter at engcorp.com Fri Jul 1 00:07:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 00:07:00 -0400 Subject: How to run commands in command line from a script In-Reply-To: References: Message-ID: Ivan Shevanski wrote: > Alright well I'm quite a noob and when I run a simple command to change > the current directory, nothing happens. I made a little test script to > show it: > > > import os > cwd = os.getcwd() > print cwd > os.system('cd = C:\Program Files') > print cwd There are at least three errors in the above. 1. The command is "cd ", not "cd = ". (Wow! Just tried it... okay, technically it appears to work, but it doesn't seem to be the documented approach, and I've _never_ seen it before, but I have to admit it works. :-) Okay then, two errors: 1. You are using a backslash without properly escaping it (as \\) or using a "raw" string (prefix the string with r as in r"my\string". Well, okay, in _this_ particular case you get away with it, because the \P sequence is not a special one, but if you'd use \t or \b or something like that it would not have worked. So, then, only one error: 1. Commands like "cd" are executed by the shell, not as separate executables (.exe files). Unfortunately, the result of this is that their effects are lost when the shell returns to Python, so you can't do what you are trying to do in quite this manner. Generally, the only way to use an application (i.e. a program like the Python interpreter, or your own .exe) to change the working folder is to have your script executed from within a batch file, write out a new batch file in your script, and then have the calling batch file execute that script if it exists. Roughly like this: --------file mycd.bat---------- @echo off if exist c:\temp\_mycd.bat del c:\temp\_mycd.bat c:\python24\python.exe myscript.py rem Note: file _mycd.bat written by myscript.py if exist c:\temp\_mycd.bat call c:\temp\_mycd.bat --------somewhere inside myscript.py-------- newDir = r'c:\Program Files' f = open(r'c:\temp\_mycd.bat', 'w') f.write('''rem This file generated by myscript.py cd = %s''' % newDir) f.close() --------file _mycd.bat----------- rem This file generated by myscript.py cd = c:\Program Files Hope that helps... :-) -Peter From daniel.dittmar at sap.corp Fri Jul 8 11:50:03 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 08 Jul 2005 17:50:03 +0200 Subject: Use cases for del In-Reply-To: <42ce923f@nntp0.pdx.net> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <42ce923f@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Testing for None should be an is-test (not just for speed). In > older pythons the == result wasn't necessarily same as is-test. > This made sense to me after figuring out NULL in database stuff. NULL in SQL databases has nothing to do with Python None. I'm quite sure that None == None always returned boolean true. In a SQL database, NULL = NULL will always return NULL, which is prety much the same as FALSE. Except for NOT, AS NOT NULL is NULL. Daniel From grante at visi.com Thu Jul 7 00:38:32 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 04:38:32 -0000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> <11cp7fusjoid468@corp.supernews.com> <1120706984.868966.266710@g14g2000cwa.googlegroups.com> Message-ID: <11cpce8shb7si77@corp.supernews.com> On 2005-07-07, George Sakkis wrote: > I guess he means why not define foo as property: > > class demo(object): > foo = property(fget = lambda self: self.v, > fset = lambda self,v: setattr(self,'v',v)) > > d = demo() > d.foo = 3 > print d.foo In some ways that's even cleaner. In my simplivied example all the foo() method was doing was setting/returning an attribute, but usually there's a bit more going on (e.g. system calls with possible side effects). To me it's a bit more explicit that d.foo(3) d.foo() are doing something other than just getting/setting the value of an instance attribute. If all I really wanted to do was get/set the instance's "v" attribute, I probably would have just done it like this d.v = 3 print d.v -- Grant Edwards grante Yow! .. I wonder if I at ought to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER? From invalidemail at aerojockey.com Sun Jul 3 17:00:54 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 3 Jul 2005 14:00:54 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> Message-ID: <1120424454.854518.100610@o13g2000cwo.googlegroups.com> Christopher Subich wrote: > Carl Banks wrote: > > > Listcomps et al. cannot do everything map, lambda, filter, and reduce > > did. Listcomps are inferior for functional programming. But, you see, > > functional is not the point. Streamlining procedural programs is the > > point, and I'd say listcomps do that far better, and without all the > > baroque syntax (from the procedural point of view). > > I've heard this said a couple times now -- how can listcomps not > completely replace map and filter? If you're doing heavy functional programming, listcomps are tremendously unwieldy compared to map et al. -- CARL BANKS From graham.fawcett at gmail.com Wed Jul 20 13:47:50 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 20 Jul 2005 10:47:50 -0700 Subject: How to store "3D" data? (data structure question) References: Message-ID: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> Sebastian Bassi wrote: > Hello, > > I have to parse a text file (was excel, but I translated to CSV) like > the one below, and I am not sure how to store it (to manipulate it > later). > > Here is an extract of the data: > [snip] This looks a lot like 2D data (row/column), not 3D. What's the third axis? It looks, too, that you're not really interested in storage, but in analysis... Since your "line" columns all have names, why not use them as keys in a dictionary? The associated values would be lists, in which you could keep references to matching rows, or parts of those rows (e.g. name and allele). Count up the length of the row, and you have your "number of matches". import csv # let Python do the grunt work f = file('name-of-file.csv') reader = csv.reader(f) headers = reader.next() # read the first row line_names = headers[2:] results = {} # set up the dict for lname in line_names: # each key is a line-name results[lname] = [] for row in reader: # iterate the data rows row_name, allele = row[:2] line_values = row[2:] # get the line values. # zip is your friend here. It lets you iterate # across your line names and corresponding values # in parallel. for lname, value in zip(line_names, line_values): if value == '*': results[lname].append((row_name, allele)) # a quick look at the results. for lname, matches in results.items(): print '%s %d' % (lname, len(matches)) Graham From T.A.Meyer at massey.ac.nz Wed Jul 27 00:37:45 2005 From: T.A.Meyer at massey.ac.nz (Meyer, Tony) Date: Wed, 27 Jul 2005 16:37:45 +1200 Subject: [path-PEP] Path inherits from basestring again Message-ID: >>> Do people really like using __div__ to mean join? >> >> I think the '+' is used as a join for both strings and lists, so it >> would probably be the better choice as far as consistency with the >> language is concerned. > > The issue with that is that as long as we are subclassing > strings, the + is already defined for a useful operation > and the subclass probably shouldn't be changing the way that works. But a Path isn't a string, it's string-like. I presume (but am too lazy to check) that at the moment using '+' on two Paths gives a Path that concatenates the __str__ versions of the Paths, like: >>> Path("/foo/bar") + Path("/cat/dog") Path("/foo/bar/cat/dog") I can see that this would make sense in some situations, but ISTM that it would make a great deal more sense (and be much more intuitive) to have concatenation include the separator character (i.e. be join). =Tony.Meyer From bronger at physik.rwth-aachen.de Sun Jul 31 17:41:33 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 23:41:33 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <87ek9fr0c3.fsf@wilson.rwth-aachen.de> <86ack2hkol.fsf@bhuda.mired.org> Message-ID: <87mzo2zm9e.fsf@wilson.rwth-aachen.de> Hall?chen! Mike Meyer writes: > Torsten Bronger writes: > >> [...] >> >> None of us has talked about changing syntax. However, the >> standard library is part of the language unless you're really >> very petty. > > Or you use different Python implementations. There are four > different Python implementations in the world. Not everything in > the CPYthon standard library runs in all of them. Or are you going > to claim that someone usin Jython isn't using Python because they > can't use the full standard library? Well, in a way, they aren't using Python indeed. For example, most Python books tell only partly the truth in this case. > [...] > >>>> This is not a sign of decadence, but a very good promotional >>>> argument. >>> >>> But it's not required for the language to succeed. >> >> Today it is (except for very special-purpose languages). > > To put this differently, it's required if you want to succeed as a > language for the specific purpose of creating GUI > applications. I'd agree to that. But there are *lots* of other > application areas around, so limiting your definition of "success" > to that one field is very short-sighted. You have to take into account not only the number of application areas, but also their respective importance. I'm interested in a language with a big community. This is my definition of success. It has to do with the functionality I can expect (more contributors can create more modules and documentation) and with future-proofness. GUI applications seem to be the most attractive application type. This is not only true for commercial programming. When I look at the most agile projects on Sourceforge, almost all of them have a GUI. Therefore, GUI-aware languages attract much larger user bases, and so they cater my definition of being successful. > [...] By which measure C is still immensely popular, because of > the large number of older applications that are written in it that > are available - Python being one such. Legacy code is not a sign of success IMO because it implies a difficult future. > [...] I'd say Python has succeeded as a web development language, > and as a systems scripting language - and I've certainly missed > some. I don't think that Python should rely on these old strongholds. In the biggest bookstore of our region, there is one book about Zope but a whole bookself about PHP. And I've never used consciously a Python system script in contrast to dozens of Perl scripts. In contrast to PHP or Perl, I consider Python a general-purpose language. There is its future in my opinion. However, this area is much tougher, and you need a good GUI approach there. > [...] > >>> [...] Could it be that that's what you really want - someone to >>> distribute Python bundled with an enterprise-class GUI library >>> and IDE? >> >> Well, a nice thing to have, but besides my point. > > Then you seem to have missed some of your own points. C++ > succeeded without having a standard GUI library. You claimed that > that success was because of a single distribution that included > the things you are looking for. Why can't the same thing work for > Python? I just didn't say that it couldn't work. But I don't think it'll happen, that's all. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From mwm at mired.org Fri Jul 8 00:33:13 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 08 Jul 2005 00:33:13 -0400 Subject: question about introspection using inspect module References: <5vll4ihfvt.fsf@akron.bmi.ohio-state.edu> <5vr7eafimo.fsf@akron.bmi.ohio-state.edu> Message-ID: <86k6k1vrw6.fsf@bhuda.mired.org> Benjamin Rutt writes: > what I am actually trying to do is to build a database of Python > modules. so then later, I can write a tool in my favorite editor > (Emacs) to invoke some forms of completion against this database > (e.g. os.remov or socket. to see a list of all socket module > definitions). The problem with that is that Python is dynamic, so the list of completions may change over time. Not very likely, I know, but still... Have you considered writing this tool in Python, with Pymacs ? That way, you could get the list at runtime with a dir(module). http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From vibtrip at yahoo.com Tue Jul 5 12:17:51 2005 From: vibtrip at yahoo.com (Vibha Tripathi) Date: Tue, 5 Jul 2005 09:17:51 -0700 (PDT) Subject: Python Regular Expressions: re.sub(regex, replacement, subject) Message-ID: <20050705161752.44433.qmail@web53901.mail.yahoo.com> Hi Folks, I put a Regular Expression question on this list a couple days ago. I would like to rephrase my question as below: In the Python re.sub(regex, replacement, subject) method/function, I need the second argument 'replacement' to be another regular expression ( not a string) . So when I find a 'certain kind of string' in the subject, I can replace it with 'another kind of string' ( not a predefined string ). Note that the 'replacement' may depend on what exact string is found as a result of match with the first argument 'regex'. Please let me know if the question is not clear. Peace. Vibha ======= "Things are only impossible until they are not." __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From spike666 at mac.com Sat Jul 9 23:30:04 2005 From: spike666 at mac.com (spike grobstein) Date: 9 Jul 2005 20:30:04 -0700 Subject: importing files from a directory Message-ID: <1120966204.900591.212980@g44g2000cwa.googlegroups.com> I'm a total Python newbie, so bear with me here... I'm writing a program that has a user-configurable, module-based architecture. it's got a directory where modules are stored (.py files) which subclass one of several master classes. My plan is to have the program go into the folder called "Modules" and load up each file, run the code, and get the class and append it to an array so I can work with all of the objects later (when I need to actually use them and whatnot). What I'm currently doing is: import os print "Loading modules..." mod_dir = "Modules" module_list = [] #empty list... dir_list = os.listdir(mod_dir) for item in dir_list: # strip off the extensions... if (item == "__init__.py"): continue elif (item[-3:] == '.py'): mod_name = item[:-3] elif (item[-4:] == '.pyc'): mod_name = item[:-4] else: continue print "Loading %s..." % mod module_list.append(__import__("Modules.%s" % mod)) print "Done." it works more or less like I expect, except that... A. the first time it runs, blah.py then has a blah.pyc counterpart. When I run the program again, it imports it twice. Not horrible, but not what I want. is there any way around this? B. module_list winds up consisting of items called 'Modules.blah' and I'd like to have just blah. I realize I could say: my_module = __import__("Modules.%s" % mod) module_list.append(getattr(my_module, mod)) but... is there a better way to accomplish what I'm trying to do? tia. ...spike From markturansky at gmail.com Tue Jul 5 23:25:47 2005 From: markturansky at gmail.com (markturansky at gmail.com) Date: 5 Jul 2005 20:25:47 -0700 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? Message-ID: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> I'd like to dynamically find and invoke a method in a Python CGI. In javascript, the running script is 'this' (Python's 'self'), except that 'self' is not defined. I want to do this: var m = this["MethodName"]; //where the method name is passed via an http variable m(); //this invokes a method in javascript How do I do the same in python? self["MethodName"] fails... From tjreedy at udel.edu Sun Jul 10 19:30:58 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jul 2005 19:30:58 -0400 Subject: Cat and Mouse (wes Re: Efficiency of using long integers to hold bitmaps) References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> <42D1A678.1040705@v.loewis.de> Message-ID: ""Martin v. L?wis"" wrote in message news:42D1A678.1040705 at v.loewis.de... > Right. OTOH, I notice a frequent game of Katze und Maus (cat and mouse?) Yes, apparently with the same idiomatic meaning, as you decribe the game here perfectly. TJR From cam.ac.uk at mh391.invalid Sat Jul 16 04:42:54 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 16 Jul 2005 09:42:54 +0100 Subject: HTML expect in python In-Reply-To: <7uWdnWpzxZCnDUXfRVn-vQ@comcast.com> References: <7uWdnWpzxZCnDUXfRVn-vQ@comcast.com> Message-ID: D H wrote: > See the mechanize module: http://wwwsearch.sourceforge.net/mechanize/ I second this, a very useful module. I've unfortunately had to change it a little to deal with inevitably bad HTML supplied by web sites. -- Michael Hoffman From sybrenUSE at YOURthirdtower.com.imagination Mon Jul 4 08:44:49 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 4 Jul 2005 14:44:49 +0200 Subject: Unicode drives me crazy... References: Message-ID: fowlertrainer at citromail.hu enlightened us with: > I want to get the WMI infos from Windows machines. > I use Py from HU (iso-8859-2) charset. Why not use Unicode for everything? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From peter at somewhere.com Fri Jul 1 03:22:24 2005 From: peter at somewhere.com (Peter Maas) Date: Fri, 01 Jul 2005 09:22:24 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) In-Reply-To: References: Message-ID: Simon Brunning schrieb: > Sibylle Koczian needs to sort part of a list. His first attempt made > the natural mistake - sorting a *copy* of part of the list: I think it was _her_ first attempt. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From devnull at joreybump.com Sun Jul 10 09:02:23 2005 From: devnull at joreybump.com (Jorey Bump) Date: Sun, 10 Jul 2005 13:02:23 GMT Subject: Yet Another Python Web Programming Question References: <1120959373.895552.161480@f14g2000cwb.googlegroups.com> Message-ID: Daniel Bickett wrote in news:mailman.1556.1120970289.10512.python-list at python.org: > I neglected to mention an important fact, and that is the fact that I > am limited to Apache, which elminates several suggestions (that are > appreciated none-the-less). "Limited to Apache" is not the same as "using apache in a restricted environment", so we may need more clarification. If you are looking for a solution that sits on top of apache somehow, and you have system administrative access, there are a lot of choices, including ones that use mod_python. If something is not intended to interface directly with apache, it can still be proxied through apache while it runs on an alternate local port (a standalone app with an embedded web server, for example). If you mean that you're in a typical hosted environment with insufficient privileges to install or configure much of anything, you might be stuck with CGI. Since you mention in your original post that you have a folder in your home directory that's in sys.path, your provider is trying to do something to support python applications (hopefully, the path is specific to your virtual host, to avoid namespace collisions). In any case, if this was done to support mod_python, you can meet some of your criteria with mod_python.publisher, but you will almost certainly want to use a staging platform to develop your apps beforehand, since it is necessary to either restart apache or touch imported modules after editing. BTW, this is how I use Python for web applications myself: Each virtual host gets a special directory prepended to the PYTHONPATH, in which the bulk of my applications are created as packages. Then I use mod_python.publisher to publish single modules that serve as interfaces, converting values from requests and passing them on to the packages, which I try to make web agnostic (in fact, I develop most of the backend code locally before even trying it out on the web, so I can use it in other application domains). I've looked at other offerings, but as soon as I see proprietary markup or commands embedded in HTML, I lose interest, so I feel your pain. From jbellis at gmail.com Sat Jul 9 19:26:00 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 9 Jul 2005 16:26:00 -0700 Subject: Yet Another Python Web Programming Question In-Reply-To: References: Message-ID: <1120951560.056334.163210@g14g2000cwa.googlegroups.com> Daniel Bickett wrote: > He would read the documentation of Nevow, Zope, and Quixote, and would > find none of them to his liking because: > > * They had a learning curve, and he was not at all interested, being > eager to fulfill his new idea for the web app. It was his opinion that > web programming should feel no different from desktop programming. If you're coming from a PHP background, you'll find Spyce's learning curve even shallower. http://spyce.sourceforge.net -Jonathan From rkern at ucsd.edu Sun Jul 17 09:26:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 17 Jul 2005 06:26:39 -0700 Subject: Tuples in function argument lists In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I'm trying to understand the use of tuples in function argument lists. > > I did this: > >>>>def tester(a, (b,c)): > > ... print a, b, c > ... > >>>>tester(1, 2) > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in tester > TypeError: unpack non-sequence > > That was obvious result. > >>>>tester(1, (2, 3)) > > 1 2 3 > >>>>tester('ab', 'ab') > > ab a b > > And so were those. > > Then I tried this: > >>>>def tester(a, (b,c)=None): > > ... if (b,c) is None: > ... print a, None > ... else: > ... print a, b, c > > Needless to say, it did not do what I expected it to do. I didn't expect > it to either :-) > > I tried looking at the language reference here: > > http://docs.python.org/ref/function.html > > but I can't seem to find anything in their that says that tuples-as-args > are legal. Am I misreading the docs, or is this accidental behaviour that > shouldn't be relied on? Tuples-as-arg are legal. Tuple-as-keyword, too *if* the default value is something that can actually unpack to a tuple. A default of None is...silly. In [6]: def tester(a, (b,c)=(1,2)): ...: print a,b,c ...: In [7]: tester(1) 1 1 2 Tuple-as-arg is probably pretty safe. Tuple-as-keyword, possibly not-so-much. > Does anyone use this behaviour, and if so, under what circumstances is it > useful? import math def distance((x1,y1), (x2,y2)): return math.sqrt((x2-x1)**2 + (y2-y1)**2) distance(point1, point2) Personally, I prefer to explicitly unpack the tuple in the function body. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Thu Jul 28 04:15:26 2005 From: http (Paul Rubin) Date: 28 Jul 2005 01:15:26 -0700 Subject: Problems with permissions etc References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> <1122534295.713767.61190@o13g2000cwo.googlegroups.com> Message-ID: <7xu0if5otd.fsf@ruckus.brouhaha.com> "Frank Millman" writes: > My reasons for wanting the mac address are nothing to do with security. > I have in mind a retail point-of-sale situation, where I want to record > which transactions took place at which point-of-sale. I hope that, in > this context, my use of the mac address will be safe enough. Don't count on it. There was a widely publicized exploit at some big retail chain (maybe Target) when they did something like that over a wifi network a year or so ago. Attackers with the right gear had themselves a party. If you're moving data that represents real-world money, you have to assume someone will launch sophisticated attacks to get at it. From jepler at unpythonic.net Tue Jul 5 14:21:26 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 5 Jul 2005 13:21:26 -0500 Subject: resume upload In-Reply-To: References: Message-ID: <20050705182125.GA19195@unpythonic.net> probably by using REST. This stupid program puts a 200 line file by sending 100 lines, then using REST to set a resume position and sending the next 100 lines. import getpass, StringIO, ftplib lines = ["Line %d\n" % i for i in range(200)] part1 = "".join(lines[:100]) part2 = "".join(lines[:100]) f = ftplib.FTP('server', 'username', 'password') f.debugging = True f.sendcmd('CWD /tmp') f.storbinary("STOR example", StringIO.StringIO(part1)) f.putcmd('REST %d' % len(part1)) resp = f.getresp(); if resp[0] != '3': raise ftplib.error_reply, resp f.storbinary("STOR example", StringIO.StringIO(part2)) f.quit() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cam.ac.uk at mh391.invalid Wed Jul 27 14:44:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 27 Jul 2005 19:44:42 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Ron Adam wrote: > In all current cases, (that I know of), of differing types, '+' raises > an error. Not quite: >>> "hello " + u"world" u'hello world' >>> 4.5 + 5 9.5 > Question: Is a path object mutable? No. This should answer the rest of your questions. -- Michael Hoffman From farcepest at gmail.com Sun Jul 3 09:10:26 2005 From: farcepest at gmail.com (Andy Dustman) Date: 3 Jul 2005 06:10:26 -0700 Subject: Python, mysql, floating point values question References: Message-ID: <1120396226.630353.128500@o13g2000cwo.googlegroups.com> Use DECIMAL columns with MySQLdb-1.2.0 and Python-2.4 and you should get values back using Python's new decimal type. http://docs.python.org/whatsnew/node9.html This avoids floating point inaccuracies. From a.carl at ngc.com Fri Jul 8 11:05:41 2005 From: a.carl at ngc.com (Carl, Andrew) Date: Fri, 8 Jul 2005 08:05:41 -0700 Subject: Python Windows Install Problem (Error #2755) Message-ID: <8AB7DFF4B7187C43B0C93FA2D55E5B8C3064D8@xcgca210.northgrum.com> > Please find attached a PDF file (removed due to size) containing > (2) print-screen images of an error (Code # 2755) occuring during > attempted installation of python for windows, version 2.4.1 (on PC > using MS2000). Any help would be appreciated! > > Thanks, Andy Carl -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at thomas-lotze.de Thu Jul 14 07:10:28 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Thu, 14 Jul 2005 13:10:28 +0200 Subject: Frankenstring References: Message-ID: Peter Otten wrote: > Not clumsy, just slow. As you wish ;o) I didn't mean clumsy as in "clumsy looking Python code" anyway, rather as in "clumsy to use the Python machinery for operations that are straight-forward and efficient in C, in which language str and cStringIO are implemented already". > I hope you'll let us know how much faster your > final approach turns out to be. I'm pretty convinced that implementing an algorithmically nice state machine that goes through a string char by char won't get any faster than using s[index] all the time unless I do a frankenstring in C. Failing that, a more pragmatic approach is what Andreas suggests; see the other subthread. > By the way, I'll consider anything that > doesn't implement seek() and tell() cheating :-) An implementation of frankenstring would have to have seek and tell, that's the point of doing it. But for half-way simple state machines, hiding the index handling in a Python class that slows things down it just not worth it. Doing index += 1 here and there is fine if it happens only half a dozen times. I know it's not beautiful, that's why I started this thread ;o) -- Thomas From hancock at anansispaceworks.com Fri Jul 1 01:17:54 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 00:17:54 -0500 Subject: Speaking of list-comprehension? In-Reply-To: References: Message-ID: <200507010017.54637.hancock@anansispaceworks.com> On Thursday 30 June 2005 10:13 pm, Chinook wrote: > >>> ta = [5, 15, 12, 10, 9] > >>> for i in range(len(ta)): > ... if ta[i] >= 10: > ... ta[i] -= 10 > ... else: > ... ta[i] += 10 It's not exactly the same in that it doesn't change values in place, but this is similar if you are only interested in the values: ta = [t>=10 and t-10 or t+10 for t in ta] (this rebinds ta, so if you had a former reference to ta, it won't be changed by this code). In general, I don't think in-place operations are in the domain of list comprehensions, since they are expressions. I might be able to mangle something into doing it, but it's probably a bad idea anyway. I think your loop is stylistically fine as is (if you need to change the list in place). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ed at leafe.com Sun Jul 31 21:17:28 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 21:17:28 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <1122839323.736894.74620@f14g2000cwb.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <1122839323.736894.74620@f14g2000cwb.googlegroups.com> Message-ID: <200507312117.28104.ed@leafe.com> On Sunday 31 July 2005 15:48, Kay Schluehr wrote: > Ed promised to support many GUI toolkits I promised nothing of the sort. I said that we had designed our UI layer to be toolkit-agnostic, with the design goal of making choice of UI toolkit irrelevant. I also said that we recognize the sheer size of such a task, and have no current plans to support any toolkit besides wxPython. There is a difference in designing a project to make something *possible*, and promising to implement all those possibilities. -- -- Ed Leafe -- http://leafe.com -- http://dabodev.com From philippe at philippecmartin.com Thu Jul 7 01:37:30 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 07 Jul 2005 05:37:30 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> <1120636418.166800.42290@o13g2000cwo.googlegroups.com> <1120642040.109796.212450@o13g2000cwo.googlegroups.com> Message-ID: ???? Almost sounds like a racist comment - sorry if I misunderstood Antoon Pardon wrote: > Op 2005-07-06, Michele Simionato schreef : >> Fuzzyman: >>> So Lisp is for really good programmers, and Python is for >>> mediocre programmers ? >> >> >> Python is *also* for mediocre programmers. I see this as a >> strength, not as a weakness. > > But sometimes I get the impression people want it to evolve > so it is only for mediocre programmers. > From santafefrank at cybermesa.com Sun Jul 3 09:19:39 2005 From: santafefrank at cybermesa.com (Frank LaFond) Date: Sun, 03 Jul 2005 07:19:39 -0600 Subject: debugger? In-Reply-To: References: Message-ID: <42C7E5EB.5080302@cybermesa.com> You might also look at Boa. http://boa-constructor.sourceforge.net/ While I haven't tried all the things on your list, I've been able to do all the things I've wanted to do in the debugger. It is also an IDE for wxPython, so it works well for that, but I don't know about other GUI libraries. Qiangning Hong wrote: > ...The debugger should meet _most_ of the following > requirements: > > 1. can debug wxPython applications (and other GUI lib). > 2. an intuitive way to set/clear/enable/disable breakpoints. > 3. can set conditional breakpoints (i.e. break when some condition satisfied). > 4. variable watch list, namescope watching (local, global) > 5. evaluate expression, change variable values, etc within debugging. > 6. change the running routine, (i.e. go directly to a statement, skip > some statements, etc) > 7. clever way to express objects, not just a string returned by repr() > 8. perform profiling > 9. a clear interface. > 10. cross-platform. > 11. free, or better, open source. > > What debugger will you suggest? > Or what more polish feature you want to see in an ideal python > debugger? -- hope this thread will help IDE developers to fill their > todo list with some shining ideas :) > Frank LaFond http://www.effectiveqa.com From grig.gheorghiu at gmail.com Thu Jul 14 15:54:39 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 14 Jul 2005 12:54:39 -0700 Subject: Native ODBC access for python on linux? In-Reply-To: References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> Message-ID: <1121370879.773875.55240@f14g2000cwb.googlegroups.com> I concur with Larry. I find that by properly abstracting the database connection code in my own class, I can then use any DB-API-compliant Python module to connect to a variety of databases. I use for example cxOracle to connect to Oracle and kinterbasdb to connect to firebird. I haven't tried connecting to MySQL natively yet, but I don't think it would be any different. Grig From pwatson at redlinepy.com Sun Jul 31 11:38:08 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 31 Jul 2005 10:38:08 -0500 Subject: Enumerate registered codecs Message-ID: <3l49j2F10qginU1@individual.net> I see the list of standard encodings in Python 2.4.1 documentation section 4.9.2. Is there a method to enumerate the registered codecs at runtime? From gsakkis at rutgers.edu Fri Jul 8 15:26:06 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Jul 2005 12:26:06 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> <86oe9dvs6d.fsf@bhuda.mired.org> <86wto1tfnc.fsf@bhuda.mired.org> Message-ID: <1120850766.790091.281630@g49g2000cwa.googlegroups.com> "Mike Meyer" wrote: > I only know one compiler that punts after the first error. Even with > lots of cheap computing power, it's still very annoying. > > Come to think of it, Python does this, doesn't it? For some reason, > that doesn't annoy me. Maybe because I don't think of it as a > edit/compile/run cycle, but as an edit/run cycle, and I expect those > stop after one errror. Yes, the very short edit/run cycle is one reason. A second one is that syntax errors are in general a pretty small percentage compared to runtime errors (at least for anyone that has been using python for a week or more), so even if the syntax checker did report all of them at once it wouldn't make much difference in the overall debugging time. Third, at least one editor (Komodo) reports syntax error on the fly as you edit and this helps saving a few seconds now and then. George From pyweek1 at mechanicalcat.net Thu Jul 21 02:41:54 2005 From: pyweek1 at mechanicalcat.net (pyweek1 at mechanicalcat.net) Date: Thu, 21 Jul 2005 16:41:54 +1000 Subject: Python Game Programming Challenge update Message-ID: <200507211641.54141.pyweek1@mechanicalcat.net> There's only one week to go before registration opens for the first Python Game Programming Challenge (also known as PyWeek). That means there's only (checks website) 37 days to go before the challenge starts! If you have a Python-based graphics, sound, music or game library that you'd like to use or promote in the challenge, then you've only got 7 days to make it public. Write some simple API docs and submit it to . Couldn't be easier! For those who came in late, the PyWeek challenge: 1. Invites all Python programmers to write a game in one week from scratch either as an individual or in a team, 2. Must be challenging and fun, 3. Entries must be developed during the competition, and must incorporate some theme decided at the start of the competition, 4. Will hopefully increase the public body of python game tools, code and expertise, 5. Will let a lot of people actually finish a game, and 6. May inspire new projects (with ready made teams!) ----------------------------------------------------------- Visit the PyWeek website: http://www.mechanicalcat.net/tech/PyWeek/ From exarkun at divmod.com Thu Jul 21 09:00:05 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 09:00:05 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: Message-ID: <20050721130005.26278.1638397423.divmod.quotient.15430@ohm> On Thu, 21 Jul 2005 00:51:45 -0400, Christopher Subich wrote: >Jp Calderone wrote: > >> In the particular case of wxWidgets, it turns out that the *GUI* blocks >> for long periods of time, preventing the *network* from getting >> attention. But I agree with your position for other toolkits, such as >> Gtk, Qt, or Tk. > >Wow, I'm not familiar with wxWidgets; how's that work? wxWidgets' event loop doesn't differentiate between two unrelated (but similar sounding) concepts: blocking arbitrary input from the user (as in the case of modal dialogs) and blocking execution of code. When you pop up a modal dialog, your code will not get another chance to run until the user dismisses it. Similarly, as long as a menu is open, your code will not get to run. Jp From rrr at ronadam.com Wed Jul 6 21:09:58 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 01:09:58 GMT Subject: Use cases for del In-Reply-To: <11cokv26rabdndf@corp.supernews.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-07-06, Ron Adam wrote: > > >>It would be a way to set an argument as being optional without actually >>assigning a value to it. The conflict would be if there where a global >>with the name baz as well. Probably it would be better to use a valid >>null value for what ever baz if for. If it's a string then "", if its a >>number then 0, if it's a list then [], etc... > > > Except those aren't "null values" for those types. 0 is a > perfectly good integer value, and I use it quite often. There's > a big difference between an "invalid integer value" and an > integer with value 0. Why would you want to use None as an integer value? If a value isn't established yet, then do you need the name defined? Wouldn't it be better to wait until you need the name then give it a value? From edvard+news at majakari.net Thu Jul 14 02:05:41 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Thu, 14 Jul 2005 09:05:41 +0300 Subject: all possible combinations References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> Message-ID: <87irzdexca.fsf@titan.staselog.com> John Machin writes: >>>My list is not arbitrary. I'm looking for all 'combinations' as I >>>originally posted. Order does not matter to me... just all possibilities. >> That's good, since you only need combinations of "a", "b" and "c" the > "You keep using that word. I do not think it means what you think it means." Inconceivable! -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! "Debugging is twice as hard as writing the code in the firstplace. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian W. Kernighan From jeremy at emperorlinux.com Fri Jul 29 13:18:10 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Fri, 29 Jul 2005 13:18:10 -0400 Subject: Wheel-reinvention with Python (was: Ten Essential Development Practices) In-Reply-To: <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> Message-ID: <1122657490.4202.17.camel@localhost.localdomain> On Fri, 2005-07-29 at 17:59 +0200, Torsten Bronger wrote: > Hall?chen! > > Michael Hoffman writes: > > > Dark Cowherd wrote: > > > >> GUI, Web development, Application Framework - it is shambles. > > > > Yeah, I agree. When I finally make that GUI application I still > > don't know whether I am going to use wx or PyGTK. > > I agree, too, although I can only talk about GUI toolkits. At first > one thinks "well, perfect, I have the choice between four Four? 1. wx 2. PyGTK 3. Tk (Are you including this one even?) 4. ??? Of the few I can think of, only one would qualify as great. :) >>wink<< > great GUI > systems". However, except for very special demands, there is no > clear winner. You start learning one, and immediately wonder > whether the other might be better. Although it sounds paradoxical, > this can be quite frustrating. After all, most of us don't have the > energy or motivation to test all candidates thoroughly. > > Besides, development resources are shared between all projects. > This is especially sad with regard to IDEs. There are even more > IDEs/dialog editors/widget builders than Toolkits, none of them > being mature. > > >> Is there some place to discuss topics like this? Is this the right place? > > > > Sure, although you might want to start a new thread. ;) > > At least a new subject ... > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > -- > http://mail.python.org/mailman/listinfo/python-list From mwm at mired.org Wed Jul 6 23:35:53 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 06 Jul 2005 23:35:53 -0400 Subject: Favorite non-python language trick? References: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> <86psu2410u.fsf@bhuda.mired.org> <86ll4q3q0m.fsf@bhuda.mired.org> <1120689545.113419.318680@g14g2000cwa.googlegroups.com> Message-ID: <86y88juw2u.fsf@bhuda.mired.org> "Shai" writes: > They're called "Special vars", and you need to define them (unlike > local LISP variables, which behave essentially like Python vars), but > then you use them just like other vars (that is, you usually bind them > with LET). This is the first I hear about them being ill-considered in > LISP; http://www.gigamonkeys.com/book/ is a recently published LISP > book which recommends them. I don't know about Scheme, but I think it > does have them. I'm pretty sure scheme doesn't have dynamically bound variables. I just went through r5rs to check, and couldn't find them. > dynamic x=10 > def bar(): > print x > > I specified the syntax as I did, specifically to make it match the > current definition of globals, which "enjoys" the same problems you > noted with my dynamics. This looks different from what I understood before. You're now declaring the variable dynamic in the global scope, rather than in the function that makes it dynamic. This is a *much* more palatable situation. Globals are lexically scoped. As such, you can find the defintion of the variable by examining the module that includes the function. Yes, other modules can reach into your module and change them - but you can find those, because they reference your module by name. A dynamic variable declared so in a function has no such clue associated with it. If the variable is declared dynamic in the module of the enclosed function, that provides a contextual clue. Of course, you can do pretty much anything you want if you're willing to grovel over the guts of the environment enough, but some things shouldn't be easy. > While I didn't write it explicitly, if both LISP and Python globals are > to be followed, the dynamic x should somehow be defined in the scope of > its module. On second thought, this means "dynamic" _must_ be added in > the variable definition, for foo.foogle will simply access it as > "othermodule.x", which doesn't differentiate globals from dynamics. > > Either way, Python as it is now allows foo.foogle to change x even > without dynamic variables; it is accessible as barmodule.x. bar() > should expect to have other functions mess with its globals, and > dynamics are no different. The question is, how hard is it to find the other people who are messing with bar()'s globals? Normal usage with the current situation makes it fairly starightforward. How does adding dynamicly bound variables change this? Of course, if you add the requirement that the variable be tagged in the scope of the module, you're making things a lot better. That way, readers of the module know that they need to look back along the call chain for functions that use such variables. That makes them much saner to find. >> Instead of dynamic meaning "all references to the named variable(s) >> will be dynamic until this function exits", have it mean "the named >> variable(s) will be dynamic in this function." Whether it should only >> check local variables in the calling routines, check local + global, >> or check for all free variables, is an open question. >> >> I.e. - your example would be written: >> >> x = 10 >> def foo(): >> dynamic x >> print x >> >> def bar(): >> x = 11 >> foo() >> >> def baz(): >> bar() # prints 11 >> foo() # Possibly an error? >> > > This introduces the same problem you noted with my original proposal, > but in reverse: Now, in bar(), you define and use a local variable, and > suddenly some library function changes its behavior misteriously. True. That pretty much kills my proposal. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From markturansky at gmail.com Thu Jul 7 00:01:46 2005 From: markturansky at gmail.com (markturansky at gmail.com) Date: 6 Jul 2005 21:01:46 -0700 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? In-Reply-To: References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: <1120708906.383844.312160@o13g2000cwo.googlegroups.com> 'self' is not defined in this circumstance. The poster above (using 'locals()') has it right. From jepler at unpythonic.net Sun Jul 31 09:32:05 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 31 Jul 2005 08:32:05 -0500 Subject: Newb: Telnet 'cooked data','EOF' queries. In-Reply-To: <42ECC473.4050307@tesco.net> References: <42ECC473.4050307@tesco.net> Message-ID: <20050731133201.GA12776@unpythonic.net> On Sun, Jul 31, 2005 at 01:30:43PM +0100, glen wrote: > Could someone explain what "cooked data" is. The telnet protocol contains special sequences which are interpreted by the telnet client or server program. These are discussed in the telnet RFC, which is RFC854 according to the telnetlib docstring. "Cooked" data is data after these special sequences are removed. > Also when trying read_all() the program seems to lock up, which I assume > is because it is waiting for an EOF, but 'when' is an EOF received. As far as I know, the only EOF in telnet is when the other side closes the socket. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVETHIScyber.com.au Tue Jul 5 19:46:05 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 06 Jul 2005 09:46:05 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: On Tue, 05 Jul 2005 09:46:41 -0500, Terry Hancock wrote: > On Tuesday 05 July 2005 08:17 am, Steven D'Aprano wrote: >> Sorry, but you are mistaken. "lambda" is a _reserved_ word in the >> Python language, while "function" etc are not, but they are certainly >> part of the language. Try explaining what def and import do without >> using the words "function" or "module". Maybe you can do it, using >> circumlocutions, but it isn't easy, and costs clarity. > > This is still a relevant distinction. One relevant point is that I am > perfectly free to use, say, the Spanish or Chinese word to describe > "module" or "function", but the keywords "def" and "import" will > remain the same. No, that isn't relevant. That's just localisation. I'm also free to fork Python and change the keywords. [snip] > The "Python sense" is not arbitrary. There are very direct visual or > logical (i.e. INTUITIVE) connections between these words' *English* > meanings (not just mathematical, either) and their meanings in Python. I had NEVER even heard the word "tuple" before learning Python. I spent weeks mispelling it as "turple", and I finally had to look it up in a dictionary to see if it was a real English word. Out of the four English dictionaries in my house, none of them have the word. Let's dump tuple from the language too, its just "a stupid name for a list that can't change". Agreed? [snip] > Similarly, "decorate" is 'make more attractive by adding ornament, > colour, etc.' In Python, a "decorator" applies a wrapper to a function > to provide it with some additional functionality. Which is certainly NOT decoration, since the point of decoration is that it is not functional! Plain bathroom tiles are functional. Decorating them with leaves or flowers or patterns is not functional. [snip] > Now, if you are armed ONLY with the English definition, you will > possibly run into some trouble, because the programming usage is a > *specialization* of the term -- we strictly take only *one* of the > English definitions to apply, and we narrow its meaning a bit. Yes. Every specialization has its own jargon, and computer programming is no different. One of the things new programmers have to learn is the jargon. [snip] > "lambda" has no such advantage. Here's the *entire* gcide definition: Nonsense. All that means is that lambda in the programming sense is too specialized to make it into most ordinary dictionaries. Just like tuple. [snip] >> Think back to when you were a schoolboy at your first day of school. >> Unless you had a very unusual upbringing, you probably had never heard >> the word "function" before. > > Total BS. I knew the word "function" in it's English language sense, > probably by the time I was 6. I *know* my kids know it. Okay, maybe my memories of being five are faulty. But if not six, then five, or four, or three, or two. At _some_time_ function was entirely unknown to you, and you had to just learn it. [snip] >> You had to learn that word, discover what it means, and then it becomes >> familiar. You don't notice the process only because it happened so long >> ago, at an age that your brain was operating in "language acquisition >> mode" and picking up vocabulary at an incredible rate. > > If you're arguing that language is acquired rather than innate, you are > bludgeoning an obvious point. The point is that *jargon* should ideally > derive in a natural way from commonly-used language, That's a bonus, sure. It is an important rule to follow, but not at the expense of distorting the language: t = immutable_list(L) map(anonymous_function x: x+1, L) versus: t = tuple(L) map(lambda x: x+1, L) > if we want it to be > easy to acquire for people who don't learn programming between the ages > of 1 and 5 as we learn our native languages. Even in the 21st century, > I think this includes just about all of us. ;-) If they can't memorize one or two things, they aren't going to be much good at programming no matter how easy the language is to use. >> There is nothing about the word "string" that especially brings to mind >> "an array of bytes representing characters". The analogy of "string of >> characters" to "string of beads" breaks down as soon as you have >> multiple lines of text. > > Ah, but that's useful. "Strings" AREN'T "multiple lines of text" in the > computer's memory, are they? '\n' is just another bead. The "multiple > lines" is a representation, or way of laying out the beads. Very useful > distinction, and immediately driven by the choice of analogy. Who cares about the implementation details of how the bytes are laid out in the computer's memory? Unless you are programming in a low level language like C or assembly, this is entirely irrelevant. You have characters laid out along lines, and lines laid out in a second dimension. The natural way to work with text is something like this: for line in text: for word in line: # or character do_something() [snip] >> I won't say that the anonymous function meaning of lambda comes to my >> mind before the Greek letter, but it isn't very far behind, and rapidly >> catching up. (I use lambda a lot more than I speak Greek.) It wouldn't >> surprise me if one day I think of Python programming before the Greek >> letter, just as the world aleph brings to my mind the sense of infinity >> before the sense of it being a Hebrew letter. > > Then it is clearly *not you* who should be served by the naming scheme. > Anyone so deeply trained and experienced should be expected to adapt, > you have the wherewithall to do so. It is the new user for whom the > clarity of the jargon is so important. > > Personally, I find the term "anonymous function" to be a whole lot > clearer than "lambda" or "lambda function". Indeed, if asked what > "lambda" means, my reply is it's a "stupid name for an anonymous > function", and if my listener is less savvy "for a function that doesn't > have a name, because you only use it once". And any half-way experienced Python programmer will say, "What are you talking about?" add_one = lambda x: x+1 Yes, I know that the name "add_one" is not the same as the name for a function when you use def, but the function still has a name. The difference might be an important difference, but it is not one you care about unless you are doing introspection. > Having said that, I too will miss the *concept* of an anonymous > function, although I wouldn't mind at all if its name changed, or if it > were somehow integrated into the "def" keyword's usage. Def would be short for ... defend? defile? defer? defame? default? deflect? There's always *something* to learn. Why def instead of define? Because "easy to write" beats "instantly obvious to a beginner", if the word is used all the time and is easy to memorize. > Using backticks > or some other syntax delimiter also sounds promising, Ew, perl :-( > although we're sort of running out of them. ;-) -- Steven. From luis_XX at XXiname.com Sat Jul 23 13:58:47 2005 From: luis_XX at XXiname.com (Luis P. Mendes) Date: Sat, 23 Jul 2005 18:58:47 +0100 Subject: PostgreSQL & Python vs PHP Message-ID: <3kfaucFu3tlfU1@individual.net> Hi, I don't know anything about PHP and I'm initiating right now with PostgreSQL. Could someone tell me the pros and cons of assessing the PostgreSQL databases with Python vs. PHP? I will need to build a database that has to be assessed by a dozen clients via a web page in an intranet (possibly from outside, too). Is Python more used on the client side and PHP on the server side? I now Python, although I'm far from being an expert. Luis From cmedcoff at hotmail.com Sun Jul 17 21:43:00 2005 From: cmedcoff at hotmail.com (chuck) Date: 17 Jul 2005 18:43:00 -0700 Subject: stdin/stdout fileno() always returning -1 from windows service Message-ID: <1121650980.574867.244590@g44g2000cwa.googlegroups.com> I have found that sys.stdin.fileno() and sys.stdout.fileno() always return -1 when executed from within a win32 service written using the win32 extensions for Python. Anyone have experience with this or know why? From roy at panix.com Sun Jul 10 10:00:15 2005 From: roy at panix.com (Roy Smith) Date: Sun, 10 Jul 2005 10:00:15 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: aahz at pythoncraft.com (Aahz) wrote: > Using ``in`` saves a bytecode of method lookup on ``has_key()`` (which is > the correct spelling). You are right. My example is somewhat out of date w/r/t newer language features, and writing hasKey() instead of has_key() was just plain a mistake. Thanks for the corrections. From albert at compuscan.co.za Fri Jul 22 11:12:20 2005 From: albert at compuscan.co.za (Albert Leibbrandt) Date: Fri, 22 Jul 2005 17:12:20 +0200 Subject: difficulty connecting to networked oracle database In-Reply-To: <1121965751.373621.193380@o13g2000cwo.googlegroups.com> Message-ID: <20050722151232.EB8311E4006@bag.python.org> >> As the other posters already mentioned, cx_Oracle is the way to go. I'm >> using it to connect to Oracle not only on Windows, but also on Solaris, >> Linux and AIX. >> Grig I can second that, I have been using python and cx_oracle for more than 3 years now Albert From cam.ac.uk at mh391.invalid Fri Jul 22 15:31:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 20:31:37 +0100 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > When files are opened through a "path" object -- e.g. > path('name').open() -- then file.name returns the path object that was > used to open it. Also works if you use file(path('name')) or open(path('name')). -- Michael Hoffman From barrynyc at gmail.com Sun Jul 10 14:10:06 2005 From: barrynyc at gmail.com (Barry) Date: Sun, 10 Jul 2005 14:10:06 -0400 Subject: bsddb environment lock failure -- resolved In-Reply-To: <759fdc8f050709215564c7c89b@mail.gmail.com> References: <759fdc8f050709215564c7c89b@mail.gmail.com> Message-ID: <759fdc8f050710111014c80143@mail.gmail.com> Upgrading db4 to db4-4.1.25-14.rpm seems to have take care of this. On 7/10/05, Barry wrote: > I have python2.4.1 installed on two machines: > -- one is Fedora core 1, where the bsddb module works fine > -- one is Redhat ES 3.0, and I installed mysql 4.1 (and > mysql-python2.1) after putting the newer python on the machine. > > python2.2, which came with Redhat ES, works fine, so I suppose I > messed up the build. > > I much appreciate any insight in how to fix this. > > Barry > > Here are some details: > > When trying to open (or create) a db, I get this error > > File "/opt/Python-2.4.1/Lib/bsddb/__init__.py", line 285, in hashopen > e = _openDBEnv() > File "/opt/Python-2.4.1/Lib/bsddb/__init__.py", line 339, in _openDBEnv > e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | > db.DB_INIT_MPOOL) > bsddb._db.DBError: (38, 'Function not implemented -- process-private: unable to > initialize environment lock: Function not implemented') > > I tried rebuilding python2.4.1, but 'make test' shows bsddb errors. > > First, there is: > > test_bsddb3 skipped -- Use of the `bsddb' resource not enabled > > test_whichdb shows the environment lock error > > At the end, it's anydbm, bsddb, shelve, and whichdb failed. > > I don't which of the differences in setup are important here, but both > python.2.4.1 are installed in /opt > > both have libdb-4.1, although slightly different: > > The Fedora machine has libdb from db4-4.1.25-14.rpm > The Redhat, from db4-4.1.25-8.1 -- this one also has libdb_cxx-3.1.so > - libdb_cxx-3.3.so > From grante at visi.com Sat Jul 2 22:29:14 2005 From: grante at visi.com (Grant Edwards) Date: Sun, 03 Jul 2005 02:29:14 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1120354245.338107.113140@o13g2000cwo.googlegroups.com> Message-ID: <11cejbqk07q2b6c@corp.supernews.com> On 2005-07-03, Darkfalz wrote: > I find this amusing even when they have the most cockney, ghetto > English accent, Americans still find it "sophisticated". No they don't. Americans have pretty much the same stereotypes about regional English accents that the average Brit does. -- Grant Edwards grante Yow! Do you guys know we at just passed thru a BLACK visi.com HOLE in space? From M.Waack at gmx.de Mon Jul 25 04:37:16 2005 From: M.Waack at gmx.de (Mathias Waack) Date: Mon, 25 Jul 2005 08:37:16 GMT Subject: Web-Forms References: <1122028683.587356.288270@g43g2000cwa.googlegroups.com> Message-ID: <0x1Fe.5$1E1.264@se2-cb104-9.zrh1.ch.colt.net> Michele Simionato wrote: > Use twill:http://www.idyll.org/~t/www-tools/twill.html I'll do so. Twill is great, anyway thanks for all other responses too. Mathias From godwinburby at rediffmail.com Wed Jul 13 02:00:05 2005 From: godwinburby at rediffmail.com (Godwin) Date: 12 Jul 2005 23:00:05 -0700 Subject: Web App like Google References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> Message-ID: <1121234405.159361.19430@g49g2000cwa.googlegroups.com> Thanks for informing me about NLTK. I'll certainly look into it and other options. Hope my dream doesn't go into the graves. Godwin Burby From steven.bethard at gmail.com Wed Jul 13 10:25:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jul 2005 08:25:00 -0600 Subject: set and frozenset unit tests? In-Reply-To: References: <3jhaoaFq2kajU1@individual.net> Message-ID: Jacob Page wrote: > Oye, there's quite a number of set and frozenset features that aren't > well-documented that I now need to implement. What a fun chore! It would be a great help if you could submit appropriate documentation patches for the areas you don't think are well-documented: http://sourceforge.net/tracker/?group_id=5470&atid=305470 STeVe From http Sun Jul 31 04:08:03 2005 From: http (Paul Rubin) Date: 31 Jul 2005 01:08:03 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: <7xd5ozv1ng.fsf@ruckus.brouhaha.com> Cliff Wells writes: > application. End users shouldn't need to worry about installing third > party packages (or even Python for that matter). Tools such as py2exe > and Inno installer make this pretty simple on Windows, and py2app on > OS/X accomplishes the same. It should be irrelevant to end users what > libraries or tools you use to develop the app. What if I want to be able to write multi-platform applications without having to deal with OS-specific packaging schemes for every OS that I want to run on? Even if I only want to run on Linux, I don't see how to package a wxPython application to minimize end user hassle. The only realistic GUI's to use are Tkinter or HTTP/HTML over a local socket talking to a user-provided web browser. From richardlewis at fastmail.co.uk Wed Jul 6 12:21:35 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Wed, 06 Jul 2005 17:21:35 +0100 Subject: Tkinter grid layout In-Reply-To: References: Message-ID: <1120666895.4753.237877752@webmail.messagingengine.com> On Wed, 06 Jul 2005 17:36:01 +0200, "Eric Brunel" said: > On Wed, 06 Jul 2005 11:44:55 +0100, Richard Lewis > wrote: > > > Hi there, > > > > I've got a tree control in Tkinter (using the ESRF Tree module) but I > > can't get it to layout how I want it. > > > > I'd like to have it so that it streches north/south (anchored to the top > > and bottom), is of a fixed width and is anchored to the left hand side. > > Here's my code (its derived from one of the examples from the ESRF web > > site): > > > > class MainWindow(Frame): > [snip code] > > First of all, it is not a good idea to make your so-called window inherit > from Frame: a Frame is not a window in tk, but a generic container. > [....] > But basically, my advice would be: > - Never make your windows inherit from Frame; make them inherit from Tk > for the main window or from Toplevel for all other ones > - When you have resize problems, always check the whole widget hierarchy > from the actual window down to the widget showing the problem. The cause > is very often not on the widget itself, but on one of its containers. > And very sound advice it turns out to be! I've changed my MainWindow class to inherit from Tk and now all the layout works fine. Thanks very much for your help! Cheers, Richard From peter at engcorp.com Thu Jul 7 18:25:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Jul 2005 18:25:21 -0400 Subject: threads and sleep? In-Reply-To: <1120678061.051033.230090@f14g2000cwb.googlegroups.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <1120625123.135496.318590@g44g2000cwa.googlegroups.com> <1120678061.051033.230090@f14g2000cwb.googlegroups.com> Message-ID: Jonathan Ellis wrote: > Peter Hansen wrote: >>I can't address the issue of whether or not "most" such projects require >>distributed locking, because I'm not familiar with more than half of >>such projects, as you appear to be. > > Your sarcasm is cute, I suppose, but think about it for a minute. If > the opposite of what I assert is true, why would even the mainstream > press be running articles along the lines of "multicore CPUs mean > programming will get tougher because locking is hard to get right and > you can't just scale by relying on the cpu to run your one > thread/process really fast anymore." > > http://www.gotw.ca/publications/concurrency-ddj.htm for one example. Thanks, but then let me remove the last (sarcastic) part, the "as you appear to be", and just leave the rest as is. I am *not* familiar with this issue, but nevertheless still feel that the OP's problem does not involve any such locking, so although it's quite possible that you are correct, I have nothing more to add on the matter. If you think he needs locking, and that therefore multi-process stuff via Pyro might not work, he's probably the guy to talk to... I happen to feel it would probably work fine. -Peter From theller at python.net Tue Jul 5 15:06:14 2005 From: theller at python.net (Thomas Heller) Date: Tue, 05 Jul 2005 21:06:14 +0200 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: <1120589407.845466.261180@g14g2000cwa.googlegroups.com> Message-ID: mcherm at gmail.com writes: > Ralf W. Grosse-Kunstleve wrote: >> I often find myself writing:: >> >> class grouping: >> >> def __init__(self, x, y, z): >> self.x = x >> self.y = y >> self.z = z >> # real code, finally >> >> This becomes a serious nuisance in complex applications with long >> argument lists > > Yes... indeed it does. This is so common that there is a standard > idiom for handling it: > > def __init__(self, x, y, z): > self.__dict__.update(locals()) > > sometimes with modifications to avoid setting self.self. >> I am actually using a simple trick:: >> >> adopt_init_args(self, locals()) > > If the implementation is only 3-4 lines long (and a simpler > implementation can be), then is can simply be included inline with > every script that needs to use it. > >> - The ``adopt_init_args(self, locals())`` incantation is hard to >> remember and difficult to explain to new-comers. > > A better name would help with this. The need for locals() is > unavoidable. Ahem - sys._getframe() Thomas From devlai at gmail.com Fri Jul 1 12:44:11 2005 From: devlai at gmail.com (Devan L) Date: 1 Jul 2005 09:44:11 -0700 Subject: Regular Expression for pattern substitution In-Reply-To: References: Message-ID: <1120236251.006103.97030@g43g2000cwa.googlegroups.com> re.replace. I don't think there's any way to avoid it. Except maybe having an alias email address or a fake one. From tzot at sil-tec.gr Sat Jul 2 09:26:16 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 16:26:16 +0300 Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> <5aj2c11l5vl4qds031uj7ucikikcf7uvji@4ax.com> <42c60f3b.300522458@news.oz.net> Message-ID: On Sat, 02 Jul 2005 03:55:43 GMT, rumours say that bokr at oz.net (Bengt Richter) might have written: >Alt-spacebar, e, l, (uparrow/downarrow)*, Esc > (lower case L)--^ ^^^^^^^^^^^^^^^^^--does the scrolling. Esc ends the scrolling mode. Damn! it says Scroll in there in the system menu, doesn't it? Talk about blindness... >Seems to work for cmd.exe on NT4 XP too. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From spam.csubich+block at block.subich.spam.com Sun Jul 24 18:09:32 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 24 Jul 2005 18:09:32 -0400 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: Message-ID: <6kUEe.27888$TU.9583@bignews1.bellsouth.net> Soeren Sonnenburg wrote: > On Sat, 2005-07-23 at 23:35 +0200, Marc 'BlackJack' Rintsch wrote: >>Both operate on the lists themselves and not on their contents. Quite >>consistent if you ask me. > But why ?? Why not have them operate on content, like is done on > *arrays ? Because they're lists, not arrays. What do you propose that the following do: [1,2,3] + [4,5,6] [1,2] + [3,4,5] [1,2] + [{3:4,5:6}] dict_var_1.keys() + dict_var_2.keys() [g(3) for g in [f1 f2 f3] + [f4 f5 f6]] I point out that the idiom is + , not + . Operations on lists must deal with them as lists, not lists of any specific type. From news at NOwillmcguganSPAM.com Wed Jul 6 06:30:14 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 06 Jul 2005 11:30:14 +0100 Subject: frozenset question In-Reply-To: References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> Message-ID: <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> Qiangning Hong wrote: > On 7/6/05, Will McGugan wrote: > >>Hi, >> >>Are there any benefits in using a frozenset over a set, other than it >>being immutable? > > > A frozenset can be used as a key of a dict: Thanks, but I meant to imply that. I was wondering if frozenset was faster or more efficient in some way. Thinking back to the dark ages of C++, you could optimize things that you knew to be constant. Will -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From steve at REMOVETHIScyber.com.au Sat Jul 30 09:34:06 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 30 Jul 2005 23:34:06 +1000 Subject: Comparison of functions References: Message-ID: On Sat, 30 Jul 2005 08:13:26 -0400, Peter Hansen wrote: > Beginners should not be comparing lambdas. > > Neither should you. ;-) Actually, yes I should, because I'm trying to make sense of the mess that is Python's handling of comparisons. At least two difference senses of comparisons is jammed into one, leading to such such warts as these: >>> L = [] >>> L.sort() # we can sort lists >>> L.append(1+1j) >>> L.sort() # even if they include a complex number >>> L.append(1) >>> L.sort() # but not any more Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= Um, I didn't ask to compare complex numbers using comparison operators. I asked to sort a list. And please don't tell me that that sorting is implemented with comparison operators. That just means that the implementation is confusing numeric ordering with sort order. Then there is this: >>> 1 > 0 True >>> 1+0j == 1 True >>> 1+0j == 1 > 0 True >>> 1+0j > 0 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= I applaud that Python has got rich comparisons for those who need them. But by confusing the question "which comes first in a sorted list?" with "which is larger?", you get all sorts of warts like being unable to sort lists with some objects, while being able to make meaningless comparisons like ''.join >= [].append. I'm not sure what the solution to this ugly state of affairs is. I'm not even sure if there is a solution. But I'm willing to make a good effort to *look*, and even though you were joking, I don't appreciate being told not to. -- Steven. From littlejohn.75 at news.free.fr Mon Jul 18 18:06:55 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 18 Jul 2005 22:06:55 GMT Subject: J-Integra for COM (Java COM interoperability) References: <1121719181.408096.190110@g43g2000cwa.googlegroups.com> Message-ID: <42dc27ff$0$6693$626a14ce@news.free.fr> Le 18 Jul 2005 13:39:41 -0700, j-integra_support at intrinsyc.com a ?crit : snip > > J-Integra for COM Features: snip > > For a free evaluation, visit our website at > http://j-integra.intrinsyc.com/ > > Regards, > > Shane Sauer Q: What are the Vikings singing in the background ? A: Spam, spam, spam ! From cyril.bazin at gmail.com Tue Jul 12 05:33:57 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Tue, 12 Jul 2005 11:33:57 +0200 Subject: Trying to come to grips with static methods In-Reply-To: References: Message-ID: Ok, sorry, you are right Robert. What about this one: class Parser(object): def toParser(p): if type(p) == str: if len(p) == 1: return lit(p) return txt(p) return p toParser = staticmethod(toParser) This is meant to translate p to a parser if it's not one. 'lit' is a function that take a string of length 1 and return a parser of char. 'txt' is a function that take a string of any length and return a parser. I hope it is a better example! That one of the rare case I used static method in Python... Cyril On 7/12/05, Robert Kern wrote: > > Cyril Bazin wrote: > > (sorry, my fingers send the mail by there own ;-) > > > > Im my opinion, class method are used to store some functionalities > > (function) related to a class in the scope of the class. > > > > For example, I often use static methods like that: > > > > class Point: > > def __init__(self, x, y): > > self.x, self.y = x, y > > > > def fromXML(xmlText): > > x, y = functionToParseXMLUsingMinidomForExample(xmlText) > > return Point(x, y) > > fromXML = staticmethod(fromXML) > > > > Here, it is used to define some kind of second constructor... > > > > Note that class decorator can simplify the notation, but break the > > compatility with older Python... > > Huh? classmethod was introduced with staticmethod, and in fact, this use > case is exactly what classmethods are for, not staticmethods. > > In [2]: class Point(object): # <-- note inheritance from object > ...: def __init__(self, x, y): > ...: self.x, self.y = x, y > ...: def fromXML(cls, xmlText): > ...: x, y = parseXML(xmlText) > ...: return cls(x, y) > ...: fromXML = classmethod(fromXML) > ...: > > In [3]: class NewPoint(Point): > ...: pass > ...: > > In [4]: def parseXML(xmlText): > ...: return 1, 4 > ...: > > In [5]: p = NewPoint.fromXML('') > > In [6]: isinstance(p, NewPoint) > Out[6]: True > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ccalvert at pacbell.net Fri Jul 8 15:07:42 2005 From: ccalvert at pacbell.net (Charlie Calvert) Date: Fri, 08 Jul 2005 19:07:42 GMT Subject: Defending Python Message-ID: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> I perhaps rather foolishly wrote two article that mentioned Python as a good alternative language to more popular tools such as C# or Java. I encountered more resistance than I had expected. If someone who really knows a lot about Python would like to go over to the CodeFez website and defend Python a bit better than I can, that would be appreciated. The articles are called "The War of the Virtual Bills," and "Ranking Languages: Fear as a Career Move." Here are the links: http://www.codefez.com http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/135/RankingLanguagesFearasaCareerMove.aspx http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/134/TheWaroftheVirtualBills.aspx Thanks. - Charlie From tim.peters at gmail.com Wed Jul 13 23:16:27 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 13 Jul 2005 23:16:27 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae0507132016738a2c3a@mail.gmail.com> [Steven D'Aprano] > (All previous quoting ruthlessly snipped.) And ruthlessly appreciated ;-) > A question for Tim Peters, as I guess he'll have the most experience in > this sort of thing. > > With all the cross-platform hassles due to the various C compilers not > implementing the IEEE standard completely or correctly, I wonder how much > work would be involved for some kind soul to implement their own maths > library to do the lot, allowing Python to bypass the C libraries > altogether. > > Are you falling over laughing Tim, or thinking what a great idea? Neither, really. Doing basic + - * / in SW is way too slow to sell to programmers who take floats seriously in their work. For libm, K-C Ng at Sun was writing fdlibm at the same time Peter Tang & I were writing a "spirit of 754" libm for Kendall Square Research (early 90's). KSR is long gone, and the code was proprietary anyway; fdlibm lives on, with an MIT-like ("do whatever you want") license, although it doesn't appear to have enjoyed maintenance work for years now: http://www.netlib.org/fdlibm/ fdlibm is excellent (albeit largely inscrutable to non-specialists) work. I believe that, at some point, glibc replaced its math functions with fdlibm's, and went on to improve them. Taking advantage of those improvements may (or may not) raise licensing issues Python can't live with. There are at least two other potential issues with using it: 1. Speed again. The libm I wrote for KSR was as accurate and relentlessly 754-conforming as fdlibm, but approximately 10x faster. There's an enormous amount of optimization you can do if you can exploit every quirk of the HW you're working on -- and the code I wrote was entirely unportable, non-standard C, which couldn't possibly run on any HW other than KSR's custom FPU. C compiler vendors at least used to spend a lot of money similarly crafting libraries that exploited quirks of the HW they were targeting, and lots of platforms still have relatively fast libms as a result. fdlibm aims to run on "almost any" 32-bit 754 box, and pays for that in comparative runtime sloth. . Since fdlibm was written at Sun over a decade ago, you can guess that it wasn't primarily aiming at the Pentium architecture. 2. Compatibility with the platform libm. Some users will be unhappy unless the stuff they get from Python is quirk-for-quirk and bug-for-bug identical to the stuff they get from other languages on their platform. There's really no way to do that unless Python uses the same libm. For example, many people have no real idea what they're doing with libm functions, and value reproducibility over anything else -- "different outcomes means one of them must be in error" is the deepest analysis they can, or maybe just have time, to make. Alas, for many uses of libm, that's a defensible (albeit appalling <0.6 wink>) attitude (e.g., someone slings sin() and cos() to plot a circle in a GUI -- when snapping pixels to the closest grid point, the tiniest possible rounding difference can make a pixel "jump" to a neighboring pixel, and then "it's a bug" if Python doesn't reproduce the same pixel plotting accidents as, e.g., the platform C or JavaScript). > What sort of work is needed? Is it, say, as big a job as maintaining > Python? Bigger? One weekend spent working solidly? Half a full-time year if done from scratch by a numeric programming expert. Maybe a few weeks if building on fdlibm, which probably needs patches to deal with modern compilers (e.g., http://www.netlib.org/fdlibm/readme has no date on it, but lists as "NOT FIXED YET": 3. Compiler failure on non-standard code Statements like *(1+(int*)&t1) = 0; are not standard C and cause some optimizing compilers (e.g. GCC) to generate bad code under optimization. These cases are to be addressed in the next release. ). From theller at python.net Mon Jul 4 13:25:13 2005 From: theller at python.net (Thomas Heller) Date: Mon, 04 Jul 2005 19:25:13 +0200 Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> <1120496836.806367.65780@z14g2000cwz.googlegroups.com> Message-ID: "Derek van Vliet" writes: > The second method you describe sounds like it is along the lines of > what I need to do. Is there a way to do this using the Python/C API? > > For instance, if I have the contents of a pyc file loaded entirely into > memory, and I have a pointer to the beginning of the file and the size > in bytes at my disposal, can I import that by any means? The .pyc file format is sort of 'documented' in lib/py_compile.py. IIRC, it is a magic number, a timestamp, plus a marshalled code object. Thomas From tjreedy at udel.edu Tue Jul 19 22:50:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 19 Jul 2005 22:50:29 -0400 Subject: socket programming References: <20050719204601.GB24773@mail.smule.com> <20050719210319.GA29578@mail.smule.com> Message-ID: "Helge Aksdal" wrote in message news:20050719210319.GA29578 at mail.smule.com... >* Terry Reedy [2005/07/19 22:57]: > >> Ask your server administrator if you are bumping up against a hidden >> connection limit. Or if a query can ask about multiple accounts. > > how can i use a connection limit to my advantage? I was suggesting acquisition of knowledge. If you are making inquiries as part of a work assignment by the company that is restricting your inquiries, then you have an explanation for why you cannot complete the project as soon as expected. Terry J. Reedy From rkern at ucsd.edu Fri Jul 15 06:49:23 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 15 Jul 2005 03:49:23 -0700 Subject: Documenting extension modules? In-Reply-To: <42D79025.4000405@gmx.net> References: <42D79025.4000405@gmx.net> Message-ID: Francois De Serres wrote: > Hiho, > > I can't seem to find a proper way to document my extension module. > Following the C API doc: > > static PyMethodDef ioMethods[] = { > {"o_count", o_count, METH_VARARGS, "Return the count of available > MIDI outputs."}, > .... > } > > lacks: > a) module level documentation In your init function, assign a PyStr object to __doc__. > b) function parameters Add that information to your docstring. I don't think that there is a way to get this information via inspect. > Also, I'd like to know if there's a typical format for the help string > (but in C), compatible with docstring's > """short desription > > long description""" char *o_count__doc__; char *o_count__doc__ = "short description\n"\ "\n"\ "long description\n"; -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nixin at itec.co.za Tue Jul 12 08:02:47 2005 From: nixin at itec.co.za (niXin) Date: Tue, 12 Jul 2005 14:02:47 +0200 Subject: Software needed Message-ID: Hi Can anyone direct me to where I can find free software to do the following: Document Management Software --------------------------- 1. Written in PHP or Python 2. scanning feature - where I can scan a document I'm basically trying to setup a paperless office..lol If you could help that would be great. Thanx From ac063 at lafn.org Wed Jul 20 11:33:39 2005 From: ac063 at lafn.org (David Smith) Date: Wed, 20 Jul 2005 08:33:39 -0700 Subject: Newbie question: Explain this behavior - a followup In-Reply-To: References: Message-ID: max wrote: > David Smith wrote in > news:db99ec$2epm$1 at zook.lafn.org: > > >>range statements, the example doesn't work. >> >>Given that the beginning and ending values for the inner range >>statement are the same, the inner range statement will never be > > > Is your question about the semantics of for else blocks or about the > suitability of the algorithm given in the example? The for else block > is behaving exactly as expected... > > Good question. The question was directed at the latter, the suitability of algorithm for determining prime numbers. >>>>range(1,1) > > [] > >>>>range(500,500) > > [] > > > see > http://groups- > beta.google.com/group/comp.lang.python/browse_frm/thread/d6c084e791a00 > 2f4?q=for+else&hl=en& > > for a good explanation of when the else part of the loop is executed. > Basically, whenever the loop is exited normally, which is what happens > when you iterate over an empty list like the one returned by > range(1,1) > > > max > > From mrmaple at gmail.com Tue Jul 12 09:09:57 2005 From: mrmaple at gmail.com (James Carroll) Date: Tue, 12 Jul 2005 09:09:57 -0400 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: <3jftckFpvhv2U2@individual.net> Message-ID: Notice the dictionary is only changed if the key was missing. >>> a = {} >>> a.setdefault("a", "1") '1' >>> a.setdefault("a", "2") '1' >>> a.setdefault("b", "3") '3' >>> a {'a': '1', 'b': '3'} >>> a.setdefault("a", "5") '1' >>> a {'a': '1', 'b': '3'} -Jim On 7/11/05, Peter Hansen wrote: > Ric Da Force wrote: > > How does setdefault work exactly? I am looking in the docs and can't figure > > it out... > > If the key (the first argument) already exists in the dictionary, the > corresponding value is returned. If the key does not exist in the > dictionary, it is stored in the dictionary and bound to the second > argument, and then that second argument is returned as the value. > > (I always have to ignore the name to think about how it works, or it > gets in the way of my understanding it. The name makes fairly little > sense to me.) > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > > From jemfinch at gmail.com Thu Jul 28 13:41:54 2005 From: jemfinch at gmail.com (jemfinch at gmail.com) Date: 28 Jul 2005 10:41:54 -0700 Subject: Advanced concurrancy In-Reply-To: References: Message-ID: <1122572514.482082.270140@g44g2000cwa.googlegroups.com> Asynchrony is not concurrency. If you have to turn your code "inside out," (that is, if you have to write your code such that the library calls your code, rather than vice versa) it's very much *not* concurrency: it's just asynchrony. While Twisted makes asynchronous code relatively easy to write and maintain, it's just not concurrency. I can't simply drop my single-threaded code into it and have it work, like I can with a truly concurrent system. Jeremy From cjw at sympatico.ca Tue Jul 12 09:20:17 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 12 Jul 2005 09:20:17 -0400 Subject: Puzzled In-Reply-To: <42d34a22.435805525@news.oz.net> References: <42d34a22.435805525@news.oz.net> Message-ID: Bengt Richter wrote: > On Mon, 11 Jul 2005 22:10:33 -0400, "Colin J. Williams" wrote: > > >>The snippet of code below gives the result which follows >> >>for k in ut.keys(): >> name= k.split('_') >> print '\n1', name >> if len(name) > 1: >> name[0]= name[0] + name[1].capitalize() >> print '2', name >> name[0]= name[0].capitalize() >> print '3', name >> >>1 ['logical', 'or'] >>2 ['logicalOr', 'or'] >>3 ['Logicalor', 'or'] >> >>I was expecting that 3 would read ['LogicalOr', 'or'] >> >>If I replace the above code with: >> >>for k in ut.keys(): >> name= k.split('_') >> print '\n1', name >> if len(name) > 1: >> name[0]= name[0].capitalize() + name[1].capitalize() >> print '2', name >> else: >> name[0]= name[0].capitalize() >> print '3', name >> >>I get the desired result. >> > > If you walk through the results, you can see what happens to name[2] on output line 2: > > >>> 'logicalOr'.capitalize() > 'Logicalor' > > I.e., > >>> help(str.capitalize) > Help on method_descriptor: > > capitalize(...) > S.capitalize() -> string > > Return a copy of the string S with only its first character > capitalized. ^^^^-- meaning all the rest lowercased, > which changed your trailing 'Or' > > So, doing .capitalize on all the pieces from split('_') and then joining them: > > >>> def doit(w): return ''.join([s.capitalize() for s in w.split('_')]) > ... > >>> doit('logical_or') > 'LogicalOr' > >>> doit('logical') > 'Logical' > >>> doit('logical_or_something') > 'LogicalOrSomething' > >>> doit('UP_aNd_down') > 'UpAndDown' > > Regards, > Bengt Richter Many thanks. I missed the implication that any upper case characters after the first are changed to lower case. Colin W. From bokr at oz.net Sun Jul 10 21:56:28 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 01:56:28 GMT Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> <42d1a333.327534629@news.oz.net> Message-ID: <42d1cff6.338993877@news.oz.net> On Sun, 10 Jul 2005 15:53:22 -0700, Robert Kern wrote: >Bengt Richter wrote: > >> Then googling for mascsyma [sic ;-)] got Dang, and I put "[sic]" too. IOW, 'macsyma'.replace('cs','sc') > >I doubt it. ;-) > Rightly ;-/ Fingers think they know spelling better than I do ;-/ Regards, Bengt Richter From t-meyer at ihug.co.nz Thu Jul 7 19:35:06 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 8 Jul 2005 11:35:06 +1200 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: Message-ID: > Everyone complaining about Eclipse in this thread needs to go > try 3.1. The interface is much much much more responsive. The problem with Eclipse, IMO, is Java. I've tried 3.1 on a WinXP machine and, like just about any Java program, it's incredibly slow and a real pain to use. On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and smoothly and is reasonably nice to use. I'd happily recommend that Mac users try Eclipse, but never a Windows (Python) programmer. =Tony.Meyer From flamesrock at gmail.com Sat Jul 2 03:23:45 2005 From: flamesrock at gmail.com (flamesrock) Date: 2 Jul 2005 00:23:45 -0700 Subject: wxPython: Terminal Output -> Scrollable Panel? Message-ID: <1120289025.359671.148450@g14g2000cwa.googlegroups.com> First, I'm very new to gui programming, so please go lightly on me :) Ok, so far I've settled on wxPython, and what I'd like to do as a first leap is *convert* a text program into a gui program. It would have a few buttons as function controls and one main scrollable panel that acts like a terminal window. I want to make it so that clicking on a button that performs an operation will output it to the scrollable wxpython terminal panel, and (if possible) save that output as text (or maybe into a logfile). Anyone know how to do this? Like a log window? I've seen something like this in a program called 'nicotine' but have no idea how to implement it myself. -thanks From steve at REMOVETHIScyber.com.au Tue Jul 12 12:03:08 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 02:03:08 +1000 Subject: Creating anonymous functions using eval References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> Message-ID: On Tue, 12 Jul 2005 08:28:45 -0700, Devan L wrote: > How is this different from a nested function? Well, "this" is a newsgroup posting written by you. Nested functions in Python are callable objects that exist as attributes of other callable objects, so the two are very different. Alternatively, if you expect a sensible answer, how about asking a sensible question? You can start by telling us just what it is that you are comparing to nested functions. -- Steven. From cyril.bazin at gmail.com Mon Jul 4 07:11:51 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Mon, 4 Jul 2005 13:11:51 +0200 Subject: f*cking re module In-Reply-To: <1120473422.864033.36350@o13g2000cwo.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <1120473422.864033.36350@o13g2000cwo.googlegroups.com> Message-ID: If you are looking for HTML tags or something like that. Have a look at the HTMLParser (docs.python.org). On 4 Jul 2005 03:37:02 -0700, jwaixs wrote: > Thank you for your replies, it's much obvious now. I know more what I > can and can't do with the re module. But is it possible to search for > more than one string in the same line? > > bv. I want to replace the with " " > with "\n" and every thing that's not between the two python > tags must begin with "\nprint \"\"\"" and end with "\"\"\"\n"? Or do I > need more than one call? > > -- > http://mail.python.org/mailman/listinfo/python-list > From cam.ac.uk at mh391.invalid Fri Jul 22 04:36:02 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 09:36:02 +0100 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: Stefan Rank wrote: > on 22.07.2005 00:21 Michael Hoffman said the following: >> Any Java hackers here want to tell us of the wonders of the Java Path >> class? > > no such thing exists. > > there is only the `File` class that incorporates a little bit of the > `path` functionality and some of the python built-in `file` functionality. Ah, here it is: http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html -- Michael Hoffman From mwh at python.net Mon Jul 11 08:09:50 2005 From: mwh at python.net (Michael Hudson) Date: Mon, 11 Jul 2005 12:09:50 GMT Subject: math.nroot [was Re: A brief question.] References: Message-ID: Tim Peters writes: > [Tim Peters] > >>>> All Python behavior in the presence of infinities, NaNs, and signed > >>>> zeroes is a platform-dependent accident, mostly inherited from that > >>>> all C89 behavior in the presence of infinities, NaNs, and signed > >>>> zeroes is a platform-dependent crapshoot. > > [Michael Hudson] > >>> As you may have noticed by now, I'd kind of like to stop you saying > >>> this :) -- at least on platforms where doubles are good old-fashioned > >>> 754 8-byte values. > > [Tim] > >> Nope, I hadn't noticed! I'll stop saying it when it stops being true, > >> though . Note that since there's not even an alpha out for 2.5 > >> yet, none of the good stuff you did in CVS counts for users yet. > > [Michael] > > Well, obviously. OTOH, there's nothing I CAN do that will be useful > > for users until 2.5 actually comes out. > > Sure. I was explaining why I keep saying what you say you don't want > me to say: until 2.5 actually comes out, what purpose would it serve > to stop warning people that 754 special-value behavior is a x-platform > crapshoot? Much of it (albeit less so) will remain a crapshoot after > 2.5 comes out too. Well, OK, I phrased my first post badly. Let me try again: I want to make this situation better, as you may have noticed. > >>> But first, I'm going to whinge a bit, and lay out some stuff that Tim > >>> at least already knows (and maybe get some stuff wrong, we'll see). > >>> > >>> Floating point standards lay out a number of "conditions": Overflow > >>> (number too large in magnitude to represent), Underflow (non-zero > >>> number to small in magnitude to represent), Subnormal (non-zero number > >>> to small in magnitude to represent in a normalized way), ... > > >> The 754 standard has five of them: underflow, overflow, invalid > >> operation, inexact, and "divide by 0" (which should be understood more > >> generally as a singularity; e.g., divide-by-0 is also appropriate for > >> log(0)). > > > OK, the decimal standard has more, which confused me for a bit > > (presumably it has more because it doesn't normalize after each > > operation). > > The "conditions" in IBM's decimal standard map, many-to-one, on to a > smaller collection of "signals" in that standard. It has 8 signals: > the 5 I named above from 754, plus "clamped", "rounded", and > "subnormal". Distinctions are excruciatingly subtle; e.g., "rounded" > and "inexact" would be the same thing in 754, but, as you suggest, in > the decimal standard a result can be exact yet also rounded (if it > "rounds away" one or more trailing zeroes), due to the unnormalized > model. Right, yes, that last one confused me for a while. Why doesn't 754 have subnormal? Actually, I think I'm confused about when Underflow is signalled -- is it when a denormalized result is about to be returned or when a genuine zero is about to be returned? > >>> For each condition, it should (at some level) is possible to trap each > >>> condition, or continue in some standard-mandated way (e.g. return 0 > >>> for Underflow). > > >> 754 requires that, yes. > > >>> While ignoring the issue of allowing the user to control this, I do > >>> wish sometimes that Python would make up it's mind about what it does > >>> for each condition. > > >> Guido and I agreed long ago that Python "should", by default, raise an > >> exception on overflow, invalid operation, and divide by 0, and "should > >> not", by default, raise an exception on underflow or inexact. > > And, I'll add, "should not" on rounded, clamped and subnormal too. Sure, but we already have a conforming implementation of 854 with settable traps and flags and rounding modes and all that jazz. Maybe we should just implement floats in Python. > >> Such defaults favor non-expert use. Experts may or may not be happy > >> with them, so Python "should" also allow changing the set. > > > Later :) > > That's a problem, though. 754 subsets are barely an improvement over > what Python does today: Well, my contention is that the consistent application of one particular 754 subset would be an improvement. Maybe I'm wrong! > > (In the mean time can we just kill fpectl, please?) > > Has it been marked as deprecated yet (entered into the PEP for > deprecated modules, raises deprecation warnings, etc)? I don't know. > IMO it should become deprecated, but I don't have time to push that. A bit of googling suggests that more people pass --with-fpectl to configure than I expected, but I doubt more than 1% of those actually use the features thus provided (of course, this is a guess). > >>> There are a bunch of conditions which we shouldn't and don't trap by > >>> default -- Underflow for example. For the conditions that probably should > >>> result in an exception, there are inconsistencies galore: > >>> > >>> >>> inf = 1e300 * 1e300 # <- Overflow, no exception > >>> >>> nan = inf/inf # <- InvalidOperation, no exception > > >> Meaning you're running on a 754 platform whose C runtime arranged to > >> disable the overflow and invalid operation traps. > > > Isn't that the standard-mandated start up environment? > > The 754 standard mandates "non-stop" mode (all traps disabled) at > startup, but who in this chain is _claiming_ to implement the 754 > standard? Your platform C may or may not, and your OS may or may not. Well, fair point, but it's a convenient stick to beat unconforming platform vendors with. I only really care about platforms that make at least a half-hearted effort towards 754 compliance. I'm not looking to improve behaviour on a PDP-10 running TOPS (or whatever). > >> You're seeing native HW fp behavior then. > > > But anyway, shouldn't we try to raise exceptions in these cases? > > I believe Python should raise exceptions in these cases by default, > because, as above, they correspond to the overflow and > invalid-operation signals respectively, and Python should raise > exceptions on the overflow, invalid-operation, and divide-by-0 signals > by default. But I also believe Python _dare not_ do so unless it also > supplies sane machinery for disabling traps on specific signals (along > the lines of the relevant standards here). Um. Python raises OverflowError more often that it used to, it seems to me, and already _dares_ to raise it from (e.g.) math.exp with no way of turning this off I can see. > Many serious numeric programmers would be livid, and justifiably so, > if they couldn't get non-stop mode back. Maybe I'm missing something (and writing this reply in multiple stages makes this more likely) but they don't have it now, do they? > The most likely x-platfrom accident so far is that they've been > getting non-stop mode in Python since its beginning. I know I'm repeating myself, but didn't this changeset: http://fisheye.cenqua.com/changelog/python?cs=MAIN:tim_one:20010905223655 change that rather? (It affects 2.2 and later, I think). > > I don't think it's a particularly good idea to try to utilize the fp > > hardware's ability to do this at this stage, btw, but to add some kind > > of check after each operation. > > That's possible, anyway. Doing it in software is slow, but if you > look at the horrid contortions fpectlmodule.c endures to try to > exploit HW facilities, it's not clear that the latter is any faster. I think it might well be slow, too, at least some of the time; the conclusion of this rather long thread: http://lists.freebsd.org/pipermail/freebsd-stable/2005-May/014575.html was "turn --with-fpectl off". > >>> >>> pow(1e100, 100) <- Overflow, exception > >>> Traceback (most recent call last): > >>> File "", line 1, in ? > >>> OverflowError: (34, 'Numerical result out of range') > >>> >>> math.sqrt(-1) # <- InvalidOperation, exception > >>> Traceback (most recent call last): > >>> File "", line 1, in ? > >>> ValueError: math domain error > > >> Unlike the first two examples, these call libm functions. > > > And the user cares about this why? > > Didn't say the user did care. I know you didn't, and I also knew the reason for the different behaviours, but that doesn't make me feel that much better. > Why doesn't Python already supply a fully 754-conforming arithmetic > on 754 boxes? It's got almost everything to do with implementation > headaches, and very little to do with what users care about. > Because all the C facilities are a x-platform mess, the difference > between calling and not calling libm can be the difference between > using the platform libm or Python needing to write its own libm. > For example, there's no guarantee that math.sqrt(-1) will raise > ValueError in Python, because Python currently relies on the > platform libm sqrt to detect _and report_ errors. The C standards > don't require much of anything there. Can't we use the stuff defined in Appendix F and header of C99 to help here? I know this stuff is somewhat optional, but it's available AFAICT on the platforms I actually use (doesn't mean it works, of course). I'm thinking something like this: fexcept_t flags; feclearexcept(FE_ALL_EXCEPT); /* stuff, e.g. r = exp(PyFloat_AS_DOUBLE(x)) */ fegetexceptflag(&flags, FE_ALL_EXCEPT) /* inspect flags to see if any of the flags we're currently trapping are set */ [...] > >> Then it's a x-platform crapshoot whether and when the libm functions > >> set errno to ERANGE or EDOM, and somewhat of a mystery whether it's > >> better to reproduce what the native libm considers to be "an error", > >> or try to give the same results across platforms. Python makes a > >> weak attempt at the latter. > > > Well, you can at least be pretty sure that an infinite result is the > > result of an overflow condition, I guess. > > There are at least two other causes: some cases of divide-by-0 (like > 1/0 returns +Inf), and non-exceptional production of an infinite > result from infinite operands (like sqrt(+Inf) should return +Inf, and > there's nothing exceptional about that). Yeah, but I think those can be dealt with (if we really wanted to). OTOH, I think Inexact would be pain itself to detect without hw support, and Underflow would be tedious. > >>> At least we're fairly consistent on DivisionByZero... > > >> When it's a division by 0, yes. It's cheap and easy to test for that. > >> However, many expert uses strongly favor getting back an infinity > >> then instead, so it's not good that Python doesn't support a choice > >> about x/0. > > > Indeed. But I'd rather work on non-settable predictability first. > > OTOH, I bet I could find people willing to pay for the ability to > "turn off" divide-by-0 exceptions (or the people talking my ear off at > PyCon this year were just bluffing ). Noted. > BTW, since there's so little the HW can help us with here in reality > (since there's no portable way to get at it), In what way does C99's fenv.h fail? Is it just insufficiently available, or is there some conceptual lack? > any predictability is going to be supplied by software, and software > for that will work better over the long run if it's designed from > the start realizing that it needs to consult some form of context to > decide what is and is not "an exception". Also noted. [...] > > This make me sad. > > > > Whether my code should have returned an infinite value or raised an > > exception for "1e1000" is an open question, but I'd like the answer to > > be less accidental. > > It's a delicate house of cards right now for sure. In some ways, > experts have learned to live with-- and exploit --it: when they > _want_ an overflow exception they'll use pow(), and when they don't > they'll just multiply. Another question: where can I find these experts? How come they haven't tried to reduce the mess before? I guess "academia" is an answer to both those questions... [...] > >> and overflow doesn't always result in an infinity either (depends on > >> the rounding mode in effect)). > > > If we're allowing the user to alter rounding mode, I imagine we'll > > have a much better idea about this sort of thing. For now, I think we > > can assume a default rounding that doesn't do that, and someone who > > has a platform like where it has his or her own problem. > > IME the rounding modes in 754 are almost never changed from the > default to-nearest-even, and I can live with that. The rounding modes > in the Decimal module will be changed a lot, though (due to the > insanity of politically mandated rounding rules in currency > calculations). Decimal is a solved problem, here (and also an inspiration for design). > >>> On the issue of platforms that start up processes with traps enabled, > >>> I think the correct solution is to find the incantation to turn them > >>> off again and use that in Py_Initialize(), though that might upset > >>> embedders. > > >> Hard to know. Python currently has a hack to disable traps on > >> FreeBSD, in python.c's main(). > > > Oh, right. Well, I don't much care about embedding, anyway. > > So far, I think FreeBSD remains the only known Python platform that > enables some FP traps by default. So it's OK if you _just_ don't care > much about embedding on FreeBSD . Even less to worry about! Cheers, mwh -- I never realized it before, but having looked that over I'm certain I'd rather have my eyes burned out by zombies with flaming dung sticks than work on a conscientious Unicode regex engine. -- Tim Peters, 3 Dec 1998 From ramen at lackingtalent.com Tue Jul 19 17:38:46 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 19 Jul 2005 14:38:46 -0700 Subject: Jython Released In-Reply-To: References: <6NWdna8jsbEov0DfRVn-vA@comcast.com> Message-ID: Ramza Brown wrote: >> >> I figured it out. You might want to document this somewhere. ;) >> java -cp jython_Release_2_2alpha1.jar >> org.python.util.install.Installation > > Did you try double clicking on the jar. That is what most do or at > least the last package supported that. Yeah. It opens in WinRAR. =) Dave From listmaster at ittoolbox.com Wed Jul 6 05:05:14 2005 From: listmaster at ittoolbox.com (listmaster at ittoolbox.com) Date: Wed, 6 Jul 2005 11:05:14 +0200 (CEST) Subject: TEST Message-ID: <20050706090514.AC3BD1E4014@bag.python.org> Dear ITtoolbox Groups Subscriber, Your message has NOT been distributed to the ITtoolbox BusinessObjects-L discussion group. Please continue reading for further details and instructions. On Wednesday, May 26, 2004, ITtoolbox launched nine new discussion topics, each focusing on specific Business Objects products. There is no longer one ITtoolbox BusinessObjects-L address. As a current group member, you are automatically subscribed to the new topics and can begin to send and receive messages immediately. Instead of addressing messages to BusinessObjects-L at Groups.ITtoolbox.com, you must now send messages to one or more of the appropriate ITtoolbox Business Objects discussion topics below. Analytic Applications - BusinessObjects-AnalyticApps-L at Groups.ITtoolbox.com Connectivity - BusinessObjects-Connectivity-L at Groups.ITtoolbox.com Data Integration - BusinessObjects-DataIntegration-L at Groups.ITtoolbox.com Development - BusinessObjects-Dev-L at Groups.ITtoolbox.com Installations and Upgrades - BusinessObjects-InstallsUpgrades-L at Groups.ITtoolbox.com Performance Management and Security -BusinessObjects-Performance-L at Groups.ITtoolbox.com Reporting and Analysis - BusinessObjects-ReportingAnalysis-L at Groups.ITtoolbox.com General Business Objects Issues - BusinessObjects-Other-L at Groups.ITtoolbox.com ITtoolbox also hosts the BusinessObjects-Crystal-L discussion group. Unlike the eight discussion topics listed above, you are not automatically subscribed to this group. To begin sending and receiving messages from the ITtoolbox BusinessObjects-Crystal-L discussion group, you can subscribe by visiting http://BI.ITtoolbox.com/groups/groups.asp?v=BUSINESSOBJECTS-CRYSTAL-L. Please read the FAQs below for more information. 1) Why am I receiving messages from different e-mail addresses? There is no longer one BusinessObjects-L e-mail address. Instead, each Business Objects area of discussion has its own e-mail address. You will receive messages from each address corresponding to the new ITtoolbox Business Objects discussion topics. 2) How do I send a message to the new ITtoolbox Business Objects discussion topics? >From the list above, choose the most relevant topic based on the subject of your message. For example, if your message is relevant to Reporting, it should be addressed to BusinessObjects-ReportingAnalysis-L at Groups.ITtoolbox.com. 3) What if I want my message to go to more than one topic? Simply address your message to as many ITtoolbox Business Objects discussion topics as are relevant to the subject of your message. ITtoolbox will make sure each user only gets your message one time, even if they are subscribed to multiple groups. 4) What if I do not want to receive messages from all the ITtoolbox Business Objects discussion topics? You may, at any point, choose to unsubscribe from specific ITtoolbox Business Objects discussion topics. To unsubscribe, please sign in to your ITtoolbox User ID with your e-mail address at http://My.ITtoolbox.com/My_Groups.asp. If you have never signed in before, you may request a password by visiting http://My.ITtoolbox.com/ForgotPassword.asp. You must individually unsubscribe from each topic. 5) Why did you add individual Business Objects discussion topics? I thought the ITtoolbox BusinessObjects-L discussion group worked just fine. ITtoolbox received feedback from many group members requesting the opportunity to conduct more specialized discussion about particular Business Objects applications. Since such clear areas exist, we felt they warranted their own discussion topics. The creation of these new topics will improve the overall quality of discussion by enabling you to receive focused, high quality solutions with less turnaround time than ever before. 6) What if I still have questions? If you still have questions, please contact Listmaster at ITtoolbox.com. Thank you for your understanding. Sincerely, List Administrator Listmaster at ITtoolbox.com From darkcowherd at gmail.com Sat Jul 23 12:21:36 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Sat, 23 Jul 2005 21:51:36 +0530 Subject: smtplib In-Reply-To: <000a01c58bd1$f2da5db0$1603a8c0@avc> References: <000a01c58bd1$f2da5db0$1603a8c0@avc> Message-ID: <5f4d3cb505072309212b6060ff@mail.gmail.com> On 7/19/05, Alberto Vera wrote: > Hello: > > Do you know If the smtplib routine have been changed in last releases? > > I used this script: > > http://docs.python.org/lib/SMTP-example.html > > but it didn't work with the last release. > > Do you know any idea about this change? > > Regards > > -- > http://mail.python.org/mailman/listinfo/python-list > > If you are using Windows there is no SMTP server running on localhost by default so you may be getting an error. If you post the error you are getting it may help -- Dark Cowherd From rkern at ucsd.edu Wed Jul 6 17:01:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 06 Jul 2005 14:01:39 -0700 Subject: Scipy - Latex Annotations in plots In-Reply-To: References: Message-ID: Matthias R. wrote: > Unfortunately matplotlib is only a 2D-plotting library. > > Do you know another one with 3D-capabilities as well? There's PyX. > That would be very nice, Yes, yes it would. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rrr at ronadam.com Wed Jul 6 11:18:31 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 15:18:31 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Dan Sommers wrote: > On Wed, 06 Jul 2005 14:33:47 GMT, > Ron Adam wrote: > > >>Since this is a Python 3k item... What would be the consequence of >>making None the default value of an undefined name? And then assigning >>a name to None as a way to delete it? > > > [ ... ] > > >>Any drawbacks? > > > Lots more hard-to-find errors from code like this: > > filehandle = open( 'somefile' ) > do_something_with_an_open_file( file_handle ) > filehandle.close( ) > > Regards, > Dan If do_something_with_an_open_file() is not defined. Then you will get: TypeError: 'NoneType' object is not callable If "file_handle" (vs "filehandle") is None. Then you will still get an error as soon as you tried to use the invalid file handle. AttributeError: 'NoneType' object has no attribute 'read' If the error was filehundle.close() you will get: AttributeError: 'NoneType' object has no attribute 'close' I don't think any of those would be hard to find. Cheers, Ron From rrr at ronadam.com Sun Jul 3 23:41:44 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 04 Jul 2005 03:41:44 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: Erik Max Francis wrote: > Ron Adam wrote: > >> Each item needs to stand on it's own. It's a much stronger argument >> for removing something because something else fulfills it's need and >> is easier or faster to use than just saying we need x because we have y. >> >> In this case sum and product fulfill 90% (estimate of course) of >> reduces use cases. It may actually be as high as 99% for all I know. >> Or it may be less. Anyone care to try and put a real measurement on it? > > > Well, reduce covers 100% of them, and it's one function, and it's > already there. So you are saying that anything that has a 1% use case should be included as a builtin function? I think I can find a few hundred other functions in the library that are used more than ten times as often as reduce. Should those be builtins too? This is a practical over purity issue, so what are the practical reasons for keeping it. "It's already there" isn't a practical reason. And it covers 100% of it's own potential use cases, is circular logic without a real underlying basis. Cheers, Ron From blee at EPWU.org Tue Jul 26 09:51:45 2005 From: blee at EPWU.org (Brian Lee) Date: Tue, 26 Jul 2005 07:51:45 -0600 Subject: subscribe Message-ID: <25133FB9D614D411864500508B64433A039C7100@EPWUMAIL> Subscribe Thanks, Brian Lee -------------- next part -------------- An HTML attachment was scrubbed... URL: From renato.ramonda at gmail.com Sun Jul 3 13:09:14 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Sun, 03 Jul 2005 19:09:14 +0200 Subject: debugger? In-Reply-To: References: Message-ID: <_YUxe.23497$TR5.4547@news.edisontel.com> Qiangning Hong ha scritto: > Eric3 need pyqt so it is not free under windows platform. Eric3 has had a free version for months now on windows, since the kde on win32 project recompiled the free versions on windows. And qt4 now has a GPL version free on windows too. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From ffu at softpro.de Wed Jul 6 16:39:32 2005 From: ffu at softpro.de (Frank Fuchs) Date: Wed, 6 Jul 2005 22:39:32 +0200 Subject: out of office auto-reply Message-ID: <200507062039.j66KdWD31689@lucy.ux.softpro.de> Dear sender, I am on vacation up to and including Sunday, July 10th, 2005 and I will be travelling on Monday and Tuesday after. My first day back in the office might be Wednesday, July 13th, 2005 - at which time I will have access to email again. If it's urgent you can try my mobile on Monday/Tuesday, July 11th/12th, but you will not be able to reach me during my vacation. During my absence, please contact one of my colleagues in management or your sales representative. Sincerely, Frank Fuchs Managing Director, CIO and CTO SOFTPRO Group SOFTPRO Software Professional GmbH & Co. KG Wilhelmstr. 34 D-71034 Boeblingen Germany www.signplus.com www.softpro.de From cjw at sympatico.ca Sat Jul 2 10:15:48 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 02 Jul 2005 10:15:48 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> Message-ID: Rocco Moretti wrote: > Paul Rubin wrote: > >> Rocco Moretti writes: >> >>> Except that (please correct me if I'm wrong) there is somewhat of a >>> policy for not including interface code for third party programs which >>> are not part of the operating system. (I.e. the modules in the >>> standard libary should all be usable for anyone with a default OS + >>> Python install.) >> >> >> >> I've never heard of Python having such a policy and I don't understand >> how such a stupid policy could be considered compatible with a >> proclaimed "batteries included" philosophy. Why would Python >> advocates want to make Python deliberately uncompetitive with PHP, >> Java, and other languages that do include database modules? > > > Well, since there seems to be an outpouring of disgust at my statement, > and no official confirmation/rejection, it's probably a figment of my > prematurely failing mind. > > However, if there was such a policy, it would not be unequivocally > "stupid." First off, there is a bit of flexibility in what is considered > part of the OS. E.g, Linux may properly refer to just the kernel, but > rarely is just the kernel installed. Various utilities and programs > might be considered part of the OS because they are ubiquitously > installed, or are included with the Python distribution itself (as Tk is > with windows Python). > > For those programs which aren't ubiquitously installed, or even for ones > that are, but require significant configuration, it is reasonable to > expect that if someone has the ability and goes to the effort of > locating, obtaining, installing, and configuring a third party program, > they can just as easily obtain and install the python module, especially > as it's usually as easy as "python setup.py install". > > At any rate, I'm not advocating such a policy, I'm just saying it can > make a bit of sense if you look at it from a certain angle. I agree. It makes sense to develop a policy first. Colin W. From littlejohn.75 at news.free.fr Fri Jul 1 18:12:29 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 01 Jul 2005 22:12:29 GMT Subject: No subject References: Message-ID: <42c5bfcd$0$31208$636a15ce@news.free.fr> Le Fri, 01 Jul 2005 20:47:45 +0200, Andreas Kostyrka a ?crit : about C++ templates > And they are a kind of "compile-time" late binding. You get the worst > from both worlds. All the complication of a static typing system, and at > the same time no safety. +1 QOTW From jabel at plus.net Tue Jul 12 11:09:24 2005 From: jabel at plus.net (John Abel) Date: Tue, 12 Jul 2005 16:09:24 +0100 Subject: Missing Something Simple In-Reply-To: <920a9e9a63459b003a5135ff3d77f330@upf.edu> References: <42D3C920.2000808@plus.net> <11f99613a4f2a4c64f8055e060b8e965@upf.edu> <42D3D089.6030403@plus.net> <920a9e9a63459b003a5135ff3d77f330@upf.edu> Message-ID: <42D3DD24.9020806@plus.net> harold fellermann wrote: > >so, if I understand you right, what you want to have is a list of >mutable objects, whose value you can change without changing the >objects' >references. > > Yes! >class Proxy : > def __init__(self,val) : self.set(val) > def set(self,val) : self.val = val > def get(self) : return self.val > > >a = Proxy(1) >b = Proxy(2) >c = Proxy(3) > >varList = [a,b,c] > >for i in varList : > i.set(returnVarFromFunction()) > >print a,b,c > >prints whatever returnVarFromFunction has returned. >n.b.: instead of the Proxy class, you can use any other mutable >objects, e.g. lists. > > >- harold - > > >-- >"All unsere Erfindungen sind nichts als verbesserte Mittel > zu einem nicht verbesserten Zweck." >-- H.D. Thoreau > > > That does it. Thank you! J From mwm at mired.org Tue Jul 19 23:01:56 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 19 Jul 2005 23:01:56 -0400 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: <86psterxi3.fsf@bhuda.mired.org> Rocco Moretti writes: > Leif K-Brooks wrote: >> rbt wrote: >> >>>IMO, most of the people who deride goto do so because they heard or read >>> where someone else did. >> 1 GOTO 17 >> 2 mean, GOTO 5 >> 3 could GOTO 6 >> 4 with GOTO 7 >> 5 what GOTO 3 >> 6 possibly GOTO 24 >> 7 you! GOTO 21 >> 8 that GOTO 18 >> 9 really, GOTO 23 >> 10 understandable? >> 11 neat. GOTO 16 >> 12 and GOTO 25 >> 13 are GOTO 9 >> 14 I GOTO 26 >> 15 wrong GOTO 20 >> 16 I GOTO 2 >> 17 Yes, GOTO 14 >> 18 simple GOTO 12 >> 19 agree GOTO 4 >> 20 with GOTO 22 >> 21 Gotos GOTO 13 >> 22 something GOTO 8 >> 23 really GOTO 11 >> 24 be GOTO 15 >> 25 easily GOTO 10 >> 26 totally GOTO 19 > > I dislike gotos because it is too easy to inadvertently create > infinite loops. <10 WINK; 20 GOTO 10> And it's impossible without them? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tjreedy at udel.edu Sat Jul 2 15:51:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 2 Jul 2005 15:51:01 -0400 Subject: A brief question. References: Message-ID: "Nathan Pinno" wrote in message news:BAY106-DAV24B7740FBE52E30E607BB6C4E50 at phx.gbl... >Brief question for anyone who knows the answer, because I don't. > Is there anyway to make Python calculate square roots? Python can calculate any calculable function of the objects it has to work with. So the answer depends on what you mean by 'square roots': the infinite decimal or a finite approximation thereof. Terry J. Reedy From npsanders at bridgenex.com Thu Jul 28 03:40:13 2005 From: npsanders at bridgenex.com (Nathan Sanders) Date: Thu, 28 Jul 2005 00:40:13 -0700 Subject: Sr. Compiler Engineering Opportunity Message-ID: <20050728073757.45C491E4002@bag.python.org> Hello- I'm hoping to network with you and find out if you know anyone who you think could be interested in the following opportunity? Sr. Compiler Engineer Position Type: Full-Time Employee Location: San Jose, California (Silicon Valley, USA) Generous Compensation and Stock package -------------------------------------------------------------------- Job Description: You will be responsible for identifying, developing, and delivering critical enhancements to programming models and the compiler tool chain for a new and unique multi-processor architecture. Requirements: Experience with compiler back-end technology In-depth understanding of processor architectures Excellent interpersonal and debugging skills Candidate should be self-motivated and comfortable working in a fast paced, mission-critical engineering environment Valuable Skills: Candidates with previous experience in multi-processor architectures, SIMD architectures and media architectures, as well as familiarity with the GCC source base is a plus. Experience: Minimum 3-5 years of experience M.S. in Computer Science, Computer or Electrical Engineering required PhD in Computer Science, Computer or Electrical Engineering a plus More about the company: Our client develops and licenses innovative computing, microprocessor and semiconductor technologies and related intellectual property. Founded in the mid 90's, They first became known for designing, developing and selling their highly efficient x86-compatible software- based microprocessors, which deliver a balance of low power consumption, high performance, low cost and small size suited for diverse computing platforms. They also develop advanced power management technologies for controlling leakage and increasing power efficiency in semiconductor and computing devices. Thanks, ------------------------------------------------------------------ Nathan Sanders Principal/Manager Bridgenex LLC 2464 El Camino Real #206 Santa Clara, Ca 95051 Office: 1.800.881.5733 Email: nathan at bridgenex.com Corporate: www.bridgenex.com :::STAFFING CONLULTANT SERVICES FOR HIGH TECH::: From exarkun at divmod.com Thu Jul 21 09:02:42 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 09:02:42 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: <7xoe8woii0.fsf@ruckus.brouhaha.com> Message-ID: <20050721130242.26278.927647637.divmod.quotient.15432@ohm> On 20 Jul 2005 22:06:31 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >Christopher Subich writes: >> > In the particular case of wxWidgets, it turns out that the *GUI* >> > blocks for long periods of time, preventing the *network* from >> > getting attention. But I agree with your position for other >> > toolkits, such as Gtk, Qt, or Tk. >> >> Wow, I'm not familiar with wxWidgets; how's that work? > >Huh? It's pretty normal, the gui blocks while waiting for events >from the window system. I expect that Qt and Tk work the same way. But not Gtk? :) I meant what I said: wxWidgets behaves differently in this regard than Gtk, Qt, and Tk. Jp From python at rcn.com Wed Jul 6 04:01:34 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jul 2005 01:01:34 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <1120636894.567642.54380@g47g2000cwa.googlegroups.com> > There's really not a single good re tutorial or documentation >I could found! With * being a greedy operator, your post's subject line matches, "firetrucking" which, of course, has nothing to do with regular expressions, or python.org's re how-to guide, or Amazon's 18 books on the subject, or the hundreds of available on-line tutorials. http://www.amk.ca/python/howto/regex/ http://www.amazon.com/exec/obidos/search-handle-form/102-9115182-7050550 http://www.google.com/search?q=regular+expression+tutorial Raymond From fowlertrainer at anonym.hu Tue Jul 5 10:07:44 2005 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 05 Jul 2005 16:07:44 +0200 Subject: Python exception hook simple example needed Message-ID: <42CA9430.7090307@anonym.hu> Hi ! I wrote some mails to wxPy, and this list about "wxPython and global exception handling" theme. I need to port my Delphi apps to wxPy, and I want to use same exception mechanism like Delphi use. When any exception get unhandled, the app's main cycle get it, and show in a dialog (and I can catch it, and I can write it to a log file with many developer information). So: I need to create this in wx+Py. But my computer crashed yesterday, some local emails, files deleted, etc... If anyone has an idea, how to I catch exceptions globally, please write me. I think they are wrote about Python exception hook... If you have a simple example how to use it, write to me ! Thanx for your help: ft From elmo13 at jippii.fi Thu Jul 14 07:35:40 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Thu, 14 Jul 2005 14:35:40 +0300 Subject: Multivariable polynomials References: <1121219789.988951.122880@g47g2000cwa.googlegroups.com> <1121298932.104813.244170@g47g2000cwa.googlegroups.com> Message-ID: On Wed, 13 Jul 2005 16:55:32 -0700, Chris wrote: > Fantastic. May I ask what you are hoping to use it for? > > I checked out Scientific python: > http://starship.python.net/~hinsen/ScientificPython/ > > It has a module with multivariate polynomials with support for a good > functionality but I think the input style won't suit my needs. In any > case, perhaps it will be helpful for you. > > Chris Nothing at the moment:) Just plain interested. Maybe in the future. I'm focused on an area bit different at the moment(My post's a couple ones after this one). From johnandsarah at estragon.freeserve.co.uk Sat Jul 30 07:21:39 2005 From: johnandsarah at estragon.freeserve.co.uk (John Perks and Sarah Mount) Date: Sat, 30 Jul 2005 12:21:39 +0100 Subject: Block-structured resource handling via decorators References: <8664uti1kr.fsf@bhuda.mired.org> Message-ID: > The only cases I see the first school of thought is when the resource > in question is "scarce" in some way. By "resource" I meant anything with some sort of acquire/release semantics. There may be plenty of threading.Locks available, but it's still important that a given Lock is released when not needed. For example, most OS's place a > > class withFile(blockScopedResource): > > init, cleanup = open, 'close' > Well, I'd say that using a string for cleanup and a function for init > is unpythonic. I could have specified cleanup as lambda f:f.close(), but as I thought it might be quite common to call a method on the resourse for cleanup, if a string is specified a method of that name is used instead. > The question is whether having to turn your scope into a > function to do this is more trouble than it's worth. Needing one slightly contrived-looking line (the def) vs a try-finally block with explicit cleanup code? I know which I'd prefer, but for all I know I could in a minority of 1 here. > I'd certainly be interested in seeing the implementation. And so you shall... I start with the base class. It does all the work, everything else is just tweaks for convenience. Normally, then, you wouldn't need to bother with all the __init__ params. class blockScopedResource(object): def __init__(self, init, cleanup, initArgs, initKwargs, cleanupArgs, cleanupKwargs, passResource, resourceIsFirstArg): self.init = init # function to get resource self.cleanup = cleanup # function to release resource self.initArgs, self.initKwargs = initArgs, initKwargs self.cleanupArgs, self.cleanupKwargs = cleanupArgs, cleanupKwargs self.passResource = passResource # whether resource is passed into block self.resourceIsFirstArg = resourceIsFirstArg # whether resource is arg to init, # rather than returned from it def __call__(self, block): resource = self.init(*self.initArgs, **self.initKwargs) if self.resourceIsFirstArg: resource = self.initArgs[0] try: if self.passResource: block(resource) else: block() finally: self.cleanup(resource, *self.cleanupArgs, **self.cleanupKwargs) But this still won't do conveniently for files and locks, which are my motivating examples. The simpleResource class constructor gets its setup from attributes on the type of the object being created, with sensible defaults being set on simpleResource itself. As stated above, if a string is supplied as init or cleanup, it is treated as a method name and that method is used instead. def stringToMethod(f): # Getting the attribute from the class may have wrapped it into # an unbound method; in this case, unwrap it if isinstance(f, types.MethodType) and f.im_self is None: f = f.im_func if not isinstance(f, basestring): return f def helper(resource, *args, **kwargs): return getattr(resource, str(f))(*args, **kwargs) return helper class simpleResource(blockScopedResource): def __init__(self, *initArgs, **initKwargs): # get attributes off type t = type(self) blockScopedResource.__init__(self, stringToMethod(t.init), stringToMethod(t.cleanup), initArgs, initKwargs, t.cleanupArgs, t.cleanupKwargs, t.passResource, t.resourceIsFirstArg) # defaults supplied here cleanupArgs, cleanupKwargs = (), {} passResource = True resourceIsFirstArg = False Then useful implementations can be written by: class withFile(simpleResource): init, cleanup = open, 'close' class withLock(simpleResource): init, cleanup = 'acquire', 'release' passResource = False resourceIsFirstArg = True And new ones can be created with a similar amount of effort. Of course, one-liners can be done without using the decorator syntax: withLock(aLock)(lambda:doSomething(withAnArg)) Gotcha: If you stack multiple resource-decorator it won't do what you want: # !!! DOESN'T WORK !!! @withLock(aLock) @withLock(anotherLock) def do(): # ... Either nest them explicitly (causing your code you drift ever further to the right): @withLock(aLock) def do(): @withLock(anotherLock) def do(): # ... Or come up with a multiple-resource handler, which shouldn't be too hard: @withResources(withLock(aLock), withLock(anotherLock), withFile('/dev/null')) But I'll get round to that another day. From phm4 at kent.ac.uk Sun Jul 10 11:37:36 2005 From: phm4 at kent.ac.uk (Philipp H. Mohr) Date: Sun, 10 Jul 2005 16:37:36 +0100 (BST) Subject: passing arguments to a function - do I need type ? In-Reply-To: <1121009364.541781.17880@g14g2000cwa.googlegroups.com> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <1121009364.541781.17880@g14g2000cwa.googlegroups.com> Message-ID: Hello, thank you very much for all your help. I have solved the problem - you guys where right, the problem was some where else. I have another class which got an accessor: def getCenter(self): global center return center and I called it by saying n.getCenter, but this returns: > I changed it to n.getCenter() and now it works. Despite some small problems I am really getting to like python. Thank you, Phil On Sun, 10 Jul 2005, Paul McGuire wrote: > Is getCenter a function? If so, you need to invoke distance using: > dist = self.distance( n.getCenter(), newElement ) > > Of course, that is assuming that newElement is a local variable of type > list/tuple/etc. > > -- Paul > > From titogarcia_borra_esto at gmail.com Wed Jul 27 14:48:28 2005 From: titogarcia_borra_esto at gmail.com (Tito) Date: Wed, 27 Jul 2005 20:48:28 +0200 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: > Thank you both for your quick answers. Thank you *all* for your quick answers. From ssnail at gmail.com Mon Jul 4 10:05:16 2005 From: ssnail at gmail.com (shablool) Date: 4 Jul 2005 07:05:16 -0700 Subject: curses -- getxy() error In-Reply-To: <1120471995.826051.126700@z14g2000cwz.googlegroups.com> References: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> <1120471995.826051.126700@z14g2000cwz.googlegroups.com> Message-ID: <1120485916.759166.27060@g43g2000cwa.googlegroups.com> Thanks! (silly me) k33rni at gmail.com wrote: > shablool wrote: > > Could someone please explain why stdscr.getxy() always raise an > > exception: > [code here] > the method is named getyx(), this is old unix heritage. > see http://www.python.org/doc/2.0.1/lib/curses-window-objects.html From walterbrunswick at sympatico.ca Mon Jul 25 19:52:59 2005 From: walterbrunswick at sympatico.ca (Walter Brunswick) Date: Mon, 25 Jul 2005 19:52:59 -0400 Subject: Importing User-defined Modules References: Message-ID: <6XeFe.998$d02.286464@news20.bellglobal.com> Thomas Guettler, your solution was very impractical besides being ignorant of my problem. Thanks for trying nonetheless. Andrew Clover, that is exactly what I was looking for. A few examples would have been nice, but I think I can manage from here. Thanks you. From hancock at anansispaceworks.com Mon Jul 11 03:14:04 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 11 Jul 2005 02:14:04 -0500 Subject: Legacy data parsing In-Reply-To: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: <200507110214.04313.hancock@anansispaceworks.com> On Friday 08 July 2005 01:31 pm, gov wrote: > Where I work, we receive large quantities of data which is currently > all printed on large, obsolete, dot matrix printers. This is a problem > because the replacement parts will not be available for much longer. > > So I'm trying to create a program which will capture the fixed width > text file data and convert as well as sort the data (there are several > different report types) into a different format which would allow it to > be printed normally, or viewed on a computer. If this is really your reason for wanting to do this, it seems like your solutions is overkill. If you really just want the data to get reformatted for printing on a modern printer, it would be trivial to do this with a text-formatter like "enscript" (see, e.g.: http://people.ssh.com/mtr/genscript/ ) which produces Postscript output from ASCII text. On a typical Linux system, this sort of tool is usually part of your printer installation, after which it runs more or less invisibly. OTOH, if the *real* reason is that you don't like the look of the dot matrix output and you want it *rearranged* and reformatted for aesthetic reasons, then you might reasonably want to use Python to do that as you suggest. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From sjmachin at lexicon.net Fri Jul 22 07:44:38 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jul 2005 21:44:38 +1000 Subject: find a specified dictionary in a list In-Reply-To: References: Message-ID: <42e0dc25$1@news.eftel.com> Odd-R. wrote: > I have this list: > > [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] > > All the dictionaries of this list are of the same form, and all the oids > are distinct. If I have an oid and the list, how is the simplest way of > getting the dictionary that holds this oid? > Something like this: def oidfinder(an_oid, the_list): for d in the_list: if d['oid'] == an_oid: return d return None # These are not the oids you are looking for. From siyer at Princeton.EDU Thu Jul 14 14:53:31 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Thu, 14 Jul 2005 14:53:31 -0400 Subject: Tkinter Button widget Message-ID: <4c8d3255547de.42d67c6b@Princeton.EDU> Hi, I have another Tkinter-related question. At the beginning of my program, a tkinter window is created with six buttons. Each of these buttons is assigned a function that should be executed only when the button is pressed. However, it seems that these functions are all executed once when the button widgets are first created. Why is this the case and how do I prevent this from happening? Shankar From gene.tani at gmail.com Fri Jul 29 09:13:48 2005 From: gene.tani at gmail.com (gene tani) Date: 29 Jul 2005 06:13:48 -0700 Subject: writing a web client In-Reply-To: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> References: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> Message-ID: <1122642828.810852.146650@g14g2000cwa.googlegroups.com> fuzzy's urllib2 info is excellent. The other way peopel snarf stuff over HTTP and FTP is using 'wget' or 'libcurl'. THere's http://pycurl.sourceforge.net/ From peter at engcorp.com Tue Jul 5 21:44:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Jul 2005 21:44:22 -0400 Subject: System Independent Wallpaper Changer In-Reply-To: <42cb220c$1_5@alt.athenanews.com> References: <42cb220c$1_5@alt.athenanews.com> Message-ID: <4rGdnd_T08bbqlbfRVn-2w@powergate.ca> Terrance N. Phillip wrote: > This is what I've got... the code should work on a typical Windows > system, I think... > if os.name in ['nt', 'win98', 'me']: > osWindows = True > else: > osWindows = False [snip] > if os_type = 'W': I think you might have a problem with the above, where it seems you changed from one approach to another part way through solving the problem... should throw a NameError pretty quick when you run it though. -Peter From benn at cenix-bioscience.com Mon Jul 11 07:42:56 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 11 Jul 2005 13:42:56 +0200 Subject: __eq__ on a dict In-Reply-To: <1121080710.869704.31180@g49g2000cwa.googlegroups.com> References: <1121080710.869704.31180@g49g2000cwa.googlegroups.com> Message-ID: <42D25B40.5090601@cenix-bioscience.com> wittempj at hotmail.com wrote: >These methods are documanted here: >http://docs.python.org/ref/customization.html > > > Hmm, can't see anything about implementation of python dict methods __eq__, __lt__ or __gt__ there - general docs but not specific to the dict here - at least not as far as I can see from these docs. Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From draghuram at gmail.com Fri Jul 15 17:05:24 2005 From: draghuram at gmail.com (draghuram at gmail.com) Date: 15 Jul 2005 14:05:24 -0700 Subject: ssh popen stalling on password redirect output? In-Reply-To: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> Message-ID: <1121461524.880603.214930@f14g2000cwb.googlegroups.com> In general, it is good idea to use expect kind of tool to deal with interactive programs like ssh. You may try using pexpect (http://pexpect.sourceforge.net). From rrr at ronadam.com Thu Jul 7 23:25:57 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 08 Jul 2005 03:25:57 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <74ize.27369$ho.19404@bignews6.bellsouth.net> References: <74ize.27369$ho.19404@bignews6.bellsouth.net> Message-ID: <9nmze.144208$VH2.52770@tornado.tampabay.rr.com> Christopher Subich wrote: > As others have mentioned, this looks too much like a list comprehension > to be elegant, which also rules out () and {}... but I really do like > the infix syntax. Why would it rule out ()? You need to put a lambda express in ()'s anyways if you want to use it right away. print (lambda x,y:x+y)(1,2) If you don't use the ()'s it reads the y(1,2) as part of the lambda expression, might as well require the ()'s to start with rather than leave it open for a possible error. You could even say () is to function as [] is to list. a function : name(args) -> returns a value a list : name[index] -> returns a value My choice: name = (let x,y return x+y) # easy for beginners to understand value = name(a,b) value = (let x,y return x+y)(a,b) I think the association of (lambda) to [list_comp] is a nice distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) Cheers, Ron From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 12:05:49 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 18:05:49 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <8dKdnaBmHKO2kHjfRVn-uQ@powergate.ca> References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> <8dKdnaBmHKO2kHjfRVn-uQ@powergate.ca> Message-ID: <3kkgutFut490U1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: > > Peter Hansen wrote: > >> Would basestring() be a better name? > > > "tobase"? > > "tostring"? > > "tobasestring"? > > Of these choices, the latter would be preferable. > > > Alternative is to set a class attribute "Base" of the > > Path class. Or export PathBase as a name from the module > > (but that's not quite useful, because I > > expect Path to be imported via "from os.path import Path"). > > I don't understand how that would work. An attribute on the *class*? > What would it be, a callable? So mypath.Base(mypath) or something? > Please elaborate... [_base is str or unicode] class Path: Base = _base [...] So you could do "Path.Base(mypath)" or "mypath.Base(mypath)". > What about just .basestring, as a read-only attribute on the Path object? Reasonable, though the term as such is preoccupied too. Reinhold From grante at visi.com Wed Jul 6 10:47:12 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Jul 2005 14:47:12 -0000 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <11clc1v4el6no7d@corp.supernews.com> Message-ID: <11cnrngi4lrqn0a@corp.supernews.com> On 2005-07-06, Peter Hansen wrote: >>>Or is the Python interpreter actually doing the context >>>switches itself? >> >> Upon further thought, that just can't be the case. There has >> to be multiple instances of the intepreter because the >> interpreter can make C system calls that block (thus blocking >> that instance of the interpreter). Other Python threads within >> the program continue to run, so there must be multiple Python >> intepreters. > > Maybe you should consider and explain what you mean by > "multiple interpreters"? That in a multi-theraded Python program, the code that impliments the Python VM is executing "simultaneously" in multiple contexts: one for each thread (and possibly one master thread). I was responding to somebody who said that there were two issue with using multiple CPUs: 1) the interpreter (singular) only ran on one CPU. 2) the GIL. My point was that 1) couldn't be true. There must be multiple instances of the interpreter since in a multi-threaded Python program, the interpeter blocks when making libc calls like read() write() recv() send(), and yet other Python threads continue to run. If there _were_ only a single interpeter, and it ran only on a single CPU, then the GIL wouldn't be needed. > As I understand the concept, and based on my several years' > old reading of the virtual machine code, I wouldn't say there > are multiple interpreters. > > There's a reason the GIL is the *global* interpreter lock... Exactly. -- Grant Edwards grante Yow! I've been WRITING at to SOPHIA LOREN every 45 visi.com MINUTES since JANUARY 1ST!! From grante at visi.com Thu Jul 14 15:33:48 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 14 Jul 2005 19:33:48 -0000 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? References: <11ddckucctde603@corp.supernews.com> Message-ID: <11ddfgsg4nlch86@corp.supernews.com> On 2005-07-14, Tim Peters wrote: > Python does go out of its way to raise ZeroDivisionError when > dividing by 0. > >> 1/0 is defined by the standard as +Inf and 0/0 is NaN. >> >> That's what my platform does for programs written in C. > > IOW, that's what your platform C does (the behavior of these > cases is left undefined by the C89 standard, so it's not the > case that you can write a _portable_ C89 program relying on > these outcomes). True, but as a paracial matter, all of the C platforms I care about all do obey IEEE 754. > What does your platform C return for the integer expression > 42/0? Is any other outcome "wrong"? I guess I though it was obvious from my reference to IEEE 754 that I was referring to floating point operations. I don't know (or generally care) what my C platform does for integer divide by zero. >> Python apparently checks for division by zero and throws and >> exception rather than returning the correct value calculated >> by the underlying platform. >> >> Is there any way to get Python to return the correct results >> for those operations rather than raising an exception? > > No, except when using the decimal module. The latter provides > all the facilities in IBM's proposed standard for decimal > floating-point, which intends to be a superset of IEEE 854: > > http://www2.hursley.ibm.com/decimal/ > > It's relatively easy to do this in the decimal module because > it emulates, in software, all the gimmicks that most modern > FPUs provide in hardware. > > Note that support for 754 was rare on Python platforms at the > time Python was designed, and nobody mentioned 754 support as > even a vague desire in those days. I often foget how old Python is. Still, I've been using IEEE floating point in C programs (and depending on the proper production and handling of infinities and NaNs) for more than 20 years now. I had thought that Python might have caught up. > In the absence of user interest, and in the absence of HW > support for NaNs or infinities on most Python platforms, Really? I would have guessed that most Python platforms are '586 or better IA32 machines running either Windows or Linux. They all have HW support for NaNs and Infinities. > the decision to raise an exception was quite sensible at the > time. Python could not have implemented 754 semantics without > doing emulating fp arithmetic in SW on most platforms (as the > decimal module does today), and for much the same reasons you > can't give a non-silly answer to my earlier "what does your > platform C return for the integer expression 42/0?" question > today . > >> There's no way to "resume" from the exception and return a >> value from an exception handler, right? > > Correct. > > Note that there's a huge, current, informed discussion of > these issues already in the math.nroot thread. -- Grant Edwards grante Yow! It's OKAY --- I'm an at INTELLECTUAL, too. visi.com From jwaixs at gmail.com Mon Jul 4 06:37:02 2005 From: jwaixs at gmail.com (jwaixs) Date: 4 Jul 2005 03:37:02 -0700 Subject: f*cking re module In-Reply-To: References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <1120473422.864033.36350@o13g2000cwo.googlegroups.com> Thank you for your replies, it's much obvious now. I know more what I can and can't do with the re module. But is it possible to search for more than one string in the same line? bv. I want to replace the with " " with "\n" and every thing that's not between the two python tags must begin with "\nprint \"\"\"" and end with "\"\"\"\n"? Or do I need more than one call? From peter at engcorp.com Thu Jul 28 21:49:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Jul 2005 21:49:45 -0400 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Dan Sommers wrote: > The Zen applies to all aspects of software > (and other things, too, but they're off topic here), from human readable > reports and requirements and documentation, to GUI's, to test cases, to > code, to database schemta, as well as the development methodology and > practices themselves. > > Sometimes you have to look at the Zen sideways, so that "implementation" > appears to be replaced by the particular aspect or aspects (or the > software, or just software, as a whole, for the true Masters out there) > you happen to be working on at the time, but such is the nature of Zen. It also applies to Motorcycle Maintenance, of course... (as in "Zen and the Art of"). -Peter From grante at visi.com Thu Jul 7 10:42:11 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 14:42:11 -0000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> Message-ID: <11cqfq3norg5c84@corp.supernews.com> On 2005-07-07, Ron Adam wrote: >> class demo: >> def foo(v=None): >> if v is not None: >> self.v = v >> return self.v > > You are really checking if v exists, so having it undefined in > namespace as the default is consistent with what you are > doing. > > As I said above... > > >>>>It would be a way to set an argument as being optional without > >>>>actually assigning a value to it. > > So it would still work like you expect even though v is not > bound to anything. Like I said the bigger problem is that > globals will be visible and that would create a conflict. > Setting a value to None in a function hides globals of the > same name. That wouldn't happen if None unbound names as del > does. Good point. I hadn't thought of that. > So you would need to use something else for that purpose I > suppose, but that was why None became a literal in the first > place, so maybe it's taking a step backwards. > > >> 2) So I can use it as sort of a NaN equivalent. >> >> if self.fd is None: >> self.fd = os.open('foo.bar','w') >> >> if self.fd is not None: >> os.close(self.fd) >> self.fd = None > > It would still work as you expect. A while back I suggested an 'also' > for if that would do exactly that with only one test. Nobody liked it. > > if self.fd is None: > self.fd = os.open('foo.bar','w') > # do something with self.fd > > also: > os.close(self.fd) > self.fd = None > > >>>If a value isn't established yet, then do you need the name >>>defined? >> >> I find it more obvious to set the name to None during the >> periods that it isn't valid than to delete it and check for a >> NameError when I want to know if the value is usable or not. > > You would still be able to do that explicitly and it probably would be a > good idea when you aren't sure if a name is left over from something else. > > If a name is None, it means it's available and unassigned, so > you don't have to check for a NameError. How would you spell "if a name is None"? Personally, I think the spellings del name if 'name' in locals() is much more explicit/obvious than name = None name is None I expect the "=" operator to bind a name to a value. Having it do something completely different some of the time seems a bit unpythonic. -- Grant Edwards grante Yow! Today, THREE WINOS at from DETROIT sold me a visi.com framed photo of TAB HUNTER before his MAKEOVER! From rrr at ronadam.com Sun Jul 3 02:06:46 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 03 Jul 2005 06:06:46 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sat, 02 Jul 2005 20:26:31 -0700, Devan L wrote: > > >> Claiming that sum etc. do the same job is the whimper of >>someone who doesn't want to openly disagree with Guido. >> >>Could you give an example where sum cannot do the job(besides the >>previously mentioned product situation? > > > There is an infinite number of potential lambdas, and therefore an > infinite number of uses for reduce. > > > > sum only handles a single case, lambda x,y: x+y > > product adds a second case: lambda x,y: x*y > > So sum and product together cover precisely 2/infinity, or zero percent, > of all possible uses of reduce. But together, sum and product, probably cover about 90% of situations in which you would use reduce. Getting a total (sum) from a list probably covers 80% of the situations reduce would be used on it's own. (I can't think of any real uses of product at the moment. It's late.) I'm just estimating, but I think that is the gist of adding those two in exchange for reduce. Not that they will replace all of reduce use cases, but that sum and product cover most situations and can be implemented more efficiently than using reduce or a for loop to do the same thing. The other situations can easily be done using for loops, so it's really not much of a loss. Ron From rafi at free.fr Thu Jul 28 15:39:15 2005 From: rafi at free.fr (rafi) Date: Thu, 28 Jul 2005 21:39:15 +0200 Subject: multiple inheritance super() In-Reply-To: <1122548998.766210.101860@g47g2000cwa.googlegroups.com> References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> <42e748e9$0$32207$626a14ce@news.free.fr> <1122454160.835071.87690@z14g2000cwz.googlegroups.com> <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> Message-ID: <42e9346e$0$7835$626a14ce@news.free.fr> Michele Simionato wrote: >>http://fuhm.org/super-harmful/ > > > That is a pretty good page; I must say that my position is more radical > (i.e. it is not super which > is harmful, it is multiple inheritance itself that it is harmful: was I > going to design a new language > I would implement it *without* multiple inheritance). > > Michele Simionato > I do not agree on that point: Nobody is forced to used multiple inheritance, and when it is the right solution to be used, then it would be a shame not to have it. I remember the pain it was to implement some CORBA stuff using Java (moreover compared to C++) because of the lack of multiple inheritance. -- rafi "Imagination is more important than knowledge." (Albert Einstein) From peter at engcorp.com Tue Jul 12 00:40:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Jul 2005 00:40:05 -0400 Subject: Searching through a list of tuples In-Reply-To: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> References: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> Message-ID: Repton wrote: > I often find myself storing data in a list of tuples, and I want to ask > questions like "what is the index of the first tuple whose 3rd element > is x", or "give me the first tuple whose 2nd element is y". > > I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for > elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a > better way? > > (something like lst.index(x, key=..) or lst.find(y, key=..) would be > nice) If the latter form would make you happy, why not just write a simple utility function that does what you want (by using the first technique, if you wish), and then calling it will be as simple as lst.index(....) And no, since you are basically doing a form of pattern matching, I don't think there's a shortcut. -Peter From luis_lupe2XXX at netvisaoXXX.pt Mon Jul 25 12:32:57 2005 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Mon, 25 Jul 2005 17:32:57 +0100 Subject: PostgreSQL & Python vs PHP In-Reply-To: <42e372e6$0$5872$626a14ce@news.free.fr> References: <3kfaucFu3tlfU1@individual.net> <1122139628.703635.48610@g14g2000cwa.googlegroups.com> <3kfetaFu5fcrU1@individual.net> <42e372e6$0$5872$626a14ce@news.free.fr> Message-ID: <3kkiheFutdngU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I would like to thank all of you. For what I've read, I'll be using python instead of Php. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFC5RQ5Hn4UHCY8rB8RAi3QAKCuU3tgluOZXktbseUmq5d6WpyGCgCfWTCK hKweHnSkvEm/QLKwMw4uP2A= =6asH -----END PGP SIGNATURE----- From t-meyer at ihug.co.nz Thu Jul 28 22:52:55 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 29 Jul 2005 14:52:55 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: [using __div__ to mean join] > I'm not too happy with it, too, but do we have alternatives? > As paths are strings, we can hardly override the '+' operator, > so there's not much operators left. > > Of course, one can use joinwith() if he doesn't like '/'. My argument is that the alternative is to not provide an operator for this, and to force people to use the appropriate join function (joinwith, I gather). Not everything needs to have an operator! (In Python, at least ). Consider the 'discussion' regarding '@' and decorators. It's pretty clear that the Python community really isn't in favour of overloading characters with a lot of different meanings, and would much prefer being explicit (explicit is better than implicit, and all that). (Guido disagreed in this particular case, of course, but I believe that is an exception). I don't speak for python-dev or know for sure, but I suspect that the PEP would have a greater chance of acceptance (the goal, I presume) if this __div__ hackery wasn't in it. =Tony.Meyer From __peter__ at web.de Wed Jul 6 12:40:48 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Jul 2005 18:40:48 +0200 Subject: Conditionally implementing __iter__ in new style classes References: Message-ID: Thomas Heller wrote: > I'm trying to implement __iter__ on an abstract base class while I don't > know whether subclasses support that or not. > Hope that makes sense, if not, this code should be clearer: > > class Base: > def __getattr__(self, name): > if name == "__iter__" and hasattr(self, "Iterator"): > return self.Iterator > raise AttributeError, name > Is there any way I could make the above code work with new style > classes? Obligatory metaclass approach: class Base: class __metaclass__(type): def __new__(mcl, name, bases, classdict): try: classdict["__iter__"] = classdict["Iterator"] except KeyError: pass return type.__new__(mcl, name, bases, classdict) class Alpha(Base): def Iterator(self): yield 42 class Beta(Base): def __getitem__(self, index): return [1, 2, 3, "ganz viele"][index] for item in Alpha(): print item for item in Beta(): print item, print Peter From hancock at anansispaceworks.com Fri Jul 1 15:03:59 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 14:03:59 -0500 Subject: nested lists - utter newbie In-Reply-To: References: <1120206344.531419.54240@g47g2000cwa.googlegroups.com> Message-ID: <200507011403.59449.hancock@anansispaceworks.com> On Friday 01 July 2005 05:37 am, Benjamin Niemann wrote: > rahoool at gmail.com wrote: > > > Hi, > > why is this possible - > >>>>b = [1,2,3] > >>>>b[2] = b > >>>>b > > [1,2,[...]] > >>>>b[2] > > [1,2,[...]] > >>>>b[2][2][2][2][2] > > [1,2,[...]] > > > > but this is not - > >>>>x = [1,2,x] > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'x' is not defined > > Because the right hand side ('[1,2,x]') is evaluated *before* the value is > bound to the name 'x' - and at this point there is obviously no name 'x' > defined. OTOH, the name "b" was bound to the list, so it can be put into the list, just like any other name. At that point, the list contains a series of references, one of which happens to be to itself. If you are familiar with Unix/Linux filesystems, you've probably already seen behavior like this with either symbolic or hard links -- it's quite possible to create loops so that a directory is contained within itself. Such a structure is not strictly a "tree" any more, but a "directed graph". Those are the data structures terms for them, and you might try a little googling to learn more about them. The *really* smart thing is that Python *writes* the list as: [1,2,[...]] instead of printing a traceback due to "excessive recursion" which is what it used to do. This is because the representation method was changed to catch such circular references and stick in the "[...]" instead. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From paj at pajhome.org.uk Sat Jul 23 04:40:21 2005 From: paj at pajhome.org.uk (Paj) Date: 23 Jul 2005 01:40:21 -0700 Subject: Neat access to db query results Message-ID: <1122108021.130671.32330@f14g2000cwb.googlegroups.com> Hi, I often wish for a really high-level way to access db results, being willing to forego some efficiency. I came up with a class you can use like: cur = db.cursor() cur.execute('select abc, def from blah') for row in dbcur_iter(cur): print row['abc'], row['def'] Here's the class: class dbcur_iter: def __init__(self, cur): self.cur = cur self.names = [x[0] for x in cur.description] def __iter__(self): return self def next(self): x = cur.fetchone() if x is None: raise StopIteration return dict(zip(self.names, x)) Hope you find it useful! Do send me any feedback. Paul From steve at REMOVETHIScyber.com.au Thu Jul 21 11:43:28 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 22 Jul 2005 01:43:28 +1000 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> Message-ID: On Thu, 21 Jul 2005 10:27:24 -0400, Bill Mill wrote: [snip] > I said the *builtins* section. I think you learn pretty quick that > figuring out what functions are builtins is pretty important in every > language. There's a fair number of people out there giving the advice > to read chapter 2 of the library reference cover-to-cover for a good > starter on python. Sure. But for a beginner to start learning the language by reading the language manual is a bit much to ask. Some people can do it, but most learn best by doing, not by reading dry, abstract descriptions of what various functions do. In my experience, iterators and generators don't even make sense until you've spent some time playing with them. > Furthermore, I wasn't being hard on the guy, he still added up to +1. > Lighten up, I was joking. There is no need to get defensive, I was merely commenting on the need to understand that inexperienced programmers often don't know enough about the language to know where to start looking for the answer. In fact, it isn't just inexperienced programmers, but experienced programmers too. I'm sure Guido doesn't need to look up enumerate in the reference manual; but if he wanted to write a program to calculate the positions of the anti-nodes of vibratory modes of the bound-state of a muon and a proton/neutron pair, the odds are pretty good he wouldn't even know where to start looking either :-) The great thing about Usenet and the Internet is that we can pick each other's brains for answers, instead of flailing around blindly in manuals that don't understand the simplest natural language query. And isn't that why we're here? Regards, -- Steven. From bh at intevation.de Sat Jul 2 13:55:15 2005 From: bh at intevation.de (Bernhard Herzog) Date: Sat, 02 Jul 2005 19:55:15 +0200 Subject: Favorite non-python language trick? References: <42c5b862$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes: > Rocco Moretti wrote: >> Joseph Garvin wrote: >> >> I'm not aware of a language that allows it, but recently I've found >> myself wanting the ability to transparently replace objects.... >> I mainly look for it in the "object replaces self" form, but I guess >> you could also have it for arbitrary objects, e.g. to wrap a logging >> object around a function, even if you don't have access to all >> references of that function. >> Why isn't it in Python? It's completely counter to the conventional >> object semantics. > > Actually this is the old (and terrifying) Smalltalk message 'becomes:'. > There is a concrete reason it is not in python: objects are represented > as pointers to their data structures, do not have identical sizes, and > therefore cannot be copied into each others data space. That limitation applies only some of the time, e.g. when you inherit from built-in types. But for ordinary classes it can be done: >>> class A(object): ... def __init__(self, x): ... self.x = x ... >>> class B(object): ... def __init__(self, y): ... self.y = y ... >>> a = A(1) >>> b = B(2) >>> vars(a) {'x': 1} >>> vars(b) {'y': 2} >>> a.__class__, b.__class__ = b.__class__, a.__class__ >>> a.__dict__, b.__dict__ = b.__dict__, a.__dict__ >>> vars(a) {'y': 2} >>> isinstance(a, B) True Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From haraldarminmassa at gmail.com Fri Jul 22 07:14:18 2005 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 22 Jul 2005 04:14:18 -0700 Subject: PEP on path module for standard library In-Reply-To: References: <3kacleFslj6sU1@individual.net> Message-ID: <1122030858.575024.98420@g14g2000cwa.googlegroups.com> >Having path descend from str/unicode is extremely useful since I can >then pass a path object to any function someone else wrote without >having to worry about whether they were checking for basestring. I use path.py from Jason to encapsulate a lot of the windows plattform specialities of path dealing. Being able to use path-opjects at every place where I would use str or unicode is very essential, because I often use Python to tame Excel and Word. To open files within these programms needs some "plain str" as "PATH" for the file. (which, of course, can also be down by ways to "convert" PATH to STRING. Harald From cam.ac.uk at mh391.invalid Sun Jul 31 13:46:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 31 Jul 2005 18:46:37 +0100 Subject: shelve: writing out updates?! In-Reply-To: References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: phil hunt wrote: > But, what if the Python documentation was on a Wiki? Then it would > be easy to update! Of course, we would have to guard against false > or malicious updates, but Wikipedia manage that OK. The > Documentation Wiki could then be used as a basis for the "official" > documentation that comes with each new release. > > Does this idea make some sense? Or are there hidden pitfalls? I thought the `Annotatable Python Docs`_ were a good idea but they seem to have fallen into disuse. .. _Annotatable Python Docs: http://pydoc.amk.ca/frame.html -- Michael Hoffman From helge at aksdal.net Tue Jul 19 16:46:01 2005 From: helge at aksdal.net (Helge Aksdal) Date: Tue, 19 Jul 2005 22:46:01 +0200 Subject: socket programming In-Reply-To: References: <20050719184205.GA24773@mail.smule.com> Message-ID: <20050719204601.GB24773@mail.smule.com> * Jaime Wyant [2005/07/19 21:26]: > It sounds really strange to connect to a server "several hundred" > times. If I had to guess, the server monitored all of the connects > coming from your IP address and eventually stopped accepting ANY > connections. That's really what it eventually does, just that it refuses my connection, and a connection to another server is established. The alternative is to do it by http connection, but i'm afraid that's going to be too slow. or am i wrong here? To help you understand me better, this is a server at work that gives me some account information, so when i want to check "several hundred" accounts i need to look them up one by one since the server closes the connection after each query. -- Helge Aksdal From fdeserres at gmx.net Fri Jul 15 12:01:04 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Fri, 15 Jul 2005 18:01:04 +0200 Subject: Exception in callback => GPF? Message-ID: <42D7DDC0.3080802@gmx.net> Hiho, When there's an unhandled exception in my extension-module's-callback-into-Python-function-object, I get a GPF and Python exits. When the exception is being handled within the callback (hence in Python), I get a very significant hiccup (1 to 5 seconds freeze). Question: is there a specific way to deal with exceptions when they happen inside such a callback? I searched the web with no avail. All callbacks examples I've seen seem not to care about exceptions. Maybe of importance: the callback is initiated within a native thread. My C extension module is calling back into Python like this: /* Python callback function object. */ static PyObject * my_callback = NULL; /* C callback function passed to the implementation. */ static void external_callback(const MidiData * const data) { if (my_callback && (my_callback != Py_None)) { if (! data) { PyErr_SetString(PyExc_IndexError, getLastErrorMessage()); } else { PyObject * arglist = NULL; PyObject * result = NULL; PyGILState_STATE gil = PyGILState_Ensure(); arglist = Py_BuildValue("(i,i,s#)", data->deviceIndex, data->timestamp, data->buffer, data->size);// 0, 0, "test", 4);// result = PyEval_CallObject(my_callback, arglist); Py_DECREF(arglist); Py_DECREF(result); PyGILState_Release(gil); } } } TIA, Francois From __peter__ at web.de Tue Jul 12 00:48:40 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Jul 2005 06:48:40 +0200 Subject: Searching through a list of tuples References: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> Message-ID: Repton wrote: > I often find myself storing data in a list of tuples, and I want to ask > questions like "what is the index of the first tuple whose 3rd element > is x", or "give me the first tuple whose 2nd element is y". > > I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for > elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a > better way? > > (something like lst.index(x, key=..) or lst.find(y, key=..) would be > nice) >>> items = [(1, "a", 10), (2, "b", 20), (3, "c", 30)] >>> class Key(object): ... def __init__(self, key): ... self.key = key ... def __eq__(self, other): ... return self.key(other) ... >>> items.index(Key(lambda x: x[2] == 20)) 1 >>> items.index(Key(lambda x: x[1] == "c")) 2 A cleaner and probably faster solution would be to subclass list and override index()/find(). Peter From irmen.NOSPAM at xs4all.nl Fri Jul 1 03:00:23 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 01 Jul 2005 09:00:23 +0200 Subject: Scket connection to server In-Reply-To: References: Message-ID: <42c4ea08$0$64480$e4fe514c@news.xs4all.nl> Christopher Subich wrote: > Steve Horsley wrote: > >> There is a higher level socket framework called twisted that everyone >> seems to like. It may be worth looking at that too - haven't got round >> to it myself yet. > > > I wouldn't say 'like,' exactly. I've cursed it an awful lot (mostly for > being nonobvious), but it does a damn fine job at networking, especially > if you're comfortable building your own protocols. If you want a communication library that *is* obvious and easy to use, try Pyro http://pyro.sourceforge.net --Irmen From lordverminard at gmail.com Sat Jul 16 12:51:55 2005 From: lordverminard at gmail.com (lordverminard at gmail.com) Date: 16 Jul 2005 09:51:55 -0700 Subject: python certification Message-ID: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> i want to get a small certificate or diploma in python. it should be online cuz i live in pakistan and wont have teast centers near me. it should be low cost as i am not rich. and hopefully it would be something like a a begginer certification cuz i am new to python. From Florian.Lindner at xgm.de Sat Jul 2 11:30:59 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sat, 02 Jul 2005 17:30:59 +0200 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: Peter Hansen wrote: > godwin wrote: >> I wanna thank Martin for helping out with my ignorance concerning >> execution of stored procedure with python. Now i have decided to write >> a web app that googles into my companies proprietary database. > > Just checking... do you really mean "googles", or is that in your mind a > synonym for "search"? > >> I need >> to know whether zope is good for that job. > > For which part of it? The web part, or the searching part? It's not > likely sufficient for the searching part, since it doesn't include > database interfaces other than to its own ZODB. What proprietary > database is involved? That's not correct. Zope2 includes DB interfaces to MySQL, PostGre, ODBC and many others. For Zope3 IIRC there are not yet so many interfaces. Florian From rkern at ucsd.edu Thu Jul 7 15:42:40 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 07 Jul 2005 12:42:40 -0700 Subject: Python Module Exposure In-Reply-To: References: Message-ID: Jacob Page wrote: > I have created what I think may be a useful Python module, but I'd like > to share it with the Python community to get feedback, i.e. if it's > Pythonic. If it's considered useful by Pythonistas, I'll see about > hosting it on Sourceforge or something like that. Is this a good forum > for exposing modules to the public, or is there somewhere > more-acceptable? Does this newsgroup find attachments acceptable? No. Please put files somewhere on the web and post a URL. This would be a good forum to informally announce and discuss your module. Formal announcements once you, e.g. put it on SF should go to c.l.py.announce . -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bokr at oz.net Mon Jul 11 21:53:27 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 01:53:27 GMT Subject: extend for loop syntax with if expr like listcomp&genexp ? References: <42d30319.417620065@news.oz.net> <42d30af1$1@news.eftel.com> Message-ID: <42d31b7a.423861700@news.oz.net> On Tue, 12 Jul 2005 10:12:33 +1000, John Machin wrote: >Bengt Richter wrote: >> E.g., so we could write >> >> for x in seq if x is not None: > >Chundrous; looks like that p**l language ... ^^^^^^^^^--piqued my interest, where'd that come from? ;-) > >> print repr(x), "isn't None ;-)" >> >> instead of >> >> for x in (x for x in seq if x is not None): > >Byzantine ... Perhaps not if you wanted to enumerate the selected elements, as in for i, x in enumerate(x for x in seq if x is not None): > >> print repr(x), "isn't None ;-)" >> >> just a thought. >> > >What's wrong with the following? > >for x in seq: > if x is not None: > print repr(x), "isn't None ;-)" Nothing. Just noting that there's (at least) two kinds of for -- the plain old one, and the ones inside list comprehensions and generator expressions, and it struck me that not allowing the full listcomp/genexp syntax in the ordinary for context was a seemingly unnecessary restriction. Regards, Bengt Richter From newsgroups at jhrothjr.com Sat Jul 9 11:38:57 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 9 Jul 2005 09:38:57 -0600 Subject: removing list comprehensions in Python 3.0 References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> Message-ID: <11cvrskoskmmg7e@news.supernews.com> "Raymond Hettinger" wrote in message news:1120919382.609886.62680 at g14g2000cwa.googlegroups.com... > In all probability, both list comprehensions and generator expressions > will be around in perpetuity. List comps have been a very successful > language feature. > > The root of this discussion has been the observation that a list > comprehension can be expressed in terms of list() and a generator > expression. However, the former is faster when you actually want a > list result and many people (including Guido) like the square brackets. > > After the advent of generators, it seemed for a while that all > functions and methods that returned lists would eventually return > iterators instead. What we are learning is that there is a place for > both. It is darned inconvenient to get an iterator when you really > need a list, when you want to slice the result, when you want to see a > few elements through repr(), and when you need to loop over the > contents more than once. I was wondering about what seemed like an ill-concieved rush to make everything an iterator. Iterators are, of course, useful but there are times when you really did want a list. John Roth > > > Raymond Hettinger > From theller at python.net Wed Jul 6 11:57:42 2005 From: theller at python.net (Thomas Heller) Date: Wed, 06 Jul 2005 17:57:42 +0200 Subject: Conditionally implementing __iter__ in new style classes Message-ID: I'm trying to implement __iter__ on an abstract base class while I don't know whether subclasses support that or not. Hope that makes sense, if not, this code should be clearer: class Base: def __getattr__(self, name): if name == "__iter__" and hasattr(self, "Iterator"): return self.Iterator raise AttributeError, name class Concrete(Base): def Iterator(self): yield 1 yield 2 yield 3 The idea is that if a subclass of Base defines an 'Iterator' method, instances are iterable. They are not iterable otherwise. The above gives the expected behaviour: iter(Base()) raises a "TypeError: iteration over non-sequence", and iter(Concrete()) returns a generator. If, however, I make Base a newstyle class, this will not work any longer. __getattr__ is never called for "__iter__" (neither is __getattribute__, btw). Probably this has to do with data descriptors and non-data descriptors, but I'm too tired at the moment to think further about this. Is there any way I could make the above code work with new style classes? Thanks, Thomas From codedivine at gmail.com Wed Jul 6 19:42:24 2005 From: codedivine at gmail.com (Rahul) Date: 6 Jul 2005 16:42:24 -0700 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <1120693344.248307.46950@g49g2000cwa.googlegroups.com> Hi. Instead of listing the difference ..here are some things that are COMMON to both common lisp and python : 1.Dynamic typing. 2.garbage collection 3.powerful data structures 4.good object systems. (here people from lisp usually claim that clos is the most powerful object system...but i think python and lisp are comparable with none of them being better than the other. they are different than each other. and i consider clos without mop to be inferior. mop stands for meta object protocol...a thing which hasnt been specified in the ansi lisp standard but is provided by most implementations) 5.functions and types as first class objects 6.interactive development. The differences: 1.Macros : Macros are extremely powerful and a double edges sword. Dont believe anyone (whether they praise them or abhor them). Go and learn them and decide for yourself. 2.Readability : Python is generally believed to be far more readable than ANY other language. (Lisp isnt particularly unreadable). The only way to really find out which is better is to learn both and decide yourself. i personally like python , lisp and c. now c evokes derision from both python and lisp folks sometimes and thats incorrect too. rahul seberino at spawar.navy.mil wrote: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. > > It got me curious if Lisp > is inherently faster to develop complex apps in. It would seem if you > could create your own language in Lisp using macros that that would be > quite an advantage.... > > I realize that Python has operator overloading and OOP so I'm not sure. > > Any ideas? Any *evidence* one way or another? > > thanks! > > Chris From claird at lairds.us Fri Jul 22 19:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 22 Jul 2005 23:08:03 GMT Subject: Detecting computers on network References: <1122052633.489908.94230@g49g2000cwa.googlegroups.com> Message-ID: <6q98r2-1dm.ln1@lairds.us> In article <1122052633.489908.94230 at g49g2000cwa.googlegroups.com>, gene tani wrote: >Hi Sandeep, > >i didn't see where you said if these hosts you want to ping are on your >internal network, or beyond your gateway. Probably the only truly >reliable way to maintain an active hosts list is to install a >ping-sending client on them, like > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 > >And think about possible legal ramifications of port scanning hosts or >possibly getting your IP blacklisted by a host's firewall, before you >do it. > Let me shift that excellent summary very slightly: it might help to clarify what "active host" means. In some situations, managers just want to know, "which of our Web servers respond to requests for their top-level page?" If you're dealing with *that* (or which mail servers are serving mail, or ...), then it's entirely appropriate simply to perform the operation (to request a page through HTTP, for example) in question. From lee at example.com Fri Jul 22 17:50:17 2005 From: lee at example.com (Lee Harr) Date: Fri, 22 Jul 2005 21:50:17 GMT Subject: Query - Pexpect References: <1122041513.698420.278720@o13g2000cwo.googlegroups.com> Message-ID: On 2005-07-22, Girish wrote: > Hi , > > I wanna do some automation work using "pexpect". > I have an application which must be invoked from the command line in > linux environment,it consists of buttons,textboxes etc can i access > those widgets using "pexpect",say i wanna enter a value 3.3 in the > textbox and then click on the ok button,to run the apllication.The > application is developed using wxpython.ur suggestions will be of gr8 > help.plz do reply. > expect (and pexpect) read and write streams, so they are mostly used to control console-based applications. If your app also takes input on standard in and copies the commands to the textboxes and buttons then it might work. Otherwise you will need to look elsewhere. From onurb at xiludom.gro Fri Jul 8 04:53:50 2005 From: onurb at xiludom.gro (bruno modulix) Date: Fri, 08 Jul 2005 10:53:50 +0200 Subject: Pattern question In-Reply-To: <42cd5493$0$900$8fcfb975@news.wanadoo.fr> References: <42cd5493$0$900$8fcfb975@news.wanadoo.fr> Message-ID: <42ce3f20$0$13033$636a15ce@news.free.fr> cantabile wrote: > Hi, > > I'm trying to write a small installer for a server. But this program > should be able to run in the future under heterogenous environments and > os (at least linux/windows). I mean, the install will be done either in > text mode or curses or gtk or tk, either in debian or windows 2000 and > so on... > > The idea, at the moment, is as follows : > > class Server: > def __init__(self, params = None): > self.params = params > def __getattr__(self, attr): > return self.params.get(attr, None) > > class Installer: > def __init__(self, gui = None): > self.gui = gui > self.srv = None > > def update(self, dict): > self.srv = Server(dict) > > class Gui: > def __init__(self, installer = None): > self.installer = installer > def main(): > ## Some stuff here calling doIt() when the > ## user is done with filling various fields > > def doIt(self): > dict = {"param1":"qwerty", "param2":"uiop"} > self.installer.update(dict) > > def main(): > inst = Installer() > gui = Gui(inst) > inst.gui = gui > inst.gui.main() > > ## Here will be the actual install method > ## ... > > ## An example of accessing srv values: > print inst.srv.param1, inst.srv.param2 > > But, considering this code, I find the 3 first lines of my main() a bit > heavy. I have to inform inst that it has a 'gui', and Gui that it has an > 'installer'. I was trying to implement something looking like (very > roughly) to the Observer pattern (so that the Gui would be totally > independant from the actual install process). > I guess there is something wrong in my approach. Is there a better > pattern than this one for that kind of stuff ? > > Tanks for your help. You may want to have a look at the Factory pattern... # outrageously oversimplified dummy exemple class Gui(object): def __init__(self, installer): self.installer = installer class PosixGui(Gui): pass class Win32Gui(Gui): pass class GuiFactory(object): def getGui(self, installer): if os.name == 'posix': return PosixGui(installer) elif os.name == 'win32': return Win32Gui(installer) else: raise "os %s not supported" % os.name class Installer(object): def __init__(self, guiFactory): self.gui = guiFactory.getGui(self) def main(): inst = Installer(GuiFactory()) return inst.gui.main() NB 1: You may want to hide away the gui stuff: class Installer(object): def __init__(self): self.gui = GuiFactory().getGui(self) def main(self): return self.gui.main() def main(): return Installer().main() NB 2 : if it has to run in text mode, you should consider renaming "gui" to "ui", since a CLI is not really a 'graphical' ui !-) NB 3 : I made the GuiFactory a class, but it could also be a simple function. NB 4 : there are of course other solutions to the problem, which may or not be more appropriate... HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From http Mon Jul 25 05:07:42 2005 From: http (Paul Rubin) Date: 25 Jul 2005 02:07:42 -0700 Subject: Retrieving and saving images from internet address References: <1122282085.216772.286680@z14g2000cwz.googlegroups.com> Message-ID: <7xwtnf9rtt.fsf@ruckus.brouhaha.com> "rock69" writes: > http://www.infomedia.it/immagini/riviste/covers/cp/cp137.jpg > > and I would like to download that image and save it to a local file. > How do you do that in Python? See the docs for the urllib module. From edvard+news at majakari.net Fri Jul 1 06:52:48 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Fri, 01 Jul 2005 13:52:48 +0300 Subject: Escaping commas within parens in CSV parsing? References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> Message-ID: <87wtoa23y7.fsf@titan.staselog.com> felciano at gmail.com writes: > I am trying to use the csv module to parse a column of values > containing comma-delimited values with unusual escaping: > > AAA, BBB, CCC (some text, right here), DDD > > I want this to come back as: > > ["AAA", "BBB", "CCC (some text, right here)", "DDD"] Quick and somewhat dirty: change your delimiter to a char that never exists in fields (eg. null character '\0'). Example: >>> s = 'AAA\0 BBB\0 CCC (some text, right here)\0 DDD' >>> [f.strip() for f in s.split('\0')] ['AAA', 'BBB', 'CCC (some text, right here)', 'DDD'] But then you'd need to be certain there's no null character in the input lines by checking it: colsep = '\0' for field in inputs: if colsep in field: raise IllegalCharException('invalid chars in field %s' % field) If you need to stick with comma as a separator and the format is relatively fixed, I'd probably use some parser module instead. Regular expressions are nice too, but it is easy to make a mistake with those, and for non-trivial stuff they tend to become write-only. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From rbt at athop1.ath.vt.edu Fri Jul 22 09:49:16 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 22 Jul 2005 09:49:16 -0400 Subject: broken links In-Reply-To: References: Message-ID: <1122040156.31319.0.camel@athop1.ath.vt.edu> I found it: os.path.exists(path) On Fri, 2005-07-22 at 09:22 -0400, rbt wrote: > How can I find broken links (links that point to files that do not > exist) in a directory and remove them using Python? I'm working on RHEL4 > > Thanks, > rbt From stefan.rank at ofai.at Fri Jul 22 04:21:53 2005 From: stefan.rank at ofai.at (Stefan Rank) Date: Fri, 22 Jul 2005 10:21:53 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: <42E0ACA1.9000406@ofai.at> on 22.07.2005 00:21 Michael Hoffman said the following: > Reinhold Birkenfeld wrote: > >>John Roth wrote: >> >> >>>Why did Guido want a PEP? >> >>He said, >> >>""" >>Whoa! Do we really need a completely different mechanism for doing the >>same stuff we can already do? The path module seems mostly useful for >>folks coming from Java who are used to the Java Path class. > > """ > > What is this Java Path class? I have been STFWing and have found nothing > on it in the. Indeed if you search for "Java Path class" (with quotes) > almost half of the pages are this message from Guido. ;) > > Any Java hackers here want to tell us of the wonders of the Java Path > class? no such thing exists. there is only the `File` class that incorporates a little bit of the `path` functionality and some of the python built-in `file` functionality. my little self would actually propose to make *path* a built-in type as an intermediate between file and basestring/str/unicode (the latter is probably needed). *ducks* From rkern at ucsd.edu Fri Jul 15 07:39:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 15 Jul 2005 04:39:39 -0700 Subject: Question about basic use of a timer object from timeit module to execute code every so often in a class In-Reply-To: <1121426865.426413.86020@g47g2000cwa.googlegroups.com> References: <1121426865.426413.86020@g47g2000cwa.googlegroups.com> Message-ID: 42zeros at gmail.com wrote: > I would like a function to be executed every x often. > I was just wondering how to pass the following code correctly. my > object t just doesn't know what checkMail is. How can I tell it that > checkMail is a member of the class MyApp? Reread the documentation for timeit. It doesn't do what you think it does. Look at wxTimer instead. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bokr at oz.net Sun Jul 3 15:50:29 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Jul 2005 19:50:29 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: <42c83dec.443548208@news.oz.net> On Sat, 02 Jul 2005 13:50:25 GMT, "Andrew Koenig" wrote: >"Ralf W. Grosse-Kunstleve" wrote in message >news:mailman.1236.1120298654.10512.python-list at python.org... > >> class grouping: >> >> def __init__(self, .x, .y, .z): >> # real code right here > >> Emulation using existing syntax:: > >> def __init__(self, x, y, z): >> self.x = x >> del x >> self.y = y >> del y >> self.z = z >> del z > >I think this is a bad idea, for a subtle reason. > >In Python, unlike many other languages, the names of formal parameters are >part of a function's interface. For example: > > def f(x, y): > return x-y > >Now f(3, 4) is -1 and f(y=3,x=4) is 1. > >The names of instance variables are generally not part of a class' >interface--they are part of its implementation. > >This proposed feature, whenever used, would tie a class' implementation to >the interface of every method that uses the feature. As far as I can see, >it is impossible to use the feature without constraining the implementation >in this way. > >For this reason, I would much rather have the mapping between parameter >names and instance variables be explicit. > > What if parameter name syntax were expanded to allow dotted names as binding targets in the local scope for the argument or default values? E.g., def foometh(self, self.x=0, self.y=0): pass would have the same effect as def foometh(self, self.y=0, self.x=0): pass and there would be a persistent effect in the attributes of self (whatever object that was), even with a body of pass. I'm not sure about foo(self, **{'self.x':0, 'self.y':0}), but if you didn't capture the dict with a **kw formal parameter, IWT you'd have to be consistent and effect the attribute bindings implied. (Just a non-thought-out bf here, not too serious ;-) Regards, Bengt Richter From tim.golden at viacom-outdoor.co.uk Thu Jul 21 04:01:27 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 21 Jul 2005 09:01:27 +0100 Subject: Lots of pdf files Message-ID: <9A28C052FF32734DACB0A288A3533991044D2130@vogbs009.gb.vo.local> [Greg Lindstrom] | There does not appear to be a simple way to merge many pdf's | into one. I'm currently using ghostscript (on Win32) to merge multiple postscript files into one PDF (by specifying multiple inputs to the gswin32c command). I imagine it can do the same for multiple PDF inputs on Linux. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Fri Jul 22 14:29:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 14:29:18 -0400 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Duncan Booth wrote: > As I said elsewhere I haven't > used path for anything real, so I'm still finding surprises such as why > this doesn't do what I expect: > >>>>p = path('a/b') >>>>q = path('c/d') >>>>p+q > > path(u'a/bc/d') Just a note, though you probably know, that this is intended to be written this way with path: >>> p / q path(u'a/b/c/d') -Peter From daniel.dittmar at sap.corp Wed Jul 6 10:12:46 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 06 Jul 2005 16:12:46 +0200 Subject: Use cases for del In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Arguing the case for del: how would I, in doing automated testing, > ensure that I've returned everything to a "clean" starting point in all > cases if I can't delete variables? Sometimes a global is the simplest > way to do something... how do I delete a global if not with "del"? globals ().__delitem__ (varname) except that the method would probably be called delete. Daniel From roccomoretti at hotpop.com Wed Jul 27 17:45:31 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 27 Jul 2005 16:45:31 -0500 Subject: SciPy and NetCDF In-Reply-To: <1122499062.943121.65200@z14g2000cwz.googlegroups.com> References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> <1122499062.943121.65200@z14g2000cwz.googlegroups.com> Message-ID: Scott Kilpatrick wrote: > So wherever pycdf does a: > > from Numeric import * > > what is the equivalent for SciPy? i.e. where is the full Numeric module > in SciPy? Python packages are in a pretty flat hierarchy. There really isn't a "SciPy Numeric" and a "pycdf Numeric" - Numeric, as an independant module, installs to pretty much the same location regardless of what module has it as a dependancy. So "from Numeric import *" isn't importing Numeric as a subpackage of pycdf, it is importing it from the top level global package namespace. That was a long way of saying that "from Numeric import *" in pycdf is exactly the same as "from Numeric import *" in SciPy. Note that the local/global import issue is subject to a clarification/alteration in the near future - but for now we have to live with a little ambiguity. From jeffm at rivernet.com.au Tue Jul 12 13:24:48 2005 From: jeffm at rivernet.com.au (Jeff Melvaine) Date: Wed, 13 Jul 2005 03:24:48 +1000 Subject: Efficiency of using long integers to hold bitmaps References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> Message-ID: <42d3fced@news.rivernet.com.au> Bengt, Thanks for your informative reply, further comments interleaved. "Bengt Richter" wrote in message news:42d165d0.311819733 at news.oz.net... > On Mon, 11 Jul 2005 02:37:21 +1000, "Jeff Melvaine" > wrote: > >>I note that I can write expressions like "1 << 100" and the result is >>stored >>as a long integer, which means it is stored as an integer of arbitrary >>length. I may need to use a large number of these, and am interested to >>know whether the storage efficiency of long integers is in danger of >>breaking my code if I use too many. Would I do better to write a class >>that >>defines bitwise operations on arrays of integers, each integer being >>assumed >>to contain at most 32 bits? I cannot find information in the Python >>manuals >>for 2.4.1 that would allow me to resolve this question; perhaps the >>intention is that programmers should not rely on implementation details. >> >>Thanks in advance, >> > Sounds like a possible^H^H^H^H^H^H^H^Hprobable premature optimization > worry ;-) > I'm writing a Sudoku solver of generic order. The object is not to make it half a millisecond faster than the guy next door's solver, but I'd like it to be able to do a bit more than just the daily newspaper puzzle, e.g. search for uniquely solvable puzzles with minimal numbers of clues. NP-completeness will put a lid on things sooner or later, but I'd like to get as far as possible before that happens. Why in Python? All my recent professional experience is in writing Ada, which is not my idea of a rapid prototyping language (or a rapid deliverable item handover language either, for that matter :). Why do I want it to be efficient during debugging, rather than after fine tuning? I take your point, but in a sense the ability to handle large problems is part of the proof of concept. > What is a "large number of these" going to amount to? How many, tops? > And how many bits in each? How many operations between them? (Since > integers > are immutable, operations mean allocation of space for new ones for > results > and disposing of unused garbage ones (probably back to a special fast pool > for > integers and longs)). Are you interested in a speed/memory tradeoff? > The algorithms that interest me most do not involve cyclic data structures, so I am trusting in built-in reference counts to avoid memory leaks. At the moment I'm expecting to use bitmaps of constant size (81 for order 3, or 256 for order 4) for the most numerous data items, so fragmentation should not be excessive. Space was my first thought, but I also expect that the parallelism of bitwise operations will be reasonably time-efficient. I would hope to be able to do operations more quickly on a bitmap of n bits than on a list or array of n integer variables with values constrained to 0 or 1. However the prospect of writing "a & b" and getting multiword functionality that could prove the concepts was rather appealing too; almost executable pseudocode. The effectiveness of the algorithms will determine how much time and space I use, but for NP-complete problems the ceiling is always too low, and one is constantly learning new ways to duck. > If your bit vectors are extremely large and sparse (have only a few bits > "on"), > you might consider sets (import sets and help(sets)) of the bit numbers as > representations. > > BTW, I wonder if anyone has written an ordered bit set class in C yet. I > was tempted ;-) > For symbolic Boolean algebra on systems of 729 or 4096 variables, sparse is the way to go, but I would want ordered sets too. I've already implemented a Boolean algebra system using Python lists (oops, thank you again Raymond) of 32-bit bitmaps, and the calculations it does are not dazzlingly fast. My question about using long integers had a different approach in mind. > How much memory do you have? Buying more can be a pretty cheap way of > solving space worries > if you are getting paid for your time. > 512Mb. The only time I've hit the limit so far was when I got distracted enough to leave out the escape condition in a small recursive function. Death was surprisingly rapid. > You should be able to subclass int or long as a way of writing your > program in terms of > your own bit vector class. Then you can change your mind and change the > underlying representation > without changing the code that uses the api. Compared to plain longs it > will cost you some speed > to keep converting results to your own type though. > I like to encapsulate, but I hadn't thought of that one. Yes, it's an approach to getting the best of both worlds; instant performance or flexibility. The thought of executable pseudocode that I translate into something better if necessary is not too bad for now. > Bottom line, whether your code will "break" due to storage problems or be > fast enough > will depend on numbers you didn't provide ;-) > Re netiquette (with thanks to other posters who made this thread so stimulating), I don't demand that respondents to my posted questions should do all my thinking for me at a fine level of detail. But thank you Bengt, for taking the trouble to point me in helpful directions. It is certainly worth the OP's trouble to facilitate this for respondents. Jeff > Regards, > Bengt Richter From andre.roberge at gmail.com Fri Jul 22 12:52:29 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 22 Jul 2005 09:52:29 -0700 Subject: Python and Tablet PC: limitations? Message-ID: <1122051149.256485.209160@g44g2000cwa.googlegroups.com> I'm considering buying a Tablet PC and read somewhere (sorry, can't point to a link) that someone had tried running a "standard" Python program (wxMozilla demo I *think*, but can't be sure) that simply crashed. Any happy Tablet PC user/Python programmer combo? If so, any word of advice, suggestion as to best Tablet PC/accessory for a nice Python programming environment? Thanks to all in advance, Andr? From michele.simionato at gmail.com Fri Jul 22 06:38:03 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 22 Jul 2005 03:38:03 -0700 Subject: Web-Forms In-Reply-To: References: Message-ID: <1122028683.587356.288270@g43g2000cwa.googlegroups.com> Use twill:http://www.idyll.org/~t/www-tools/twill.html Michele Simionato From bdesth.quelquechose at free.quelquepart.fr Sat Jul 23 05:30:19 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 23 Jul 2005 11:30:19 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e20737$0$21113$626a14ce@news.free.fr> Thanos Tsouanas a ?crit : > Hello. > > I would like to have a quick way to create dicts from object, so that a > call to foo['bar'] would return obj.bar. > > The following works, but I would prefer to use a built-in way if one > exists. Is there one? > > Thanks in advance. > > class dictobj(dict): > """ > class dictobj(dict): > A dictionary d with an object attached to it, > which treats d['foo'] as d.obj.foo. > """ > def __init__(self, obj): > self.obj = obj > def __getitem__(self, key): > return self.obj.__getattribute__(key) I'd replace this last line with: return getattr(self.obj, key) Now given your specs, I don't see what's wrong with your solution. From bogus@does.not.exist.com Fri Jul 1 10:05:02 2005 From: bogus@does.not.exist.com () Date: Fri, 01 Jul 2005 14:05:02 -0000 Subject: No subject Message-ID: #! rnews 1856 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!tiscali!transit0.news.tiscali.nl!tudelft.nl!txtfeed1.tudelft.nl!feeder1.cambrium.nl!feed.tweaknews.nl!news2.euro.net!newsfeed.freenet.de!newspeer1.nwr.nac.net!in.100proofnews.com!in.100proofnews.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Modules for inclusion in standard library? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 26 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <3ian37Fkjle0U1 at individual.net> <11c343ho6i6hv17 at news.supernews.com> <1x6lpi6z.fsf at python.net> <7xwtodvzsv.fsf at ruckus.brouhaha.com> <7x3br1ger1.fsf at ruckus.brouhaha.com> <86slyza5hn.fsf at bhuda.mired.org> Mime-Version: 1.0 Date: Fri, 1 Jul 2005 13:46:28 GMT Xref: news.xs4all.nl comp.lang.python:384359 Mike Meyer writes: > Harry George writes: > > > b) Installing distutils-aware python packages is trivial. I'd rather > > the energy which might go into a bigger std library go instead into > > helping projects which don't have distutils-style builds. > > How about integrating distutils and PyPI, so that distutils can > automatically download and install packages that are required by the > package it's currently installing? In other words, C-Python-AN. > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. I personally don't do auto download/installs, preferring instead to scan the code before build/install. However, getting a list of dependencies would be nice. Maybe a setup.py --requires flag. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From thomas at thomas-lotze.de Sat Jul 9 17:10:49 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sat, 09 Jul 2005 23:10:49 +0200 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Steve Juranich wrote: > I was wondering how true this holds for Python, where exceptions are such > an integral part of the execution model. It seems to me, that if I'm > executing a loop over a bunch of items, and I expect some condition to > hold for a majority of the cases, then a "try" block would be in order, > since I could eliminate a bunch of potentially costly comparisons for each > item. Exactly. > But in cases where I'm only trying a single getattr (for example), > using "if" might be a cheaper way to go. Relying on exceptions is faster. In the Python world, this coding style is called EAFP (easier to ask forgiveness than permission). You can try it out, just do something 10**n times and measure the time it takes. Do this twice, once with prior checking and once relying on exceptions. And JFTR: the very example you chose gives you yet another choice: getattr can take a default parameter. > What do I mean by "cheaper"? I'm basically talking about the number of > instructions that are necessary to set up and execute a try block as > opposed to an if block. I don't know about the implementation of exceptions but I suspect most of what try does doesn't happen at run-time at all, and things get checked and looked for only if an exception did occur. An I suspect that it's machine code that does that checking and looking, not byte code. (Please correct me if I'm wrong, anyone with more insight.) -- Thomas From Scott.Daniels at Acm.Org Fri Jul 8 11:21:53 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 08 Jul 2005 08:21:53 -0700 Subject: Use cases for del In-Reply-To: References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> Message-ID: <42ce923f@nntp0.pdx.net> Ron Adam wrote: > Here's something interesting: > > import time > > x = None > t = time.time() > for i in range(1000000): > if x==None: > pass > print 'None:',time.time()-t > > x = 'to-end' > t = time.time() > for i in range(1000000): > if x=='to-end': > pass > print 'String:',time.time()-t > > >>> > None: 0.46799993515 > String: 0.360000133514 > > > Of course the difference this would make on a single call in practically > Nill. > > Anyway, time to call it a night so tomorrow I don't make anymore silly > mistakes on comp.lang.python. :) > > Cheers, > Ron > Try this: import time def timed(number): nreps = ereps = [None] * number t0 = time.time() x = None for i in ereps: if x == None: pass x = 'to-' + 'end' # make sure equal string, not identical string for i in nreps: if x == None: pass t1 = time.time() for i in ereps: if x == 'to-end': pass x = None for i in nreps: if x == 'to-end': pass t2 = time.time() x = None for i in ereps: if x is None: pass x = 'to-end' # magic unnecessary here. for i in nreps: if x is None: pass return t0, t1, t2, time.time() t0, t1, t2, t3 = timed(1000000) print '== None:', t1 - t0 print '== String:', t2 - t1 print 'is None:', t3 - t2 =========================== == None: 0.578000068665 == String: 0.594000101089 is None: 0.31200003624 Testing for None should be an is-test (not just for speed). In older pythons the == result wasn't necessarily same as is-test. This made sense to me after figuring out NULL in database stuff. is-test will always work for None despite the other half. Not so for bogus objects like: >>> class WildCard(object): def __eq__(self, other): return True >>> (WildCard() is None), (None is WildCard()) (False, False) >>> (WildCard() == None), (None == WildCard()) (True, True) --Scott David Daniels Scott.Daniels at Acm.Org From pawel at sakowski.pl Thu Jul 7 11:08:31 2005 From: pawel at sakowski.pl (=?ISO-8859-2?Q?Pawe=B3?= Sakowski) Date: Thu, 07 Jul 2005 17:08:31 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: Tom Anderson wrote: > def flatten(ll): > return reduce(lambda a, l: a.extend(l), ll, []) > > How would one do that as a list comp, by the way? I'm really not very good > with them yet. Not really a list-comprehension based solution, but I think what you want is >>> ll=[[1,2],[3,4,5],[6]] >>> sum(ll,[]) [1, 2, 3, 4, 5, 6] -- Pawe? Sakowski From godwinburby at rediffmail.com Wed Jul 13 04:24:43 2005 From: godwinburby at rediffmail.com (Godwin) Date: 13 Jul 2005 01:24:43 -0700 Subject: Web App like Google In-Reply-To: <1121234930.929540.47140@o13g2000cwo.googlegroups.com> References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> <1121234930.929540.47140@o13g2000cwo.googlegroups.com> Message-ID: <1121243083.069998.210100@g14g2000cwa.googlegroups.com> Thanks for making me aware of the security loophole of the web app i am planning. Godwin Burby From me at nowhere.invalid Wed Jul 20 15:30:45 2005 From: me at nowhere.invalid (Mike L.G.) Date: Wed, 20 Jul 2005 19:30:45 GMT Subject: wxPython && wxGlade Message-ID: Hello! Is there a way to span columns using wxGlade? I'd like to get a layout that looks like this: |---------------| ||-----||------|| ||edit ||button|| ||-----||------|| ||-------------|| || button || ||-------------|| |---------------| I would like the 2nd button on the 2nd row to span to the 2nd column. I've been able to span rows and columns using wxGridBagSizer, but wxGlade does not seem to offer this type of sizer. Is this layout visibly possible using wxGlade? Thank you for your time. -- Mike L.G. http://www.mahalosoft.com From steve at REMOVETHIScyber.com.au Tue Jul 19 09:56:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 19 Jul 2005 23:56:19 +1000 Subject: Dictionary, keys and alias References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> <5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: On Tue, 19 Jul 2005 10:20:04 +0200, Glauco wrote: >> The only niggly worry I have is I'm not sure when hash can be used, when >> it is unique, or even if is it guaranteed to be unique. >> > > Thank Steve, the idea was the same... > but yours using hash is much elegant. I'm still worried about hash of two unrelated objects returning the same value. Another implementation is to keep a hidden attribute of the object, and initialise it to the integer 0. Instead of using hash(key), you use the current value of the integer, then increment the integer by one. This is guaranteed to be unique, no matter what. -- Steven. From bokr at oz.net Mon Jul 4 10:43:07 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 04 Jul 2005 14:43:07 GMT Subject: OT: ^ in redirection (windows) References: Message-ID: <42c94383.510514691@news.oz.net> On 4 Jul 2005 13:07:02 GMT, Duncan Booth wrote: >Miki Tebeka wrote: > >> Can someone explain me the difference between: >> echo 1 > 1.txt 2>&1 >> and >> echo 1 > 1.txt 2>^&1 >> >> (Windows XP "cmd" shell) >> >> Both produce 1.txt with the content 1. >> >> (Sadly, I don't know how to search for ^ in google). >> > >The first of these joins stderr to stdout, but since there is no output to >stderr has no visible effect. > >The second should prevent special treatment of the & character, but in this >particular case actually has no effect. > >You can see the effects more clearly if you redirect a handle which >actually does have some output: > >stdout redirected to stderr, but stderr still goes to console so no visible >effect: > >C:\temp>echo hi 1>&2 >hi > >stdout redirected to stderr, then stderr redirected to a file, but stdout >still points at original stderr so no visible effect: > >C:\temp>echo hi 1>&2 2>x.txt >hi > >stderr redirected to a file, then stdout redirected to same file. Output >goes in a file: >C:\temp>echo hi 2>x.txt 1>&2 > >C:\temp>type x.txt >hi > >Same as above. Using ^ to avoid special interpretation of the & has no >effect: >C:\temp>echo hi 2>x.txt 1>^&2 > >C:\temp>type x.txt >hi > You'd think ^ would be mentioned in http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx but it seems not to be. Regards, Bengt Richter From hancock at anansispaceworks.com Sun Jul 31 10:02:15 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 31 Jul 2005 09:02:15 -0500 Subject: Wheel-reinvention with Python In-Reply-To: <87mzo4zsu4.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: <200507310902.15748.hancock@anansispaceworks.com> On Saturday 30 July 2005 01:54 am, Torsten Bronger wrote: > Calvin Spealman writes: > > > The choice is GUI toolkits is largely seperate from > > Python. Consider that they are just bindings to libraries that are > > developed completely seperate of the language. GUI is should be > > seperate from the language, and thus not bound to same > > expectations and desires as elements of the language itself. > > I disagree. A modern language must provide a convenient and > well-embedded way to write GUI applications. I know I'm diving into this conversation late, and I haven't read the whole thread, but has someone yet mentioned the "anygui" project? This has stalled, but it was IMHO a good idea. It sounds as if you are re-voicing the need that instigated the project in the first place. http://anygui.sourceforge.net/ AFAIK, the project stalled because not enough people were sufficiently interested in the need. Some people said that just using wx or Tkinter was easier. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From fperez.net at gmail.com Mon Jul 18 20:09:15 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Mon, 18 Jul 2005 18:09:15 -0600 Subject: goto References: Message-ID: Steven Bethard wrote: > Hayri ERDENER wrote: >> what is the equivalent of C languages' goto statement in python? > > Download the goto module: > http://www.entrian.com/goto/ > And you can use goto to your heart's content. And to the horror of all > your friends/coworkers. ;) > > STeVe That is actually a _really_ cool piece of code, in terms of showing off the kind of things which are possible in python if you're willing to be a little sneaky. Thanks for the pointer ! best f From exarkun at divmod.com Thu Jul 21 11:07:55 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 21 Jul 2005 11:07:55 -0400 Subject: Overriding a built-in exception handler In-Reply-To: <1121956750.750199.289050@g14g2000cwa.googlegroups.com> Message-ID: <20050721150755.26278.470011266.divmod.quotient.15464@ohm> On 21 Jul 2005 07:39:10 -0700, callmebill at gmail.com wrote: >I'm having a tough time figuring this one out: > > >class MyKBInterrupt( ..... ): > print "Are you sure you want to do that?" > >if __name__ == "__main__": > while 1: > print "Still here..." > > >So this thing keeps printing "Still here..." until the user hits ctl-c, >at which time the exception is passed to MyKBInterrupt to handle the >exception, rather than to whatever the built-in handler would be. > >I've Read-TFM, but I only see good info on how to create my own class >of exception; I don't see anything on how to override an existing >exception handler. > >Thanks in advance for any help. See excepthook in the sys module documentation: http://python.org/doc/lib/module-sys.html Jp From gsakkis at rutgers.edu Fri Jul 1 01:33:19 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 22:33:19 -0700 Subject: Splitting string into dictionary References: <59e9fd3a0506302121197c545a@mail.gmail.com> <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> Message-ID: <1120195999.101197.135740@z14g2000cwz.googlegroups.com> "Robert Kern" wrote: > Ignore the last message. > > translations = [x.strip(" '") for x in line.split('|')] > d = dict(zip(translations[::2], translations[1::2])) Or in case you're working with a lot and/or huge records, the second line can be more efficiently written as: from itertools import izip, islice d = dict(izip(islice(translations,0,None,2), islice(translations,1,None,2))) George From python at rcn.com Sat Jul 23 12:28:22 2005 From: python at rcn.com (Raymond Hettinger) Date: 23 Jul 2005 09:28:22 -0700 Subject: list implementation References: <1121655435.153214.292520@o13g2000cwo.googlegroups.com> <1121665250.103706.323680@g47g2000cwa.googlegroups.com> Message-ID: <1122136102.185277.180110@f14g2000cwb.googlegroups.com> > > [sj] > >> Thus, random access is an O(1) operation while insertion/deletion is an > >> O(n) operation. [Raymond Hettinger] > > Yes. [Heikki Orsila aka host.invalid] > Unfortunately no. Check Terry Reeds answer. Random access is O(1), > insertion/deletion to front is O(n), and i/d to back is O(1). The back > i/d operation has amortized O(1) cost. Duh. Excellent misreading of a simple answer to the OP's plain question. It is clear from his post that he already had a pretty accurate guess about how lists were implemented and the consequent performance implications. What was needed was a confirmation of his guess and a pointer to collections.deque() for O(1) insertion/deletion on the ends. For O(1) length changing ops in the middle, his suggestion of a linked list was not off base. IOW, a simple yes would have served. Raymond P.S. Non-standard abbreviations like, i/d, are rarely helpful to your readers. From spam.csubich+block at block.subich.spam.com Sun Jul 3 01:11:53 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 01:11:53 -0400 Subject: What are the other options against Zope? In-Reply-To: References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: Dennis Lee Bieber wrote: > The Windows registry is "a maze of twisty little passages, all > alike" ITYM "a maze of twisty little passeges, {058C1536-2201-11D2-BFC1-00805F858323}" > The registry a cryptic, bloated, system by which M$ can hide > details about anything they want... Instead of having separate .INI > files scattered about. A registry, in general, is a decent idea. It's more robust and more permanent than environment variables, and the centralization is better than INI files scattered about (probably). The problem is that the Windows Registry has passed beyond all mortal ken, probably sometime around when they started indexing things by GUID, losing any hierarchy based on application. That, and the file format definitely isn't robust to bit-rot that happened too often on FAT16/32 filesystems. From thomas at thomas-lotze.de Thu Jul 21 04:54:29 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Thu, 21 Jul 2005 10:54:29 +0200 Subject: is this pythonic? References: Message-ID: Mage wrote: > Or is there better way? > > for (i, url) in [(i,links[i]) for i in range(len(links))]: > ... > > "links" is a list. for i, url in enumerate(links): -- Thomas From darkcowherd at gmail.com Sat Jul 23 11:25:21 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Sat, 23 Jul 2005 20:55:21 +0530 Subject: What is your favorite Python web framework? In-Reply-To: <1122048187.041743.205780@g43g2000cwa.googlegroups.com> References: <1122048187.041743.205780@g43g2000cwa.googlegroups.com> Message-ID: <5f4d3cb50507230825591c4bcd@mail.gmail.com> Hi, I have also been looking around to start web development. Almost everybody says - "Zope ooooh steep learning curve", so looking at alternatives. But to people have got past that curve. Is Zope worth it. My applications would be data entry heavy. Think inventory and accounting apps. Would going past the learning curve allow me to write applications like that. -- Dark Cowherd From jepler at unpythonic.net Mon Jul 18 11:46:22 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Jul 2005 10:46:22 -0500 Subject: Windows command line problem In-Reply-To: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> Message-ID: <20050718154621.GE2199@unpythonic.net> I don't exactly know what is going on, but '\x96' is the encoding for u'\N{en dash}' (a character that looks like the ASCII dash, u'\N{hyphen-minus}', u'\x45') in the following windows code pages: cp1250 cp1251 cp1252 cp1253 cp1254 cp1255 cp1256 cp1257 cp1258 cp874 Windows is clearly doing something clever. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVETHIScyber.com.au Sat Jul 23 23:36:53 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 13:36:53 +1000 Subject: consistency: extending arrays vs. multiplication ? References: Message-ID: On Sat, 23 Jul 2005 18:30:02 +0200, Soeren Sonnenburg wrote: > Hi all, > > Just having started with python, I feel that simple array operations '*' > and '+' don't do multiplication/addition but instead extend/join an > array: * and + are not array operations, they are list operations. Lists in Python can contain anything, not just numeric values. Python doesn't have built-in mathematical arrays, otherwise known as matrices. There are modules that do that, but I haven't used them. Google on Numeric Python. -- Steven. From fuzzyman at gmail.com Sat Jul 16 05:23:22 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Jul 2005 02:23:22 -0700 Subject: IDLE in Jython In-Reply-To: References: <1121436094.769121.247470@z14g2000cwz.googlegroups.com> Message-ID: <1121505802.554885.106600@g43g2000cwa.googlegroups.com> Pippy looks pretty dead. Wasn't someone else working on a Palm port ? Best Regards, Fuzzyman http://www.voidspace.org.uk/python From rutski89 at gmail.com Fri Jul 1 23:56:24 2005 From: rutski89 at gmail.com (Patrick Rutkowski) Date: Fri, 1 Jul 2005 23:56:24 -0400 Subject: Bad Math Message-ID: I started reading a python book today, one example was: >>> 4 / (2.0 + 3) 0.8 My input/output was: >>> 4 (2.0 + 3) 0.80000000000000004 Something smells fishy here... whats up? --python 2.4.1 From paolo.veronelli at gmail.com Thu Jul 28 14:42:19 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Thu, 28 Jul 2005 20:42:19 +0200 Subject: Advanced concurrancy In-Reply-To: References: Message-ID: <42E9270B.9040109@gmail.com> Peter Tillotson wrote: > Hi, > > I'm looking for an advanced concurrency module for python and don't seem > to be able to find anything suitable. Does anyone know where I might > find one? I know that there is CSP like functionality built into > Stackless but i'd like students to be able to use a standard python build. > > I'm trying to develop distributed / Grid computing modules based on > python. The aim is to be able to use barriers for synchronisation and > channels for communication between processes running on a single box. > Then the jump to multiple processes on multiple boxes and eventually to > MPI implementations. Hopefully, each jump should not be that big a leap. > > Of course it would be nice if there was a robust way of managing > concurrency in python aswell ;-) > And deferredGenerator in twisted.internet.defer is the robust way for that. It blows up python readability in contrast,but once you got them and made your library I think they are also usable. I do believe, without deferreds in the core ,python will have bad times surviving the net, but that's really an opinion. Have fun, Paolino From jepler at unpythonic.net Sun Jul 10 22:46:20 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 10 Jul 2005 21:46:20 -0500 Subject: Efficiency of using long integers to hold bitmaps In-Reply-To: <42d14ec3@news.rivernet.com.au> References: <42d14ec3@news.rivernet.com.au> Message-ID: <20050711024616.GA21228@unpythonic.net> You'll find that using Python Longs unsuitable if you *change* the bitmaps---All numeric types are immutable, so you'll copy the bitmap each time you perform an operation like "set bit". numarray has a 'bit' typecode, though I'm not sure how such an array is actually stored---from a quick look, it appears it's stored one bit per byte: >>> numarray.ones((3,3), 'Bool').tostring() '\x01\x01\x01\x01\x01\x01\x01\x01\x01' A Python object layer around array.array('B') would not necessarily be fast, but it would at least avoid the copying problem, and be memory efficient. import array class BitArray2D: def __init__(self, rows, cols): self.rows = rows self.cols = cols nbytes = (rows * cols + 7) / 8 self._data = array.array('B', [0]) * nbytes def __getitem__(self, (r,c)): # TODO: check r, c in bounds idx = r + c * self.rows byte = idx / 8 bit = 1 << (idx%8) return bool(self._data[byte] & bit) def __setitem__(self, (r, c), v): # TODO: check r, c in bounds idx = r + c * self.rows byte = idx / 8 bit = 1 << (idx%8) if v: self._data[byte] |= bit else: self._data[byte] &= ~bit b = BitArray2D(10, 10) print b._data for x in range(10): b[x,x] = b[9-x,x] = 1 print b._data print for x in range(10): for y in range(10): print " *"[b[x,y]], print Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVEMEcyber.com.au Thu Jul 21 21:51:02 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 22 Jul 2005 11:51:02 +1000 Subject: Difference between " and ' References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> Message-ID: <42E05106.5060905@REMOVEMEcyber.com.au> Michael Hoffman wrote: > John Machin wrote: > >> b83503104 at yahoo.com wrote: >> >>> Can someone tell me the difference between single quote and double >>> quote? >> >> >>> ord("'") - ord('"') >> 5 > > Very zen. But unfortunately incorrect, since the original poster didn't ask for the difference between the ordinal values of the single quote and double quote characters, but for the difference between the characters themselves. The question was in plain English, and in my opinion, perfectly understandable, especially since some common programming languages do have significant differences between single-quoted strings and double-quoted strings. It may shock some people to learn that difference in the sense of mathematical subtraction is not the only meaning of the word, but there it is. One wouldn't, I hope, misunderstand "What is the difference between spaghetti marinara and spaghetti pescatora?" and attempt to subtract one from the other, since subtraction is not defined for foodstuffs. -- Steven. From teoryn at gmail.com Mon Jul 25 09:27:33 2005 From: teoryn at gmail.com (teoryn) Date: 25 Jul 2005 06:27:33 -0700 Subject: Problem loading a file of words In-Reply-To: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> Message-ID: <1122298053.790180.292810@g43g2000cwa.googlegroups.com> Thanks to everyone for all the help! Here's the (at least for now) final script, although note I'm using 2.3.5, not 2.4, so I can't use some of the tips that were given. #!/usr/bin/python # Filename: unscram.py def sort_string(word): '''Returns word in lowercase sorted alphabetically''' word_list = list(word.lower()) word_list.sort() return ''.join(word_list) print 'Building dictionary...', dictionary = { } f = file('/usr/share/dict/words', 'r') for line in f.readlines(): line = line.strip() # remove whitespace at both ends if line: # line is not the empty string line = line.lower() sline = sort_string(line) if sline in dictionary: dictionary[sline].append(line) #print 'Added %s to key %s' % (line,sline) else: dictionary[sline] = [line] #print 'Created key %s for %s' % (sline,line) f.close() print 'Ready!' lookup = raw_input('Enter a scrambled word : ') while lookup: try: results = dictionary[sort_string(lookup)] for x in results: print x, print except: print "?????" lookup = raw_input('Enter a scrambled word : ') As for the end of the file idea, that word wasn't at the end of the file, and there was a blank line, so that's out of the question. The word list I was using was 272,520 words long, and I got it a while back when doing this same thing in java, but as you can see now I'm just using /usr/share/dict/words which I found after not finding it in the place listed in Nick's comment. I'm still lost as to why my old code would only work for the small file, and another interesting note is that with the larger file, it would only write "zzz for zzz" (or whatever each word was) instead of "Created key zzz for zzz". However, it works now, so I'm happy. Thanks for all the help, Kevin From Scott.Daniels at Acm.Org Sun Jul 3 11:14:28 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 03 Jul 2005 08:14:28 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: <42c7f923$1@nntp0.pdx.net> egbert wrote: > On Sat, Jul 02, 2005 at 08:26:31PM -0700, Devan L wrote: > >>Also, map is easily replaced. >>map(f1, sequence) == [f1(element) for element in sequence] > > How do you replace > map(f1,sequence1, sequence2) > especially if the sequences are of unequal length ? > > I didn't see it mentioned yet as a candidate for limbo, > but the same question goes for: > zip(sequence1,sequence2) OK, you guys are picking on what reduce "cannot" do. The first is [f1(*args) for args in itertools.izip(iter1, iter2)] How to _you_ use map to avoid making all the intermediate structures? I never saw anything about making zip go away. It is easy to explain. Now reduce maps to what I was taught to call "foldl." How do you express "foldr?" How do you express: _accum = initial() for elem in iterable: _accum = func(elem, _accum, expr) ... If you want functional programming in python, you have at least three big problems: 1) Python has side effect like mad, so order of evaluation matters. I'd claim any useful language is like that (I/O to a printer is kind of hard to do out-of-order), but I'd get sliced to death by a bunch of bullies wielding Occam's razors. 2) Python's essential function call is not a single-argument function which might be a tuple, it is a multi-argument function which is not evaluated in the same way. The natural duality of a function taking pairs to a function taking an arg and returning a function taking an arg and returning a result breaks down in the face of keyword args, and functions that take an indeterminate number of arguments. Also, because of (1), there is a big difference between a function taking no args and its result. 3) Python doesn't have a full set of functional primitives. Fold-right is one example, K-combinator is another, .... Why pick on reduce as-is to keep? There is another slippery slope argument going up the slope adding functional primitives. --Scott David Daniels Scott.Daniels at Acm.Org From roccomoretti at hotpop.com Tue Jul 12 12:20:48 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 12 Jul 2005 11:20:48 -0500 Subject: Why does reply to messages on this list put the sender in the To In-Reply-To: References: <5f4d3cb5050712081720b880ac@mail.gmail.com> Message-ID: Peter Decker wrote: > On 7/12/05, Dark Cowherd wrote: > > >>Most lists when i hit reply it puts the list address back in the To >>address and some lists allow you to configure this. >> >>But in this list reply sends the mail back as a private mail and there >>seems to be no option to configure this. >> > In cases where people are discussing problems and supplying solutions, > replying to the list is essential so that as many people as possible > can benefit from the knowledge contained in the reply. Private replies > only benefit the lone recipient, while list replies benefit everyone > on the list and everyone who later searches the archives. There have been some q&a lists I've been on where the sole content of the list is people posting questions. Questions rarely get a response on-list. It makes the list practically worthless. To top it off, the archive of the mailing list only lists the questions, but never the (private) answers. It makes Google a pain to use, as you get hits to people asking the same question you want, but never the answers. Sorry, had to vent. From bdesth.quelquechose at free.quelquepart.fr Sat Jul 23 09:03:17 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 23 Jul 2005 15:03:17 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: <20050723084827.GA6903@zermelo.sians.org> <42E216C1.70707@tiscali.it> Message-ID: <42e23920$0$18458$636a15ce@news.free.fr> Thanos Tsouanas a ?crit : > On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote: > >>use getattr(self.obj,key) possibly, as __getattribute__ gets total >>control on attribute access > > > Thanks, but what do you mean by 'total control'? __getattribute__ is really some kind of an evil black voodoo mumbo jumbo juju magic method... More seriously: __getattr__() (if defined) is called when and if the 'normal' attribute lookup process failed. It's main use is to delegate attribute access to a proxied/wrapped/decorated object. __getattribute__() (if defined) completely override the attribute lookup process - so it gets full control over attribute access. This does not directly concern what you're doing now, but still, for a number of reasons, the canonical pythonic way to do named attribute access is with the builtin getattr() function, that will call on the appropriate lookup mechanism. As a general rule, '__magic__' methods are implementation, not API, so you shouldn't call on them directly unless you have a reaaaally goooood reason to do so. HTH Bruno From piet at cs.uu.nl Fri Jul 1 14:26:32 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 01 Jul 2005 20:26:32 +0200 Subject: Running Python interpreter in Emacs References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> <1119811726.576282.59500@g49g2000cwa.googlegroups.com> Message-ID: >>>>> "Rex Eastbourne" (RE) wrote: >RE> I went to My Computer | Properties | Advanced | Environment Variables >RE> and added c:\program files\python24 to both the PYTHONPATH and Path >RE> variables. Still no luck. I don't know whether the path I'm talking >RE> about is the same as the $PATH you referred to, or whether I'm supposed >RE> to put python.exe explicitly somewhere; could someone refer me to a >RE> place where I can read about these things? Is c:\program files\python24 the directory where python.exe is? You can try two things: 1. Use "c:\program files\python24" in the PATH environment variable, i.e. with the quotes. 2. Set emacs' variable py-python-command to the location of the python executable, e.g. (setq py-python-command "c:\\program files\\python24\\python.exe") or use customize to set that variable. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP E17999C4] Private email: piet at vanoostrum.org From spam.csubich+block at block.subich.spam.com Sun Jul 3 13:57:19 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 13:57:19 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <1120384643.995676.226320@g43g2000cwa.googlegroups.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > Listcomps et al. cannot do everything map, lambda, filter, and reduce > did. Listcomps are inferior for functional programming. But, you see, > functional is not the point. Streamlining procedural programs is the > point, and I'd say listcomps do that far better, and without all the > baroque syntax (from the procedural point of view). I've heard this said a couple times now -- how can listcomps not completely replace map and filter? I'd think that: mapped = [f(i) for i in seq] filtered = [i for i in seq if f(i)] The only map case that doesn't cleanly reduce is for multiple sequences of different length -- map will extend to the longest one (padding the others with None), while zip (izip) truncates sequences at the shortest. This suggests an extension to (i)zip, possibly (i)lzip ['longest zip'] that does None padding in the same way that map does. Reduce can be rewritten easily (if an initial value is supplied) as a for loop: _accum = initial for j in seq: _accum=f(_accum,j) result = _accum (two lines if the result variable can also be used as the accumulator -- this would be undesirable of assigning to that can trigger, say, a property function call) Lambdas, I agree, can't be replaced easily, and they're the feature I'd probably be least happy to see go, even though I haven't used them very much. From me at privacy.net Sun Jul 17 18:37:34 2005 From: me at privacy.net (Admin) Date: Sun, 17 Jul 2005 19:37:34 -0300 Subject: What is your favorite Python web framework? References: Message-ID: On Sun, 17 Jul 2005 19:15:49 -0300, Sybren Stuvel wrote: > http://www.unrealtower.org/mycheetah "Error 404 while looking up your page AND when looking for a suitable 404 page. Sorry! No such file /var/www/www.unrealtower.org/compiled/error404.py" I can't express myself on Cheetah, sorry!! -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From steve at REMOVETHIScyber.com.au Sat Jul 23 04:16:14 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 23 Jul 2005 18:16:14 +1000 Subject: Difference between " and ' References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> <2b-dnStjP7tKdH3fRVn-sA@powergate.ca> Message-ID: On Fri, 22 Jul 2005 08:38:28 -0400, Peter Hansen wrote: > Steven D'Aprano wrote: >> It may shock some people to learn that difference in the sense of >> mathematical subtraction is not the only meaning of the word, but there >> it is. One wouldn't, I hope, misunderstand "What is the difference >> between spaghetti marinara and spaghetti pescatora?" and attempt to >> subtract one from the other, since subtraction is not defined for >> foodstuffs. > > >>> sum(ord(c) for c in 'spaghetti marinara') - sum(ord(c) for c in > "spaghetti pescatora") > -119 > > Works for me... ;-) Yes, but if you had thought about the problem a little longer, you would have removed the spaghetti from both, since they just cancel each other. Although that does assume that the commutative law holds for pasta products. Personally, I prefer this answer: >>> import sets >>> sets.Set("spaghetti marinara") - sets.Set("spaghetti pescatora") Set(['m', 'n']) -- Steven. From detlev at die-offenbachs.de Sun Jul 3 06:46:24 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 03 Jul 2005 12:46:24 +0200 Subject: debugger? References: Message-ID: Qiangning Hong wrote: > Detlev Offenbach wrote: >> Qiangning Hong wrote: >> >> >>>I have read a lot of posts discussing python IDEs, but most of them >>>focus on the editor, GUI builder, project management, customizability, >>>etc.... Some talked about debugging capability, but only on an >>>available/unavailable level. >>> >>>I use vim to edit my code, wxGlade to build the GUI or hand-code it, >>>and I still prefer that. So, until now, I haven't tried many IDEs. >>> >>>However, while I use pdb or inserting "print" statement to debug my >>>apps, sometimes it is a pain. I think I need a good GUI debugger to >>>help me. The debugger should meet _most_ of the following >>>requirements: >>> >>>1. can debug wxPython applications (and other GUI lib). >>>2. an intuitive way to set/clear/enable/disable breakpoints. >>>3. can set conditional breakpoints (i.e. break when some condition >>>satisfied). 4. variable watch list, namescope watching (local, global) >>>5. evaluate expression, change variable values, etc within debugging. >>>6. change the running routine, (i.e. go directly to a statement, skip >>>some statements, etc) >>>7. clever way to express objects, not just a string returned by repr() >>>8. perform profiling >>>9. a clear interface. >>>10. cross-platform. >>>11. free, or better, open source. >>> >>>What debugger will you suggest? >>>Or what more polish feature you want to see in an ideal python >>>debugger? -- hope this thread will help IDE developers to fill their >>>todo list with some shining ideas :) >>> >> >> >> Eric3 should be compliant with your list. Try it at >> http://www.die-offenbachs.de/detlev/eric3.html >> >> Regards, >> Detlev > > Eric3 need pyqt so it is not free under windows platform. > > If you use it together with the free windows port of Qt and PyQt, than it is free. Detlev -- Detlev Offenbach detlev at die-offenbachs.de From cam.ac.uk at mh391.invalid Wed Jul 27 08:46:19 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 27 Jul 2005 13:46:19 +0100 Subject: stuff from it In-Reply-To: <1122462519.813555.211860@g44g2000cwa.googlegroups.com> References: <1122462519.813555.211860@g44g2000cwa.googlegroups.com> Message-ID: itsoooook at yahoo.com wrote: > can i have my money back Yes. -- Michael Hoffman From cowie.rob at gmail.com Fri Jul 22 07:56:34 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 22 Jul 2005 04:56:34 -0700 Subject: Web frame systems vs. pure Python In-Reply-To: <1122029632.548775.161360@z14g2000cwz.googlegroups.com> References: <1122029632.548775.161360@z14g2000cwz.googlegroups.com> Message-ID: <1122033394.885211.189860@g47g2000cwa.googlegroups.com> I don't know what your project is, but a web framework might make your system more scalable and maintainable if it gets larger. They often provide useful mechanisms for maintaining state and persistance. Template systems IMHO should be considered separately from App frameworks (although they may be integrated). If you will frequently be rendering web pages that are predominantly static but augmented with dynamically generated/retrieved data, templates are a good way to go. However, they can confuse if your system is only simple. In that case, I wouldn't go for a full blown templating engine but 'roll my own' using python dictionaries and 'string interpolation' (a daft name as it isn't really interpolation). Furthermore, app frameworks are sometimes a pain to install on a webserver, particularly if you do not have control of it. It all depends on your project size, your willingness to spend some serious time climbing the learning curve associated with a framework, and the server you wish to deploy on. From dalke at dalkescientific.com Fri Jul 22 13:23:03 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 22 Jul 2005 17:23:03 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > You're right, conceptually a path > HAS_A string description, not IS_A string, so from a pure OO point of > view, it should not inherit string. How did you decide it's "has-a" vs. "is-a"? All C calls use a "char *" for filenames and paths, meaning the C model file for the filesystem says paths are strings. Paths as strings fit the Liskov substitution principle in that any path object can be used any time a string is used (eg, "loading from " + filename) Good information hiding suggests that a better API is one that requires less knowledge. I haven't seen an example of how deriving from (unicode) string makes things more complicated than not doing so. Andrew dalke at dalkescientific.com From tjreedy at udel.edu Sun Jul 10 16:26:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jul 2005 16:26:24 -0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: "Ralf W. Grosse-Kunstleve" wrote in message news:20050710133959.83611.qmail at web31512.mail.mud.yahoo.com... I have a suggestion I don't remember seeing for flagging which vars to autoinit without new syntax: use '_' instead of '.'. I have never seen local vars with a leading '_'. So, in combination with whatever other mechanism (metaclass, __init__ decorator?) def __init__(self, _x, y, _z) : would automatically do self.x = _x, self.z = _z, but not self.y = y. Terry J. Reedy From twic at urchin.earth.li Wed Jul 6 09:38:31 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 6 Jul 2005 14:38:31 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: On Wed, 6 Jul 2005, Terry Hancock wrote: > On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote: > >> I understand that the backslash is popular in some ivory-tower >> functional languages. Currently, a backslash can be used for explicit >> line joining, and is illegal elsewhere on a line outside a string >> literal, so i think it's available for this. It would be utterly >> unpythonic to use puntuation instead of a keyword, and it would make no >> sense to novices, but it would scare the crap out of C programmers, >> which has to be worth something. > > With list comprehensions and generators becoming so integral, I'm > not sure about "unpythonic". I'm going to resist the temptation to argue that list comps are themselves unpythonic :). Hang on, where's the punctuation in either of those? They *are* done with keywords! A generator is just a function with "yield" instead of "return", list comprehensions are just list literals where the explicit sequence of items is replaced with code producing them, using the keywords "for", "in" and "if", and a generator expression is a list comp *without any punctuation!* > And a syntax just occured to me -- what about this: > > [y*x for x,y] > > ? Terrible. Square brackets mean a list, and a lambda is not anything like a list. I see where you're coming from, though; a lambda is a lot like the first half of a list comp that's broken off and is roaming free. I can't think of a good syntax for it, though. tom -- find porn apricot From paolo_veronelli at tiscali.it Sun Jul 31 15:25:02 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sun, 31 Jul 2005 21:25:02 +0200 Subject: namespaces In-Reply-To: References: <42EC9690.2040301@tiscali.it> Message-ID: <42ED258E.8030302@tiscali.it> >>Steven D'Aprano wrote: > Why not? Is it too slow? Too many lines of code? Uses too much memory? > What exactly is the problem? I would like to see your profile tests that > show why this is not acceptable. > Are you sure that this solution is less efficient than creating a class? A > class has all that extra machinery and methods and attributes that needs > to be created, only to be thrown away. How do you know that my solution is > less efficient than your solution? The example was an example , and my concern is not about that example to be fast or small (readable probably), but for python programming tools as being complete, or academic interest or just to talk with people on a hot sunday (in this zone of the north emisphere) on interesting (for me at least) things. The calculations for all,badcars and table are not complex in this case, so we can redo them often because we are wasters, but in other cases they can be different. Me: >>Even worse I get with methods and function namespaces. > > What is "even worse" about them? > For my thinking, worse is to understand how they derive their pattern from generic namespaces. Methods seems not to have a writeble one,while functions as George and Rob remembered have one which is not read only.Why? (Also my aim is to learn from postings not to show others' implementations are better or worse in the sense I prefer, times are gone for me for that. ) Paolino ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From tim.peters at gmail.com Thu Jul 14 15:14:26 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 14 Jul 2005 15:14:26 -0400 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? In-Reply-To: <11ddckucctde603@corp.supernews.com> References: <11ddckucctde603@corp.supernews.com> Message-ID: <1f7befae050714121434029e99@mail.gmail.com> [Grant Edwards] > I've read over and over that Python leaves floating point > issues up to the underlying platform. > > This seems to be largely true, but not always. My underlying > platform (IA32 Linux) correctly handles 1.0/0.0 and 0.0/0.0 > according to the IEEE 754 standard, but Python goes out of its > way to do the wrong thing. Python does go out of its way to raise ZeroDivisionError when dividing by 0. > 1/0 is defined by the standard as +Inf and 0/0 is NaN. > > That's what my platform does for programs written in C. IOW, that's what your platform C does (the behavior of these cases is left undefined by the C89 standard, so it's not the case that you can write a _portable_ C89 program relying on these outcomes). What does your platform C return for the integer expression 42/0? Is any other outcome "wrong"? > Python apparently checks for division by zero and throws and exception > rather than returning the correct value calculated by the > underlying platform. > > Is there any way to get Python to return the correct results > for those operations rather than raising an exception? No, except when using the decimal module. The latter provides all the facilities in IBM's proposed standard for decimal floating-point, which intends to be a superset of IEEE 854: http://www2.hursley.ibm.com/decimal/ It's relatively easy to do this in the decimal module because it emulates, in software, all the gimmicks that most modern FPUs provide in hardware. Note that support for 754 was rare on Python platforms at the time Python was designed, and nobody mentioned 754 support as even a vague desire in those days. In the absence of user interest, and in the absence of HW support for NaNs or infinities on most Python platforms, the decision to raise an exception was quite sensible at the time. Python could not have implemented 754 semantics without doing emulating fp arithmetic in SW on most platforms (as the decimal module does today), and for much the same reasons you can't give a non-silly answer to my earlier "what does your platform C return for the integer expression 42/0?" question today . > There's no way to "resume" from the exception and return a > value from an exception handler, right? Correct. Note that there's a huge, current, informed discussion of these issues already in the math.nroot thread. From jdennett at acm.org Fri Jul 15 22:18:54 2005 From: jdennett at acm.org (James Dennett) Date: Fri, 15 Jul 2005 19:18:54 -0700 Subject: How can I import a py script by its absolute path name? In-Reply-To: <42d7ee79$0$809$3a628fcd@textreader.nntp.hccnet.nl> References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> <87ackpeeag.fsf@titan.staselog.com> <42d7ee79$0$809$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: J.Bijsterbosch wrote: > Hello Edward, > > "Edvard Majakari" schreef in bericht > news:87ackpeeag.fsf at titan.staselog.com... > >>Thorsten Kampe writes: >> >> >>>"sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')" >> >>Well, of course. As I said, it was untested :) I just copied the path > > string, > >>and didn't remember Windows uses path names which need special >>treatment. > > > Hmm, what you call special treatment comes from pythons deep underlying C > and C++ language heietidge I presume. A backslash in a C or C++ string means > the following character is a so called escape character, like \n represents > a newline and \r a return to the beginning of a line. > If you really want a backslash you need to type it twice like so \\. Has > nothing to do with Windows...;-)) Actually, it does have a connection to Windows. On Unix, backslashes are rarely used for anything *except* escape characters. Pathnames tend not to include backslashes, so in most cases it's not necessary to escape backslashes in path names. On Windows, however, backslash is a valid path separator, and must be escaped. So, on Unix, for a path separator, you type "/". On Windows you can either do the same, or type "\\". (Or (ab)use raw strings.) -- James From steve at REMOVETHIScyber.com.au Sat Jul 2 22:16:48 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 12:16:48 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 01 Jul 2005 19:15:46 -0700, Erik Max Francis wrote: > Sean McIlroy wrote: > >> if that's the case then list >> comprehensions and/or "first class functions" are likely to be the next >> target. > > Slippery slope arguments are logical fallacies, you know. Not if you are actually standing on a slippery slope. But seriously, no, they aren't. The slippery slope argument is _not_ "X is happening now, so Y will happen no matter what we do". That would be a fallacy. The argument is actually "X is happening now. If X continues to happen into the future, Y is the logical consequence of that process. If we wish to avoid Y, we must stop X". And that is not a fallacy in general (although of course it could be, if there is no causal relationship between X and Y). In this particular case, I suspect Sean is wrong. Guido seems to like list comprehensions. Unless I'm mistaken (not for the first time) I think he actually introduced them to the language. They won't be going anywhere anytime soon. -- Steven From peter at engcorp.com Sat Jul 9 22:22:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Jul 2005 22:22:52 -0400 Subject: already written optparse callback for range and list arguments? In-Reply-To: References: Message-ID: <6NidnaumWZ8cG03fRVn-sQ@powergate.ca> Alex Gittens wrote: > I would like my program to accept a list of range values on the > command line, like > -a 1 > -a 1-10 > -a 4,5,2 > > In the interest of avoiding reinventing the wheel, is there already > available code for a callback that would enable optparse to parse > these as arguments? Doesn't that depend on what you plan to do with them? Do you want them as a special Range object, or a series of integers, or a list of tuples, or what? -Peter From cam.ac.uk at mh391.invalid Sun Jul 3 06:03:46 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 03 Jul 2005 11:03:46 +0100 Subject: No sys.ps2 in IDLE (was Re: question) In-Reply-To: References: Message-ID: yipusi wrote: > IDLE 1.0.3 > >>>>import sys >>>>sys.ps2 > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.ps2 > AttributeError: 'module' object has no attribute 'ps2' > > > where is the problem? The problem is that you are using IDLE (and an old version at that), which doesn't use sys.ps2. -- Michael Hoffman From kwharrigan at yahoo.com Fri Jul 22 09:48:39 2005 From: kwharrigan at yahoo.com (kwharrigan at yahoo.com) Date: 22 Jul 2005 06:48:39 -0700 Subject: time.time() under load between two machines Message-ID: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> I am working on some code using python and a distributed system. Some particular message is sent on one machine (with a timestamp logged) and after the message is received, a timestamp is made. I am having problems with negative latencies happening under intense CPU load. There is ntp sync happening so the machines should be very well in sync. Example: machine1 ---- sendTime = time.time() machine2 --- recvTime = time.time() Latency = recvTime-sendTime is NEGATIVE Is it possible that the CPU load is affecting the accuracy of the time.time() call, or that the relative difference in CPU load between the machines is causing this delta inaccuracy? Any help would be appreciated. Kyle Harrigan From cappy2112 at gmail.com Tue Jul 26 22:01:10 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 26 Jul 2005 19:01:10 -0700 Subject: GUI - Windows: Where to get started In-Reply-To: References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: <1122428995.530428.187960@z14g2000cwz.googlegroups.com> if you want something one step simpler than wX & TK take a look at http://www.averdevelopment.com/python/EasyDialogs.html or http://www.ferg.org/easygui/index.html You loose a lot of flexibility, but get ultra simple (and plain-looking) widgets, without all of the complexity of of a gui Framework, expecially wx. This is a quick and dirty way to add some really simple dialogues to a Python program. But you don't get exposed to the concepts you need to know to work with a full-powered framework. Try PythonCard, for a framework that abstracts wx even further, but still providing most of the functionality (if not all of it) of wx. Alo take a look at QT/pyQT (another framework and it's wrapper) From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 11 17:25:21 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 11 Jul 2005 23:25:21 +0200 Subject: Environment Variable In-Reply-To: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> References: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> Message-ID: <3jg6e1Fpm157U1@individual.net> tuxlover at gmail.com wrote: > Is it possible to set an environment variable from inside the python > script which will be retained after the script exits. > > If I use the following code: > > import os > os.putvar("name", "tuxlover") > > the enivironment variable name is visible to only the sub-process > created by os.system and os.popen. But as soon as the python script > vanishes, the environment variable "name" is gone. > > What I am wondering is that is it possible to set a environment > variable from inside a python script, and then access it (say, echo > $name from the shell) after the python script exits. No, I regret it is currently not. But I see a significant chance that someone gets on the time machine and implants this into Thompson's head some 30 years earlier as soon as you post that a third time. Reinhold From pmaupin at gmail.com Sat Jul 2 00:01:20 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 1 Jul 2005 21:01:20 -0700 Subject: $6 into $1000ands this actually works! References: <1120268191.451376.48310@g47g2000cwa.googlegroups.com> Message-ID: <1120276880.249968.150750@g49g2000cwa.googlegroups.com> Thomas wrote: > TURN $6 INTO $15,000 IN ONLY 30 DAYS...HERES HOW! > $$$$$ REMEMBER, IT IS 100% LEGAL! DON'T PASS THIS UP! and I thought this was about some new currency/decimal module implementation which remembers units and does the conversion correctly... From steven.bethard at gmail.com Sat Jul 9 21:26:05 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 09 Jul 2005 19:26:05 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120887889.287054.194040@o13g2000cwo.googlegroups.com> References: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> <1120887889.287054.194040@o13g2000cwo.googlegroups.com> Message-ID: <_Y6dnRE7P82s5E3fRVn-jg@comcast.com> Devan L wrote: >>>>import timeit >>>>t1 = timeit.Timer('list(i for i in xrange(10))') >>>>t1.timeit() > > 27.267753024476576 > >>>>t2 = timeit.Timer('[i for i in xrange(10)]') >>>>t2.timeit() > > 15.050426800054197 > >>>>t3 = timeit.Timer('list(i for i in xrange(100))') >>>>t3.timeit() > > 117.61078097914682 > >>>>t4 = timeit.Timer('[i for i in xrange(100)]') >>>>t4.timeit() > > 83.502424470149151 > > Hrm, okay, so generators are generally faster for iteration, but not > for making lists(for small sequences), so list comprehensions stay. Ahh, thanks. Although, it seems like a list isn't very useful if you never iterate over it. ;) Also worth noting that in Python 3.0 it is quite likely that list comprehensions and generator expressions will have the same underlying implementation. So while your tests above satisfy my curiosity (thanks!) they're not really an argument for retaining list comprehensions in Python 3.0. And list comprehensions won't go away before then because removing them will break loads of existing code. STeVe From grante at visi.com Fri Jul 1 20:38:21 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 02 Jul 2005 00:38:21 -0000 Subject: When someone from Britain speaks, Americans hear a "Britishaccent"... References: <11c8tgjju7ljvd4@corp.supernews.com> Message-ID: <11cboft55n5hg85@corp.supernews.com> On 2005-07-02, Andrew Durdin wrote: > On 7/1/05, Grant Edwards wrote: >> On 2005-06-30, Delaney, Timothy (Tim) wrote: >> > Tom Anderson wrote: >> > >> >> How about carrier? >> > >> > Ends in an "a" (Australian ;) >> >> Right, but due to some wierd property requiring conservation of >> consonants, when speaking Strine you've got to take the r's >> removed from words like "carrier" and "order", and add them to >> the ends of other words like Amanda. > > No, you've got it wrong -- we take them and insert them where they > were never intended to be: > > "I saw Amanda" sounds like "I sawramanda" Unless Amanda wasn't alone. Then it's I sawr amandar and joe. That's known as a "linking r" or something like that and is used to between a word that ends in a vowel (or a w?) and a subsequent word that starts with a vowel. If the preceeding word was supposed to end in an "r", it may be an intrusive r. Wikipedia has a pretty good article about the whole "r" thing: http://en.wikipedia.org/wiki/Rhotic_accent -- Grant Edwards grante Yow! Yow! Maybe I should at have asked for my Neutron visi.com Bomb in PAISLEY-- From nephish at xit.net Sun Jul 31 14:43:02 2005 From: nephish at xit.net (nephish at xit.net) Date: 31 Jul 2005 11:43:02 -0700 Subject: getting an empty tuple In-Reply-To: References: <1122824426.310199.136660@o13g2000cwo.googlegroups.com> Message-ID: <1122835382.838766.84350@o13g2000cwo.googlegroups.com> ok, this is what works: if x == (): sorry about the bad info. and what i ment to put was x[0] not x(0) thanks for the tips its all good now shawn Steven D'Aprano wrote: > On Sun, 31 Jul 2005 08:40:26 -0700, nephish wrote: > > > Hey there, > > i have a simple database query that returns as a tuple the number of > > rows that the query selected. > > kinda like this > > > >>>> cursor.execute('select value from table where autoinc > 234') > >>>> x = cursor.fetchall() > >>>> print x > > > >>>> 21L > > 21L is not a tuple, it is a long integer. > > > ok, means 21 rows met the criteria of the query. but if there are none > > that match, > > like i do a > > > >>>> print x > >>>> 0L > > > > how do i encorporate that into an equation ? > > i have tried all kinds of stuff > > And did they work? If they didn't work, tell us the exact error message > you got. > > > > if x == 0L > > If x is a long integer, then that will work. Of just "if x == 0:" will > work too. > > > > if x(0) == None > > No. That means x is a function, and you are giving it an argument of 0, > and it returns None. > > > if x == None > > You said that your query returns a tuple, but then gave an example where > it returns a long int. None is not a tuple, nor a long int, so testing > either of those things against None will never be true. > > Did you try any of these things in the interactive interpreter? Python is > a great language for experimenting, because you can try this yourself: > > # run your setup code ... > # and then do some experimenting > cursor.execute('select value from table where autoinc > 99999999') > # or some value that will never happen > x = cursor.fetchall() > print x > > What do you get? > > > > anyway, what shoud i do to test if the result is empty? > > Long ints are never empty, but they can be zero: > > if x == 0: > print "no rows were found" > elif x == 1: > print "1 row was found" > else: > print "%d rows were found" % x > > Tuples can be empty: > > if len(x) == 0: > print "no rows were found" > > or if you prefer: > > if x == (): > print "no rows were found" > > > But the cleanest, most Pythonic way is just to do a truth-test: > > if x: > print "something was found" > else: > print "x is empty, false, blank, nothing..." > > > -- > Steven. From jason at tishler.net Mon Jul 18 08:16:33 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 18 Jul 2005 08:16:33 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050208175514.GA3788@tishler.net> References: <41FF5A67.3090606@llnl.gov> <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> Message-ID: <20050718121633.GC3292@tishler.net> Dean, On Tue, Feb 08, 2005 at 12:55:15PM -0500, Jason Tishler wrote: > On Tue, Feb 08, 2005 at 08:01:11AM -0800, Dean N. Williams wrote: > > $ rebaseall > > /usr/bin/rebaseall: line 70: [: too many arguments > > /usr/bin/rebaseall: line 75: [: too many arguments > > /usr/bin/rebaseall: line 94: $TmpFile: ambiguous redirect > > cannot read /cygdrive/c/Documents > > > > On my laptop installation everything works just fine. What is the > > difference? > > The TMP and/or TEMP environment variables have at least two spaces in > them. > > The easiest workaround is to execute rebaseall like the following: > > $ TMP=/tmp rebaseall > > Long term I will change rebaseall to deal better with spaces in shell > variables. The above rebaseall problem has been fixed: http://cygwin.com/ml/cygwin-announce/2005-07/msg00031.html Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From jgrahn-nntq at algonet.se Sun Jul 10 08:35:08 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 10 Jul 2005 12:35:08 GMT Subject: passing arguments to a function - do I need type ? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: (You posted your question as a followup to oen of Xah Lee's musings. That is not the best of ideas, since people with threaded newsreaders tend not to see it. Just post (creating a new thread) next time.) On Sun, 10 Jul 2005 11:19:31 +0100 (BST), Philipp H. Mohr wrote: > Hello, > I got a newbie question, I have written the following distance function: > > def distance(self,element1, element2): > dist = 0 > > for n in range(len(element1)): > dist = dist + pow((element1[n] - element2[n]),2) > print 'dist' + dist > return sqrt(dist) > > and in order to be able to use len() and index element1[] the function > needs to know that the arguments element1 and element2 are both listst or > doesn't it ? Yeah, or something else supporting len(x) and x[n]. > I get the following error msg: ... > TypeError: len() of unsized object ... > AND if I take len out I get: ... > TypeError: unsubscriptable object Well, that depends on the types of the arguments you're passing to the method, doesn't it? A call like distance([1,1], [0,0]) works fine for me. And here is a slightly simpler implementation which avoids len (thus accepting a wider range of argument types) and pow: def distance(element1, element2): dist=0 for a, b in zip(element1, element2): n = float(a-b) dist += n*n return math.sqrt(dist) (Dunno if that's the correct formula for n-dimensional distance. I have forgotten way too much math in the past ten years.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From jack at performancedrivers.com Wed Jul 13 12:37:50 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 13 Jul 2005 12:37:50 -0400 Subject: all possible combinations In-Reply-To: References: <1121267364.28617.4.camel@athop1.ath.vt.edu> <1121269202.29571.1.camel@athop1.ath.vt.edu> Message-ID: <20050713163750.GA3089@performancedrivers.com> On Wed, Jul 13, 2005 at 05:07:33PM +0100, Duncan Smith wrote: > rbt wrote: > > On Wed, 2005-07-13 at 11:09 -0400, rbt wrote: > > > >>On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: > >> > >>>Say I have a list that has 3 letters in it: > >>> > >>>['a', 'b', 'c'] > >>> > >>>I want to print all the possible 4 digit combinations of those 3 > >>>letters: > >>> > >>>4^3 = 64 > >>> > >>>aaaa > >>>abaa > >>>aaba > >>>aaab > >>>acaa > >>>aaca > >>>aaac > >>>... > >>> > >>>What is the most efficient way to do this? > >> > >>Expanding this to 4^4 (256) to test the random.sample function produces > >>interesting results. It never finds more than 24 combinations out of the > >>possible 256. This leads to the question... how 'random' is sample ;) > >> > >>Try it for yourselves: > >> > >>test = list('1234') > >> > >>combinations = [] > >>while 1: > >> combo = random.sample(test, 4) > >> possibility = ''.join(combo) > >> if possibility not in combinations: > >> print possibility > >> combinations.append(possibility) > >> continue > >> else: > >> continue > >> > > > > > > Someone pointed out off-list that this is doing permutation, not > > combination. Is there a way to make random.sample to do combinations? > > > Probably not in any sensible way. But what you list in your original > post are not distinct combinations. e.g. abaa and aaba are both 3 a's > and 1 b. Maybe you mean that order does matter (and you're actually > looking for all distinct permutations of all combinations)? > This is called a cartesian product, and the easiest way is to do import probstat # probstat.sourceforge.net letters = list('abcd') for (guys) in probstat.Cartesian([letters] * 4): print ''.join(guys) It's a C module I wrote to do this stuff a few years ago, still compiles and runs just fine (at least on linux). -jackdied From cyril.bazin at gmail.com Fri Jul 8 14:31:06 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Fri, 8 Jul 2005 20:31:06 +0200 Subject: FORTRAN like formatting In-Reply-To: <0DF798CBF125BF4AA1227F26431C29BD01A32ECA@pnlmse27.pnl.gov> References: <0DF798CBF125BF4AA1227F26431C29BD01A32ECA@pnlmse27.pnl.gov> Message-ID: Hello, I don't anderstand very well Fortran syntax, but want you say something like that: def toTable(n1, n2, n3): return "%20s%20s%20s"%tuple(["%.12f"%x for x in [n1, n2, n3]]) Example: >>> import math >>> toTable(math.pi, 10, 8.2323) ' 3.141592653590 10.000000000000 8.232300000000' If it is not that, please could you give an example of input and output of your code? Cyril On 7/8/05, Einstein, Daniel R wrote: > > > Hi, > > Sorry for this, but I need to write ASCII from my Python to be read by > FORTRAN and the formatting is very important. Is there any way of doing > anything like: > > write(*,'(3(" ",1pe20.12))') (variable) > > In other words, I want three columns 20 spaces long, with 12 digits after > the decimal and so on and so forth. > > What I am really looking for is some general indication of how to do such > formatting in Python. > > Any help? > > Dan > > > Daniel R Einstein, PhD > Biological Monitoring and Modeling > Pacific Northwest National Laboratory > P.O. Box 999; MSIN P7-59 > Richland, WA 99352 > Tel: 509/ 376-2924 > Fax: 509/376-9064 > daniel.einstein at pnl.gov > > -- > http://mail.python.org/mailman/listinfo/python-list > > From simon.dahlbacka at gmail.com Wed Jul 20 15:12:51 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 20 Jul 2005 12:12:51 -0700 Subject: Printing a variable's name not its value In-Reply-To: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> References: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> Message-ID: <1121886771.309517.156380@g47g2000cwa.googlegroups.com> as you have been told, there is no way to get a variable's name, take a look at http://effbot.org/zone/python-objects.htm to find out why this is so. From http Sun Jul 31 03:32:05 2005 From: http (Paul Rubin) Date: 31 Jul 2005 00:32:05 -0700 Subject: Dabo in 30 seconds? References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> Message-ID: <7xy87nctxm.fsf@ruckus.brouhaha.com> Ed Leafe writes: > > I am going to go ahead and throw out Dabo with all of the others that claim > > quick development of an application. You try them and then you get bugs, > > bugs, bugs. Or they don't compile without 16000 dependencies. Forget it. My > > advice is to choose something, one thing, that is REAL standard, and in the > > standard library (e.g. Tkinter). > > Sorry you feel that way. You'll miss out on really great Python > products that aren't in the standard Library, such as Twisted, > Zope/Plone, Dabo, and many others. ... Python is a base. You build > from there. Those issues about the 1600 dependencies don't apply nearly as much to pure Python modules (e.g. Twisted) as they do to extension modules that require the presence of further stuff on the system. E.g., on Linux, to use wxPython, you need wxWidgets, which needs GTK 1.5, which has been obsolete for years, and there are all sorts of build conflicts when you try to compile this stuff out of the box. I don't know where Dabo fits in. It does sound nice in some regards. Pico Lisp uses an interesting approach to portable GUI's: it includes a socket-based GUI API and a special Java applet that runs in a browser and implements the API. All the issues of dealing with OS-specific window systems go away, as long as you can run a Java-enabled browser and point it at the Pico Lisp application. See: http://www.software-lab.de/down.html From bokr at oz.net Fri Jul 15 19:24:52 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 15 Jul 2005 23:24:52 GMT Subject: Generating a list of None References: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> Message-ID: <42d82da3.279202121@news.oz.net> On 14 Jul 2005 19:25:41 -0700, "Nicolas Couture" wrote: >Hi, > >Is it possible to generate a list of `None' ? > >opts.__dict__.values() below could be represented by [None, None, None] > >--- >def get_options(opts): > """Return True or False if an option is set or not""" > vals = opts.__dict__.values() > > for val in vals: > if val is not None: > return True > > return False >--- > >This is how I'd like to see it: > >--- >def get_options(opts): > """Return True or False if an option is set or not""" > vals = opts.__dict__.values() > > for if vals is [None * len(vals)]: > return False > > return True >--- how about (untested) def get_options(opts): """Return True or False if an option is set or not""" return [1 for val in vars(opts).values() if val is not None] and True or False Regards, Bengt Richter From peter at engcorp.com Sun Jul 31 12:11:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Jul 2005 12:11:23 -0400 Subject: Thaughts from an (almost) Lurker. In-Reply-To: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> References: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Message-ID: Paddy wrote: > Sometimes when reading c.l.p. I mentally stand off from what I have > been reading and get an odd feeling that 'WE ARE BEING TESTED'. That > someone else is purposefully posting a near repetitive post, or obvious > flame bait etc - not for the usual reasons, but to track the dynamics > af the replies. Rather like dropping a stone in the river and watching > pythonistas return c.l.p. to its normal, helpful, and polite norm. > Fascinating. > I only hope that if thats the case, then they should post their > findings here. Hmm... was that a test, too? ;-) From nethawg1 at verizon.net Mon Jul 18 13:01:18 2005 From: nethawg1 at verizon.net (windozbloz) Date: Mon, 18 Jul 2005 17:01:18 GMT Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: Jeff Epler wrote: > I honestly don't know why anyone would spend money for a development > environment, no matter how fancy. I don't knowdefinitelye would develop > software in a language that doesn't have at least one open > implementation. > > It's a great way to get screwed when Borland goes under or decides > they only want to sell a new, incompatible product. What do you do with > your existing product when that happens? Re-train on a new platform, > and re-write from scratch? > > Just say no to proprietary software. > > Jeff Thanks Jeff, Point taken! I had given that considerable thought. Your words 'retrain on a new platform' struck a loud cord with me, thank you, I will definitely reconsider. I don't ever want to find myself locked behind 'the GATES of hell' again! Doug -- LINUX protects me from the GATES of hell !!! From kay.schluehr at gmx.net Mon Jul 11 07:53:33 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Jul 2005 04:53:33 -0700 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> <1121059708.002859.67570@g44g2000cwa.googlegroups.com> <3jei85FpehftU1@individual.net> Message-ID: <1121082813.911573.91650@o13g2000cwo.googlegroups.com> Reinhold Birkenfeld schrieb: > Kay Schluehr wrote: > > Dan Sommers schrieb: > > > >> How about this: > >> > >> def __init__(self, self.x, y, self.z): > >> # self.x, self.z from first and third explicit parameters > >> do_something_with_y() > > > > Can you tell me in which way it is anyhow better than the original > > proposal > > > > def __init__(self, .x, y, .z): > > # self.x, self.z from first and third explicit parameters > > do_something_with_y() > > > > besides that it is more verbose? > > It is more explicit. Explicit is better than implicit. The punctuation syntax makes it explicit too. But maybe a point is a more tiny and less explicit symbol than an @ that makes a decorator explicit ;) > But as with many proposals, this raises consequential questions, for > example, how "self.x" parameters are handled in other methods, or even > functions, as __init__ is not special-cased by the parser. > > Reinhold Yes. My argument against the syntax is more that of a language lawyer: how a class uses the argument parameters of a constructor is an implementation detail of a class and should not be published in the constructor interface. One may assign special attributes to the classes ( e.g. tagging it with a metaclass ) or a qualifier. I had recently a look on Scala an object-functional language running on top of the JVM. Scala introduces the concept of a "case class" to represent object trees. All arguments passed into a case class constructor become automagically object attributes. This is for convenience and let the tree grow if the passed arguments are case class instances again. Here it is the class type that determines how it's construction is handled. I think this is a reasonable approach. Kay From noreply at gcgroup.net Wed Jul 6 12:32:42 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 06 Jul 2005 16:32:42 GMT Subject: Tkinter grid layout In-Reply-To: References: Message-ID: Excuse me for intruding, but I followed examples and ended up with a similar architecture: from Tkinter import * class MyMain(Frame): def __init__(self, master): self.root = master self.master=master root = Tk() app = MyMain(root) app.master.title("Object Editor") root.mainloop() Erick, are you saying it should be modified to something like : from Tkinter import * class MyMain(Tk): ... ... app = MyMain() app.title("My App") app.mainloop() Thanks, Bill Eric Brunel wrote: > On Wed, 06 Jul 2005 11:44:55 +0100, Richard Lewis > wrote: > >> Hi there, >> >> I've got a tree control in Tkinter (using the ESRF Tree module) but I >> can't get it to layout how I want it. >> >> I'd like to have it so that it streches north/south (anchored to the top >> and bottom), is of a fixed width and is anchored to the left hand side. >> Here's my code (its derived from one of the examples from the ESRF web >> site): >> >> class MainWindow(Frame): > > [snip code] > > First of all, it is not a good idea to make your so-called window > inherit from Frame: a Frame is not a window in tk, but a generic > container. Creating a Frame without a container window will > automatically initialize the tk toolkit, creating a default window which > will become the default parent for widgets where you don't specify one. > According to the well-known "explicit is better than implicit" > principle, if a MainWindow instance are actually the main window for > your application, you'd really better inherit from the Tkinter class for > the main window, which is Tk. Doing it this way has a lot of advantages > over what you do; for example, if you later have to create a menu bar > for your application, you will be able to do it in the MainWindow class. > If you inherit from Frame, you won't get any access to the actual > window, so you won't be able to create a menu in it. > > This may seems to be unrelated to your problem, but it's not: by > creating a Frame, you introduce one more unneeded container. So, in some > code you don't show here, you have to insert the MainWindow instance > into its parent window via a call to its pack or grid method. Since the > code you show seems to be correct, I guess the problem is in this call > to pack or grid, which probably does not tell the Frame how to behave > when its parent window is resized, causing it to get the default > behaviour, which is "do nothing at all". > > To be sure this actually is the problem, try to replace the line: > Frame.__init__(self, master) > in MainWindow.__init__ by: > Frame.__init__(self, master, bg='blue', bd=2) > This way, a blue border will appear around the frame, allowing you to > see how it grows. > Then run your application, and resize the window. You should see that > the frame does not grow when the window grows, explaining why your tree > deos not grow (in fact, it would grow if its container did; but its > container doesn't...) > > So you should either make your MainWindow class inherit from Tk, which > eliminates the unneeded container and the problems it may cause, or make > sure the pack or grid on your MainWindow instance actually tells the > container to grow with its container. With pack, it's quite easy: just > do myWindow.pack(fill=BOTH, expand=1). With grid, it's a bit more > complicated, since you will have to configure the grid on the container. > > But basically, my advice would be: > - Never make your windows inherit from Frame; make them inherit from Tk > for the main window or from Toplevel for all other ones > - When you have resize problems, always check the whole widget hierarchy > from the actual window down to the widget showing the problem. The cause > is very often not on the widget itself, but on one of its containers. > > HTH From edvard+news at majakari.net Wed Jul 6 11:18:50 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 06 Jul 2005 18:18:50 +0300 Subject: Favorite non-python language trick? References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> Message-ID: <87hdf8ync5.fsf@titan.staselog.com> (sorry, my NUA had lost the original article) > >> I'm curious -- what is everyone's favorite trick from a non-python >> language? And -- why isn't it in Python? Ability to tag some methods 'deprecated' as in Java (from 1.5 onwards?). However, Python interpreter doesn't have to do it: pydoc and similar tools could detect, say, '@deprecated' in method comment string and warn user about it. Currently I just document deprecated methods, and if I feel like it, I also add def some_method_which_is_badly_named_or_just_plain_wrong(..) """docstring This method is now deprecated. Use frob() instead. """ sys.stderr.write('warning: method some_method_which_is_badly_named_or_just_plain_wrong is now deprecated') -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! You shouldn't verb verbs. From gsakkis at rutgers.edu Fri Jul 1 11:25:47 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 08:25:47 -0700 Subject: No subject References: Message-ID: <1120231547.928636.59270@g43g2000cwa.googlegroups.com> >> - namespaces > > >Aren't namespaces basically the same as packages/modules in python? > > Not in the way C++ uses them. In Python if would be something like this: > --------------------------- > import os > using namespace casa > class os: > def open(self, file): > pass > a = os.open('something') > b = std::os.open('something') > using namespace std > c = casa::os.open('something') > d = os.open('something') > --------------------------- > This is a realy stupid example. It's essentially an extra hierarchy > layer to avoid naming clashes. I don't know of a way to do this in > Python, how would you do this? I'm not sure how your pseudo python/c++ example resolves name clashes, and honestly I would rather not deal with such mind boggling code. You can certainly avoid name clashes in python less ambiguously; explicit is better than implicit: from std import os as std_os from casa import os as casa_os class os: def open(self, file): pass a = os.open('something') b = std_os.open('something') c = casa_os.open('something') By the way, if os is a class, open() should probably be called in an instance of os, i.e. os().open('something'), but that's not the point of your example. > >> - data hiding > > >Surely you can hide data in python? > > Again, how? Is there a way to force that an external user of my lib can > not use my internal data/methods/classes, unless he uses odd compiler > hacks? Strictly speaking, no you can't, at least in pure python. The convention is to prefix internal names with single underscores. There is limited language support for private class attributes through name mangling (http://www.python.org/doc/current/tut/node11.html), but that's in general frowned upon, unless you have very good reasons to do so. I never understood how mainstream OO languages expect the designer of a class to know in advance that an attribute should be hidden or unnecessary to its subclasses by being declared "private" instead of "protected". The distinction between public and non-public (private + protected) is more understandable, but again python's philosophy is "we're all consenting adults here". _single_underscored names just flash a "use at your own risk" signal, instead of tying your hands in case the original class designer made a wrong assumption. George From jbellis at gmail.com Thu Jul 21 23:34:06 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 21 Jul 2005 20:34:06 -0700 Subject: ANN: Spyce 2.0.3 Message-ID: Spyce 2.0.3 released Spyce is a python web application server, combining features of popular frameworks such as ASP.NET and JSP with Pythonic elegance. Spyce may be deployed as a standalone server, proxied behind Apache, under mod_python, FastCGI, or CGI. Spyce 2.0 includes features unique to Python web frameworks such as Active Handlers - reusable components without the leaky abstractions seen in ASP.NET et al. - http://spyce.sourceforge.net/docs/doc-lang_handlers.html Active Tag compiler - http://spyce.sourceforge.net/docs/doc-tag_new2.html 2.0.3 is a bugfix and documentation-improvement release. The installation section of the manual has received particular attention. There is also the new section on starting your first project (http://spyce.sourceforge.net/docs/doc-conf_next.html), which answers the FAQ, "how do I organize my Spyce files." Demos and downloads are available at http://spyce.sourceforge.net/. Changelog is at http://svn-hosting.com/svn/spyce/trunk/spyce/CHANGES. Jonathan Ellis http://spyced.blogspot.com From martin.witte at gmail.com Mon Jul 25 15:57:55 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 25 Jul 2005 12:57:55 -0700 Subject: how to write a line in a text file In-Reply-To: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> Message-ID: <1122321475.234274.180140@g47g2000cwa.googlegroups.com> A recipe is * open your file for reading: f = open('filename.txt', 'r') * read all lines in a list: content = f.readlines() * close the file: f.close() * set the third element in the list to something else: content[2] = 'Blahdiblah' * re-open the file for writing: f = open('filename.txt', 'w') * write the list to the file: f.writelines(content) * close the file: f.close() From python at rcn.com Thu Jul 28 09:55:59 2005 From: python at rcn.com (Raymond Hettinger) Date: 28 Jul 2005 06:55:59 -0700 Subject: can list comprehensions replace map? References: <1122508803.920261.303730@g49g2000cwa.googlegroups.com> Message-ID: <1122558959.275032.232920@g44g2000cwa.googlegroups.com> [Paolino] > Well, for my little experiences use cases in which the lists have different > lengths are rare, but in those cases I don't see the reason of not being > able > to zip to the longest one.What is really strange is that I have to use > map(None,....) for that,instead of another zip-like function which ,at > least > would be intutitive for the average user.Also map(None,...) looks like a > super-hack > and it's not elegant or readable or logic (IMO) > > I think zip comes to substitute the tuple.__new__ untolerant > implementation.A dumb like me wuold expect map(tuple,[1,2,3],[2,3,4]) to > work, so pretending map(None,....) would do it is like saying that None > and tuple are near concepts, which is obviously an absurdity. Yes, map(None, ...) lacks grace and it would be nice if it had never been done. The more recently implemented zip() does away with these issues. The original was kept for backwards compatibility. That's evolution. My sense for the rest is that your difficulties arise from fighting the language rather than using it as designed. Most language features are the result of much deliberation. When design X was chosen over alternative Y, it is a pretty good cue that X is a more harmonious way to do things. Some other languages chose to implement both X and Y. On the plus side, your intuition likely matches one of the two. On the minus side, someone else's intuition may not match your own. Also, it leads to language bloat. More importantly, such a language provides few cues as to how to select components that work together harmoniously. Unfortunately, that makes it effortless to mire yourself in deep goo. My advice is to use the language instead of fighting it. Guido has marked the trail; don't ignore the signs unless you really know where you're going. Raymond "... and soon you'll feel right as rain." -- from The Matrix From rrr at ronadam.com Thu Jul 7 01:21:26 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 05:21:26 GMT Subject: Use cases for del In-Reply-To: <11cp2c8184lnv83@corp.supernews.com> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-07-07, Ron Adam wrote: > >>Grant Edwards wrote: >> >> >>>On 2005-07-06, Ron Adam wrote: >>> >>> >>> >>>>It would be a way to set an argument as being optional without >>>>actually assigning a value to it. The conflict would be if >>>>there where a global with the name baz as well. Probably it >>>>would be better to use a valid null value for what ever baz if >>>>for. If it's a string then "", if its a number then 0, if it's >>>>a list then [], etc... >>> >>>Except those aren't "null values" for those types. 0 is a >>>perfectly good integer value, and I use it quite often. There's >>>a big difference between an "invalid integer value" and an >>>integer with value 0. >> >>Why would you want to use None as an integer value? > > > 1) So I know whether an parameter was passed in or not. Perhaps > it's not considered good Pythonic style, but I like to use a > single method for both get and set operations. With no > parameters, it's a get. With a parameter, it's a set: > > class demo: > def foo(v=None): > if v is not None: > self.v = v > return self.v You are really checking if v exists, so having it undefined in namespace as the default is consistent with what you are doing. As I said above... >>>>It would be a way to set an argument as being optional without >>>>actually assigning a value to it. So it would still work like you expect even though v is not bound to anything. Like I said the bigger problem is that globals will be visible and that would create a conflict. Setting a value to None in a function hides globals of the same name. That wouldn't happen if None unbound names as del does. So you would need to use something else for that purpose I suppose, but that was why None became a literal in the first place, so maybe it's taking a step backwards. > 2) So I can use it as sort of a NaN equivalent. > > if self.fd is None: > self.fd = os.open('foo.bar','w') > > if self.fd is not None: > os.close(self.fd) > self.fd = None It would still work as you expect. A while back I suggested an 'also' for if that would do exactly that with only one test. Nobody liked it. if self.fd is None: self.fd = os.open('foo.bar','w') # do something with self.fd also: os.close(self.fd) self.fd = None >>If a value isn't established yet, then do you need the name >>defined? > > I find it more obvious to set the name to None during the > periods that it isn't valid than to delete it and check for a > NameError when I want to know if the value is usable or not. You would still be able to do that explicitly and it probably would be a good idea when you aren't sure if a name is left over from something else. If a name is None, it means it's available and unassigned, so you don't have to check for a NameError. >>Wouldn't it be better to wait until you need the name then >>give it a value? > > "Better" is a value judgement. I prefer setting it None and > than deleting it and then checking for existance. They would be the same in this case. Setting it to None would delete it also. And checking it for None will let you know it's available or if it has a value... You are right that it's a value judgment. I agree. BTW, I'm sort of just exploring this a bit, not trying to argue it's any better than what we currently do. I think it could work either way, but it would mean doing things in a different way also, not neccisarily a good idea. Cheers, Ron From bdesth.quelquechose at free.quelquepart.fr Sat Jul 9 16:49:40 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 09 Jul 2005 22:49:40 +0200 Subject: Defending Python In-Reply-To: <11cvsutdl580b17@corp.supernews.com> References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> Message-ID: <42d031da$0$30239$636a15ce@news.free.fr> Grant Edwards a ?crit : > On 2005-07-09, Brian wrote: > > >>>folks as an easily acquired extra skill. >> >>I agree 100% with your statement above. Python may not be sufficient >>for being the only programming language that one needs to know -- yet, >>it does come in VERY handy for projects that need to perform tasks on >>non-Microsoft operating systems. :-) > > > It's also darned handy for projects that need to perform tasks > on Microsft operating systems but you want to do all the > development work under a real OS. > It's also darned handy for projects that need to perform tasks on Microsft operating systems. From richardlewis at fastmail.co.uk Wed Jul 6 06:44:55 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Wed, 06 Jul 2005 11:44:55 +0100 Subject: Tkinter grid layout Message-ID: <1120646695.4393.237852689@webmail.messagingengine.com> Hi there, I've got a tree control in Tkinter (using the ESRF Tree module) but I can't get it to layout how I want it. I'd like to have it so that it streches north/south (anchored to the top and bottom), is of a fixed width and is anchored to the left hand side. Here's my code (its derived from one of the examples from the ESRF web site): class MainWindow(Frame): def __init__(self, master): Frame.__init__(self, master) self.document = # new DOM document self.create_site_list() def create_site_list(self): self.list_model = ListModel(self.document) # ListModel class returns the DOM outline as a simple Python data structure self.site_list = Tree.Tree(master=self,\ root_id="root",\ root_label="Site",\ get_contents_callback=self.get_list_item,\ # get_list_item uses the list_model to build list nodes width=300) self.site_list.grid(row=0, column=0, sticky=N+SW) self.grid_rowconfigure(0, weight=1) vsb = Scrollbar(self, orient=VERTICAL) vsb.grid(row=0, column=1, sticky=NS) self.site_list.configure(yscrollcommand=vsb.set) vsb.configure(command=self.site_list.yview) hsb = Scrollbar(self, orient=HORIZONTAL) hsb.grid(row=1, column=0, sticky=EW+S) self.site_list.configure(xscrollcommand=hsb.set) hsb.configure(command=self.site_list.xview) self.site_list.focus_set() This code makes it centred in the east/west direction and a constant height anchored to the top. I guess its the sticky values I need to play with (?) but I can't find the right combination. I've given the code with the ones that seem logically correct (to me!) I expect this is probably quite trivial for someone who knows what they're doing. Any ideas? Cheers, Richard From apoco at cox.net Sun Jul 10 02:42:43 2005 From: apoco at cox.net (Jacob Page) Date: Sat, 09 Jul 2005 23:42:43 -0700 Subject: Python Module Exposure In-Reply-To: <1120975905.198149.19240@z14g2000cwz.googlegroups.com> References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> <1120934851.208175.19180@f14g2000cwb.googlegroups.com> <1120975905.198149.19240@z14g2000cwz.googlegroups.com> Message-ID: George Sakkis wrote: > "Jacob Page" wrote: > >>I selected option one; Intervals are immutable. However, this doesn't >>mean that __add__ has to go, as that function has no side-effects. The >>reason I chose option one was because it's uncommon for a mathematical >>operation on two objects to return a different type altogether. > > Mathematically what you described corresponds to sets that are not > closed under some operation and it's not uncommon at all; a few > examples are: > - The set of integers is not closed under division: int / int -> > rational > - The set of real numbers is not closed under square root: sqrt(real) > -> complex > - The set of positive number is not closed under subtraction: > pos_number - pos_number -> number > - And yes, the set of intervals is not closed under union. Yes, but I wasn't talking about mathematical operations in general; I was talking about mathematical operations in Python. Example: 6 / 5 doesn't yield a float (though I heard that might change in future versions). If the union of two integers yielded a set of integers, then it'd make more since for the union of two Intervals to yield an IntervalSet. But it doesn't. Just as set([2, 6]) creates a set of two integers, IntervalSet(Interval(...), Interval(...)) creates a set of two intervals. > On another note, I noticed you use __contains__ both for membership and > is-subset queries. This is problematic in case of Intervals that have > other Intervals as members. The set builtin type uses __contains__ for > membership checks and issubset for subset checks (with __le__ as > synonym); it's good to keep the same interface. Good catch. I think I've made similar mistakes for a few of the other functions, too. Thanks for your help. From cbfalconer at yahoo.com Mon Jul 11 02:44:27 2005 From: cbfalconer at yahoo.com (CBFalconer) Date: Mon, 11 Jul 2005 06:44:27 GMT Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <1121044120.904683.266560@g14g2000cwa.googlegroups.com> Message-ID: <42D1EB26.4D71F01E@yahoo.com> Paul Bilnoski wrote: > >> The barbar generals will just grunt while the French generals >> will inspire with some poetic invocation. > > For auction: > One authentic French army-issued rifle. Only dropped once. What has that got to do with the king of the elephants? -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson From luismgz at gmail.com Wed Jul 6 14:36:07 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 6 Jul 2005 11:36:07 -0700 Subject: Good starterbook for learning Python? In-Reply-To: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: <1120674966.933845.304690@o13g2000cwo.googlegroups.com> Before buying a book, I suggest starting out with at least one of these beginners tutorials available in internet: - Non-Programmers Tutorial For Python by Josh Cogliati (honors.montana.edu/~jjc/easytut/easytut/) - A Byte of Python by Swaroop CH (www.byteofpython.info) There are many others, but these ones are very good. The first one is best for someone who knows nothing about programing, and the second one is probably better for you, since you already have some experience. It's good for absolute beginners though. Books: - Learning Python by Mark Lutz - Core Python by Wesley Chun Regards, Luis From reinhold-birkenfeld-nospam at wolke7.net Thu Jul 21 18:05:25 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 22 Jul 2005 00:05:25 +0200 Subject: PEP on path module for standard library In-Reply-To: <11e06nch396gccd@news.supernews.com> References: <11e06nch396gccd@news.supernews.com> Message-ID: <3kakh5Ftjd9mU1@individual.net> John Roth wrote: > "Michael Hoffman" wrote in message > news:dbofk2$g1f$1 at gemini.csx.cam.ac.uk... >> Many of you are familiar with Jason Orendorff's path module >> , which is frequently >> recommended here on c.l.p. I submitted an RFE to add it to the Python >> standard library, and Reinhold Birkenfeld started a discussion on it in >> python-dev >> . >> >> The upshot of the discussion was that many python-dev'ers wanted path >> added to the stdlib, but Guido was not convinced and said it must have a >> PEP. > > Why did Guido want a PEP? Is it because he likes the idea but > feels the feature set needs to be examined a bit more by the wider > community, or is it some other reason? He said, """ Whoa! Do we really need a completely different mechanism for doing the same stuff we can already do? The path module seems mostly useful for folks coming from Java who are used to the Java Path class. With the massive duplication of functionality we should also consider what to recommend for the future: will the old os.path module be deprecated, or are we going to maintain both alternatives forever? (And what about all the duplication with the os module itself, like the cwd() constructor?) Remember TOOWTDI. """ Reinhold From steve at REMOVETHIScyber.com.au Sat Jul 23 04:26:43 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 23 Jul 2005 18:26:43 +1000 Subject: is this possible? References: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> <1122044382.956382.287310@g47g2000cwa.googlegroups.com> Message-ID: On Fri, 22 Jul 2005 07:59:42 -0700, scrimp wrote: > I am using reportlab not to generate PDF files, Isn't that amazing! I'm also using reportlab not to generate PDF files too! I installed the program, and it just sits there, not generating as many PDF files as I don't want for as long as I don't want them. :-) > but I want to be able > to print them without having to install acrobat reader. I looked > through the users guide and found nothing about printing to a printer > (programmatically). I want to be able to automate the printing of > reports when they are available. Does anyone know how this is done > using reportlab? thanks! As others have suggested, if you have to deal with PDF files without Acrobat, you could use ghostscript. Also pre-installed on many versions of Linux, and probably other Unixes as well, is pdf2ps which will convert the PDF file to a pure postscript file, which you can then print to any printer which understands postscript. If you are using Windows, you can possibly find open source or free software to do these things. Google is your friend: www.google.com But the chances are you'll have to install *something* -- compared to even the most impoverished Linux distro, Windows is very much "batteries not included", and while Python does come with many batteries, a full-blown postscript interpreter is not one of them. -- Steven. From sarir.khamsi at raytheon.com Thu Jul 28 13:32:23 2005 From: sarir.khamsi at raytheon.com (Sarir Khamsi) Date: Thu, 28 Jul 2005 10:32:23 -0700 Subject: Adding code and methods to a class dynamically Message-ID: I have a class (Command) that derives from cmd.Cmd and I want to add methods to it dynamically. I've added a do_alias() method and it would be nice if I could turn an alias command into a real method of Command (that way the user could get help and name completion). The code would be generated dynamically from what gets passed to the do_alias() method. I've tried looking in the Python cookbook and have tried: def funcToMethod(func, clas, method_name=None): setattr(clas, method_name or func.__name__, func) class Command(object, cmd.Cmd): # ... def do_f1(self, rest): print 'In Command.do_f1()' def do_alias(self, rest): rest.strip() # remove leading and trailing whitespace pat = re.compile(r'^(\w+)\s+(\w+)$') mo = pat.search(rest) if mo: newName = mo.group(1) existingName = mo.group(2) code = 'def do_' + newName + '(self, rest):\n' code += ' self.do_' + existingName + '(rest)\n' exec code funcToMethod(getattr(newModule, 'do_' + existingName), self, 'do_' + 'existingName') else: print 'Invalid alias command' but this does not seem to work. What I get is: $ importDynamic.py (Cmd) do alias x f1 *** Unknown syntax: do alias x f1 (Cmd) Any suggestions? Thanks. Sarir From twic at urchin.earth.li Sun Jul 3 15:26:20 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 3 Jul 2005 20:26:20 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: On Sun, 3 Jul 2005, Tim Peters wrote: > [Fredrik Johansson] > >>>> I'd rather like to see a well implemented math.nthroot. 64**(1/3.0) >>>> gives 3.9999999999999996, and this error could be avoided. > > [Steven D'Aprano] >>>>>> math.exp(math.log(64)/3.0) >>> 4.0 >>> >>> Success!!! > > None of this generalizes usefully -- these are example-driven > curiousities. I was afraid of that. Thanks for shedding some light on it, though. >> YES! This is something that winds me up no end; as far as i can tell, >> there is no clean programmatic way to make an inf or a NaN; > > All Python behavior in the presence of infinities, NaNs, and signed > zeroes is a platform-dependent accident, mostly inherited from that all > C89 behavior in the presence of infinities, NaNs, and signed zeroes is a > platform-dependent crapshoot. Okay. That's a shame. >> in code i write which cares about such things, i have to start: >> >> inf = 1e300 ** 1e300 >> nan = inf - inf > > That would be much more portable (== would do what you intended by > accident on many more platforms) if you used multiplication instead of > exponentiation in the first line. Yes - that's what i meant to write, but i must have got carried away with the asterisks. Sorry about that. >> And then god forbid i should actually want to test if a number is NaN, >> since, bizarrely, (x == nan) is true for every x; instead, i have to >> write: >> >> def isnan(x): >> return (x == 0.0) and (x == 1.0) > > The result of that is a platform-dependent accident too. Python 2.4 > (but not eariler than that) works hard to deliver _exactly_ the same > accident as the platform C compiler delivers, and at least NaN > comparisons work "as intended" (by IEEE 754) in 2.4 under gcc and MSVC > 7.1 (because those C implementations treat NaN comparisons as intended > by IEEE 754; note that MSVC 6.0 did not): > > So at the Python level you can do "x != x" to see whether x is a NaN > in 2.4+(assuming that works in the C with which Python was compiled; > it does under gcc and MSVC 7.1). I see. I have to confess that i'm using 2.3. So, is there a way of generating and testing for infinities and NaNs that's portable across platforms and versions of python? If not, could we perhaps have some constants in the math module for them? math.inf and math.nan should do nicely (although there is the question of just _which_ nan that should be ...). It wouldn't help with old versions of python, but it'd solve the problem for the future. >> or is this expression: >> >> -1.0 ** 0.5 >> >> Evaluated wrongly? > > Read the manual for the precedence rules. -x**y groups as -(x**y). -1.0 > is the correct answer. If you intended (-x)**y, then you need to insert > parentheses to force that order. So i see. Any idea why that precedence order was chosen? It goes against conventional mathematical notation, as well as established practice in other languages. Also, would it be a good idea for (-1.0) ** 0.5 to evaluate to 1.0j? It seems a shame to have complex numbers in the language and then miss this opportunity to use them! tom -- When you mentioned INSERT-MIND-INPUT ... did they look at you like this? From sarir.khamsi at raytheon.com Fri Jul 29 16:56:57 2005 From: sarir.khamsi at raytheon.com (Sarir Khamsi) Date: Fri, 29 Jul 2005 13:56:57 -0700 Subject: Adding code and methods to a class dynamically References: Message-ID: Peter Hansen writes: > I'm not sure what "completion" means in this case, and I'm not aware > of any "command-line completion" support in cmd.Cmd though it may well > be there, so I can't say. Certainly there is nothing in any way > different about the new attribute created by the alias code, as both > it and the original attribute are bound to exactly the same method. If you have the readline module, you get TAB command completion for free (a la bash, emacs, etc)...or maybe readline only gives you emacs-style command history editing, or both...not sure. From usenet at zabiello.com Mon Jul 18 07:45:22 2005 From: usenet at zabiello.com (JZ) Date: Mon, 18 Jul 2005 13:45:22 +0200 Subject: What is your favorite Python web framework? References: <1121685852.674382.216790@g14g2000cwa.googlegroups.com> Message-ID: <1myz92llzdq71.qz6wr10keyp8.dlg@40tude.net> Dnia 18 Jul 2005 04:24:12 -0700, paron napisa?(a): >>I favor speed of development, intensive OO development, performance under >>heavy load, short learning curve, good documentation and community. > > I settled on CherryPy: > > Performance under load -- can't say one way or the other. I do know > it's lightweight -- 40kb download, I recall. I do not know how new CherryPy 2.1 (which now can use wsgi) is fast and stable but earler versions were quite unstable under heavy loads. Its paradigm "creating web site like standalone appl" (inherited from Cherry1) is not good suited to more complicated internet applications. Much more stable and much faster is e.g. Mygty (http://myghty.org) It is about 2x faster then CherryPy. Also faster than CherryPy is Webware and SkunkWeb. I did not check how fast is Django... It is fresh framework for open source community. -- JZ From pinard at iro.umontreal.ca Sun Jul 31 10:37:27 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 31 Jul 2005 10:37:27 -0400 Subject: keylogger in Python In-Reply-To: References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> Message-ID: <20050731143727.GA8428@phenix.progiciels-bpi.ca> [Michael Hoffman] > Jay wrote: > > yo, thanks for the great input. And the only reason i want to > > create a python based keylogger is because there is none. Just a > > fun project... But im gonna do some more research on the keyboard > > drivers and stuff like that and to learn how to attach my python > > porgrams into the sub-processes so that it would instead log every > > char instead of just char in the IDE. > I think this is going to be much harder than you think, and I imagine > this will only end in frustration for you. You will not be able to do > it well with just Python. I would recommend a different fun project. I'm just stumbling on that message, and did not follow the whole thread, sorry if I repeat things already discussed. My point is that Python is able to do surprising things, given the `fcntl' and `ioctl' modules. Surely on Linux, logging keys under X-Windows or under virtual terminals are quite different matters. Let me share a related experience for virtual terminals. I once had to rush the port on Linux a few QNX applications, written in C, which were using the QNX term library for input and display. In console mode, the QNX keyboard is richer than the Linux one. As users wanted to retain the _exact_ keyboard functionality, I saw no choice but reading raw scan codes on the Linux side. So, I wrote a term library emulator as a thin C layer, which was itself using a Python module (Python was to be transparently embedded by the emulated library) for doing the bulk of keyboard processing. It was something pretty heretic to do, I know. But Python was more than fast enough for handling the low-level keyboard reading, for applications otherwise all written in C. But it allowed the port to be done quickly. While debugging such a thing, you often loose the keyboard and with it, the capability of switching terminals, so you have to devise some extra machinery for restoring the keyboard into a usable state. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From donn at drizzle.com Thu Jul 21 01:42:32 2005 From: donn at drizzle.com (Donn Cave) Date: Thu, 21 Jul 2005 05:42:32 -0000 Subject: Need to interrupt to check for mouse movement References: <7xoe8woii0.fsf@ruckus.brouhaha.com> Message-ID: <1121924551.512211@yasure> Quoth Paul Rubin : | Christopher Subich writes: | > > In the particular case of wxWidgets, it turns out that the *GUI* | > > blocks for long periods of time, preventing the *network* from | > > getting attention. But I agree with your position for other | > > toolkits, such as Gtk, Qt, or Tk. | > | > Wow, I'm not familiar with wxWidgets; how's that work? | | Huh? It's pretty normal, the gui blocks while waiting for events | from the window system. I expect that Qt and Tk work the same way. In fact anything works that way, that being the nature of I/O. But usually there's a way to add your own I/O source to be dispatched along with the UI events -- the toolkit will for example use select() to wait for X11 socket I/O, so it can also respond to incoming data on another socket, provided along with a callback function by the application. Am I hearing that wxWindows or other popular toolkits don't provide any such feature, and need multiple threads for this reason? Donn Cave, donn at drizzle.com From steve at REMOVETHIScyber.com.au Wed Jul 13 09:55:28 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 23:55:28 +1000 Subject: Building a function call? References: Message-ID: On Wed, 13 Jul 2005 06:16:54 -0700, Robert Kern wrote: > Duncan Booth wrote: >> Francois De Serres wrote: >> >>>Having a string: "dothat" >>>and a tuple: (x, y) >>>1. What's the best way to build a function call like: dothat(x,y)? [snip] >> No, none of this is a good place to use eval. [snip] >> import otherModule >> vars(otherModule)[aString](*aTuple) > > Ick! Please: > getattr(otherModule, aString)(*aTuple) Or, remember that functions are first class objects in Python. Instead of passing around the function name as a string, pass around a reference to the function itself. Something like this: def dothis(x,y): return x-y def dothat(x,y): return x+y somefunction = dothis somefunction(3, 2) => returns 1 somefunction = dothat somefunction(3, 2) => returns 5 allfunctions = [dothis, dothat] for func in allfunctions: print func(3, 2) => prints 1 then 5 If you want to collect user-supplied strings and use them to find a function, you could use eval (terribly risky and unsafe), or you could do something like this: funcnames = {} for func in allfunctions: funcnames[func.__name__] = func F = raw_input("Enter the name of a function: ") try: funcnames[F](3, 2) except KeyError: print "Function '%s' not found!" % F In my humble opinion, people muck about with eval, locals and globals far too often. It is unclear, hard to maintain, and frequently a security risk. These confusing, unsafe practices can usually be avoided by remembering that functions are first class objects just like ints, strings and lists. -- Steven. From kay.schluehr at gmx.net Sat Jul 9 08:39:34 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 Jul 2005 05:39:34 -0700 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <20050705232102.18901.qmail@web31508.mail.mud.yahoo.com> Message-ID: <1120912774.258331.12150@g47g2000cwa.googlegroups.com> Ralf W. Grosse-Kunstleve schrieb: > My initial proposal > (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't > exactly get a warm welcome... Well ... yes ;) Ralf, if you want to modify the class instantiation behaviour you should have a look on metaclasses. That's what they are for. It is not a particular good idea to integrate a new method into the object base class for each accidental idea and write a PEP for it. I provide you an example which is actually your use case. It doesn't change the class hierarchy : the metaclass semantics is not "is a" as for inheritance but "customizes" as one would expect also for decorators. class autoattr(type): ''' The autoattr metaclass is used to extract auto_xxx parameters from the argument-tuple or the keyword arguments of an object constructor __init__ and create object attributes mit name xxx and the value of auto_xxx passed into __init__ ''' def __init__(cls,name, bases, dct): super(autoattr,cls).__init__(name,bases,dct) old_init = cls.__init__ defaults = cls.__init__.im_func.func_defaults varnames = cls.__init__.im_func.func_code.co_varnames[1:] def new_init(self,*args,**kwd): for var,default in zip(varnames[-len(defaults):],defaults): if var.startswith("auto_"): self.__dict__[var[5:]] = default for var,arg in zip(varnames,args): if var.startswith("auto_"): self.__dict__[var[5:]] = arg for (key,val) in kwd.items(): if key.startswith("auto_"): self.__dict__[key[5:]] = val old_init(self,*args,**kwd) cls.__init__ = new_init class app: __metaclass__ = autoattr def __init__(self, auto_x, y, auto_z = 9): pass >>> a = app(2,5) >>> a.x 2 >>> a.z 9 >>> a.y -> AttributeError Kay From Scott.Daniels at Acm.Org Sat Jul 2 15:26:49 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 02 Jul 2005 12:26:49 -0700 Subject: Inheriting from object In-Reply-To: <42c69a4f.336127175@news.oz.net> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> <42c69a4f.336127175@news.oz.net> Message-ID: <42c6e2ca$1@nntp0.pdx.net> Bengt Richter wrote: > On Thu, 30 Jun 2005 08:54:31 -0700, Scott David Daniels wrote: >>Or, perhaps: >> class foo(object): >> def __init__(self, *args, **kwargs): >> super(foo, self).__init__(self, *args, **kwargs) >> ... >> > > Doesn't super(foo, self).__init__ return a bound method, so you don't > need to pass self again? I.e., > super(foo, self).__init__(*args, **kwargs) Yes, of course (a silly cut-o / paste-o). > BTW, there's something about referring to type(self) by its not > always dependably bound (though usually global) name that bothers me. > > I wonder if the above common use of super could be implemented as a property of object, > so you'd normally inherit it and be able to write > self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose) > > I.e., self.__super__ would effectively return the equivalent of > super(type(self), self) The problem with this is: class A(object): def __init__(self, *args, **kwargs): print 'Set A(*%r, **%r)' % (args, kwargs) class B(A): def __init__(self, *args, **kwargs): print 'Set B(*%r, **%r)' % (args, kwargs) super(B, self).__init__(*args, **kwargs) class C(B): def __init__(self, *args, **kwargs): print 'Set C(*%r, **%r)' % (args, kwargs) super(C, self).__init__(*args, **kwargs) class D(A): def __init__(self, *args, **kwargs): print 'Set D(*%r, **%r)' % (args, kwargs) super(type(self), self).__init__(*args, **kwargs) class E(D): def __init__(self, *args, **kwargs): print 'Set E(*%r, **%r)' % (args, kwargs) super(type(self), self).__init__(*args, **kwargs) You'll see the problem when you attempt to create an instance of E. All of the others work just fine. --Scott David Daniels Scott.Daniels at Acm.Org From bokr at oz.net Tue Jul 12 22:25:35 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Jul 2005 02:25:35 GMT Subject: if not DEBUG: log = null_log References: Message-ID: <42d47595.35476352@news.oz.net> On Wed, 13 Jul 2005 11:00:14 +1000, Simon Burton wrote: > >Hi, > >I'm after a no-op command, so that i can redirect >logging commands in performance critical code. > >Something like this: > >def log(*args): print args >def null_log(*args): pass >if not DEBUG: log = null_log > >is unacceptable because of the overhead of calling >functions in python. > I think you could make the existence of log calls dependent on whether you compile with an optimize flag by abusing an assert statement, e.g., assert log(some, args) or True would always make the call in debug mode, but would never raise the exception because of the "or True", even if log return None. If you compile with optimization, the entire assert statement disappears from the byte code, UIAM. if you use if __debug__: log(some, args) I think[1] you still the the if-test code, though that is pretty quick compared to a function call, so maybe you don't have to worry about it, unless it is in a super-hot loop. [1] I thought is saw somewhere that if __debug__: suite might be completely optimized away like assert, but I couldn't locate it off hand. It would seem pretty safe and useful though. Regards, Bengt Richter From guettli at thomas-guettler.de Mon Jul 25 05:13:55 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 25 Jul 2005 11:13:55 +0200 Subject: Importing User-defined Modules References: Message-ID: Am Sun, 24 Jul 2005 13:12:04 -0400 schrieb Walter Brunswick: > I need to import modules with user-defined file extensions that differ from '.py', and also (if possible) redirect the bytecode > output of the file to a file of a user-defined extension. > I've already read PEP 302 (http://www.python.org/peps/pep-0302.html), but I didn't fully understand it. Would someone [who > understands it] please be able to give me a synopsis of it, along with a few explanatory examples, or some other alternatives, if > any? You could do it like this: Copy the file to directory which is in sys.path. Give the file the extension ".py". Import it with __import__ (http://docs.python.org/lib/built-in-funcs.html#l2h-6) Copy the bytecode somewhere. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From rkern at ucsd.edu Mon Jul 4 00:33:05 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 03 Jul 2005 21:33:05 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> Message-ID: Erik Max Francis wrote: > Ron Adam wrote: > >>So you are saying that anything that has a 1% use case should be >>included as a builtin function? >> >>I think I can find a few hundred other functions in the library that are >>used more than ten times as often as reduce. Should those be builtins too? >> >>This is a practical over purity issue, so what are the practical reasons >>for keeping it. "It's already there" isn't a practical reason. And it >>covers 100% of it's own potential use cases, is circular logic without a >>real underlying basis. > > But the Python 3000 plan, at least what we've heard of it so far, isn't > to move it to a standard library module. It's to remove it altogether, > replacing it with sum and product. Since sum and product don't cover > all the uses cases for reduce, this is a case of taking one function > that handles all the required use cases and replacing it with _two_ > functions that don't. Since it's doubling the footprint of the reduce > functionality, arguments about avoiding pollution are red herrings. Four, in fact. sum(), product(), any(), and all(). The problem with this discussion is that no one is saying anything new[1]. We've heard all of the arguments for and against removing these functions. Over and over and over again. They're not changing anyone's mind, not yours, not mine, and definitely not Guido's. And it's not even like Python 3000 is around the corner or in any stage of concrete planning. Adding our voices to the chorus *now* won't make a bit of difference, nor should it. The size of the chorus doesn't matter; Python isn't developed by votes. We tried that once before; it didn't work so well. When planning for Python 3000 really gets going, when Guido gets a year's sabbatical to work on it, when we can see how map/filter/reduce/lambda fit into the whole scheme of how this new language works, *then* is the time to be having these discussions. Right now, all we're doing is making each other bitter and angry for no good reason. [1] Okay, there was that guy who predicted that list comprehensions and first-class functions were the next to go. That was new. But also wrong. I think we can discount that. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gsakkis at rutgers.edu Tue Jul 12 07:53:31 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jul 2005 04:53:31 -0700 Subject: automatically assigning names to indexes References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> Message-ID: <1121169211.877343.200570@z14g2000cwz.googlegroups.com> wrote: > I know its been done before, but I'm hacking away on a simple Vector > class. > > class Vector(tuple): > def __add__(self, b): > return Vector([x+y for x,y in zip(self, b)]) > def __sub__(self, b): > return Vector([x-y for x,y in zip(self, b)]) > def __div__(self, b): > return Vector([x/b for x in self]) > def __mul__(self, b): > return Vector([x*b for x in self]) > > I like it, because it is simple, and can work with vectors of any > size... > > However, I'd like to add attribute access (magically), so I can do > this: > > v = Vector((1,2,3)) > print v.x > print v.y > print v.z > > as well as: > > print v[0] > print v[1] > print v[2] > > Has anyone got any ideas on how this might be done? And what should happen for vectors of size != 3 ? I don't think that a general purpose vector class should allow it; a Vector3D subclass would be more natural for this. George From Steve.Coates at smiths-aerospace.com Mon Jul 4 02:48:58 2005 From: Steve.Coates at smiths-aerospace.com (Coates, Steve (ACHE)) Date: Mon, 4 Jul 2005 00:48:58 -0600 Subject: Determining actual elapsed (wall-clock) time Message-ID: <3082C9F9373DAD43918C64BAC1CF038CF59222@COSSMGMBX04.EMAIL.CORP.TLD> > -----Original Message----- > From: Roy Smith [mailto:roy at panix.com] > Sent: 02 July 2005 21:22 > To: python-list at python.org > Subject: Re: Determining actual elapsed (wall-clock) time > If you get the UTC time, daylight savings time doesn't enter > the equation. > If the system clock is reset, however, you're out of luck. I > can't think of any time-related API which doesn't rely on the > system clock as a reference. If the system clock is good, > you get good time. If the system clock sucks, or changes, you don't. > > If you care about time, you want your system clock controlled > by NTP. > There's just no excuse not to. > > Is there some reason you can't just use the system clock? I > suppose if you had to, you could hobble together your own NTP > client which keeps network time independent of the system > clock. But that would be a lot of work and it's hard to > imagine the effort would be justified. > > There is already an NTP client in the ASPN cookbook :- http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117211 ****************************************** The information contained in, or attached to, this e-mail, may contain confidential information and is intended solely for the use of the individual or entity to whom they are addressed and may be subject to legal privilege. If you have received this e-mail in error you should notify the sender immediately by reply e-mail, delete the message from your system and notify your system manager. Please do not copy it for any purpose, or disclose its contents to any other person. The views or opinions presented in this e-mail are solely those of the author and do not necessarily represent those of the company. The recipient should check this e-mail and any attachments for the presence of viruses. The company accepts no liability for any damage caused, directly or indirectly, by any virus transmitted in this email. ****************************************** From caleb1 at telkomsa.net Tue Jul 19 17:26:13 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 19 Jul 2005 23:26:13 +0200 Subject: Finding # prefixing numbers References: <1121772902.193765.258700@g49g2000cwa.googlegroups.com> Message-ID: You really owe it to yourself to try the PyParsing package, if you have to do this kind of thing with any frequency. The syntactic difference between PyParsing and regular expressions is greater than the syntactic difference between Python and C. thx Caleb On Tue, 19 Jul 2005 13:35:02 +0200, peterbe at gmail.com wrote: > In a text that contains references to numbers like this: #583 I want to > find them with a regular expression but I'm having problems with the > hash. Hopefully this code explains where I'm stuck: > >>>> import re >>>> re.compile(r'\b(\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > ['123', '234', '456'] >>>> re.compile(r'\b(X\d\d\d)\b').findall('X123 x (X234) or:X456 X6789') > ['X123', 'X234', 'X456'] >>>> re.compile(r'\b(#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > [] >>>> re.compile(r'\b(\#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > [] > > As you can guess, I'm trying to find a hash followed by 3 digits word > bounded. As in the example above, it wouldn't have been a problem if > the prefix was an 'X' but that's not the case here. > From graham.fawcett at gmail.com Tue Jul 12 13:07:37 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 12 Jul 2005 10:07:37 -0700 Subject: Web App like Google References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> Message-ID: <1121188057.886202.86860@g43g2000cwa.googlegroups.com> In translating natural language to SQL, be sure you're not introducing opportunities for SQL injection attacks. Code like sql = 'SELECT %s FROM %s' % (this, that) is considered dangerous, because a well-crafted value for "that" can be used to, e.g., delete rows from your tables, run system commands, etc. You can save a lot of worry by using a database account with read-only privileges, but you still have to be careful. My advice is to read up on "sql injection" before going too public with your code. Graham From grante at visi.com Thu Jul 7 10:48:03 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 14:48:03 -0000 Subject: Do a "Python beginners e-mail list" exist? References: Message-ID: <11cqg53dg8gmj6b@corp.supernews.com> On 2005-07-07, Alessandro Brollo wrote: > Far from a professional programmer, I'm simply a newbie Python > user. Two basic questions: > > 1. I don't want to post banal questions about Python to main > Python list. Go ahead. We're really quite nice. Extraordinarily so by Usenet standards. > Does a "banal Python questions list" or a "Python > beginners list" exist? There's a tutor list: http://mail.python.org/mailman/listinfo/tutor > 2. There is somewhere a very patient fellow willing to be my > free "python tutor" by personal e-mailing outside the mail > list? . The ideal candidate would be someone, sharing with > me some other fields of interest (I'm a middle-aged Italian > pathologist, with some dBase III and dBase IV past > programming experience, and I like nature and mainly > horses). I guess I'm out, the only thing I can claim is middle-age. :) We generally encourange questions to be posted in public forums such as the tutor list or c.l.p so that others can benefit from the exchange as well. No matter what you ask, somebody else will someday want to know the same thing, and Google will find them the answer if it's in a public forum. -- Grant Edwards grante Yow! He is the at MELBA-BEING... the ANGEL visi.com CAKE... XEROX him... XEROX him -- From ross at REMOVETHISorcon.ETC.nz Tue Jul 19 04:28:31 2005 From: ross at REMOVETHISorcon.ETC.nz (Ross) Date: Tue, 19 Jul 2005 20:28:31 +1200 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> Message-ID: On 15 Jul 2005 17:33:39 -0700, "MKoool" wrote: >I have a file with binary and ascii characters in it. I massage the >data and convert it to a more readable format, however it still comes >up with some binary characters mixed in. I'd like to write something >to just replace all non-printable characters with '' (I want to delete >non-printable characters). > >I am having trouble figuring out an easy python way to do this... is >the easiest way to just write some regular expression that does >something like replace [^\p] with ''? > >Or is it better to go through every character and do ord(character), >check the ascii values? > >What's the easiest way to do something like this? > >thanks Easiest way is open the file with EdXor (freeware editor), select all, Format > Wipe Non-Ascii. Ok it's not python, but it's the easiest. From bokr at oz.net Sat Jul 30 14:42:59 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Jul 2005 18:42:59 GMT Subject: functions without parentheses References: <42e9c49b.24281464@news.oz.net> Message-ID: <42ebc3e4.155170673@news.oz.net> On Fri, 29 Jul 2005 20:54:42 +1000, Steven D'Aprano wrote: >On Fri, 29 Jul 2005 06:37:52 +0000, Bengt Richter wrote: > >> I suggested in a previous thread that one could support such a syntax by >> supporting an invisible binary operator between two expressions, so that >> examine "string" translates to examine.__invisbinop__("string") if >> examine as an expression evaluates to an object that has a __invisbinop__ method. > >Why would you want to? > Mainly to say that I think there is way to do it (and thus further to mulch the idea garden ;-) whatever the merits. As to the merits, I haven't thought about it much, but ISTM for limited contexts it would allow you to spell concatenating/aggregating expressions without the "line noise" of intervening operator glyphs, e.g., agg = Aggregate() first_thing second_thing 3 "four" etc.and.so.forth ; or mypath = Path() prefix middle filename+'.ext' ; # explicit terminating ';' or (...) might be needed # if EOL can be part of whitespace delim as below or arr = (ArrayElementAggregator() 11 12 13 21 22 23 ) The latter presupposes that white-space including an EOL causes attempt to access an alternate __invisbinop__ (e.g., __invisbinopNL__) that one could define to aggregate new rows of expressions, but would not be an error if absent, and thus end a single-line aggregator without explict ';' or parens. I haven't thought of all the ramifications, I was just playing with the idea ;-) Others might think of other ways to answer your "why" ;-) Regards, Bengt Richter From gene.tani at gmail.com Tue Jul 19 13:39:06 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jul 2005 10:39:06 -0700 Subject: OO design In-Reply-To: <87br4zdpym.fsf@bigfoot.com> References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> <87br4zdpym.fsf@bigfoot.com> Message-ID: <1121794745.991117.286410@g44g2000cwa.googlegroups.com> fav DP books: http://www.oreilly.com/catalog/hfdesignpat/ http://www.netobjectives.com/dpexplained/ From harold.fellermann at upf.edu Thu Jul 7 09:50:19 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 7 Jul 2005 15:50:19 +0200 Subject: Windows Cmd.exe Window In-Reply-To: <48cc122d9ef6d3dc90fd4ca36482a1da@upf.edu> References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <1120742729.424832.189110@f14g2000cwb.googlegroups.com> <48cc122d9ef6d3dc90fd4ca36482a1da@upf.edu> Message-ID: <03537e8a6a228d6e34e6742c4e7d7c81@upf.edu> On 07.07.2005, at 15:43, harold fellermann wrote: > On 07.07.2005, at 15:25, Giles Brown wrote: > >> Nah. You're missing my point. I only want the command window not to >> be closed if there is an *exception*. Picky I know, but there you go. > > well, then register raw_input as exit function: > >>>> import atexit >>>> atexit.register(raw_input) > > works fine in my terminal. should do in your framework also. sorry, I did not think. if you want to wait for input _only_ if an exception occured, your exit function needs to check for the exception: >>> import atexit >>> >>> def wait_on_exc() : ... import sys ... if sys.exc_type : ... raw_input() ... >>> atexit.register(wait_on_exc) this should do the job, now. - harold - -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen From deets at web.de Sun Jul 3 08:53:27 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 03 Jul 2005 14:53:27 +0200 Subject: website catcher In-Reply-To: <1120393925.181952.192040@g49g2000cwa.googlegroups.com> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> Message-ID: <3iq5e7Fmn8drU1@uni-berlin.de> jwaixs wrote: > Thank you, but it's not what I mean. I don't want some kind of client > parser thing. But I mean the page is already been parsed and ready to > be read. But I want to store this page for more use. I need some kind > of database that won't exit if the cgi-bin script has finished. This > database need to be open all the time and communicate very easily with > the cgi-bin framwork main class. Why does it need to be "open"? Store it in a pickled file, an load read that pickle when you need it. Or not even as pickle, just as file in the FS. Basically what you are talking about is a webserver - so just use that. Diez From jepler at unpythonic.net Thu Jul 28 12:05:14 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 28 Jul 2005 11:05:14 -0500 Subject: codecs.getencoder encodes entire string ? In-Reply-To: <1122565377.433764.274280@f14g2000cwb.googlegroups.com> References: <1122565377.433764.274280@f14g2000cwb.googlegroups.com> Message-ID: <20050728160510.GB13474@unpythonic.net> On Thu, Jul 28, 2005 at 08:42:57AM -0700, nicolas_riesch wrote: > And a last question: can I call this "enc" function from multiple > threads ? Yes. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cliff at develix.com Sun Jul 31 14:33:37 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 11:33:37 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <873bpvqu9g.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> Message-ID: <1122834817.19618.58.camel@localhost.localdomain> On Sun, 2005-07-31 at 10:01 +0200, Torsten Bronger wrote: > Hall?chen! > > Cliff Wells writes: > > > [...] > > > > The least headache for end users comes from properly packaging your > > application. End users shouldn't need to worry about installing third > > party packages (or even Python for that matter). Tools such as py2exe > > and Inno installer make this pretty simple on Windows, and py2app on > > OS/X accomplishes the same. > > Does py2exe work for all GUI libraries? It'll highly probably work > with Tkinter, and I've read that it also works with pyGTK, but does > it also work with wxPython or PyQt? py2exe and py2app work for wxPython at least, not sure about the other gui toolkits. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From lainedacier at gmail.com Tue Jul 26 05:30:28 2005 From: lainedacier at gmail.com (lainedacier at gmail.com) Date: 26 Jul 2005 02:30:28 -0700 Subject: Suggestions for Python XML library which can search and insert In-Reply-To: <42E5EEB7.400@REMOVEMEcyber.com.au> References: <1122354487.477401.290910@g43g2000cwa.googlegroups.com> <42E5EEB7.400@REMOVEMEcyber.com.au> Message-ID: <1122370228.292828.283450@g44g2000cwa.googlegroups.com> > Why do you care if they are nested for loops? > > What is the problem you are experiencing that is caused > by for loops? > The nested loops which I speak of are highly dependent on the structure of the document tree. The examples which I've seen using DOM or ElementTree deal with shallow trees, but in my case, I am dealing with deeper trees--which means that the degree of nesting would also grow deeper if I were to follow suit. Also, it makes for hard to manage code. I'd say that lxml is exactly what I'm looking for, because it supports XPath and Robert Kern's example is pretty reassuring. Thanks Robert Kern! From peter at engcorp.com Fri Jul 22 14:25:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 14:25:50 -0400 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Stefan Rank wrote: > (It would be nice to get `path`(s) easily from a `file`, at the moment > there is only file.name if I'm not mistaken). When files are opened through a "path" object -- e.g. path('name').open() -- then file.name returns the path object that was used to open it. -Peter From qwweeeit at yahoo.it Thu Jul 14 12:53:36 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 14 Jul 2005 09:53:36 -0700 Subject: Splitting on a word References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> <1121344568.230244.214440@o13g2000cwo.googlegroups.com> Message-ID: <1121360016.527837.283180@g49g2000cwa.googlegroups.com> Hi Bernhard, firstly you must excuse my English ("angry" is a little ...strong, but my vocabulary is limited). I hope that the experts keep on helping us newbie. Also if I am a newbie (in Python), I disagree with you: my solution (with the help of Joe) answers to the problem of splitting a string using a delimiter of more than one character (sometimes a word as delimiter, but it is not required). The code I supplied can be misleading because is centered in web parsing, but my request is more general (Next time I will only make the question without examples!) If I were a professional programmer I could agree with you and the "Batteries included" concept and all the other considerations ("off-the-shelf solutions" and ...not reinventing the wheel). Also the terrific example you supply in order to caution me not to follow dully (found in the dictionary) the "simple & short" concept, doesn't apply to me (too complicated!). I am so far from a real programmer that when an error occurs, I use try/except (if they solve the problem) without caring of the sources of the mistake, ...EAFP!). So I don't care too much of possible future mistakes (also if the code takes into account capital letters). For the specific case I mentioned, actually if the closing tag ">" is missing perhaps I obtain wrong results... I will worry when necessary (also if the Murphy law...). Bye. From bokr at oz.net Mon Jul 25 16:30:34 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 25 Jul 2005 20:30:34 GMT Subject: [path-PEP] Path inherits from basestring again References: <3kjihkFubvl6U1@individual.net> <74SdndmpGeuannjfRVn-1w@powergate.ca> Message-ID: <42e5489f.1138078400@news.oz.net> On Mon, 25 Jul 2005 11:19:25 -0400, Peter Hansen wrote: >Michael Hoffman wrote: >> Reinhold Birkenfeld wrote: >>> Tony Meyer wrote: >>>> Do people really like using __div__ to mean join? >>> >>> I'm not too happy with it, too, but do we have alternatives? ... >>> Of course, one can use joinwith() if he doesn't like '/'. >> >> I've used the path module pretty extensively and always use joinpath(). >> Personally, I'm -0 on __div__, but I suppose if anyone here claimed to >> have used in the past, rather than it just being some novelty that might >> be a good idea, that would be good enough for keeping it. > >I've tried it both ways, and ended up accepting / as a useful and clean >approach, though as a general rule I find operator-overloading to be >fairly hideous and to lead to Perlish code. This one I resisted for a >while, then found it fairly pleasant, making it perhaps the exception to >the rule... > >Perhaps it's just that in code that builds paths out of several >components, it seemed quite straightforward to read when it used / >instead of method calls. > >For example, from one program: > > scripts = userfolder / scriptfolder > scriptpath = scripts / self.config['system']['commandfile'] > >instead of what used to be: > > scripts = userfolder.joinpath(scriptfolder) > scriptpath = scripts.joinpath(self.config['system']['commandfile']) > >Even so I'm only +0 on it. (;-) How about a __use_adjacent_operand__ op with simple expression white-space-separated adjacency implying it? Then you could leave out the '/' and write scripts = userfolder scriptfolder scriptpath = scripts self.config['system']['commandfile'] Hm, if you made that __hadjacent__ for horizontal whitespace, and __vadjacent__ if the white space included '\n', then you could form even two-dimensional arrays without all that of punctuation (except that you'd need an explicit ending ';' for the above or () most likely for 2D) (funnyarray() 1 2 3 4 5 6 ) BTW, more OT, wouldn't '|' be more platform-neutral as the joining operator? ;-) Regards, Bengt Richter From cjw at sympatico.ca Mon Jul 18 14:15:30 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 18 Jul 2005 14:15:30 -0400 Subject: What is your favorite Python web framework? In-Reply-To: <1121707100.874433.115360@g49g2000cwa.googlegroups.com> References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> <8Y-dnatKvJ13LEbfRVn-rQ@powergate.ca> <1121707100.874433.115360@g49g2000cwa.googlegroups.com> Message-ID: <0lSCe.2023$je2.289853@news20.bellglobal.com> Luis M. Gonzalez wrote: > Peter Hansen wrote: > >>Gerhard Haering wrote: >> >>>On Mon, Jul 18, 2005 at 09:06:21AM -0400, Peter Hansen wrote: >>> >>>>I'm not familiar with this expression. What do you mean by "black horse"? >>> >>>Maybe "the Ferrari of pythonic frameworks" (black horse on yellow >>>background being the symbol of Ferrari). >> >>I know there are "black sheep" in some families, and "dark horse >>candidates". Also yellow-bellied sapsuckers. There's a "black horse" >>fish in the Mississippi valley (also, quite coincidentally, of the >>sucker family). Not entirely sure that was the intended connotation. :-) >> >>-Peter > > > I'm used to make those mistakes too... > This mailing list taught me more English than Python for sure. > I read the expression "Dark horse contender" many times, and i guess it > has some reminiscence from medieval times and the cavalry stories. > It meaning is something like the "unknown that could be the new champ", > someone intriguing and mysterious who doesn't unveil its skills untill > showtime. Am I right? > > Cheers, > Luis > You're right on!. Colin W. From lbates at syscononline.com Fri Jul 1 15:42:40 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 01 Jul 2005 14:42:40 -0500 Subject: calldll compiled for Python 2.4 for Windows Message-ID: Does anyone have calldll.pyd compiled for Python 2.4 for Windows? I've made extensive use of it and haven't had the time to go back and convert everything to ctypes. I'd like to upgrade from Python 2.2 but am stuck without this module. BTW, I don't have any C compilers available on my machine. Thanks in advance for any assistance. Larry Bates From zen19725 at zen.co.uk Sun Jul 31 04:39:25 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 09:39:25 +0100 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <7x3bpve8w5.fsf@ruckus.brouhaha.com> Message-ID: On 31 Jul 2005 00:23:38 -0700, Paul Rubin wrote: >zen19725 at zen.co.uk (phil hunt) writes: >> What you say Pythonic, what do you mean? And how do you rate >> Tkinter, PyGtk, PyQt/PyKDE, wxWindows for "Pythonicness"? > >Tkinter is not very Pythonic because it's sort of a Frankenstein >hybrid of Python and Tcl, but at least it's there and it more or less >works. The others are non-Pythonic because they're not included in >the standard distro and therefore the Pythonic "use the included >batteries" tenet says to use Tkinter despite its flaws. OK, hows this for an idea: 1. create a new API, loosely based on the Tkinter API, but more Pythonic 2. implement Tk using this API (probably won't be difficult because we can use Tkinter as a base) 3. Implement bindings to Gtk and Qt/KDE using this API. -- Email: zen19725 at zen dot co dot uk From thomasbartkus at comcast.net Fri Jul 8 14:03:56 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 8 Jul 2005 13:03:56 -0500 Subject: pygtk does ... ? Message-ID: <9ZCdneC20ZwHIlPfRVn-jQ@telcove.net> I am experimenting (flailing around?) with glade and python. Both under MS Windows and Linux. I understand why I want to "import gtk" It gives me access to the critical gui program loop gtk.main() and main_quit() I am also very grateful for import gtk.glade This lets me open my xml format glade file gtk.glade.XML("MyGladeFile.glade") full of defined gtk widgets and the function signal_autoconnect(dic) which lets me hang my Python callback routines onto those gtk widgets. Whew! At least I've gotten started. It sure wasn't easy. The question is - What the heck is the pygtk library for? help(pygtk) tells me not much more than - "Python bindings for the GTK+ widget set" Why would I want to "import pygtk" with it's single function "require(version)"? What is it supposed to do? Where does it fit in? Or does it fit in at all? Thomas Bartkus From xen0n at vodafone.it Tue Jul 19 09:47:10 2005 From: xen0n at vodafone.it (xen0n at vodafone.it) Date: 19 Jul 2005 06:47:10 -0700 Subject: Python s60 Contact DB Message-ID: <1121780830.418009.176650@o13g2000cwo.googlegroups.com> Hi, i hope the expert can help me! I have a little problem: This piece of code, in python console s60, before compiling will work great: try: ..db = contacts.open() ..names = [] ..numbers = [] The problem is that, if i compile it with py2sis (pyrsc_template.tmp replaced with the original to solve the submenus bug) it doesnt work, when that piece of code is executed, i receive error -50 and nothing happen! hope u can help me! 10ks a lot in advance Regards. From dbickett at gmail.com Sat Jul 9 16:43:13 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sat, 9 Jul 2005 20:43:13 +0000 Subject: Yet Another Python Web Programming Question Message-ID: <1d6cdae305070913436fcef8b4@mail.gmail.com> This post started as an incredibly long winded essay, but halfway through I decided that was a terribly bad idea, so I've trimmed it down dramatically, and put it in the third person (for humor's sake). Once upon a time a boy named Hypothetical programmed in PHP and made many a web application. It would be a long while before he would find Python, and since that time he would have no desire to ever touch PHP again. He would, however, be compelled to write a web application again, but in Python now, of course. He would read the documentation of Nevow, Zope, and Quixote, and would find none of them to his liking because: * They had a learning curve, and he was not at all interested, being eager to fulfill his new idea for the web app. It was his opinion that web programming should feel no different from desktop programming. * They required installation (as opposed to, simply, the placement of modules), whereas the only pythonic freedom he had on his hosting was a folder in his /home/ dir that was in the python system path. * See the first point, over and over again. All he really wanted was something that managed input (i.e. get, post) and output (i.e. headers: "Content-type:"), and he would be satisfied, because he wasn't an extravagant programmer even when he used PHP. Python using CGI, for example, was enough for him until he started getting 500 errors that he wasn't sure how to fix. He is also interested in some opinions on the best/most carefree way of interfacing with MySQL databases. Thanks for your time, -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From cam.ac.uk at mh391.invalid Sun Jul 24 17:16:12 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jul 2005 22:16:12 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3ki8g4Fua4dvU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> <3khg7cFuh446U1@individual.net> <-tWdnRUeMaY5TH7fRVn-sw@powergate.ca> <3ki8g4Fua4dvU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > I'm in no way the last instance on this. > For example, everyone with CVS access is free to change the files ;) I don't have CVS write access :(, so I'll have to keep kibitzing for now. > Honestly, I'm in constant fear that allowing too much and loading too much > features won't increase the acceptance of python-dev What do you mean by this? To me code like this: if _base is str: def __eq__(self, other): return isinstance(other, Path) and _base.__eq__(self, other) [...] else: # Unicode has no rich compare methods def __cmp__(self, other): if isinstance(other, Path): return _base.__cmp__(self, other) return NotImplemented is the feature that you do not need: the feature of not returning True. You don't need this feature, and I consider it to be harmful. It breaks duck-typing unnecessarily, and means that people who want to use some other path library, or just str/unicode as they do today cannot compare those paths against stdlib Paths. We should retain the design principle of the original path.py that Path objects should be drop-in replacements for the str or unicode objects they replace, as much as possible. We cannot predict all the things people are doing with strings today, and attempting to do so can only lead to bugs. In the current implementation, the only cases where a path object cannot be used as a drop-in replacement for a string are (a) some extension modules, and (b) code that tests the object class using type() instead of using isinstance(). I think these are unavoidable but other incompatibilities, like changing the semantics of comparisons or join() are avoidable. I've started a Wiki page for design principles and discussion here: http://wiki.python.org/moin/PathClass -- Michael Hoffman From walterbrunswick at sympatico.ca Wed Jul 13 20:07:11 2005 From: walterbrunswick at sympatico.ca (Walter Brunswick) Date: Wed, 13 Jul 2005 20:07:11 -0400 Subject: Consecutive Character Sequences Message-ID: Is there any way to [efficiently] iterate through a sequence of characters to find N [or more] consecutive equivalent characters? So, for example, the string "taaypiqee88adbbba" would return 1 if the number (of consequtive characters) supplied in the parameters of the function call was 2 or 3, because "a", "e", 8, and "b" is repeated 2 or 3 times. Thanks for any assistance. W. Brunswick. From brian at sweetapp.com Fri Jul 15 07:44:08 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 15 Jul 2005 13:44:08 +0200 Subject: Python Programming Contest In-Reply-To: <17111.39597.277505.234455@montanaro.dyndns.org> References: <42D780EF.6020809@sweetapp.com> <17111.39597.277505.234455@montanaro.dyndns.org> Message-ID: <42D7A188.2010306@sweetapp.com> skip at pobox.com wrote: > Brian> I've decided that it would be be fun to host a weekly Python > Brian> programming contest. The focus will be on algorithms that require > Brian> a bit of thought to design but not much code to implement. > > For some of us that's what we do day-in, day-out at work. It's just not > called a contest. To make it more challenging, we sometimes leave out the > "bit of thought" part. ;-) Hmmm...I find that I am rarely faced with challenging algorithmic problems in my day-to-day work. I continuously face difficult design decisions but that is a difficult sort of beast all together. This contest is for people who like thinking about algorithms. Cheers, Brian From supercomputer at gmail.com Wed Jul 13 09:22:27 2005 From: supercomputer at gmail.com (supercomputer at gmail.com) Date: 13 Jul 2005 06:22:27 -0700 Subject: Parsing Data, Storing into an array, Infinite Backslashes In-Reply-To: References: <1121114842.623294.156790@g44g2000cwa.googlegroups.com> <1121174471.662146.216900@z14g2000cwz.googlegroups.com> Message-ID: <1121260947.601732.209800@g44g2000cwa.googlegroups.com> I ended up using this code to solve my problem. > for a, b, c, d in s: > if not query.has_key((a,b)): query[(a,b)] = [] > query[(a,b)].append("%s=%s" % (c, d)) > for (a,b), v in query.items(): > print a, b, ", ".join(v) I'm relatively new to python/programming in general. I usually write in php and have produced this website and application http://my-pbs.sf.net One of the things that makes php easy to program in is the documentation provided at php.net. It is extremely easy to find the correct functions to use. Are there any sites you could recommend that discusses structures of loops and strings? I have an OReilly book called, "Programming Python" and it focuses to much on showing examples rather than structure and methods. Thanks for the help. From cam.ac.uk at mh391.invalid Thu Jul 21 11:24:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 16:24:45 +0100 Subject: Overriding a built-in exception handler In-Reply-To: <1121956750.750199.289050@g14g2000cwa.googlegroups.com> References: <1121956750.750199.289050@g14g2000cwa.googlegroups.com> Message-ID: callmebill at gmail.com wrote: > I've Read-TFM, but I only see good info on how to create my own class > of exception; I don't see anything on how to override an existing > exception handler. You need to read the tutorial on handling exceptions: http://docs.python.org/tut/node10.html -- Michael Hoffman From heuer at semagia.com Tue Jul 26 08:29:11 2005 From: heuer at semagia.com (Lars Heuer) Date: Tue, 26 Jul 2005 14:29:11 +0200 Subject: psp & php integration In-Reply-To: <20050725185152.1B9D81E4007@bag.python.org> References: <20050725185152.1B9D81E4007@bag.python.org> Message-ID: <393862241.20050726142911@semagia.com> Hi Jon, [ PHP / Python ] > If not, is there any other way in Python (or PHP) to achieve this? I'm not sure if it helps, but here is package that integrates the Python into PHP: http://www.csh.rit.edu/~jon/projects/pip/ Best regards, Lars -- http://semagia.com From desparn at wtf.com Wed Jul 6 12:36:17 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Wed, 06 Jul 2005 12:36:17 -0400 Subject: Where are gui-sig archives? Message-ID: I was trying to view the gui-sig archives, but when I click on the link (from ), I get a "Not Found" error: The requested URL /pipermail/gui-sig/ was not found on this server. Apache/1.3.33 Server at mail.python.org Port 80 Does anyone have an active link to the archives? -- rzed From kay.schluehr at gmx.net Sat Jul 9 02:52:14 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Jul 2005 23:52:14 -0700 Subject: removing list comprehensions in Python 3.0 References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> <1120883125.259644.80490@g47g2000cwa.googlegroups.com> Message-ID: <1120891934.417014.201230@g49g2000cwa.googlegroups.com> Leif K-Brooks schrieb: > Kay Schluehr wrote: > >>>>list.from_str("abc") > > > > list("a", "b", "c" ) > > > I assume we'll also have list.from_list, list.from_tuple, > list.from_genexp, list.from_xrange, etc.? One might unify all those factory functions into a single list.from_iter that dispatches to the right constructor that still lives under the hood. More conceptually: there is some abstract iter base class providing a from_iter method which may be overwritten in concrete subclasses like tuple, str or list. I would further suggest a lazy iterator used to evaluate objects when they get accessed the first time: >>> l = lazy( math.exp(100) , 27 ) >>> l[1] 27 The first element won't ever be evaluated if it does not get accessed explicitely. This is some very special kind of partial evaluation/specialization. Kay From skilpat at gmail.com Fri Jul 15 10:10:10 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 15 Jul 2005 07:10:10 -0700 Subject: System calls not using correct permissions? References: <1121381512.615154.186430@o13g2000cwo.googlegroups.com> Message-ID: <1121436610.483056.27000@g44g2000cwa.googlegroups.com> Oops, yeah I should have mentioned some of that. It's a Linux environment, and it's running Python 2.2. To my knowledge, the batch files my program calls run a few processes on some data and generate a few temporary files. I believe those files are not correctly being generated. There is an error message in one of the scripts that says could not find xxx.xxx, which is a temp file it creates. The batch files are all executed with tcsh. From rganesan at myrealbox.com Sat Jul 2 03:45:21 2005 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Sat, 02 Jul 2005 13:15:21 +0530 Subject: pexpect question.... References: <1120236289.836018.234240@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "draghuram at gmail" == draghuram at gmail com writes: > Hi, > I am using pexpect to spawn an interactive program and wait for > particular string in its output. It works fine but once I get this > required information, I really don't care about the child process > anymore. I would effectively want to "detach" from it. How about just calling close(), i.e. without wait=1? No need to spawn a new thread. Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From cam.ac.uk at mh391.invalid Mon Jul 25 10:44:54 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 25 Jul 2005 15:44:54 +0100 Subject: Path PEP: What should Path(None) do? Message-ID: Currently it returns Path('None'). This means I have to do a check on input before pathifying it to make sure it is not None. Perhaps it should throw ValueError? -- Michael Hoffman From ed at leafe.com Sun Jul 31 00:13:18 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 00:13:18 -0400 Subject: Dabo in 30 seconds? In-Reply-To: <200507302029.34011.jstroud@mbi.ucla.edu> References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> Message-ID: <200507310013.18706.ed@leafe.com> On Saturday 30 July 2005 23:29, James Stroud wrote: > I am going to go ahead and throw out Dabo with all of the others that claim > quick development of an application. You try them and then you get bugs, > bugs, bugs. Or they don't compile without 16000 dependencies. Forget it. My > advice is to choose something, one thing, that is REAL standard, and in the > standard library (e.g. Tkinter). Sorry you feel that way. You'll miss out on really great Python products that aren't in the standard Library, such as Twisted, Zope/Plone, Dabo, and many others. Python is a base. You build from there. -- -- Ed Leafe -- http://leafe.com -- http://dabodev.com From bokr at oz.net Sun Jul 31 23:11:08 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 01 Aug 2005 03:11:08 GMT Subject: Printing Docstrings Without Importing References: <1122746909.441941.226760@o13g2000cwo.googlegroups.com> Message-ID: <42ed90cf.273165611@news.oz.net> On 30 Jul 2005 11:08:29 -0700, "Kamilche" wrote: >I have a large project that is getting complex, and I would like to >print the docstrings without importing the modules. The only Python >utility I could find references is apparently defunct and hasn't been >updated in 4 years. > >I don't care how spartan the output is - it could look exactly like >python's internal docstrings, for all I care. It would be a nice added >bonus if it printed to HTML, but not if it greatly increased the >interface complexity. But I don't want to have to import the module to >run it! I want to just have a function that I pass a list of filenames >to. > >Does anyone know of such a utility? > No, but here's one I just created (not tested very much): ----< docstr2html.py >-------------------------------------------- # docstr2html.py """ Prints html to display docstrings of modules specified on command line, with optional globbing and html page title default override. Usage: [python] docstr2html.py [-title "some title"] (file_pattern)+ Note: If redirecting stdout, some windows versions require [python] to be explicit. """ import glob, time, compiler # copied from cgi module: def escape(s, quote=None): """Replace special characters '&', '<' and '>' by SGML entities.""" s = s.replace("&", "&") # Must be done first! s = s.replace("<", "<") s = s.replace(">", ">") if quote: s = s.replace('"', """) return s def htmlhdr(title=None): if title is None: title = 'doc strings as of %s'%time.ctime() print '%s' %escape(title) def htmltrlr(): print '' def module_file_docstr2html(modulesourcepath): print '
' print '' print ' ' % escape(modulesourcepath) try: print ' ' % escape(compiler.parseFile(modulesourcepath).doc) except Exception, e: print ' ' % escape( 'Exception %s: %s' % (e.__class__.__name__, e)) print '
%s
%s
Error encountered:
%s
' if __name__ == '__main__': import sys, os args = sys.argv[1:] if not args: raise SystemExit(__doc__) if args[0] == '-title': args.pop(0); title = args.pop(0) else: title = None htmlhdr(title) for fspec in args: for path in glob.glob(fspec): module_file_docstr2html(os.path.abspath(path)) htmltrlr() ------------------------------------------------------------------ Running it (first to get the help response, which is just the doc string ;-) [20:04] C:\pywk\ut>python docstr2html.py Prints html to display docstrings of modules specified on command line, with optional globbing and html page title default override. Usage: [python] docstr2html.py [-title "some title"] (file_pattern)+ Note: If redirecting stdout, some windows versions require [python] to be explicit. Then generating the html: [20:04] C:\pywk\ut>python docstr2html.py docstr2html.py doc strings as of Sun Jul 31 20:04:55 2005
C:\pywk\ut\docstr2html.py
Prints html to display docstrings of modules specified on command line,
with optional globbing and html page title default override.

  Usage: [python] docstr2html.py [-title "some title"] (file_pattern)+

Note: If redirecting stdout, some windows versions require [python] to be explicit.
You can use file specs like someplace\*.py (wild cards) and it should do all the files and put it all in tables in the html output. Note that is uses all file specs as patterns, and ignores without complaint any that don't match anything. Regards, Bengt Richter From paul.richards at gmail.com Mon Jul 25 07:51:39 2005 From: paul.richards at gmail.com (Pauldoo) Date: 25 Jul 2005 04:51:39 -0700 Subject: Counting processors Message-ID: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> Hi, Is a way in python to obtain the total number of processors present in the system? os.platform doesn't seem to contain anything useful. From simon.brunning at gmail.com Mon Jul 18 08:05:09 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 18 Jul 2005 13:05:09 +0100 Subject: goto In-Reply-To: <261d32a705071804483ef68021@mail.gmail.com> References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: <8c7f10c605071805052f98dd7a@mail.gmail.com> On 7/18/05, Hayri ERDENER wrote: > hi, > what is the equivalent of C languages' goto statement in python? > best regards http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/832906c6122dc137 Let's not go through *that* again... -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From barrynyc at gmail.com Sun Jul 10 00:55:14 2005 From: barrynyc at gmail.com (Barry) Date: Sun, 10 Jul 2005 00:55:14 -0400 Subject: bsddb environment lock failure Message-ID: <759fdc8f050709215564c7c89b@mail.gmail.com> I have python2.4.1 installed on two machines: -- one is Fedora core 1, where the bsddb module works fine -- one is Redhat ES 3.0, and I installed mysql 4.1 (and mysql-python2.1) after putting the newer python on the machine. python2.2, which came with Redhat ES, works fine, so I suppose I messed up the build. I much appreciate any insight in how to fix this. Barry Here are some details: When trying to open (or create) a db, I get this error File "/opt/Python-2.4.1/Lib/bsddb/__init__.py", line 285, in hashopen e = _openDBEnv() File "/opt/Python-2.4.1/Lib/bsddb/__init__.py", line 339, in _openDBEnv e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | db.DB_INIT_MPOOL) bsddb._db.DBError: (38, 'Function not implemented -- process-private: unable to initialize environment lock: Function not implemented') I tried rebuilding python2.4.1, but 'make test' shows bsddb errors. First, there is: test_bsddb3 skipped -- Use of the `bsddb' resource not enabled test_whichdb shows the environment lock error At the end, it's anydbm, bsddb, shelve, and whichdb failed. I don't which of the differences in setup are important here, but both python.2.4.1 are installed in /opt both have libdb-4.1, although slightly different: The Fedora machine has libdb from db4-4.1.25-14.rpm The Redhat, from db4-4.1.25-8.1 -- this one also has libdb_cxx-3.1.so - libdb_cxx-3.3.so From cyril.bazin at gmail.com Mon Jul 18 10:30:12 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Mon, 18 Jul 2005 16:30:12 +0200 Subject: Dictionary, keys and alias In-Reply-To: References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> <5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: I think "hash" doesn't guarantee the unicity of the result. But, it should avoid the collisions... >>> foo = "foo" >>> hash(foo) -740391237 >>> hash(-740391237) -740391237 I think it's like some kind md5sum... I propose this solution: ----------------------------------------------------------- from UserDict import UserDict class DoubleDict(UserDict): def __init__(self, *args): UserDict.__init__(self, *args) self.values = {} #self.aliases = {} def setAlias(self, key, alias): # Point the alias to the same hash as the real key. if key in self: self.data[alias] = self.data[key] else: self[alias] = key def __getitem__(self, key): return self.values[self.data[key]] def __setitem__(self, key, value): self.data.setdefault(key, key) self.values[self.data[key]] = value print "Result:" d = DoubleDict() d["a"] = 1 d["c"] = 4 d.setAlias("a", "b") print d["a"], d["b"], d["c"] d["a"] = 2 print d["a"], d["b"], d["c"] d["b"] = 3 d.setAlias("b", "c") print d["a"], d["b"], d["c"] del d["c"] d["c"] = 5 print d["a"], d["b"], d["c"] del d["a"] d["a"] = 6 print d["a"], d["b"], d["c"] ------------------------------------------------------- Result: 1 1 4 2 2 4 3 3 3 3 3 5 6 6 5 As you can see the last test (del "a" and reassign "a") fail because it reassign "b". But, if your application doesn't need to midify the aliases, it's ok (I think). Else you can redefine the method __delitem__. Cyril On 7/18/05, Steven D'Aprano wrote: > > On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote: > > > I want to insert a concept of alias in a dict_based class. > > > > The idea is to have a facoltative name in the same dict that correspond > > at the same value. With this alias i can change original value. > > > > example: > > > > mydict['a'] = 1 > > I must define an alias example: myFunctAlias( mydict, 'a', 'b') > > print mydict > > {'a':1, 'b':1} > > mydict['b'] = 2 > > print mydict > > {'a':2, 'b':2} > > > > > > The only idea i have is to implement two dictionary one for convert > > name, alias in two keys with the same value (eg.numeric) in the first > > dict. The second for store only one time the k, v . > > You need some sort of redirection, something like this (untested): > > class Doubledict: > def __init__(self, **kargs): > self.data = {} > self.aliases = {} > for key in kargs: > # Point the key to a hash. > self.aliases[key] = hash(key) > # And point the hash at the value. > self.data[hash(key)] = kargs[key] > > def setalias(self, key, alias): > # Point the alias to the same hash as the real key. > self.aliases[alias] = hash(key) > > def __getitem__(self, key): > return self.data[self.aliases[key]] > > def __setitem__(self, key, value): > self.data[self.aliases[key]] = value > > > The only niggly worry I have is I'm not sure when hash can be used, when > it is unique, or even if is it guaranteed to be unique. > > -- > Steven. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d0153030 at hotmail.com Fri Jul 15 11:36:52 2005 From: d0153030 at hotmail.com (Sandeep Arya) Date: Fri, 15 Jul 2005 21:06:52 +0530 Subject: How to send broadcast message over network and collect all the IP address? Message-ID: Hello to all Well this is my first mail on this list. I am facing a problem associated with collecting IP address on my network. What i thought is to send broadcast packet over the network and then recieving back the reply from the computers and bridges connected to my network and then adding their IP Address in a list. How this can be achieved? Say my computer on which application will run's IP is 192.168.100.254 and subnetmask is 255.255.255.0 How to do this in core Python? Sandeep _________________________________________________________________ 7000 classifieds http://www.sulekha.com/classifieds/cllist.aspx?nma=IN&ref=msn -Chennai, Mumbai, Hyderabad Bangalore. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 10 16:14:40 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 10 Jul 2005 22:14:40 +0200 Subject: Defending Python In-Reply-To: References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> Message-ID: <42d17b1f$0$19917$636a15ce@news.free.fr> Jorey Bump a ?crit : > Bruno Desthuilliers wrote in > news:42d031da$0$30239$636a15ce at news.free.fr: > > >>Grant Edwards a ?crit : >> >>>On 2005-07-09, Brian wrote: >>> >>> >>> >>>>>folks as an easily acquired extra skill. >>>> >>>>I agree 100% with your statement above. Python may not be sufficient >>>>for being the only programming language that one needs to know -- yet, >>>>it does come in VERY handy for projects that need to perform tasks on >>>>non-Microsoft operating systems. :-) >>> >>> >>>It's also darned handy for projects that need to perform tasks >>>on Microsft operating systems but you want to do all the >>>development work under a real OS. >>> >> >>It's also darned handy for projects that need to perform tasks on >>Microsft operating systems. > > > It's also darned handy for projects that need to perform tasks... Or > don't... And for other things besides projects... > > Anyway, it's darned handy! it's. From kelio at yandex.ru Mon Jul 25 12:35:07 2005 From: kelio at yandex.ru (kelio at yandex.ru) Date: 25 Jul 2005 09:35:07 -0700 Subject: urllib2 problem/bug: Request.add_header does() nothing? Message-ID: <1122309307.181534.162940@g44g2000cwa.googlegroups.com> I have a simple cgi-script on a server that prints all key-value pairs from a request. And it really works when i use a browser and type smth like http://server/cgi-bin/test?name=mike&johny=dummy. But when I use the following script, nothing is printed (like i type http://server/cgi-bin/test request in the browser). What is wrong about it? It's hard to believe there's a bug nobody's noticed for such a long time (I've tried Python 2.1.3 and 2.4.1 on Windows, and 2.2.2 on Linux). I've also tried to make a request using urllib (without 2) sending pairs as data in a POST request - and it also worked. Thanks for help! elio. #!/usr/bin/python import urllib2 request = urllib2.Request(r"http://server/cgi-bin/test") request.add_header("product", "SohoCore") request.add_header("version", "1.1") request.add_header("build", "1251") reply = urllib2.urlopen(request).readlines() for i in reply: print i From tjreedy at udel.edu Sun Jul 10 20:11:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jul 2005 20:11:38 -0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com><20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: "Dan Sommers" wrote in message news:m2ll4euv02.fsf at unique.fully.qualified.domain.name.yeah.right... > On Sun, 10 Jul 2005 16:26:24 -0400, > "Terry Reedy" wrote: >> I have a suggestion I don't remember seeing for flagging which vars to >> autoinit without new syntax: use '_' instead of '.'. I have never seen >> local vars with a leading '_'. So, in combination with whatever other >> mechanism (metaclass, __init__ decorator?) > >> def __init__(self, _x, y, _z) : > >> would automatically do self.x = _x, self.z = _z, but not self.y = y. > >> Terry J. Reedy > > That's a pretty big change; now all formal parameters beginning with an > underscore have a brand new meaning. As I said, 'in combination with whatever other mechanism', meaning one that one has to intentionally invoke. So there would be no code breaking: the suggestion is for a convention used with currently available mechanism (assuming that such is possible) that would give the fine-grained control not so easily possible with the current update_dict_with_locals idiom. It would be easier to write the decorator if it were passed the (quoted) names of the parameters to be 'attributed'. But then the user would have to write and keep in synchrony two lists, one a (quoted) subset of the other. So I thought it better to have the decorator writer and decorator function work a little harder to introspect and interpret one list with some items marked somehow in a currently legal but unusual manner. > How about this: > > def __init__(self, self.x, y, self.z): > # self.x, self.z from first and third explicit parameters This is new syntax that is not currently legal. My suggestion was for a solution that avoided that difficulty and that could, I believe, be implemented now, in less time that this thread has been going on, rather than maybe some years from now. Terry J. Reedy From jdennett at acm.org Mon Jul 11 01:33:19 2005 From: jdennett at acm.org (James Dennett) Date: Sun, 10 Jul 2005 22:33:19 -0700 Subject: inheritance In-Reply-To: <1121038079.306961.322370@g44g2000cwa.googlegroups.com> References: <1121031208.829250.82160@g44g2000cwa.googlegroups.com> <1121038079.306961.322370@g44g2000cwa.googlegroups.com> Message-ID: <3wnAe.11070$HV1.1330@fed1read07> J wrote: > just to follow up. I managed to get it working by having a closer look > at the xxmodules. However, the example does the following > > typedef struct > { > PyStructBaseClass mBase; > int mValue; > } PyStructDerivedClass; > > Does anything speak agains doing this ? > > typedef struct : public PyStructBaseClass > { > int mValue; > } PyStructDerivedClass; > > It seems to work for me. The advantage is that access to the members in > that structure is easier. The .mBase is not needed .... Well, it's C++, not C, and in C++ you wouldn't idiomatically use typedef there, but rather write struct pyStructDerivedClass : PyStructBaseClass { int mValue; }; You'll also be relying on assumptions of how single inheritance is implemented by your C++ compiler -- but that said, I've used this assumption in the past and found it to be valid for a wide range of compiler/ABIs. -- James From fdeserres at gmx.net Sun Jul 24 06:25:45 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Sun, 24 Jul 2005 12:25:45 +0200 Subject: tuple to string? In-Reply-To: <42E0EED4.4020001@gmx.net> References: <42E0EED4.4020001@gmx.net> Message-ID: <42E36CA9.5070403@gmx.net> Francois De Serres wrote: >hiho, > >what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to >the string 'spam'? > >TIA, >Francois > > thanks to all! I'll pick ('%c' * len(t)) % t, for it's readability and the fact that join() is on the deprec'd list. Francois From alan.green at gmail.com Mon Jul 11 20:54:04 2005 From: alan.green at gmail.com (Alan Green) Date: 11 Jul 2005 17:54:04 -0700 Subject: Make a .WAV file come out of the left speaker in Windows Message-ID: <1121129643.984392.164270@f14g2000cwb.googlegroups.com> I am writing a Python script that uses the win32all winsound package to play a .wav file. I the sound come out of the left hand speaker, but not the right hand speaker. I've look at some Python sound libraries (PySonic, Audiere, pygame), as well as any number of command line .wav file players. For differing reasons, none of these were suitable. Two possiblities are: (a) Convert the mono .WAV file to a stereo .WAV file that plays out of the left speaker only, or (b) Use the win32 ActiveX to adjust the Windows sound output balance all the way to the left. Can anybody offer suggestions as to where to start with these two? Does anybody have other solutions to suggest? Alan. From brian at sweetapp.com Fri Jul 15 05:25:03 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 15 Jul 2005 11:25:03 +0200 Subject: Python Programming Contest Message-ID: <42D780EF.6020809@sweetapp.com> I've decided that it would be be fun to host a weekly Python programming contest. The focus will be on algorithms that require a bit of thought to design but not much code to implement. I'm doing to judge the solutions based on execution speed. It sucks but that is the easiest important consideration to objectively measure. I'll also indicated which solutions I think are good examples of Python design. Hopefully, people's solutions can provide a resource for people looking for best practice examples and also for people looking for performance ideas. You can find the first problem here: http://www.sweetapp.com/pycontest/contest1 I'm always looking for feedback, so let me know what you think or if you have any ideas for future problems. Cheers, Brian From cf_1957 at hotmail.com Wed Jul 20 08:22:56 2005 From: cf_1957 at hotmail.com (chris) Date: Wed, 20 Jul 2005 12:22:56 GMT Subject: OO design References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: Extremely grateful for all the responses. I've pasted them all into a document and can now read all your valuable ideas together. Even at a first reading they have already helped clarify my thinking. Also minor clarifications:: > I'm hoping some of you python > lamas out there might be able to share some of your wisdom on the subject. lama = guru = teacher (not a furry animal, although my dog has certainly taught me a few tricks ... like when to take her for a walk, when to play ball, and when its time for a tummy rub.) > bwaha be well and happy always From noreply at gcgroup.net Tue Jul 19 13:52:19 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 19 Jul 2005 17:52:19 GMT Subject: main window in tkinter app In-Reply-To: References: Message-ID: O.K. I tried from scratch, and the following snippet produces an infinite loop saying: File "C:\Python24\lib\lib-tk\Tkinter.py", line 1647, in __getattr__ return getattr(self.tk, attr) If I comment out the __init__ method, I get the titled window, and print out self.var ('1') import os from Tkinter import * class MyApp(Tk): var=1 def __init__(self): pass def getval(self): return self.var app = MyApp() app.title("An App") print app.getval() app.mainloop() Eric Brunel wrote: > On Mon, 18 Jul 2005 16:57:51 GMT, William Gill wrote: > >> A short while ago someone posted that(unlike the examples) you should >> use Tk as the base for your main window in tkinter apps, not Frame. >> Thus : >> >> class MyMain(Frame): >> def __init__(self, master): >> self.root = master >> self.master=master >> self.createWidgets() >> def createWidgets(): >> ... >> root = Tk() >> app = MyMain(root) >> app.master.title("Object Editor") >> root.mainloop() >> >> would become: >> >> class MyMain(Tk): >> ... >> ... >> app = MyMain() >> app.title("My App") >> app.mainloop() >> >> When I try converting to this approach I run into a problem with the >> __init__() method. It appears to go into an infinite loop in >> tkinter.__getattr__(). > > [...] > > I never ran into this problem. Can you please post a short script > showing this behavior? Without knowing what you exactly do in your > __init__ and createWidgets method, it's quite hard to figure out what > happens... From siona at chiark.greenend.org.uk Thu Jul 28 10:05:22 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jul 2005 15:05:22 +0100 (BST) Subject: multiple inheritance super() References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: >Michele Simionato wrote: >> was I >> going to design a new language >> I would implement it *without* multiple inheritance). That way lies Java. The number of times I've wished an interface were actually a mixin.... *shudder* >Multiple inheritance can be very useful if not used in an unresponsible way. Exactly. I think the correct approach is to regard multiple inheritence as a very advanced OO topic, leave it out of tutorials as much as possible, and when finally introduced reinforce the idea that it should be used only with caution. Speaking as someone who has used it to commit monstrosities in C++ which I have grown to regret. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From cam.ac.uk at mh391.invalid Sun Jul 10 06:14:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 10 Jul 2005 11:14:37 +0100 Subject: Python Forum In-Reply-To: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> References: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> Message-ID: Throne Software wrote: > Throne Software has opened up a Python Forum at: > > http://www.thronesoftware.com/forum/ > > Join us! Why shouldn't I just stay here? -- Michael Hoffman From tjreedy at udel.edu Mon Jul 4 15:18:54 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jul 2005 15:18:54 -0400 Subject: Considering moving from Delphi to Python [Some questions] References: <5f4d3cb505070410192ba525d7@mail.gmail.com> Message-ID: "Dark Cowherd" wrote in message news:5f4d3cb505070410192ba525d7 at mail.gmail.com... > We program in Delphi in our shop and are generally very happy with it. > We are now looking at cross-platform options especially for middle > tier and web server. > > I have been doing a lot of reading and testing of Python, I am falling > in love with the language :-) If you have not, Google 'Python Delphi'. The second entry is Python (2.1+) for Delphi (6). For what it is worth, the fifth is a Wiki entry : "Python was the oracular serpent of Delphi. It was the offspring of Gaia and the mud that was left over after the flood of Deucalion" Terry J. Reedy From jforcier at strozllc.com Fri Jul 22 20:57:08 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: Fri, 22 Jul 2005 20:57:08 -0400 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: References: Message-ID: <8B4460A3-9B61-4CD4-88FE-7A6AAF27DA3A@strozllc.com> On Jul 22, 2005, at 7:46 PM, Michael Hoffman wrote: > I'm too tired and/or lazy to check, but I believe str() is calling > MyClass.__str__(testObject) as it is supposed to rather than > testObject.__str__() as you say it is supposed to. ;-) > > Someone else or Google can probably enlighten you on the reason for > this > better than I. I think this is something that is not explained very > well > in the docs, which do say that a class implements special method > names, > but doesn't make it very clear that an object can't always override > them. > > If you redirect to a second method you can overwrite on the > instance, I > think you will get the results you want. > -- > Michael Hoffman > -- > http://mail.python.org/mailman/listinfo/python-list > So in other words, __str__() and its ilk are class methods instead of instance methods? The documentation appears to contradict this: (http://python.org/doc/2.4/ref/specialnames.html) "For instance, if a class defines a method named __getitem__(), and x is an instance of this class, then x[i] is equivalent to x.__getitem__ (i)." However, you appear to be correct, and the docs appear to be confused: class MyClass(object): def edit(self): return "I'm in edit mode" def setToEdit(self): MyClass.__str__ = self.edit In [3]: test = MyClass() In [4]: str(test) Out[4]: '<__main__.MyClass object at 0x2d21d0>' In [5]: test.setToEdit() In [6]: str(test) Out[6]: "I'm in edit mode" Of course, this doesn't quite do what I had in mind, and in fact you could say it's kinda sloppy, binding an ostensibly static class method to an instance method: In [7]: repr(MyClass.__str__) Out[7]: '>' Either way, guess I will have to take another route. Your suggestion is what I'd had in mind, and does the job pretty well. I'm still attempting to figure out the best approach to my overall problem, however, so who knows where I will end up =) Thanks for the response! If you or anyone else can shed some insight on *why* this is the way it is (and why/if the docs are in fact incorrect) I'd appreciate further replies. More knowledge == better. Regards, Jeff -- Jeffrey E. Forcier Junior Developer, Research and Development Stroz Friedberg, LLC 15 Maiden Lane, 12th Floor New York, NY 10038 [main]212-981-6540 [direct]212-981-6546 http://www.strozllc.com This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by any error in transmission. If you have received this message in error, please immediately notify the sender by e-mail or by telephone at 212.981.6540, delete the message and all copies from your system and destroy any hard copies. You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient. From twic at urchin.earth.li Sat Jul 2 10:15:25 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 2 Jul 2005 15:15:25 +0100 Subject: map vs. list-comprehension In-Reply-To: References: Message-ID: On Fri, 1 Jul 2005, Sion Arrowsmith wrote: > Tom Anderson wrote: >> On Thu, 30 Jun 2005, Roy Smith wrote: >> >>> Even some of the relatively recent library enhancements have been kind >>> of complicated. The logging module, for example, seems way over the >>> top. >> >> Exactly the same thing happened with Java. > > I was under the impression that Python's logging module (like unittest) > was based on a common Java one, and it's complexity could be blamed on > that. That would explain it. Who was responsible for this crime? I say we shoot them and burn the bodies. >> if you look at the libraries that were in 1.1, they're very clean and >> simple (perhaps with the exception of AWT). 1.2 added a load of stuff >> that was much less well-designed (with the notable exception of the >> collections stuff, which is beautiful) > > There are very many adjectives I could (and have) used to describe the > Collection framework. "Beautiful" is not among them. I think the closest > I could manage is "baroque". Oh, i don't think it's really that bad. For java. tom -- REMOVE AND DESTROY From Scott.Daniels at Acm.Org Tue Jul 26 19:59:59 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 26 Jul 2005 16:59:59 -0700 Subject: multiple inheritance super() In-Reply-To: <42e6aac4$0$14586$626a14ce@news.free.fr> References: <42e6aac4$0$14586$626a14ce@news.free.fr> Message-ID: <42e6c629@nntp0.pdx.net> rafi wrote: > A related question is about the order of the __init__ calls. Considering > the following sample: > > #--8<--- > class A (object): > def __init__ (self): > super (A, self) .__init__ () > print 'i am an A' > class B (object): > def __init__ (self): > super (B, self) .__init__ () > print 'i am a B' > class C (A, B): > def __init__ (self): > super (C, self) .__init__ () > print 'i am a C' > c = C () > > aerts $ python2.4 inheritance.py > i am a B > i am an A > i am a C > > I do understand the lookup for foo: foo is provided by both classes A > and B and I do not state which one I want to use, so it takes the first > one in the list of inherited classes (order of the declaration). However > I cannot find an explanation (I may have googled the wrong keywords) for > the order of the __init__ calls from C. I was expecting (following the > same order as the method lookup): This should make it clear: class A (object): def __init__ (self): print '', super (A, self) .__init__ () print '' class B (object): def __init__ (self): print '', super (B, self) .__init__ () print '' class C (A, B): def __init__ (self): print '', super (C, self) .__init__ () print '' C() --Scott David Daniels Scott.Daniels at Acm.Org From simon.brunning at gmail.com Thu Jul 14 06:32:56 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 14 Jul 2005 11:32:56 +0100 Subject: Python Newbie In-Reply-To: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> References: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> Message-ID: <8c7f10c605071403326406f4e8@mail.gmail.com> On 14 Jul 2005 03:24:29 -0700, linuxfreak wrote: > Hi all, > I came accross this article by Eric Raymond in which he has sung > peans about the python language. Well that has whetted my appetite... > So I decided to get down and dirty. But alas I got down but not dirty.. > i cant seem to find a good tutorial to help me get started. Whats the > next best thing to do? Ask the pros and where do you find them...in a > mailing list of course. So heres me asking if anyone has any pointers > to some good basic python tutorial. Something that teaches one to get > going. http://wiki.python.org/moin/BeginnersGuide -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From kay.schluehr at gmx.net Mon Jul 11 01:28:28 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Jul 2005 22:28:28 -0700 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> Message-ID: <1121059708.002859.67570@g44g2000cwa.googlegroups.com> Dan Sommers schrieb: > How about this: > > def __init__(self, self.x, y, self.z): > # self.x, self.z from first and third explicit parameters > do_something_with_y() Can you tell me in which way it is anyhow better than the original proposal def __init__(self, .x, y, .z): # self.x, self.z from first and third explicit parameters do_something_with_y() besides that it is more verbose? Kay From seungwjun at gmail.com Sun Jul 17 22:59:34 2005 From: seungwjun at gmail.com (sj) Date: 17 Jul 2005 19:59:34 -0700 Subject: list implementation Message-ID: <1121655574.593794.61940@f14g2000cwb.googlegroups.com> I believe the type "list" is implemented as an array of pointers. Thus, random access is an O(1) operation while insertion/deletion is an O(n) operation. That said, I have the following questions: 1. Am I correct in saying the above? 2. Implementing list as an array is part of language specification or implementation-dependent? 3. What if I actually need a doubly-linked list for constant-time insertion/deletion? Is there a built-in type or a standard class? Thanks. From ed at leafe.com Sun Jul 31 21:22:30 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 21:22:30 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <7xek9e5ywq.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <7xek9e5ywq.fsf@ruckus.brouhaha.com> Message-ID: <200507312122.30363.ed@leafe.com> On Sunday 31 July 2005 19:38, Paul Rubin wrote: > I can put up a Tk gui in about 5 lines of code from a stock Python > distro without having to install anything additional. ?How do I do > that with wxPython? import dabo app = dabo.dApp() dApp.start() Sorry, I couldn't do it in 5. ;-) Oh, and that includes a full menu, too. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From qwweeeit at yahoo.it Wed Jul 13 09:19:54 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 13 Jul 2005 06:19:54 -0700 Subject: Splitting on a word Message-ID: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> Hi all, I am writing a script to visualize (and print) the web references hidden in the html files as: ' underlined reference' Optimizing my code, I found that an essential step is: splitting on a word (in this case 'href'). I am asking if there is some alternative (more pythonic...): # SplitMultichar.py import re # string s simulating an html file s='ffy: ytrty python fyt wx dtrtf' p=re.compile(r'\bhref\b',re.I) lHref=p.findall(s) # lHref=['href','HREF'] # for normal html files the lHref list has more elements # (more web references) c='~' # char to be used as delimiter # c=chr(127) # char to be used as delimiter for i in lHref: s=s.replace(i,c) # s ='ffy: ytrty python fyt wx dtrtf' list=s.split(c) # list=['ffy: ytrty python fyt wx dtrtf'] #=----------------------------------------------------- If you save the original s string to xxx.html, any browser can visualize it. To be sure as delimiter I choose chr(127) which surely is not present in the html file. Bye. From newsgroups at jhrothjr.com Fri Jul 1 19:40:39 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 1 Jul 2005 17:40:39 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <11cbl3rb2alb32@news.supernews.com> "Tom Anderson" wrote in message news:Pine.LNX.4.62.0507011430540.12731 at urchin.earth.li... > Comrades, > > During our current discussion of the fate of functional constructs in > python, someone brought up Guido's bull on the matter: > > http://www.artima.com/weblogs/viewpost.jsp?thread=98196 > > He says he's going to dispose of map, filter, reduce and lambda. He's > going to give us product, any and all, though, which is nice of him. > > What really struck me, though, is the last line of the abstract: > > "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme > folks. :-)" > > I disagree strongly with Guido's proposals, and i am not an > ex-Lisp, -Scheme or -any-other-functional-language programmer; my only > other real language is Java. I wonder if i'm an outlier. > > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? As far as biases is concerned: my background is assembler. I've never learned Lisp (although I did learn Forth at one time.) I think I could note that originally there were five of the things, including apply, which was cleanly replaced by the * and ** notation in function definitions and calls. Map, filter and reduce are three things one can do with lists (or in fact more general sequences). List comprehensions cleanly replace filter. They don't quite replace map, and they definitely don't replace reduce. Claiming that sum etc. do the same job is the whimper of someone who doesn't want to openly disagree with Guido. Lambda is a horse of a quite different color. There are times when an inline definition is the best thing one can have for notational expressiveness. While lambda has a lot of problems, Guido seems to be resisting replacing it with something that can actually do the job. Having to define an external function or class doesn't always improve expressiveness. Sometimes it reduces it. To quote Sean O'Lochlain: "Sometimes the best symbol for a sharp knife is a sharp knife." [1] John Roth [1] In one of Randall Garrett's Lord Darcy stories. > > tom > > -- > Batman always wins From jules at REMOVETHIS.op59.net Tue Jul 12 07:02:18 2005 From: jules at REMOVETHIS.op59.net (Julian Smith) Date: Tue, 12 Jul 2005 12:02:18 +0100 Subject: Creating anonymous functions using eval Message-ID: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> I've been playing with a function that creates an anonymous function by compiling a string parameter, and it seems to work pretty well: def fn( text): exec 'def foo' + text.strip() return foo This can be used like: def foo( x): print x( 2, 5) foo( fn( ''' ( x, y): print 'x^2 + y^2 = ', x*x + y*y return y ''')) - which outputs: x^2 + y^2 = 29 5 You can also mimic conventional function definitions: f = fn( ''' ( x, y): print 'x, y=', x, y print 1.0*x/y return y ''') print 'calling f' f( 5, 6) This outputs: calling f x, y= 5 6 0.833333333333 You do things like allow/require an initial `def' for clarity, check that all the lines of text are indented so that nothing is executed when the anonymous function is created, etc etc. Obvious disadvantages are that the function text may have to escape quotes, and will not be showed with syntax colouring in editors. Apart from that, it seems quite a useful way of overcoming the limitations of python's lambda. But... I haven't seen this technique mentioned anywhere, so does anyone know of any problems that I should be wary of? - Julian -- http://www.op59.net/ From rrr at ronadam.com Sat Jul 9 02:46:57 2005 From: rrr at ronadam.com (Ron Adam) Date: Sat, 09 Jul 2005 06:46:57 GMT Subject: removing list comprehensions in Python 3.0 In-Reply-To: References: <1120862284.807190.249820@g44g2000cwa.googlegroups.com> <1120883125.259644.80490@g47g2000cwa.googlegroups.com> Message-ID: Leif K-Brooks wrote: > Kay Schluehr wrote: > >>>>>list.from_str("abc") >> >>list("a", "b", "c" ) > > > > I assume we'll also have list.from_list, list.from_tuple, > list.from_genexp, list.from_xrange, etc.? List from list isn't needed, nor list from tuple. That's what the * is for. And for that matter neither is the str.splitchar() either. class mylist(list): def __init__(self,*args): self[:]=args[:] mylist(*[1,2,3]) -> [1,2,3] mylist(*(1,2,3)) -> [1,2,3] mylist(*"abc") -> ['a','b','c'] mylist(1,2,3) -> [1,2,3] mylist([1],[2]) -> [[1],[2]] mylist('hello','world') -> ['hello','world'] Works for me. ;-) I always thought list([1,2,3]) -> [1,2,3] was kind of silly. Cheers, Ron From danb_83 at yahoo.com Wed Jul 6 11:36:49 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 6 Jul 2005 08:36:49 -0700 Subject: Create datetime instance using a tuple. References: <2fdabf19.0507060101.6184974e@posting.google.com> Message-ID: <1120664209.370370.312120@g14g2000cwa.googlegroups.com> Qiangning Hong wrote: > On 6 Jul 2005 02:01:55 -0700, Negroup wrote: > > Hi, all. > > I would like to know if it is possible to create a datetime instance > > using a tuple instead of single values. > > > > I mean: > > >>> from datetime import datetime > > >>> t = (1, 2, 3) > > >>> dt = datetime(t) > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: function takes at least 3 arguments (1 given) > > > > (class datetime(year, month, day[, hour[, minute[, second[, > > microsecond[, tzinfo]]]]]) > > Use: > dt = datetime(*t) It's better to write: dt = datetime(*t[:6]) This gives you compatibility with the (year, month, day, hour, minute, second, weekday, julian_day, dst) tuples returned by time.gmtime, time.localtime, and time.strptime. From gsakkis at rutgers.edu Tue Jul 19 10:02:18 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Tue, 19 Jul 2005 10:02:18 -0400 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: <1121781747.6b5089eb6576a56f3b0851ea53fe69e0@teranews> "rbt" wrote: > On Mon, 2005-07-18 at 12:27 -0600, Steven Bethard wrote: > > Hayri ERDENER wrote: > > > what is the equivalent of C languages' goto statement in python? > > > > Download the goto module: > > http://www.entrian.com/goto/ > > And you can use goto to your heart's content. And to the horror of all > > your friends/coworkers. ;) > > > > STeVe > > Shouldn't that be "to the horror of all your goto-snob friends." > > IMO, most of the people who deride goto do so because they heard or read > where someone else did. > > Many of the world's most profitable software companies (MS for example) > have thousands of goto statements in their code... oh the horror of it > all. Why aren't these enlightened-by-the-gods know-it-alls as profitable > as these obviously ignorant companies? It should not really come as a shock that the same fellow who came up with a brilliant efficient way to generate all permutations (http://tinyurl.com/dnazs) is also in favor of goto. Coming next from rbt: "Pointer arithmetic in python ?". George From chinook.nr at tds.net Mon Jul 4 23:49:31 2005 From: chinook.nr at tds.net (Chinook) Date: Mon, 04 Jul 2005 23:49:31 -0400 Subject: HTML Conventions In-Reply-To: <200507041257.46687.rutski89@gmail.com> References: <200507041257.46687.rutski89@gmail.com> Message-ID: Patrick Rutkowski wrote: > I couldn't help but make an even better list in reference to this thread: > I'll go you one better :<)) I found the source of what I pulled that table from: http://jaynes.colorado.edu/PythonGuidelines.html Lee C From rrr at ronadam.com Wed Jul 6 15:20:15 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 19:20:15 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Dan Sommers wrote: >> AttributeError: 'NoneType' object has no attribute 'read' > > > This is the one of which I was thinking. So you see this error at the > end of a (long) traceback, and try to figure out where along the (long) > line of function calls I typed the wrong name. Currently, the very end > of the traceback points you right at the bad code and says "NameError: > name 'filehandle' is not defined," which tells me (very nearly) exactly > what I did wrong. The actual error could be improved a bit to refer the the name of the and line the error is in. Which would help some. AttributeError: 'NoneType' object "file_handle" has no attribute 'read' > I guess it depends on how long your traceback is and how big those > functions are. Also, from the Zen: > > Explicit is better than implicit. > > although from previous threads, we know that every pythonista has his or > her own definitions of "explicit" and "implicit." True, but this isn't any different than any other 'Type' error, or value error. And considerably easier to find than one off errors. There would be more restrictions on None than there are now so it wouldn't be as bad as it seems. For example passing a None in a function would give an error as the name would be deleted before the function actually gets it. So doing this would give an error for functions that require an argument. def foo(x): return x a = None b = foo(a) # error because a dissapears before foo gets it. >>TypeError: foo() takes exactly 1 argument(0 given) So they wouldn't propagate like you would expect. Hmmm.... interesting that would mean... lets see. 1. var = None # removes ref var, this is ok 2. None = var # give an error of course 3. var = undefined_var # same as "var = None", that's a problem! Ok... this must give an error because it would delete var silently! Definitely not good. So going on, on that basis. 4. undefined == None # Special case, evaluates to True. 5. def foo():return None # same as return without args 6. x = foo() # Would give an error if foo returns None This might be an improvement over current behavior. Breaks a lot of current code though. 7. if undefined: # error 8. if undefined==None # Special case -> True Good for checking if vars exist. 9. if undefined==False # Error, None!=False (or True) 9. while undefined: # error 10 while undefined==None: Possible loop till defined behavior. Ok... and undefined var returning None is a bad idea, but using None to del names could still work. And (undefined==None) could be a special case for checking if a variable is defined. Otherwise using an undefined name should give an error as it currently does. Cheers, Ron > Regards, > Dan From zen19725 at zen.co.uk Sun Jul 31 05:14:52 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 10:14:52 +0100 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <7x3bpve8w5.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 31 Jul 2005 02:23:39 -0700, Robert Kern wrote: >phil hunt wrote: > >> OK, hows this for an idea: >> >> 1. create a new API, loosely based on the Tkinter API, but more >> Pythonic >> >> 2. implement Tk using this API (probably won't be difficult because >> we can use Tkinter as a base) >> >> 3. Implement bindings to Gtk and Qt/KDE using this API. > >Like PyGUI, more or less? > >http://www.cosc.canterbury.ac.nz/~greg/python_gui/ Not really, PyGUI attempts to be a thing in itself; what I had in mind was more of a slight reworking of Tkinter to make it more Pythonic (and at the same time give it better documentation which odesn't depend on refering to the Tcl/Tk documentation). -- Email: zen19725 at zen dot co dot uk From steven.bethard at gmail.com Wed Jul 27 20:04:04 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 27 Jul 2005 18:04:04 -0600 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: David Isaac wrote: > I ran into a need for something like map(None,x,y) > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > info from x. I almost never run into this situation, so I'd be interested to know why you need this. Here's one possible solution: py> import itertools as it py> def zipfill(*lists): ... max_len = max(len(lst) for lst in lists) ... return zip(*[it.chain(lst, it.repeat(None, max_len - len(lst))) ... for lst in lists]) ... py> zipfill(range(4), range(5), range(3)) [(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, None), (None, 4, None)] If you prefer, you can replace the call to zip with it.zip and get an iterator back instead of a list. STeVe From flamesrock at gmail.com Wed Jul 6 06:32:17 2005 From: flamesrock at gmail.com (flamesrock) Date: 6 Jul 2005 03:32:17 -0700 Subject: Help with wx.PaintDC Message-ID: <1120645937.713829.30550@g49g2000cwa.googlegroups.com> wxGlade has made this tooooooo easy for me so far. But right now I'm very confused about something: self.bmp = wx.Bitmap('sample.bmp') dc = wx.PaintDC(self.notebook_region_overview) dc.DrawBitmap(self.bmp,0,0,False) self.notebook_region_overview is basically a wx.Panel, located on the right side of a splitterWindow. Anyways, this code *should* draw sample.bmp inside the right wx.Panel (self.notebook_region_overview), but doesn't. I would be grateful if anyone could correct me. There isn't much information about drawing images to wx.Panels online. -thanks From flamesrock at gmail.com Sat Jul 2 16:31:04 2005 From: flamesrock at gmail.com (flamesrock) Date: 2 Jul 2005 13:31:04 -0700 Subject: wxPython: Terminal Output -> Scrollable Panel? In-Reply-To: References: <1120289025.359671.148450@g14g2000cwa.googlegroups.com> <-uOdneuY58vY4VvfRVn-sA@powergate.ca> <1120333932.108782.45740@g49g2000cwa.googlegroups.com> Message-ID: <1120336264.396261.108040@g44g2000cwa.googlegroups.com> Exactly what I'm looking for! Thanks From tdwdotnet at gmail.com Fri Jul 15 09:51:23 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Fri, 15 Jul 2005 14:51:23 +0100 Subject: open a mail and... In-Reply-To: <000c01c58942$5e6632d0$1603a8c0@avc> References: <000c01c58942$5e6632d0$1603a8c0@avc> Message-ID: <9afea2ac0507150651c480d47@mail.gmail.com> On 7/15/05, Alberto Vera wrote: > > Hello > > Is it possible to open a mail and download its files attached in a hard-disk > using a python script? > > Regards > -- > http://mail.python.org/mailman/listinfo/python-list > yes, use the email module. >>> msg = email.message_from_file(an_opened_file) or >>> msg = email.message_from_string(a_mail_string) then use: For part in msg.walk(): do_something(part) The email docs will help you with converting and extracting the specific attachements you are expecting HTH :) From godwinburby at rediffmail.com Thu Jul 7 00:54:37 2005 From: godwinburby at rediffmail.com (godwin) Date: 6 Jul 2005 21:54:37 -0700 Subject: I am a Java Programmer References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> Message-ID: <1120712077.420597.102880@f14g2000cwb.googlegroups.com> Buy the book "Practical Python" by Magnus Lie Hetland. It contains 10 practical projects to let u get started on you own "Pythoneering"( as Magnus calls it). Move on buddy. From gsakkis at rutgers.edu Fri Jul 22 10:04:13 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 22 Jul 2005 10:04:13 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <1122041065.7dcb5f778f485ccde56e67f27ba83c35@teranews> "Duncan Booth" wrote: > Personally I think the concept of a specific path type is a good one, but > subclassing string just cries out to me as the wrong thing to do. In other > words, to me a path represents something in a filesystem, the fact that it > has one, or indeed several string representations does not mean that the > path itself is simply a more specific type of string. > > You should need an explicit call to convert a path to a string and that > forces you when passing the path to something that requires a string to > think whether you wanted the string relative, absolute, UNC, uri etc. First off, I find this is a relatively small detail overall, that is, regardless of whether path subclasses string or not, its addition in the standard library will be a step forward. Havind said that, I think the choice between subclassing or not is going to be a practicality-vs-purity decision. You're right, conceptually a path HAS_A string description, not IS_A string, so from a pure OO point of view, it should not inherit string. OTOH, people in favor of the subclassing point out the convenience for many (or most) common cases. It's a tradeoff, so arguments for both cases should be discussed. George From philippe at philippecmartin.com Wed Jul 6 22:29:35 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 07 Jul 2005 02:29:35 GMT Subject: I am a Java Programmer References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> Message-ID: I see you got many good/funny answers already. Test Python for two WE and you'll be able to help yourself very well ... I've been through an equivalent process. Regards, Philippe mjmrifai at gmail.com wrote: > I am a java programmer and I want to learn Python Please help me. From mwm at mired.org Wed Jul 27 23:38:54 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 27 Jul 2005 23:38:54 -0400 Subject: searching string url References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> <1122500867.516196.146990@g14g2000cwa.googlegroups.com> Message-ID: <86u0iflhv5.fsf@bhuda.mired.org> googlinggoogler at hotmail.com writes: > Anyway to the orginally replier - I wish it was homework ;-), that > would mean I wouldnt be trying to find myself a job as a recent > graduate... I decided to crawl something similar to the yellow pages > (do you have them in the US?) for my select area and then find all > pages corresponding to my ideal field of work, and grab their details > into a txt file. I'm actually working on a general framework for doing this kind of thing. It's designed specifically for walking through a collection of pages from a web-based search engine, applying extra criteria to the results, and then running a bit of code on any that pass that check. It works for one site, but my attempt to try it on a second site turned up a fundamental flaw. My first site used full URLs for everything, so I happily passed soup between various methods. The second site used relative urls for everything, and it all broke. > Trouble is I keep thinking of cool new bits to add, python truely is a > beautifal language. Ideally would like to somehow write all the > information into a word mail merge - but I think that requires more > research! Given a working scrape, the only extra work is how to get it into a mail merge. That depends on your platform and the software you're using to send the mail. Shouldn't be all that hard. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ed at leafe.com Sat Jul 30 14:04:14 2005 From: ed at leafe.com (Ed Leafe) Date: Sat, 30 Jul 2005 14:04:14 -0400 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <200507301404.14150.ed@leafe.com> On Saturday 30 July 2005 13:41, Peter Hansen wrote: > The last time I checked (as I recall), at least Wax and possibly Dabo > both either lagged well behind recent wxPython developments of provide > relatively limited support, leaving out a sizable and (to me) important > number of features from what they wrapped. > > Is this a remotely accurate and current picture of things? ?Or is it > more fair to say that by adopting Dabo (or Wax?) one really loses > nothing in terms of flexibility, and gains only improved write- and > readability? I can't speak for Wax, but you don't lose anything from wxPython when you work with Dabo. At the very least, if there is something that wxPython has added that has not been integrated into Dabo yet, you can still code in native wxPython. I've taken that approach in my current work on the Visual Designer: some of the things that I needed to do couldn't be done in Dabo. But in the spirit of 'eating your own dogfood', I then go back into the UI framework code and add those things, so that the Designer is ultimately 100% Dabo code. There are also several classes in wxPython that Dabo has not wrapped, primarily the lower-level drawing classes and some of the newer graphics classes, mainly because they weren't needed for a database application framework. However, if there's a need, we'll be glad to add it. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From hongqn at gmail.com Wed Jul 6 05:31:08 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Wed, 6 Jul 2005 17:31:08 +0800 Subject: Create datetime instance using a tuple. In-Reply-To: <2fdabf19.0507060101.6184974e@posting.google.com> References: <2fdabf19.0507060101.6184974e@posting.google.com> Message-ID: On 6 Jul 2005 02:01:55 -0700, Negroup wrote: > Hi, all. > I would like to know if it is possible to create a datetime instance > using a tuple instead of single values. > > I mean: > >>> from datetime import datetime > >>> t = (1, 2, 3) > >>> dt = datetime(t) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: function takes at least 3 arguments (1 given) > > (class datetime(year, month, day[, hour[, minute[, second[, > microsecond[, tzinfo]]]]]) Use: dt = datetime(*t) -- Qiangning Hong Get Firefox! From peter at engcorp.com Sat Jul 30 08:13:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 08:13:26 -0400 Subject: Comparison of functions In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > Playing around with comparisons of functions (don't ask), I discovered an > interesting bit of unintuitive behaviour: > >>>>(lambda y: y) < (lambda y: y) > False > > Do the comparison again and things become even more bizarre: > >>>>(lambda y: y) < (lambda y: y) > True > >>>>(lambda y: y) < (lambda y: y) > False > > This behaviour should be easy for experienced Pythonisters to answer, but > will probably confuse beginners greatly. Beginners should not be comparing lambdas. Neither should you. ;-) -Peter From davecook at nowhere.net Fri Jul 22 10:03:16 2005 From: davecook at nowhere.net (Dave Cook) Date: Fri, 22 Jul 2005 14:03:16 GMT Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: On 2005-07-22, TPJ wrote: > 7. "(...) The pygtk (and gtk port in general) does not yet support > threading on windows. (...) GTK 2.0 is supposed to fix it but support > isn't available *yet*. (...)" May 17 2002 Pretty sure this hasn't been the case for a long time. The current stable version of gtk is 2.6. > sure if PyGTK is stable on Windows... For now I know that wxPython runs > well on Windows. I've used pygtk with success on windows. I suggest installing the gladewin package and pygtk, then perhaps hacking some of the demos in the pygtk distro. http://gladewin32.sourceforge.net/index.php http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ One advocacy point: There are complete reference docs, an extensive tutorial, and a constantly evolving FAQ for pygtk. One point against: requires X11 on a Mac; definitely not native there, though that's where I do a lot of my pygtk development. > I be able to make an executable (using Py2Exe) of an application that > uses PyGTK? Yes. http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq21.005.htp Dave Cook From steve at REMOVETHIScyber.com.au Fri Jul 29 06:54:42 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 29 Jul 2005 20:54:42 +1000 Subject: functions without parentheses References: <42e9c49b.24281464@news.oz.net> Message-ID: On Fri, 29 Jul 2005 06:37:52 +0000, Bengt Richter wrote: > I suggested in a previous thread that one could support such a syntax by > supporting an invisible binary operator between two expressions, so that > examine "string" translates to examine.__invisbinop__("string") if > examine as an expression evaluates to an object that has a __invisbinop__ method. Why would you want to? -- Steven. From sybrenUSE at YOURthirdtower.com.imagination Mon Jul 4 14:50:52 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 4 Jul 2005 20:50:52 +0200 Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> <1120496338.571135.129060@g49g2000cwa.googlegroups.com> Message-ID: Derek van Vliet enlightened us with: > Up to now, I've had all my python scripts defined in XML elements, > which were compiled when my program started up using > Py_CompileString. This has worked great, but I'm finding that most > of the time my app uses to start up is spent in that > Py_CompileString It al makes sense now! Thanks for the explanation. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From peter at engcorp.com Thu Jul 14 19:52:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 19:52:56 -0400 Subject: all possible combinations In-Reply-To: <42d6ed37.197174802@news.oz.net> References: <42d6ed37.197174802@news.oz.net> Message-ID: Bengt Richter wrote: > On Thu, 14 Jul 2005 17:10:37 -0400, William Park wrote: > It's a one liner in Python too ;-) > > >>> print ' '.join([x+y+z+q for s in ['abc'] for x in s for y in s for z in s for q in s]) Or for the cost of an import and a lambda, you can keep it looking real obscure and generalize it to any size of sequence ('abcdef' or whatever) and a result length of up to 52 elements: >>> from string import letters as L >>> cartesian = lambda seq, num: eval("list(%s for __ in [seq] %s)" % ('+'.join(L[:num]), 'for %s in __ ' * num % tuple(L[:num]))) # (there are spaces at any line breaks above) >>> cartesian('abcde', 6) ['aaaaaa', 'aaaaab', 'aaaaac', 'aaaaad', 'aaaaae', 'aaaaba', ... 'eeeeec', 'eeeeed', 'eeeeee'] >>> len(_) 15625 -Peter From nyamatongwe+thunder at gmail.com Thu Jul 21 20:48:47 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 22 Jul 2005 00:48:47 GMT Subject: PEP on path module for standard library In-Reply-To: <3kacleFslj6sU1@individual.net> References: <3kacleFslj6sU1@individual.net> Message-ID: Reinhold Birkenfeld: > And it is much more "Pythonic" in my eyes. Though that word may be inaccurate > when it comes from someone else that Guido, I feel that endless chains of > '[os.path.join(os.path.join(z, "a"), x) for x in os.path.listdir(os.path.join(z, "a") if os.path.isfile(os.path.join(.... > are not qualified as being Pythonic. I like Path but the above is trying too hard to be poor code. os.path.join takes more than 2 arguments, so that should be [os.path.join(z, "a", x) for x in os.path.listdir(os.path.join(z, "a") if os.path.isfile(os.path.join(.... Neil From peter at engcorp.com Fri Jul 22 08:47:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 08:47:49 -0400 Subject: PEP on path module for standard library In-Reply-To: <3kajr8FtfejbU1@individual.net> References: <3kacleFslj6sU1@individual.net> <3kajr8FtfejbU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Michael Hoffman wrote: >>What do you gain from removing these methods? A smaller dir()? > > It made sense to me at the time I changed this, although at the moment > I can't exactly recall the reasons. Along with some of the others (and as a fairly heavy user of "path"), I would caution strongly against jumping to do make this change. Given that a strong part of the justification for path's inclusion in the standard library (as expressed here in the past) is that it is stable and widely used, making such a fundamental change at this late stage just prior to its possible acceptance seems to me very risky. I have noticed in a number of cases where a "path" was usable as a drop-in replacement for strings that previously contained paths. I can't say for sure, but I strongly suspect some of that could would be broken if "paths" weren't basestrings. I'll attempt to check in my own code. Even if those uses don't actually break, it can *also* be useful to have the string methods available on a path object, so I'm also uncertain what you gain by removing that connection, though it's clear what things you might be losing. -2 for this idea. -Peter From ahabib at engin.umich.edu Thu Jul 28 17:24:06 2005 From: ahabib at engin.umich.edu (Asad Habib) Date: Thu, 28 Jul 2005 17:24:06 -0400 (EDT) Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Well, even if you are a hobbyist, that does not excuse you from being civil. After all, we are all humans beings that deserve to be treated with respect. Professional, hobbyist, vagabond, ogre, instigator, troll ... THERE IS NO EXCUSE ... please treat others with respect. - Asad On Thu, 28 Jul 2005, Rocco Moretti wrote: > Asad Habib wrote: > > I agree with Mustafa. After all, we are a bunch of professionals and not > > vagabonds hired to take pot shots at one another. > > Except that we're not all professionals. There are a large number of > hobbyists who use Python and this list. > > At any rate, my suggestion was not to forswear gentle corrections toward > better list behavior, (emphasis on gentle) but to address the case where > one would be tempted to "fight fire with fire", and answer a potshot > with another potshot. Professionals (and even decent hobbyists) don't > escalate flame wars, even unintentionally. > -- > http://mail.python.org/mailman/listinfo/python-list > From respro at gmail.com Thu Jul 21 19:18:36 2005 From: respro at gmail.com (Tzanko Tzanev) Date: 21 Jul 2005 16:18:36 -0700 Subject: problem with string Message-ID: <6bf5f7be.0507211518.1a9b0325@posting.google.com> hi :) I need some help for this script I have -------------------- cursor = conn.cursor() cursor.execute("select * from playlist limit 5") result = cursor.fetchall() # iterate through resultset playlist_txt = '' for record in result: mp3id = record[0] mp3_title = record[1] mp3_artist = record[2] playlist_txt += mp3id + mp3_title + mp3_artist #print mp3id , " - ", mp3_title , ' - ', mp3_artist , "
" cursor.close() conn.close() ------------------ #and want to print this out of "for record in result:" print playlist_txt #but there is an error in playlist_txt += mp3id + mp3_title + mp3_artist 10x in advance :) From peter at engcorp.com Thu Jul 7 18:11:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Jul 2005 18:11:09 -0400 Subject: Use cases for del In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Duncan Booth wrote: > Peter Hansen wrote: >>Tom Anderson wrote: >>>How about just getting rid of del? >> >>Arguing the case for del: how would I, in doing automated testing, >>ensure that I've returned everything to a "clean" starting point in all >>cases if I can't delete variables? Sometimes a global is the simplest >>way to do something... how do I delete a global if not with "del". > > I generally find that unit tests force me to structure the code in a > cleaner manner, e.g. to not use globals as much, but if you do need to > delete a global you do it in exactly the same way as you delete anything: > use the "del" statement: Umm: huh? Tom suggested getting rid of del, I suggested it was required for some cases in doing testing in the fact of globals (for cases where they are the simplest approach), then you suggest that the correct approach is to use "del". Well, I agree (including your point on use of globals, which I attempted to anticipate with my comment starting "sometimes"), but I don't really see the point of your posting, Duncan... it appears redundant on all counts. -Peter From josh-python at yucs.org Mon Jul 4 20:12:08 2005 From: josh-python at yucs.org (josh) Date: Tue, 5 Jul 2005 00:12:08 +0000 (UTC) Subject: readline: edit-and-execute-command Message-ID: anybody know why "edit-and-execute-command" doesn't work in python's readline? it doesn't even show up in a dump of readline functions: $ cat fc_test C-p: dump-functions C-e: edit-and-execute-command $ $ python Python 2.4 (#1, Jan 14 2005, 14:29:23) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. --- import readline --- readline.read_init_file('fc_test') if you hit control p, and you won't see 'edit-and-execute-command' listed at all, though you will when you run "INPUTRC=fc_test bash" thanks in advance From fuzzyman at gmail.com Wed Jul 6 09:04:36 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jul 2005 06:04:36 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120642040.109796.212450@o13g2000cwo.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> <1120636418.166800.42290@o13g2000cwo.googlegroups.com> <1120642040.109796.212450@o13g2000cwo.googlegroups.com> Message-ID: <1120655076.585562.65250@g44g2000cwa.googlegroups.com> Fair enough ;-) I'd like to discover the power of Lisp, but I have a limited amount of time to sink into programming... so maybe I'm better off putting my energies and imagination into Python. *A language is a medium of expression.* - Paul Graham All the best. Fuzzy http://www.voidspace.org.uk/python From luismgz at gmail.com Sat Jul 9 19:31:50 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 9 Jul 2005 16:31:50 -0700 Subject: Yet Another Python Web Programming Question In-Reply-To: References: Message-ID: <1120951910.507252.194800@g14g2000cwa.googlegroups.com> Try Karrigell ( http://karrigell.sourceforge.net ). And let me know what you think... Cheers, Luis From samgurung at gmail.com Thu Jul 14 06:24:29 2005 From: samgurung at gmail.com (linuxfreak) Date: 14 Jul 2005 03:24:29 -0700 Subject: Python Newbie Message-ID: <1121336669.837363.303850@g49g2000cwa.googlegroups.com> Hi all, I came accross this article by Eric Raymond in which he has sung peans about the python language. Well that has whetted my appetite... So I decided to get down and dirty. But alas I got down but not dirty.. i cant seem to find a good tutorial to help me get started. Whats the next best thing to do? Ask the pros and where do you find them...in a mailing list of course. So heres me asking if anyone has any pointers to some good basic python tutorial. Something that teaches one to get going. Thanks a ton guys, Linuxfreak From finite.automaton at gmail.com Mon Jul 11 17:28:35 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 11 Jul 2005 14:28:35 -0700 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: <1121117315.034614.62760@o13g2000cwo.googlegroups.com> IIRC, the self.__dict__.update(locals()) trick confuses psyco. But you can make a decorator to achieve the same result. There's not really a convincing case for extending python syntax. def attribute_decorator(f): import inspect argnames = inspect.getargspec(f)[0] def decorator(*args, **keywords): bound_instance = args[0] for name, value in zip(argnames[1:], args[1:]): setattr(bound_instance, name, value) return f(*args, **keywords) return decorator #--------- example use: class foo(object): @attribute_decorator def __init__(self, thing): print "init: self.thing is", repr(self.thing) f = foo('hello world') --ljp From Python.LeoJay at gmail.com Wed Jul 20 21:12:52 2005 From: Python.LeoJay at gmail.com (Leo Jay) Date: 20 Jul 2005 18:12:52 -0700 Subject: Newbie question about lists References: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> Message-ID: <1121908372.875767.321980@f14g2000cwb.googlegroups.com> you may use the decimal module which was introduced in Python2.4 >>> from decimal import * >>> li = [Decimal(".25"), Decimal(".10"), Decimal(".05"), Decimal(".01")] >>> print li [Decimal("0.25"), Decimal("0.10"), Decimal("0.05"), Decimal("0.01")] >>> From python-url at phaseit.net Fri Jul 29 13:37:49 2005 From: python-url at phaseit.net (Simon Brunning) Date: Fri, 29 Jul 2005 17:37:49 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 29) Message-ID: QOTW: "Guido has marked the trail; don't ignore the signs unless you really know where you're going." - Raymond Hettinger 'Proverbs 28:14 JPS "Happy is the man that feareth alway; but he that hardeneth his heart shall fall into evil." Obviously an exhortation to not ignore raised exceptions with "except: pass".' - Robert Kern Jason Orendorff's path module is a popular alternative to the build in os.path and shutil modules. Michael Hoffman and Reinhold Birkenfeld are working on a PEP suggesting that it be included in the standard library: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1f5bcb67c4c73f15 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/df1b647a0f103640 Java has nearly as many web frameworks as Python, but you can run any of them on any of the Java web application servers because they are all built on the Java Servlet specification. PEP 333, the Python Web Server Gateway Interface, aims to bring something similar to the world of Python: http://www.python.org/peps/pep-0333.html A short but sweet day-of-the-month suffix generator from John Machin: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/904fa627890c85dd Thanos Tsouanas wants access to an object's namespace dictionary: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5cc509d138e1701 David Isaac wants to avoid map(), but he wants a zip() function that runs to the length of the longest sequence. It's suggested that zip() should be able to do this, but Raymond Hettinger channels Guido and thinks that this would be a bad idea: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/265675b50fee8ec1 Tiny.be release four open source enterprise applications: http://lwn.net/Articles/145209/ Who needs "Ten Essential Development Practices"? We've got The Zen of Python: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c52d3c17f1ea9ec5 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From teoryn at gmail.com Mon Jul 25 10:39:28 2005 From: teoryn at gmail.com (teoryn) Date: 25 Jul 2005 07:39:28 -0700 Subject: Problem loading a file of words In-Reply-To: References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> <1122298053.790180.292810@g43g2000cwa.googlegroups.com> Message-ID: <1122302368.508836.215150@f14g2000cwb.googlegroups.com> I changed to using line = line.strip() instead of line = line [:-1] in the original and it it worked. Thanks! From samgurung at gmail.com Fri Jul 22 00:15:56 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 21:15:56 -0700 Subject: wxPython & Fedora Core 4 Message-ID: <1122005756.744692.285840@f14g2000cwb.googlegroups.com> Hi guys, Has anyone installed wxPython on Fedora Core 4. Apparently it need the libstdc++.so.5 file while Fedora installs the newer libstdc++.so.6 file. I tried installing the libstdc rpm from fedora core 3 which would have installed the required file but Fedora does not allow multiple versions of the same file . Man this is frustrating. Help desparately required.......... Thanks From noreply at python.org Sat Jul 23 06:18:45 2005 From: noreply at python.org (Mail Administrator) Date: Sat, 23 Jul 2005 14:18:45 +0400 Subject: Returned mail: see transcript for details Message-ID: <20050723102002.4E55E386DFB@mail.lsi.ru> The original message was included as attachment -------------- next part -------------- This part of message has been infected and was deleted! Dr.Web(R) Daemon report: infected with Win32.HLLM.MyDoom.49 ------------------------------------------------------- Dr.Web(R) Antivirus Service: http://www.drweb.com/ ------------------------------------------------------- From rkern at ucsd.edu Thu Jul 28 19:02:53 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 16:02:53 -0700 Subject: c/c++ extensions and help() In-Reply-To: <1122591137.423810.286960@f14g2000cwb.googlegroups.com> References: <1122591137.423810.286960@f14g2000cwb.googlegroups.com> Message-ID: Lenny G. wrote: > Is there a way to make a c/c++ extension have a useful method > signature? Right now, help(myCFunc) shows up like: > > myCFunc(...) > description of myCFunc > > I'd like to be able to see: > > myCFunc(myArg1, myArg2) > description of myCFunc > > Is this currently possible? There really isn't a way to let the inspect module know about extension function arguments. Just put it in the docstring. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bvande at po-box.mcgill.ca Tue Jul 5 15:34:47 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 05 Jul 2005 15:34:47 -0400 Subject: precision problems in base conversion of rational numbers In-Reply-To: <200507051049.37103.hancock@anansispaceworks.com> References: <42C91973.6090208@po-box.mcgill.ca> <200507051049.37103.hancock@anansispaceworks.com> Message-ID: <42CAE0D7.2040100@po-box.mcgill.ca> Terry Hancock said unto the world upon 05/07/2005 11:49: > On Monday 04 July 2005 06:11 am, Brian van den Broek wrote: > >>As a self-directed learning exercise I've been working on a script to >>convert numbers to arbitrary bases. It aims to take any of whole >>numbers (python ints, longs, or Decimals), rational numbers (n / m n, >>m whole) and floating points (the best I can do for reals), and >>convert them to any base between 2 and 36, to desired precision. Thanks to Terry and mensanator for the replies. To consolidate, I respond to Terry in-line and then add some response to mensanator at the end. > Interesting, I'd like to see that. I'd like it to be seen :-) I will soon send my current version in a private email. >>I'm pretty close but I know I am not handling the precision quite >>right. Nothing other than understanding hangs on it, but, that's >>enough :-) > > > Okay. You do understand that many numbers that can be exactly > represented in one base cannot be in another? Indeed. The original impetus for writing this was to substantiate my claim in an off-list conversation that whether a given rational had a repeating or terminating expansion was a function of the base of representation. In particular, that 1 / n in base n is 0.1 > E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating > decimal: 0.3333333.... And of course, there are infinitely many > other examples. The exact example I used in my off-list exchange :-) (No "great minds" claim, sadly, as it is the natural example.) > Needless to say, the conventional floating point numbers in Python > are actually stored as *binary*, which is why there is a "decimal" > module (which is new). > > If you're going to be converting between bases anyway, it probably > makes little difference whether you are using the decimal module > or not, of course. You'll have the same problems the conventional > float numbers do. It may be a function of the algorithm I picked, but I am almost certain that I switched to employing Decimals after finding a substantial inaccuracy with a purely float logic. I will likely get around to switching back to floats late tonight to confirm my recollection. > Getting back to your precision problem: I bet if you simply > evaluate the error term as I have above, and then convert *that* into > your base of choice, you will be able to tell how many places are > correct in the conversion. > > That is to, say, stop think about "number of places" and instead > think about "representation error". That number is a real property > of the data which can be represented in any base. Then you can > convert it to number of places in the representation process. A useful "cognitive correction", thanks :-) > e.g. 0.000005 has 6 places behind the zero in decimal, how many > does base3(0.000005)? --- that's the accuracy of the statement > > 0.33333 base10 ~= 0.1 base3 +- base3(0.000005 base10) > > Roughly, we know that 0.000005 = 10^-5 / 2. The same term > in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved > using logarithms, but I'll "leave that as an excercise for the reader", > because I'm too lazy to go look it up, and I've forgotten the > details. ;-) Thanks. mensanator provided the actual formula for my case. I had a "magic number" in my code by which I multiplied my desired level of "number of places in the representation" to obtain the value for decimal.getcontext.prec. mensanator wrote: > The value you want for x is log(17)/log(10) = > 1.2304489213782739285401698943283 where x was my "magic number". I've not had a chance to think it through yet, but I feel confident that given the formula, I'll be able to work out *why* that is the formula I need. So, thanks for that, too. mensanator also pointed out an inaccuracy in my posted example. I had 345 / 756 represented in base 17 to 80 digits, and came up with a repeating expansion. It was pointed out that I should have rounded up the last 'digit' ['17-it' ? :-) ]. Indeed. I'd been concentrating on getting the conversion logic right before adding logic to deal with rounding and should have mentioned my result was not a rounded one, but merely a truncation of the infinite expansion. Thanks for the correction / reminder to add the logic. > I hope this is helpful, though, > Terry Indeed, both your's and mensanator's. Thanks to both. Best to all, Brian vdB From devlai at gmail.com Sun Jul 10 00:16:16 2005 From: devlai at gmail.com (Devan L) Date: 9 Jul 2005 21:16:16 -0700 Subject: Python Forum In-Reply-To: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> References: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> Message-ID: <1120968976.764802.277130@g14g2000cwa.googlegroups.com> I see a total of 12 posts and 8 users. From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 10:58:22 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 16:58:22 +0200 Subject: Path PEP: What should Path(None) do? In-Reply-To: References: Message-ID: <3kkd0fFuqreeU1@individual.net> Michael Hoffman wrote: > Currently it returns Path('None'). This means I have to do a check on > input before pathifying it to make sure it is not None. > > Perhaps it should throw ValueError? The problem is that Path() currently acts like str() and will therefore accept almost anything that has a string representation. We can do two things: 1) restrict Path.__new__ arguments to be strings or unicode only, or 2) special-case None and what else comes in mind. I think 1) is the proper solution. Path() is not a general stringifier as str(), and shouldn't act like one. Reinhold From callmebill at gmail.com Fri Jul 15 16:27:28 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 15 Jul 2005 13:27:28 -0700 Subject: Native ODBC access for python on linux? In-Reply-To: <_ICdne5Z-td7lUXfRVn-2A@telcove.net> References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> <8NCdnRaSkdR-XkvfRVn-jg@telcove.net> <86r7e0al3p.fsf@bhuda.mired.org> <1121446822.710877.312020@g44g2000cwa.googlegroups.com> <_ICdne5Z-td7lUXfRVn-2A@telcove.net> Message-ID: <1121459248.688862.96130@f14g2000cwb.googlegroups.com> I know... I'm expecting pain, and when that pain doesn't arrive I assume that I did something wrong. Actually, I was using the odbc/dbi stuff that ships with the win32 distribution for my windows work, and using MySQLdb for my linux work. Most of the code is the same. But I suppose the big benefit of using MySQLdb on both (which certainly works) is that there is no abiguity as to what the user is running for an OS. You don't have a special case "If you're on Windows, do this; if you're on linux, do that"... Rather, by having everyone indiscriminately require MySQLdb, then that forces a unity. That's probably the way to go, huh? From hegedus at med.unc.edu Thu Jul 28 12:21:29 2005 From: hegedus at med.unc.edu (Tamas Hegedus) Date: Thu, 28 Jul 2005 12:21:29 -0400 Subject: xml-object mapping Message-ID: <42E90609.5030309@med.unc.edu> Hi! I am looking for an xml-object mapping tool ('XML Data Binding-design time product') where I can define the mapping rules in 'binding files' and the parser is generated automatically. Similar to the solution of Dave Kuhlman (http://www.rexx.com/~dkuhlman/generateDS.html) where the mapping is defined in an xml file (if I am understand well). But I already have the target object. The xml-tags should not be used as a property/member name, but should be mapped to an existing object. (There are existing tools, but written in Java (I would prefer Python; I am biologist not using Java for 5 years), like JiBX (http://jibx.sourceforge.net), Castor (http://www.castor.org; "XML-based mapping file to specify bindings for existing object models")) Thanks for your help in advance, Tamas -- Tamas Hegedus, PhD | phone: (1) 919-966 0329 UNC - Biochem & Biophys | fax: (1) 919-966 5178 5007A Thurston-Bowles Bldg | mailto:hegedus at med.unc.edu Chapel Hill, NC, 27599-7248 | http://biohegedus.org From nav+posts at bandersnatch.org Mon Jul 18 15:47:03 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 18 Jul 2005 15:47:03 -0400 Subject: Python scripts wont run - HELP References: <42dbd734_2@x-privat.org> Message-ID: <87irz7j3rc.fsf@localhost.localdomain> windozbloz writes: > It now works from the command line like you said. Shouldn't I also be able > to 'click' an icon that has been set to executable and launch the whole > process that way? You'll need to put an interpreter line at the beginning of your script, as other posters have indicated. This tells the shell how to handle the file. When you double-click a program icon in your file browser, the browser starts a shell process which is handed the file's name for execution. #!/usr/bin/python Says, "This file is interpreted by /usr/bin/python". The idiom you will often see: #!/usr/bin/env python Says, "Find 'python' in this user's environment, and give this file to that program for interpretation". That allows you to use a different python interpreter (say, /usr/local/bin/python if that comes first on your PATH environment variable), and allows the script to be more friendly for systems that do not have a /usr/bin/python. Depending on the GUI, you may not see a terminal window open for the script's execution, or the terminal might close as soon as the script exits, which will prevent you from looking at any output. Unless the program has a GUI, running it from the command-line is usually better than double-clicking it in a file browser. Nick -- #include /* sigmask (sig.c) 20041028 PUBLIC DOMAIN */ int main(c,v)char *v;{return !c?putchar(* /* cc -o sig sig.c */ v-1)&&main(0,v+1):main(0,"Ojdl!Wbshjti!=ojdlAwbshjti/psh?\v\1");} From mwm at mired.org Sun Jul 3 16:39:33 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 16:39:33 -0400 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> Message-ID: <86u0jb1v5m.fsf@bhuda.mired.org> anthonyberet writes: > My question isn't as all-encompassing as the subject would suggest... > > I am almost a Python newbie, but I have discovered that I don't get > along with IDLE, as i can't work out how to run and rerun a routine > without undue messing about. > > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of > code, to see the effects of tweaks, without having to save it each > time, or re-typing it over and over (I haven't even worked out how to > cut and paste effectively in the IDLE environment). > > I see lots of alternate IDEs etc, but which would allow me the simple > interface that I have described? - I really don't know about IDEs in > general, and I suspect I would be out of my depth with one of those. > > Thanks, and feel free to mock ;) Try an emacs (Xemacs is my preference). That should come with a python editing mode, which includes the ability to send code to a Python interpreter running in interactive mode in another window. So what you do is edit the code in a file on disk, and then ship it all to the interpreter (with C-c C-c). You can then use the objects defined in the file at the interperter prompt. After you identify a bug, you edit the function/method in question, and ship the function/class to the interpreter with M-C-x. You can then start playing with the new version of the function/class to check it. Note that this behavior isn't specific to Python. It's pretty standard emacs support for all languages that have a REPL loop. The command keys are even the same if you change languages. Be warned - changing a class doesn't change the code of any objects that were defined using the old class. So you get this sequence: x = MyClass() x.Test() # reveal bug in MyClass # edit MyClass.py, fix the bug, and M-C-x the class x.Test() # The bug is still there! x = MyClass() x.Test() # Now it's gone. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From stian at soiland.no Wed Jul 6 14:42:51 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 6 Jul 2005 20:42:51 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120610787.940292.15210@g43g2000cwa.googlegroups.com> References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <20050706184251.GT12095@itea.ntnu.no> On 2005-07-06 02:46:27, George Sakkis wrote: > So, who would object the full-word versions for python 3K ? > def -> define > del -> delete > exec -> execute > elif -> else if I'm all for it. I would even be tempted of changing def to function, but it would look stupid in: class A: function make_my_day(self): return "Your day" a = A() since a.make_my_day() is really a method, not a standalone function. We could use "function" instead of "lambda" though =) Objections for the "else if" might be that it sounds like you can replace "else if" with "else x=94" if you want. Thumbs up for "else if" because it explains what it is much better than "elif". "elseif" ? -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] From elmo13 at jippii.fi Wed Jul 13 16:25:46 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Wed, 13 Jul 2005 23:25:46 +0300 Subject: Searching for metadata related tools for use with python References: Message-ID: On Wed, 13 Jul 2005 23:22:01 +0300, Elmo M?ntynen wrote: > On Wed, 13 Jul 2005 15:49:27 +0300, Elmo M?ntynen wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> I'm interested in various metadata >> extraction/prosessing/distribution/something tools(including ways of >> differentiating between files, eg hashing etc) and especially python >> enabled ones. I'm also considering content-recognition/differentiating >> eg. image recognition. I'm already aware of these: python-bitzi, >> python-musicbrainz, mmpython, IMDbPY, python-mhash and imgSeek. If you >> could point me to other relating resources it would be great. >> >> Elmo >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.1 (GNU/Linux) >> Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org >> >> iD8DBQFC1Q3WctNFyQJObrsRAjXbAJ92B53YC9NqtC9nymK07OL+L3mNTwCgmlbb >> dPfSDsqJzBh+xa3h5L28Qac= >> =AtAo >> -----END PGP SIGNATURE----- > > I would also like comments if you're pretty sure the aren't any other > related resources. Anything related to organizing one's > filecollections(be it music, photos, books etc.), though i'm not > particularly interested in another mp3/ogg-tagger(report it still > though, if you will), would be interesting also. > > Elmo I'm going for completeness(though a never-ending chase you might say). Elmo From jforcier at strozllc.com Fri Jul 22 18:42:34 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: Fri, 22 Jul 2005 18:42:34 -0400 Subject: "Aliasing" an object's __str__ to a different method Message-ID: <2034E1FC-7F20-4BE6-A390-139AED5DE01F@strozllc.com> I am attempting to write a class whose string representation changes in response to external stimuli. While that effect is obviously possible via other means, I attempted this method first and was surprised when it didn't work, so I now want to know why :) Given the following class definition: class MyClass(object): def Edit(self): return "I, %s, am being edited" % (self) def View(self): return "I, %s, am being viewed" % (self) def setEdit(self): self.__str__ = self.__repr__ = self.Edit def setView(self): self.__str__ = self.__repr__ = self.View ...I would expect the following behavior: In [130]: testObject = MyClass() In [131]: testObject.setEdit() In [132]: str(testObject) Out[132]: 'I, <__main__.MyClass object at 0x511270>, am being edited' Unfortunately, this is what happens instead: In [130]: testObject = MyClass() In [131]: testObject.setEdit() In [132]: str(testObject) Out[132]: '<__main__.MyClass object at 0x511270>' In other words, str() is _NOT_ apparently calling .__str__ as it's supposed to! However, calling __str__ directly (which, yes, you're not supposed to do) does work as expected: In [133]: testObject.__str__() Out[133]: 'I, <__main__.MyClass object at 0x511270>, am being edited' Now, my understanding is that functions/methods are first-order objects, and can be pointed to via reference, and that appears to be true: In [135]: def func1(): .....: print "I'm func1" .....: In [136]: def func2(): .....: print "I'm func2" .....: In [137]: func2 = func1 In [138]: func2() I'm func1 However, expressions such as self.__str__ = aren't working for me, as above. Why not? Thanks for any responses, Jeff -- Jeffrey E. Forcier Junior Developer, Research and Development Stroz Friedberg, LLC 15 Maiden Lane, 12th Floor New York, NY 10038 [main]212-981-6540 [direct]212-981-6546 http://www.strozllc.com This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by any error in transmission. If you have received this message in error, please immediately notify the sender by e-mail or by telephone at 212.981.6540, delete the message and all copies from your system and destroy any hard copies. You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient. From fake at not.real Sat Jul 9 05:13:20 2005 From: fake at not.real (vch) Date: Sat, 09 Jul 2005 13:13:20 +0400 Subject: file.readlines() question Message-ID: Does a call to file.readlines() reads all lines at once in the memory? Are the any reasons, from the performance point of view, to prefer *while* loop with readline() to *for* loop with readlines()? From python at rcn.com Sun Jul 17 21:32:28 2005 From: python at rcn.com (Raymond Hettinger) Date: 17 Jul 2005 18:32:28 -0700 Subject: Filtering out non-readable characters References: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> <1121570966.6b3e122aacf94730620c39031b3c126b@teranews> Message-ID: <1121650348.789315.133660@z14g2000cwz.googlegroups.com> [George Sakkis] > It's only obvious in the sense that _after_ you see this idiom, you can go back to the docs and > realize it's not doing something special; OTOH if you haven't seen it, it's not at all the obvious > solution to "how do I get the first 256 characters". So IMO it should be mentioned, given that > string.translate often operates on the identity table. I think a single sentence is adequate for the > reference docs. For Py2.5, I've accepted a feature request to allow string.translate's first argument to be None and then run as if an identity string had been provided. Raymond Hettinger From newsgroups at jhrothjr.com Thu Jul 21 19:43:40 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 21 Jul 2005 17:43:40 -0600 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: <11e0cpe7vqrm18a@news.supernews.com> "Reinhold Birkenfeld" wrote in message news:3kakh5Ftjd9mU1 at individual.net... > John Roth wrote: >> "Michael Hoffman" wrote in message >> news:dbofk2$g1f$1 at gemini.csx.cam.ac.uk... >>> Many of you are familiar with Jason Orendorff's path module >>> , which is frequently >>> recommended here on c.l.p. I submitted an RFE to add it to the Python >>> standard library, and Reinhold Birkenfeld started a discussion on it in >>> python-dev >>> . >>> >>> The upshot of the discussion was that many python-dev'ers wanted path >>> added to the stdlib, but Guido was not convinced and said it must have a >>> PEP. >> >> Why did Guido want a PEP? Is it because he likes the idea but >> feels the feature set needs to be examined a bit more by the wider >> community, or is it some other reason? > > He said, > > """ > Whoa! Do we really need a completely different mechanism for doing the > same stuff we can already do? The path module seems mostly useful for > folks coming from Java who are used to the Java Path class. With the > massive duplication of functionality we should also consider what to > recommend for the future: will the old os.path module be deprecated, > or are we going to maintain both alternatives forever? (And what about > all the duplication with the os module itself, like the cwd() > constructor?) Remember TOOWTDI. > """ Read literally, this says (at least to me) "I don't want to fix it because I don't think it's broke." As far as the Java remark is concerned, I suspect that it's because in Java there is no such thing as a function; everything is either a method on an object or a static method on a class. And as far as I'm concerned, it's broke. I could see getting rid of the bits and pieces of procedural code in 3.0, but not sooner. John Roth > > Reinhold From tjreedy at udel.edu Thu Jul 28 10:08:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 28 Jul 2005 10:08:12 -0400 Subject: Sr. Compiler Engineering Opportunity References: <20050728073757.45C491E4002@bag.python.org> Message-ID: "Nathan Sanders" wrote in message news:20050728073757.45C491E4002 at bag.python.org... > I'm hoping to network with you and find out if you know anyone who > you think could be interested in the following opportunity? Since this does not appear to have anything to do with Python, it appears to be off-topic spam. Job listings for Python programming, on the other hand, are ok. From finite.automaton at gmail.com Wed Jul 27 12:35:05 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 27 Jul 2005 09:35:05 -0700 Subject: Stripping C-style comments using a Python regexp References: <1122478928.879240.89110@g47g2000cwa.googlegroups.com> Message-ID: <1122482105.439897.65920@z14g2000cwz.googlegroups.com> > Is there some equivalent feature in Python regexps? cpp_pat = re.compile('(/\*.*?\*/)|(".*?")', re.S) def subfunc(match): if match.group(2): return match.group(2) else: return '' stripped_c_code = cpp_pat.sub(subfunc, c_code) ...I suppose this is what the Perl code might do, but I'm not sure, since trying to read it hurts my brain... From rkern at ucsd.edu Sun Jul 31 19:42:56 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 16:42:56 -0700 Subject: subclassing list In-Reply-To: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> References: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> Message-ID: spike wrote: > I've googled like crazy and can't seem to find an answer to why this > isn't working. > > I want to create a custom list class that acts as a circular list. > > ie: my_list = (0, 1, 2) > > how I want it to behave: > > my_list[0] -> 0 > my_list[1] -> 1 > my_list[2] -> 2 > my_list[3] -> 0 > my_list[4] -> 1 > ...etc > > so, what I've tried to do is: > > def circular_list(list): > def __getitem__(self, i): > if (i >= len(self)): > return self[i % len(self)] > else: > return self[i] > > items = circular_list(range(8)) > > however, when I want to iterate over it with a for statement, I get: > > TypeError: iteration over non-sequence You also need to post the code that raises the error, or no one else can debug it. > what am I missing? I have no idea why you get that error. I do not in Python 2.4.1. However, I also don't get what you desire either. Iteration over lists (and subclasses of list) hasn't used __getitem__ since Python 2.2. http://www.python.org/doc/2.2/lib/typeiter.html In [7]: class circular_list(list): ...: def __getitem__(self, i): ...: return list.__getitem__(self, i%len(self)) ...: In [8]: items = circular_list(range(8)) In [9]: for i in items: ...: print i ...: 0 1 2 3 4 5 6 7 In fact, if all you need is iteration, use itertools.cycle(). In [6]: itertools.cycle? Type: type Base Class: String Form: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/itertools.so Docstring: cycle(iterable) --> cycle object Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. In [11]: class better_circular_list(circular_list): ....: def __iter__(self): ....: return itertools.cycle(list.__iter__(self)) ....: In [13]: bcl = better_circular_list(range(8)) In [14]: for i in bcl: ....: print i ....: 0 1 2 3 4 5 6 7 0 1 2 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jason at tishler.net Fri Jul 22 12:44:20 2005 From: jason at tishler.net (Jason Tishler) Date: Fri, 22 Jul 2005 12:44:20 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E0E281.6060009@llnl.gov> References: <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> Message-ID: <20050722164420.GA1912@tishler.net> Dean, On Fri, Jul 22, 2005 at 05:11:45AM -0700, Dean N. Williams wrote: > I downloaded your new Cygwin from http://cygwin.com and tried to build > install Python/CDAT again. It appears to have built properly, but when > I try to execute, it receive a sock error. How do I get around this > problem? I don't know -- it is not clear what you are trying to do. Are you trying to build Cygwin Python or just CDAT? On Fri, Jul 22, 2005 at 07:09:08AM -0700, Dean N. Williams wrote: > To be more specific. If I try to import socket I get the "ImportError: > No module named _socket". What do I need to install from Cygwin in > order for this to work? AFAICT, nothing. The above seems to indicate your Python installation is broken. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From hongqn at gmail.com Sun Jul 3 05:01:54 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Sun, 03 Jul 2005 17:01:54 +0800 Subject: debugger? In-Reply-To: References: Message-ID: <42C7A982.9090903@gmail.com> Detlev Offenbach wrote: > Qiangning Hong wrote: > > >>I have read a lot of posts discussing python IDEs, but most of them >>focus on the editor, GUI builder, project management, customizability, >>etc.... Some talked about debugging capability, but only on an >>available/unavailable level. >> >>I use vim to edit my code, wxGlade to build the GUI or hand-code it, >>and I still prefer that. So, until now, I haven't tried many IDEs. >> >>However, while I use pdb or inserting "print" statement to debug my >>apps, sometimes it is a pain. I think I need a good GUI debugger to >>help me. The debugger should meet _most_ of the following >>requirements: >> >>1. can debug wxPython applications (and other GUI lib). >>2. an intuitive way to set/clear/enable/disable breakpoints. >>3. can set conditional breakpoints (i.e. break when some condition >>satisfied). 4. variable watch list, namescope watching (local, global) >>5. evaluate expression, change variable values, etc within debugging. >>6. change the running routine, (i.e. go directly to a statement, skip >>some statements, etc) >>7. clever way to express objects, not just a string returned by repr() >>8. perform profiling >>9. a clear interface. >>10. cross-platform. >>11. free, or better, open source. >> >>What debugger will you suggest? >>Or what more polish feature you want to see in an ideal python >>debugger? -- hope this thread will help IDE developers to fill their >>todo list with some shining ideas :) >> > > > Eric3 should be compliant with your list. Try it at > http://www.die-offenbachs.de/detlev/eric3.html > > Regards, > Detlev Eric3 need pyqt so it is not free under windows platform. -- Qiangning Hong _____________________________________________________________ / Humanity has advanced, when it has advanced, not because it \ | has been sober, responsible, and cautious, but because it | | has been playful, rebellious, and immature. | | | \ -- Tom Robbins / ------------------------------------------------------------- \ , , \ /( )` \ \ \___ / | /- _ `-/ ' (/\/ \ \ /\ / / | ` \ O O ) / | `-^--'`< ' (_.) _ ) / `.___/` / `-----' / <----. __ / __ \ <----|====O)))==) \) /==== <----' `--' `.__,' \ | | \ / ______( (_ / \______ ,' ,-----' | \ `--{__________) \/ From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 07:22:06 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 13:22:06 +0200 Subject: PostgreSQL & Python vs PHP In-Reply-To: <3kfetaFu5fcrU1@individual.net> References: <3kfaucFu3tlfU1@individual.net> <1122139628.703635.48610@g14g2000cwa.googlegroups.com> <3kfetaFu5fcrU1@individual.net> Message-ID: <42e372e6$0$5872$626a14ce@news.free.fr> Luis P. Mendes a ?crit : (snip) > I need to build it from the server and also client side. > > For the client side I'll be using Python. > > But for the server side, I would like to hear some opinions. Is it worth > learning Php? I dont think so - unless you have no other choice !-) More seriously, Python is at least as good (much better IMHO...) as PHP for web applications, and the only thing (the only I can think of...) that's really easier to do with PHP is to write unmaintainable code with all logic and presention mixed up, global variables coming from outer space, etc... Another point is that, since you'll need to implement your domain model in Python for the client app anyway, duplicating it in PHP would not only be a waste of time, but also lead to a maintence nightmare. Using Python on both the client and server side, you'll just have to write specific controllers and views for the web application. A last thing is that PostgreSQL supports Python as an extension language. My 2 cents... From dalke at dalkescientific.com Fri Jul 22 00:42:50 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 22 Jul 2005 04:42:50 GMT Subject: PEP on path module for standard library References: <3kacleFslj6sU1@individual.net> <3kajr8FtfejbU1@individual.net> Message-ID: Michael Hoffman wrote: > Having path descend from str/unicode is extremely useful since I can > then pass a path object to any function someone else wrote without > having to worry about whether they were checking for basestring. I think > there is a widely used pattern of accepting either a basestring[1] or a > file-like object as a function argument, and using isinstance() to > figure out which it is. Reinhold Birkenfeld wrote: > Where do you see that pattern? IIRC it's not in the stdlib. Here's the first place that comes to mind for me xml.sax.saxutils def prepare_input_source(source, base = ""): """This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.""" if type(source) in _StringTypes: source = xmlreader.InputSource(source) elif hasattr(source, "read"): f = source source = xmlreader.InputSource() source.setByteStream(f) if hasattr(f, "name"): source.setSystemId(f.name) and xml.dom.pulldom def parse(stream_or_string, parser=None, bufsize=None): if bufsize is None: bufsize = default_bufsize if type(stream_or_string) in _StringTypes: stream = open(stream_or_string) else: stream = stream_or_string if not parser: parser = xml.sax.make_parser() return DOMEventStream(stream, parser, bufsize) Using the power of grep aifc.py def __init__(self, f): if type(f) == type(''): f = __builtin__.open(f, 'rb') # else, assume it is an open file object already self.initfp(f) binhex.py class HexBin: def __init__(self, ifp): if type(ifp) == type(''): ifp = open(ifp) imghdr.py if type(file) == type(''): f = open(file, 'rb') h = f.read(32) else: location = file.tell() h = file.read(32) file.seek(location) f = None mimify.py if type(infile) == type(''): ifile = open(infile) if type(outfile) == type('') and infile == outfile: import os d, f = os.path.split(infile) os.rename(infile, os.path.join(d, ',' + f)) else: ifile = infile wave.py def __init__(self, f): self._i_opened_the_file = None if type(f) == type(''): f = __builtin__.open(f, 'rb') self._i_opened_the_file = f # else, assume it is an open file object already self.initfp(f) compiler/transformer.py: if type(file) == type(''): file = open(file) return self.parsesuite(file.read()) plat-mac/applesingle.py if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) site-packages/ZODB/ExportImport.py if file is None: file=TemporaryFile() elif type(file) is StringType: file=open(file,'w+b') site-packages/numarray/ndarray.py if type(file) == type(""): name = 1 file = open(file, 'wb') site-packages/kiva/imaging/GdImageFile.py if type(fp) == type(""): import __builtin__ filename = fp fp = __builtin__.open(fp, "rb") else: filename = "" site-packages/reportlab/graphics/renderPM.py if type(image.path) is type(''): im = _getImage().open(image.path).convert('RGB') else: im = image.path.convert('RGB') site-packages/twisted/protocols/irc.py def __init__(self, file): if type(file) is types.StringType: self.file = open(file, 'r') (hmm, that last one looks buggy. It should have a "else: self.file = file" afterwards.) Used in the std. lib and used by many different people. (I excluded the Biopython libraries in this list, btw, because I may have influenced the use of this sort of type check.) Andrew dalke at dalkescientific.com From mail at thronesoftware.com Sat Jul 9 23:46:46 2005 From: mail at thronesoftware.com (Throne Software) Date: 9 Jul 2005 20:46:46 -0700 Subject: Python Forum Message-ID: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> Throne Software has opened up a Python Forum at: http://www.thronesoftware.com/forum/ Join us! From jeff.maitland at gmail.com Wed Jul 6 11:05:01 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Wed, 6 Jul 2005 11:05:01 -0400 Subject: threads and sleep? In-Reply-To: <11cnrngi4lrqn0a@corp.supernews.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <11clc1v4el6no7d@corp.supernews.com> <11cnrngi4lrqn0a@corp.supernews.com> Message-ID: <6829832e05070608053f9f9525@mail.gmail.com> Thanks for the info. I was doing some more diggging and I came across a module/class called POSH which should allow me to do what I want. My question now is, has anyone here used this and if so what it as easy to implement as what I am reading it is? (I have to wait for the sys admin to install the module on that server, but I have made a modified implemted the syntax into a copy of the code to test it as soon as the admin installs it.) Once again thanks for the information that you all have shared. Jeff From mg.mailing-list at laposte.net Tue Jul 5 07:20:29 2005 From: mg.mailing-list at laposte.net (mg) Date: Tue, 05 Jul 2005 13:20:29 +0200 Subject: distutils is able to handle... Message-ID: <42CA6CFD.8040700@laposte.net> Hello I work on an finite element framework and Python bindings have been developped. Actually, we use Boost.Build as build system but we would like to change it. We have two kinds of problems. First, the framework is used for generate pure C++ applications with static libraries ; second, the framework have some dependencies to fortran projects. Then, in order to know if Distutils can be use in our case, I would like to know if : - Can distutil compile static C/C++ libraries ? - Can distutil compile C/C++ applications ? - Can distutil manage fortran compiler and compile fortran libraries and applications ? Thank for your answers From jepler at unpythonic.net Wed Jul 6 09:42:22 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 6 Jul 2005 08:42:22 -0500 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: <42C8B151.2010503@REMOVEMEcyber.com.au> Message-ID: <20050706134222.GA5936@unpythonic.net> On Tue, Jul 05, 2005 at 09:49:33PM +0100, Tom Anderson wrote: > Are there any uses for NaN that aren't met by exceptions? Sure. If you can naturally calculate two things at once, but one might turn out to be a NaN under current rules. x, y = calculate_two_things() if isnan(x): perform_next_step_with_only_y(y) else: perform_next_step_with_both(x, y) Under your scheme, you'd have to write try: x, y = calculate_two_things() except NaNException: y = calculate_one_thing() perform_next_step_with_only_y(y) else: perform_next_step_with_both(x, y) and at the very least duplicate the code for calculating 'y', possibly re-doing a lot of work at runtime too. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bokr at oz.net Sat Jul 2 14:06:18 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 02 Jul 2005 18:06:18 GMT Subject: Inheriting from object References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> Message-ID: <42c69a4f.336127175@news.oz.net> On Thu, 30 Jun 2005 08:54:31 -0700, Scott David Daniels wrote: >Sion Arrowsmith wrote: >> ... And if you were to do so, surely: >> class foo(object): >> def __init__(self, *args, **kwargs): >> super(foo, self).__init__(self) >> >> would be the preferred way to go? >> >Or, perhaps: > class foo(object): > def __init__(self, *args, **kwargs): > super(foo, self).__init__(self, *args, **kwargs) > ... > Doesn't super(foo, self).__init__ return a bound method, so you don't need to pass self again? I.e., super(foo, self).__init__(*args, **kwargs) BTW, there's something about referring to type(self) by its not always dependably bound (though usually global) name that bothers me. I wonder if the above common use of super could be implemented as a property of object, so you'd normally inherit it and be able to write self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose) I.e., self.__super__ would effectively return the equivalent of super(type(self), self) (I think Michele Simionato may have posted some idea like this early on that I didn't really follow, but maybe my subconscious snagged and garbled ;-) Regards, Bengt Richter From newsgroups at jhrothjr.com Sat Jul 2 21:56:39 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 2 Jul 2005 19:56:39 -0600 Subject: Inheriting from object References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> <42c69a4f.336127175@news.oz.net> Message-ID: <11ceherfogsb879@news.supernews.com> "Bengt Richter" wrote in message news:42c69a4f.336127175 at news.oz.net... > I wonder if the above common use of super could be implemented as a > property of object, > so you'd normally inherit it and be able to write > self.super.__init__(*args, **kwargs) # (maybe spell it > self.__super__.__init__(...) I suppose) > > I.e., self.__super__ would effectively return the equivalent of > super(type(self), self) Well, let's look at it. If I implemented a super() method on object (and I didn't shadow it anywhere) what I'd have when it was invoked is something like def super(self): stuff >From there one could get the current instance's class, so we've got all the ingredients of the regular super(class, instance) built-in function. What it wouldn't have is the ability to invoke it on an arbitrary class and instance. The big issue seems to be the direction Guido wants to take Python - he seems to not want to put methods on the object type. I have to say that I don't understand his reasoning, if that is indeed his position. John Roth > > Regards, > Bengt Richter From premshree.pillai at gmail.com Sun Jul 31 23:15:30 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Mon, 1 Aug 2005 08:45:30 +0530 Subject: keylogger in Python In-Reply-To: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> Message-ID: On 30 Jul 2005 01:11:32 -0700, Jay wrote: > ok, i thought for 2 seconds i might have created a Keylogger in python > keylogging = keylogger() > keylog = open("keylog2.log", "w") > text = raw_input() > > keylog.write(text) > keylog.close > keylog = open("keylog2.log", "r") > keylog.read OMG! -- Premshree Pillai http://www.livejournal.com/users/premshree/ From spam.csubich+block at block.subich.spam.com Sat Jul 23 20:45:48 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 23 Jul 2005 20:45:48 -0400 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: References: <1122083350.151604.87980@g44g2000cwa.googlegroups.com> Message-ID: Paolino wrote: > Little less ugly: > In [12]:class A(object): > ....: def __str__(self):return self.__str__() > ....: def str(self):return 'ciao' > ....: def setStr(self):self.__str__=self.str > ....: > > In [13]:a=A() > > In [14]:a.setStr() > > In [15]:str(a) > Out[15]:'ciao' Not quite bug-free, by my eye that'll infintely recur if you call str(A()). From onurb at xiludom.gro Mon Jul 11 05:31:26 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 11 Jul 2005 11:31:26 +0200 Subject: Python Forum In-Reply-To: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> References: <1120967206.803548.216920@g47g2000cwa.googlegroups.com> Message-ID: <42d23c71$0$11560$636a15ce@news.free.fr> Throne Software wrote: > Throne Software has opened up a Python Forum at: > > http://www.thronesoftware.com/forum/ > > Join us! > Why should we ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From uche.ogbuji at gmail.com Fri Jul 15 12:50:38 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 15 Jul 2005 09:50:38 -0700 Subject: Differences between RDFlib - 4RDF and Redfoot - 4Suite? In-Reply-To: References: Message-ID: <1121446238.230645.37970@g14g2000cwa.googlegroups.com> "I was wondering about the differences with the referred libs and servers. Since the documentation isn't so thorough(and a bit because of my laziness), I thought I'd make request for usage accounts etc. stating the pros and cons of the aforementioned. Any notes would be appreciated." RDFLib is a thinner layer, more of the raw API. 4RDF adds in Versa query, a graph visualization tool, and multiple back ends. However, for the longest time the idea has been to merge the strengths of the two packages (big example: rdflib's parser is up to the latest round of specs. 4RDF's is not). As part of a client project I've actually begun the process of replacing 4RDF's parser with rdflib's in 4Suite (a separate add-on until the 4Suite 1.1. branch emerges). I'd say for now if you just need quick RDF parsing, and you're not also using plain XML, and stuff like Versa RDF query language aren't important to you, you'll get along just fine with rdflib. -- Uche http://copia.ogbuji.net From uval at rz.uni-karlsruhe.de Wed Jul 6 18:42:28 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Thu, 07 Jul 2005 00:42:28 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: I think in some contextes map is more readable than [f() for i in S] because it's more verbatim Removing lamdba would be reduce readability of Python, I think here for examble of code like class App: .... .... def drawLines(self, event): from random import randint r = lambda : randint(1, 100) self.canvas.create_line(r(), r(), r(), r()) defining one extra function would only confuse and self.canvas.create_line(r(1, 100), r(1, 100), r(1, 100), r(1, 100)) is not very nice to look at and what about creating one liner factories like from math import log10 log = lambda basis: lambda x: log10(x) / log10(basis) log2 = log(2) log2(2**10) -> 10.0 I would consider it as a great loss for Python if lambda will disappear From brian at rkspeed-rugby.dk Fri Jul 8 06:13:43 2005 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: 08 Jul 2005 12:13:43 +0200 Subject: Scipy - Latex Annotations in plots References: Message-ID: "Matthias R." writes: > Unfortunately matplotlib is only a 2D-plotting library. > > Do you know another one with 3D-capabilities as well? > That would be very nice, You can quite easily write a function that produces metapost code. Featpost is the best 3d-lib for that, afaik. The good thing is that you get plot that work in both latex and pdflatex and integrates completely with latex text. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html From peter at engcorp.com Tue Jul 19 21:50:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 19 Jul 2005 21:50:33 -0400 Subject: How do I send keystrokes to a console window in Windows XP? In-Reply-To: <1121784455.136313.301610@g47g2000cwa.googlegroups.com> References: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> <1121713006.253298.302050@g49g2000cwa.googlegroups.com> <1121784455.136313.301610@g47g2000cwa.googlegroups.com> Message-ID: RTG wrote: > With this capability, other possibilities open up. > Is there a way to read the output from the from the console window? > For example, how can we capture the output of the dir command? Normally one does that using a call to things like os.popen, or using the new subprocess module. If that's not suitable (if for some bizarre reason you really do want to pick up the output of "dir" after someone has run it manually in the console, and I can't imagine why you would want that), then search in the list archives for a recent thread that did investigate just that issue: how to capture text from a console window in Win32. I don't recall the answer but I'm sure you can find it. -Peter From could.net at gmail.com Mon Jul 18 07:21:01 2005 From: could.net at gmail.com (could ildg) Date: Mon, 18 Jul 2005 19:21:01 +0800 Subject: Python s60 In-Reply-To: <1121682721.727110.91100@g14g2000cwa.googlegroups.com> References: <1121682721.727110.91100@g14g2000cwa.googlegroups.com> Message-ID: <311b5ce1050718042171d918c@mail.gmail.com> you can reference http://www.bigbold.com/snippets/tags/series60?page=2 On 18 Jul 2005 03:32:01 -0700, xen0n at vodafone.it wrote: > Hi, I have looked around for any type of example of script that claims > to read the contacts database from an s60 phone, but i cant figure how > to use that examples. All i want is a simple, CLEAR, script that show > how to open contact database of an s60 phone and load all contacts > present into a listbox, nothing else. This will be easy for the > experts! please help me! Thanks in advance! > > -- > http://mail.python.org/mailman/listinfo/python-list > From BorgMotherShip at AliensR_US.org Mon Jul 18 21:18:31 2005 From: BorgMotherShip at AliensR_US.org (Eric) Date: Mon, 18 Jul 2005 18:18:31 -0700 Subject: retrieving https pages Message-ID: I'm using Linux - Manriva LE2005, python 2.3 (or i can also use python 2.4 on my other system just as well). Anyways... I want to get a web page containing my stock grants. The initial page is an https and there is a form on it to fill in your username and password and then click "login" I played with python's urlopen and basically it complains "your browser doesnt support frames" meaning the urlopen call makes it unhappy somehow. Is it reasonable to think i can build a script to login to this secure website, move to a different page (on that site) and download it to disk? Or am i just looking at a ling complicated task. I'd really like to get the page because then i can analyze it from a cron job and email myself my current options value each week or each month. Thanks Eric From bvande at po-box.mcgill.ca Sun Jul 10 13:23:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 10 Jul 2005 13:23:18 -0400 Subject: An absolute Newbie question In-Reply-To: References: Message-ID: <42D15986.9050505@po-box.mcgill.ca> wpog said unto the world upon 10/07/2005 12:41: > Hello, > > I have a question about using "IDLE", and that is whenever I start write my > own program in the "Python Shell" it will automatically execute whatever > command I have written, for example: >>> print 'Hello World" > > So, how to I get it to not execute, so that I can write a program that has > ordinary executable functions, and stuff like that? > > I do have some experience with Turbo Pascal, and so I'm hoping that this > will be an even easier language to learn, and thus far it does seem so, but > I need to get past this first;-). > > Thanks in advance, > > wpog Take a look at . But the quick answer: Launch IDLE. File Menu -> New Window Type away. (Be sure to explicitly save with the py or pyw extension, as IDLE does not add it for you.) HTH, Brian vdB From python at rcn.com Tue Jul 12 01:21:41 2005 From: python at rcn.com (Raymond Hettinger) Date: 11 Jul 2005 22:21:41 -0700 Subject: tuple.index(item) In-Reply-To: References: Message-ID: <1121145701.569771.299320@g49g2000cwa.googlegroups.com> [David Isaac] > > Why don't tuples support an index method? > > It seems natural enough ... [Peter Hansen] > This question has been posed several (many?) times in the past. See the > archives for more detail, but basically the answer that is usually given > is this: > > Tuples are intended to be used somewhat like C "structs", or Pascal > "records", which is to say they should contain heterogeneous sequences > of information for which the concept of ".index()" is fairly > meaningless. They are _not_ generally intended to be used as "read-only > lists", and that's basically why .index() wasn't defined for them. > > Another answer that probably follows close on the heels of that one is > along the lines of "patches are always welcome", but I honestly don't > know if a patch to add this would be accepted. Probably checking > Sourceforge for past patches would give an answer, since it seems likely > someone has already tried. Executive summary: Guido likes it the way it is. Someday, he may change his mind. Probably not. Raymond Hettinger From dalke at dalkescientific.com Fri Jul 29 14:02:20 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 29 Jul 2005 18:02:20 GMT Subject: can list comprehensions replace map? References: Message-ID: Me: >> Could make it one line shorter with > >> from itertools import chain, izip, repeat >> def fillzip(*seqs): >> def done_iter(done=[len(seqs)]): >> done[0] -= 1 >> if not done[0]: >> return [] >> return repeat(None) >> seqs = [chain(seq, done_iter()) for seq in seqs] >> return izip(*seqs) Peter Otten: > that won't work because done_iter() is now no longer a generator. > In effect you just say > > seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], > [])] It does work - I tested it. The trick is that izip takes iter() of the terms passed into it. iter([]) -> an empty iterator and iter(repeat(None)) -> the repeat(None) itself. 'Course then the name should be changed. Andrew dalke at dalkescientific.com From rwgk at yahoo.com Sat Jul 9 20:42:56 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 9 Jul 2005 17:42:56 -0700 (PDT) Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <42d06226$1@nntp0.pdx.net> Message-ID: <20050710004256.52265.qmail@web31507.mail.mud.yahoo.com> --- Scott David Daniels wrote: > Should be: > class autoinit(object): > def __init__(self, *args, **keyword_args): > for name, value in zip(self.__autoinit__.im_func.func_code. > co_varnames[1:], args): > setattr(self, name, value) > for name, value in keyword_args.items(): > setattr(self, name, value) > self.__autoinit__(*args, **keyword_args) Thanks! I didn't do it like this out of fear it may be too slow. But it turns out to be faster: overhead: 0.00 plain_grouping: 0.27 update_grouping: 0.43 plain_adopt_grouping: 0.68 autoinit_grouping: 1.15 autoinit_setattr_grouping: 1.08 # yours autoattr_grouping: 1.06 I am amazed. Very good! Cheers, Ralf ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: autoinit_timings.py URL: From s_t_a_n_i at gmx.net Mon Jul 25 21:21:19 2005 From: s_t_a_n_i at gmx.net (Stani) Date: 25 Jul 2005 18:21:19 -0700 Subject: SPE Ide Crash In-Reply-To: <1122110314.436649.290920@f14g2000cwb.googlegroups.com> References: <1122110314.436649.290920@f14g2000cwb.googlegroups.com> Message-ID: <1122340879.774093.259930@f14g2000cwb.googlegroups.com> linuxfreak wrote: > Hi Stani, > > Downloaded your latest SPE editor 0.7.4.m . I'm running wxPython 2.6.1 > on a Fedora Core 4 machine. The IDE is great but guess what it crashes > without warning. Was typing some code and boom the whole thing > disappeared without a trace. Thought should let you know > > All you guys using this IDE has it ever crashed on you like this??? SPE is now in beta-testing phase until the warning sign on the homepage is gone. Please be patient and collaborate: Use SPE in the debug mode: >>> python spe.py --debug > debug.txt Than you can put the error report (debug.txt) on the bug tracker (see spe homepage: http://www.stani.be/python/spe/blog) and it will be fixed asap. By the way 0.7.4.n is out now. Stani From steve at REMOVETHIScyber.com.au Tue Jul 12 02:37:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 16:37:35 +1000 Subject: __eq__ on a dict References: Message-ID: Replying to myself... how sad. On Tue, 12 Jul 2005 15:41:46 +1000, Steven D'Aprano wrote: > That wasn't clear from his post at all. If he had explained what he > wanted, I wouldn't have wasted my time explaining what he already knew. On reading it, that came across more snarky than I intended. Sorry. > Asking the right question helps. But not in this case, because comparison > of objects is ... confusing. There doesn't seem to be any definitive > answer to the question, not that I have been able to find, although plenty > of hints. > > My first thought was the comparisons between dicts is implemented as > comparisons between their items, ie cmp(dictA, dictB) is turned into > cmp(dictA.items(), dictB.items()). But that doesn't seem to be the case: However, I wasn't completely insane, since I came across this tidbit: http://python.active-venture.com/ref/comparisons.html "Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal. Outcomes other than equality are resolved consistently, but are not otherwise defined." with a footnote leading to this comment: "Earlier versions of Python used lexicographic comparison of the sorted (key, value) lists, but this was very expensive for the common case of comparing for equality." I also suggested: > My second thought was that comparison is implemented by first comparing > keys, then values, ie cmp(dictA, dictB) [snip] > I don't think I can prove it though. I certainly can't prove it, since my example pseudo-code fails even on the example I used earlier. Sigh. In summary: Equality of dicts is guaranteed. Two dicts are equal if and only if their keys:value pairs are equal. Other orderings between dicts are calculated consistently but not in any documented way. One gotcha is that some dicts are unordered: py> {1:1j} < {1:2j} Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= but even that is special-cased up to the wazzoo: py> {1:1j} < {1:1j} False -- Steven. From peter at engcorp.com Thu Jul 28 18:24:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Jul 2005 18:24:59 -0400 Subject: pySerial Windows write problem In-Reply-To: <3tudna94E-hWoXTfRVn-tw@nmt.edu> References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: Bob Greschke wrote: > But writing anything to the port > quickly (not always right away...like maybe 5-6 iterations through the > loop?) causes the > > win32file.CloseHandle(self.hComPort) > > statement in the 'def close(self)' function of the serialwin32.py file of > the pySerial package to hang for a few seconds, then return. Are you certain it is this line that is blocking, and not the preceding line which is a call to SetCommTimeouts()? How did you prove which line it is? (I don't have an answer to the problem, just wanted to be sure of the information...) -Peter From devlai at gmail.com Fri Jul 1 15:24:44 2005 From: devlai at gmail.com (Devan L) Date: 1 Jul 2005 12:24:44 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> Message-ID: <1120245884.872772.231420@o13g2000cwo.googlegroups.com> With the exception of reduce(lambda x,y:x*y, sequence), reduce can be replaced with sum, and Guido wants to add a product function. From fuzzyman at gmail.com Fri Jul 22 03:29:39 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Jul 2005 00:29:39 -0700 Subject: Web-Forms In-Reply-To: <86ek9rrahv.fsf@bhuda.mired.org> References: <86ek9rrahv.fsf@bhuda.mired.org> Message-ID: <1122017379.811774.280470@f14g2000cwb.googlegroups.com> Mike Meyer wrote: > Mathias Waack writes: > > > Hi, > > > > I need to access some information from a web site which are only accessible > > through a form. Thus for each bucket of data you have to fill out the form, > > submit it and wait for an answer. Very easy - if you don't have to check > > some hundred times. Of course this site requires cookies, it is not > > directly accessible by URL and so on. All that nice stuff used to make a > > web site more professional;) > > > > But now the question: how can this be solved by using Python? > > urllib2 (in the standard library) for reading the data from the > website. BeautifulSoup http://www.crummy.com/software/BeautifulSoup/> for extracting data > from the pages. > Adding ClientForm for automatically handling the forms and ClientCookie/cookielib for automatic cookie handling. Best Regards, Fuzzy http://www.voidspace.org.uk/python > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin.witte at gmail.com Sun Jul 3 07:51:43 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 3 Jul 2005 04:51:43 -0700 Subject: what is the difference between command prompt and IDLE? In-Reply-To: References: Message-ID: <1120391503.683511.303290@g44g2000cwa.googlegroups.com> start reading here: http://www.python.org/idle/doc/idlemain.html, although it is not up to date most of the information still holds up From gsakkis at rutgers.edu Mon Jul 4 14:23:48 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 4 Jul 2005 11:23:48 -0700 Subject: math.nroot References: <1120432250.340056.237460@g44g2000cwa.googlegroups.com> <42C8AD20.30004@REMOVEMEcyber.com.au> <1120476994.515029.129260@g14g2000cwa.googlegroups.com> <861x6e1nhf.fsf@bhuda.mired.org> Message-ID: <1120501428.350672.75140@f14g2000cwb.googlegroups.com> "Mike Meyer" wrote: > "George Sakkis" writes: > > "Steven D'Aprano" wrote: > > > >> But it doesn't make sense to say that two flags are equal: > >> > >> keep_processing = True > >> more_reading_needed = True > >> while more_reading_needed and keep_processing: > >> get_more_records() > >> process_records() > >> if not keep_processing: > >> print "User clicked Cancel" > >> > >> What does it mean to say that the flag done_processing > >> is equal to the flag more_reading_needed? (That is not > >> the same question as asking if the two flags have the > >> same value.) > > > > Huh ? Equality *is* the answer to whether two "things" (flags or > > whatever) have the same value or not. > > I think it seriously depends on what your "things" are. It also depends seriously on what your _values_ are. > For instance: > > length_in_meters = 1 > length_in_feet = 3.2808399 > > The two variables clearly have different values. Yet they are also > clearly equal - representing a distance of 1 meter, within tolerances. > > On the other hand: > > length_in_meters = 1 > time_in_days = 1 > > These two variables clearly have the same value. Yet they aren't > equal. In fact, comparing them is clearly an error. Indeed, if the values are represented as plain numbers. In a different formulation, values can be represented as unit numbers (e.g. http://home.tiscali.be/be052320/Unum.html) as in length_in_meters = 1 * M length_in_feet = 3.2808399 * FT These two values _are_ equal then. George From http Thu Jul 14 08:10:38 2005 From: http (Paul Rubin) Date: 14 Jul 2005 05:10:38 -0700 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <1120577852.042709.251940@o13g2000cwo.googlegroups.com> Message-ID: <7xll49si4h.fsf@ruckus.brouhaha.com> Andreas Kostyrka writes: > Basically the current state of art in "threading" programming doesn't > include a safe model. General threading programming is unsafe at the > moment, and there's nothing to do about that. It requires the developer > to carefully add any needed locking by hand. So how does Java do it? Declaring some objects and functions to be synchronized seems to be enough, I thought. From sjmachin at lexicon.net Sun Jul 24 07:55:19 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 24 Jul 2005 21:55:19 +1000 Subject: tuple to string? In-Reply-To: References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> Message-ID: <42e381a6@news.eftel.com> Steven D'Aprano wrote: > On Sat, 23 Jul 2005 23:31:04 +1000, John Machin wrote: > > >>>>You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-) >>> >>> >>>Ah, ok. Didn't want to lookup the precedence rules... >> >> >>Look up the precedence rules? Are you aware of any language where * / >>and % _don't_ have the same precedence?? > > > Do languages like Pascal that don't have string formatting expressions, or > use the % operator, count? A thousand pardons; I should have said "Are you aware of any language which has % (as primarily a numeric remainder/modulo operator) but * / and % _don't_ have the same precedence??" OK, given a language which does have * and / used among other things for numerical multiply and divide, (a) are you aware of any such language which does does not have * and / at the same precedence level (b) supposing one wanted to introduce % as a numerical remainder/modulo/whatever operator (plus other meaning(s) for non-numeric types), would you care to argue that it should not have the same precedence level (as * and /)? Pascal was/is a prime example of bad precedence choice: a > b or c > d means a > (b or c) > d in Pascal (not very useful) and (a > b) or (c > d) in many other languages. > > How about languages like Forth that don't have precedence rules at all, > unless "first come, first served" is a precedence rule? No precedence rules -> no relevance to the topic From cyril.bazin at gmail.com Sun Jul 24 21:23:04 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Mon, 25 Jul 2005 03:23:04 +0200 Subject: Simple Problem In-Reply-To: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> References: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> Message-ID: By any chance are you speaking about the function "repr" ? Cyril On 24 Jul 2005 18:14:13 -0700, ncf wrote: > > I know I've seen this somewhere before, but does anyone know what the > function to escape a string is? (i.e., encoding newline to "\n" and a > chr(254) to "\xfe") (and visa-versa) > > Thanks for helping my ignorance :P > > -Wes > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fdeserres at gmx.net Fri Jul 15 08:31:03 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Fri, 15 Jul 2005 14:31:03 +0200 Subject: Documenting extension modules? In-Reply-To: <1121429087.709252.156690@g44g2000cwa.googlegroups.com> References: <42D79025.4000405@gmx.net> <1121429087.709252.156690@g44g2000cwa.googlegroups.com> Message-ID: <42D7AC87.10800@gmx.net> Simon Dahlbacka wrote: >Re: assigning a PyStr object to __doc__, take a look at Py_InitModule3, >which does that for you. > > > got it, thx. >Then you have the PyDoc_STRVAR macro in python.h that you might want to >use (see definition below). But as Robert already told you, you'll need >to provide the necessary information about i.e. parameters yourself in >the docstrings. > >/* Define macros for inline documentation. */ >#define PyDoc_VAR(name) static char name[] >#define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str) >#ifdef WITH_DOC_STRINGS >#define PyDoc_STR(str) str >#else >#define PyDoc_STR(str) "" >#endif > > > beautiful. PS: The following snip from http://python.fyxm.net/peps/pep-0007.html was helpful to me in understanding usage of these macros: - Use the PyDoc_STR() or PyDoc_STRVAR() macro for docstrings to support building Python without docstrings (./configure --without-doc-strings). For C code that needs to support versions of Python older than 2.3, you can include this after including Python.h: #ifndef PyDoc_STR #define PyDoc_VAR(name) static char name[] #define PyDoc_STR(str) (str) #define PyDoc_STRVAR(name, str) PyDoc_VAR(name) = PyDoc_STR(str) #endif - The first line of each fuction docstring should be a "signature line" that gives a brief synopsis of the arguments and return value. For example: PyDoc_STRVAR(myfunction__doc__, "myfunction(name, value) -> bool\n\n\ Determine whether name and value make a valid pair."); Always include a blank line between the signature line and the text of the description. If the return value for the function is always None (because there is no meaningful return value), do not include the indication of the return type. - When writing multi-line docstrings, be sure to always use backslash continuations, as in the example above, or string literal concatenation: PyDoc_STRVAR(myfunction__doc__, "myfunction(name, value) -> bool\n\n" "Determine whether name and value make a valid pair."); Though some C compilers accept string literals without either: /* BAD -- don't do this! */ PyDoc_STRVAR(myfunction__doc__, "myfunction(name, value) -> bool\n\n Determine whether name and value make a valid pair."); not all do; the MSVC compiler is known to complain about this. From future_retro at yahoo.co.uk Fri Jul 22 07:04:34 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 22 Jul 2005 04:04:34 -0700 Subject: RegUnloadkey access denied In-Reply-To: <1122024834.778860.321410@g44g2000cwa.googlegroups.com> References: <1122022887.947520.152460@o13g2000cwo.googlegroups.com> <1122024834.778860.321410@g44g2000cwa.googlegroups.com> Message-ID: <1122030274.847247.45270@g14g2000cwa.googlegroups.com> solved it! I need to close the key first import ntsecuritycon import win32security import win32api import _winreg import win32con flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) Loadid = win32security.LookupPrivilegeValue(None, 'SeRestorePrivilege') Saveid = win32security.LookupPrivilegeValue(None, 'SeBackupPrivilege') LoadPrivilege = [(Loadid, ntsecuritycon.SE_PRIVILEGE_ENABLED)] SavePrivilege = [(Saveid, ntsecuritycon.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(htoken, 0, LoadPrivilege) win32security.AdjustTokenPrivileges(htoken, 0, SavePrivilege) key = _winreg.HKEY_USERS hkey = win32api.RegLoadKey(key,'Marc','c:\\ntuser.dat') okey = win32api.RegOpenKeyEx(key,'Marc\\test',0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(okey,'test',0,_winreg.REG_DWORD,0) win32api.RegCloseKey(okey) win32api.RegUnLoadKey(key,'Marc') From bokr at oz.net Sun Jul 10 03:01:07 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 10 Jul 2005 07:01:07 GMT Subject: removing list comprehensions in Python 3.0 References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> <1120963325.227725.123030@g43g2000cwa.googlegroups.com> Message-ID: <42d0c704.271167688@news.oz.net> On Sat, 09 Jul 2005 22:32:22 -0600, Steven Bethard wrote: >Raymond Hettinger wrote: >> [Steven Bethard] >> >>>I would hope that in Python 3.0 list comprehensions and generator >>>expressions would be able to share a large amount of implementation, and >>>thus that the speed differences would be much smaller. But maybe not... >> >> Looking under the hood, you would see that the implementations are >> necessarily as different as night and day. Only the API is similar. > >Necessarily? It seems like list comprehensions *could* be implemented >as a generator expression passed to the list constructor. They're not >now, and at the moment, changing them to work this way seems like a bad >idea because list comprehensions would take a performance hit. But I >don't understand why the implementations are *necessarily* different. >Could you explain? > >STeVe > >P.S. The dis.dis output for list comprehensions makes what they're doing >pretty clear. But dis.dis doesn't seem to give me as much information >when looking at a generator expression: > >py> def ge(items): >... return (item for item in items if item) >... >py> dis.dis(ge) > 2 0 LOAD_CONST 1 (expression> at 0116FD20, file "", line 2>) > 3 MAKE_FUNCTION 0 > 6 LOAD_FAST 0 (items) > 9 GET_ITER > 10 CALL_FUNCTION 1 > 13 RETURN_VALUE > >I tried to grep through the dist\src directories for what a generator >expression code object looks like, but without any luck. Any chance you >could point me in the right direction? >>> import dis >>> g = ge([1,2,0,3,'',4]) >>> dis.dis(g) Traceback (most recent call last): File "", line 1, in ? File "d:\python-2.4b1\lib\dis.py", line 46, in dis raise TypeError, \ TypeError: don't know how to disassemble generator objects but: >>> dis.dis(ge) 2 0 LOAD_CONST 1 ( at 02EE4FA0, file "", line 2>) 3 MAKE_FUNCTION 0 6 LOAD_FAST 0 (items) 9 GET_ITER 10 CALL_FUNCTION 1 13 RETURN_VALUE >>> ge.func_code ", line 1> >>> ge.func_code.co_consts (None, at 02EE4FA0, file "", line 2>) >>> ge.func_code.co_consts[1] at 02EE4FA0, file "", line 2> >>> dis.dis(ge.func_code.co_consts[1]) 2 0 SETUP_LOOP 28 (to 31) 3 LOAD_FAST 0 ([outmost-iterable]) >> 6 FOR_ITER 21 (to 30) 9 STORE_FAST 1 (item) 12 LOAD_FAST 1 (item) 15 JUMP_IF_FALSE 8 (to 26) 18 POP_TOP 19 LOAD_FAST 1 (item) 22 YIELD_VALUE 23 JUMP_ABSOLUTE 6 >> 26 POP_TOP 27 JUMP_ABSOLUTE 6 >> 30 POP_BLOCK >> 31 LOAD_CONST 0 (None) 34 RETURN_VALUE A little more info, anyway. HTH. Regards, Bengt Richter From cam.ac.uk at mh391.invalid Fri Jul 22 13:47:52 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 18:47:52 +0100 Subject: return None In-Reply-To: <3kcpbbFtjttlU1@individual.net> References: <3kcpbbFtjttlU1@individual.net> Message-ID: Ximo wrote: > Can I do a function which don't return anything? > > The question is that, if I do a function that have a return or without > return, it returns always "None", but i want that it doesnt return me > nothing When you execute the statement a = myfunction() What do you want to be in a, if not None? -- Michael Hoffman From newstonne at web.de Wed Jul 13 09:24:25 2005 From: newstonne at web.de (Roland Heiber) Date: Wed, 13 Jul 2005 15:24:25 +0200 Subject: Building a function call? In-Reply-To: <7OWdnRFJ_sHkk0jfRVn-hw@powergate.ca> References: <7OWdnRFJ_sHkk0jfRVn-hw@powergate.ca> Message-ID: Peter Hansen wrote: >> locals().get("dothat")(*c) This was just meant as a quick example, not as production-level code ;) Even with globals(), I think its a bit odd ..., but safer than using eval() ... HtH, Roland From ivanlan at pauahtun.org Fri Jul 1 09:07:57 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Fri, 01 Jul 2005 07:07:57 -0600 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <42c51eeb$0$255$edfadb0f@dread12.news.tele.dk> Message-ID: <42C5402D.5D275B6A@pauahtun.org> Hi All-- Max M wrote: > > Another good bet is BeautifulSoup, which is absolutely great for > scraping content from webpages. > > http://crummy.com/software/BeautifulSoup/index.html > Not if you want to handle HTML in anything but ASCII. BeautifulSoup insists you change your site.py to change the default encoding if you want to use non-ASCII. It might work beautifully, but I won't use it, at least not until it's fixed to understand encodings. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From rafi at free.fr Tue Jul 26 17:27:25 2005 From: rafi at free.fr (rafi) Date: Tue, 26 Jul 2005 23:27:25 +0200 Subject: multiple inheritance super() In-Reply-To: References: Message-ID: <42e6aac4$0$14586$626a14ce@news.free.fr> Peter Hansen wrote: > km wrote: > >> Hi all, >> >> In the following code why am i not able to access class A's object >> attribute - 'a' ? I wishto extent class D with all the attributes of >> its base classes. how do i do that ? [snip] > Each class should do a similar super() call, with the appropriate name > substitutions. [snip] > -Peter A related question is about the order of the __init__ calls. Considering the following sample: #--8<--- class A (object): def __init__ (self): super (A, self) .__init__ () print 'i am an A' def foo (self): print 'A.foo' class B (object): def __init__ (self): super (B, self) .__init__ () print 'i am a B' def foo (self): print 'B.foo' class C (A, B): def __init__ (self): super (C, self) .__init__ () print 'i am a C' c = C () c.foo () #--8<--- aerts $ python2.4 inheritance.py i am a B i am an A i am a C A.foo I do understand the lookup for foo: foo is provided by both classes A and B and I do not state which one I want to use, so it takes the first one in the list of inherited classes (order of the declaration). However I cannot find an explanation (I may have googled the wrong keywords) for the order of the __init__ calls from C. I was expecting (following the same order as the method lookup): i am an A i am a B i am a C A.foo Thanks -- rafi "Imagination is more important than knowledge." (Albert Einstein) From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 08:17:20 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 14:17:20 +0200 Subject: Get directory from http web site References: <1122029473.532056.215900@z14g2000cwz.googlegroups.com> Message-ID: rock69 enlightened us with: > I was wondering if there's some neat and easy way to get the entire > contents of a directory at a specific web url address. [...] Is it > possible to retrieve this list (not the physical files) and have it > stored in a variable of type list or something? Check out the chapter on HTML parsing at http://www.diveintopython.org/ Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From darkcowherd at gmail.com Tue Jul 12 11:17:27 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Tue, 12 Jul 2005 20:47:27 +0530 Subject: Why does reply to messages on this list put the sender in the To Message-ID: <5f4d3cb5050712081720b880ac@mail.gmail.com> Most lists when i hit reply it puts the list address back in the To address and some lists allow you to configure this. But in this list reply sends the mail back as a private mail and there seems to be no option to configure this. Am I missing something DarkCowherd From rorley at gmail.com Tue Jul 12 11:25:50 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 08:25:50 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121181602.408662.210790@g14g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> Message-ID: <1121181950.339056.171260@g44g2000cwa.googlegroups.com> OK, so my problem is I have a text file with all of these instances, for example 5000 facts about animals. I need to go through the file and put all of the facts (lines) that contain the word lion into a file called lion.txt. If I come across an animal or other word for which a file does not yet exist I need to create a file for that word and put all instances of that word into that file. I realize that this should probably create 30,000 files or so. Any help would be REALLY appreciated. Thanks. Reece From jlconlin at lanl.gov Thu Jul 14 19:14:24 2005 From: jlconlin at lanl.gov (Jeremy) Date: Thu, 14 Jul 2005 17:14:24 -0600 Subject: readlines() doesn't read entire file Message-ID: I have a most aggravating problem. I don't understand what is causing readlines() not to read all the lines in the file. I have the following syntax: # some initial stuff XS = xsdir(Datapath + '/xsdir', options.debug) # some more stuff class xsdir(object): #{{{1 """This class handles all of the data and methods for reading the xsdir file.""" def __init__(self, Datapath, debug=False): self.xsdir = file(Datapath, 'r') # File object self.lines = self.xsdir.readlines() if debug: print self.lines # and then other stuff as well I can see all the lines in the list self.lines, but they are not all the lines in the file. When I look at the file in Vim, I can see all the lines, but Python cannot. Can someone help me with this one? Thanks, Jeremy From edvard+news at majakari.net Wed Jul 6 11:32:24 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 06 Jul 2005 18:32:24 +0300 Subject: Favorite non-python language trick? References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> <87hdf8ync5.fsf@titan.staselog.com> Message-ID: <87d5pwympj.fsf@titan.staselog.com> Thomas Heller writes: > I don't see what's wrong with this code, and if one wanted, one could > also implement a decorator which calls warnings.warn when the function > is called: > > def c_buffer(init, size=None): > "deprecated, use create_string_buffer instead" > import warnings > warnings.warn("c_buffer is deprecated, use create_string_buffer instead", > DeprecationWarning, stacklevel=2) > return create_string_buffer(init, size) Well, nothing's wrong there, and the same could be done with Java before. However, having a consistent deprecated string everywhere allows easier eg. automatic finding of such methods from documentation. Decorators also help here, but that requires version 2.3 or newer (which usually isn't a problem, but can be) Hey! I hadn't realized category parameter nor stacklevel in warnings module (just used a few times, never read the doc because I didn't need to). Neat, thanks. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From stian at soiland.no Wed Jul 6 15:16:40 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 6 Jul 2005 21:16:40 +0200 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <42CB6554.9010505@REMOVEMEcyber.com.au> References: <-8ydnZxXGOCQvlbfRVn-3Q@comcast.com> <42CB6554.9010505@REMOVEMEcyber.com.au> Message-ID: <20050706191640.GX12095@itea.ntnu.no> On 2005-07-06 07:00:04, Steven D'Aprano wrote: > map(lambda x: if x == 0: 1; else: math.sin(x)/x, > myList) And now for the "readable" list comprehension version: [x==0 and 1 or math.sin(x)/x for x in myList] Now even though I'm into the short-circuiting of and-or and even occasionally have used such masturbation techniques as this, I don't think it qualifies as pythonic. If it was me, I would probably even have written: [x and math.sin(x)/x or 1 for x in myList] -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] From jforcier at strozllc.com Mon Jul 25 20:51:28 2005 From: jforcier at strozllc.com (Jeffrey E. Forcier) Date: 25 Jul 2005 17:51:28 -0700 Subject: Time formatting and date suffixes References: Message-ID: <1122339088.884031.32100@g44g2000cwa.googlegroups.com> See, I was thinking I'd have to write a short function to do it myself, but I hadn't realized it could be quite *that* short. Thanks! That'll do quite nicely, and is definitely something I'm going to throw in my "general utility functions" folder :) Regards, Jeff From zondo at pillock.freeserve.co.uk Fri Jul 8 14:03:28 2005 From: zondo at pillock.freeserve.co.uk (Glenn Hutchings) Date: Fri, 08 Jul 2005 18:03:28 +0000 Subject: [ANNOUNCE] pysudoku 0.1 Message-ID: Announcing PySuDoku version 0.1, yet another Sudoku program written in Python. But this one has features that I don't see in any of the others: * Cute interactive solving mode via Tkinter. * Puzzle generation option, for making your own puzzles. * Nicely packaged for installation via distutils. Sudoku, for the remaining 27 people in the world who don't know already, is a logic puzzle where you have to fill in the numbers in a 9x9 grid so that each row, column and 3x3 box has exactly one of the numbers 1-9 in them. You can get pysudoku at: http://www.freewebtown.com/zondo/programs From tiissa at nonfree.fr Sun Jul 24 11:54:11 2005 From: tiissa at nonfree.fr (tiissa) Date: Sun, 24 Jul 2005 17:54:11 +0200 Subject: FAQ? In-Reply-To: References: Message-ID: <42e3b9a2$0$16759$626a14ce@news.free.fr> Michael Hoffman wrote: > Keith P. Boruff wrote: > >> Michael Hoffman wrote: >> >>> Keith P. Boruff wrote: >>> >>>> Is there an FAQ available specific to this NG as I'm sure some of >>>> the list slicing questions I have have been asked before. > > Therefore I asked a question on why you want a *newsgroup* FAQ when it > sounds like you want a *Python* FAQ, so that I and others could > potentially be more helpful in answering your unasked question. Seems to me there is a slight misunderstanding here. Some newsgroups publish a FAQ, based on the questions that are asked in it. These FAQ are often related to the subject of the NG, not specifically the NG and its mechanics. It is advised, when someone wants to post in these kind of NG, to check if their question is not yet answered in the FAQ published by the NG on the subject. Therefore, I think the OP was checking if there was such a FAQ on Python published specifically in c.l.python besides the ones he already found on the web. From sybrenUSE at YOURthirdtower.com.imagination Wed Jul 20 03:30:36 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 20 Jul 2005 09:30:36 +0200 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <86psterxi3.fsf@bhuda.mired.org> Message-ID: Mike Meyer enlightened us with: >> I dislike gotos because it is too easy to inadvertently create >> infinite loops. <10 WINK; 20 GOTO 10> > > And it's impossible without them? I thought the same thing, but then I read it again and thought about the "inadvertently". As soon as you see a "while True", you _know_ it's going to loop forever. As soon as you see a "goto 10", you don't. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From spam.csubich+block at block.subich.spam.com Thu Jul 14 20:40:09 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 14 Jul 2005 20:40:09 -0400 Subject: Changing size of Win2k/XP console? In-Reply-To: <42d6cf32$0$16170$39db0f71@news.song.fi> References: <42d6bdd2$0$16170$39db0f71@news.song.fi> <42d6cf32$0$16170$39db0f71@news.song.fi> Message-ID: Sheeps United wrote: > I'm far from sure if it's the right one, but I think it could be > SetConsoleScreenBufferSize from Kernel32. Hrr, for some reason I have nasty > feeling in back of my head... That could also be totally wrong way of > approaching. I have the source code to a win32-console program lying around, and it uses SetConsoleScreenBufferSize from C++ to do just that. From cliff at develix.com Sun Jul 31 20:48:23 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 17:48:23 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <7x3bpuzf2n.fsf@ruckus.brouhaha.com> References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> <7xr7de5zoe.fsf@ruckus.brouhaha.com> <7x3bpuzf2n.fsf@ruckus.brouhaha.com> Message-ID: <1122857303.19618.207.camel@localhost.localdomain> On Sun, 2005-07-31 at 17:16 -0700, Paul Rubin wrote: > Cliff Wells writes: > > > It did last time I tried installing it, which was maybe 3-6 months ago. > > > Someone posted that it had been updated recently. > > > > Looking on SourceForge, I see that 2.4.2.4 had GTK2 builds and it's > > dated 2003-10-01. > > That's sort of interesting. I think I downloaded whatever was on > wxpython.org. Usually there will be a link to a couple different builds on wxpython.org. I can see where it would be pretty easy to grab the wrong one. > No this was definitely a GTK issue. I avoid OS upgrades because of > issues like what you describe. If I want a new OS, I buy a new hard > drive and install the new OS from scratch, or even buy a new computer. I usually keep /home on a separate partition. That lets me wipe / and do a fresh install without affecting my personal stuff. I will say that using apt/yum to upgrade works pretty well these days, as long as the jump isn't too far (i.e. more than one major release). Still, I too prefer the fresh install, just out of paranoia probably. Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From bdesth.quelquechose at free.quelquepart.fr Thu Jul 14 19:50:33 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 15 Jul 2005 01:50:33 +0200 Subject: Python and MySQL server In-Reply-To: References: Message-ID: <42d6f39b$0$28125$626a14ce@news.free.fr> Unknown a ?crit : > Python 2.4 > Linux kernel 2.6.12 > > Hi, > > 1. How do I make the following statement to search for all Strings I > input from console? > > for example, with the code below I need to enter %hello world% (yeah, > including the % symbols) to find all entries for hello world on the > tableName. But I want to set the % symbols on the code itself so I don't > have to input manually the % at the prompt. > > searchWhat = raw_input ('Search for : ') searchWhat = "%%%s%%" % raw_input ('Search for : ') You have to double the % symbol to escape it. You'd better be *very* careful with user input, specially when you use it like this: > cursor.execute('select * from tableName where contentField like > %s',(searchWhat)) Please consider checking and cleaning user inputs before using'em in a query. > 2. I'm entering data by copying and pasting. Much of the text is in > multiple lines and some formated sections such as paragraphs, > indentations, double lines and what not. > > How do I enter keep the formated text intact if entering from console? Launch a text-mode editor with a temp file name and read back that file if it exists once the editor is closed. Pseudo code: fname = create_a_name_that_dont_exists_yet() openEditor() # block until the editor is closed if os.path.file_exists(fname): text_to_insert = open(fname).read() # ... My 2 cents... From python at rcn.com Thu Jul 21 22:29:32 2005 From: python at rcn.com (Raymond Hettinger) Date: 21 Jul 2005 19:29:32 -0700 Subject: dictionary that discards old items References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> Message-ID: <1121999372.836621.190950@o13g2000cwo.googlegroups.com> [Will McGugan] > I need a collection class that behaves like a dictionary but when it > reaches 'n' items it discards the oldest item so that the length never > goes above 'n'. (Its for caching search results) import collections class Cache(dict): def __init__(self, n, *args, **kwds): self.n = n self.queue = collections.deque() dict.__init__(self, *args, **kwds) def __setitem__(self, k, v): self.queue.append(k) dict.__setitem__(self, k, v) if len(self) > self.n: oldk = self.queue.popleft() del self[oldk] # . . . # make similar modifications to setdefault, __delitem__, fromkeys # and other mutating methods as needed # Example c = Cache(3) for w in 'the quick brown fox jumped over the lazy dog'.split(): c[w] = w[:1].upper() print repr(c) From dvanvliet at 3dna.net Mon Jul 4 14:59:20 2005 From: dvanvliet at 3dna.net (Derek van Vliet) Date: 4 Jul 2005 11:59:20 -0700 Subject: importing pyc from memory? In-Reply-To: <42c97d97.525382369@news.oz.net> References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> <1120496836.806367.65780@z14g2000cwz.googlegroups.com> <42c97d97.525382369@news.oz.net> Message-ID: <1120503560.595831.184580@o13g2000cwo.googlegroups.com> I do have to do everything you describe here in the current implementation of my system. I realize that importing a pyc file and compiling a string results in two different things. This is okay though as I'm fairly sure this will still suit my needs. As I said, the file format I plan to store these compiled scripts in is proprietary, but it would be very comparable storing them in XML elements as CDATA. I'm hoping that this would allow me to import and run them, thereby removing the need for my app to compile scripts. From miki.tebeka at zoran.com Tue Jul 5 02:01:22 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 5 Jul 2005 09:01:22 +0300 Subject: wxPy + Py2Exe + sys.argv[0] In-Reply-To: <42C94C72.6090900@anonym.hu> References: <42C94C72.6090900@anonym.hu> Message-ID: <20050705060122.GH3876@zoran.com> Hello fowlertrainer, > Hi ! > > The problem that when I started the program from CMD, the sys.argv is > show the good path (in my machine the c:\dev\xxxx...) from Dialog1.py. > But when I compile it with Py2Exe, and try to start the exe, it has been > not found the hwinfo.ini file what store the setup informations of the > program. This is intensional, py2exe stores some modules in the zip files and want Python to find them first. > def LoadIniFile(): > s=os.path.dirname(sys.argv[0])+'/hwinfo.ini' > f=open(s,'r') > l=(f.read()).split('\n') > d={} > for s in l: > if s.find('=')<>-1: > sl=s.split('=') > sl[0]=sl[0].strip().lower() > sl[1]=sl[1].strip() > d[sl[0]]=sl[1] > return d > > So that folder is must be correct ! > > Why I get error ? What I can do if I want to use it as normal py ? I usually have something like the following in my code. from os.path import isfile, dirname from sys import path APPDIR = path[0] # Application directory if isfile(APPDIR): # py2exe APPDIR = dirname(APPDIR) HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From jlconlin at lanl.gov Mon Jul 11 11:45:26 2005 From: jlconlin at lanl.gov (Jeremy) Date: Mon, 11 Jul 2005 09:45:26 -0600 Subject: regular expression questions in Python Message-ID: I am (very) new top regular expressions and I am having a difficult time understanding how to do them. I have the following in my script: zaidsearch = r'''^ {5,}([\d]{4,5})(.\d{2,2}c)''' ZAIDSearch = re.compile(search, re.IGNORECASE) When I do: ZAID.search(...) then this works fine. I would like to write it as: zaidsearch = r'''^ {5,}([\d]{4,5}) #My comments (.\d{2,2}c) #More of my comments''' ZAIDSearch = re.compile(zaidsearch, re.VERBOSE) but this doesn't work. I get the following error: raise error, v # invalid expression sre_constants.error: nothing to repeat So I guess my question is: how do I use the VERBOSE option to make my regular expression easier to understand for a human? Secondly, how can I use both the VERBOSE and IGNORECASE options? Thanks, Jeremy From mage at mage.hu Wed Jul 27 08:04:15 2005 From: mage at mage.hu (Mage) Date: Wed, 27 Jul 2005 14:04:15 +0200 Subject: question about deleting records from mysql In-Reply-To: <42E7720E.90307@xit.net> References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> <42E7720E.90307@xit.net> Message-ID: <42E7783F.2040303@mage.hu> nephish wrote: >Simon Brunning wrote: > > > >>On 27 Jul 2005 04:29:33 -0700, nephish at xit.net wrote: >> >> >> >> >>>Hey there, >>>sorry , second question in as many days. >>>i am trying to do some stuff with MySQLdb and the thing is, i can >>>select records and such, but when i try to delete them, they dont >>>really go away. >>> >>> >>> >>> >>A fiver says you need to commit your changes. >> >> >> >> >> >ok, do i do that with cursor.commit() ? >thanks > > Yes, or maybe you should write a lightweight layer between the dbapi and your program which can turn on and off the autocommit by calling "commit" and "begin" as query. I did this in my pgsql layer. Using transactions every time is almost as bad as never using them. Mage From grante at visi.com Tue Jul 19 20:10:23 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 20 Jul 2005 00:10:23 -0000 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? References: <1121813534.868644.30590@g47g2000cwa.googlegroups.com> Message-ID: <11dr5jf8dba6h07@corp.supernews.com> On 2005-07-19, sp1d3rx at gmail.com wrote: > Chris, How would a wireless router show a signal to noise ratio? On a web page. > Especially if it's providing the signal? It receives as well. At least mine does. Data goes both in and out. -- Grant Edwards grante Yow! I feel real at SOPHISTICATED being in visi.com FRANCE! From steve at REMOVETHIScyber.com.au Sat Jul 2 21:43:54 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 11:43:54 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> Message-ID: On Fri, 01 Jul 2005 12:24:44 -0700, Devan L wrote: > With the exception of reduce(lambda x,y:x*y, sequence), reduce can be > replaced with sum, and Guido wants to add a product function. How do you replace: reduce(lambda x,y: x*y-1/y, sequence) with sum? Inquiring minds want to know. -- Steven. From paul_d_smith at x-hotmail.com Thu Jul 28 04:04:17 2005 From: paul_d_smith at x-hotmail.com (Paul D.Smith) Date: Thu, 28 Jul 2005 09:04:17 +0100 Subject: Create a variable "on the fly" References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> <42e7c390$0$446$626a14ce@news.free.fr> Message-ID: <42e89182$0$13699$ed9e5944@reading.news.pipex.net> Bruno, FYI, notes in-line... Cheers, Paul DS > > a look instantiate Python variables of the appropriate type. > > What do you mean "of the appropriate type" ? You want to typecast (eg. > from string to numeric) ? Then you need to know what env var must be > casted to what type ? Then you don't need to create variables 'on the fly' ? > > I must have missed something... Good point - my Python "nomenclature" is still in its infancy. The background is that I've inherited some historical Python scripts that need to be configured from a bash shell script (as these Python scripts are being integrated into a bigger system driven by shell scripts and with a pre-existing single "point-of-configuration") instead of the existing Pything config script. The existing Python script configures these parameters thus... PARM1='Fred' PARM2=12 ... So I could so the following... PARM1=os.environ['PARM1'] PARM2=os.environ['PARM2'] ... The problem is that this config file is almost certainly not complete (as the complete integration of all scripts has not been done) and I don't want to spend my life tweaking not one config file (the shell script), but two (the shell script and the Python script). Now I'm helped because in fact the parameters have a common format e.g. MY_PARM1... MY_PARM2... so I can define shell environment variables with the same names and then look for any parameter defined in the shell and named "MY_..." and instantiate the Python variable from that. What I'm left with is the following... 1. A shell script which I maintain. 2. A simple Python config which searches for all shell environment variables named "MY_..." and instantiates then as Python variables. 3. Historical scripts that run without me needing to spend time hunting down all the config variables and replacing them with os.environ['MY_...']. Agreed that long term this is not good practice, but short term it's a time save. From nospam at [127.0.0.1] Wed Jul 20 01:53:53 2005 From: nospam at [127.0.0.1] (Chris) Date: Wed, 20 Jul 2005 06:53:53 +0100 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? References: Message-ID: In article , Steven D'Aprano writes >On Tue, 19 Jul 2005 07:24:19 +0100, Chris wrote: >> Could anyone write a small program to log the Signal-to-Noise figures >> for a Netgear DG834 router? >Are you offering to pay somebody to do it, or just suggesting a project >for some Python programmer who is bored and looking for a small project to >work on out of love? Yes, Steven, the latter. Sometimes programmers need an idea for a project - and, for them, knowing that someone would actually value what they did might make it more fun for them. -- Chris From spam.csubich+block at block.subich.spam.com Sun Jul 31 11:53:20 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 31 Jul 2005 11:53:20 -0400 Subject: Thaughts from an (almost) Lurker. In-Reply-To: References: <1122794976.360827.171160@g49g2000cwa.googlegroups.com> Message-ID: Robert Kern wrote: > My experience with USENET suggests that there is always a steady stream > of newbies, trolls, and otherwise clueless people. In the absence of > real evidence (like traceable headers), I don't think there's a reason > to suspect that there's someone performing psychological experiments on > the denizens of c.l.py. Er... yes! Exactly! These are not the trolls you're looking for, move along. :) From bronger at physik.rwth-aachen.de Sun Jul 31 04:01:15 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 10:01:15 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: <873bpvqu9g.fsf@wilson.rwth-aachen.de> Hall?chen! Cliff Wells writes: > [...] > > The least headache for end users comes from properly packaging your > application. End users shouldn't need to worry about installing third > party packages (or even Python for that matter). Tools such as py2exe > and Inno installer make this pretty simple on Windows, and py2app on > OS/X accomplishes the same. Does py2exe work for all GUI libraries? It'll highly probably work with Tkinter, and I've read that it also works with pyGTK, but does it also work with wxPython or PyQt? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From bvande at po-box.mcgill.ca Thu Jul 7 04:03:14 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 07 Jul 2005 04:03:14 -0400 Subject: Do a "Python beginners e-mail list" exist? In-Reply-To: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> References: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> Message-ID: <42CCE1C2.6090409@po-box.mcgill.ca> Alessandro Brollo said unto the world upon 07/07/2005 03:24: > Far from a professional programmer, I'm simply a > newbie Python user. Two basic questions: > > 1. I don't want to post banal questions about Python > to main Python list. Does a "banal Python questions > list" or a "Python beginners list" exist? Check out the Tutor list Best, Brian vdB From duncan.booth at invalid.invalid Wed Jul 6 10:50:43 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Jul 2005 14:50:43 GMT Subject: Use cases for del References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Tom Anderson wrote: >> How about just getting rid of del? Removal from collections could be >> done with a method call, and i'm not convinced that deleting variables >> is something we really need to be able to do (most other languages >> manage without it). > > Arguing the case for del: how would I, in doing automated testing, > ensure that I've returned everything to a "clean" starting point in all > cases if I can't delete variables? Sometimes a global is the simplest > way to do something... how do I delete a global if not with "del"? > I generally find that unit tests force me to structure the code in a cleaner manner, e.g. to not use globals as much, but if you do need to delete a global you do it in exactly the same way as you delete anything: use the "del" statement: >>> x = 3 >>> def f(): global x del x >>> x 3 >>> f() >>> x Traceback (most recent call last): File "", line 1, in -toplevel- x NameError: name 'x' is not defined >>> Where I have used 'del' in a unit test it has been to delete local variables rather than globals. Specifically I wanted to ensure that some data structures were being torn down properly, so the test went something like this: setup: creates a weakref dictionary. teardown: asserts that the weakref dictionary is empty. then each test does: try: create something add it to the weakref dictionary then test it finally: use del to remove local variables force a garbage collection Without the del, when a test fails you get two failures, because the traceback information keeps the variables alive. From sjmachin at lexicon.net Wed Jul 13 22:22:44 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Jul 2005 12:22:44 +1000 Subject: Help - Classes and attributes In-Reply-To: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> Message-ID: <42d5cc75@news.eftel.com> rh0dium wrote: > Hi all, > > I believe I am having a fundamental problem with my class and I can't > seem to figure out what I am doing wrong. Basically I want a class > which can do several specific ldap queries. So in my code I would have > multiple searches. But I can't figure out how to do it without it > barfing.. > > The error is straightforward .. > > LDAP Version 2.0.8 > Traceback (most recent call last): > File "./ldap-nsc.py", line 62, in ? > l.search() > File "./ldap-nsc.py", line 40, in search > ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, > retrieveAttrs) > AttributeError: NSCLdap instance has no attribute 'search_s' > > > The code is also I believe straight forward.. > > import ldap > > class NSCLdap: > > def __init__(self,server="sc-ldap.nsc.com"): > who=""; cred="" > self.server=server > try: > print "LDAP Version", ldap.__version__ > l=ldap.open(server) > l.simple_bind_s(who, cred) > l.protocol_version=ldap.VERSION3 > except ldap.LDAPError, error_message: > print "Couldn't Connect to %s %s " % > (server,error_message) > > def search(self, baseDN="o=nsc.com", > retrieveAttrs=None,searchAttrs="cn=*klass*" ): > searchScope = ldap.SCOPE_SUBTREE > try: If you had bothered to do some elementary debugging, like "print repr(l)" here, just before the exception-triggering statement, .... > ldap_result_id = l.search_s(baseDN, searchScope, > searchAttrs, retrieveAttrs) > result_set = [] > while 1: > result_type, result_data = l.result(ldap_result_id, 0) > if (result_data == []): > break > else: > ## here you don't have to append to a list > ## you could do whatever you want with the > individual entry > ## The appending to list is just for > illustration. > if result_type == ldap.RES_SEARCH_ENTRY: > result_set.append(result_data) > print result_set > except ldap.LDAPError, error_message: > print "Errors on Search %s " % error_message > > def setBaseDN(self, baseDN="o=nsc.com"): > return baseDN > > if __name__ == '__main__': > > l = NSCLdap() > l.search() > > > I would love some pointers - clearly my code thinks that search_s is an > attribute of my class but it's not.. You are confusing the bejaysus out of yourself and your audience by using "l" as a name (1) at all (2) to represent two *different* things, one in script-global scope -- l = NSCLdap() -- and one in the __init__ method of your class -- l=ldap.open(server). Use two different sensible names; then your real problem should become apparent -- unless of course in the meantime some wally thinks it a good idea to prevent your attaining a clue yourself by spoon-feeding you. From varghjarta at gmail.com Mon Jul 25 00:37:10 2005 From: varghjarta at gmail.com (=?ISO-8859-1?Q?Varghj=E4rta?=) Date: Mon, 25 Jul 2005 12:37:10 +0800 Subject: Fire event when variable is Set/Get In-Reply-To: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> References: <1122264367.061487.3570@o13g2000cwo.googlegroups.com> Message-ID: Thank you! Wow, this might be exactly what I want! Thanks to the pythonness (syntax) the code might even be shorter then implementing it in C#! Gonna go and play around with this some more(now), and can't wait til I get home (there will be some massive code cleaning). I wonder why I've never come across this before, feels like i've googled alot these last weeks. Python has grown in my eyes. On 24 Jul 2005 21:06:07 -0700, tharaka wrote: > You are in luck because Python has "Properties" just like .NET. > > For details lookup the documentation of the built-in function > property(). I'll just paste it here: > > > property( [fget[, fset[, fdel[, doc]]]]) > > Return a property attribute for new-style classes (classes that derive > from object). > fget is a function for getting an attribute value, likewise fset is a > function for setting, and fdel a function for del'ing, an attribute. > Typical use is to define a managed attribute x: > > > class C(object): > def getx(self): return self.__x > def setx(self, value): self.__x = value > def delx(self): del self.__x > x = property(getx, setx, delx, "I'm the 'x' property.") > > > ... now u can use x like any variable and, python will get & set it > through the appropriate methods. Hope this answers your question. > > -- > http://mail.python.org/mailman/listinfo/python-list > From hancock at anansispaceworks.com Tue Jul 5 11:27:56 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 5 Jul 2005 10:27:56 -0500 Subject: What are the other options against Zope? In-Reply-To: <42C953FE.6030207@anvilcom.com> References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <42c8dd47$0$298$edfadb0f@dread12.news.tele.dk> <42C953FE.6030207@anvilcom.com> Message-ID: <200507051027.56715.hancock@anansispaceworks.com> On Monday 04 July 2005 10:21 am, phil wrote: > A data base with properties and methods. Cool. I am so sure I already said this. Well, I guess I typed too much else. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From nephish at xit.net Tue Jul 26 19:55:26 2005 From: nephish at xit.net (nephish at xit.net) Date: 26 Jul 2005 16:55:26 -0700 Subject: need some info on MySQL module. Message-ID: <1122422126.817344.207840@o13g2000cwo.googlegroups.com> Hey there, does anyone know where i can find some real documentation on the MySQLdb module? This thing is driving me nuts. all i can find on the internet is some brief tutorials. I need to know whats up with some of my stuff i even bought Programming Python by O'Reilly, out of over 1200 pages, and it only has a page or two dedicated to it. eeek. Thanks. <>< From spam.csubich+block at block.subich.spam.com Thu Jul 14 13:40:01 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 14 Jul 2005 13:40:01 -0400 Subject: threads and sleep? In-Reply-To: References: Message-ID: Jp Calderone wrote: > On 14 Jul 2005 05:10:38 -0700, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: > >> Andreas Kostyrka writes: >> >>> Basically the current state of art in "threading" programming doesn't >>> include a safe model. General threading programming is unsafe at the >>> moment, and there's nothing to do about that. It requires the developer >>> to carefully add any needed locking by hand. >> >> >> So how does Java do it? Declaring some objects and functions to be >> synchronized seems to be enough, I thought. > > > Multithreaded Java programs have thread-related bugs in them too. So it > doesn't seem to be enough. Like Python's model, Java's is mostly about > ensuring internal interpreter state doesn't get horribly corrupted. It > doesn't do anything for application-level state. For example, the Hrm... this would suggest the possibility of designing a metaclass, perhaps, that would ensure synchronous access to an object. Perhaps "wrap" the class in another, that gets and releases a mutex on any external get/set access (except, possibly, for a specified list of "asynchronous" data members and methods). This, of course, wouldn't elminate deadlocks, but that's a problem that arises from interaction from multiple objects, rather than within a single one. From rrr at ronadam.com Sun Jul 10 21:17:17 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 11 Jul 2005 01:17:17 GMT Subject: decorators as generalized pre-binding hooks In-Reply-To: <42d1813e.318841369@news.oz.net> References: <42d02c21.231516573@news.oz.net> <9s2Ae.227054$w15.137655@tornado.tampabay.rr.com> <42d1813e.318841369@news.oz.net> Message-ID: Bengt Richter wrote: > On Sun, 10 Jul 2005 05:35:01 GMT, Ron Adam wrote: >>So far they are fairly equivalent. So there's not really any advantage >>over the equivalent inline function. But I think I see what you are >>going towards. Decorators currently must be used when a function is >>defined. This option attempts to makes them more dynamic so that they >>can be used where and when they are needed. > > IMO part of the decorator benefit is clearer code, and also IMO the > @range_check and @default_value decorators succeed in that. The code > generated would presumably be the same, unless the exception capture > discussed further down were implemented. If you take the decorator at face value, it's clear. (In a sort of because I said so way.) But if you look in the decorator, it may be quite unclear. Ie.. it sort of sweeps the dirt under the rug. (IMO) The thing is, defining a decorator can be fairly complex compared to a regular function depending on what one is trying to do. >>How about if you make it optional too? >>@@keeplog log_of_interesting_values # if keeplog decorate. >>b = get_value(c,d) >> >>Just a thought. > > Yes, but that is too easy to do another way. Plus I want to reserve > '@@' for an AST-time decoration idea I have ;-) The @@ could be whatever, but a single @ could probably be used just as well. How about any line that begins with an @ is preparsed as sugar. And then create a simple sugar language to go along with it? But that would be compile time macros wouldn't it. ;-) >>When it comes to decorators, and now the with statements, I can't help >>but feel that there's some sort of underlying concept that would work >>better. It has to do with generalizing flow control in a dynamic way >>relative to an associated block. >> >>One thought is to be able to use a place holder in an expression list to >>tell a statement when to do the following block of code. > > it depends on scope and control aspects of what you mean by "block". By block I meant the indented following suite. No special scope rules that don't already currently exist in any 'if', 'while', or 'for' suite. > But I doubt if we have much chance of introducing something is one > more bf in the storm of "with" ideas that have already been > discussed. I'd like to think until 2.5 is released that there's still a chance that something better could come along. But it would have to be pretty darn good I expect. > They strike me as a kind of macro idea where the only substitution argument > is the block suite that follows, which IMO is a severe limitation on both > the macro idea and the use of blocks ;-) I'm not sure it's macro or not. Maybe it's a flow control parser statement? Does that sound any better than macro? ;-) >>I like the place holders because I think they make the code much more >>explicit and they are more flexible because you can put them where you >>need them. > > Yes, but if you want to go that way, I'd want to have named place holders > and be able to refer to arbitrary things that make sense in the context. From what I've seen so far, there's a lot of resistance to real run time macro's. So I don't expect them any time soon. The mechanism I suggested doesn't store code or name it. So it's not a macro, it's closer to a while that conditionally runs the body, but in this case the condition is when instead of if. It's a different concept that I think can compliment the language without being too complex. Named macros make it even more useful. Here I used 'this' as the keyword to indicate when the suite is to be done. So it's a do-this-suite statement. do f = opening(filename); try this; finally f.close(): suite Now using "Sugar" language! ;-) # Create sugar @with_opened = "opening(%s); try this; finally f.close()" do f = $with_opened%('filename'): # $ indicates sugar suite I used Pythons % operator as it already exists and works fine in this situation. Easy to implement as well. Hmm.. not sure how to apply this to a decorator. Lets see... Working it out... # function to use def check_range(x): if x in range(10,25): return raise RangeError # or what ever is suitable # Make the decorator with sugar @checkrange = "%s %s check_range(%s)" Parses on spaces as default? $checkrange% # Use the following line here x = 24 # since nothing given after the % Which will results in... x = check_range(24) There should be a way to specify an additional argument I think. The exact rules would need to be worked out. It also might be a good way to test sugar ideas before they become part of the language. >>>orthogonal-musing-ly ;-) >> >>"Orthogonal is an unusual computer language in which your program flow >>can go sideways. In actuality in can go in just about any direction you >>could want." >> >> http://www.muppetlabs.com/~breadbox/orth/ > > Interesting. And an implementation from our own Jeff Epler? I didn't see that. LOL Cheers, Ron > Regards, > Bengt Richter From fperez.net at gmail.com Thu Jul 7 17:51:28 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 07 Jul 2005 15:51:28 -0600 Subject: question about introspection using inspect module References: <5vll4ihfvt.fsf@akron.bmi.ohio-state.edu> <5vr7eafimo.fsf@akron.bmi.ohio-state.edu> Message-ID: Benjamin Rutt wrote: > Fernando Perez writes: > >> I certainly don't want to discourage you from learning about python >> introspection, it's one of the most fun aspects of the language. But just >> as an FYI, the pydoc system already does much of what you have in mind, at >> least if I'm reading your description correctly: >> >> planck[/tmp]> pydoc -p 12345 >> pydoc server ready at http://localhost:12345/ > > thanks, I'm aware of that actually, and seeing all the information > available there was inspiring to me. OK, you never know :) > what I am actually trying to do is to build a database of Python > modules. so then later, I can write a tool in my favorite editor > (Emacs) to invoke some forms of completion against this database > (e.g. os.remov or socket. to see a list of all socket module > definitions). well, I have no idea if this will be of any use, but it might: http://cedet.sourceforge.net/ I use their speedbar quite a bit, but it sounds from the description like they have some other fancier tools. I'd be quite curious to know if they play nicely with python (they mention C++ explicitly), and how much value they add. Let me know if you are familiar with them, or if you end up investigating these further. Cheers, f From pydecker at gmail.com Tue Jul 26 17:28:12 2005 From: pydecker at gmail.com (Peter Decker) Date: Tue, 26 Jul 2005 17:28:12 -0400 Subject: GUI - Windows: Where to get started In-Reply-To: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: On 26 Jul 2005 12:44:13 -0700, Ernesto wrote: > Would anyone know a good place to start for learning how to build > simple GUI's in Windows XP? I just want users to be able to select a > few parameters from a pull-down menu, then be able to run some batch > files using the parameters from the pull down menus. I would also need > a "Browse" menu, so users could point to a place on the local disc (ie > C:\PointSystemHere). Can anyone give a noob some tips? THANKS!!! wxPython is (IMO) the best-looking and most flexible UI toolkit out there, but the code can be fairly un-Pythonic. I've started using Dabo, which includes a wrapper around wxPython that makes UI coding clean and very Pythonic. While Dabo is an entrie application framework, you can just use the UI stuff if you want. There is also a Windows runtime that will install Python, wxPython, Dabo, and everything else you need to create and run Dabo apps. No need to hassle with multiple installs just to try it out. You can get Dabo at http://dabodev.com -- # p.d. From dalke at dalkescientific.com Fri Jul 29 11:38:32 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 29 Jul 2005 15:38:32 GMT Subject: can list comprehensions replace map? References: Message-ID: Peter Otten wrote: > Combining your "clever" and your "elegant" approach to something fast > (though I'm not entirely confident it's correct): > > def fillzip(*seqs): > def done_iter(done=[len(seqs)]): > done[0] -= 1 > if not done[0]: > return > while 1: > yield None > seqs = [chain(seq, done_iter()) for seq in seqs] > return izip(*seqs) Ohh, that's pretty neat passing in 'done' via a mutable default argument. It took me a bit to even realize why it does work. :) Could make it one line shorter with from itertools import chain, izip, repeat def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return [] return repeat(None) seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Go too far on that path and the code starts looking likg from itertools import chain, izip, repeat forever, table = repeat(None), {0: []}.get def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 return table(done[0], forever) return izip(*[chain(seq, done_iter()) for seq in seqs]) Now add the performance tweak.... def done_iter(done=[len(seqs)], forever=forever, table=table) Okay, I'm over it. :) Andrew dalke at dalkescientific.com From cliff at develix.com Sun Jul 31 02:28:26 2005 From: cliff at develix.com (Cliff Wells) Date: Sat, 30 Jul 2005 23:28:26 -0700 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> <7xmzo4nmf0.fsf@ruckus.brouhaha.com> Message-ID: <1122791306.19618.55.camel@localhost.localdomain> On Sat, 2005-07-30 at 16:52 -0700, Bugs wrote: > Cliff Wells wrote: > > > > But how stable is GTK on systems such as Windows and OS/X? That has > > been what has kept me from using it. Most GTK apps I've used on Windows > > (including the venerable GIMP) are nowhere near as stable as their Linux > > counterparts (although this may not be entirely the fault of GTK). > > Also, GTK on OS/X requires Fink, which is a pretty hefty requirement to > > place on an end user. > > > > wxWidgets only uses GTK on Linux. On Windows and OS X it uses native > widgets where possible. You missed my point. I'm advocating wxPython over PyGTK for this reason. I'm quite aware of how wxPython functions. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From jeremy at emperorlinux.com Wed Jul 27 13:24:32 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Wed, 27 Jul 2005 13:24:32 -0400 Subject: Bash Helper Script Message-ID: <1122485073.4150.9.camel@localhost.localdomain> I wrote something real quick this morning that I thought might be somewhat useful to someone else. It's just a bash script that lets you do a few things do a "project directory" (in my case, python subversion projects) in a decently sensible way. Usage is: # cp pypadmin MyProjectDir/pypadmin # ./pypadmin skel # ./pypadmin clean # ./pypadmin package # ./pypadmin publish The actual targets are kept in ./.pypadmin/NAME, where NAME is one of: - package_name (name of the tarball that will be created) - publish_host (name of the host to scp to) - clean_files (globs of filenames to delete when clean is invoked) Running ./pypadmin skel will create a skeleton layout into which you put these values. For instance: # ./pypadmin skel # echo "foo.tar.bz2" > .pypadmin/package_name # echo "*.pyc" > .pypadmin/clean_files # echo "emperorlinux.com:~" > .pypadmin/publish_host -------------- next part -------------- A non-text attachment was scrubbed... Name: pypadmin Type: application/x-shellscript Size: 2168 bytes Desc: not available URL: From dalke at dalkescientific.com Fri Jul 22 13:30:13 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 22 Jul 2005 17:30:13 GMT Subject: Difference between " and ' References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: Fran?ois Pinard wrote: > There is no strong reason to use one and avoid the other. Yet, while > representing strings, Python itself has a _preference_ for single > quotes. I use "double quoted strings" in almost all cases because I think it's easier to see than 'single quoted quotes'. Andrew dalke at dalkescientific.com From peter at somewhere.com Mon Jul 4 06:14:40 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 04 Jul 2005 12:14:40 +0200 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? In-Reply-To: <1120398483.415818.95360@o13g2000cwo.googlegroups.com> References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> <1120368681.573445.199710@g44g2000cwa.googlegroups.com> <1120371274.448543.145890@g43g2000cwa.googlegroups.com> <1120398483.415818.95360@o13g2000cwo.googlegroups.com> Message-ID: George Sakkis schrieb: > Given that the latest 2.x python will be 2.9 Why not 2.13 or 2.4711? Version strings are sequences of arbitrary integers separated by dots and not decimal numbers, or are they? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From cam.ac.uk at mh391.invalid Sun Jul 31 11:27:01 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 31 Jul 2005 16:27:01 +0100 Subject: keylogger in Python In-Reply-To: References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> Message-ID: Fran?ois Pinard wrote: > Surely on Linux, logging keys under X-Windows or under virtual terminals > are quite different matters. Let me share a related experience for > virtual terminals. I once had to rush the port on Linux a few QNX > applications, written in C, which were using the QNX term library > for input and display. In console mode, the QNX keyboard is richer > than the Linux one. As users wanted to retain the _exact_ keyboard > functionality, I saw no choice but reading raw scan codes on the Linux > side. So, I wrote a term library emulator as a thin C layer, which was > itself using a Python module (Python was to be transparently embedded by > the emulated library) for doing the bulk of keyboard processing. You think this is a suitable beginner project? And for that matter, it doesn't sound like you were doing keylogging, as it is usually understood to mean globally logging keypresses, no matter the application being presented to the user. -- Michael Hoffman From http Sat Jul 16 21:30:47 2005 From: http (Paul Rubin) Date: 16 Jul 2005 18:30:47 -0700 Subject: secure uploading References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> <7x4qauaccl.fsf@ruckus.brouhaha.com> <1121563713.124461.230540@g47g2000cwa.googlegroups.com> Message-ID: <7xoe922p88.fsf@ruckus.brouhaha.com> "macaronikazoo" writes: > well I want a script to upload something automatically, so i need a > python script to do that for me. my hoster has ssl enabled on their > server and I have generated a key. but now I need to know how to > upload something using ssl to the server. how to I ftp something to > the server using ssl? Ftp is not usually done over ssl. Usually you'd use http over ssl. From richie at entrian.com Mon Jul 4 04:02:14 2005 From: richie at entrian.com (Richie Hindle) Date: Mon, 04 Jul 2005 09:02:14 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <3ih84nFlkegqU1@individual.net> <1120230975.207574.136930@f14g2000cwb.googlegroups.com> Message-ID: [Chan] > T can be silent in England too .. > > frui' > cricke' [Stephen] > Both of those words (fruit and cricket) have the letter T sounded. > > Stephen (Nationality: English). Not necessarily - in my native accent they'd be replaced with glottal stops. Richie (Nationality: West Yorkshire 8-) (Having a daughter has improved my speech - I'm much more careful about enunciating my words properly so that she doesn't pick up my bad habits.) -- Richie Hindle richie at entrian.com From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 18 11:25:23 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 18 Jul 2005 17:25:23 +0200 Subject: re.IGNORECASE and re.VERBOSE In-Reply-To: References: Message-ID: <3k1vv3Fs9jv3U1@individual.net> Simon Brunning wrote: > On 7/18/05, Jeremy wrote: >> I am using regular expressions and I would like to use both >> re.IGNORECASE and re.VERBOSE options. I want to do something like the >> following (which doesn't work): >> >> matsearch = r'''^\ {0,4}([mM]\d+) ''' >> MatSearch = re.compile(matsearch, re.VERBOSE, re.IGNORECASE) > > MatSearch = re.compile(matsearch, re.IGNORECASE + re.VERBOSE) While this works when you are only combining flags, the general way of handling flags (= bit-fields) is with the three bit-wise operators '^', '&' and '|'. Reinhold From rkern at ucsd.edu Thu Jul 28 16:21:09 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 13:21:09 -0700 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Asad Habib wrote: > What, do you not consider yourself a professional? Not really, no. > Just because you are in > academia does not justify attacking people on a mailing list and then > justifying your attack with Harter's quote! Uh, it was a joke. A self-denigrating joke. I was calling *myself* a "vagabond." I even had a smiley! And the .sig quote has nothing to do with anything. > Life is more than a quote - > look outside your academic cocoon and you will realize what I mean. Thank G-d my irony meter is under warranty. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mraptor at gmail.com Sun Jul 10 10:20:34 2005 From: mraptor at gmail.com (raptor) Date: 10 Jul 2005 07:20:34 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: <1121005233.992711.141640@z14g2000cwz.googlegroups.com> I think u are wrong.. I think perl is much more exrpressive in semantics than Python.. From newsgroups at jhrothjr.com Fri Jul 22 12:55:13 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 22 Jul 2005 10:55:13 -0600 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <11e297jkf6i5bfa@news.supernews.com> "Daniel Dittmar" wrote in message news:dbr79q$ftg$1 at news.sap-ag.de... > Duncan Booth wrote: >> I would have expected a path object to be a sequence of path elements >> rather than a sequence of characters. > > Maybe it's nitpicking, but I don't think that a path object should be a > 'sequence of path elements' in an iterator context. > > This means that > > for element in pathobject: > > has no intuitive meaning for me, so it shouldn't be allowed. However, a path as a sequence of characters has even less meaning - I can't think of a use, while I have an application where traversing a path as a sequence of path elements makes perfect sense: I need to descend the directory structure, directory by directory, looking for specific files and types. John Roth > > Daniel From cam.ac.uk at mh391.invalid Wed Jul 27 14:39:59 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 27 Jul 2005 19:39:59 +0100 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: David Isaac wrote: > Newbie question: > > I have been generally open to the proposal that list comprehensions > should replace 'map', but I ran into a need for something like > map(None,x,y) > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > info from x. How do I do this as a list comprehension? (Or, > more generally, what is the best way to do this without 'map'?) It ain't broke so I'd stick with what you're doing. Even if map() is removed as a builtin, it will surely stick around in a module. -- Michael Hoffman From ptmcg at austin.rr.com Mon Jul 25 17:49:35 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Jul 2005 14:49:35 -0700 Subject: pyparsing 1.3.2 released In-Reply-To: <42e55901$1@news.eftel.com> References: <42e55901$1@news.eftel.com> Message-ID: <1122328175.251952.19000@g43g2000cwa.googlegroups.com> Garn! Twa' the de'ils wairk! I wad be laith to misquo' the Sco'ish Bard! I was trying to make sure I spelled "a-gley" - I lapsed into the common, but incorrect, quotation. (http://www.robertburns.org/works/75.shtml) Thanks! -- Paul From ivanlan at pauahtun.org Fri Jul 8 22:35:43 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Fri, 08 Jul 2005 20:35:43 -0600 Subject: Codecs Message-ID: <42CF37FF.D660865F@pauahtun.org> Hi All-- As far as I can tell, after looking only at the documentation (and not searching peps etc.), you cannot query the codecs to give you a list of registered codecs, or a list of possible codecs it could retrieve for you if you knew enough to ask for them by name. Why not? It seems to me that if I want to try to read an unknown file using an exhaustive list of possible encodings, the best place to keep the most current list is the codec registry itself, not in the documentation for the codec module. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From thorsten at thorstenkampe.de Thu Jul 14 05:17:10 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 14 Jul 2005 10:17:10 +0100 Subject: all possible combinations References: <1121277937.a2a3097d7c150f1b8a3f41a21a9f2b25@teranews> Message-ID: * Thomas Bartkus (2005-07-13 20:20 +0100) > "George Sakkis" wrote in message > news:1121277937.a2a3097d7c150f1b8a3f41a21a9f2b25 at teranews... >> "rbt" wrote: >> >>> Say I have a list that has 3 letters in it: >>> >>> ['a', 'b', 'c'] >>> >>> I want to print all the possible 4 digit combinations of those 3 >>> letters: >>> >>> 4^3 = 64 >> >> >> It's actually 3^4 = 81 (3 candidates/choice ** 4 choices) > > Yes. You get a cigar! > > Someone else (Jack Diederich) also mentioned "This is called a cartesian > product, ..." > Right again. In set theory it's called "cartesian product" while in combinatorics it's called "variation with repetition". There is some "die-hard" terminology confusion about permutations, combinations and variations (see [1] for example). (luckily at least most of the Python "officials" (GvR and Frederik Lundh) seem to agree about this terminology) Thorsten [1] http://groups-beta.google.com/group/comp.lang.python/msg/dea80dec0192eda6?hl=en& From fuzzyman at gmail.com Wed Jul 6 09:02:15 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jul 2005 06:02:15 -0700 Subject: Good starterbook for learning Python? In-Reply-To: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: <1120654935.486354.75550@g47g2000cwa.googlegroups.com> A book that will stay useful as a referene *after* you've used it to learn is 'Programming Python'. Best Regards, Fuzzy http://www.voidspace.org.uk/python From anton.vredegoor at gmail.com Fri Jul 22 08:31:26 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 22 Jul 2005 05:31:26 -0700 Subject: Python on a public library computer Message-ID: <1122035486.585382.15370@g44g2000cwa.googlegroups.com> This is about how to start a Python interpreter on a very locked down library computer. Some time ago I started a thread about it.(Google won't let me reply to older topics so I'm starting a new topic with the same title) A few days ago I found a Jython console applet that can be run from a webpage: http://tams-www.informatik.uni-hamburg.de/applets/jython/primacheck.html This opens a webpage (well, maybe after some editing, I can't get google to display this link on the same line) which after some time aks the user to sign an applet which then turns out to be a complete Jython editor and interpreter! I'm looking for the sourcecode of a project like this so that I can host such a page myself and include more modules. Can anyone reach the author or has anyone written something like it and is willing to share the code? Alternatively can someone give me some tips about how to write it myself? Currently I'm at the stage where I can compile and run the examples (and the applets!) on the Jython homepage. I'm still wondering about how to sign applets. Maybe the interpreter could be done by using the code.py module from Jython itself and just redirect stdin and stdout to an applet? Anton p.s. John Lee: You remembered correctly, such a thing exists. From jeethurao at gmail.com Thu Jul 21 21:21:53 2005 From: jeethurao at gmail.com (jeethu_rao) Date: 21 Jul 2005 18:21:53 -0700 Subject: Returning histogram-like data for items in a list References: <1121991583.d3afc1984aea914bde79a8c890963f28@teranews> Message-ID: <1121995313.145791.167950@o13g2000cwo.googlegroups.com> Adding to George's reply, if you want slightly more performance, you can avoid the exception with something like def hist(seq): h = {} for i in seq: h[i] = h.get(i,0)+1 return h.items() Jeethu Rao From gustavo at niemeyer.net Tue Jul 19 16:52:56 2005 From: gustavo at niemeyer.net (Gustavo Niemeyer) Date: Tue, 19 Jul 2005 17:52:56 -0300 Subject: [ANN] python-dateutil 1.0 Message-ID: <20050719205256.GA20755@burma.localdomain> Changes since 0.9 ----------------- * Fixing parsing of XXhXXm formatted time after day/month/year has been parsed. * Adding patch by Jeffrey Harris optimizing rrule.__contains__. What is it? ----------- The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. Features -------- * Computing of relative deltas (next month, next year, next monday, last week of month, and a lot more); * Computing of relative deltas between two given date and/or datetime objects; * Computing of dates based on very flexible recurrence rules (every month, every week on Thursday and Friday, every Friday 13th, and a *LOT* more), using a superset of the iCalendar RFC specification. Parsing of RFC strings is supported as well. * Generic parsing of dates in almost any string format; * Timezone (tzinfo) implementations for tzfile(5) format files (/etc/localtime, /usr/share/zoneinfo, etc), TZ environment string (in all known formats), iCalendar format files, given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, UTC timezone, and Windows registry-based timezones. * Internal up-to-date world timezone information based on Olson's database. * Computing of Easter Sunday dates for any given year, using Western, Orthodox or Julian algorithms; * More than 400 test cases. Where to get it? ---------------- https://moin.conectiva.com.br/DateUtil -- Gustavo Niemeyer http://niemeyer.net From dirk.dierickx at liamg.moc Mon Jul 4 05:21:06 2005 From: dirk.dierickx at liamg.moc (dirk dierickx) Date: Mon, 04 Jul 2005 11:21:06 +0200 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> Message-ID: On Sun, 03 Jul 2005 17:35:16 +0100, anthonyberet wrote: > I see lots of alternate IDEs etc, but which would allow me the simple > interface that I have described? - I really don't know about IDEs in > general, and I suspect I would be out of my depth with one of those. Eclipse and pydev are good. for testing out small routines you can use ipython, which is great. -- If you tell the truth you don't have to remember anything. -- Mark Twain From peter at engcorp.com Mon Jul 18 21:33:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 21:33:28 -0400 Subject: Threads: Issue and suggestion required In-Reply-To: References: Message-ID: Sandeep Arya wrote: > My query is. Is this possible that my main thread and my newly born > thread will execute their task simultaneously/parallel. (I read that > Python interpretor allows only one thread execution at a time. Using its > global lock. And switch among active thread based on time set by > setSwitchTime() function.. Is this correct?) Where did you see something about a setSwitchTime() function? Anyway, the statement about Python allowing "only one thread execution at a time" is wrong (allowing for the possibility of misunderstanding given that it's grammatically incorrect, so you might have meant something other than what I understand it as). By definition, threads simulate "parallel units of execution", so certainly threads (in almost any system) appear to execute simultaneously. In practice, of course, if you have only a single CPU then only one thing at a time can be happening (things like interrupts aside), and in an interpreter like Python's the same thing applies at a higher level: only one "bytecode" instruction at a time can be executing. Nevertheless, threads in Python certainly "appear" to execute in parallel, whether you have two or ten, and the details are generally transparent at the level you are interested in... > I just wannn know what is lifetime of thread. A threads runs until it ends... > As I was planning to > implement one function such that: > > 1.0 function starts > 2.0 create socket > 3.0 Open socket > 4.0 Do whatever task to do > 5.0 Close socket > 6.0 Function ends > > I wanna know that if i assign such above mentioned function to > thread::run then will the thread die after step 6.0 above i.e. function > ends. Basically that is correct. Anyway, threads in Python are trivial to play with, even at the interactive prompt, so why not just try them out and see how things go? -Peter From uval at rz.uni-karlsruhe.de Thu Jul 7 15:12:40 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Thu, 07 Jul 2005 21:12:40 +0200 Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] In-Reply-To: References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: > Am I just weird? I feel the same way about where to use lambda's and where *not* I come from C and C++ background and defining a function at the top level (no nested functions) would always require good reasons function name has to be remembered, to put it in other words it has to be added in a mental list of available function and writing a 2 liner function would only cause call overhead (if not inlined) this may be the reason why "def" feels to me to have more weight as "lambda" usually you define lambda and forget it, no wasted time to find proper name, which may also pollute the namespace I find it more clear solution, it's concise From skip at pobox.com Tue Jul 26 12:39:09 2005 From: skip at pobox.com (skip at pobox.com) Date: Tue, 26 Jul 2005 11:39:09 -0500 Subject: Emacs skeletons In-Reply-To: References: Message-ID: <17126.26413.646330.320994@montanaro.dyndns.org> Michael> Does anyone have any Emacs skeletons they find useful for Michael> Python? What's an "Emacs skeleton"? Skip From cam.ac.uk at mh391.invalid Wed Jul 6 20:55:57 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 07 Jul 2005 01:55:57 +0100 Subject: Inheritance/Late Private Binding In-Reply-To: References: Message-ID: Jeremy Moles wrote: > Forgive me if this topic has been brought up before, but I was curious > as to why I was getting this behavior and was hoping someone > knowledgeable could explain. :) What behavior? > I "feel" like even without the explicit call to a simple base ctor(), > mangling should still happen correctly. This doesnt, however, seem to be > the case... How is mangling happening incorrectly? Functions in base classes that are overridden by subclasses aren't called implicitly. Also, I think using the term "ctor()" is confusing since you don't seem to have anything callable named ctor. As for the constructor, just call it __init__, it will avoid confusion with __new__. -- Michael Hoffman From diesch at spamfence.net Fri Jul 22 09:45:59 2005 From: diesch at spamfence.net (Florian Diesch) Date: Fri, 22 Jul 2005 15:45:59 +0200 Subject: wxPythin installation woes References: <1121939845.672075.122220@z14g2000cwz.googlegroups.com> <1121953932.310914.241710@f14g2000cwb.googlegroups.com> Message-ID: <20050722134559.1DE3.0.NOFFLE@dieschf.news.arcor.de> linuxfreak wrote: > > Sybren Stuvel wrote: >> linuxfreak enlightened us with: >> > Turns out that libstdc++.so.5 is needed but I checked and i see >> > that libstdc++.so.6 is installed on my system. >> >> On my system (Ubuntu, based on Debian), I can have multiple versions >> of libstdc++ installed at the same time. > > Does anyone know if the same can be done in fedora distributions??? Of course it can. Read the Program Library HOWTO or ask in a linux group. Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From rkern at ucsd.edu Mon Jul 11 15:43:28 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Jul 2005 12:43:28 -0700 Subject: ImportError: No module named numarray In-Reply-To: <20050711140654.34220.qmail@web50302.mail.yahoo.com> References: <20050711140654.34220.qmail@web50302.mail.yahoo.com> Message-ID: enas khalil wrote: > > when i write a code to import some module like the following : > > > from nltk.probability import ConditionalFreqDist > > I got the error : > > Traceback (most recent call last): > File "C:\Python24\toky.py", line 1, in -toplevel- > from nltk.probability import ConditionalFreqDist > File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, > in -toplevel- > import types, math, numarray > ImportError: No module named numarray > > can you please tell me the cause I already did. You need to install numarray. http://www.stsci.edu/resources/software_hardware/numarray -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From john at castleamber.com Tue Jul 19 12:43:38 2005 From: john at castleamber.com (John Bokma) Date: 19 Jul 2005 16:43:38 GMT Subject: Xah's edu corner: on Microsoft hatred References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: "Malcolm" wrote: > > "John Bokma" wrote >> A typical Xah Lee posting... wake me up when he is able to write a >> single post that makes and sense, and doesn't contain fuck or similar >> words. >> > Obscene language isn't acceptable on comp.lang.c. > > It is an international group, and what might be acceptable in America > may be considered totally offensive, maybe even illegal, elsewhere. Then you are going to have a hard time with Xah Lee, since he thinks it makes the message more clear. -- John Small Perl scripts: http://johnbokma.com/perl/ Perl programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From http Sat Jul 30 04:10:30 2005 From: http (Paul Rubin) Date: 30 Jul 2005 01:10:30 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <7x8xzoogsp.fsf@ruckus.brouhaha.com> D H writes: > where fdel = def (self): > ........... > As you can see, it doesn't save much over the traditional way since > you have to name the "anonymous" lambdas anyway. It saves polluting the surrounding namespace with superfluous variables that aren't going to be used again. From Gov at mailinator.com Mon Jul 11 12:25:25 2005 From: Gov at mailinator.com (gov) Date: 11 Jul 2005 09:25:25 -0700 Subject: Legacy data parsing In-Reply-To: References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: <1121099125.468774.23250@g43g2000cwa.googlegroups.com> Actually, we receive the data in the form of a text file. The original data is sent from an IBM mainframe then to Ottawa where it is captured by an "SNA Print Server that receives the VPS print jobs, writes them to disk and then runs a PERL script program on the disk file. This PERL script program scans the file's VPS banner page for key words (e.g. JobName, Destination, Form) and then creates a Plain Text and a Rich Text Format (RTF)." This system is available Nationally for every region in Canada. It is unfortunate that our government has been so slow in updating such an old process. Since I don't really know (or have access to) the inner workings of the mainframe or the conversion process, I can't really do much there. The reason why I don't wish to simply replace the printer simply convert it so it can be used on newer printers is because the data will also be used to automate tasks (such as creating form letters to clients). From guy.lateur at b-b.be Wed Jul 6 06:40:53 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Wed, 06 Jul 2005 10:40:53 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: Ok, we didn't have the IMAP service running; we do now (no SSL). Connecting to the server is not a problem anymore, but logging in is. It works with the administrator account, but not with my personal account. We have restricted access to all machines in 10.0.0.0/255.255.255.0, which includes my machine. My password is empty (yeah, I know..). Could that be the problem? I'm using this: pw = '' Thanks, g From martin.witte at gmail.com Mon Jul 11 07:18:30 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 11 Jul 2005 04:18:30 -0700 Subject: __eq__ on a dict In-Reply-To: References: Message-ID: <1121080710.869704.31180@g49g2000cwa.googlegroups.com> These methods are documanted here: http://docs.python.org/ref/customization.html From gh at ghaering.de Fri Jul 8 19:29:30 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 09 Jul 2005 01:29:30 +0200 Subject: psycopg simplest problem In-Reply-To: References: <1110592231.853484.197370@z14g2000cwz.googlegroups.com> Message-ID: <42CF0C5A.2060703@ghaering.de> Glauco wrote: > [...] > Gerhard thank you very much, this example explain me some idea, but > anyway don't resolve the core question. > In you example when dateVal is a None or textVal is none. > argument x must be DateTime, not None. > so i must manipulate for the empty string or None cases No, you don't. If you leverage the two-parameter form of .execute(many), your Python DB-API module will handle the None => NULL case for you transparently. -- Gerhard From gsakkis at rutgers.edu Sun Jul 3 10:50:09 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Jul 2005 07:50:09 -0700 Subject: math.nroot [was Re: A brief question.] References: Message-ID: <1120402209.357781.108970@o13g2000cwo.googlegroups.com> "Steven D'Aprano" wrote: > Unfortunately, floating point maths is a bit of a black art. Try this > simple calculation: > > py> 4.0/3 - 5.0/6 > 0.49999999999999989 > > Should be 0.5 exactly. > > Many numbers which you can write exactly in decimal cannot be > stored exactly in floating point. Even something as simple as one tenth > 0.1 doesn't have an exact representation in binary: > > py> 1.0/10 > 0.10000000000000001 Given that 0.5 *can* be represented exactly in binary (try 0.3/0.6), your first example illustrates something worse about floating point arithmetic: not only many decimal numbers cannot be represented exactly as binary floating point, but that the kind and the order of operations in arithmetic expressions affects the accuracy of the result. *Even worse* than that, errors can be accumulated over a sequence of operations, so that even if each individual error is typically very small, the overall error might be non-trivial. There's a whole area studying the analysis and control of error in floating point arithmetic so it's not quite black art for everyone; e.g. see http://docs.sun.com/source/806-3568/ncg_goldberg.html, http://http.cs.berkeley.edu/~demmel/cs267/lecture21/lecture21.html for more. George From steven.bethard at gmail.com Tue Jul 12 14:06:54 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jul 2005 12:06:54 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <42d0c704.271167688@news.oz.net> References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> <1120963325.227725.123030@g43g2000cwa.googlegroups.com> <42d0c704.271167688@news.oz.net> Message-ID: Steven Bethard wrote: > py> def ge(items): > ... return (item for item in items if item) > ... Bengt Richter wrote: > >>> dis.dis(ge) > 2 0 LOAD_CONST 1 ( at 02EE4FA0, file "", line 2>) > 3 MAKE_FUNCTION 0 > 6 LOAD_FAST 0 (items) > 9 GET_ITER > 10 CALL_FUNCTION 1 > 13 RETURN_VALUE [snip] > >>> dis.dis(ge.func_code.co_consts[1]) > 2 0 SETUP_LOOP 28 (to 31) > 3 LOAD_FAST 0 ([outmost-iterable]) > >> 6 FOR_ITER 21 (to 30) > 9 STORE_FAST 1 (item) > 12 LOAD_FAST 1 (item) > 15 JUMP_IF_FALSE 8 (to 26) > 18 POP_TOP > 19 LOAD_FAST 1 (item) > 22 YIELD_VALUE > 23 JUMP_ABSOLUTE 6 > >> 26 POP_TOP > 27 JUMP_ABSOLUTE 6 > >> 30 POP_BLOCK > >> 31 LOAD_CONST 0 (None) > 34 RETURN_VALUE Outstanding. Thanks a lot! For comparison, here's the relevant dis.dis output for list comprehensions. py> def lc(items): ... return [item for item in items if item] ... py> dis.dis(lc) 2 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_FAST 1 (_[1]) 7 LOAD_FAST 0 (items) 10 GET_ITER >> 11 FOR_ITER 24 (to 38) 14 STORE_FAST 2 (item) 17 LOAD_FAST 2 (item) 20 JUMP_IF_FALSE 11 (to 34) 23 POP_TOP 24 LOAD_FAST 1 (_[1]) 27 LOAD_FAST 2 (item) 30 LIST_APPEND 31 JUMP_ABSOLUTE 11 >> 34 POP_TOP 35 JUMP_ABSOLUTE 11 >> 38 DELETE_FAST 1 (_[1]) 41 RETURN_VALUE Interestingly, the LC code and the code of a GE's "generator-expression" code object look quite similar, with basically a LOAD_FAST/LIST_APPEND replaced by a YIELD_VALUE. But I don't know byte code well enough to guess how the dangling local variable in LCs will be eliminated in Python 3.0 (as has been suggested a number of times). One way to eliminate it would be (as suggested) to make LCs syntactic sugar for list(). But it also looks like it might be possible to do a DELETE_FAST with an appropriately hidden name... STeVe From andreas at kostyrka.org Wed Jul 13 17:32:41 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 23:32:41 +0200 Subject: httplib/HTTPS Post Problem In-Reply-To: <1121088563.465929.31290@g43g2000cwa.googlegroups.com> References: <1121088563.465929.31290@g43g2000cwa.googlegroups.com> Message-ID: <1121290361.4728.2.camel@andi-lap> Am Montag, den 11.07.2005, 06:29 -0700 schrieb michaelparkin at gmail.com: > Hi, > > Sorry to post what might seem like a trivial problem here, but its > driving me mad! > > I have a simple https client that uses httplib to post data to a web > server. > > When I post over http & https using curl the data is recieved by the > web server with no problems. Just a curious guess: Are you behind a proxy? If so, it's a known and never fixed bug from Python 1.5 times ;) You might also try to use PyCurl. Andreas > > When I post using my python client the headers get there, but the body > of the message does not. > > My code is pretty standard and has the format: > > > httplib.HTTPSConnection.debuglevel = 1 > connection = httplib.HTTPSConnection(host_name, key_file = key, > cert_file = cert) > connection.putrequest("POST", path) > connection.putheader("Content-Length", str(len(body))) > > ...(some more headers)... > > connection.endheaders() > connection.send(body) > > response = connection.getresponse() > connection.close() > > (some code has been removed for clarity).. > > I can see in the debug messages the body getting sent, but nothing > arrives at > the server... > > I think I would understand whats going on better if I knew how Python > uses the > underlying socket - does it > > a) open the socket, send the header & body together or > b) send the header, wait, then send the body? > > I think the answer to this question solve my problem - can anyone help? > > Thanks. > > p.s. I'm using Python 2.3.3 [GCC 3.3.3 (SuseLinx)] > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From rkern at ucsd.edu Thu Jul 28 02:49:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Jul 2005 23:49:25 -0700 Subject: how to get function signature In-Reply-To: <1122532836.853488.286030@g14g2000cwa.googlegroups.com> References: <1122532836.853488.286030@g14g2000cwa.googlegroups.com> Message-ID: upadhyay at gmail.com wrote: > Hi, > > I was working on a dir like function that gives more information than > the usual dir, but I am not satisfied with the way I get function > arguments for callable members of an object. Take a look at it here: > http://nerdierthanthou.nfshost.com/2005/07/mdir-for-python.html. I have > seen PythonWin showing function arguments as tooltips, can anyone > please let me know how to get it. import inspect -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nyamatongwe+thunder at gmail.com Tue Jul 19 00:48:10 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 19 Jul 2005 04:48:10 GMT Subject: os.path.expanduser on Windows: UnicodeEncodeError In-Reply-To: References: Message-ID: Bob Swerdlow wrote: > My application is getting this error on Windows XP (works fine on Mac OS > X) when it calls os.path.expanduser: > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 52-56: ordinal not in range(128) What does your environment look like? You can find out by typing "SET" at a command prompt. The settings used are HOME, HOMEPATH and HOMEDRIVE. Also helpful to print out the value being handed to os.path.expanduser. > I found referenes to Path 957650, but I'm not familiar with how such > fixes are processed. Is there a patch I can add to fix this? How do I > know what version of Python it is fixed in - that is, will upgrading to > Python 2.3.5 fix this? The patch is still "Status: Open" so hasn't been applied to a release. It is not certain that this will fix your problem. The main benefit of the patch appears to be IMO that it will use the standard USERPROFILE environment variable. Neil From gene.tani at gmail.com Fri Jul 22 09:17:50 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jul 2005 06:17:50 -0700 Subject: command line argument passing In-Reply-To: References: Message-ID: <1122038270.420920.25080@z14g2000cwz.googlegroups.com> just remember: sys.argv[0] == script name http://www.artima.com/weblogs/viewpost.jsp?thread=4829 From q1fz6yj02 at sneakemail.com Thu Jul 7 16:03:23 2005 From: q1fz6yj02 at sneakemail.com (Jules Dubois) Date: Thu, 07 Jul 2005 14:03:23 -0600 Subject: latex/bibtex python paper? References: <1120663725.339927.141870@g47g2000cwa.googlegroups.com> Message-ID: <1666101.1SynQDipdN@knode.kde> On Wednesday 06 July 2005 09:28, schwehr at gmail.com (<1120663725.339927.141870 at g47g2000cwa.googlegroups.com>) wrote: > Hi All, > > Does anyone have a good template that I might use for writing a python > paper in latex/bibtex? [...] > > When I cite these, I get something like this (Foundation[2005]). Questions like this are better asked in comp.text.tex, where they are on-topic. There is a fine TeX/LaTeX/etc. FAQ at: http://www.tex.ac.uk/cgi-bin/texfaq2html Finally, here are some sample bibtex results: http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html From peter at engcorp.com Thu Jul 14 10:53:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 10:53:22 -0400 Subject: How can I import a py script by its absolute path name? In-Reply-To: References: <311b5ce105071404412d4bf318@mail.gmail.com> Message-ID: <6pGdnUXmweLc4UvfRVn-iA@powergate.ca> Jesse Noller wrote: > for f in os.listdir(os.path.abspath(libdir)): > module_name = f.strip('.py') > import module_name > > Obviously, this throws: > ImportError: No module named module_name > > Is there some way to do this? Use the __import__ builtin function. From zen19725 at zen.co.uk Sun Jul 31 04:36:55 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 09:36:55 +0100 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <87ack3qyu8.fsf@wilson.rwth-aachen.de> Message-ID: On Sun, 31 Jul 2005 08:22:23 +0200, Torsten Bronger wrote: >> >> What you say Pythonic, what do you mean? And how do you rate >> Tkinter, PyGtk, PyQt/PyKDE, wxWindows for "Pythonicness"? > >I don't like to set arguments to -1 or NULL, but to None. Fair enough >I'd like >to have extensive support for keyword arguments. Tkinter has that -- Email: zen19725 at zen dot co dot uk From inigoserna at terra.es Sat Jul 16 17:49:01 2005 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Sat, 16 Jul 2005 23:49:01 +0200 Subject: ANN: MyNewspaper-1.0 Message-ID: <1121550542.29657.10.camel@inigo.katxi.org> Hi there, I'm really pleased to announce the first public release of MyNewspaper. MyNewspaper is a personal RSS Aggregator and Reader, licensed under GPL. Why? As everybody says, I couldn't find any which fulfills all my requirements. In fact I used liferea and was pretty happy with it, but it eats lot of memory when you have many feeds and the program is running for much time, but the main problem was that it's a desktop program and I couldn't read the feeds from the work. So I started writing my own RSS aggregator and reader. MyNewspaper is written in Python with a bit of javascript and uses sqlite as permanent storage for the articles. It is installed as a CGI, so in order to use and manage it you need a web browser and a web server. Feeds are updated by a command run by cron or from the WebUI. Read more and download it from: http://inigo.katxi.org/devel/mynewspaper or http://www.terra.es/personal7/inigoserna/mynewspaper Of course, all comments, suggestions etc. are welcome. And yes, I know code is really awful now, but I wanted to make a public release to get some feedback while improving the code. Best regards, -- I?igo Serna Katxijasotzaileak -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From python at rcn.com Tue Jul 12 19:49:47 2005 From: python at rcn.com (Raymond Hettinger) Date: 12 Jul 2005 16:49:47 -0700 Subject: Inconsistency in hex() References: Message-ID: <1121212187.052208.72990@g47g2000cwa.googlegroups.com> [Steven D'Aprano] > > hex() of an int appears to return lowercase hex digits, and hex() of a > > long uppercase. [Terry Reedy] > Already bug-reported and fixed for 2.5 (to use lowercase, I believe). > http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1224347 Score another victory for the time machine ;-) Raymond From rahu at gawab.com Fri Jul 15 14:46:04 2005 From: rahu at gawab.com (Jonathan Conrad) Date: Fri, 15 Jul 2005 14:46:04 -0400 Subject: Reading variables from a forked child (Python C/API) In-Reply-To: <1121442371.861520@yasure> References: <42d7ab64@duster.adelaide.on.net> <1121442371.861520@yasure> Message-ID: <42D8046C.4010009@gawab.com> #ifdef def Donn Cave wrote: > Quoth MrEntropy : > > | I'm having a little trouble getting an idea running. I am writing a C > | program which is really a frontend to a Python program. Now, my C > | program starts up, does some initialisation like initialisation of it's > | variables and Py_Initialize() and then it fork()s. After forking the > | child launches the python program with Py_Main() and with the parent I > | want to be able to read the variables of the Python program. I have > | tried many ways but cannot find a solution to do this. > > That's because there is no solution. After a fork, the only effect > observable in the parent process is the return value of fork, which > will have a non-zero value. Subsequent execution in the child process > occurs completely independently from the parent, and leaves no trace > whatever. So you can't read variables from memory, that were set by > the child. Though there is probably some solution involving a third party such as POSIX threads, Linux has a clone(2) procedure which fork(2) is a macro of. It is tricky to use, but allows for having the child process have the same pid, memory, memory mappings, file tables, etc. BSD mmap(2) is more portable and can be used for interprocess sharing. The solution which Don Cave provided is probably the one that Mr. Entropy needs to start with. More specifically, ... #else int main (int argc, char **argv) { int fd0, fd1, fd2; { int fd_in [2], fd_out [2], fd_err [2]; pipe (fd_in); fd0 = fd_in [1]; pipe (fd_out); fd1 = fd_out [0]; pipe (fd_err); fd2 = fd_err [0]; if (!fork ()) { dup2 (fd_in [0], 0); close (fd0); dup2 (fd_out [1], 1); close (fd1); dup2 (fd_err [1], 2); close (fd2); execl ("python", "python", 0); perror ("execution failed"); exit (1); } } write (fd0, "print None\n", 11); write (1, b, read (fd1, b, sizeof (b) /* 5 or more */)); #define write0(q...) write (fd0, "print " #q "\n", \ sizeof (#q) + 5 + 1 - 1) write0 (True); write (1, b, read (fd1, b, sizeof (b))); write0 (5, str (5.0), ...); write (1, b, read (fd1, b, sizeof (b))); return write0 (True, False, None, True and False, True and None, False and None, True and False and None) && 0; } #endif From guettli at thomas-guettler.de Mon Jul 11 09:47:04 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 11 Jul 2005 15:47:04 +0200 Subject: importing files from a directory References: <1120966204.900591.212980@g44g2000cwa.googlegroups.com> Message-ID: Am Sat, 09 Jul 2005 20:30:04 -0700 schrieb spike grobstein: > I'm a total Python newbie, so bear with me here... > > I'm writing a program that has a user-configurable, module-based > architecture. it's got a directory where modules are stored (.py files) > which subclass one of several master classes. [cut] > for item in dir_list: > # strip off the extensions... > if (item == "__init__.py"): > continue > elif (item[-3:] == '.py'): item.endswith(".py") would be more python-like. > mod_name = item[:-3] > elif (item[-4:] == '.pyc'): elif item.endswith(".pyc"): continue # Don't load module twice > else: > continue > > print "Loading %s..." % mod > > module_list.append(__import__("Modules.%s" % mod)) > > print "Done." > > > it works more or less like I expect, except that... > > A. the first time it runs, blah.py then has a blah.pyc counterpart. > When I run the program again, it imports it twice. Not horrible, but > not what I want. is there any way around this? See above: Just don't load it. The compiled "pyc" file is taken automatically if it is newer than the "py" file. > B. module_list winds up consisting of items called 'Modules.blah' and > I'd like to have just blah. I realize I could say: > > my_module = __import__("Modules.%s" % mod) > module_list.append(getattr(my_module, mod)) I use this getattr() after __import__, too. I don't think there is a easier way. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From gsakkis at rutgers.edu Fri Jul 1 02:40:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 23:40:59 -0700 Subject: I am a Java Programmer References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> Message-ID: <1120200059.025267.12090@f14g2000cwb.googlegroups.com> "mjmri... at gmail.com" wrote: > I am a java programmer and I want to learn Python Please help me. Google Is Your Friend: http://www.razorvine.net/python/PythonForJavaProgrammers http://www.ferg.org/projects/python_java_side-by-side.html George From zsolt-google1 at mailblocks.com Wed Jul 13 17:40:40 2005 From: zsolt-google1 at mailblocks.com (pythonUser_07) Date: 13 Jul 2005 14:40:40 -0700 Subject: Issues With Threading In-Reply-To: <1121182937.775486.51050@o13g2000cwo.googlegroups.com> References: <1121182937.775486.51050@o13g2000cwo.googlegroups.com> Message-ID: <1121290840.042689.99400@g49g2000cwa.googlegroups.com> This is a complete shot in the dark but you might want to sys.stdout.flush() between print calls? From Scott.Daniels at Acm.Org Thu Jul 28 11:45:02 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 28 Jul 2005 08:45:02 -0700 Subject: Create a variable "on the fly" In-Reply-To: <42e89182$0$13699$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> <42e7c390$0$446$626a14ce@news.free.fr> <42e89182$0$13699$ed9e5944@reading.news.pipex.net> Message-ID: <42e8f51f$1@nntp0.pdx.net> Paul D.Smith wrote: >... What I'm left with is the following... > 1. A shell script which I maintain. > 2. A simple Python config which searches for all shell environment variables > named "MY_..." and instantiates then as Python variables. > 3. Historical scripts that run without me needing to spend time hunting down > all the config variables and replacing them with os.environ['MY_...']. Suppose you have a module named 'MY', with MY.py as: import os _globals = globals() for _name, _entry in os.environ.iteritems(): if _name.startswith('MY_'): try: _entry = int(_entry) except ValueError: try: _entry = float(_entry) except ValueError: pass _globals[_name[3 :]] = _entry then, wherever your python scripts use MY_XYZ, you begin the script with "import MY" and change every "MY_XYZ" to "MY.XYZ". --Scott David Daniels Scott.Daniels at Acm.Org From mwh at python.net Tue Jul 5 07:34:43 2005 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Jul 2005 11:34:43 GMT Subject: math.nroot [was Re: A brief question.] References: Message-ID: Tim Peters writes: > All Python behavior in the presence of infinities, NaNs, and signed > zeroes is a platform-dependent accident, mostly inherited from that > all C89 behavior in the presence of infinities, NaNs, and signed > zeroes is a platform-dependent crapshoot. As you may have noticed by now, I'd kind of like to stop you saying this :) -- at least on platforms where doubles are good old-fashioned 754 8-byte values. But first, I'm going to whinge a bit, and lay out some stuff that Tim at least already knows (and maybe get some stuff wrong, we'll see). Floating point standards lay out a number of "conditions": Overflow (number too large in magnitude to represent), Underflow (non-zero number to small in magnitude to represent), Subnormal (non-zero number to small in magnitude to represent in a normalized way), ... For each condition, it should (at some level) is possible to trap each condition, or continue in some standard-mandated way (e.g. return 0 for Underflow). While ignoring the issue of allowing the user to control this, I do wish sometimes that Python would make up it's mind about what it does for each condition. There are a bunch of conditions which we shouldn't and don't trap by default -- Underflow for example. For the conditions that probably should result in an exception, there are inconsistencies galore: >>> inf = 1e300 * 1e300 # <- Overflow, no exception >>> nan = inf/inf # <- InvalidOperation, no exception >>> pow(1e100, 100) <- Overflow, exception Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') >>> math.sqrt(-1) # <- InvalidOperation, exception Traceback (most recent call last): File "", line 1, in ? ValueError: math domain error At least we're fairly consistent on DivisionByZero... If we're going to trap Overflow consistently, we really need a way of getting the special values reliably -- which is what pep 754 is about, and its implementation may actually work more reliably in 2.5 since my recent work... On the issue of platforms that start up processes with traps enabled, I think the correct solution is to find the incantation to turn them off again and use that in Py_Initialize(), though that might upset embedders. Cheers, mwh -- rasterman is the millionth monkey -- from Twisted.Quotes From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 09:32:45 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 15:32:45 +0200 Subject: Comparison of functions In-Reply-To: References: Message-ID: <3l1druF10aj5pU1@individual.net> Steven D'Aprano wrote: > On Sat, 30 Jul 2005 08:13:26 -0400, Peter Hansen wrote: > >> Beginners should not be comparing lambdas. >> >> Neither should you. ;-) > > Actually, yes I should, because I'm trying to make sense of the mess that > is Python's handling of comparisons. At least two difference senses of > comparisons is jammed into one, leading to such such warts as these: > >>>> L = [] >>>> L.sort() # we can sort lists >>>> L.append(1+1j) >>>> L.sort() # even if they include a complex number >>>> L.append(1) >>>> L.sort() # but not any more > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= > > Um, I didn't ask to compare complex numbers using comparison operators. I > asked to sort a list. And please don't tell me that that sorting is > implemented with comparison operators. That just means that the > implementation is confusing numeric ordering with sort order. Sorting is implemented with comparison operators. How should it be otherwise? Would you prefer a __sort__ method to specify sort order? And how would you sort a list of complex numbers? > Then there is this: > >>>> 1 > 0 > True Okay. >>>> 1+0j == 1 > True Okay. >>>> 1+0j == 1 > 0 > True (1+0j == 1) yields True, which is comparable to 0. >>>> 1+0j > 0 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= But complex numbers are not greater or littler than others. You can't order them, not on a one-dimensional scale. > I applaud that Python has got rich comparisons for those who need them. > But by confusing the question "which comes first in a sorted list?" with > "which is larger?", you get all sorts of warts like being unable to sort > lists with some objects, while being able to make meaningless > comparisons like ''.join >= [].append. That's a wart indeed, and intended to be removed for 3.0, if I'm informed correctly. Reinhold From simon.dahlbacka at gmail.com Mon Jul 18 13:03:16 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 18 Jul 2005 10:03:16 -0700 Subject: Image orientation and color information with PIL? In-Reply-To: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> References: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> Message-ID: <1121706196.750728.310140@g49g2000cwa.googlegroups.com> if you mean that you want to figure out which way the image is depending on the actual data in the image, then you'll most likely get to do the image processing yourself, on the other hand, if you are talking jpegs from a relatively new camera then I suppose that you should be able to get that info by looking at the EXIF information. AFAIK you can read exif with PIL, but not write. From cam.ac.uk at mh391.invalid Fri Jul 22 11:19:30 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 16:19:30 +0100 Subject: PEP on path module for standard library In-Reply-To: <1122041649.070945.85380@g49g2000cwa.googlegroups.com> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > Havind said that, I think > the choice between subclassing or not is going to be a > practicality-vs-purity decision. You're right, conceptually a path > HAS_A string description, not IS_A string, so from a pure OO point of > view, it should not inherit string. OTOH, people in favor of the > subclassing point out the convenience for many (or most) common cases. It would be an entirely different matter if we were designing a language from scratch. But we have to deal with an existing codebase that expects strings. Here's some code I just wrote seconds ago to construct a path for a scp upload: """ DST_DIRPATH = path("host:~/destination") RSS_EXT = "rss" dst_filenamebase = os.extsep.join([postcode.lower(), RSS_EXT]) dst_filepath = DST_DIRPATH.joinpath(dst_filenamebase) """ With the current path implementation, this Just Works. If I were using something that parsed and understood paths, the scp/rcp convention of host:filename would either cause an error or have to be programmed in separately. The current implementation is much more flexible. What are the practical advantages and conveniences of *not* subclassing from basestring? -- Michael Hoffman From siona at chiark.greenend.org.uk Thu Jul 7 09:29:20 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Jul 2005 14:29:20 +0100 (BST) Subject: Strange os.path.exists() behaviour References: <42cc3613$0$22287$8fcfb975@news.wanadoo.fr> Message-ID: Jeff Epler wrote: >Pierre wrote: >> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on wi= >n32 > ^^^^= >^^^ >Here's the bug. You're using Windows. It's a filesystem, but not as we kn= >ow it... > [ ... ] >As you can see, not only does Windows think that "exist...." exists, but it= > can >successfully "type" its contents too! The "reason" for this behaviour is that the concept of a file extension is firmly embedded in the operating system. exists is a file with no extension, as is exists. (no, it doesn't make a distinction between "no extension" and "an empty extension"). >From there it's not too great a leap of induction to suppose that exists.... is the same file called exists with no extension. It's not unlike being able to stick an arbitrary number of /s onto the end of a directory name on a sane OS/filesystem. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From __peter__ at web.de Wed Jul 13 13:37:13 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Jul 2005 19:37:13 +0200 Subject: Searching through a list of tuples References: <1121142059.974360.48900@o13g2000cwo.googlegroups.com> <42d41cde$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > iter(elem?in?lst?if?elem[3]?==?x).next() > > Does this look any better???At?least?it?stops?when?the?answer?is?found. Next time you'll recommend if (a>b) == True: # ... Watch out, you're on a slippery slope here :-) Peter From peter at engcorp.com Tue Jul 26 11:47:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Jul 2005 11:47:11 -0400 Subject: Packages and modules In-Reply-To: References: Message-ID: Dan wrote: >>>no executable code in >>>__init__.py is executed, even though "import test" seems to succeed. > > I've discovered that "import test" *does* cause executable code in the > package to be executed. However, I can't execute it on the command line > using "python test". Is there a way to do this? Using the latest version of Python, "python -m test" should do it, though I don't know if that works for packages, or just modules. Hang on... appears to work only for modules. Okay, this should be universal, if slightly more awkward: python -c "import xyz" The problem with this approach is that it won't execute the "if __name__ == '__main__':" code at the end, so if you want to execute a particular function directly, just add the call manually: python -c "import xyz; xyz.main()" >>There _is_ a standard library package called test > Oh, you're right. But I've renamed the module to XYZ and I still have > the problem. Which problem? From peter at engcorp.com Mon Jul 18 09:01:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 09:01:06 -0400 Subject: Dictionary, keys and alias In-Reply-To: <5mLCe.24301$b93.15018@tornado.fastwebnet.it> References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> <5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: <_MOdnc2Ag8xyOkbfRVn-pw@powergate.ca> Glauco wrote: > I want to insert a concept of alias in a dict_based class. ... > Any suggestion ? Yes, in future don't attempt to start a new thread using "Reply" unless you are happy not having your post read by all those who have already "killed" the thread to which you replied. Anyone who was not interested in the Python Programming Contest thread is unlikely to have seen your question. -Peter From steven.bethard at gmail.com Tue Jul 19 22:47:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 19 Jul 2005 20:47:03 -0600 Subject: popen2 usage In-Reply-To: <1121799002.440543.206050@g43g2000cwa.googlegroups.com> References: <1121799002.440543.206050@g43g2000cwa.googlegroups.com> Message-ID: jb wrote: > Hi there: > > I need help with popen2 usage. I am coding on Windows 2000 environment > and I am basically trying to run command line executable program that > accepts command line arguments from user. I want to be able to provide > these arguments through input pipe so that executable does not require > any intervention from the user. The way I am doing this is as below: > > out1, in1 = popen2.popen2("testme.exe > abc.txt") > in1.write('-test1') > in1.flush() > in1.close() > > But this does not seem to be working, when I open abc.txt file it does > not show '-test1' argument that was supplied via in1.write method. This > causing executable to wait forever unless user manually kills the > process. I'm confused; is "-test1" a command line argument to testme.exe? Or is it the text that testme.exe should receive from standard input? Either way, I would suggest using subprocess instead of popen*. To pass -test1 as a command line argument, do something like: import subprocess as sp p = sp.Popen(["testme.exe", "-test1"], stdout=sp.PIPE) out1 = sp.stdout.read() To pass -test1 through standard input, do something like: import subprocess as sp p = sp.Popen(["testme.exe"], stdout=sp.PIPE) p.stdin.write("-test1") p.stdin.flush() p.stdin.close() out1 = p.stdout HTH, STeVe From jepler at unpythonic.net Mon Jul 18 13:02:15 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Jul 2005 12:02:15 -0500 Subject: Image orientation and color information with PIL? In-Reply-To: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> References: <1121705037.667860.241980@g47g2000cwa.googlegroups.com> Message-ID: <20050718170215.GG2199@unpythonic.net> >>> i = Image.open("blue.jpg") >>> i.size (3008, 2000) >>> i.mode 'RGB' 'RGB' is the value for color jpeg images. I believe that for black&white images, i.mode is 'L' (luminosity). If you want to determine whether an existing image is landscape or portrait, then just compare i.size[0] (width) and i.size[1] (height). If by "determine if an image is horizontal/vertical", you want to find the orientation data recorded by some digital cameras, you can do that with PIL 1.1.4. According to the release notes for 1.1.4, + Added experimental EXIF support for JPEG files. To extract EXIF information from a JPEG file, open the file as usual, and call the "_getexif" method. If successful, this method returns a dictionary mapping EXIF TIFF tags to values. If the file does not contain EXIF data, the "_getexif" method returns None. The "ExifTags" module contains a dictionary mapping tags to tag names. This interface will most likely change in future versions. The exif tag 274 is Orientation. The values you'll see most often are 1 (Normal), 6 and 8 (90 and 270 degree rotations). Orientation can also encode 180 degree rotation, as well as any of the four rotations combined with a mirror operation. >>> [k for (k,v) in ExifTags.TAGS.items() if v == 'Orientation'] [274] >>> e = i._getexif() >>> if e: print e[274] 1 I have written a standalone Python module that reads and changes the EXIF orientation data. You can view it here: http://unpy.net/cgi-bin/viewcvs.cgi/aethertool/disorient.py?rev=1.2&content-type=text/vnd.viewcvs-markup It is available under the terms of the GNU GPL. Here's another page about EXIF orientation data: http://sylvana.net/jpegcrop/exif_orientation.html Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fdeserres at gmx.net Sun Jul 24 13:01:18 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Sun, 24 Jul 2005 19:01:18 +0200 Subject: tuple to string? In-Reply-To: References: <42E0EED4.4020001@gmx.net> <42E36CA9.5070403@gmx.net> Message-ID: <42E3C95E.1070307@gmx.net> Robert Kern wrote: >Francois De Serres wrote: > > > >>I'll pick ('%c' * len(t)) % t, for it's readability and the fact that >>join() is on the deprec'd list. >> >> > >''.join() is certainly not deprecated. What made you think that? > > > this: http://www.python.org/doc/2.4.1/lib/node110.html but I now realize it's a different version of join() that was proposed here... thank you, Francois From mwm at mired.org Thu Jul 21 19:32:06 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 21 Jul 2005 19:32:06 -0400 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <86psterxi3.fsf@bhuda.mired.org> <86y881qcol.fsf@bhuda.mired.org> Message-ID: <86pstbrb0p.fsf@bhuda.mired.org> Rocco Moretti writes: >> My "favorite" infinte loop with while is: >> i = 0 >> while i < 20: >> do_process(i) >> Note the prominent *lack* of any change to i here? >> Oh, for: >> from i = 0 >> invariant 0 <= i <= 20 >> variant 21 - i >> until i > 19 >> loop >> do_process(i) >> which throws an exception at the beginning of the second loop. > > What language is that from? Eiffel. > I take it the exception is from the "21-i" not changing as it goes > around the loop, right? (But why can't "variant i" work just as well?) Because that's the way variant is defined. You actually want the variant to move in a specific direction, so that you don't wind up incrementing it when you should be decrementing it. Eiffel chose down, so you you need -i at the very least. It also insists that the invariant be positive. I'm not sure why; it makes the variant more complicated, resulting in exceptions from bugs in the variant as well as bugs in the loop. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jepler at unpythonic.net Mon Jul 11 17:22:55 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 11 Jul 2005 16:22:55 -0500 Subject: Parsing Data, Storing into an array, Infinite Backslashes In-Reply-To: <1121114842.623294.156790@g44g2000cwa.googlegroups.com> References: <1121114842.623294.156790@g44g2000cwa.googlegroups.com> Message-ID: <20050711212255.GB14310@unpythonic.net> Your code is needlessly complicated. Instead of this business while 1: try: i = fetch.next() except stopIteration: break simply write: for i in fetch: (if there's an explicit 'fetch = iter(somethingelse)' in code you did not show, then get rid of that and just loop 'for i in somethingelse') i[1] will never compare equal to count, because i[1] is always a string and count is always an integer. Integers and strings are never equal to each other. Wring code like x = "a string " + 3 does not work in Python. You can either convert to a string and then use the + operator to concatenate: x = "a string " + str(3) or you can use %-formatting: x = "a string %s" % 3 ("%s" accepts any sort of object, not just strings) Using repr(...) (`...` is just a shorthand for this) is what is really introducing the backslashes. When it outputs a string, it quotes the string using backslashes. But you pass the old part of the prepared string through it each time, which leads to doubling backslashes. Below is a program I wrote to process the data in your message. It prints out Memory 2 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM2/J13, ConfigurationType=2 Memory 3 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM3/J14, ConfigurationType=2 Memory 0 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM0/J11, ConfigurationType=2 Memory 1 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM1/J12, ConfigurationType=2 the result is out of order because the result of calling .items() on a dict is in an arbitrary order. Jeff s = [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed', 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0', 'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0', 'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory', '1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'], ['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'], ['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary', '0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2', 'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2', 'Slot', 'DIMM2/J13'], ['Memory', '2', 'ConfigurationType', '2'], ['Memory', '3', 'Summary', '0'], ['Memory', '3', 'Speed', 'PC3200U-30330'], ['Memory', '3', 'Type', 'DDR SDRAM'], ['Memory', '3', 'Size', '512'], ['Memory', '3', 'Slot', 'DIMM3/J14'], ['Memory', '3', 'ConfigurationType', '2']] query = {} for a, b, c, d in s: if not query.has_key((a,b)): query[(a,b)] = [] query[(a,b)].append("%s=%s" % (c, d)) for (a,b), v in query.items(): print a, b, ", ".join(v) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cmedcoff at hotmail.com Mon Jul 18 10:37:16 2005 From: cmedcoff at hotmail.com (chuck) Date: 18 Jul 2005 07:37:16 -0700 Subject: stdin/stdout fileno() always returning -1 from windows service References: <1121650980.574867.244590@g44g2000cwa.googlegroups.com> Message-ID: <1121697436.413522.268110@g49g2000cwa.googlegroups.com> Interesting. The stdin and stdout objects in my service seems respond to returing a string for the statements str(sys.stdin) and str(sys.stdout). I guess they are just not attached to files? Can you provide a reference (MSDN or otherwise) that indicates that Windows Services don't have standard I/O? From steven.bethard at gmail.com Fri Jul 1 13:38:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 01 Jul 2005 11:38:49 -0600 Subject: aligning text with space-normalized text In-Reply-To: References: Message-ID: Peter Otten wrote: > import re > _reLump = re.compile(r"\S+") > > def indices(text, chunks): > lumps = _reLump.finditer(text) > for chunk in chunks: > lump = [lumps.next() for _ in chunk.split()] > yield lump[0].start(), lump[-1].end() Thanks, that's a really nice, clean solution! STeVe From lafrance at adobe.com Fri Jul 8 01:22:10 2005 From: lafrance at adobe.com (news.corp.adobe.com) Date: Fri, 08 Jul 2005 05:22:10 GMT Subject: urllib2 - basic authentication and the put and delete methods Message-ID: <64oze.2034$S17.395743@monger.newsread.com> I need to perform basic authentication and I also need to be able to use the put and delete methods to copy files / delete files on a server. Here is how I successfully perform basic authentication to read a page: ------------------------------------------------ import urllib2, os, base64 os.system("cls") theurl = 'http://myurl.com:9090/ESG/en_US/GLtest/' username = 'myusername' password = 'mypassword' req = urllib2.Request(theurl) realm = 'Apache Tomcat/4.1.27' base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) handle = urllib2.urlopen(req) thepage = handle.read() print thepage ------------------------------------------------ But despite much searching, I have yet to discover how to then use PUT and DELETE to copy files / delete files on the server. From tim.peters at gmail.com Mon Jul 11 20:21:52 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 11 Jul 2005 20:21:52 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae050711172130fb26d2@mail.gmail.com> [Tim Peters] >>>>>> All Python behavior in the presence of infinities, NaNs, and signed >>>>>> zeroes is a platform-dependent accident, mostly inherited from that >>>>>> all C89 behavior in the presence of infinities, NaNs, and signed >>>>>> zeroes is a platform-dependent crapshoot. [Michael Hudson] >>>>> As you may have noticed by now, I'd kind of like to stop you saying >>>>> this :) -- at least on platforms where doubles are good old-fashioned >>>>> 754 8-byte values. [Tim] >>>> Nope, I hadn't noticed! I'll stop saying it when it stops being true, >>>> though . Note that since there's not even an alpha out for 2.5 >>>> yet, none of the good stuff you did in CVS counts for users yet. [Michael] >>> Well, obviously. OTOH, there's nothing I CAN do that will be useful >>> for users until 2.5 actually comes out. [Tim] >> Sure. I was explaining why I keep saying what you say you don't want >> me to say: until 2.5 actually comes out, what purpose would it serve >> to stop warning people that 754 special-value behavior is a x-platform >> crapshoot? Much of it (albeit less so) will remain a crapshoot after >> 2.5 comes out too. [Michael] > Well, OK, I phrased my first post badly. Let me try again: > > I want to make this situation better, as you may have noticed. Yup, I did notice that! I've even pointed it out. In a positive light . >>>>> But first, I'm going to whinge a bit, and lay out some stuff that Tim >>>>> at least already knows (and maybe get some stuff wrong, we'll see). >>>>> >>>>> Floating point standards lay out a number of "conditions": Overflow >>>>> (number too large in magnitude to represent), Underflow (non-zero >>>>> number to small in magnitude to represent), Subnormal (non-zero >>>>> number to small in magnitude to represent in a normalized way), ... >>>> The 754 standard has five of them: underflow, overflow, invalid >>>> operation, inexact, and "divide by 0" (which should be understood more >>>> generally as a singularity; e.g., divide-by-0 is also appropriate for >>>> log(0)). >>> OK, the decimal standard has more, which confused me for a bit >>> (presumably it has more because it doesn't normalize after each >>> operation). >> The "conditions" in IBM's decimal standard map, many-to-one, on to a >> smaller collection of "signals" in that standard. It has 8 signals: >> the 5 I named above from 754, plus "clamped", "rounded", and >> "subnormal". Distinctions are excruciatingly subtle; e.g., "rounded" >> and "inexact" would be the same thing in 754, but, as you suggest, in >> the decimal standard a result can be exact yet also rounded (if it >> "rounds away" one or more trailing zeroes), due to the unnormalized >> model. > Right, yes, that last one confused me for a while. > > Why doesn't 754 have subnormal? Who cares <0.1 wink>. > Actually, I think I'm confused about when Underflow is signalled -- is it > when a denormalized result is about to be returned or when a genuine > zero is about to be returned? Underflow in 754 is involved -- indeed, the definition is different depending on whether the underflow trap is or is not enabled(!). On top of that, it's not entirely defined -- some parts are left to the implementer's discrection. See http://www2.hursley.ibm.com/decimal/854M8208.pdf for what, from a brief glance, looks very much like the underflow text in the final 754 standard. Note that subnormals and underflow are much less a real concern with 754 doubles than with 754 floats, because the latter have such a small dynamic range. >>>>> For each condition, it should (at some level) is possible to trap each >>>>> condition, or continue in some standard-mandated way (e.g. return 0 >>>>> for Underflow). >>>> 754 requires that, yes. >>>>> While ignoring the issue of allowing the user to control this, I do >>>>> wish sometimes that Python would make up it's mind about what it >>>>> does for each condition. >>>> Guido and I agreed long ago that Python "should", by default, raise an >>>> exception on overflow, invalid operation, and divide by 0, and "should >>>> not", by default, raise an exception on underflow or inexact. >> And, I'll add, "should not" on rounded, clamped and subnormal too. > Sure, but we already have a conforming implementation of 854 with > settable traps and flags and rounding modes and all that jazz. No, we don't, but I assume you're talking about the decimal module. If so, the decimal module enables traps on overflow, invalid operation, and divide-by-0 by default. A conforming implementation would have to disable them by default. Apart from that difference in defaults, the decimal module does intend to conform fully to the proposed decimal FP standard. > Maybe we should just implement floats in Python. Certainly the easiest way to get 754 semantics across boxes! Been there, done that, BTW -- it's mondo slow. >>>> Such defaults favor non-expert use. Experts may or may not be happy >>>> with them, so Python "should" also allow changing the set. >>> Later :) >> That's a problem, though. 754 subsets are barely an improvement over >> what Python does today: > Well, my contention is that the consistent application of one > particular 754 subset would be an improvement. Maybe I'm wrong! I wrote more about that later (as in exploiting that infix * doesn't raise OverlowError, but pow(float, float) probably does). >>> (In the mean time can we just kill fpectl, please?) >> Has it been marked as deprecated yet (entered into the PEP for >> deprecated modules, raises deprecation warnings, etc)? I don't know. >> IMO it should become deprecated, but I don't have time to push that. > A bit of googling suggests that more people pass --with-fpectl to > configure than I expected, but I doubt more than 1% of those actually > use the features thus provided (of course, this is a guess). I expect 1% is way high. Before we stopped building fpectl by default, Guido asked and heard back that there were no known users even at LLNL anymore (the organization that contributed the code). >>>>> There are a bunch of conditions which we shouldn't and don't trap by >>>>> default -- Underflow for example. For the conditions that probably >>>>> should result in an exception, there are inconsistencies galore: >>>>> >>>>> >>> inf = 1e300 * 1e300 # <- Overflow, no exception >>>>> >>> nan = inf/inf # <- InvalidOperation, no exception Remember this below. >>>> Meaning you're running on a 754 platform whose C runtime arranged to >>>> disable the overflow and invalid operation traps. >>> Isn't that the standard-mandated start up environment? >> The 754 standard mandates "non-stop" mode (all traps disabled) at >> startup, but who in this chain is _claiming_ to implement the 754 >> standard? Your platform C may or may not, and your OS may or may not. > Well, fair point, but it's a convenient stick to beat unconforming > platform vendors with. Yup. > I only really care about platforms that make at least a half-hearted > effort towards 754 compliance. I'm not looking to improve behaviour > on a PDP-10 running TOPS (or whatever). >>>> You're seeing native HW fp behavior then. >>> But anyway, shouldn't we try to raise exceptions in these cases? Note that the only cases you could have been talking about here were the plain * and / examples above. >> I believe Python should raise exceptions in these cases by default, And I was talking about the plain * and / examples too. >> because, as above, they correspond to the overflow and >> invalid-operation signals respectively, and Python should raise >> exceptions on the overflow, invalid-operation, and divide-by-0 signals >> by default. But I also believe Python _dare not_ do so unless it also >> supplies sane machinery for disabling traps on specific signals (along >> the lines of the relevant standards here). > Um. Python raises OverflowError more often that it used to, it seems > to me, and already _dares_ to raise it from (e.g.) math.exp with no > way of turning this off I can see. I was talking about * and / (and, by extension, also + and -). As I originally said, libm is a different story (for implementation reasons). I don't believe Python could get away with raising exceptions on overflow or invalid operation for + - * or / unless there were also a way to get back current behavior (which is non-stop + - * / on almost all (and possibly all) current Python platforms, with the exception of divide-by-0). >> Many serious numeric programmers would be livid, and justifiably so, >> if they couldn't get non-stop mode back. > Maybe I'm missing something (and writing this reply in multiple stages > makes this more likely) but they don't have it now, do they? They do for + - * /. >> The most likely x-platfrom accident so far is that they've been >> getting non-stop mode in Python since its beginning. Again referring to + - * /. > I know I'm repeating myself, but didn't this changeset: > > http://fisheye.cenqua.com/changelog/python?cs=MAIN:tim_one:20010905223655 > > change that rather? (It affects 2.2 and later, I think). That was about libm error reporting, not + - * /. It also wasn't trying to _increase_ libm error coverage, it was trying to get back the error coverage we _had_ before some C compilers started exploiting the much looser libm error reporting allowed by C99. C89 required more from libm, and as people moved to newer C compilers Python stopped raising exceptions where it had raised them before, because their libm stopped setting errno in nasty cases. The patch above tried to get former behavior back. Ideally, users would have a choice between exceptions or non-stop mode for libm functions too. >>> I don't think it's a particularly good idea to try to utilize the fp >>> hardware's ability to do this at this stage, btw, but to add some kind >>> of check after each operation. >> That's possible, anyway. Doing it in software is slow, but if you >> look at the horrid contortions fpectlmodule.c endures to try to >> exploit HW facilities, it's not clear that the latter is any faster. > I think it might well be slow, too, at least some of the time; the > conclusion of this rather long thread: > > http://lists.freebsd.org/pipermail/freebsd-stable/2005-May/014575.html > > was "turn --with-fpectl off". LOL! That's a classic -- thanks for pointing it out. There's indeed little you can do that's slower than slopping setjmp/longjmp around every piddly operation. >>>>> >>> pow(1e100, 100) <- Overflow, exception >>>>> Traceback (most recent call last): >>>>> File "", line 1, in ? >>>>> OverflowError: (34, 'Numerical result out of range') >>>>> >>> math.sqrt(-1) # <- InvalidOperation, exception >>>>> Traceback (most recent call last): >>>>> File "", line 1, in ? >>>>> ValueError: math domain error >>>> Unlike the first two examples, these call libm functions. >>> And the user cares about this why? >> Didn't say the user did care. > I know you didn't, and I also knew the reason for the different > behaviours, but that doesn't make me feel that much better. Maybe we could stick to questions you do want answers to, then? >> Why doesn't Python already supply a fully 754-conforming arithmetic >> on 754 boxes? It's got almost everything to do with implementation >> headaches, and very little to do with what users care about. >> Because all the C facilities are a x-platform mess, the difference >> between calling and not calling libm can be the difference between >> using the platform libm or Python needing to write its own libm. >> For example, there's no guarantee that math.sqrt(-1) will raise >> ValueError in Python, because Python currently relies on the >> platform libm sqrt to detect _and report_ errors. The C standards >> don't require much of anything there. > Can't we use the stuff defined in Appendix F and header of > C99 to help here? I know this stuff is somewhat optional, but it's > available AFAICT on the platforms I actually use (doesn't mean it > works, of course). It's entirely optional part of C99. Python doesn't require C99. The most important example of a compiler that doesn't support any of that stuff is Microsoft's, although they have their own MS-specific ways to spell most of it. > I'm thinking something like this: > > fexcept_t flags; > > feclearexcept(FE_ALL_EXCEPT); > > /* stuff, e.g. r = exp(PyFloat_AS_DOUBLE(x)) */ > > fegetexceptflag(&flags, FE_ALL_EXCEPT) > > /* inspect flags to see if any of the flags we're currently trapping > are set */ Assuming the platform libm sets 754 flags appropriately, that's a fine way to proceed on platforms that also support that specific spelling. ... >>> Well, you can at least be pretty sure that an infinite result is the >>> result of an overflow condition, I guess. > > There are at least two other causes: some cases of divide-by-0 (like > > 1/0 returns +Inf), and non-exceptional production of an infinite > > result from infinite operands (like sqrt(+Inf) should return +Inf, and > > there's nothing exceptional about that). > Yeah, but I think those can be dealt with (if we really wanted to). They certainly could be. > OTOH, I think Inexact would be pain itself to detect without hw > support, and Underflow would be tedious. In the absence of HW help, there's really no hope for those short of emulating fp arithmetic in SW. >>>>> At least we're fairly consistent on DivisionByZero... >>>> When it's a division by 0, yes. It's cheap and easy to test for that. >>>> However, many expert uses strongly favor getting back an infinity >>>> then instead, so it's not good that Python doesn't support a choice >>>> about x/0. >>> Indeed. But I'd rather work on non-settable predictability first. >> OTOH, I bet I could find people willing to pay for the ability to >> "turn off" divide-by-0 exceptions (or the people talking my ear off at >> PyCon this year were just bluffing ). > Noted. >> BTW, since there's so little the HW can help us with here in reality >> (since there's no portable way to get at it), > In what way does C99's fenv.h fail? Is it just insufficiently > available, or is there some conceptual lack? Just that it's not universally supported. Look at fpectlmodule.c for a sample of the wildly different ways it _is_ spelled across some platforms. A maze of #ifdefs could work too, provided we defined a PyWhatever_XYZ API to hide platform spelling details. >> any predictability is going to be supplied by software, and software >> for that will work better over the long run if it's designed from >> the start realizing that it needs to consult some form of context to >> decide what is and is not "an exception". > Also noted. > [...] >>> This make me sad. >>> >>> Whether my code should have returned an infinite value or raised an >>> exception for "1e1000" is an open question, but I'd like the answer to >>> be less accidental. >> It's a delicate house of cards right now for sure. In some ways, >> experts have learned to live with-- and exploit --it: when they >> _want_ an overflow exception they'll use pow(), and when they don't >> they'll just multiply. > Another question: where can I find these experts? I'm one. I'd expect to find others on the numerical Python lists, not on c.l.py. The folks at Enthought would be good to talk with. > How come they haven't tried to reduce the mess before? It's tedious, exacting, time-consuming, and an endless source of x-platform problems. I'd much rather work on the Python Challenge riddles now <0.5 wink>, speaking of which ... From spam.csubich+block at block.subich.spam.com Tue Jul 12 16:00:29 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 12 Jul 2005 16:00:29 -0400 Subject: python parser In-Reply-To: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> References: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> Message-ID: tuxlover wrote: > I have to write a verilog parser in python for a class project. I was > wondering if all you folks could advise me on choosing the right python > parser module. I am not comfortable with lex/yacc and as a result find > myself strugging with any module which use lex/yacc syntax/philosophy. > pyparser looks good to me, but before I dive into it, I would really > appreciate feedback from members of this group I've had good luck with DParser for Python (http://staff.washington.edu/sabbey/dy_parser/index.html); in fact, it might even be a very easy translation from a premade Verilog grammar to a DParser grammar (Google search if you don't have BNF for Verilog already). Two caevats come to mind, though; documentation isn't as newbie-friendly as it could be, and DParser requires a binary library -- it's not Python-only, which might matter for your project. From sbassi at gmail.com Wed Jul 20 15:54:38 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Wed, 20 Jul 2005 16:54:38 -0300 Subject: How to store "3D" data? (data structure question) In-Reply-To: References: Message-ID: On 7/20/05, Cyril Bazin wrote: > The question of the type of the data sutructure depends of your use of the > data. > You could avoid some confusion without naming your columns "lines"... Yes, that is because they are "plant lines", that is why is called "lines" :) > Anyway, here is a piece of code that read the file and count the star on > the fly: > (The result is a dict of dict of int.) THANK YOU, I will check it out! -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From http Sun Jul 31 19:23:13 2005 From: http (Paul Rubin) Date: 31 Jul 2005 16:23:13 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> <7xvf2rync2.fsf@ruckus.brouhaha.com> <87r7dfymy1.fsf@wilson.rwth-aachen.de> Message-ID: <7xmzo25zmm.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > I can't really understand your hostility towards non-Tkinter > toolkits. In the case of wxPython, it's part of SUSE, which is > probably also true for Fedora and Mandriva. Installing is as easy > as selecting a checkbox. This covers a very great deal of Linux > users. On Windows you have to call an exe file. No it's not on Fedora, at least FC3. I had huge trouble trying to build it and gave up. I had similar problems on RH9. From cam.ac.uk at mh391.invalid Tue Jul 26 10:09:59 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 26 Jul 2005 15:09:59 +0100 Subject: Emacs skeletons Message-ID: Does anyone have any Emacs skeletons they find useful for Python? I Googled a little but didn't find anything enticing. I already have a script that sets up script/module templates, so those aren't all that useful. -- Michael Hoffman From steve at ferg.org Tue Jul 26 09:14:45 2005 From: steve at ferg.org (Steve) Date: 26 Jul 2005 06:14:45 -0700 Subject: problem with ActiveState install Message-ID: <1122383685.483563.137600@g47g2000cwa.googlegroups.com> I've installed the ActiveState binary distribution for Solaris in my home directory, but I'm having problems with Tk. I think I did everything right -- I used gtar rather than Solaris tar, and the install process indicated it was successful. I added the python directory to ~/.bashrc. Python works fine from the command line. But if I try to execute anything that uses Tkinter (including Idle), the console window goes blank and then nothing else happens. I have to use control+z to break out. Does anyone have any idea what the problem might be, and how to fix it? Thanks in advance, -- Steve Ferg From smadim2 at grads.ece.mcmaster.ca Tue Jul 19 16:32:40 2005 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Tue, 19 Jul 2005 16:32:40 -0400 Subject: time string conversion Message-ID: <42DD6368.50500@grads.ece.mcmaster.ca> hi; i have a string that look like 16:23:20.019519 (i.e. system time) without days and months. I want to convert it to just one long floating point number with as many decimal places as possible. is there a funciton to do that? thanks ms From jgrahn-nntq at algonet.se Tue Jul 19 12:47:47 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 19 Jul 2005 16:47:47 GMT Subject: secure uploading References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> <7x4qauaccl.fsf@ruckus.brouhaha.com> <1121563713.124461.230540@g47g2000cwa.googlegroups.com> Message-ID: On 16 Jul 2005 18:28:33 -0700, macaronikazoo wrote: > well I want a script to upload something automatically, so i need a > python script to do that for me. Well, you need /something/. If you are on a Unix machine, you'd be better off with a cron job. > my hoster has ssl enabled on their > server and I have generated a key. but now I need to know how to > upload something using ssl to the server. how to I ftp something to > the server using ssl? Are you sure your hoster doesn't provide ssh access to his machines? If he does, there is a wealth of protocols and tools for secure file transfer: scp, sftp, tar-over-ssh, cpio-over-ssh, rsync-over-ssh, ... With some loss of security, you may even be able to avoid handling passwords. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From rrr at ronadam.com Wed Jul 6 17:18:42 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 21:18:42 GMT Subject: Use cases for del In-Reply-To: <3j2st8Fnu7j9U1@individual.net> References: <3j2st8Fnu7j9U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Ron Adam wrote: > >>Ron Adam wrote: >> >> >>>And accessing an undefined name returned None instead of a NameError? >> >>I retract this. ;-) >> >>It's not a good idea. But assigning to None as a way to unbind a name >>may still be an option. > > IMO, it isn't. This would completely preclude the usage of None as a value. > None is mostly used as a "null value". The most prominent example is default > function arguments: > > def foo(bar, baz=None): > > With None unbinding the name, what would you suggest should happen? baz being > undefined in the function scope? It would be a way to set an argument as being optional without actually assigning a value to it. The conflict would be if there where a global with the name baz as well. Probably it would be better to use a valid null value for what ever baz if for. If it's a string then "", if its a number then 0, if it's a list then [], etc... If it's an object... I suppose that would be None... Oh well. ;-) > Or, what should happen for > > somedict[1] = None Remove the key of course. var = somedict[1] Would then give an error. and (somedict[1] == None) Would evaluate to True. > ? Also, the concept of _assigning_ something to a name to actually _unassign_ > the name is completely wrong. That's not anymore wrong than ([] == [None]) --> False. Having a None value remove a name binding could make the above condition True. > Of course, this is a possible way to unassign names if (and only if) > (1) there is a real "undefined" value (not None) > (2) unbound names return the undefined value > > Look at Perl. Do we want to be like that? ;) > > Reinhold The problem I had with perl is that number of symbols and ways of combining them can be quite confusing when you don't use it often. So it's either a language you use all the time... or avoid. Anyway, there seems to be enough subtle side effects both small and large to discount the idea. While implementing it may be possible, it would require a number of other changes as well as a different way of thinking about it, so I expect it would be disliked quite a bit. Cheers, Ron From notareal at address.com Tue Jul 12 18:33:06 2005 From: notareal at address.com (Jive Dadson) Date: Tue, 12 Jul 2005 22:33:06 GMT Subject: new division in Pythonwin Message-ID: I like to use Pythonwin as my desktop calculator. It's bothersome to have to type in "from __future__ import division" into the interactive window every time I open it. I've tried various ways to attempt to get it to import new division at startup, but no luck. I can get it to execute a file, but apparently it does so in an environment that gets discarded, rather than in the environment of the interactive window. So the "from __future__" statement has no effect. Any suggestions? Thankee. From sethjn at gmail.com Sat Jul 30 14:01:18 2005 From: sethjn at gmail.com (Seth Nielson) Date: Sat, 30 Jul 2005 11:01:18 -0700 Subject: A replacement for lambda In-Reply-To: <3l1blnF10c1i9U1@individual.net> References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> <3l1blnF10c1i9U1@individual.net> Message-ID: I understand that there are a number of people who wish to remove lambda entirely from the language. Nevertheless, I find it a useful and powerful tool in actual development. Any replacement must support the following: *delayed evaluation*. I need a convenient (def is not always convenient) way of saying, "don't do this now". That is why I use lambda. -- Seth Nielson On 7/30/05, Reinhold Birkenfeld wrote: > Stefan Rank wrote: > > on 30.07.2005 10:20 Paolino said the following: > >> why (x**2 with(x))<(x**3 with(x)) is not taken in consideration? > >> > >> If 'with' must be there (and substitue 'lambda:') then at least the > >> syntax is clear.IMO Ruby syntax is also clear. > >> > > > > I am sorry if this has already been proposed (I am sure it has). > > > > Why not substitue python-lambdas with degenerated generator expressions:: > > > > (lambda x: func(x)) == (func(x) for x) > > > > i.e. a one time callable generator expression (missing the `in` part). > > The arguments get passed into the generator, I am sure that can be > > combined with the PEP about passing args and Exceptions into a generator. > > It's hard to spot, and it's too different to a genexp to have such a similar > syntax. > > Reinhold > -- > http://mail.python.org/mailman/listinfo/python-list > From me at privacy.net Thu Jul 21 23:12:33 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 21 Jul 2005 23:12:33 -0400 Subject: Setting environment variables for tcsh session References: Message-ID: On Thu, 21 Jul 2005 21:39:01 -0500, David Durkee wrote: > I'm trying to write a script I can run from tcsh in Terminal (on Mac > OS X) that will set environment variables that can be accessed by > subsequent commands I execute in that session. Not having any luck so > far. Here's what I've tried: By design, you can't do that (think of the problems if arbitrary programs could change your interactive shell's environment behind your back). Processes (your script) cannot change the environment of their parents (your shell). The best you can do is have your script output the right commands and have your shell read them. See "Command Substitution" in the tcsh man page. Regards, Dan -- Dan Sommers From philippe at philippecmartin.com Tue Jul 12 13:34:19 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 12 Jul 2005 17:34:19 GMT Subject: pywin32 com server "cash" question Message-ID: Hi, I just got the pywin32 "hello world" COM server to install and I did manage to use it from VB 6.0. However, there are some glitches I do not comprehend: 1) at one point I got a python runtime error telling me the "testcomserver" was not found - I got rid of that problem by deleteting the appropriate (I hope) registry and reregistering the server 2) If I change the source of the server from: return "Hello" + .... to: return "Hello my friend " + .... I still get "Hello BINGO" only in my VB message box. this even if I try to re-register (which does not seem necessary) the server. Q.1) What could that error have meant ? Q.2) is there a way to "flush" whatever so my new code "Hello my friend" shows up ? The VB looks like this: Private Sub Command1_Click() Dim shdemo = CreateObject("Python.TestServer") MsgBox (shdemo.Hello("BINGO")) End Sub The Python server : class HelloWorld: _reg_clsid_ = "{7CC9F362-486D-11D1-BB48-0000E838A65F}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] #_reg_class_spec_ = "testcomserver.HelloWorld" def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello My Friend " + " " * self.softspace + str(who) if __name__=='__main__': # ni only for 1.4! import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) import pythoncom print pythoncom.CreateGuid() Regards, Philippe From helge at aksdal.net Thu Jul 21 15:55:19 2005 From: helge at aksdal.net (Helge Aksdal) Date: Thu, 21 Jul 2005 21:55:19 +0200 Subject: socket programming In-Reply-To: <1121865616.375295.129420@z14g2000cwz.googlegroups.com> References: <20050719184205.GA24773@mail.smule.com> <1121865616.375295.129420@z14g2000cwz.googlegroups.com> Message-ID: <20050721195519.GA31697@mail.smule.com> * gry at ll.mit.edu [2005/07/20 15:26]: > What I have done in similar circumstances is put in a random sleep > between connections to fool the server's load manager. Something like: > > .import time > .min_pause,max_pause = (5.0, 10.0) #seconds > .while True: > . time.sleep(random.uniform(min_pause, max_pause)) > . do_connection_and_query_stuff() > > It works for me. Just play with the pause parameters until it fails > and add a little. thanks, this worked for me too. slows down the program, but at least it works. :) -- Helge Aksdal From rkern at ucsd.edu Sun Jul 31 05:23:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 02:23:39 -0700 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <7x3bpve8w5.fsf@ruckus.brouhaha.com> Message-ID: phil hunt wrote: > OK, hows this for an idea: > > 1. create a new API, loosely based on the Tkinter API, but more > Pythonic > > 2. implement Tk using this API (probably won't be difficult because > we can use Tkinter as a base) > > 3. Implement bindings to Gtk and Qt/KDE using this API. Like PyGUI, more or less? http://www.cosc.canterbury.ac.nz/~greg/python_gui/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From thomasbartkus at comcast.net Mon Jul 18 20:35:02 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 18 Jul 2005 19:35:02 -0500 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: <863bqbu0rb.fsf@bhuda.mired.org> Message-ID: On Mon, 18 Jul 2005 19:56:24 -0400, Mike Meyer wrote: > "Thomas Bartkus" writes: >>> > Re-train on a new platform, >>> > and re-write from scratch? >> >> What do you do when an open source project you were using gets >> abandoned? > > cvs import -m "sources for orphaned project" > > >> Hard to see much difference here. > > Doing support for object-only distributions is *much* harder than doing > it for source distributions. > > I have a habit of picking products based on technical superiority, not > popularity. As a result, I have a nice collection of orphans. That's > because technical quality has little or nothing to do with > profitability. > > On the other hand, since starting to use open source projects, I've > never had one I depend on fail. I've had some I contributed to fail, but > that's a different thing. I didn't suggest that orphaned open source projects were a problem. I simply point out that they are no more, nor less, of a problem than an orphaned (and paid for!) commercial product. > I suspect that technical quality in open source projects contributes to > their attracting people to support them. Perhaps. And there is no way to support a commercial product other than by becoming an employee. > This makes them ever so > much more attractive than proprietary solutions, where technical quality > seems to be irrelevant to longevity. This last statement sounds too much like a canard. It is difficult to deny that commercial products either put some significant value on the table or go bust. Although people can be, and sometimes are, swindled few can afford to simply throw their money away. IOW - technical quality is *never* irrelivant to longevity. And one must also consider that technical merit, by itself, is rarely sufficient. The open source world is awash with much that is high on technical merit but commercially unviable. There is much out there that one would gladly pay good $ for if only for lack of that last (but most difficult!) 5% effort that would bring many of these projects to fruition. Which brings me back to the point that the difference between free and $500 (or $1000!) amounts to virtually *nothing* when evaluating a tool. You use what is most effective to get the job done. Thomas Bartkus From samgurung at gmail.com Thu Jul 21 09:52:12 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 06:52:12 -0700 Subject: wxPythin installation woes In-Reply-To: References: <1121939845.672075.122220@z14g2000cwz.googlegroups.com> Message-ID: <1121953932.310914.241710@f14g2000cwb.googlegroups.com> Does anyone know if the same can be done in fedora distributions??? Sybren Stuvel wrote: > linuxfreak enlightened us with: > > Turns out that libstdc++.so.5 is needed but I checked and i see > > that libstdc++.so.6 is installed on my system. > > On my system (Ubuntu, based on Debian), I can have multiple versions > of libstdc++ installed at the same time. > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From zen19725 at zen.co.uk Sun Jul 31 05:18:25 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sun, 31 Jul 2005 10:18:25 +0100 Subject: [path-PEP] Path inherits from basestring again References: <3l1q3tF10l1krU1@individual.net> <3l3e2tF10ehjrU1@individual.net> Message-ID: On Sun, 31 Jul 2005 09:48:45 +0200, Reinhold Birkenfeld wrote: >> >> An improvement to what? To how the class is implemented, or to how >> it is used? > >No, the second function is cleaner and more readable than the first, >IMHO. True, but the first function, at all of seven lines, is hardly complicated. I mean, if anyone couldn't understand it, they'd never make a programmer. >> If you mean the former, yes is it, due to the os.path module not >> providing a function that does this. >> >> If you mean the latter, I disagree, because I would then have to >> call it with something like: >> >> pn = normalizePath(Path(p), q) > >That's easily helped by s/tp = p/tp = Path(p)/. I have no idea what that comment means. >> and then I would have the problem that (pn) isn't a string so >> calling a function to write some data into the file at that filename >> would no longer work, i.e. this: >> >> writeFile(pn, someData) >> >> would become this: >> >> writeFile(pn.getString(), someData) > >Why? A Path is a string. Aha, having read about path on the web, I know that now. I also withdraw my objections; it looks like it could well have been useful on some of the projects I've worked on. -- Email: zen19725 at zen dot co dot uk From michael at stroeder.com Wed Jul 13 11:54:53 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 13 Jul 2005 17:54:53 +0200 Subject: DNS access In-Reply-To: <1121265881.737855.284030@g44g2000cwa.googlegroups.com> References: <1121265881.737855.284030@g44g2000cwa.googlegroups.com> Message-ID: laksh wrote: > > is it possible to give parameters like the IP of a DNS server and the > DNS query to a python program and obtain the response from the DNS > server ? http://pydns.sf.net http://www.dnspython.org/ http://www.google.com/search?hl=en&q=python+dns&btnG=Google+Search Ciao, Michael. From rkern at ucsd.edu Sun Jul 31 02:32:28 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 30 Jul 2005 23:32:28 -0700 Subject: shelve: writing out updates?! In-Reply-To: References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: phil hunt wrote: > Obviously it's good when stuff is well documented. > > I wonder if the barrier to good documentation is set too high? > If i wanted to add some documentation here, I'd have to download the > current source for the latest Python documentation, download, > install and learn the code that processes the source documentation, > write my changes then send the results into the CVS. (I'm assuming > that's roughly correct -- I haven't actually done it). No, write the content in a reasonable format (i.e. plain text), post it to the bug tracker, assign it to Fred Drake (I think), and he'll put it in the right format. If it's longer documentation, like for a full module, then it's better to actually learn the LaTeX so it can be dropped in as is. > The point is, that would be a major effort, too major to merely add > a few lines detailing the .sync method. > > But, what if the Python documentation was on a Wiki? Then it would > be easy to update! Of course, we would have to guard against false > or malicious updates, but Wikipedia manage that OK. That's a debatable assertion, but I don't think we'll have the same problems of Wikipedia thanks to the apolitical nature of Python documentation. > The > Documentation Wiki could then be used as a basis for the "official" > documentation that comes with each new release. > > Does this idea make some sense? Or are there hidden pitfalls? Yes! Someone actually has to do it! The same idea has come up time and time again. It's still not here because no one has been able to commit to the effort involved. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From twic at urchin.earth.li Tue Jul 5 16:43:27 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 5 Jul 2005 21:43:27 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: On Tue, 5 Jul 2005, Terry Hancock wrote: > Having said that, I too will miss the *concept* of an anonymous > function, although I wouldn't mind at all if its name changed, or if it > were somehow integrated into the "def" keyword's usage. Using backticks > or some other syntax delimiter also sounds promising, although we're > sort of running out of them. ;-) I understand that the backslash is popular in some ivory-tower functional languages. Currently, a backslash can be used for explicit line joining, and is illegal elsewhere on a line outside a string literal, so i think it's available for this. It would be utterly unpythonic to use puntuation instead of a keyword, and it would make no sense to novices, but it would scare the crap out of C programmers, which has to be worth something. tom -- [Philosophy] is kind of like being driven behind the sofa by Dr Who - scary, but still entertaining. -- Itchyfidget From news at NOwillmcguganSPAM.com Wed Jul 6 09:25:30 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 06 Jul 2005 14:25:30 +0100 Subject: frozenset question In-Reply-To: References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> Message-ID: <42cbdbde$0$10471$da0feed9@news.zen.co.uk> Steven D'Aprano wrote: > There is no significant speed difference between immutable and mutable > sets, at least for queries. Regardless of whether it is successful or > unsuccessful, mutable or immutable, it takes about 0.0000025 second to do > each test of item in set. Why would you need to optimize that? > > If you tell us what you are trying to do, and under what circumstances it > is too slow, we'll see if we can suggest some ways to optimize it. > > But if you are just trying to optimize for the sake of optimization, > that's a terrible idea. Get your program working first. Then when it > works, measure how fast it runs. If, and ONLY if, it is too slow, > identify the parts of the program that make it too slow. That means > profiling and timing. Then optimize those parts, and nothing else. > > Otherwise, you will be like the car designer trying to speed up his sports > cars by making the seatbelts aerodynamic. No need for the 'premature optimization is the root of all evil' speech. I'm not trying to optimize anything - just enquiring about the nature of frozenset. If typing 'frozenset' over 'set' gave me a saving in time or memory (even if tiny) I would favour immutable sets, where appropriate. Thanks for the info. Will -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From philippe at philippecmartin.com Thu Jul 21 06:44:45 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 21 Jul 2005 10:44:45 +0000 Subject: returning list of strings from Python COM to Visual basic 6 In-Reply-To: References: Message-ID: <200507211044.46686.philippe@philippecmartin.com> Thanks a bunch, I'll try this, This raises two questions: 1) How do I declare the receiving VB variable ? 2) Then, can I use the returned object as a COM object: call its public methods (that would be hot)? Dim newobj as ????? newobj = acom.Get_Obj() newobj.A_Public() Regards, Philippe On Thursday 21 July 2005 09:55 am, Stefan Schukat wrote: > You have to wrap the python object with a COM object: > > def Get_Obj(self): > return win32com.server.util.wrap(an_object) > > > Stefan > > > -----Original Message----- > > From: python-list-bounces+sschukat=dspace.de at python.org > > [mailto:python-list-bounces+sschukat=dspace.de at python.org]On Behalf Of > > Philippe C. Martin > > Sent: Thursday, July 21, 2005 1:42 AM > > To: python-list at python.org > > Subject: Re: returning list of strings from Python COM to > > Visual basic 6 > > > > > > I can now pass and return quite a few types except object > > instances: my > > python code gets to the point where I do: > > > > > > def Get_Obj(self): > > ..... > > return an_object > > > > My VB code looks like > > > > Dim obj as Variant > > > > obj = acom.Get_Obj() > > > > > > I get an "unexpected Python error ..... Objects of type > > 'instance' can not > > be converted to a COM VARIANT" > > > > Is there a way out ? > > > > Thanks, > > > > Philippe > > > > Philippe C. Martin wrote: > > > Hi, > > > > > > Is it possible ? > > > > > > ex: return ['1','2'] > > > > > > If so which type should I use in VB ? > > > > > > dim res as ??????? > > > > > > Set testObj = CreateObject("xxxx") > > > > > > res = testObj.AMethodThatReturnsAListOfStrings() > > > > > > > > > Thanks, > > > > > > Philippe > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > The "Leading Manufacturing Test Company of the Year 2005" > http://www.dspace.de/goto?f_s_award -- ************************************* Philippe C. Martin SnakeCard, LLC www.snakecard.com +1 405 694 8098 ************************************* From cliff at develix.com Sun Jul 31 16:57:22 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 13:57:22 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <7xpsszv1v9.fsf@ruckus.brouhaha.com> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xpsszv1v9.fsf@ruckus.brouhaha.com> Message-ID: <1122843443.19618.126.camel@localhost.localdomain> On Sun, 2005-07-31 at 01:03 -0700, Paul Rubin wrote: > Cliff Wells writes: > > Then why are you using Python at all? Shouldn't you be in the "safe > > home" of Java or Visual Basic, where "standards" are all you have? > > I don't know about VB but Java does a much better job of supporting > standards than Python does. Python's advantage is in being a much > more pleasant language to code in. It would benefit greatly from also > doing a better job implementing standards. Many or most of the Python > library modules that purport to implement standards just sort of > get halfway there and then stop. Well, this is a problem with open source in general. Take a look at sourceforget and you'll see hundreds if not thousands of packages that never even made it out of "planning" stages. It might be nice to see some things standardized in Python, but I'm unconvinced that the GUI toolkit is one of them. Different GUI toolkits vary widely in flexibility, ease-of-use (and this varies on who you are), target platform, etc. For instance, I might be inclined to write a GUI in pygame, if the particular app I'm writing required it. Personally, while I prefer wxPython in general, I *like* having options for those times when wxPython simply isn't the right tool for the job. "When all you have is a TkHammer..." Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From mwm at mired.org Sun Jul 31 14:58:24 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 14:58:24 -0400 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: <8664uqhkfj.fsf@bhuda.mired.org> Cliff Wells writes: > On Sun, 2005-07-31 at 00:59 -0400, Mike Meyer wrote: > >> I don't particularly like Tkinter, but it seems to me that it's pretty >> much won. It seems to be installed on every desktop platform along >> with Python. That means that if I want to distribute GUI apps, I'm >> going to cause the least headache for my end users by writing them in >> Tkinter. > > By this argument, we should just give up and use Visual* on Windows. Not for me - my end users don't run Windows. Well, some of them may, but for those, my distribution is even easier to use than the ones you build with py2exe. > The least headache for end users comes from properly packaging your > application. End users shouldn't need to worry about installing third > party packages (or even Python for that matter). Tools such as py2exe > and Inno installer make this pretty simple on Windows, and py2app on > OS/X accomplishes the same. It should be irrelevant to end users what > libraries or tools you use to develop the app. And what do I use to bundle my application for Unix? Most of the things I build get installed on Unix servers. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From Scott.Daniels at Acm.Org Fri Jul 1 13:53:04 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 01 Jul 2005 10:53:04 -0700 Subject: shelve in a ZipFile? In-Reply-To: References: Message-ID: <42c57b58$1@nntp0.pdx.net> Terry Hancock wrote: > I only just recently had a look at the shelve module.... > That would be handy if, for example, I wanted to couple > (and compress into the bargain) by putting my two > shelf files into a single zip archive. You are, however, fooling yourself if you think a shelve solution can be made to gracefully interact with a zip- compressed version. In order to zip the shelve data, it must all be seen in a pass, so every update would necessarily rewrite the entire shelve storage. much better to extract the entire shelve file, operate on it, and re-compress it. Even if uncompressed, the zip archive format is not going to happily allow you to change the size of any of the "files" it stores. --Scott David Daniels Scott.Daniels at Acm.Org From quentel.pierre at wanadoo.fr Wed Jul 6 15:50:43 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Wed, 06 Jul 2005 21:50:43 +0200 Subject: Strange os.path.exists() behaviour Message-ID: <42cc3613$0$22287$8fcfb975@news.wanadoo.fr> os.path.exists(path) returns True if "path" exists But on Windows it also returns True for "path" followed by any number of dots : Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.exists('Lib/os.py') True # expected >>> os.path.exists('Lib/os.py.') True # unexpected >>> os.path.exists('Lib/os.py.....') True # unexpected >>> Is there a reason for this ? Is there a test that returns True only for the really existing path ? Pierre From nospam at [127.0.0.1] Wed Jul 20 01:51:05 2005 From: nospam at [127.0.0.1] (Chris) Date: Wed, 20 Jul 2005 06:51:05 +0100 Subject: Could anyone write a small program to log the Signal-to-Noise figures for a Netgear DG834 router? References: <1121813534.868644.30590@g47g2000cwa.googlegroups.com> Message-ID: In article <1121813534.868644.30590 at g47g2000cwa.googlegroups.com>, "sp1d3rx at gmail.com" writes >Chris, How would a wireless router show a signal to noise ratio? >Especially if it's providing the signal? The Netgear DG834 is a wired router. Its statistics page gives line loss and SNR. -- Chris From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 08:10:22 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 14:10:22 +0200 Subject: wxPython & Fedora Core 4 References: <1122005756.744692.285840@f14g2000cwb.googlegroups.com> Message-ID: Christophe Lambin enlightened us with: > However, since your wxPython package wasn't built for FC4, you may > run into other problems. That should be solved by recompiling the wxPython RPMs. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From sjmachin at lexicon.net Tue Jul 26 10:06:09 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 27 Jul 2005 00:06:09 +1000 Subject: regex problem In-Reply-To: References: <42e62ff6$1@news.eftel.com> Message-ID: <42e64351$1@news.eftel.com> Duncan Booth wrote: > John Machin wrote: > > >>So here's the mean lean no-flab version -- you don't even need the >>parentheses (sorry, Thomas). >> >> >>>>>rx1=re.compile(r"""\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,""") >>>>>rx1.findall("1234,2222-8888,4567,") >> >>['1234,', '2222-8888,', '4567,'] > > > No flab? What about all that repetition of \d? A less flabby version: > > >>>>rx1=re.compile(r"""\b\d{4}(?:-\d{4})?,""") >>>>rx1.findall("1234,2222-8888,4567,") > > ['1234,', '2222-8888,', '4567,'] > OK, good idea to factor out the prefix and follow it by optional -1234. However optimising re engines do common prefix factoring, *and* they rewrite stuff like x{4} as xxxx. Cheers, John From rbt at athop1.ath.vt.edu Thu Jul 14 13:38:59 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 14 Jul 2005 13:38:59 -0400 Subject: all possible combinations In-Reply-To: <42d6662a$1@news.eftel.com> References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> Message-ID: <1121362739.24407.4.camel@athop1.ath.vt.edu> Thanks to all who were helpful... some of you guys are too harsh and cynical. Here's what I came up with. I believe it's a proper combination, but I'm sure someone will point out that I'm wrong ;) groups = [list('abc'),list('abc'),list('abc'),list('abc')] already = [] while 1: LIST = [] for g in groups: sample = random.sample(g, 1) LIST.append(sample[0]) STRING = ''.join(LIST) if STRING not in already: print STRING already.append(STRING) if len(already) == 81: break On Thu, 2005-07-14 at 23:18 +1000, John Machin wrote: > Steven D'Aprano wrote: > > On Thu, 14 Jul 2005 08:49:05 +1000, John Machin wrote: > > > > > >>"You keep using that word. I do not think it means what you think it means." > >> > >>Both of you please google("define: combination") > > > > > > Combination: "a coordinated sequence of chess moves". > > > > "An option position that is effected by either a purchase of two long > > positions or two short positions. The investor purchases a call and a put > > (or sells a call and a put) with different expiration dates and/or > > different strike prices." > > > > Or perhaps "in Scheme, a function call, consisting of a function name and > > arguments written within parentheses." > > > > Yes, mathematically the definition of combination includes that order does > > not matter. But that certainly isn't the case in common English. Now, > > John, given the tone of the posts you are complaining about, > > Wrong -- no complaint. Another quote: "It's a joke, Joyce!" > > > do you think > > I was using combination in the precise mathematical sense, or the common > > English sense? > > As in "Please don't get your combinations in a twist?"? > > > > > (Hint: the very first definition Google finds is "a collection of things > > that have been combined; an assemblage of separate parts or qualities ". > > Not a word there about order mattering or not.) > From rkern at ucsd.edu Sat Jul 2 14:08:15 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 02 Jul 2005 11:08:15 -0700 Subject: A brief question. In-Reply-To: References: Message-ID: Nathan Pinno wrote: > > Hi all, > > Brief question for anyone who knows the answer, because I don't. Is > there anyway to make Python calculate square roots? http://docs.python.org/ There is a search facility. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sameer_deshpande at hotmail.com Wed Jul 13 07:33:40 2005 From: sameer_deshpande at hotmail.com (sameer_deshpande) Date: 13 Jul 2005 04:33:40 -0700 Subject: Console logging/output for DocXMLRPCServer Message-ID: <1121254420.108281.119370@z14g2000cwz.googlegroups.com> Hello, I have written simple code using DocXMLRPCServer. How do I log method name on the console after invoking registered method on server. On the console it just prints message as [hostname - date/time and "POST /RPC2 HTTP/1.0" 200 -] code is: from DocXMLRPCServer import DocXMLRPCServer def Test(dummy): print dummy return 1 if __name__ == '__main__': server = DocXMLRPCServer(("", 8000, logRequests = 1)) server.register_function(Test) server.serve_forever() ----------------- >>> import xmlrpclib >>> s = xmlrpclib.Server("http://localhost:8000") >>> s.Test("Hello") Output of console after invoking method Test is: hostname - - [13/Jul/2005 13:28:04] "POST /RPC2 HTTP/1.0" 200 - Thanks Sameer From harold.fellermann at upf.edu Wed Jul 6 13:29:18 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 6 Jul 2005 19:29:18 +0200 Subject: inheriting file object In-Reply-To: References: Message-ID: <64ec755851ab67842e1a7f8a04ed6bc9@upf.edu> On 06.07.2005, at 18:58, Jeremy wrote: > Hello all, > I am trying to inherit the file object and don't know how to do it. I > need to open a file and perform operations on it in the class I am > writing. I know the simple syntax is: > > class MyClass(file): > ... > > but I don't know how to make it open the file for reading/writing. Can > anyone help me out with this? just invoke file.__init__ inside your own init. if you don't need to do any initializiation in myFile.__init__, just leave the method and file.__init__ will be invoked automatically. class myFile(file) : def __init__(self,fname,mode="r") : file.__init__(self,fname,mode) for line in myFile('testfile') : print line - harold - -- If your only tool is a hammer, every problem looks like a nail. -- From franz.steinhaeusler at gmx.at Wed Jul 20 07:56:43 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 20 Jul 2005 13:56:43 +0200 Subject: Python IDE References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> <1121828209.276340.9640@o13g2000cwo.googlegroups.com> Message-ID: On 19 Jul 2005 19:56:49 -0700, "Luis M. Gonzalez" wrote: >Have you tried PyCrust? >http://sourceforge.net/projects/pycrust/ It is long time ago, that pycrust was delevoped as sourceforge project. It is part of the wxPython distribution and I have recently added some features. You could take a look at wxPython-user mailing list. Pycrust is great to try/play with Python and wxPython. But also DrPython has a powerful shell prompt. -- Franz Steinhaeusler From peter at engcorp.com Fri Jul 29 08:08:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 08:08:56 -0400 Subject: pySerial Windows write problem In-Reply-To: References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: Bob Greschke wrote: > "Peter Hansen" wrote in message > >>I'd call it very unusual >>(in my experience) to have a program open and close a serial port >>repeatedly. > > One of the serial ports (there are actually two) is used to read some NMEA > sentences from a GPS. It is only rarely read. If it is also opened when > the program starts and kept open would you just dump the buffer and then > read to get the most current info? What happens when the buffer fills up? > The "main" port is just commands sent, responses received kind of traffic. Generally, yes, you just dump data received up to the point you are about to send a new request (if this is a request/response type of thing). PySerial has a .flush() method of some kind I believe, or you can just loop as long as inWaiting() isn't False. If you aren't using hardware or software handshaking, then the buffer filling up is a non-issue for you or the sender. If you're using handshaking, then you do have to keep the buffer from filling. Pretty much all my interesting code runs the PySerial stuff in a separate thread, reading whenever data is available, and (this is a simplification) posting it to a Queue which the main thread can read from as required. In that scenario, you could just have a flag that causes the receive thread to stop posting stuff to the Queue where you currently have close the port to prevent data being seen. I don't recall: is NMEA 0183 asynchronous? Messages can be sent by the GPS even when you didn't ask for one explicitly? If so, then it's possible there are problems even with your current approach: what if you open the port halfway through a packet, and receive only the last few bytes? If it's synchronous (data sent only in response to your requests), then none of this is an issue since there will be no traffic unless you ask for it, so the serial port will be idle between uses. -Peter From jabel at plus.net Thu Jul 21 06:42:09 2005 From: jabel at plus.net (John Abel) Date: Thu, 21 Jul 2005 11:42:09 +0100 Subject: Generating images with text in them In-Reply-To: References: Message-ID: <42DF7C01.5040501@plus.net> Have you downloaded the pilfonts.zip from effbot.org? J phil hunt wrote: >I am trying to generate some images (gifs or pngs) with text in >them. I can use the Python Imaging Library, but it only has access >to the default, rather crappy, font. > >Ideally I'd like to use one of the nicer fonts that come with my X >Windows installation. Using Tkinter I can draw these fonts on the >screen; is there any way to get these fonts into a bitmapped image? >For example, can I draw some text on a canvas and then "grab" that >canvas as a bitmap into PIL, and then save it as a file? > >Alternately, is there a good source of PIL font files (.pil files) >somewhere? > >If the writers of the Python Imaging Library are reading this, may I >suggest that they add more fonts to it. Yes, that would increase >the size, but these days disk space is cheap and programmer time >expensive. > > > From me at privacy.net Sat Jul 30 20:09:18 2005 From: me at privacy.net (Dan Sommers) Date: Sat, 30 Jul 2005 20:09:18 -0400 Subject: functions without parentheses References: <42e9c49b.24281464@news.oz.net> <42ebc3e4.155170673@news.oz.net> Message-ID: On Sat, 30 Jul 2005 18:42:59 GMT, bokr at oz.net (Bengt Richter) wrote: > or > arr = (ArrayElementAggregator() > 11 12 13 > 21 22 23 > ) What was that again about every other computer language wanting to be Lisp? ;-) Regards, Dan -- Dan Sommers From andreas at kostyrka.org Wed Jul 13 04:12:33 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 10:12:33 +0200 Subject: threads and sleep? In-Reply-To: <1120577852.042709.251940@o13g2000cwo.googlegroups.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <1120577852.042709.251940@o13g2000cwo.googlegroups.com> Message-ID: <1121242353.5240.68.camel@andi-lap> Am Dienstag, den 05.07.2005, 08:37 -0700 schrieb Jonathan Ellis: > In many ways, Python is an incredibly bad choice for deeply > multithreaded applications. One big problem is the global interpreter > lock; no matter how many CPUs you have, only one will run python code > at a time. (Many people who don't run on multiple CPUs anyway try to > wave this off as a non-problem, or at least worth the tradeoff in terms > of a simpler C API, but with multicore processors coming from every > direction I think the "let's pretend we don't have a problem" approach > may not work much longer.) Well, it's not a tradeoff in a simpler C API. It's a more complicated thing. Much more complicated. ;) Basically nobody has been able to propose a sensible solution for removing the GIL. Any solution would have to have the following properties: a) must be safe. b) should be probably not slow as a snail ;) The problem with a) is that loosing this property is not a proposition. As it is probably a core benefit of Python. So the ceval function would have to lock any object used it encounters when executing. Trouble: How to deal with deadlocks. And it would entail locking and unlocking heaps of objects on any line of Python code. Basically the current state of art in "threading" programming doesn't include a safe model. General threading programming is unsafe at the moment, and there's nothing to do about that. It requires the developer to carefully add any needed locking by hand. Any error in doing that will give very hard to debug errors that might show up only in very specific hardware configurations. And there is no way to detect these errors automatically, which would be needed to raise a nice exception, which is the standard at the moment in Python. > > If the GIL isn't an issue (and in your case it clearly is), you'll > quickly find that there's little support for debugging multithreaded > applications, and even less for profiling. As I've said above, there is a case that the current "safe computing" model of Python isn't compatible with the current state of art in threading. > > Sometimes running multiple processes is an acceptable workaround; if > not, good luck with the rewrite in Java or something else with real > thread support. (IIRC Jython doesn't have a GIL; that might be an > option too.) Jython might not have a GIL, but it probably will be have really bad performance because it has to lock all kind of objects during executation. > > Python is a great tool but if you really need good threading support > you will have to look elsewhere. Yes and no. For a completely general threading support, Python isn't probably what one wants. OTOH general threading developement is a bit more painful than many application developers want to endure. There are ways to do a more structured threading in Python quite ok: a) rewrite your number crunching thread stuff in C and release the GIL. b) if you've got a task that can live with less communication -> one might fork of some computation and communicate the results via pipe. c) Live with the GIL. While multi-core CPUs are coming, it will a time before the mainstream hardware will get to more than 2 logical CPUs. You get quite a bit of speedup already by delegating all the OS and other background tasks to one CPU core. And one thing one shouldn't forget is that finely multithreaded apps aren't faster magically. If you spend need to add 50% more work for locking, you will not get many benefits from threading on a 2 core box: Assuming a two-core box does have about the processing power of 1.8 cores (because of memory contentation, and other problems. Depending upon use and the exact hardware it might be even worse than that). Now your single-threaded app runs 10seconds. With locking this would be about 15seconds. 15 seconds divided by 1.8 gives 8.33seconds. And that assumes that your application is perfectly threadable and will have no contentation for data between it's threads. And it assumes a favorable 1.8 speedup factor for 2 cores. And the hardware level overhead for more cores goes up, especially if you run multiple threads of one program -> because the fine interaction between this threads raises the contentation for data between the cores/processors. So, yes Python isn't multithreading well. At least not at the moment. But this is basically there isn't currently a theoretical way to provide the environment that Python does safely in a multithreaded app without an incredible performance hit. Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From titogarcia_borra_esto at gmail.com Wed Jul 27 15:28:46 2005 From: titogarcia_borra_esto at gmail.com (Tito) Date: Wed, 27 Jul 2005 21:28:46 +0200 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: Once again: thank you. From peter at engcorp.com Sat Jul 2 07:36:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 07:36:49 -0400 Subject: wxPython: Terminal Output -> Scrollable Panel? In-Reply-To: <1120289025.359671.148450@g14g2000cwa.googlegroups.com> References: <1120289025.359671.148450@g14g2000cwa.googlegroups.com> Message-ID: <-uOdneuY58vY4VvfRVn-sA@powergate.ca> flamesrock wrote: > I want to make it so that clicking on a button that performs an > operation will output it to the scrollable wxpython terminal panel, and > (if possible) save that output as text (or maybe into a logfile). The example code includes something called "PyCrust" which does pretty much this. (The logging part is fairly trivial, so I won't mention it.) I'm sure you could look in the source to learn more. You can start by running the demo, and finding that particular one, playing with it a bit, and then seeing how the demo code invokes PyCrust. Then find the source for PyCrust in the wxPython folder (under your lib/site-packages folder in c:\python24) and start reading. -Peter From tjreedy at udel.edu Sat Jul 2 15:43:51 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 2 Jul 2005 15:43:51 -0400 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: "Colin J. Williams" wrote in message news:gaxxe.15816$mK5.1126958 at news20.bellglobal.com... >Isn't this where the discussion should start? There should be some >general policy guiding the types of modules which should be in the >standard library. A couple of times, Guido has given his general policy as generally useful; best-of-breed, tested and accepted by the community; and backed by a developer who will adapt it and its doc up to stdlib standards (if necessary) and commit to maintainence for a few years. Terry J. Reedy From exarkun at divmod.com Sun Jul 3 01:09:28 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 3 Jul 2005 01:09:28 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: Message-ID: <20050703050928.26278.1428199365.divmod.quotient.4639@ohm> On Sun, 03 Jul 2005 01:01:18 -0400, Christopher Subich wrote: >Steven D'Aprano wrote: >> comps. But reduce can't be written as a list comp, only as a relatively >> complex for loop at a HUGE loss of readability -- and I've never used >> Lisp or Scheme in my life. I'm surely not the only one. > >See my reply to your other post for a more detailed explanation, but I >don't think that the for-loop solution is much less readable at all, and >the additional complexity involved is simply setting the initial value >and result for the accumulator. The for-loop solution is even more >flexible, because it can include anonymous code blocks and not just >expressions. > >One caevat that I just noticed, though -- with the for-solution, you do >need to be careful about whether you're using a generator or list if you >do not set an explicit initial value (and instead use the first value of >'sequence' as the start). The difference is: >_accum = g.next() >for i in g: _accum = stuff(_accum,i) > >versus >_accum = g[0] >for i in g[1:]: _accum = stuff(_accum,i) In either case, you want to write: i = iter(g) _accum = i.next() for elem in i: _accum = stuff(_accum, elem) You also want to catch the StopIteration from that explicit .next() call, but that's an unrelated matter. Jp From none at pacbell.net Thu Jul 14 12:20:15 2005 From: none at pacbell.net (Richard) Date: Thu, 14 Jul 2005 16:20:15 GMT Subject: Efficiently Split A List of Tuples References: Message-ID: On Wed, 13 Jul 2005 20:53:58 -0400, Peter Hansen wrote: > a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) > zip(*a) > This seems to work. Thanks. Where do I find documentation on "*args"? From fernandomirandamuro at gmail.com Sat Jul 30 17:44:45 2005 From: fernandomirandamuro at gmail.com (Fernando M.) Date: 30 Jul 2005 14:44:45 -0700 Subject: python SMTP server Message-ID: <1122759885.881136.186360@g47g2000cwa.googlegroups.com> Hi, i made a test with smtplib module a few days ago, for sending mails, and i was wondering if there's another module for running an SMTP server, so i could make a standalone script for sending mails without using an external SMTP server. I've been searching but i'm not sure if there are modules for it, or anything. Which ones are my options? Thanks. From cliff at develix.com Sun Jul 31 20:09:09 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 17:09:09 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <7xr7de5zoe.fsf@ruckus.brouhaha.com> References: <20050730171613.1839738924.EP@zomething.com> <200507302029.34011.jstroud@mbi.ucla.edu> <7xy87nctxm.fsf@ruckus.brouhaha.com> <7xr7de5zoe.fsf@ruckus.brouhaha.com> Message-ID: <1122854949.19618.193.camel@localhost.localdomain> On Sun, 2005-07-31 at 16:22 -0700, Paul Rubin wrote: > Cliff Wells writes: > > wxWidgets/wxPython hasn't required GTK 1.x in quite a long time. Please > > get your facts straight. > > It did last time I tried installing it, which was maybe 3-6 months ago. > Someone posted that it had been updated recently. Looking on SourceForge, I see that 2.4.2.4 had GTK2 builds and it's dated 2003-10-01. I also know that GTK2 support came well before this and was in fact a build option long before Robin made an official release. Unfortunately SF doesn't go back any further than this and I don't have time to research it further. Nevertheless it's provable that wxPython had GTK2 releases almost 2 years ago. http://sourceforge.net/project/showfiles.php?group_id=10718&package_id=10559 > I spent several hours trying to install wxPython on Linux without > success (a lot of that was figuring out that some undefined symbol it > was complaining about was some GTK 1.5 function that had didn't exist > in GTK 2.1). As I remember, wxPython itself compiled without too much > trouble but wxWidgets and/or GTK 1.5 (once I got a copy of that) had > some problems. I decided I just didn't care enough to keep pursuing it. I've seen a few people run into issues like this, usually as the result of autoconf/automake finding obsolete libraries on a system (e.g. if you upgraded your redhat from 7.3 to 9.0 and stale libraries were left around). This isn't specific to wx, I've seen similar problems with other software (PostgreSQL being a common one). They can usually be fixed, but it does take some sleuthing. Still, can't really blame wx for this as it's more the distro's fault for not having good update/packaging systems. > > > http://www.software-lab.de/down.html > > > > It sounded interesting until you said "Java Applet". Talk about causing > > deployment issues... > > Yeah, I don't have Java in my browser, but it's very widely deployed. > For most of the stuff I do though, a plain HTML interface is fine. Yah, I think Java is the one thing I've never had work satisfactorily (read "without crashing or failing to load altogether") on Fedora/Redhat. For a while I had it working with the JVM from IBM, but those happy days are long gone. I now simply ignore apps written in Java. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From philippe at philippecmartin.com Tue Jul 5 17:56:15 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 05 Jul 2005 21:56:15 GMT Subject: How to display Values of a file References: Message-ID: <3mDye.2498$vT3.2484@newssvr30.news.prodigy.com> I think you'll have to go through extensions: http://starship.python.net/crew/mhammond/ Regards, Philippe Kakushi wrote: > Hi my name is Andrew beginning/intermediate Python User. I am using a > win xp computer Python 2.4 > > I would like to write a python application that would allow me to view > paths of all installed files and registry values associated with that > file for example I enter the file C:\WINDOWS\iexplorer.exe and it gives > me reg value 1, reg value 2, folder 1, folder 2. > > This will eventually lead into running an application installer, for > example C:\setup.exe and running through the processes of the install > displaying a listing of all associated files with that install through > my application > > Is this something that is possible with Python if so what modules should > I look into If so has anyone done anything similiar > > if not I guess I will have to look into different ideas From flyaflyaa at gmail.com Tue Jul 26 02:06:58 2005 From: flyaflyaa at gmail.com (flyaflya) Date: Tue, 26 Jul 2005 14:06:58 +0800 Subject: [pygame]how to copy a surface to an other surface with alpha value? Message-ID: I want to join some surfaces to a new big surface with alpha cannel, I want the new surface has same pixels(inclue r,g,b and alpha value) as the pixels on the source surfaces. my code as follow: surf = pygame.Surface((200,200)) surf.blit(surf1, (0,0)) surf.blit(surf2, (0,100)) ..... but these codes can't copy alpha value to the new surface.how can I deal with it? From dave at boost-consulting.com Wed Jul 6 19:45:10 2005 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 06 Jul 2005 19:45:10 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <42cc41c5$0$23671$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers writes: > I discovered FP with David Mertz's papers about FP in Python. I had > never read nor write a line of lisp, scheme, haskell, caml etc before. > And I'd certainly start thinking of choosing another MYFL if anonymous > functions where to disappear from Python. Note that I said "anonymous > functions", not "lambda". Concerning map, filter, reduce etc, these > functions can live in a separate module, and this wouldn't bother me. > But anonymous functions are part of the language syntax, so there is no > work-around. Actually I'm pretty sure there is. It should be possible to re-implement the Boost Lambda library in Python: http://www.boost.org/libs/lambda Compared with in-language lambda support it would have the advantage of brevity and clarity for very small functions, but there are lots of disadvantages, too. I wonder how Guido would feel if people started using a (relatively) slow library solution with odd warts as a consequence of dropping real lambdas. -- Dave Abrahams Boost Consulting www.boost-consulting.com From benji at benjiyork.com Mon Jul 18 22:47:52 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 18 Jul 2005 22:47:52 -0400 Subject: How do I send keystrokes to a console window in Windows XP? In-Reply-To: <1121713006.253298.302050@g49g2000cwa.googlegroups.com> References: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> <1121713006.253298.302050@g49g2000cwa.googlegroups.com> Message-ID: <42DC69D8.8030009@benjiyork.com> GoogleGroups at garringer.net wrote: > This gives me hope, but what I really need to do is to send keystrokes > to an <<>> console window. That's exactly what the code does. Try it out, you'll see how it works quickly enough. -- Benji York From guy.lateur at b-b.be Mon Jul 4 03:42:36 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Mon, 04 Jul 2005 07:42:36 GMT Subject: Outlook COM: how to create a MailItem from a .msg file Message-ID: Hi all, I've been writing some code to move some data into and out of Outlook (2003 + Exchange 2003). I have some email .msg files on our file server, and I can't seem to get them back into the Outlook object I need, ie a MailItem. I've tried to use App.CopyFile() to (temporarily) put the file in an OL folder. Problem is, however, this returns a DocumentItem and not a MailItem. Is there any way I could 'cast' this DItem into a MItem? Apparently, OL treats it as any general document - which, btw, shows in the view, too; it has another icon and you have to open it to view it). Or maybe there's another way to open it; I really only need the object in memory. Any ideas? TIA, g From cam.ac.uk at mh391.invalid Fri Jul 29 11:30:07 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 29 Jul 2005 16:30:07 +0100 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> Message-ID: Dark Cowherd wrote: > GUI, Web development, Application Framework - it is shambles. Yeah, I agree. When I finally make that GUI application I still don't know whether I am going to use wx or PyGTK. > Is there some place to discuss topics like this? Is this the right place? Sure, although you might want to start a new thread. ;) -- Michael Hoffman From rkern at ucsd.edu Fri Jul 22 18:24:23 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 22 Jul 2005 15:24:23 -0700 Subject: sys.path - stuff from nowhere? In-Reply-To: References: Message-ID: Richard Kessler wrote: > Just build python 2.3.4 (needed for Zope and Plone). Trying to learn more > about use the data in sys.path from importing. When I run Python at the > command prompt, import sys and print sys.path I get stuff that makes no > sense. For example, /usr/local/lib/python23.zip. Python can import from zip files, now, so yes, it does make sense. http://www.python.org/peps/pep-0273.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From anupam.kapoor at gmail.com Tue Jul 26 02:13:04 2005 From: anupam.kapoor at gmail.com (Anupam Kapoor) Date: 25 Jul 2005 23:13:04 -0700 Subject: Extreme n00b question Message-ID: <1122358384.455900.91810@g44g2000cwa.googlegroups.com> hi all, a python n00b, so please bear with me. i have a simple question: i generally name python sources as a-simple-python-example.py. when i try to import a module named as above, i (obviously) get tracebacks from python interpreter. is there a way to continue naming python sources as above, and still use it as python modules ? i can ofcourse change the name to 'a_simple_python_example.py', which then works. thank you kind regards anupam From dial#####$$NOSPAM##$#$##tone at gmail.com Tue Jul 19 14:25:59 2005 From: dial#####$$NOSPAM##$#$##tone at gmail.com (Valentino Volonghi aka Dialtone) Date: Tue, 19 Jul 2005 20:25:59 +0200 Subject: Web Framework Reviews References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121796584.974756.132430@g14g2000cwa.googlegroups.com> Message-ID: <1gzyqri.s6s21q14w2934N%dial#####$$NOSPAM##$#$##tone@gmail.com> istvan.albert at gmail.com wrote: > I think you should take what you posted above and put it up on your > main site, because right now there is no way to find any information > like this. Your entire intro is about templating and leaves one with > no clues as to what else is there. Right now there are at least 2 web sites: http://divmod.org/users/exarkun/nevow-api/ + file inevow.py in nevow. http://divmod.org/users/mg/nevow-doc/ And a new one: http://dictator.kieranholland.com/prose/Meet%20Stan.html And the page I linked in my previous post: http://nevowexamples.adytum.us/ this is a living site with the living examples distributed with nevow. at least one example of formless does not work right now because of changes that we are doing in trunk right now (only formless has some problems, all the others work pretty well). There are really a lot of examples, and you can learn a lot of stuff from them. More documentation will be useful for sure, but by just coming in the irc channel #twisted.web on freenode you would have obtained all the answers you wanted to write a better review paper :). > One remark regarding stan. For me it is inconceivable that one would > build (and debug) any complicated webpage as stan does it, one element > at a time: > > docFactory = loaders.stan( > t.html[t.head[t.title["Session example"]], > t.body[display_session]] > ) > > The pages that I have to build invariably contain multiple nested html > tables etc. I shudder to think that I would ever have to build them > like that. I know you have an "inverse" ZPT like templates those are a > lot friendlier on the eyes. For someone who is does not know what Nevow > is seeing an example of Stan is very scary because IMO it does not > scale at all. This again is just an opinion. I have a little project, developed during my little free time that is linked in my signature (weever). It has over 2000 lines of xhtml templates and you can see a living example here: http://vercingetorix.dyndns.org:20080/ I can guarantee you that when templates begin to be a bit too complex stan is what saves the day. I usually use xhtml for everything (and nevow has the best templating engine out there thanks to its flexibility and simplicity, there are only 3 special tags and 3 attributes, and we are working to make it even easier than that) but when xhtml gets complicated stan is incredibly useful. Anyway stan is also incredibly useful to write little examples without requiring a new xhtml file (ok... you may use loaders.xmlstr but...) And it does scale well anyway (Quotient is entirely built using stan and it's very big). Templating engines like ZPT prefer to put some code in the template, Nevow prefers to put code in python and allow you to write some xhtml in python too. python is easier to manage and less likely to be screwed by any designer that doesn't know what python is. > Thanks for the explanations. np :) -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.4 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From ujelin at yahoo.com Fri Jul 22 12:03:02 2005 From: ujelin at yahoo.com (ulrice jardin) Date: Fri, 22 Jul 2005 09:03:02 -0700 (PDT) Subject: decoding html Message-ID: <20050722160302.34873.qmail@web60318.mail.yahoo.com> hi, is there any function that decodes html special characters? thx __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tdickenson at devmail.geminidataloggers.co.uk Wed Jul 6 06:58:48 2005 From: tdickenson at devmail.geminidataloggers.co.uk (Toby Dickenson) Date: Wed, 6 Jul 2005 11:58:48 +0100 Subject: System Independent Wallpaper Changer In-Reply-To: <42cb220c$1_5@alt.athenanews.com> References: <42cb220c$1_5@alt.athenanews.com> Message-ID: <200507061158.48719.tdickenson@devmail.geminidataloggers.co.uk> On Wednesday 06 July 2005 01:12, Terrance N. Phillip wrote: > I've done some searching, and can't seem to find a programatic way of > getting *** that to happen. http://www.google.com/search?q=setwallpaper+dcop I hope this helps -- Toby Dickenson From cam.ac.uk at mh391.invalid Thu Jul 21 18:16:06 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 23:16:06 +0100 Subject: PEP on path module for standard library In-Reply-To: <3kajr8FtfejbU1@individual.net> References: <3kacleFslj6sU1@individual.net> <3kajr8FtfejbU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Michael Hoffman wrote: > >>Having path descend from str/unicode is extremely useful since I can >>then pass a path object to any function someone else wrote without >>having to worry about whether they were checking for basestring. I think >>there is a widely used pattern of accepting either a basestring[1] or a >>file-like object as a function argument, and using isinstance() to >>figure out which it is. > > Where do you see that pattern? IIRC it's not in the stdlib. I do not think it is a *good* pattern, but it is used in Biopython. Of course, there they ARE using things like type("") so on a unicode filesystem it would already break. I seem to recall seeing it elsewhere, but I can't remember where. If you remove the basestring superclass, then you remove the ability to use path objects as a drop-in replacement for any path string right now. You will either have to use str(pathobj) or carefully check that the function/framework you are passing the path to does not use isinstance() or any of the string methods that are now gone. >>What do you gain from removing these methods? A smaller dir()? > > It made sense to me at the time I changed this, although at the moment > I can't exactly recall the reasons. > > Probably as Terry said: a path is both a list and a string. I can see the case for thinking of it in both of those ways. In the end a path is a sequence object. But a sequence of what? I have a path that looks like this: r"c:\windows\system32:altstream\test.dir\myfile.txt.zip:altstream" One way to divide this is solely based on path separators: ['c:', 'windows', 'system32:altstream', 'test.dir', 'myfile.txt.zip:altstream'] But then some of the elements of this sequence have more meaning than just being strings. "c:" is certainly something different from "windows." The file name and alternate data stream name of each element could be represented as a tuple. The extensions can also be dealt with as a sequence. I have dealt with things like filename = "filename.x.y.z" and wanted to get "filename.x" before. The current stdlib solution, os.path.splitext(os.path.splitext(filename)[0])[0] is extremely clunky, and I have long desired something better. (OK, using filename.split(os.extsep) works a little better, but you get the idea.) So if you start breaking the path into a sequence of bigger items than single character, where does it stop? What is a good design for this? -- Michael Hoffman From timr at probo.com Sat Jul 30 01:14:12 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 29 Jul 2005 22:14:12 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42ead151@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > >What kind of shenanigans must a parser go through to translate: > < > >this is the comparison of two functions, but it looks like a left- >shift on a function until the second with is encountered. Then >you need to backtrack to the shift and convert it to a pair of >less-thans before you can successfully translate it. C++ solves this exact problem quite reasonably by having a greedy tokenizer. Thus, that would always be a left shift operator. To make it less than and a function, insert a space: < -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From peter at engcorp.com Sat Jul 16 16:42:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Jul 2005 16:42:58 -0400 Subject: Filtering out non-readable characters In-Reply-To: References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Steven D'Aprano wrote: > On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen wrote: >>Bengt Richter wrote: >> >>> >>> identity = ''.join([chr(i) for i in xrange(256)]) >> >>And note that with Python 2.4, in each case the above square brackets >>are unnecessary (though harmless), because of the arrival of "generator >>expressions" in the language. > > But to use generator expressions, wouldn't you need an extra pair of round > brackets? > > eg identity = ''.join( ( chr(i) for i in xrange(256) ) ) Come on, Steven. Don't tell us you didn't have access to a Python interpreter to check before you posted: c:\>python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 >>> ''.join(chr(c) for c in range(65, 91)) 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' -Peter From rafi at free.fr Wed Jul 27 15:12:03 2005 From: rafi at free.fr (rafi) Date: Wed, 27 Jul 2005 21:12:03 +0200 Subject: multiple inheritance super() In-Reply-To: <1122454160.835071.87690@z14g2000cwz.googlegroups.com> References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> <42e748e9$0$32207$626a14ce@news.free.fr> <1122454160.835071.87690@z14g2000cwz.googlegroups.com> Message-ID: <42e7dc8b$0$6427$626a14ce@news.free.fr> Michele Simionato wrote: >>I am mostly >>using old style (without type unification) init but this motivate the >>shift for the new style. Is there somewhere a document about this? > > Yes, see http://www.python.org/2.3/mro.html by yours truly > > Michele Simionato Thanks a lot -- rafi "Imagination is more important than knowledge." (Albert Einstein) From jaywgraves at gmail.com Tue Jul 12 16:24:18 2005 From: jaywgraves at gmail.com (jay graves) Date: 12 Jul 2005 13:24:18 -0700 Subject: Frankenstring In-Reply-To: References: Message-ID: <1121199858.674056.78250@g14g2000cwa.googlegroups.com> see StringIO or cStringIO in the standard library. From Chan.Fonseka at oracle.com Fri Jul 1 11:16:15 2005 From: Chan.Fonseka at oracle.com (Chan.Fonseka at oracle.com) Date: 1 Jul 2005 08:16:15 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <3ih84nFlkegqU1@individual.net> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <3ih84nFlkegqU1@individual.net> Message-ID: <1120230975.207574.136930@f14g2000cwb.googlegroups.com> T can be silent in England too .. frui' cricke' or replaced with D in the US .. budder ledder From andreas at kostyrka.org Fri Jul 8 09:29:31 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 8 Jul 2005 15:29:31 +0200 Subject: Polling, Fifos, and Linux In-Reply-To: References: Message-ID: <20050708132931.GA2029@heaven.kostyrka.org> On Thu, Jul 07, 2005 at 10:21:19PM -0700, Jacob Page wrote: > Jeremy Moles wrote: > > This is my first time working with some of the more lower-level python > > "stuff." I was wondering if someone could tell me what I'm doing wrong > > with my simple test here? > > > > Basically, what I need is an easy way for application in userspace to > > simply echo values "down" to this fifo similar to the way proc files are > > used. Is my understanding of fifo's and their capabilities just totally > > off base? > > You shouldn't need to use select.poll(), unless I'm missing something. > I was able to get the following to work: Ok, you miss something ;) The program you proposed does busy waiting and without a time.sleep call will consume 100% CPU time :( Actually, with a named fifo the situation gets even nastier: import os, select, time fifo = os.open("fifo", os.O_RDONLY) while True: print "SELECT", select.select([fifo],[],[]) string = os.read(fifo, 1) if len(string): print string else: nf = os.open("fifo", os.O_RDONLY) os.close(fifo) fifo = nf # Perhaps add a delay under an else The problem is, that select (and poll) show a End-Of-File condition by returning ready to read. But on a FIFO, when the first client terminates, the reading end goes into a EOF state till somebody else reopens the fifo for writing. [This bit of wisdom comes Advanced Programming in the UNIX Environment by W.R. Stevens p. 400: 'If we encounter the end of file on a descriptor, that descriptor is considered readbale by select.'] closing the old descriptor must be done after opening a new one, or else you get a tiny moment where a O_WRONLY client is not able to open the file. This way there is always a reading client of the fifo. Andreas > > -=-=- > > import os > > fifo = os.open("fifo", os.O_RDONLY | os.O_NONBLOCK) > > while True: > string = os.read(fifo, 1) > if len(string): > print string > # Perhaps add a delay under an else > > -=-=- > > The Python script, when run, does nothing until you put data into the > fifo from another process. Then it immediately spits the data out, > character by character. > > I'm assuming that you've already created the fifo and that it's in the > current working directory. > -- > http://mail.python.org/mailman/listinfo/python-list From aahz at pythoncraft.com Sun Jul 10 09:21:02 2005 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2005 06:21:02 -0700 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: Roy, I know you actually know this stuff, but for the benefit of beginners.... In article , Roy Smith wrote: > >3) In some cases, they can lead to faster code. A classic example is >counting occurances of items using a dictionary: > > count = {} > for key in whatever: > try: > count[key] += 1 > except KeyError: > count[key] = 1 > >compared to > > count = {} > for key in whatever: > if count.hasKey(key): > count[key] += 1 > else: > count[key] = 1 Except that few would write the second loop that way these days:: for key in whatever: if key in count: ... Using ``in`` saves a bytecode of method lookup on ``has_key()`` (which is the correct spelling). Or you could choose the slightly more convoluted approach to save a line:: for key in whatever: count[key] = count.get(key, 0) + 1 If whatever had ``(key, value)`` pairs, you'd do:: key_dict = {} for key, value in whatever: key_dict.setdefault(key, []).append(value) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From simon.brunning at gmail.com Mon Jul 4 04:27:32 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Jul 2005 09:27:32 +0100 Subject: Lost in a sea of documentation...can you point me in the right direction? In-Reply-To: <42c46e43$0$31194$636a15ce@news.free.fr> References: <1120167496.973373.163400@f14g2000cwb.googlegroups.com> <42c46e43$0$31194$636a15ce@news.free.fr> Message-ID: <8c7f10c605070401271256b3f9@mail.gmail.com> On 6/30/05, Bruno Desthuilliers wrote: > There are 2 problems to solve: > 1/ change the 'wallpaper' > 2/ run as a background task (a 'service' on Win32, a 'daemon' on unix-likes) > > The 2nd one is already solved by your os (use Windows' task scheduler or > *n*x's cron). I was playing about with the 1st problem a couple of years ago: http://www.brunningonline.net/simon/blog/archives/winDesktop.py.html -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From gsakkis at rutgers.edu Wed Jul 13 14:05:35 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 13 Jul 2005 14:05:35 -0400 Subject: all possible combinations References: Message-ID: <1121277937.a2a3097d7c150f1b8a3f41a21a9f2b25@teranews> "rbt" wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: > > 4^3 = 64 It's actually 3^4 = 81 (3 candidates/choice ** 4 choices) > aaaa > abaa > aaba > aaab > acaa > aaca > aaac > ... > > What is the most efficient way to do this? I don't know if it's *the most* efficient -- and I don't think it really matters -- but it's fast, short and sweet: def iterPermutations(num, seq): if num: for rest in iterPermutations(num-1, seq): for item in seq: yield rest + [item] else: yield [] for comb in iterPermutations(4, list("abc")): print ''.join(comb) George From kay.schluehr at gmx.net Mon Jul 11 08:26:18 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Jul 2005 05:26:18 -0700 Subject: decorators as generalized pre-binding hooks References: <42d02c21.231516573@news.oz.net> <1121034087.932596.221010@g43g2000cwa.googlegroups.com> Message-ID: <1121084778.253840.101070@z14g2000cwz.googlegroups.com> George Sakkis schrieb: > > 1. classes have metaclasses, functions don't have metafunctions. No one > > gave an example for classes not handled at least as well with a metaclass. > > Would something like the following count ? > > @abstractclass > class AbstractFrame(object): > > @abstractclass > @innerclass > class AbstractPanel(object): > pass > > For one thing, it's more readable than the respective __metaclass__ > declarations. Moreover, stacking two or more decorators is > syntactically straightforward, while for metaclasses you have to write > boilerplate code for making a subclass of the components, e.g.: > class AbstractInnerClass(AbstractClass, InnerClass): pass > Fortunately metaclasses are not that commonly used to cause > combinatorial explosion of such boilerplate classes. I think it would be a good idea to pronounce the similarity between function decorators and metaclasses. Metaclasses were once introduced as an arcane art of fuzzy bearded hackers or supersmart 'enterprise architects' that plan at least products of Zope size but not as a tool for the simple programmer on the street. But maybe they should be and there should also be librarys of them representing orthogonal customizations ready for plug in. Since metaclasses follow an "adapt", "customize" or "decorate" semantics it is a good idea not to use inheritance to stack them which implies that one metaclass refines an other. +1 for metaclasses as class decorators. Kay From ric at next-level.com.au Mon Jul 11 20:18:58 2005 From: ric at next-level.com.au (Ric Da Force) Date: Tue, 12 Jul 2005 08:18:58 +0800 Subject: Tricky Dictionary Question from newbie References: <3jftckFpvhv2U2@individual.net> Message-ID: Thank you guys! (Reinhold, Mark and Markus) I must confess that I am absolutely awe struck at the power of this language! There is no way in the world that I would have envisaged such simple and elegant solutions!!! Reinhold, is your solution specific to 2.4? Kind Regards, Ric "Reinhold Birkenfeld" wrote in message news:3jftckFpvhv2U2 at individual.net... > Mark Jackson wrote: >> "Ric Da Force" writes: >> >>> It is hard to explain but this is what I mean: >>> >>> Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This >>> is >>> not'} >>> >>> I want this to return a new dict with string keys and lists containing >>> the >>> previous keys for repeated values. >>> >>> NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} >> >> NewDict = {} >> for x in Dict.keys(): >> try: >> NewDict[Dict[x]].append(x) >> except KeyError: >> NewDict[Dict[x]] = [x] > > Or, more up-to-date: > > NewDict = {} > for key, val in Dict.iteritems(): > NewDict.setdefault(val, []).append(key) > > Reinhold From michaelparkin at gmail.com Mon Jul 11 09:29:23 2005 From: michaelparkin at gmail.com (michaelparkin at gmail.com) Date: 11 Jul 2005 06:29:23 -0700 Subject: httplib/HTTPS Post Problem Message-ID: <1121088563.465929.31290@g43g2000cwa.googlegroups.com> Hi, Sorry to post what might seem like a trivial problem here, but its driving me mad! I have a simple https client that uses httplib to post data to a web server. When I post over http & https using curl the data is recieved by the web server with no problems. When I post using my python client the headers get there, but the body of the message does not. My code is pretty standard and has the format: httplib.HTTPSConnection.debuglevel = 1 connection = httplib.HTTPSConnection(host_name, key_file = key, cert_file = cert) connection.putrequest("POST", path) connection.putheader("Content-Length", str(len(body))) ...(some more headers)... connection.endheaders() connection.send(body) response = connection.getresponse() connection.close() (some code has been removed for clarity).. I can see in the debug messages the body getting sent, but nothing arrives at the server... I think I would understand whats going on better if I knew how Python uses the underlying socket - does it a) open the socket, send the header & body together or b) send the header, wait, then send the body? I think the answer to this question solve my problem - can anyone help? Thanks. p.s. I'm using Python 2.3.3 [GCC 3.3.3 (SuseLinx)] From George.Flaherty at marketmax.com Tue Jul 26 13:54:48 2005 From: George.Flaherty at marketmax.com (George Flaherty) Date: Tue, 26 Jul 2005 13:54:48 -0400 Subject: Emacs skeletons Message-ID: <59CF9F456FAA9045B405C441EC916F3E027A5A58@MERC24.na.sas.com> Michael, Since you are on this topic, do you (or anyone else) have any type of "code-completion" mode for python in emacs? Thanks -george -----Original Message----- From: python-list-bounces+george.flaherty=sas.com at python.org [mailto:python-list-bounces+george.flaherty=sas.com at python.org] On Behalf Of Michael Hoffman Sent: Tuesday, July 26, 2005 1:36 PM To: python-list at python.org Subject: Re: Emacs skeletons skip at pobox.com wrote: > Michael> Does anyone have any Emacs skeletons they find useful for > Michael> Python? > > What's an "Emacs skeleton"? Somewhat of an elaborate mini-language for inserting boilerplate. http://www.emacswiki.org/cgi-bin/emacs-en/SkeletonMode -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 5 23:58:39 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 6 Jul 2005 05:58:39 +0200 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: markturansky at gmail.com enlightened us with: > var m = this["MethodName"]; > m(); //this invokes a method in javascript > > How do I do the same in python? getattr. Read the documentation, it's all in there. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From steve at REMOVETHIScyber.com.au Thu Jul 7 11:45:34 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 08 Jul 2005 01:45:34 +1000 Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: On Thu, 07 Jul 2005 09:36:24 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: >> This is something I've never understood. Why is it bad >> form to assign an "anonymous function" (an object) to a >> name? > > Because it obfuscates your code for no benefit. You should avoid making it > hard for others to read your code (and 'others' includes yourself in the > future). I don't particularly think I'm that much smarter than the average programmer. In fact I *know* that I'm not that much smarter. So why do I see nothing obfuscated or obscure or difficult to understand in func = lambda x: x**3 - 5*x when apparently most of the Python community find it too complicated? Whichever is "more readable" in the absolute sense, the "abused" lambda expression above is within a gnat's whisker of the def equivalent, def func(x): return x**3 - 5*x I honestly don't understand why it is supposed to be so hard to follow. I can think of many function which should not be written with lambda, just as some things shouldn't be written as list comps. But within the limits of how much complexity you can reasonably include in a single expression, I don't see why lambda puts people off. I make it, eight mental tokens (not necessarily the same as Python tokens) for the lambda versus nine for the def. A trivial difference. In my mind, the tokens are: func, =, lambda, x, :, x**3, -, 5*x compared to: def, func, (), x, :, return, x**3, -, 5*x (Your mental parser may differ.) > Also, it obfuscates tracebacks: all lambda expressions will identify in > tracebacks as , but if you define a function you can give it a > meaningful name. Well there is that. If you have lots of lambdas assigned to names, I guess debugging could be more difficult: py> f = lambda x: 1.0/x py> f(0) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in ZeroDivisionError: float division py> def f(x): ... return 1.0/x ... >>> f(0) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f ZeroDivisionError: float division So far so good. But then: py> g = f py> del f py> g(0) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f ZeroDivisionError: float division (but we actually got the error by calling g, not f, and in fact f no longer exists at the point we called g) >> Why is it considered abuse of lambda to assign the >> functions to a name? Is it an abuse of lambda to do this? >> >> D = {"one": lambda noun: noun, >> "two": lambda noun: noun + 's', >> "many": lambda noun: 'lots of ' + noun + 's' } >> >> assert D["two"]("python") == "pythons" >> >> > No, that is approaching a reasonable use of lambda, however I would still > be inclined to write it with functions. e.g. > > def one(noun): > return noun > > def two(noun): > return noun+'s' > > def many(noun): > return 'lots of %ss' % (noun,) > > D = dict(one=one, two=two, many=many) I find your version far more difficult to follow than mine. Psychologically, I find that defs seem to carry significant mental weight in a way that lambdas don't. Even though the lambda forms are equivalent to the def forms, I find that the defs are more heavy-weight in my conceptual map of the program than a lambda would be. Put it this way: whenever I see a two-line def as above, I can't help feeling that it is a waste of a def. ("Somebody went to all the trouble to define a function for *that*?") Yet I would never think the same about a lambda -- lambdas just feel like they should be light-weight. Am I just weird? -- Steven. From red at redplanet.com Thu Jul 21 04:47:11 2005 From: red at redplanet.com (red) Date: Thu, 21 Jul 2005 10:47:11 +0200 Subject: Copying attributes In-Reply-To: References: Message-ID: Terry Hancock wrote: > I'm not sure either, yet, but can you indicate which line in your > listing is 102 in the source file? That might be helpful. 101: ## f1.normal = copy.deepcopy(f.normal) 102: f1.normal = NMesh.Vert(f.normal[0], f.normal[1], f.normal[2]) I've tried with deepcopy, but the result is exactly same. -- _red ____ _ ____ ____ __ _ From cam.ac.uk at mh391.invalid Sun Jul 24 08:58:20 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jul 2005 13:58:20 +0100 Subject: FAQ? In-Reply-To: References: Message-ID: Keith P. Boruff wrote: > Is there an FAQ available specific to this NG as I'm sure some of the > list slicing questions I have have been asked before. Try Google for . I don't know why you would want to look in a FAQ *specific* to a newsgroup to look up slicing questions, since slicing has little to do with the newsgroup. A more general Python FAQ will be more helpful. -- Michael Hoffman From http Sun Jul 31 07:22:12 2005 From: http (Paul Rubin) Date: 31 Jul 2005 04:22:12 -0700 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: <7x3bpvxlsr.fsf@ruckus.brouhaha.com> Paolino writes: > What I'm needing as a global (in globals() or at the module level or > in the module namespace) is 'translate'.The rest of bindings > (all,badcars and table) is something which is 'polluting' the module > namespace. do you want __all__ = ['translate'] ? From rrr at ronadam.com Thu Jul 28 01:46:32 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 28 Jul 2005 05:46:32 GMT Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Peter Hansen wrote: > Ron Adam wrote: > >> Michael Hoffman wrote: >> >>> Ron Adam wrote: >>> >>>> In all current cases, (that I know of), of differing types, '+' >>>> raises an error. >>> >>> >>> Not quite: >>> >>> "hello " + u"world" >>> u'hello world' >>> >>> 4.5 + 5 >>> 9.5 >>> >> In the case of numeric types, it's an addition and not a join. I >> should have specified in 'all cases, (I know of), where '+' is used to >> join objects, but I thought that was clear from the context of the >> discussion. I haven't needed to use unicode yet, so it didn't come to >> mind. > > > I believe Michael intended to show that "4.5 + 5" actually represents > using + with two different types, specifically a float and an int, thus > giving at least two common cases where errors are not raised. Yes, I got that distinction. Yet, concatenation isn't addition. Yes, they have some conceptual similarities, but they are two different operations that happen to use the same symbol for convenience. Three if you count lists and tuples join as being different from string concatinattion. > (While the issue of "addition" vs. "join" is merely a (human) language > issue... one could just as well say that those two numbers are being > "joined" by the "+".) > > -Peter It's also a Python language issue. ;-) Cheers, Ron From cam.ac.uk at mh391.invalid Tue Jul 26 13:36:14 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 26 Jul 2005 18:36:14 +0100 Subject: Emacs skeletons In-Reply-To: References: Message-ID: skip at pobox.com wrote: > Michael> Does anyone have any Emacs skeletons they find useful for > Michael> Python? > > What's an "Emacs skeleton"? Somewhat of an elaborate mini-language for inserting boilerplate. http://www.emacswiki.org/cgi-bin/emacs-en/SkeletonMode -- Michael Hoffman From EP at zomething.com Sat Jul 30 21:16:13 2005 From: EP at zomething.com (EP) Date: Sat, 30 Jul 2005 17:16:13 -0800 Subject: Dabo in 30 seconds? In-Reply-To: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> Message-ID: <20050730171613.1839738924.EP@zomething.com> Ed Leafe wrote in response to the "Python vs. Access VBA" thread: > You might want to look at Dabo, which is a database application > framework for Python. In about 30 seconds you can create an application > that queries a database, displays the results, and allows for > editing/updating/inserting/deleting records. This is a nice pitch. Can you provide simple, example code that does this? As a non-professional programmer (I write to create my own business tools, and for the enjoyment, but no one pays for my code) the ability to generate quick db apps like this would constitute a real win, even if the 30 seconds is a "Guido 30 seconds" and it takes me 5 minutes (which might underestimate Guido by some magnitudes). We're becoming so rich with competing frameworks that, not having the time to evaluate them, I have no single framework in my toolbox I am fluent with. Dabo seems like it might be worth my scarce time to learn; if I can really create a db app in "30 seconds", then I will probably do so, and get deeper into Dabo as I use it. Might become a "Dabo Guy". :-) I suspect there may be others in my shoes, both inside and outside the Python community. If I tell such a person "Oh, you have the choice of many database application frameworks in Python" such a person's eyes would glass open; if I show them "30 seconds" of clean simple code that does as you say, such a framework might not only get more widespread adoption, Python could gain wider adoption as well. Best regards, Eric From hancock at anansispaceworks.com Fri Jul 22 10:36:05 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 22 Jul 2005 09:36:05 -0500 Subject: Help with regexp please In-Reply-To: References: <4z_De.13539$Wt3.3395@bignews3.bellsouth.net> Message-ID: <200507220936.05404.hancock@anansispaceworks.com> On Thursday 21 July 2005 11:39 pm, Felix Collins wrote: > Christopher Subich wrote: > > Scott David Daniels wrote: > Thanks to you both. Wow! what a quick response! > >string.rsplit('.',1)[0] > Clever Python! ;-) > Sorry, I mainly code in C so I'm not very Pythonic in my thinking. > Thanks again... I think this is the "regexes can't count" problem. When the repetition count matters, you usually need something else. Usually some combination of string and list methods will do the trick, as here. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From anton.vredegoor at gmail.com Thu Jul 28 07:44:13 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 28 Jul 2005 04:44:13 -0700 Subject: all possible combinations In-Reply-To: References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> <42d6de96@news.eftel.com> <1122547119.104995.43340@o13g2000cwo.googlegroups.com> Message-ID: <1122551053.544511.83110@g43g2000cwa.googlegroups.com> Steve Holden wrote: > > This makes me wonder why we still don't have something like the unint > > function above in the standard distribution. > > > Because it's not what you'd call (or, at least, it's not what I'd call) > universally required. As you have shown it is relatively easy to hack > something supp when it's needed, so since it isn't something that's > required by the majority it hasn't been added to the library. How about the symmetry argument? One can use int for radix 1 to 32 (I think) but for the reverse problem we only have hex or oct (and cannot choose symbol lists but that's not so very important, if the whole matter has any significance of course :-). Hey, unint might even win the "more general" approval! Anton "or maybe it's just because it's difficult to find a good name for it" From mwh at python.net Sun Jul 31 14:45:40 2005 From: mwh at python.net (Michael Hudson) Date: Sun, 31 Jul 2005 18:45:40 GMT Subject: Changing interpreter's deafult output/error streams References: Message-ID: "Ira" writes: > Using an embedded interpreter, how do I change it's default output > streams (specifically the one used by PyErr_Print() which I'm > guessing is the default error stream)? It looks as though it writes to stderr unconditionally. But most of the reasons for ended up in PyErr_Print can be intercepted at a higher level (I think -- I mean sys.excepthook & co here). Cheers, mwh -- ARTHUR: Yes. It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard". -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From daniel.dittmar at sap.corp Fri Jul 1 10:10:56 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 01 Jul 2005 16:10:56 +0200 Subject: Question about Python In-Reply-To: <42c54149$1@griseus.its.uu.se> References: <42c54149$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > But then it occured to me.. I started writing my program in Java > pre-1.5. Then came 1.5, I upgraded, and my program would still compile > and run, though I did get three warnings. The language had changed a > little bit; I had to assign a type to three arrays. That wasn't so bad. > > However, when I look at the various Python modules/libraries, I see > that there are several versions of them, for different versions of > python. I've seen everything from "for python 1.5" up to "for python > 2.4" with all versions in between. This scares me a little bit. I assume > that the reason for the different versions is because of new language > features? Python is generally backwards compatible * pure Python modules will work unchanged when used with a newer version of Python (so it's almost always: for Python 1.5 and later). You might get some deprecation warnings and these appear one every run (compared to Java, where they appear only when compiling). But they can be disabled. * Python extension modules written in C can mostly be recompiled from source with the new headers and will work as well * binary extensions generally won't work with newer Python, that's why you often see several downloads for a specific module. On Unix, binary compatibility worked pretty well up to 2.2 (Meaning I could use modules compiled for 1.5 with Python 2.2), but that was just a coincidence and I wouldn't rely on it for future versions. Summary: If you are able to compile all your needed extensions yourself, then new Python versions aren't really a problem. Daniel From mwm at mired.org Mon Jul 18 19:56:24 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 18 Jul 2005 19:56:24 -0400 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: <863bqbu0rb.fsf@bhuda.mired.org> "Thomas Bartkus" writes: >> > Re-train on a new platform, >> > and re-write from scratch? > > What do you do when an open source project you were using gets abandoned? cvs import -m "sources for orphaned project" > Hard to see much difference here. Doing support for object-only distributions is *much* harder than doing it for source distributions. I have a habit of picking products based on technical superiority, not popularity. As a result, I have a nice collection of orphans. That's because technical quality has little or nothing to do with profitability. On the other hand, since starting to use open source projects, I've never had one I depend on fail. I've had some I contributed to fail, but that's a different thing. I suspect that technical quality in open source projects contributes to their attracting people to support them. This makes them ever so much more attractive than proprietary solutions, where technical quality seems to be irrelevant to longevity. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From andreas at kostyrka.org Wed Jul 20 10:59:04 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 20 Jul 2005 16:59:04 +0200 Subject: python certification In-Reply-To: <20050720142210.56E6D7EC2B@postix.sdv.fr> References: <20050720142210.56E6D7EC2B@postix.sdv.fr> Message-ID: <20050720145904.GA21538@heaven.kostyrka.org> On Wed, Jul 20, 2005 at 04:22:10PM +0200, Fabien wrote: > > Python is not about certificates or diplomas, so do not spend any > > money on it (the other guy was only joking). > > Even if Python is not about certificates, I think it's not the case for > some company. And when you say to a company that you know how to dev. in > Python, they don't know anything about your level. Well, that's what CVs, project histories and interviews are about. Asking for certification in Python (and propably for any other programming language) usually only shows that the person who asks doesn't have a clue what they are asking about ;) (These are the people look for Pearl and Pyhton programmers ;) ) Andreas > > -- > http://mail.python.org/mailman/listinfo/python-list From cyril.bazin at gmail.com Mon Jul 11 14:18:55 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Mon, 11 Jul 2005 20:18:55 +0200 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: Message-ID: Hello, Try that, it may not be the better solution, but it seems to work: #def invertDict(d): # d2 = {} # for k, v in d.iteritems(): # d2.setdefault(v, []).append(k) # return d2 Cyril On 7/11/05, Ric Da Force wrote: > > Hi all, > > I have a dictionary containing about 300 items, some of the values being > repeated. Both keys and values are strings. How can I turn this thing on > its head so that we create a key based on each unique value and build the > values based on the keys corresponding to the repeated values? > > It is hard to explain but this is what I mean: > > Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is > not'} > > I want this to return a new dict with string keys and lists containing the > previous keys for repeated values. > > NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} > > I am still learning Python and have struggled with this for hours before > deciding to go for help. Unfortunately, I didn't really know how to search > for this in google and decided to post it here. I apologise if this is too > basic for this newsgroup... > > Ric > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Fri Jul 29 16:23:02 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 29 Jul 2005 14:23:02 -0600 Subject: Filtering out non-readable characters In-Reply-To: References: Message-ID: Steve Holden wrote: > >>> tt = "".join([chr(i) for i in range(256)]) Or: tt = string.maketrans('', '') STeVe From exarkun at divmod.com Sat Jul 16 19:07:26 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 16 Jul 2005 19:07:26 -0400 Subject: Filtering out non-readable characters In-Reply-To: Message-ID: <20050716230726.26278.1501115621.divmod.quotient.13217@ohm> On Sat, 16 Jul 2005 19:01:50 -0400, Peter Hansen wrote: >George Sakkis wrote: >> "Bengt Richter" wrote: >>> >>> identity = ''.join([chr(i) for i in xrange(256)]) >> >> Or equivalently: >>>>>identity = string.maketrans('','') > >Wow! That's handy, not to mention undocumented. (At least in the >string module docs.) Where did you learn that, George? > http://python.org/doc/lib/node109.html >-Peter >-- >http://mail.python.org/mailman/listinfo/python-list > From avishorp at yahoo.com Thu Jul 21 02:53:01 2005 From: avishorp at yahoo.com (avishay) Date: 20 Jul 2005 23:53:01 -0700 Subject: Using SHFileOperation In-Reply-To: <42de8fe8$1_1@spool9-west.superfeed.net> References: <1121843013.558480.43380@g43g2000cwa.googlegroups.com> <42de8fe8$1_1@spool9-west.superfeed.net> Message-ID: <1121928781.535331.37050@g47g2000cwa.googlegroups.com> Thanks. From davecook at nowhere.net Tue Jul 19 01:41:24 2005 From: davecook at nowhere.net (Dave Cook) Date: Tue, 19 Jul 2005 05:41:24 GMT Subject: What is your favorite Python web framework? References: Message-ID: On 2005-07-17, Admin wrote: > I favor speed of development, intensive OO development, performance under > heavy load, short learning curve, good documentation and community. I like the design of nevow (nevow.com), but I don't have any practical experiences with other frameworks. The documentation is not very good, but folks on IRC have been helpful. Dave Cook From rrr at ronadam.com Mon Jul 4 01:41:45 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 04 Jul 2005 05:41:45 GMT Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > On Saturday 02 July 2005 10:35 pm, Terry Hancock wrote: > >>I tried to load a couple of different scripts to >>automatically fold Python code in vim, but none of them >>seems to do a good job. >> >>I've tried: >>python_fold.vim by Jorrit Wiersma >> http://www.vim.org/scripts/script.php?script_id=515 > > > Actually, I think this one is doing what I want now. It seems > to be that it isn't robust against files with lots of mixed tabs > and spaces. I also got "space_hi.vim" which highlights tabs > and trailing spaces, which made it a lot easier to fix the > problem. I edited my syntax coloring file to do the same thing. Not to mention adding a few key words that were missing. :-) > After fixing my source files, python_fold seems to be able > to handle them just fine. > > I must also recommend C. Herzog's python_box.vim > which is fantastic -- especially the automatic Table of > Contents generation for Python source, and pydoc.vim > which puts access to pydoc into the editor. Sounds good. I'll give it a try! :-) > Nice. Now that I have a "very sharp saw", I'm going to > have to go cut some stuff for a bit. ;-) > > -- > Terry Hancock ( hancock at anansispaceworks.com ) > Anansi Spaceworks http://www.anansispaceworks.com > From 00515879256 at fastwebnet.it Tue Jul 19 04:20:04 2005 From: 00515879256 at fastwebnet.it (Glauco) Date: Tue, 19 Jul 2005 10:20:04 +0200 Subject: Dictionary, keys and alias In-Reply-To: References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> <5mLCe.24301$b93.15018@tornado.fastwebnet.it> Message-ID: Steven D'Aprano wrote: > On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote: > > >>I want to insert a concept of alias in a dict_based class. >> >>The idea is to have a facoltative name in the same dict that correspond >>at the same value. With this alias i can change original value. >> >>example: >> >>mydict['a'] = 1 >>I must define an alias example: myFunctAlias( mydict, 'a', 'b') >>print mydict >>{'a':1, 'b':1} >>mydict['b'] = 2 >>print mydict >>{'a':2, 'b':2} >> >> >>The only idea i have is to implement two dictionary one for convert >>name, alias in two keys with the same value (eg.numeric) in the first >>dict. The second for store only one time the k, v . > > > You need some sort of redirection, something like this (untested): > > class Doubledict: > def __init__(self, **kargs): > self.data = {} > self.aliases = {} > for key in kargs: > # Point the key to a hash. > self.aliases[key] = hash(key) > # And point the hash at the value. > self.data[hash(key)] = kargs[key] > > def setalias(self, key, alias): > # Point the alias to the same hash as the real key. > self.aliases[alias] = hash(key) > > def __getitem__(self, key): > return self.data[self.aliases[key]] > > def __setitem__(self, key, value): > self.data[self.aliases[key]] = value > > > The only niggly worry I have is I'm not sure when hash can be used, when > it is unique, or even if is it guaranteed to be unique. > Thank Steve, the idea was the same... but yours using hash is much elegant. Thank you Glauco -- \\\|/// \\ - - // ( @ @ ) +---------------------oOOo-( )-oOOo--------------------------+ | | | I have a dream that one day this nation will rise up and | | live out the true meaning of its creed: "We hold these | | truths to be self-evident:that all men are created equal.| | I have a dream that one day on the red hills of Georgia | | the sons of former slaves and the sons of former | | slaveowners will be able to sit down together at a table | | of brotherhood. | | I have a dream that one day even the state of Mississippi, | | a desert state, sweltering with the heat of injustice | | and oppression, will be transformed into an oasis of | | freedom and justice. | | I have a dream that my four children will one day live in | | a nation where they will not be judged by the color of | | their skin but by the content of their character. | | I have a dream today. | | | | Martin Luther King, Jr 28 Ago 1963 | +------------------------------------------------------------+ | glauco(at)uriland.it | | www.uriland.it .oooO ICQ: 115323690 | +--------------------- ( )------ Oooo.---------------------+ \ ( ( ) \_) ) / (_/ From nephish at xit.net Mon Jul 25 15:12:56 2005 From: nephish at xit.net (nephish at xit.net) Date: 25 Jul 2005 12:12:56 -0700 Subject: how to write a line in a text file Message-ID: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> Hey there, kinda newbie question here. i know how to read the lines of a txt file. i know how to write a txt file. but how do i overwrite a line value with another value ? i mean, how do go to, say, line 3 of a text file and replace what is written on line 3 with something else? thanks <>< From peter at engcorp.com Wed Jul 20 08:30:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Jul 2005 08:30:04 -0400 Subject: goto In-Reply-To: References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <86psterxi3.fsf@bhuda.mired.org> Message-ID: Sybren Stuvel wrote: > Mike Meyer enlightened us with: > >>>I dislike gotos because it is too easy to inadvertently create >>>infinite loops. <10 WINK; 20 GOTO 10> >> >>And it's impossible without them? > > > I thought the same thing, but then I read it again and thought about > the "inadvertently". As soon as you see a "while True", you _know_ > it's going to loop forever. Unless it doesn't, of course: while True: break From sjmachin at lexicon.net Tue Jul 12 19:18:57 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 13 Jul 2005 09:18:57 +1000 Subject: Slicing every element of a list In-Reply-To: References: Message-ID: <42d44fe2@news.eftel.com> Alex Dempsey wrote: > Recently I tried to slice every element of a list of strings. First I tried: "slice"? Interesting terminology. Next problem you have, try posting an example of your input, and your expected output. E.g. repr(input_string): '"foo"\t"barre"\t"zot"\t"X"\n' repr(output_list): ['foo', 'barre', 'zot'] Then folk would be able to point out that the csv module might be a tad more appropriate -- it gives you a general solution. I'm presuming that the hard-coded number "5" means that you have a single-character field at the end that you want to ignore. Your code would be more robust in the face of change were you to ignore the last field after splitting instead of the last 5 chars before splitting. > > f = open("export.xls", "r") Aarrgghh!! a file with a ".xls" extension that you can read as a text file?? > lines = f.readlines() > > for line in lines: > line = line[1:-5] > line = line.split('\"\t\"') > > This went without returning any errors, but nothing was sliced or > split. Next I tried: > > for i in range(len(lines)): > lines[i] = lines[i][1:-5] > lines[i] = lines[i].split('\"\t\"') > > This of course worked, but why didn't the first one work. Further why > didn't the first one return an error? From martin at v.loewis.de Thu Jul 28 16:15:58 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 28 Jul 2005 22:15:58 +0200 Subject: codecs.getencoder encodes entire string ? In-Reply-To: <1122565377.433764.274280@f14g2000cwb.googlegroups.com> References: <1122565377.433764.274280@f14g2000cwb.googlegroups.com> Message-ID: <42E93CFE.3090903@v.loewis.de> nicolas_riesch wrote: > I just don't understand why it returns the "length consumed". > > Does it means that in some case, the input string can be only partially > converted ? For an encoder, I believe the answer is "no". For a decoder, it is a definite yes: if the input does not end with a complete character, you may have bytes left at the end which did not get decoded. For an encoder, the same *might* happen if you want to encode half-surrogates into, say, UTF-8; the encoder might refuse to encode the half-surrogate, and wait for the other half. Of course, the current UTF-8 encoder will then just encode the surrogate codepoint as if it was a proper character. If you extend the notion of "encoding", similar things may happen all the time. E.g. a DES encoder may only support multiples of the block size, and leave bytes at the end. > What can be the use of the "length consumed" value ? It's primarily intended for stream writers, which may need to buffer extra characters at the end that did not get encoded, and wait until more input is provided. For all practical purposes, you can ignore the length on encoding. If you are paranoid, assert that it equals the length of the input. Regards, Martin From bill.mill at gmail.com Thu Jul 21 11:12:24 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu, 21 Jul 2005 11:12:24 -0400 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <42dfb111@griseus.its.uu.se> References: <42dfb111@griseus.its.uu.se> Message-ID: <797fe3d405072108123df80a85@mail.gmail.com> On 7/21/05, Jan Danielsson wrote: > Hello all, > > How do I make a python script actually a _python_ in unix:ish > environments? > > I know about adding: > #!/bin/sh > > ..as the first row in a shell script, but when I installed python on > a NetBSD system, I didn't get a "python" executable; only a "python2.4" > executable. > > Adding "#!/usr/pkg/bin/python2.4" as the first row in the script > would probably work, but that would be too specific for the system I'm > using, imho. > > I saw someone using "#!/usr/bin/env python", but that failed on the > system I'm using, so I assume that's something specific too (or is the > installation broken?). The env program [1], which usually exists at least on a linux system, executes the program given as its argument. Thus, "/usr/bin/env python" tries to executes python, which bash will then use to run the python script. As long as env exists, and python is somewhere in the PATH, this is a fairly portable way to run python scripts. Does BSD really not come with the env program? I bet there's an equivalent you could symlink to it. Unfortunately, I've never BSDed, so I can't help you find it. To get a workable subset of the normal env functionality, you could try (assuming you use bash): /home/llimllib $ echo "$@" > /usr/bin/env /home/llimllib $ chmod a+x /usr/bin/env Peace Bill Mill bill.mill at gmail.com [1]: http://rootr.net/man/man/env/1 From clamhan at hotmail.com Wed Jul 13 17:39:32 2005 From: clamhan at hotmail.com (Martin) Date: Wed, 13 Jul 2005 22:39:32 +0100 Subject: Odd behaviour of regexp module References: <1121288737.882813.244540@f14g2000cwb.googlegroups.com> Message-ID: <282bd1l7ukjiibr7lv7rdkhls9dter85bj@4ax.com> Hi David, b.group() is equivalent to b.group(0), the entire RE match. (^(.*?)\.) will give you 'dfsf.' for that input string. What you want is b.group(1), the subgroup you're looking for inside the main RE. (.*?) which gives you 'dfsf', which is what you're looking for. Cheers, Martin On 13 Jul 2005 14:05:37 -0700, "David Veerasingam" wrote: >Hello > >It seems the grouping feature isn't behaving correctly. > >In [1]: a = 'dfsf.oct.ocfe' > >In [2]: b = re.match(r'^(.*?)\.', a); b.group() >'dfsf.' > >The expected result is 'dfsf'. Why did the regexp grab that period at >the end? > >David From gene.tani at gmail.com Tue Jul 26 12:58:19 2005 From: gene.tani at gmail.com (gene tani) Date: 26 Jul 2005 09:58:19 -0700 Subject: Knowing when a file completes. In-Reply-To: References: Message-ID: <1122397099.490235.97400@f14g2000cwb.googlegroups.com> http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html From tjreedy at udel.edu Sun Jul 31 22:02:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 31 Jul 2005 22:02:10 -0400 Subject: Determining method type given its string name presentation and itscorresponding object reference. References: <1122853524.374812.326580@g14g2000cwa.googlegroups.com> Message-ID: "Apple" wrote in message news:1122853524.374812.326580 at g14g2000cwa.googlegroups.com... > Hi I am a bit new to python. I was wondering if there is a way to > determine whether or not a given string is a member method of a given > object: Does callable(cls.attr) fit your needs? Terry J. Reedy From mage at mage.hu Tue Jul 19 07:26:38 2005 From: mage at mage.hu (Mage) Date: Tue, 19 Jul 2005 13:26:38 +0200 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <42DCE36E.8090309@mage.hu> linuxfreak wrote: >Hi guys, > Got going with python...and i must say its a pretty cool language. >Been using Xemacs to write me programs. But I want an IDE that would >give me auto-completion, online help and the like... Tried SPE and >Dr.Pyhton but the former crashes regulary and the latter is quite >unweildy and does not have a great many features. I quite like the UML >feature found in SPE but the damn thing crashes way too often. What are >you guys using and what do you think is the best IDE...or should i >stick with Xemacs/emacs??? > > > I use Eclipse with the python plugin. It never crashed. I set it to display tabs as two spaces and Eclipse tells if I type spaces instead of tabs by accident. I like it. I had no luck with the code completion, but do you really need that for writing python programs? Mage From rrr at ronadam.com Tue Jul 5 18:50:30 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 05 Jul 2005 22:50:30 GMT Subject: flatten(), [was Re: map/filter/reduce/lambda opinions ...] In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: > Ok... How about a non-recursive flatten in place? ;-) > > def flatten(seq): > i = 0 > while i!=len(seq): > while isinstance(seq[i],list): > seq.__setslice__(i,i+1,seq[i]) > i+=1 > return seq > > seq = [[1,2],[3],[],[4,[5,6]]] > print flatten(seq) > > I think I'll be using the __setslice__ method more often. This is probably the more correct way to do it. :-) def flatten(seq): i = 0 while i!=len(seq): while isinstance(seq[i],list): seq[i:i+1]=seq[i] i+=1 return seq From martin.witte at gmail.com Mon Jul 25 15:50:03 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 25 Jul 2005 12:50:03 -0700 Subject: how to imput usernames and passwords?? In-Reply-To: References: <000201c5913d$47909f20$8235a8c0@co.montezuma.co.us> Message-ID: <1122321003.923613.256970@f14g2000cwb.googlegroups.com> Try cx_Oracle http://www.computronix.com/utilities.shtml#Oracle, it is an excellent library based on the DB API of Python From wojciech_mula at poczta.null.onet.pl.invalid Wed Jul 20 16:48:21 2005 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech Mula) Date: Wed, 20 Jul 2005 20:48:21 +0000 (UTC) Subject: Lots of pdf files References: Message-ID: Greg Lindstrom wrote: > There does not appear to be a simple way to merge many pdf's into one. Program pdftk can merge pdf's, but I have never tried it. You may also use pdflatex --- there is a package called pdfpages provides powerful command \includepdf. w. From buzzard at urubu.freeserve.co.uk Wed Jul 13 12:54:18 2005 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 13 Jul 2005 17:54:18 +0100 Subject: all possible combinations In-Reply-To: References: <1121267364.28617.4.camel@athop1.ath.vt.edu> <1121269202.29571.1.camel@athop1.ath.vt.edu> Message-ID: Jack Diederich wrote: > On Wed, Jul 13, 2005 at 05:07:33PM +0100, Duncan Smith wrote: > >>rbt wrote: >> >>>On Wed, 2005-07-13 at 11:09 -0400, rbt wrote: >>> >>> >>>>On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: >>>> >>>> >>>>>Say I have a list that has 3 letters in it: >>>>> >>>>>['a', 'b', 'c'] >>>>> >>>>>I want to print all the possible 4 digit combinations of those 3 >>>>>letters: >>>>> >>>>>4^3 = 64 >>>>> >>>>>aaaa >>>>>abaa >>>>>aaba >>>>>aaab >>>>>acaa >>>>>aaca >>>>>aaac >>>>>... >>>>> >>>>>What is the most efficient way to do this? >>>> >>>>Expanding this to 4^4 (256) to test the random.sample function produces >>>>interesting results. It never finds more than 24 combinations out of the >>>>possible 256. This leads to the question... how 'random' is sample ;) >>>> >>>>Try it for yourselves: >>>> >>>>test = list('1234') >>>> >>>>combinations = [] >>>>while 1: >>>> combo = random.sample(test, 4) >>>> possibility = ''.join(combo) >>>> if possibility not in combinations: >>>> print possibility >>>> combinations.append(possibility) >>>> continue >>>> else: >>>> continue >>>> >>> >>> >>>Someone pointed out off-list that this is doing permutation, not >>>combination. Is there a way to make random.sample to do combinations? >>> >> >>Probably not in any sensible way. But what you list in your original >>post are not distinct combinations. e.g. abaa and aaba are both 3 a's >>and 1 b. Maybe you mean that order does matter (and you're actually >>looking for all distinct permutations of all combinations)? >> > > This is called a cartesian product, and the easiest way is to do > > import probstat # probstat.sourceforge.net > letters = list('abcd') > for (guys) in probstat.Cartesian([letters] * 4): > print ''.join(guys) > > It's a C module I wrote to do this stuff a few years ago, still compiles > and runs just fine (at least on linux). > > -jackdied Yep. probstat also ran on Windows the last time I used it :-). Duncan From guettli at thomas-guettler.de Tue Jul 5 10:23:00 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 05 Jul 2005 16:23:00 +0200 Subject: Python exception hook simple example needed References: Message-ID: Am Tue, 05 Jul 2005 16:07:44 +0200 schrieb fowlertrainer at anonym.hu: > Hi ! > > I wrote some mails to wxPy, and this list about "wxPython and global > exception handling" theme. > I need to port my Delphi apps to wxPy, and I want to use same exception > mechanism like Delphi use. > > When any exception get unhandled, the app's main cycle get it, and show > in a dialog (and I can catch it, and I can write it to a log file with > many developer information). Hi, maybe a look at the "cgitb" module helps you. It uses an exception handler to create a HTML page if an uncaught exception is raised. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From bokr at oz.net Sun Jul 31 15:37:29 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 31 Jul 2005 19:37:29 GMT Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42ebe919.164695739@news.oz.net> <861x5fiolv.fsf@bhuda.mired.org> Message-ID: <42ed27d4.246290497@news.oz.net> On Sun, 31 Jul 2005 00:30:36 -0400, Mike Meyer wrote: >bokr at oz.net (Bengt Richter) writes: > >> On Fri, 29 Jul 2005 18:07:31 -0400, Mike Meyer wrote: >>>I know, lambda bashing (and defending) in the group is one of the most >>>popular ways to avoid writing code. However, while staring at some Oz >>>code, I noticed a feature that would seem to make both groups happy - >>>if we can figure out how to avoid the ugly syntax. >> try >> >> http://groups-beta.google.com/groups?as_q=anonymous+def&as_ugroup=comp.lang.python >> >> for much discussion of this ;-) > >Well, that pretty much kills that. I knew there had been a lot of Well, why consider it killed? Maybe your weight could tilt the balance ;-) I still like the anonymous def. >discussion about anonymous functions, anonymous blocks, and of course >various lambda replacements. But I didn't realize almost exactly this >proposal had been discussed before. Shouldn't surprise me, though. > >Thanks to everyone who took the time to read and respond. > Sometimes ideas have to sit in the mulch for a while before it's their season to bloom ;-) Regards, Bengt Richter From ddurkee at gmail.com Thu Jul 21 22:39:01 2005 From: ddurkee at gmail.com (David Durkee) Date: Thu, 21 Jul 2005 21:39:01 -0500 Subject: Setting environment variables for tcsh session Message-ID: <76abe67f05072119396ebf0495@mail.gmail.com> Hi, I'm trying to write a script I can run from tcsh in Terminal (on Mac OS X) that will set environment variables that can be accessed by subsequent commands I execute in that session. Not having any luck so far. Here's what I've tried: ------------ #!/usr/bin/python import sys import commands import os inputs = sys.argv[1:] if len(inputs) == 2: key = inputs[0] val = inputs[1] cmd = 'setenv %s "%s"' % (key, val) print cmd print commands.getstatusoutput(cmd) print commands.getoutput('echo $' + key) ------------- I named the script pysetenv and executed it with the command: pysetenv TEST "This is a test" This prints the command in the form I intended, the tcsh setenv command. When it executes the command, however, it gets an error that makes it apparent that it is running the command in the sh shell instead of the tcsh shell I ran it from. So I changed the format of the command to that used by sh, making the last four lines of my script: cmd = "%s='%s'; export %s" % (key, val, key) print cmd print commands.getstatusoutput(cmd) print commands.getoutput('echo $' + key) For this one it was apparent that the command did not get an error, but the echo was still echoing an old value of the variable. So I replaced the last four lines with this: os.environ[key] = val print commands.getoutput('echo $' + key) In this case, the echo command printed the value of the variable I had just set! Success, or so I thought. However, a subsequent echo command from the command prompt still returned the old value of the variable. I think running the script must start a new session and that variables set in that session are only current as long as the script is running. Any ideas? David From mailman at hanez.org Sat Jul 16 18:42:21 2005 From: mailman at hanez.org (Johannes Findeisen) Date: Sun, 17 Jul 2005 00:42:21 +0200 Subject: Django - Rails killer comes... In-Reply-To: <15cuhhg8i6mrg$.ekh1brvux44n$.dlg@40tude.net> References: <15cuhhg8i6mrg$.ekh1brvux44n$.dlg@40tude.net> Message-ID: <1121553741.5653.11.camel@phantom.wg.xw3.org> On Sat, 2005-07-16 at 03:26 +0200, JZ wrote: > http://www.djangoproject.com/ Hey, that is crazy shit! I really like the concept and will give it a try ASAP! I have searched for something like this some month ago but ended my search at ROR. I am not a python hacker but i know how to use it and i hope i will become better when trying this software. Thanks for your _open_ release! I love it! Regards, -- Johannes Findeisen http://hanez.org/ From twic at urchin.earth.li Sat Jul 2 10:12:50 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 2 Jul 2005 15:12:50 +0100 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: Message-ID: On Fri, 1 Jul 2005, Ivan Van Laningham wrote: > Personally, I find that Lisp & its derivatives put your head in a very > weird place. Even weirder than PostScript/Forth/RPN, when you come > right down to it. +1 QOTW! tom -- REMOVE AND DESTROY From steve at REMOVEMEcyber.com.au Mon Jul 4 00:04:16 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 14:04:16 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <86acl31ldw.fsf@bhuda.mired.org> Message-ID: <42C8B540.4070702@REMOVEMEcyber.com.au> Mike Meyer wrote: > Steven D'Aprano writes: > >>I don't object to adding sum and product to the language. I don't object >>to adding zip. I don't object to list comps. Functional, er, functions >>are a good thing. We should have more of them, not less. > > > Yes, but where should they go? Adding functions in the standard > library is one thing. Adding builtins is another. Builtins make every > python process heavier. This may not matter on your desktop, but > Python gets used in embedded applications as well, and it does > there. Builtins also clutter the namespace. Nothing really wrong with > that, but it's unappealing. > > I'd say that removing functions is a bad thing. On the other hand, I'd > say moving them from builtins to the standard library when Python has > functionality that covers most of the use cases for them is a good > thing. > > The latter has occured for map, filter, and reduce. Lambda I'm not so > sure of, but it gets swept up with the same broom. Moving the first > three into a library module seems like a good idea. I'm not sure about > removing lambda. Removing map, filter and reduce remove most of my > use cases for it. But not all of them. Metoobe!!! Practicality beats purity: I am perfectly happy to have list comps in the language and fast, efficient functional programming tools in a module. I'm even happy to see sum and product and zip as builtins, even though logically they belong with map and reduce in the (hypothetical) functional module. I know Python isn't, and never will be, a purely functional language. But being able to use some functional techniques is good, and shouldn't be lost. -- Steven. From steve at REMOVETHIScyber.com.au Sun Jul 10 10:54:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 11 Jul 2005 00:54:59 +1000 Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <1121005233.992711.141640@z14g2000cwz.googlegroups.com> Message-ID: On Sun, 10 Jul 2005 07:20:34 -0700, raptor wrote: > I think u are wrong.. I think perl is much more exrpressive in > semantics than Python.. Well, with such great command of natural language as you are displaying, how could anyone argue with your conclusion? -- Steven. From me at privacy.net Fri Jul 29 13:24:09 2005 From: me at privacy.net (Dan Sommers) Date: Fri, 29 Jul 2005 13:24:09 -0400 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: On 29 Jul 2005 07:45:33 -0700, aahz at pythoncraft.com (Aahz) wrote: > In article , > Dan Sommers wrote: >> >> Was Tim writing about developing Python itself, or about developing >> other programs with Python? > Yes. > (C'mon, didja really expect any other answer?) It was a rhetorical question. :-) Regards, Dan -- Dan Sommers From rbt at athop1.ath.vt.edu Fri Jul 15 10:00:21 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 15 Jul 2005 10:00:21 -0400 Subject: all possible combinations In-Reply-To: References: <42d6ed37.197174802@news.oz.net> Message-ID: <1121436020.13284.1.camel@athop1.ath.vt.edu> Wow. That's neat. I'm going to use it. Thanks! On Thu, 2005-07-14 at 19:52 -0400, Peter Hansen wrote: > Bengt Richter wrote: > > On Thu, 14 Jul 2005 17:10:37 -0400, William Park wrote: > > It's a one liner in Python too ;-) > > > > >>> print ' '.join([x+y+z+q for s in ['abc'] for x in s for y in s for z in s for q in s]) > > Or for the cost of an import and a lambda, you can keep it looking real > obscure and generalize it to any size of sequence ('abcdef' or whatever) > and a result length of up to 52 elements: > > >>> from string import letters as L > >>> cartesian = lambda seq, num: eval("list(%s for __ in [seq] > %s)" % ('+'.join(L[:num]), 'for %s in __ ' * num % tuple(L[:num]))) > # (there are spaces at any line breaks above) > > >>> cartesian('abcde', 6) > ['aaaaaa', 'aaaaab', 'aaaaac', 'aaaaad', 'aaaaae', 'aaaaba', > ... > 'eeeeec', 'eeeeed', 'eeeeee'] > >>> len(_) > 15625 > > > > -Peter From alexander.chadwick at gmail.com Mon Jul 25 04:28:40 2005 From: alexander.chadwick at gmail.com (ch424) Date: 25 Jul 2005 01:28:40 -0700 Subject: Extending python - undefined symbol error on import References: <1122047378.752186.6840@z14g2000cwz.googlegroups.com> <42e16fd9$1@news.eftel.com> Message-ID: <1122280120.826850.141990@g44g2000cwa.googlegroups.com> Sweet! It works! *dances* Thank you so much -- and for the explanation! For anyone searching for this, I had to change the respective lines to: module1 = Extension('gpibmodule', libraries = ['gpibapi'], sources = ['gpibmodule.c']) just as Daniel said. Thanks again, Alex From digitalsubjunctive at gmail.com Thu Jul 21 19:15:43 2005 From: digitalsubjunctive at gmail.com (digitalsubjunctive at gmail.com) Date: 21 Jul 2005 16:15:43 -0700 Subject: Couple quick questions from a Python Noob In-Reply-To: <1121941136.679360.91490@g14g2000cwa.googlegroups.com> References: <1121934168.143332.111100@f14g2000cwb.googlegroups.com> <1121941136.679360.91490@g14g2000cwa.googlegroups.com> Message-ID: <1121987743.313957.325840@f14g2000cwb.googlegroups.com> Thanks you to. Oh, and it is .pyw, you're right. From peter at engcorp.com Fri Jul 8 22:29:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 08 Jul 2005 22:29:28 -0400 Subject: why UnboundLocalError? In-Reply-To: References: Message-ID: Alex Gittens wrote: > I'm trying to define a function that prints fields of given widths > with specified alignments; to do so, I wrote some helper functions > nested inside of the print function itself. I'm getting an > UnboundLocalError, and after reading the Naming and binding section in > the Python docs, I don't see why. > > Here's the error: > >>>>fieldprint([5, 4], 'rl', ['Ae', 'Lau']) > > Traceback (most recent call last): > File "", line 1, in ? > File "fieldprint.py", line 35, in fieldprint > str += cutbits() > File "fieldprint.py", line 11, in cutbits > for i in range(0, len(fields)): > UnboundLocalError: local variable 'fields' referenced before assignment > > This is the code: > def fieldprint(widths,align,fields): > [snip] > def cutbits(): > cutbit = [] > for i in range(0, len(fields)): > if len(fields[i]) >= widths[i]: > cutbit.append(fields[i][:widths[i]]) > fields = fields[widths[i]:] > > What's causing the error? While I don't know the "correct" fix, the immediate cause is that you are assigning to "fields" in the final line above, and there is no "global fields" statement, so the compiler thinks it must be a local, but you access it (as the error says) before it is assigned-to locally. "A" fix would be to use a different name locally, and if you really want it to reference the externally defined "fields", just do something like "lfields = fields" at the top of cutbits() (where "lfields" means "local fields", though you can pick any name you like). -Peter From tbr at nospam.nos Mon Jul 4 07:25:02 2005 From: tbr at nospam.nos (TechBookReport) Date: Mon, 04 Jul 2005 12:25:02 +0100 Subject: Review of 'data crunching' Message-ID: <8Y2dnULlibISgVTfRVnysQ@pipex.net> There's a review of 'Data Crunching' by Greg Wilson over at TechBookReport. This is not a teach-yourself Python book but one that uses Python to solve various common data-related tasks with regular expressions, XML, SQL and so on. The review is here: http://www.techbookreport.com/tbr0172.html -- TechBookReport - Programming http://www.techbookreport.com/ProgIndex.html From km at mrna.tn.nic.in Wed Jul 27 03:14:12 2005 From: km at mrna.tn.nic.in (km) Date: Wed, 27 Jul 2005 12:44:12 +0530 Subject: multiple inheritance super() Message-ID: <20050727071412.GA13681@mrna.tn.nic.in> Hi all, In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? thanks in advance for enlightment ... here's the snippet #!/usr/bin/python class A(object): def __init__(self): self.a = 1 class B(object): def __init__(self): self.b = 2 class C(object): def __init__(self): self.c = 3 class D(B, A, C): def __init__(self): self.d = 4 super(D, self).__init__() if __name__ == '__main__': x = D() print x.a # errs with - AttributeError From cantabile.03 at wanadoo.fr Thu Jul 7 12:13:08 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Thu, 07 Jul 2005 18:13:08 +0200 Subject: Pattern question Message-ID: <42cd5493$0$900$8fcfb975@news.wanadoo.fr> Hi, I'm trying to write a small installer for a server. But this program should be able to run in the future under heterogenous environments and os (at least linux/windows). I mean, the install will be done either in text mode or curses or gtk or tk, either in debian or windows 2000 and so on... The idea, at the moment, is as follows : class Server: def __init__(self, params = None): self.params = params def __getattr__(self, attr): return self.params.get(attr, None) class Installer: def __init__(self, gui = None): self.gui = gui self.srv = None def update(self, dict): self.srv = Server(dict) class Gui: def __init__(self, installer = None): self.installer = installer def main(): ## Some stuff here calling doIt() when the ## user is done with filling various fields def doIt(self): dict = {"param1":"qwerty", "param2":"uiop"} self.installer.update(dict) def main(): inst = Installer() gui = Gui(inst) inst.gui = gui inst.gui.main() ## Here will be the actual install method ## ... ## An example of accessing srv values: print inst.srv.param1, inst.srv.param2 But, considering this code, I find the 3 first lines of my main() a bit heavy. I have to inform inst that it has a 'gui', and Gui that it has an 'installer'. I was trying to implement something looking like (very roughly) to the Observer pattern (so that the Gui would be totally independant from the actual install process). I guess there is something wrong in my approach. Is there a better pattern than this one for that kind of stuff ? Tanks for your help. From enleverlesO.OmcO at OmclaveauO.com Fri Jul 1 16:56:23 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 1 Jul 2005 22:56:23 +0200 Subject: calldll compiled for Python 2.4 for Windows References: Message-ID: <42c5ae1e$0$22318$8fcfb975@news.wanadoo.fr> Hi ! Use Ctypes Michel Claveau From daniel.dittmar at sap.corp Fri Jul 29 11:45:05 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 29 Jul 2005 17:45:05 +0200 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> Message-ID: Dark Cowherd wrote: > There should be one-- and preferably only one --obvious way to do it. > > But this not true of Python. > GUI, Web development, Application Framework - it is shambles. It is so That's because there is no *obvious* way to do these. > -Quote - Phillip J. Eby from dirtsimple.org > Python as a community is plagued by massive amounts of > wheel-reinvention. The infamous web framework proliferation problem is > just the most egregious example. In stark contrast to Java, where everybody uses standard components like JSP, Struts, Tapestry, JSF, Spring, ... Daniel From exarkun at divmod.com Wed Jul 13 16:06:06 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 13 Jul 2005 16:06:06 -0400 Subject: DNS access In-Reply-To: <20050713192235.GC32027@computer.org> Message-ID: <20050713200606.26278.1826375224.divmod.quotient.11094@ohm> On Wed, 13 Jul 2005 15:22:35 -0400, Chris Lambacher wrote: >reverse dns lookup is not really special compared to a regular dns lookup. >you just need to look up a special name: >http://www.dnsstuff.com/info/revdns.htm > >to format the ip address properly use something like: >def rev_dns_string(ip_str): > nums = ip_str.split('.').reverse() > nums.extend(('in-addr', 'arpa')) > return '.'.join(nums) > It may not be special, but it is different. Reverse DNS uses PTR records, not A records. The site you referenced points this out, too: """ Reverse DNS entries are set up with PTR records (whereas standard DNS uses A records), which look like "25.2.0.192.in-addr.arpa. PTR host.example.com" (whereas standard DNS would look like "host.example.com. A 192.0.2.25"). """ Jp From http Sun Jul 31 19:38:45 2005 From: http (Paul Rubin) Date: 31 Jul 2005 16:38:45 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <7xd5ozv1ng.fsf@ruckus.brouhaha.com> Message-ID: <7xek9e5ywq.fsf@ruckus.brouhaha.com> Cliff Wells writes: > The bottom line is this: some people like Tk, some wxPython. Each has > advantages and disadvantages. But to claim that you *can only* do > something in one or the other only demonstrates that you haven't really > tried. I can put up a Tk gui in about 5 lines of code from a stock Python distro without having to install anything additional. How do I do that with wxPython? From coollakshman at gmail.com Wed Jul 13 10:44:41 2005 From: coollakshman at gmail.com (laksh) Date: 13 Jul 2005 07:44:41 -0700 Subject: DNS access Message-ID: <1121265881.737855.284030@g44g2000cwa.googlegroups.com> im looking for some advice regarding DNS lookup using python is it possible to give parameters like the IP of a DNS server and the DNS query to a python program and obtain the response from the DNS server ? please reply if u hav some idea or interest laksh From ccurvey at gmail.com Thu Jul 21 07:40:44 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 21 Jul 2005 04:40:44 -0700 Subject: Python Path Setting In-Reply-To: References: Message-ID: <1121946044.913072.317930@g44g2000cwa.googlegroups.com> http://www.python.org/doc/2.4.1/inst/search-path.html#SECTION000410000000000000000 From girishs at relq.com Fri Jul 8 08:22:27 2005 From: girishs at relq.com (Girish) Date: Fri, 8 Jul 2005 17:52:27 +0530 Subject: Query Message-ID: <001101c583b7$b4ac6d20$1c04010a@relqind01.relq.com> Hi, Can we control keyboard and mouse actions using python scripts in Linux environment? plz do reply. Regards Girish -------------- next part -------------- An HTML attachment was scrubbed... URL: From cam.ac.uk at mh391.invalid Sun Jul 24 16:32:48 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jul 2005 21:32:48 +0100 Subject: Try this In-Reply-To: <1122232247.337991.322150@o13g2000cwo.googlegroups.com> References: <1122232247.337991.322150@o13g2000cwo.googlegroups.com> Message-ID: RunLevelZero wrote: > I'm not sure I understand your first question but checkout the " glob " > module. Sounds like it may help. Who are you talking to? It would help if you quoted text from the original message, left some of the original subject, and replied to the original message instead of making a new post. -- Michael Hoffman From paolo_veronelli at tiscali.it Sun Jul 31 06:44:46 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sun, 31 Jul 2005 12:44:46 +0200 Subject: namespaces In-Reply-To: References: <42EC9690.2040301@tiscali.it> Message-ID: <42ECAB9E.4000501@tiscali.it> Robert Kern wrote: > Paolino wrote: > >>While it's not so bad we can bind names in the module namespace, (ex >>writing scripts ?) ,writing modules is someway bound to not polluting >>that namespace (really IMO). > > > I'm afraid that I can't parse that sentence. I show you a piece of code I need to define a function: import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) table=string.maketrans(badcars,'_'*len(badcars)) def translate(text): return text.translate(table) What I'm needing as a global (in globals() or at the module level or in the module namespace) is 'translate'.The rest of bindings (all,badcars and table) is something which is 'polluting' the module namespace. Now this is the non polluting version : class translate: import string all=string.maketrans('','') badcars=all.translate(all,string.letters+string.digits) @staticmethod def __call__(text,table=string.maketrans(badcars,'_'*len(badcars))): return text.translate(table) translate=translate() I'd like to have some help from the language in binding names this way. Hope I've been clearer :) Paolino ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From rwgk at yahoo.com Sat Jul 9 20:15:48 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 9 Jul 2005 17:15:48 -0700 (PDT) Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <1120912774.258331.12150@g47g2000cwa.googlegroups.com> Message-ID: <20050710001549.7217.qmail@web31514.mail.mud.yahoo.com> --- Kay Schluehr wrote: > Ralf, if you want to modify the class instantiation behaviour you I don't. I simply want to give the user a choice: __init__(self, ...) # same as always (no modification) or __autoinit__(self, ...) # self.x=x job done automatically and efficiently If someone overrides both __init__ and __autoinit__, the latter will have no effect (unless called from the user's __init__). > should have a look on metaclasses. That's what they are for. It is not > a particular good idea to integrate a new method into the object base > class for each accidental idea and write a PEP for it. ^^^^^^^^^^ ?????????? The flurry of suggestions indicates that many people have tried to find some way to reduce the boilerplate burden, even though everybody seems keen to point out that it is not that big a deal. It is not that big a deal indeed. But it is bigger than the problem solved by, e.g., enumerate, and I believe it can be solved with a comparable effort. > I provide you an example Thanks. > which is actually your use case. Close, but not quite. > It doesn't > change the class hierarchy : the metaclass semantics is not "is a" as > for inheritance but "customizes" as one would expect also for > decorators. > > class autoattr(type): > ''' > The autoattr metaclass is used to extract auto_xxx parameters from > the argument-tuple or the keyword arguments of an object > constructor __init__ > and create object attributes mit name xxx and the value of auto_xxx > passed > into __init__ > ''' > def __init__(cls,name, bases, dct): > super(autoattr,cls).__init__(name,bases,dct) > old_init = cls.__init__ > defaults = cls.__init__.im_func.func_defaults > varnames = cls.__init__.im_func.func_code.co_varnames[1:] > > def new_init(self,*args,**kwd): > for var,default in zip(varnames[-len(defaults):],defaults): This doesn't work in general. You are missing "if (defaults is not None):" as a condition for entering the loop. > if var.startswith("auto_"): > self.__dict__[var[5:]] = default > for var,arg in zip(varnames,args): > if var.startswith("auto_"): > self.__dict__[var[5:]] = arg > for (key,val) in kwd.items(): > if key.startswith("auto_"): > self.__dict__[key[5:]] = val > old_init(self,*args,**kwd) > cls.__init__ = new_init I couldn't easily time it because your approach changes the user interface (what are implementation details becomes exposed as "auto_"), but the code above is sure to introduce a serious runtime penalty. I stripped your code down to the essence. See attachment. For the user your approach then becomes: class grouping: __metaclass__ = autoattr def __init__(self, x, y, z): pass My __autoinit__ suggestion would result in (assuming object supports this by default): class grouping(object): def __autoinit__(self, x, y, z): pass I think that's far more intuitive. The timings are: overhead: 0.00 plain_grouping: 0.28 update_grouping: 0.45 plain_adopt_grouping: 0.69 autoinit_grouping: 1.15 autoattr_grouping: 1.01 Your approach wins out time-wise, mainly since you don't have to repeat the expensive '*.im_func.func_code.co_varnames[1:]" 3 or 4 * getattr + slicing operation for each object instantiation. However, I am hopeful that a built-in C implementation could eliminate most if not all runtime penalties compared to the hand-coded "plain_grouping" approach. Cheers, Ralf ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ From ali.jan at gmail.com Fri Jul 15 00:29:13 2005 From: ali.jan at gmail.com (Ali) Date: 14 Jul 2005 21:29:13 -0700 Subject: more newbie list questions In-Reply-To: <1121363544.684317.314540@g14g2000cwa.googlegroups.com> References: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> <1121363544.684317.314540@g14g2000cwa.googlegroups.com> Message-ID: <1121401753.066783.167910@g47g2000cwa.googlegroups.com> sTemplate.replace() returns a string with that substitution. so you need to reassign it such as: sTemplate = sTemplate.replace('author1', author1) Anyway, Sion Arrowsmith above showed you a much better technique of filling all those values at once. Hope this helps, Ali From rkern at ucsd.edu Sat Jul 30 19:50:24 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 30 Jul 2005 16:50:24 -0700 Subject: Escaping certain characters In-Reply-To: <42ec0f65$1@griseus.its.uu.se> References: <42ec0f65$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Hello, > > I'd like to encode the string that outputs: > > Hello > World! > > to 'Hello\x0aWorld!', and the string that outputs: > > Hello\World! > > to 'Hello\\World!'. > > Obviously, I want to be able to reverse the process. > > I'm going to assume this has already been solved in Python.. But how? In [1]: s = 'Hello\x0aWorld!' In [2]: print s Hello World! In [3]: s.encode('string_escape') Out[3]: 'Hello\\nWorld!' In [4]: Out[3].decode('string_escape') Out[4]: 'Hello\nWorld!' Not *quite* what you asked for, but it ought to be close enough. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From godoy at ieee.org Sun Jul 31 19:42:30 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 31 Jul 2005 20:42:30 -0300 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <7xd5ozv1ng.fsf@ruckus.brouhaha.com> <7xek9e5ywq.fsf@ruckus.brouhaha.com> Message-ID: <0940s2-672.ln1@strongwill.g2ctech> Paul Rubin wrote: > I can put up a Tk gui in about 5 lines of code from a stock Python > distro without having to install anything additional. How do I do > that with wxPython? You can try it here, without installing the package python-tk. And since you need to install python-tk, there's no problem at all installing package wxPython to achieve the same. Or kdebindings-python and using pyQt. Or installing another RPM package -- using Apt, so you don't have to worry about dependencies -- with a different toolkit. I've seen SuSE, Mandriva and Conectiva with separate packages for TKinter. I believe there are more. Unless, of course, you're first installing a personalized Python -- and loosing this "advantage". -- Jorge Godoy From peter at engcorp.com Wed Jul 6 08:48:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Jul 2005 08:48:50 -0400 Subject: adding a character to the last string element of a list In-Reply-To: <_WEye.1218$Ae.676@newssvr12.news.prodigy.com> References: <_WEye.1218$Ae.676@newssvr12.news.prodigy.com> Message-ID: Philippe C. Martin wrote: > I guess my slicing was wrong, l[-1] worked Note that that's _not_ a slice, however, but a reference to the last element in the list. You'd have to subclass list to be able to do something with "reference-slices". Probably returning a special object from __getslice__ which itself has references back to the original list and implements any changes back in the original instead of in itself. I haven't tried to imagine if this is even feasible. Anything "indexing" with : in it is a slice, so a copy, while anything with only a single index as you have in l[-1] is just a reference to one element in the list. -Peter From jason at tishler.net Mon Jul 25 15:22:52 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 25 Jul 2005 15:22:52 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E52F04.5010008@llnl.gov> References: <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> <42E52F04.5010008@llnl.gov> Message-ID: <20050725192252.GA3144@tishler.net> Dean, On Mon, Jul 25, 2005 at 11:27:16AM -0700, Dean N. Williams wrote: > I was able to run C:/cygwin/bin/ash.exe. This is good. In the > "ash.exe" window, I ran PATH=/bin rebaseall and received the same > error: "rebaseall: only ash processes are allowed ...... Execute > '/bin/rebaseall' from ash." Did you read the error message? In particular, the following: Exit all Cygwin processes and stop all Cygwin services. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From devlai at gmail.com Fri Jul 1 14:48:17 2005 From: devlai at gmail.com (Devan L) Date: 1 Jul 2005 11:48:17 -0700 Subject: class attribute to instance attribute In-Reply-To: References: <1120165777.941654.13390@f14g2000cwb.googlegroups.com> Message-ID: <1120243696.881393.314430@g49g2000cwa.googlegroups.com> Well, I've never heard of a method like that for assigning variables. I'd rather put it in the __init__ method. From kay.schluehr at gmx.net Sun Jul 10 01:11:38 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 Jul 2005 22:11:38 -0700 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120912774.258331.12150@g47g2000cwa.googlegroups.com> Message-ID: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> > I stripped your code down to the essence. See attachment. > For the user your approach then becomes: > > class grouping: > __metaclass__ = autoattr > def __init__(self, x, y, z): > pass No. This is clearly NOT what I had in mind. I translated your original proposal which introduced a punctuation syntax '.x' for constructor parameters forcing the interpreter to create equally named object attributes into a naming convention that can be handled by a metaclass customizer. The grouping.__init__ above does exacly nothing according to my implementation. I would never accept dropping fine-tuning capabilities. The "auto_" prefix is all the declarative magic. > My __autoinit__ suggestion would result in (assuming object supports > this by default): > > class grouping(object): > def __autoinit__(self, x, y, z): > pass > > I think that's far more intuitive. Being intuitive is relative to someones intuition. Kay From travislspencer at gmail.com Thu Jul 21 11:29:31 2005 From: travislspencer at gmail.com (travislspencer at gmail.com) Date: 21 Jul 2005 08:29:31 -0700 Subject: Filling up commands.getstatusoutput's buffer In-Reply-To: References: <1121897448.949323.8020@g43g2000cwa.googlegroups.com> Message-ID: <1121959771.399383.188790@f14g2000cwb.googlegroups.com> Jeff Epler wrote: > On Wed, Jul 20, 2005 at 03:10:49PM -0700, travislspencer at gmail.com wrote: > How much output are you talking about? Honestly, I don't know. I came on to a project were they said they were hitting up against some limit, and had a hack to work around it. I just wondered if others had hit some limit too and found diffrent workarounds. > I tried outputs as large as > about 260 megabytes without any problem. (RedHat 9, Python 2.2) > > >>> len(commands.getoutput("dd if=/dev/zero bs=512 count=512000 2>/dev/null")) > 262144000 > >>> 512 * 512000 > 262144000 I tried the same tests on CentOS, Python 2.3.4 and on Solaris 9 w/ Python 2.3.3. No problems. -- Regards, Travis Spencer From alanmk at hotmail.com Mon Jul 25 12:34:35 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 25 Jul 2005 17:34:35 +0100 Subject: Counting processors In-Reply-To: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> Message-ID: <6x8Fe.2911$R5.667@news.indigo.ie> [Pauldoo] > Is a way in python to obtain the total number of processors present in > the system? On windows, List Processor Information. Description: Returns information about the processors installed on a computer. http://www.microsoft.com/technet/scriptcenter/scripts/Python/hardware/basic/hwbapy01.mspx -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From peter at engcorp.com Fri Jul 22 09:08:25 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 09:08:25 -0400 Subject: tuple to string? In-Reply-To: References: Message-ID: Francois De Serres wrote: > hiho, > > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to > the string 'spam'? >>> mytuple = (0x73, 0x70, 0x61, 0x6D) >>> ''.join(chr(v) for v in mytuple) 'spam' From hancock at anansispaceworks.com Sat Jul 2 17:00:59 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 16:00:59 -0500 Subject: Python, mysql, floating point values question In-Reply-To: <42C6147B.9040408@lexicon.net> References: <43b72594050701154055297e73@mail.gmail.com> <42C6147B.9040408@lexicon.net> Message-ID: <200507021601.00152.hancock@anansispaceworks.com> On Friday 01 July 2005 11:13 pm, John Machin wrote: > x BETWEEN y AND z Ah, even better, thank you. > The python equivalent would be to write it out as: > > > > if a > b-epsilon and a < b+epsilon: > > print "a~=b" > > Try this: > > if b-epsilon < a < b+epsilon: This I knew, but I was trying to write the closest thing to what the SQL code would look like, and I didn't know about BETWEEN. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From benji at benjiyork.com Sat Jul 23 14:14:38 2005 From: benji at benjiyork.com (Benji York) Date: Sat, 23 Jul 2005 14:14:38 -0400 Subject: unit test nested functions In-Reply-To: <1122137952.092438.34830@f14g2000cwb.googlegroups.com> References: <1122134462.286558.16160@f14g2000cwb.googlegroups.com> <1122137952.092438.34830@f14g2000cwb.googlegroups.com> Message-ID: <42E2890E.9090003@benjiyork.com> Raymond Hettinger wrote: > [Benji York] > >>Note that when using this technique, f.g will not be bound until after >>you call the function: > > > That is a feature, not a bug. The inner function isn't even created > until the outer function is run. I'm fully aware of that. I just didn't want the OP get bit by it. -- Benji York From onurb at xiludom.gro Mon Jul 4 11:32:49 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 04 Jul 2005 17:32:49 +0200 Subject: How do you program in Python? In-Reply-To: References: <3iqif8Fmj34kU1@individual.net> <42c929dc$0$27601$636a15ce@news.free.fr> Message-ID: <42c956a2$0$31213$636a15ce@news.free.fr> Roy Smith wrote: > bruno modulix wrote: > > >>Try Emacs + python-mode. Emacs surely has a lot of warts, but I'm still >>looking for a better and more versatile code editor/IDE - specially when >>it comes to languages with REPL (-> Read-Eval-Print Loop). > > > When you build Python, make sure you build it with Gnu readline support. > Then you can just fire up an interpreter, and use emacs (or, I suppose, vi) > editing commands to scroll back through (and change) your input history. > It's not as good as a real IDE, but it's still very handy for quick > explorations. > > The next step up would be to run a real emacs, do M-X shell, then fire up a > Python interpreter inside that. > > Or, go into split screen mode in emacs, editing your python source file in > one window and running a shell in the other. Edit some code in the source > window, and it takes about 6 keystrokes to save it, flip to the other > window, and re-run the file (you can get it down to a single keystroke by > defining a simple macro and binding it to a function key). Err... actually, using python-mode is *way* more simple: [ctrl+c ! to launch the REPL (this splits the frame) if it's not already running] [ctrl+x o to go back to the source code buffer] then ctrl+c ctrl+c to execute the whole buffer in the REPL or select a region then ctrl+c ctrl+l to execute the selected region in the REPL Of course, the REPL now reflect any changes made into the source code buffer (even if changes have not been saved) !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gsakkis at rutgers.edu Tue Jul 5 09:30:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jul 2005 06:30:59 -0700 Subject: distutils is able to handle... References: Message-ID: <1120570259.138484.140720@f14g2000cwb.googlegroups.com> "mg" wrote: > Hello > > I work on an finite element framework and Python bindings have been > developped. > Actually, we use Boost.Build as build system but we would like to change > it. > > We have two kinds of problems. First, the framework is used for generate > pure C++ applications with static libraries ; second, the framework have > some dependencies to fortran projects. > Then, in order to know if Distutils can be use in our case, I would like > to know if : > - Can distutil compile static C/C++ libraries ? > - Can distutil compile C/C++ applications ? > - Can distutil manage fortran compiler and compile fortran libraries and > applications ? > > Thank for your answers I don't think distutils can handle all these, especially the last one, so I doubt it's the right tool in your case. I would suggest SCons (http://www.scons.org/), a modern make/automake/autoconf replacement that uses python for its configuration files instead of yet another cryptic half-baked mini-language or XML. George From philippe at philippecmartin.com Thu Jul 7 17:29:04 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 07 Jul 2005 21:29:04 GMT Subject: Options to integrate Python modules into native windows applications Message-ID: Hi, I am looking for the pros and cons as to how to integrate a Python module into a Windows native application. So far I have looked at 1) coding the C wrapper myself 2) using Pyrex 3) go for pywin32 and COM Thanks, Philippe From brian at sweetapp.com Fri Jul 15 12:00:49 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 15 Jul 2005 18:00:49 +0200 Subject: Python Programming Contest In-Reply-To: <17111.56543.474831.814515@montanaro.dyndns.org> References: <42D780EF.6020809@sweetapp.com> <17111.39597.277505.234455@montanaro.dyndns.org> <42D7A188.2010306@sweetapp.com> <17111.56543.474831.814515@montanaro.dyndns.org> Message-ID: <42D7DDB1.7040503@sweetapp.com> skip at pobox.com wrote: > Brian> This contest is for people who like thinking about algorithms. > > Surely you must have missed the smiley... No, I saw it but it just confused me as I have no sense of humor. Cheers, Brian From aisaac0 at verizon.net Mon Jul 11 17:23:44 2005 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 11 Jul 2005 21:23:44 GMT Subject: tuple.index(item) Message-ID: Why don't tuples support an index method? It seems natural enough ... Thanks, Alan Isaac From __peter__ at web.de Thu Jul 14 02:38:36 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Jul 2005 08:38:36 +0200 Subject: constructor list slice confusion References: Message-ID: Simon Morgan wrote: > Can somebody please explain to me why: > > class SomeClass: > def?__init__(self,?contents=[]): > self.contents?=?contents[:] > def?add(self,?element): > self.contents.append(element) > > when called a second time (i.e. to create a new instance of a SomeClass > object) results in self.contents being assigned an empty list when say for > example I've done: > > foo = SomeClass() > foo.add(1) > foo.add(2) > > beforehand? Maybe, after a little renaming you can see it yourself: class SomeClass: def __init__(self, default_contents=[]): # make a copy of default_contents that is # kept in a SomeClass instance self.contents = default_contents[:] def add(self, element): # modify the *copy* of default_contents... self.contents.append(element) When you want modifiable defaults, you can use a class attribute: >>> class SomeClass: ... default_contents = [] ... def __init__(self, contents=default_contents): ... self.contents = contents[:] ... def add(self, elem): self.contents.append(elem) ... def addDefault(self, elem): self.default_contents.append(elem) ... def __repr__(self): ... return "SomeClass(contents=%s, default_contents=%s)" % ( ... self.contents, self.default_contents) ... >>> foo = SomeClass() >>> foo SomeClass(contents=[], default_contents=[]) >>> foo.add(1) >>> foo.addDefault("x") >>> foo SomeClass(contents=[1], default_contents=['x']) >>> >>> bar = SomeClass() >>> bar SomeClass(contents=['x'], default_contents=['x']) >>> bar.add(2) >>> bar SomeClass(contents=['x', 2], default_contents=['x']) Peter From luismgz at gmail.com Wed Jul 20 17:55:50 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 20 Jul 2005 14:55:50 -0700 Subject: mod_python Apache/2.0.52 (Win32) Python 2.4 In-Reply-To: <38d6a9b7.0507201214.12c048ac@posting.google.com> References: <38d6a9b7.0507201214.12c048ac@posting.google.com> Message-ID: <1121896550.154757.152690@g47g2000cwa.googlegroups.com> Dieter Raber wrote: > Hi there, > > I am wondering if there is a mod_python for the above configuration. I > downloaded mod_python-3.1.3.win32-py2.3.exe, which of course as the > name implies keeps on asking me for a python 2.3 installation. I > imagine one could cheat a little bit with a fake registry entry that > says it was about python 2.3 but that points to python 2.4. Then again > I don't know what entry mod_python's installer is looking for. > > Thanks for your help > > Dieter Hi there, A couple of months ago, I went though the hassle of trying to install mod_python and unfortunately, there is no easy way of doing it separately, because you have to take care about each component's version, that should match the other component's one... If you one to do it all at once and get it working, try Apache2Triad: http://apache2triad.net/ This is a package inspired in EasyPhp and PhpTriad and. It installs all the required software (plus a lot of other programs - check the website). It is aimed at webdevelopers who don't want to deal with individual instalations or configurations. The only downside is that it will install many programs that you are probably not interested in... but you might like it. Cheers, Luis From deets at web.de Sun Jul 3 12:55:28 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 03 Jul 2005 18:55:28 +0200 Subject: How do you program in Python? In-Reply-To: <3iqif8Fmj34kU1@individual.net> References: <3iqif8Fmj34kU1@individual.net> Message-ID: <3iqjk1FmctofU1@uni-berlin.de> anthonyberet wrote: > My question isn't as all-encompassing as the subject would suggest... > > I am almost a Python newbie, but I have discovered that I don't get > along with IDLE, as i can't work out how to run and rerun a routine > without undue messing about. > > What I would really like is something like an old-style BASIC > interpreter, in which I could list, modify and test-run sections of > code, to see the effects of tweaks, without having to save it each time, > or re-typing it over and over (I haven't even worked out how to cut and > paste effectively in the IDLE environment). > > I see lots of alternate IDEs etc, but which would allow me the simple > interface that I have described? - I really don't know about IDEs in > general, and I suspect I would be out of my depth with one of those. The property of basic to have explicit linenumbering is the reason you've been able to work in that style of programming, as you could simply overwrite parts of the program. But that's close to undoable in all other languages. Python has the interactive REPL that you can use to toy around interactively and is very helpful to me - especially when enriched with rlcompleter2. - You can even replace functions or classes while working and toying around. But the amount of reasonable editing work that can be done in the interpreter is pretty limited. You _need_ a decent editor for that. So what I usually do is to create a test.py that contains the code I want to tinker with, and simply run that in a shell - cygwin on windows, but usually I work in *NIX-style environments, so it's even easier. As there is no compilation or whatsoever required, that works pretty well for me. Diez From bokr at oz.net Sat Jul 23 18:14:41 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 23 Jul 2005 22:14:41 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <42e15f81$1@news.eftel.com> Message-ID: <42e29d5c.963163926@news.oz.net> On Sat, 23 Jul 2005 07:05:05 +1000, John Machin wrote: >Daniel Dittmar wrote: >> Duncan Booth wrote: >> >>> I would have expected a path object to be a sequence of path elements >>> rather than a sequence of characters. >> >> >> Maybe it's nitpicking, but I don't think that a path object should be a >> 'sequence of path elements' in an iterator context. >> >> This means that >> >> for element in pathobject: >> >> has no intuitive meaning for me, so it shouldn't be allowed. > >Try this: > >A file-system is a maze of twisty little passages, all alike. Junction >== directory. Cul-de-sac == file. Fortunately it is signposted. You are >dropped off at one of the entrance points ("current directory", say). >You are given a route (a "path") to your destination. The route consists >of a list of intermediate destinations. > >for element in pathobject: > follow_sign_post_to(element) > >Exception-handling strategy: Don't forget to pack a big ball of string. >Anecdotal evidence is that breadcrumbs are unreliable. > ISTM a path is essentially a representation of a script whose interpretation by an orderly choice of interpreters finally leads to accessing to some entity, typically a serial data representation, through an object, perhaps a local proxy, that has standard methods for accessing the utimate object's desired info. IOW, a path sequence is like a script text that has been .splitline()'d and and the whole sequence fed to a local interpreter, which might chew through multiple lines on its own, or might invoke interpreters on another network to deal with the rest of the script, or might use local interpreters for various different kinds of access (e.g., after seeing 'c:' vs 'http://' vs '/c' vs '//c' etc. on the platform defining the interpretation of the head element). Turning a single path string into a complete sequence of elements is not generally possible unless you have local knowledge of the syntax of the entire tail beyond the the prefix you have to deal with. Therefore, a local platform-dependent Pathobject class should, I think, only recognize prefixes that it knows how to process or delegate processing for, leaving the interpretation of the tail to the next Pathobject instance, however selected and/or located. So say (this is just a sketch, mind ;-) po = Pathobject() results in a po that splits out (perhaps by regex) a prefix, a first separator/delimiter, and the remaining tail. E.g., in class Pathobject, def __init__(self, pathstring=None) if pathstring is None: #do useful default?? self.pathstring = pathstring self.prefix, self.sep, self.tail = self.splitter(pathstring) if self.prefix in self.registered_prefixes: self.child = self.registered_prefixes[self.prefix](self.tail) else: self.child = [] self.opened_obj = None Then the loop inside a local pathobject's open method po.open() might go something like def open(self, *mode, **kw): if self.child: self.opened_obj = self.child.open(self.tail, *mode, **kw) else: self.opened_obj = file(self.pathstring, *mode) return self And closing would just go to the immediately apparent opened object, and if that had complex closing to do, it would be its responsibility to deal with itself and its child-derived objects. def close(self): self.opened_object.close() The point is that a given pathobject could produce a new or modified pathobject child which might be parsing urls instead of windows file system path strings or could yield an access object producing something entirely synthetic. A synthetic capability could easily be introduced if the local element pathobject instance looked for e.g., 'synthetic://' as a possible first element (prefix) string representation, and then passed the tail to a subclass defining synthetic:// path interpretation. E.g., 'synthetic://temp_free_diskspace' could be a platform-independent way to get such info as that. Opening 'testdata:// ...' might be an interesting way to feed test suites, if pathobject subclasses could be registered locally and found via the head element's string representation.' One point from this is that a path string represents an ordered sequence of elements, but is heterogenous, and therefore has potentially heterogenous syntax reflected in string tails with syntax that should be interpreted differently from the prefix syntax. Each successive element of a path string effectively requires an interpreter for that stage of access pursuit, and the chain of processing may result in different path entities/objects/representations on different systems, with different interpretations going on, sharing only that they are part of the process of getting access to something and providing access services, if it's not a one-shot access. This would also be a potential way to create access to a foreign file system in pure python if desired, so long as there was a way of accessing the raw data to build on, e.g. a raw stuffit floppy, or a raw hard disk if there's the required privileges. Also 'zip://' or 'bzip2://' could be defined and registered by a particular script or in an automatic startup script. 'encrypted://' might be interesting. Or if polluting the top namespace was a problem, a general serialized data access header element might work, e.g., 'py_sda://encrypted/...' This is very H[ot]OTTOMH (though it reflects some thoughts I've had before, so be kind ;-) For compatibility with the current way of doing things, you might want to do an automatic open in the Pathobject constructor, but I don't really like that. It's easy enough to tack on ".open()" po = Pathobject('py_sda://encrypted/...') po.open() # plain read_only text default file open, apparently, but encrypted does binary behind the scenes print po.read() po.close() Say, how about if Pathobject('gui://message_box/yn/continue processing?').open().read().lower()!='y': raise SystemExit, "Ok, really not continuing ;-)" An appropriate registered subclass for the given platform, returned when the Pathobject base class instantiates and looks at the first element on open() and delegates would make that possible, and spelled platform-independently as in the code above. Regards, Bengt Richter From spanking.13.littlegoats at spamgourmet.com Thu Jul 14 16:48:09 2005 From: spanking.13.littlegoats at spamgourmet.com (Sheeps United) Date: Thu, 14 Jul 2005 23:48:09 +0300 Subject: Changing size of Win2k/XP console? References: <42d6bdd2$0$16170$39db0f71@news.song.fi> Message-ID: <42d6cf32$0$16170$39db0f71@news.song.fi> "Peter Hansen" wrote in message news:I9-dnekiad4vVUvfRVn-uw at powergate.ca... > Which Windows API call did you try using? Can you show us a line or two > of code that you tried? Most likely then someone will be able to point > out what went wrong and it will work. (Chances are that very few here > know the API call required, so by not mentioning it you're severely > limiting the number of answers you are likely to get.) No actual code, yet. I'm far from sure if it's the right one, but I think it could be SetConsoleScreenBufferSize from Kernel32. Hrr, for some reason I have nasty feeling in back of my head... That could also be totally wrong way of approaching. From cliff at develix.com Sun Jul 31 21:17:20 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 18:17:20 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <7x4qaa32p8.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <8664uqhkfj.fsf@bhuda.mired.org> <7xu0iale9x.fsf@ruckus.brouhaha.com> <7x4qaa32p8.fsf@ruckus.brouhaha.com> Message-ID: <1122859040.19618.230.camel@localhost.localdomain> On Sun, 2005-07-31 at 17:45 -0700, Paul Rubin wrote: > Cliff Wells writes: > > > The usual way to do that is with a web GUI, but nothing stops you from > > > running Tkinter on a Unix server through a remote X connection. > > > > Of course not, but unless the servers are on a trusted network and use > > an authentication scheme such as kerberos, you are asking for trouble. > > If it's for sensitive stuff normally you'd use https. Hm, I haven't tried piping X over https... I wasn't even aware it was possible... do you have a link I can check this out on? Also, why not just stunnel or ssh -Y instead? Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From gnb at itga.com.au Thu Jul 7 04:10:44 2005 From: gnb at itga.com.au (Gregory Bond) Date: Thu, 07 Jul 2005 18:10:44 +1000 Subject: How do you program in Python? In-Reply-To: References: <3iqif8Fmj34kU1@individual.net> Message-ID: <42oiad.vg8.ln@lightning.itga.com.au> Jorgen Grahn wrote: > Emacs and vim are almost always installed, or trivially installable. All I > need to remember is to bring my emacs config file. And, fortunately, USB pen drives are now big enough to hold it! From jlconlin at lanl.gov Wed Jul 6 12:58:42 2005 From: jlconlin at lanl.gov (Jeremy) Date: Wed, 06 Jul 2005 10:58:42 -0600 Subject: inheriting file object Message-ID: Hello all, I am trying to inherit the file object and don't know how to do it. I need to open a file and perform operations on it in the class I am writing. I know the simple syntax is: class MyClass(file): ... but I don't know how to make it open the file for reading/writing. Can anyone help me out with this? Thanks, Jeremy From xin.kuo at gmail.com Fri Jul 1 04:05:59 2005 From: xin.kuo at gmail.com (kuoxin) Date: 1 Jul 2005 01:05:59 -0700 Subject: Windows installation - questions about DLLs In-Reply-To: References: Message-ID: <1120205159.456824.44850@g43g2000cwa.googlegroups.com> python23.dll requires msvcrt.dll basically. if you use some .pyd, python requires other dll. for example: import _mysql # you must add a libmysql.dll for this module kuoxin Guillaume Hiron wrote: > Hi, > > I need to install python (2.3.5) on windows without the giving installer > program. > Do you know what dlls are needed? > I found python23.dll, but the other (msvcrt.dll,msvcrit.dll) seems not > be useful. > Is there other dll? Are msvcrt.dll and msvcrit.dll used by > something?(test/test___all__.py return no error whitout these two dlls). > > Thanks for helping. From mo.babaei at gmail.com Thu Jul 21 10:27:53 2005 From: mo.babaei at gmail.com (mohammad babaei) Date: Thu, 21 Jul 2005 18:57:53 +0430 Subject: Python session handling Message-ID: <5bf3a41f050721072771e2967@mail.gmail.com> Hi, What is th best way for "session tracking" in python ? regards, mo -------------- next part -------------- An HTML attachment was scrubbed... URL: From d0153030 at hotmail.com Fri Jul 22 12:32:04 2005 From: d0153030 at hotmail.com (Sandeep Arya) Date: Fri, 22 Jul 2005 10:32:04 -0600 Subject: Detecting computers on network In-Reply-To: Message-ID: Thanks linuxfreak and sybren for positive comments My application will be running on Linux. How to send ICMP ECHO as broadcast packets. I do not know this. Please tell me how to? Sybren.. Does nmap is available on every systems? I tried on my linux fc4 machine in user previleage. it was not working. Does this just belongs to superuser... Is there any other way ? Can just socket.connect or sendto help me? I.E. their return valuess... Sandeep From: Sybren Stuvel To: python-list at python.org Subject: Re: Detecting computers on network Sent: Friday, July 22, 2005 1:59 AM linuxfreak enlightened us with: >How about sending an ICMP echo packet to your broadcast address and >checking which hosts send a reply Won't work on all boxes. Windows boxes ignore broadcast pings, for example. I'd go for a call to "nmap -sP" instead, and filter it's output. Sybren _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From thanos at sians.org Tue Jul 19 12:56:20 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Tue, 19 Jul 2005 19:56:20 +0300 Subject: dictionary as property Message-ID: <20050719165620.GA4136@zermelo.sians.org> Hello. (How) can I have a class property d, such that d['foo'] = 'bar' will run a certain function of the class with 'foo' and 'bar' as it's arguments? Thanks in advance. -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From devlai at gmail.com Sat Jul 9 01:44:49 2005 From: devlai at gmail.com (Devan L) Date: 8 Jul 2005 22:44:49 -0700 Subject: removing list comprehensions in Python 3.0 In-Reply-To: References: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> Message-ID: <1120887889.287054.194040@o13g2000cwo.googlegroups.com> >>> import timeit >>> t1 = timeit.Timer('list(i for i in xrange(10))') >>> t1.timeit() 27.267753024476576 >>> t2 = timeit.Timer('[i for i in xrange(10)]') >>> t2.timeit() 15.050426800054197 >>> t3 = timeit.Timer('list(i for i in xrange(100))') >>> t3.timeit() 117.61078097914682 >>> t4 = timeit.Timer('[i for i in xrange(100)]') >>> t4.timeit() 83.502424470149151 Hrm, okay, so generators are generally faster for iteration, but not for making lists(for small sequences), so list comprehensions stay. From gh at ghaering.de Mon Jul 18 11:55:48 2005 From: gh at ghaering.de (Gerhard Haering) Date: Mon, 18 Jul 2005 17:55:48 +0200 Subject: goto In-Reply-To: <1121701216.092182.87990@g14g2000cwa.googlegroups.com> References: <1121701216.092182.87990@g14g2000cwa.googlegroups.com> Message-ID: <20050718155548.GA23436@mylene.ghaering.de> On Mon, Jul 18, 2005 at 08:40:16AM -0700, Kay Schluehr wrote: > Hayri ERDENER schrieb: > > hi, > > what is the equivalent of C languages' goto statement in python? > > best regards > > No, but some of goto's use cases can be covered by unconditional jumps > provided by exceptions. [...] I like the "named loops" concept of other HLL like Ada 95 or Java better than either goto or exceptions. It allows you to use "break" and "continue" for other than the innermost loops, too: break; => break out of inner loop break loop_name; => break out of named loop "loop_name" OTOH it's not used *that* often, so I won't argue for including it in Python ;) -- Gerhard -- Gerhard H?ring - gh at ghaering.de - Python, web & database development -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rkern at ucsd.edu Mon Jul 11 19:06:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Jul 2005 16:06:16 -0700 Subject: How does this code works: In-Reply-To: References: Message-ID: vch wrote: > Here's an example from some book: > > def foo(n): > s = [n] > def bar(i): > s[0] += i > return s[0] > return bar > > what I don't understand is how this example works, taking into account > the LGB rule. I thought that s is not accessible from bar, but it is, > apparently. Why? Python now has nested scopes. http://www.python.org/peps/pep-0227.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mwm at mired.org Fri Jul 29 20:23:32 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 29 Jul 2005 20:23:32 -0400 Subject: Block-structured resource handling via decorators References: Message-ID: <8664uti1kr.fsf@bhuda.mired.org> "John Perks and Sarah Mount" writes: > When handling resources in Python, where the scope of the resource is > known, there seem to be two schools of thought: > > (1) Explicit: > f = open(fname) > try: > # ... > finally: > f.close() > > (2) Implicit: let the GC handle it. The only cases I see the first school of thought is when the resource in question is "scarce" in some way. For example, most OS's place a limit on the number of open files a process can have, some rather tight. CPython's garbage collector will close an open file when it leaves scope. Jython's GC will close it when the file is collected, but you have no idea of when that will be, and an "open" failing won't trigger a GC. So in this case, the first form is less likely to fail unexpectedly. > I've come up with a third method that uses decorators to achieve a > useful mix between the two. The scope of the resource is clear when > reading the code (useful if the resource is only needed in part of a > function), while one does not have to write an explicit cleanup. A > couple of examples: > > @withFile(fname, 'w') > def do(f): > # ... write stuff into file f ... > > @withLock(aLock): > def do(): > # ... whatever you needed to do once the lock was acquired, > # safe in the knowledge it will be released afterwards ... > > The implementation is easily extensible: a handler for a new type of > resource can be written in as a couple of lines. For the examples above: > > class withFile(blockScopedResource): > init, cleanup = open, 'close' > > It's so simple I was wondering why I haven't seen it before. Possibly: > it's a stupid idea and I just can't see why; > everyone knows about it except me; > it's counter-intuitive (that's not the way decorators were intended); > it's "writing C# in Python" or in some other way unPythonic; > I've actually had an idea that is both Original and non-Dumb. Well, I'd say that using a string for cleanup and a function for init is unpythonic. But the general idea seems to be a good one. Making it easy to deal with resources that must be explicitly released is a good thing. The question is whether having to turn your scope into a function to do this is more trouble than it's worth. I'd certainly be interested in seeing the implementation. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Mon Jul 25 15:36:12 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Jul 2005 20:36:12 +0100 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050725192252.GA3144@tishler.net> References: <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> <42E52F04.5010008@llnl.gov> <20050725192252.GA3144@tishler.net> Message-ID: Jason Tishler wrote: > Dean, > > On Mon, Jul 25, 2005 at 11:27:16AM -0700, Dean N. Williams wrote: > >>I was able to run C:/cygwin/bin/ash.exe. This is good. In the >>"ash.exe" window, I ran PATH=/bin rebaseall and received the same >>error: "rebaseall: only ash processes are allowed ...... Execute >>'/bin/rebaseall' from ash." > > > Did you read the error message? In particular, the following: > > Exit all Cygwin processes and stop all Cygwin services. > I did an write-up of rebasing, basically updating instructions you and others had been good enough provide in the past: http://www.holdenweb.com/review/rvw002.html regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ed at leafe.com Sun Jul 31 21:13:28 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 21:13:28 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <1122829672.285541.45710@g43g2000cwa.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <1122829672.285541.45710@g43g2000cwa.googlegroups.com> Message-ID: <200507312113.28402.ed@leafe.com> On Sunday 31 July 2005 13:07, Kay Schluehr wrote: > My objection with wrappers around wrappers around wrappers is that I > have no hope ever watching the ground. If some error occurs, which > layer has to be addressed? Which developing group is reponsible? My own > or that of team A, team B, team C ... ? FWIW, we view errors that occur in Dabo as our responsibility. We've had several reported that were our fault, and we corrected them. Others were the result of underlying bugs in wxPython, and we reported them to Robin, who quickly fixed them. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From sklass at pointcircle.com Thu Jul 14 09:37:49 2005 From: sklass at pointcircle.com (rh0dium) Date: 14 Jul 2005 06:37:49 -0700 Subject: Help - Classes and attributes In-Reply-To: <42d64891$0$15020$626a14ce@news.free.fr> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> <42d64891$0$15020$626a14ce@news.free.fr> Message-ID: <1121348269.371318.221160@g44g2000cwa.googlegroups.com> Thanks Bruno!! Very much appreciated the modifications!! Bruno Desthuilliers wrote: > rh0dium a ?crit : > > Hi all, > > > > I believe I am having a fundamental problem with my class and I can't > > seem to figure out what I am doing wrong. Basically I want a class > > which can do several specific ldap queries. So in my code I would have > > multiple searches. But I can't figure out how to do it without it > > barfing.. > > > > The error is straightforward .. > > > > LDAP Version 2.0.8 > > Traceback (most recent call last): > > File "./ldap-nsc.py", line 62, in ? > > l.search() > > File "./ldap-nsc.py", line 40, in search > > ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, > > retrieveAttrs) > > AttributeError: NSCLdap instance has no attribute 'search_s' > > > > > > The code is also I believe straight forward.. > > > > import ldap > > > > class NSCLdap: > > > > def __init__(self,server="sc-ldap.nsc.com"): > > who=""; cred="" > > self.server=server > > try: > > print "LDAP Version", ldap.__version__ > > l=ldap.open(server) > > l.simple_bind_s(who, cred) > > l.protocol_version=ldap.VERSION3 > > except ldap.LDAPError, error_message: > > print "Couldn't Connect to %s %s " % > > (server,error_message) > > And then you throw away the ldap connection... > > > > def search(self, baseDN="o=nsc.com", > > retrieveAttrs=None,searchAttrs="cn=*klass*" ): > > searchScope = ldap.SCOPE_SUBTREE > > try: > > ldap_result_id = l.search_s(baseDN, searchScope, > > searchAttrs, retrieveAttrs) > > Now where is this 'l' coming from ? > > > result_set = [] > > while 1: > > result_type, result_data = l.result(ldap_result_id, 0) > > if (result_data == []): > > break > > else: > > ## here you don't have to append to a list > > ## you could do whatever you want with the > > individual entry > > ## The appending to list is just for > > illustration. > > if result_type == ldap.RES_SEARCH_ENTRY: > > result_set.append(result_data) > > print result_set > > except ldap.LDAPError, error_message: > > print "Errors on Search %s " % error_message > > > > def setBaseDN(self, baseDN="o=nsc.com"): > > return baseDN > > Err... this code is not 'setting' anything. > > > if __name__ == '__main__': > > > > l = NSCLdap() > > l.search() > > > > > > I would love some pointers - clearly my code thinks that search_s is an > > attribute of my class but it's not.. > > try with this instead : > q = NSCLdap() > q.search() > > > May I suggest a somewhat corrected version ? > > class NSCLdap(object): > def __init__(self, > server="sc-ldap.nsc.com", > baseDN="o=nsc.com", > who=None, > cred=None): > self.server = server > self.baseDN = baseDN > if who is None: > self.who = "" > else: > self.who = who > if cred is None: > self.cred = "" > else: > self.cred = cred > self.connection = None > > def connect(self): > try: > print "LDAP Version", ldap.__version__ > self.connection = ldap.open(server) > self.connection.simple_bind_s(self.who, self.cred) > self.connection.protocol_version=ldap.VERSION3 > > except ldap.LDAPError, error_message: > # I would not catch this. It's the caller's > # responsabilitie to handle this IMHO > print >> sys.stderr, "Couldn't Connect to %s %s " % > (server,error_message) > > def search(self, > baseDN=None, > searchScope=ldap.SCOPE_SUBTREE, > retrieveAttrs=None, > searchAttrs="cn=*klass*" ): > > cnx = self.connection > if baseDN is None: > baseDN = self.baseDN > > try: > ldap_result_id = cnx.search_s(baseDN, > searchScope, > searchAttrs, > retrieveAttrs) > result_set = [] > while True: > result_type, result_data =cnx.result(ldap_result_id, 0) > #if (result_data == []): > if not result_data: > break > ## here you don't have to append to a list > ## you could do whatever you want with the > ## individual entry > ## The appending to list is just for > ## illustration. > if result_type == ldap.RES_SEARCH_ENTRY: > result_set.append(result_data) > print result_set > except ldap.LDAPError, error_message: > print >> sys.stderr, "Errors on Search %s " % error_message > > if __name__ == '__main__': > truc = NSCLdap() > truc.search() From max at alcyone.com Thu Jul 7 23:14:10 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 07 Jul 2005 20:14:10 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <3j40aoFocvh4U1@individual.net> Message-ID: <6oadncSMIs0fclDfRVn-jg@speakeasy.net> Ron Adam wrote: > It's not an empty tuple, it's an empty parenthesis. Using tuples it > would be. > > (a,) == (,) > > which would be the same as: > > (,) == (,) >>> () () >>> a = () >>> type(a) >>> (,) File "", line 1 (,) ^ SyntaxError: invalid syntax You've wandered way off into the woods now. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis But since when can wounded eyes see / If we weren't who we were -- Joi From steve.morin at gmail.com Wed Jul 6 09:26:45 2005 From: steve.morin at gmail.com (steve.morin at gmail.com) Date: 6 Jul 2005 06:26:45 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <1120656405.722298.151710@g49g2000cwa.googlegroups.com> map, filter, reduce and lambda Lisp constructs, bring flexibility to the language and is why I started programming in python to begin with. Removing these constructs will be a shame and one step closer to the death of some of the basic features that make python great. From elbertlev at comcast.net Mon Jul 18 09:04:48 2005 From: elbertlev at comcast.net (Comcast) Date: Mon, 18 Jul 2005 09:04:48 -0400 Subject: goto References: Message-ID: In python there is no goto statement. In C I use goto only in one case: to exit more then one level of blocks (as a matter of fact, I always use goto EXIT in C, where EXIT is the label of the end of the function). In python you can mimic this by throwing an exception and catching it. Exception should "know" the destination label name and the catch statement should compare this name with its (catch statement) name. "Hayri ERDENER" wrote in message news:mailman.1853.1121687294.10512.python-list at python.org... hi, what is the equivalent of C languages' goto statement in python? best regards From pinard at iro.umontreal.ca Sun Jul 10 13:53:25 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 10 Jul 2005 13:53:25 -0400 Subject: computer algebra packages In-Reply-To: <20050710171221.GA29664@phenix.progiciels-bpi.ca> References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> <20050710171221.GA29664@phenix.progiciels-bpi.ca> Message-ID: <20050710175325.GA30611@phenix.progiciels-bpi.ca> > > Mascyma is (trying to be) a user-friendly graphical frontend for > > the Computer Algebra System GNU MAXIMA. > I was not successful googling for this one. Would you have an URL handy? Oops, OK! Found it at http://cens.ioc.ee/~pearu/misc/maxima/ . -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From tjreedy at udel.edu Fri Jul 1 14:22:51 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Jul 2005 14:22:51 -0400 Subject: Accepted Summer of Code proposals References: Message-ID: "A.M. Kuchling" wrote in message news:qO-dnb4jKeQF-VjfRVn-jg at speakeasy.net... > For anyone who's interested: the Python wiki now contains a list of the > PSF-mentored proposals that were accepted for Google's Summer of Code: > http://wiki.python.org/moin/SummerOfCode Thanks for posting this and thanks for coordinating the PSF effort. Snagging 18 of the 200 (according to Google) fellowships for Python is great. Terry J. Reedy From tdwdotnet at gmail.com Tue Jul 5 07:07:43 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 5 Jul 2005 12:07:43 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file In-Reply-To: References: Message-ID: <9afea2ac05070504073c596e8f@mail.gmail.com> On 7/5/05, Guy Lateur wrote: > Thanks for the suggestion, Tim. Unfortunately, I get a 'connection refused' > error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error: > (10061, 'Connection refused')". I've tried both the external IP adress and > the internal one (10.0.0.2). I'm sure there's a way to get over this, isn't > there? I just tried this and it failed with IP addresses but not hostnames/machine names, try it again with the server name. :) > One more question: can I avoid having (plain text) passwords in my code? I > guess I could make a special account for this with a password known by > everybody. Depends how secure you need it to be. For my simple stuff I just do something like this In idle/pythonwin/interactive >>> p = 'password_string' >>> p = p.encode("utf16") >>> p '\xff\xfep\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00_\x00s\x00t\x00r\x00i\x00n\x00g\x00' Then in the script user = mylogin pw = '\xff\xfep\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00_\x00s\x00t\x00r\x00i\x00n\x00g\x00' M = imaplib.IMAP4(server) M.login(mylogin,pw.decode("utf16") ('OK', ['LOGIN completed.']) HTH :) From googlinggoogler at hotmail.com Thu Jul 28 04:29:31 2005 From: googlinggoogler at hotmail.com (googlinggoogler at hotmail.com) Date: 28 Jul 2005 01:29:31 -0700 Subject: searching string url In-Reply-To: <86u0iflhv5.fsf@bhuda.mired.org> References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> <1122500867.516196.146990@g14g2000cwa.googlegroups.com> <86u0iflhv5.fsf@bhuda.mired.org> Message-ID: <1122539371.202912.41650@o13g2000cwo.googlegroups.com> Cheers for all your replies, Peter Hansen: Couldnt agree more with you about not effectivly spamming companies with my resume, thats why im crawling the local newspapers website to - to find scrapes of information about companies :-) I Wasnt planning to automate everything, more the boring address and names really - I hate typing that stuff up. I was planning orginally just to compile a list of companies that appear suitable and then go through them by hand. Cheers Dave From gtg216r at mail.gatech.edu Fri Jul 22 23:42:52 2005 From: gtg216r at mail.gatech.edu (Kane Bonnette) Date: Fri, 22 Jul 2005 23:42:52 -0400 Subject: Clearing a Text Widget In-Reply-To: References: Message-ID: Kane Bonnette wrote: > Does anyone know how the clear the text from a Tkinter Text Widget? The > delete(0, END) trick that works for Entry widgets doesn't work for Text > > I get "0 is an invalid index" when i try to do so > > Thanks in advance In case anyone's wondering, you must use 0.0 instead of 0 on a Text Widget From rkern at ucsd.edu Fri Jul 1 01:11:06 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 22:11:06 -0700 Subject: Splitting string into dictionary In-Reply-To: <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> References: <59e9fd3a0506302121197c545a@mail.gmail.com> <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> Message-ID: David Pratt wrote: > I have string text with language text records that looks like this: > > 'en' | 'the brown cow' | 'fr' | 'la vache brun' > > Two or more language records can exist in each string (example above > shows 2 - but could contain more) > The second vertical line character in the example above is the record > break in the pattern (between 'cow' and 'fr') > > What is the shortest route to getting this into a dictionary like: > > {'en':'the brown cow','fr':'la vache brun'} > > The language code is always 2 lower case letters. > > Many thanks. Ignore the last message. translations = [x.strip(" '") for x in line.split('|')] d = dict(zip(translations[::2], translations[1::2])) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From erniedude at gmail.com Tue Jul 26 15:44:13 2005 From: erniedude at gmail.com (Ernesto) Date: 26 Jul 2005 12:44:13 -0700 Subject: GUI - Windows: Where to get started Message-ID: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Hi all, Would anyone know a good place to start for learning how to build simple GUI's in Windows XP? I just want users to be able to select a few parameters from a pull-down menu, then be able to run some batch files using the parameters from the pull down menus. I would also need a "Browse" menu, so users could point to a place on the local disc (ie C:\PointSystemHere). Can anyone give a noob some tips? THANKS!!! From jwaixs at gmail.com Sun Jul 3 09:08:52 2005 From: jwaixs at gmail.com (jwaixs) Date: 3 Jul 2005 06:08:52 -0700 Subject: website catcher In-Reply-To: <3iq5e7Fmn8drU1@uni-berlin.de> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> <1120393925.181952.192040@g49g2000cwa.googlegroups.com> <3iq5e7Fmn8drU1@uni-berlin.de> Message-ID: <1120396132.606888.322880@g14g2000cwa.googlegroups.com> If I should put the parsedwebsites in, for example, a tablehash it will be at least 5 times faster than just putting it in a file that needs to be stored on a slow harddrive. Memory is a lot faster than harddisk space. And if there would be a lot of people asking for a page all of them have to open that file. if that are 10 requests in 5 minutes there's no real worry. If they are more that 10 request per second you really have a big problem and the framework would probably crash or will run uber slow. That's why I want to open the file only one time and keep it saved in the memory of the server where it don't need to be opened each time some is asking for it. Noud Aldenhoven From sjmachin at lexicon.net Sat Jul 2 19:50:32 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 03 Jul 2005 09:50:32 +1000 Subject: What's wrong with this code? In-Reply-To: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> References: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> Message-ID: <42C72848.9020609@lexicon.net> Nathan Pinno wrote: > Hi all, > > What's wrong with the following code? It says there is name error, that > random is not defined. How do I fix it? Others have already answered that question. This posting is a pre-emptive strike to head off the next half-a-dozen questions. > > # Plays the guessing game higher or lower. > # Originally written by Josh Cogliati, improved first by Quique, then by > Nathan Pinno. Some of us are interested in the process by which great pieces of code arise, how they are meticulously honed and polished, which craftpersons contributed what ... is it possible for you to publish the earlier versions? > print "Higher or Lower" > print > number = random.choice(range(100)) "number" will refer to one of: 0, 1, ......, 98, 99 > guess = 0 so you'll get a strange result by using zero here; try -1 instead > while guess != number: > guess = input("Guess a number: ") "guess" will refer to a string e.g. "42" which will *not* compare equal to the integer 42. Also you should use raw_input, not input. so do this: guess = int(raw_input("Guess a number: ")) > if guess > number: > print "Too high" > guess = input("Guess a number: ") This will cause your program to ask TWICE per trip around the loop. Lose it. > elif guess < number: > print "Too low" > guess = input("Guess a number: ") ... and again. > print "Just right" > General advice: 1. Look on the Python web site (http://www.python.org) for an introduction to Python for non-programmers. 2. Join the Python tutor list. 3. In this news group, read a little more than the threads that you have started; this guessing game was discussed in a thread started by somebody calling themselves ChuckDubya on 29 June!! Homework?? HTH, John From p at ulmcnett.com Sun Jul 31 18:57:29 2005 From: p at ulmcnett.com (Paul McNett) Date: Sun, 31 Jul 2005 15:57:29 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <87r7dfymy1.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> <7xvf2rync2.fsf@ruckus.brouhaha.com> <87r7dfymy1.fsf@wilson.rwth-aachen.de> Message-ID: <42ED5759.6030503@ulmcnett.com> Torsten Bronger wrote: > Hall?chen! > > Paul Rubin writes: > > >>Ed Leafe writes: >> >> >>>But since UIs are incredibly complex beasts, we've chosen to >>>tackle one at a time, and after looking at them all and >>>considering different issues, we chose wxPython as the best >>>toolkit for creating platform-independent apps. >> >>How on earth did you decide that, since tkinter actually runs out >>of the box when you install Python on most platforms, and wxPython >>doesn't? > > > I can't really understand your hostility towards non-Tkinter > toolkits. In the case of wxPython, it's part of SUSE, which is > probably also true for Fedora and Mandriva. Installing is as easy > as selecting a checkbox. This covers a very great deal of Linux > users. On Windows you have to call an exe file. I'm at a loss too: on Debian, it is a simple: sudo apt-get install wxpython On Redhat, you download the RPM and: rpm -i On Windows and Mac, you download the package and run through the wizard. Admittedly, installing from source is more difficult than any other project I've found, but still doable. Tkinter was a contender, but unfortunately while it is easy to use, it doesn't provide a modern GUI look and feel. That was a showstopper, at least for me. -- Paul McNett http://paulmcnett.com From steve at REMOVETHIScyber.com.au Sat Jul 23 23:16:43 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 13:16:43 +1000 Subject: Lists & "pointers" References: <42e25ac2$1@griseus.its.uu.se> Message-ID: On Sat, 23 Jul 2005 17:03:08 +0200, Jan Danielsson wrote: > The problem is that I have initialized the list like this: > > self.drawAttr = { blah, blah, blah.. } > self.storedAttr = [ ] > for i in range(0, 10): > self.storedAttr.append(self.drawAttr) > > I know what the problem is; they are all referencing the *same* > dictionary object. So, my question is: How do I initialize a list of > dictionary objects, where each list entry is its own object (which is a > copy from the self.drawAttr object). self.drawAttr = { blah, blah, blah.. } self.storedAttr = [ ] for i in range(0, 10): self.storedAttr.append(self.drawAttr.copy()) You only need to worry about the difference between copy and deepcopy if the objects inside the dict are complex objects like dicts and lists. You also said that: "I want to be able to store attributes in a list so they'll be easily accessed using the function keys." I don't think this is good usage. What happens when you change the attributes in one place but forget to change it in the other? A better solution would be to set up either a list or a mapping from function key to attribute, rather than to a COPY of the attribute. Why change things in two places rather than one? Something like this: # set up attributes before hand self.attr['Pen.Color'] = 'blue' self.attr['Pen.Thickness'] = 1 self.attr['Pen.State'] = 'down' # etc # now point the function keys to attributes self.functionkeys = {'F1' = 'Pen.Color', 'F2' = 'Pen.Thickness', 'F3' = 'Pen.State', ... } Then, when you want to access the current value of some attribute, instead of looking up a list: # bad way def get_attribute(fkey): if fkey = 'F1': return self.storedAttr[0] elif fkey = 'F2': return self.storedAttr[1] ... elif fkey = 'F12': return self.storedAttr[11] you would do something like this: # good way def get_attribute(fkey): return self.attr[self.functionkeys[fkey]] > Also, how do I store/restore entries to the list? That question is awfully open-ended. Can you be more specific? > I have found the "copy" module, and it's copy method. I assume this > would work: > > for i in range(0, 10): > self.storedAttr.append(copy.copy(self.drawAttr)) > > However, the concept of "deep copy" confuses me. Do I want it, or > don't I want it? I repeat: the attributes object is a simple dictionary. That depends on what is inside your simple dictionary. For immutable objects like ints, floats and strings, copy is sufficient: >>> D1 = {1: 'hello', 2: 'there'} >>> D1 {1: 'hello', 2: 'there'} >>> D2 = D1.copy() >>> D1[1] = 'go' >>> D1 {1: 'go', 2: 'there'} >>> D2 {1: 'hello', 2: 'there'} See what happens when the values are mutable objects: >>> DM1 = {1: [0,1], 2: [4, 5]} >>> DM2 = DM1.copy() >>> DM1[3] = [0,2] >>> DM1 {1: [0, 1], 2: [4, 5], 3: [0, 2]} >>> DM2 {1: [0, 1], 2: [4, 5]} So far so good. But now look: >>> DM1[1].append(999) >>> DM1 {1: [0, 1, 999], 2: [4, 5], 3: [0, 2]} >>> DM2 {1: [0, 1, 999], 2: [4, 5]} The difference is that although copy makes a copy of the top level of the dict, it DOESN'T make copies of the individual objects within the dict. This doesn't matter is the objects are immutable, but if they are lists or other dicts, you can get surprises like the above. -- Steven. From deets at web.de Thu Jul 28 13:44:34 2005 From: deets at web.de (Diez B.Roggisch) Date: Thu, 28 Jul 2005 17:44:34 +0000 (UTC) Subject: Regex for nested =?utf-8?b?e30=?= References: Message-ID: > constructs like a**nn**n, with a={ and b=} in your case. This should have been a**nb**n - an example would be aaabbb. Diez From steven.bethard at gmail.com Mon Jul 4 17:56:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 04 Jul 2005 15:56:49 -0600 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <3uqdndaex_FJAVTfRVn-pA@speakeasy.net> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <3uqdndaex_FJAVTfRVn-pA@speakeasy.net> Message-ID: Erik Max Francis wrote: > Steven Bethard wrote: > >> And it's almost two times slower: > > That's because you're not using operator.add. Huh? Please re-read my post. That's exactly what I used. STeVe From sdurkin at psdschools.org Sun Jul 10 13:15:56 2005 From: sdurkin at psdschools.org (Scott Durkin) Date: Sun, 10 Jul 2005 11:15:56 -0600 (MDT) Subject: An absolute Newbie question In-Reply-To: References: Message-ID: <9097.67.172.146.226.1121015756.squirrel@webmail.psdschools.org> wpog, In IDLE, go to the File menu and select New Window. You can write your program there. Just save the file with the extension .py, such as hello.py Once the program is written, you can save the changes and press F5 to run the script. If you haven't checked out the links below, you might want to refer to them: http://www.ibiblio.org/obp/thinkCSpy http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html Scott Durkin -------------------------------------------------------------------- S c o t t J. D u r k i n -------------------------------------------------------------------- Computer Science |||| Preston Junior High sdurkin at psdschools.org |||| http://staffweb.psdschools.org/sdurkin ____________________________________________________________________ ___ _ ___ _ ___ _ ___ _ ___ _ [(_)] |=| [(_)] |=| [(_)] |=| [(_)] |=| [(_)] |=| '-` |_| '-` |_| '-` |_| '-` |_| '-` |_| /mmm/ / /mmm/ / /mmm/ / /mmm/ / /mmm/ / |____________|____________|____________|____________| | | | ___ \_ ___ \_ ___ \_ Computer Room [(_)] |=| [(_)] |=| [(_)] |=| Lab N205 '-` |_| '-` |_| '-` |_| /mmm/ /mmm/ /mmm/ ____________________________________________________________________ 970.419.7358 |||| 2005-2006 From enas_khalil at yahoo.com Sat Jul 9 16:57:59 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Sat, 9 Jul 2005 13:57:59 -0700 (PDT) Subject: ImportError: No module named numarray In-Reply-To: Message-ID: <20050709205759.85835.qmail@web50307.mail.yahoo.com> dear all could you tell me how can i fix this error appears when i try to import modules from nltk as follows from nltk.probability import ConditionalFreqDist Traceback (most recent call last): File "", line 1, in -toplevel- from nltk.probability import ConditionalFreqDist File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, in -toplevel- import types, math, numarray ImportError: No module named numarray thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy at emperorlinux.com Wed Jul 13 12:56:22 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Wed, 13 Jul 2005 12:56:22 -0400 Subject: Help with mass remove in text file Message-ID: <1121273782.4572.31.camel@localhost.localdomain> On Wed, 2005-07-13 at 09:00 -0700, rorley at gmail.com wrote: > I'm trying to open a text file, remove all instances of the words > "f=x;" and "i=x;" where x can be any number 0-14. Also, I want to > remove all { " or ) or ( or ' } each time one of those characters > occurs respectively. This is what I've been able to piece together... Does this do what you're wanting? ----------------------------------------------- finds = ("{", "}", "(", ")") lines = file("foo.txt", "r").readlines() for line in lines: for find in finds: if find in line: line.replace(find, "") print lines ----------------------------------------------- > > import os, string > x = ("f=;") > y = ("i=;) > inputFile = open('abcd.txt','r') > data = inputFile.read() > inputFile.close() > search = string.find(data, x) > if search >=1: > data = data.replace(x) > data = data.replace(y) > outputFile = open('abcd.txt','w') > outputFile.write(data) > outputFile.close() > > > This doesn't work, even to just remove "f=;". Any help would be great. > > Thanks, > Reece > From fake at not.real Sat Jul 9 05:30:47 2005 From: fake at not.real (vch) Date: Sat, 09 Jul 2005 13:30:47 +0400 Subject: file.readlines() question In-Reply-To: References: Message-ID: Erik Max Francis wrote: > ... modern versions of > Python allow iteration over a file, which will read it line by line: > > for line in aFile: > ... > Thanks! Just what I need. From steve at REMOVETHIScyber.com.au Wed Jul 27 08:00:47 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 27 Jul 2005 22:00:47 +1000 Subject: how to write a line in a text file References: <42E5B0F0.6020206@REMOVEMEcyber.com.au> <42E5ED91.10402@REMOVEMEcyber.com.au> Message-ID: On Wed, 27 Jul 2005 04:26:31 +0000, Andrew Dalke wrote: > This isn't 1970. Why does your app code work directly with > files? Use a in-process database library (ZODB, SQLLite, > BerkeleyDB, etc.) to maintain your system state and let the > library handle transactions for you. And when users are happy to install a relational database system in order for their editor to save their letter to grandma, I'm sure your scheme will work well for them. Until then, I'll continue storing my user's data in files. You may, of course, choose to write buggy code that can lead to data loss, but I prefer to take a modicum of care not to destroy their data. -- Steven. From claird at lairds.us Sun Jul 17 10:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 17 Jul 2005 14:08:02 GMT Subject: ssh popen stalling on password redirect output? References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> <1121461524.880603.214930@f14g2000cwb.googlegroups.com> Message-ID: In article , Cantankerous Old Git wrote: >draghuram at gmail.com wrote: >> In general, it is good idea to use expect kind of tool to deal with >> interactive programs like ssh. You may try using pexpect >> (http://pexpect.sourceforge.net). >> > >I tried tha once (on Solaris) and found that ssh could tell that >pexpect wasn't a real tty and refused to connect. In the end, I >had pexpect do a telnet 127.0.0.1, log in, then so ssh to the >real destination. Pain in the ass but it worked. > >The Cog 1. Pexpect is designed to do better than this. Please report specific deficiencies in its operation. 2. (The original) Expect has had years of working out pty vagaries. In a pinch, I'd write in Expect, and, if necessary, control the Expect process from Python. From michele.simionato at gmail.com Wed Jul 6 05:27:20 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Jul 2005 02:27:20 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120636418.166800.42290@o13g2000cwo.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> <1120636418.166800.42290@o13g2000cwo.googlegroups.com> Message-ID: <1120642040.109796.212450@o13g2000cwo.googlegroups.com> Fuzzyman: > So Lisp is for really good programmers, and Python is for > mediocre programmers ? Python is *also* for mediocre programmers. I see this as a strength, not as a weakness. Michele Simionato From gsakkis at rutgers.edu Tue Jul 12 19:53:36 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jul 2005 16:53:36 -0700 Subject: How to match literal backslashes read from a text file using regular expressions? References: <1121207378.715533.48090@g49g2000cwa.googlegroups.com> Message-ID: <1121212416.012411.42000@z14g2000cwz.googlegroups.com> This should give you an idea of how to go about it (needs python 2.3 or newer): import re slashPattern = re.compile(r'\\(.*?)\\') for i,line in enumerate(file("parseinput")): print "line", i+1, match = slashPattern.search(line) if match: print "matched:", match.group(1) else: print "did not match" #===== output ======================= line 1 matched: 'di_--v*-.ga_-t line 2 matched: 'pas-*m #==================================== George From tzot at sil-tec.gr Fri Jul 1 16:40:44 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 01 Jul 2005 23:40:44 +0300 Subject: No subject References: Message-ID: On Fri, 01 Jul 2005 10:54:03 +0200, rumours say that "Adriaan Renting" might have written: Some thoughts interspersed: >I'm not a very experienced Python programmer yet, so I might be >mistaken, but there are a few things that would make me prefer C++ over >Python for large (over 500.000 LOC) projects. >- namespaces Python: modules? classes? >- templates Python: list.extend(["a", 5, 3.14, 1+3j]) >- strong type checking Python: print "1"+1 >- data hiding C++: #define private public >- more available libraries and more advanced developement tools. More advanced development tools, yes. More available libraries? Perhaps. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From bill.mill at gmail.com Fri Jul 15 08:25:01 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 15 Jul 2005 08:25:01 -0400 Subject: Python Programming Contest In-Reply-To: <42D7A188.2010306@sweetapp.com> References: <42D780EF.6020809@sweetapp.com> <17111.39597.277505.234455@montanaro.dyndns.org> <42D7A188.2010306@sweetapp.com> Message-ID: <797fe3d40507150525659d5ec6@mail.gmail.com> On 7/15/05, Brian Quinlan wrote: > skip at pobox.com wrote: > > Brian> I've decided that it would be be fun to host a weekly Python > > Brian> programming contest. The focus will be on algorithms that require > > Brian> a bit of thought to design but not much code to implement. > > > > For some of us that's what we do day-in, day-out at work. It's just not > > called a contest. To make it more challenging, we sometimes leave out the > > "bit of thought" part. ;-) > > Hmmm...I find that I am rarely faced with challenging algorithmic > problems in my day-to-day work. I continuously face difficult design > decisions but that is a difficult sort of beast all together. > > This contest is for people who like thinking about algorithms. > > Cheers, > Brian > -- > http://mail.python.org/mailman/listinfo/python-list > Questions: Will that random test generator (included in the download) be used to perform the actual testing? How many tests will be run on each program? What is the penalty for a wrong answer? Peace Bill Mill PS - check out http://www.sleepinginairports.net/ before you say you can't sleep in the airport :) From pydecker at gmail.com Sun Jul 31 11:51:35 2005 From: pydecker at gmail.com (Peter Decker) Date: Sun, 31 Jul 2005 11:51:35 -0400 Subject: getting an empty tuple In-Reply-To: <1122824426.310199.136660@o13g2000cwo.googlegroups.com> References: <1122824426.310199.136660@o13g2000cwo.googlegroups.com> Message-ID: On 31 Jul 2005 08:40:26 -0700, nephish at xit.net wrote: > how do i encorporate that into an equation ? > i have tried all kinds of stuff > > if x == 0L > if x(0) == None > if x == None > > anyway, what shoud i do to test if the result is empty? Just like any other test: if not x: -- # p.d. From renato.ramonda at gmail.com Wed Jul 6 14:28:25 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Wed, 06 Jul 2005 20:28:25 +0200 Subject: Good starterbook for learning Python? In-Reply-To: <1l2969k9tbx01.opflwh7p50nk.dlg@40tude.net> References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> <1120654935.486354.75550@g47g2000cwa.googlegroups.com> <1l2969k9tbx01.opflwh7p50nk.dlg@40tude.net> Message-ID: Lennart ha scritto: > Programming Python will I sell as a book that i read secondly, and use as a > reference. I'd like to suggest also "Thinking like a CS in python": a schoolbook used in real classes to teach the basis of programming. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From secun at yahoo.com Mon Jul 11 22:08:48 2005 From: secun at yahoo.com (ChrisH) Date: Tue, 12 Jul 2005 02:08:48 GMT Subject: Help with report References: <11d5scbb63afhee@corp.supernews.com> Message-ID: HTMLgen looks like it might fit the bill. In article , secun at yahoo.com says... > I should have been more specific. The report needs to be presentable to > my users and needs to have rich text type properties (multiple colors, > tables, etc) Therefore, I would like to use html if possible. > > I didn't know if there was already a report writing type of utility > already built using python, so I won't have to reinvent the wheel. > > Oh. The one other thing I forgot to mention is that the data needs to be > already updated every 10 minutes or so automatically. > > > In article <11d5scbb63afhee at corp.supernews.com>, grante at visi.com says... > > On 2005-07-11, ChrisH wrote: > > > I have some data in the following format: > > > > > > Fred Flintstone,445553454,47634565 > > > Wilma Flintstone,74857346,27576847 > > > Barney Rubble,73487346,27576435 > > > > > > I need to convert this data into a report with the user's name and > > > difference between the 2 numbers. > > > > > > Can someone recommend a good way to do this? > > > > > > BTW, it would be best if I can have it up and running by tomorrow. > > > > You really oughtn't put off homework assignments until the last > > minute. Especially if you don't know how to do them. > > > > > Also, html would be the preferred format, but not required. > > > > > > Any help would be greatly appreciated!! > > > > Hints: > > > > The string object's "split" method: http://docs.python.org/lib/string-methods.html > > > > for line in file('inputfile.txt','r') > > > > the built-in int() > > > > the string formatting operator "%": http://docs.python.org/lib/typesseq-strings.html > > > > > From __peter__ at web.de Mon Jul 4 17:56:53 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jul 2005 23:56:53 +0200 Subject: "long int..." exception reported with strange traceback location References: Message-ID: Terry Reedy wrote: >>>> os.utime("foo_test_file", (0, float(sys.maxint+1))) > Traceback (most recent call last): > File?"",?line?1,?in?? > TypeError: utime() arg 2 must be a tuple (atime, mtime) > > which is quite sane.??So?maybe?bug?was?introduced?in?2.3?which?you?were > running. But arg 2 *is* a tuple. So a least the error message is wrong, too. Peter From bronger at physik.rwth-aachen.de Sun Jul 31 05:20:45 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 11:20:45 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> <7xhdebv1t0.fsf@ruckus.brouhaha.com> Message-ID: <87vf2rpc0i.fsf@wilson.rwth-aachen.de> Hall?chen! Paul Rubin writes: > Torsten Bronger writes: > >> Does py2exe work for all GUI libraries? > > No, it's Windows-only. However, OS'es and GUI libraries are different axes in the space of possibilities. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From benji at benjiyork.com Tue Jul 12 08:03:57 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 12 Jul 2005 08:03:57 -0400 Subject: Managment of Python Libraries In-Reply-To: References: Message-ID: <42D3B1AD.7090406@benjiyork.com> Joseph Chase wrote: > In the past, I have noticed that I have spent a lot of time managing my C++ > libraries. The main thing you need are good tests. -- Benji York From benji at benjiyork.com Mon Jul 25 09:13:58 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 25 Jul 2005 09:13:58 -0400 Subject: Counting processors In-Reply-To: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> Message-ID: <42E4E596.3090704@benjiyork.com> Pauldoo wrote: > Is a way in python to obtain the total number of processors present in > the system? I don't know of a platform independent way. If you specify one or more platforms, I'm sure someone will be able to help. -- Benji York From sklass at pointcircle.com Thu Jul 14 10:05:18 2005 From: sklass at pointcircle.com (rh0dium) Date: 14 Jul 2005 07:05:18 -0700 Subject: Help - Classes and attributes In-Reply-To: <42d64891$0$15020$626a14ce@news.free.fr> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> <42d64891$0$15020$626a14ce@news.free.fr> Message-ID: <1121349918.343589.21370@g47g2000cwa.googlegroups.com> Hi I really like your approach but when do you actually get connected?? You never call the method connect? > > class NSCLdap(object): > def __init__(self, > server="sc-ldap.nsc.com", > baseDN="o=nsc.com", > who=None, > cred=None): > self.server = server > self.baseDN = baseDN > if who is None: > self.who = "" > else: > self.who = who > if cred is None: > self.cred = "" > else: > self.cred = cred > self.connection = None > > def connect(self): > try: > print "LDAP Version", ldap.__version__ > self.connection = ldap.open(server) > self.connection.simple_bind_s(self.who, self.cred) > self.connection.protocol_version=ldap.VERSION3 > > except ldap.LDAPError, error_message: > # I would not catch this. It's the caller's > # responsabilitie to handle this IMHO > print >> sys.stderr, "Couldn't Connect to %s %s " % > (server,error_message) > > def search(self, > baseDN=None, > searchScope=ldap.SCOPE_SUBTREE, > retrieveAttrs=None, > searchAttrs="cn=*klass*" ): > > cnx = self.connection > if baseDN is None: > baseDN = self.baseDN > > try: > ldap_result_id = cnx.search_s(baseDN, > searchScope, > searchAttrs, > retrieveAttrs) > result_set = [] > while True: > result_type, result_data =cnx.result(ldap_result_id, 0) > #if (result_data == []): > if not result_data: > break > ## here you don't have to append to a list > ## you could do whatever you want with the > ## individual entry > ## The appending to list is just for > ## illustration. > if result_type == ldap.RES_SEARCH_ENTRY: > result_set.append(result_data) > print result_set > except ldap.LDAPError, error_message: > print >> sys.stderr, "Errors on Search %s " % error_message > > if __name__ == '__main__': > truc = NSCLdap() > truc.search() From CantankerousOldGit at gmail.com Sat Jul 16 09:08:27 2005 From: CantankerousOldGit at gmail.com (Cantankerous Old Git) Date: Sat, 16 Jul 2005 14:08:27 +0100 Subject: ssh popen stalling on password redirect output? In-Reply-To: <1121461524.880603.214930@f14g2000cwb.googlegroups.com> References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> <1121461524.880603.214930@f14g2000cwb.googlegroups.com> Message-ID: draghuram at gmail.com wrote: > In general, it is good idea to use expect kind of tool to deal with > interactive programs like ssh. You may try using pexpect > (http://pexpect.sourceforge.net). > I tried tha once (on Solaris) and found that ssh could tell that pexpect wasn't a real tty and refused to connect. In the end, I had pexpect do a telnet 127.0.0.1, log in, then so ssh to the real destination. Pain in the ass but it worked. The Cog From rkern at ucsd.edu Sun Jul 24 23:48:34 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 20:48:34 -0700 Subject: Fire event when variable is Set/Get In-Reply-To: References: Message-ID: Varghj?rta wrote: > Hey! > > I'm a hobby programmer since many years now and I've done most of my > latest 'real application' coding in C#. I've played with python of and > on yet not catching on until a few months ago when I got myself hocked > on it for real and now I love C# _and_ Python. > > But there is something that keeps bugging me, and that keeps me from > embracing Python even more as a serious alternative to C#(for me). In > C# I make heavy use of Get & Set, mainly to fire an event that some > property has changed so that one can act on that _if one would need > to. I've grown very used to doing it and it feels like the best way to > make very OO and reusuable and easy to use Classes. > > Is there _anything_ that I could do in Python which would allow me to > known when a variable has been set or when it's being fetched to allow > me to fire an event there?. There's Enthought's Traits. http://code.enthought.com/traits/traits.htm I don't think it handles the Get part, though. You could probably come up with something using __getattribute__ for that part. http://docs.python.org/ref/new-style-attribute-access.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From michaels at rd.bbc.co.uk Fri Jul 15 06:11:02 2005 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Fri, 15 Jul 2005 11:11:02 +0100 Subject: Kamaelia Talk at Open Tech 2005, anyone for sprinting? Message-ID: Hi, Apologies first to those outside the UK... Open Tech 2005* is a follow on from previous years' NotCon events which are community driven low cost events by geeks & developers for geeks & developers. (Much like Pycon & Europython but much more general in nature) Website: http://www.ukuug.org/events/opentech2005/ Where/When: Hammersmith, London, UK, July 23rd The reason I'm posting about it is because I'm going to be talking about Kamaelia there. Unlike Python UK & Europython this is going to be a 15 minute talk, so I'll be focussing on what we've been doing with Kamaelia, what you can do with Kamaelia, and so on rather than going through internals. In addition since my talk on Kamaelia is before lunch, I'd really like to help people get started using Kamaelia (this really the point of giving talks!), so I'm going to be running a small ad-hoc/mini sprint that afternoon. There's a variety of possible sprintable things ranging from how to put together simple Kamaelia systems through to using Kamaelia for simplifying networking on Nokia mobiles through to using Kamaelia for writing games (since we have some nice Pygame based components now). I'll probably be sprinting on converting a proof of concept P2P swarming algorithm into a protocol for creating TCP server swarms. This is for joining together multicast islands to make it so that internet broadcasting, rather than narrowcasting, can become a reality for the BBC - which has clear benefits for everyone! (Even though the internet is not TV :) Kamaelia is designed to be able to picked up relatively quickly/easily, but having a working knowledge of python is probably a necessity. If you're interested, please let me know! (Either before, or at Open Tech :) Best Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From nestleNOSPAM12 at comcast.net Fri Jul 29 08:19:45 2005 From: nestleNOSPAM12 at comcast.net (Bryan) Date: Fri, 29 Jul 2005 06:19:45 -0600 Subject: os._exit vs. sys.exit References: <7a2dnSer5eC2BnTfRVn-sQ@comcast.com> Message-ID: <48GdnfrcP_Z2g3ffRVn-hg@comcast.com> "Peter Hansen" wrote in message news:u-SdnRAzQ9KHhnffRVn-gg at powergate.ca... > Andrew Dalke wrote: >> sys.exit() is identical to "raise SystemExit()". It raises a Python >> exception which may be caught at a higher level in the program stack. > > And which *is* caught at the highest levels of threading.Thread objects > (which Timer is based on). Exceptions raised (and caught or not) in a > Thread do not have any effect on the main thread, and thus don't affect > the interpreter as a whole. > > -Peter Thanks for the clarifications. One more question, can I catch this exception in my main thread and then do another sys.exit() to kill the whole process? Apparently sys.exit() allows the program to clean up resources and exit gracefully, while os._exit() is rather abrupt. Bryan From nephish at xit.net Thu Jul 28 09:39:32 2005 From: nephish at xit.net (nephish at xit.net) Date: 28 Jul 2005 06:39:32 -0700 Subject: easy float question just eludes me Message-ID: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> Hullo all ! i have a real easy one here that isn't in my book. i have a int number that i want to divide by 100 and display to two decimal places. like this float(int(Var)/100) but i need it to display the .00 even if it does not have a .00 value like this if Var is 50, i need to display .50 instead of just .5 i know there is an easy way to do this. thanks From mwm at mired.org Tue Jul 12 22:08:27 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 12 Jul 2005 22:08:27 -0400 Subject: new division in Pythonwin References: Message-ID: <86fyujlap0.fsf@bhuda.mired.org> "Jive Dadson" writes: > I like to use Pythonwin as my desktop calculator. It's bothersome > to have to type in "from __future__ import division" into the > interactive window every time I open it. I've tried various ways to > attempt to get it to import new division at startup, but no luck. I > can get it to execute a file, but apparently it does so in an > environment that gets discarded, rather than in the environment of > the interactive window. So the "from __future__" statement has no > effect. > > Any suggestions? I'm not familiar with Pythonwin, but would expect it to honor the PYTHONSTARTUP environment variable. That's how I get various things loaded into my interactive pythons. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From s_t_a_n_i at gmx.net Fri Jul 15 07:21:03 2005 From: s_t_a_n_i at gmx.net (Stani) Date: 15 Jul 2005 04:21:03 -0700 Subject: ANN: SPE IDE needs packagers & doc writers Message-ID: <1121426463.203024.163650@o13g2000cwo.googlegroups.com> **SPE needs packagers & doc writers** SPE is moving websites. The new websites will be: - homepage: http://www.stani.be/python/spe - downloads & SVN: http://developer.berlios.de/projects/python Please help to make this transition smooth: update your bookmarks and report this url change to websites, which are not updated yet. A new release of SPE will be available there soon. Some parts of SPE were rewritten to make it (more) stable for wxPython 2.6 (probably also for 2.5). SPE is looking for following volunteers (especially for linux and mac os x): - :Packagers: SPE is urgently looking for packagers for all Linux version and OS X. Your support will be appreciated by a lot of users. Also you will be mentioned in the SPE website&documentation (unless you don't want of course). - :Beta-testers: If you would like to be a beta-tester please send an email to me (s_t_a_n_i$yahoo.com), describing your python & OS configuration. - :Developpers: SPE will use SVN for collaborative development. If you are experienced with wxPython, please join. Also somebody to help to setup the SVN would be nice. - :Documentation: The documentation of SPE could be far more complete with contributions from users. It is now written in OpenOffice 1.9+ to generate pdf and html. SPE documentation is looking for contributors, translators and coordinators. For more info: - http://www.stani.be/python/spe/blog/sm_documentation - http://www.stani.be/python/spe/manual/pdf - http://www.stani.be/python/spe/manual/odt (open office) - :Donations: ...are of course always welcome. Everyone is kindly invited to subscribe to the mailing list, where these issues can be developped collectively. *About SPE* *Spe is a python IDE with auto indentation & completion, call tips, syntax coloring & highlighting, uml viewer, class explorer, source index, auto todo list, sticky notes, pycrust shell, file browsers, drag&drop, context help, Blender support, ... Spe ships with wxGlade (gui designer), PyChecker (source code doctor) and Kiki (regex console).* From miki.tebeka at zoran.com Mon Jul 4 09:10:01 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 4 Jul 2005 16:10:01 +0300 Subject: Debugging embedded python In-Reply-To: <1120465254.327966.196570@g14g2000cwa.googlegroups.com> References: <1120465254.327966.196570@g14g2000cwa.googlegroups.com> Message-ID: <20050704131001.GE3876@zoran.com> Hello Fotis, > I linked it to python24.lib (under eclipse cdt/win2k) and it compiles, > links and runs fine. > The problem is when I try to debug it (gdb). I cannot go single > stepping into the code, more than one threads seem to be running, I get > messages like "No source file named d:/workspace/pyTest/main.cpp", and > if I set a breakpoint to the function Fotis_root then I cannot see any > variables. In fact I cannot see no stack, no registers nothing, within > this function! I *think* that you need to tell GDB where are the source directories (try "help dir") HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From pydecker at gmail.com Sat Jul 30 12:28:15 2005 From: pydecker at gmail.com (Peter Decker) Date: Sat, 30 Jul 2005 12:28:15 -0400 Subject: Wheel-reinvention with Python In-Reply-To: <87slxwqp32.fsf@wilson.rwth-aachen.de> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <871x5gs6oy.fsf@wilson.rwth-aachen.de> <87slxwqp32.fsf@wilson.rwth-aachen.de> Message-ID: On 7/30/05, Torsten Bronger wrote: > > Well, wxPython itself is largely the work of a single person, but > > I doubt that many consider that a reason to avoid it. > > But the developer and contributor base is much larger, so the > project has reached the critical mass. So until it reached that critical mass, you would have argued against supporting it or using it? That seems to be what you're doing here. Dabo is about a year and a half along; IMO, its progress in such a short time frame is a very positive thing, not at all a negative. > > As far as your comment about 'slowing down' the app, I've found > > that Dabo and pure-wxPython apps run indistinguishably. Perhaps > > there are some microseconds of extra processing, but I sure > > haven't noticed it. And I don't think that the comment about > > installing another package is fair; *anything* outside of the > > standard distribution requires that, and Dabo is no more difficult > > than copying to site-packages. > > I didn't want to say that Dabo is bad. I just wanted to point out > that its presence (and the presence of comparable projects) doesn't > ease the IMO unfortunate situation with GUI toolkits for Python. Perhaps, but I see it differently, since Dabo doesn't attempt to add a new toolkit. I greatly preferred the look of wxPython over TkInter and PyGtk, since I do a lot of cross-platform work. But while I liked the results, I didn't like coding in wxPython. Dabo is giving me the best of both worlds: a Pythonic language, and great-looking GUI apps. So I feel that it is improving the situation with GUI toolkits for Python in that it is allowing me to use the best toolkit without having to write un-Pythonic code. It would be great if the wxPython folks would adopt Dabo, and eventually integrate it so that there is but a single, Pythonic way of working with wxPython, but it seems that they have their hands full just wrapping the C++ code of wxWidgets. -- # p.d. From daniel.einstein at pnl.gov Fri Jul 8 14:09:20 2005 From: daniel.einstein at pnl.gov (Einstein, Daniel R) Date: Fri, 08 Jul 2005 11:09:20 -0700 Subject: FORTRAN like formatting Message-ID: <0DF798CBF125BF4AA1227F26431C29BD01A32ECA@pnlmse27.pnl.gov> Hi, Sorry for this, but I need to write ASCII from my Python to be read by FORTRAN and the formatting is very important. Is there any way of doing anything like: write(*,'(3(" ",1pe20.12))') (variable) In other words, I want three columns 20 spaces long, with 12 digits after the decimal and so on and so forth. What I am really looking for is some general indication of how to do such formatting in Python. Any help? Dan Daniel R Einstein, PhD Biological Monitoring and Modeling Pacific Northwest National Laboratory P.O. Box 999; MSIN P7-59 Richland, WA 99352 Tel: 509/ 376-2924 Fax: 509/376-9064 daniel.einstein at pnl.gov -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjsobol at JustThe.net Mon Jul 18 23:59:32 2005 From: sjsobol at JustThe.net (Steve Sobol) Date: Mon, 18 Jul 2005 20:59:32 -0700 Subject: Xah's edu corner: on Microsoft hatred In-Reply-To: <1121739870.261503.66830@g43g2000cwa.googlegroups.com> References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> <1121739870.261503.66830@g43g2000cwa.googlegroups.com> Message-ID: Cong Wang wrote: > M$ is evil! Not as evil as off-topic rants posted to c.l.j.programmer. -- JustThe.net - Steve Sobol / sjsobol at JustThe.net / PGP: 0xE3AE35ED Coming to you from Southern California's High Desert, where the temperatures are as high as the gas prices! / 888.480.4NET (4638) "Life's like an hourglass glued to the table" --Anna Nalick, "Breathe" From k04jg02 at kzoo.edu Thu Jul 14 01:15:10 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Wed, 13 Jul 2005 23:15:10 -0600 Subject: Efficiently Split A List of Tuples In-Reply-To: References: Message-ID: <42D5F4DE.206@kzoo.edu> Peter Hansen wrote: >(I believe this is something Guido considers an "abuse of *args", but I >just consider it an elegant use of zip() considering how the language >defines *args. YMMV] > >-Peter > > An abuse?! That's one of the most useful things to do with it. It's transpose. From simon.dahlbacka at gmail.com Fri Jul 1 07:39:43 2005 From: simon.dahlbacka at gmail.com (simon.dahlbacka at gmail.com) Date: 1 Jul 2005 04:39:43 -0700 Subject: accessing individual element in a list. In-Reply-To: <1120217689.339747.91140@g44g2000cwa.googlegroups.com> References: <1120217689.339747.91140@g44g2000cwa.googlegroups.com> Message-ID: <1120217983.347814.172900@f14g2000cwb.googlegroups.com> >>> import wmi >>> c = wmi.WMI() >>> for printdriver in c.Win32_PrinterDriver(): ... pd = printdriver.Name >>> print pd AGFA-AccuSet v52.3,3,Windows NT x86 >>> pd[1] # type(pd) == str u'G' >>> pd.split(',') # split returns a new list, and you do not save it [u'AGFA-AccuSet v52.3', u'3', u'Windows NT x86'] >>> pd[0] # pd is still a string u'A' so basically, .split is probably the best way to split it up (unless you want to fiddle with regular expressions, but that seems overkill in this case), but you need to store the new list. split does not do anything "inline" From newsgroups at jhrothjr.com Sat Jul 23 19:51:31 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 23 Jul 2005 17:51:31 -0600 Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> Message-ID: <11e5m07ef4nq339@news.supernews.com> "Reinhold Birkenfeld" wrote in message news:3kfpovFu3rt9U1 at individual.net... > > I'll look into it. What about iteration and indexing? Should it support > "for element in path" or "for char in path" or nothing? I frankly can't think of a use for iterating over the characters in the path, but I have a number of programs that check elements, iterate over them and index them (frequently backwards). I also like to know the number of elements, which seems to make sense as len(path). Again, the number of characters in the path seems to be utterly useless information - at least, I can't imagine a use for it. John Roth > > Reinhold From richardjones at optushome.com.au Fri Jul 8 20:37:02 2005 From: richardjones at optushome.com.au (richard) Date: Sat, 09 Jul 2005 10:37:02 +1000 Subject: Ann: The first PyWeek Python Game Programming Competition References: Message-ID: <42cf1c2e$0$9731$afc38c87@news.optusnet.com.au> Lee Harr wrote: >> Clip Art >> note: >> more links welcome > > How about: > http://www.openclipart.org/ Thanks! Richard (aka PyWeek organiser bunny) From newstonne at web.de Wed Jul 13 03:22:44 2005 From: newstonne at web.de (Roland Heiber) Date: Wed, 13 Jul 2005 09:22:44 +0200 Subject: Frankenstring In-Reply-To: References: Message-ID: Thomas Lotze wrote: > It's definitely no help that file-like objects are iterable; I do want > to get a character, not a complete line, at a time. Hi, if i did understand what you mean, what about using mmap? Iterating over characters in a file like this: # -*- coding: iso-8859-1 -*- import os import mmap f = open("file.txt", "r+") size = os.path.getsize("file.txt") m = mmap.mmap(f.fileno(), size) for x in m: print x m.close() f.close() From draghuram at gmail.com Fri Jul 1 12:44:49 2005 From: draghuram at gmail.com (draghuram at gmail.com) Date: 1 Jul 2005 09:44:49 -0700 Subject: pexpect question.... Message-ID: <1120236289.836018.234240@f14g2000cwb.googlegroups.com> Hi, I am using pexpect to spawn an interactive program and wait for particular string in its output. It works fine but once I get this required information, I really don't care about the child process anymore. I would effectively want to "detach" from it. Is there any way to do such thing in pexpect? I did read pexpect's doc but couldn't find any information in this regard. Currently, I am spawning a new thread that just does pexpect_spawned_child.close(wait=1). It seems to work in some cases but the child process is occassionally getting deadlocked. # strace -p 23159 Process 23159 attached - interrupt to quit write(2, "H_235J Task 4 being run as INCR"..., 72 It just sits there indefinitely. Python is 2.3.3 and the OS is SuSe 9.1. Thanks, Raghu. From peter at engcorp.com Thu Jul 14 16:18:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 16:18:52 -0400 Subject: Changing size of Win2k/XP console? In-Reply-To: <42d6bdd2$0$16170$39db0f71@news.song.fi> References: <42d6bdd2$0$16170$39db0f71@news.song.fi> Message-ID: Sheeps United wrote: > Hi, I'm quite a newbie but I've managed to google around before asking > stupid Q's here. > > I'm wrestling with little (amateurish) console program and I would like > change its size. I also know that it could be done with Windows API call. I > tried doing that myself but no good. > > Could anyone help me? Which Windows API call did you try using? Can you show us a line or two of code that you tried? Most likely then someone will be able to point out what went wrong and it will work. (Chances are that very few here know the API call required, so by not mentioning it you're severely limiting the number of answers you are likely to get.) -Peter From opengeometry at yahoo.ca Thu Jul 14 17:10:37 2005 From: opengeometry at yahoo.ca (William Park) Date: Thu, 14 Jul 2005 17:10:37 -0400 Subject: all possible combinations References: Message-ID: rbt wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: > > 4^3 = 64 > > aaaa > abaa > aaba > aaab > acaa > aaca > aaac > ... > > What is the most efficient way to do this? Since you're doing cross product (ie. 3*3*3*3), manual loop of 4 level deep would be the fastest in terms of algorithm. C vs. Python is implementation detail. In Bash shell, this is one-liner, echo {a,b,c}{a,b,c}{a,b,c}{a,b,c} or maybe two, abc=(a b c) echo {^abc}{^abc}{^abc}{^abc} -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From chaghi at sion.com Tue Jul 5 23:48:56 2005 From: chaghi at sion.com (Mariano Draghi) Date: Wed, 06 Jul 2005 00:48:56 -0300 Subject: is there an equivalent of javascript's this["myMethod"] for the currently running script? In-Reply-To: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> References: <1120620346.964264.89580@g44g2000cwa.googlegroups.com> Message-ID: markturansky at gmail.com wrote: > I'd like to dynamically find and invoke a method in a Python CGI. > > In javascript, the running script is 'this' (Python's 'self'), except > that 'self' is not defined. > > I want to do this: > > var m = this["MethodName"]; //where the method name is passed via an > http variable > m(); //this invokes a method in javascript > > How do I do the same in python? > > self["MethodName"] fails... > Don't know if this is the best solution... but you need something around the lines of: >>> def foo(): ... print "bar" ... >>> m = locals()["foo"] >>> >>> m() bar >>> i.e., you need to play a bit with locals() Hope that helps -- Mariano From uwb at uwbomb.net Fri Jul 8 12:10:47 2005 From: uwb at uwbomb.net (uwb) Date: Fri, 08 Jul 2005 16:10:47 GMT Subject: file handling in a server (.py) file using xmlrpc Message-ID: I've got a call to glob in a .py file sitting in an apache cgi-bin directory which refuses to work while the exact same code works from a python console session. I'm guessing that in order to read or write files from any sort of a script file sitting in the cgi-bin directory on a server, something has to be set to allow such activity. I'd appreciate it if anybody with as clue as to what that was could tell me about it. From hancock at anansispaceworks.com Fri Jul 22 10:40:09 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 22 Jul 2005 09:40:09 -0500 Subject: is this possible? In-Reply-To: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> References: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> Message-ID: <200507220940.09954.hancock@anansispaceworks.com> On Friday 22 July 2005 08:26 am, scrimp wrote: > Is it possible to print a PDF file using python without having acrobat > reader installed on the machine?? Sure, there are several free-licensed PDF readers. Perhaps the most obvious is Ghostscript ("gs") which can interpret PDF as well as Postscript. On a Linux system, you probably already have this installed. On other platforms, you may have to provide it. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From gsakkis at rutgers.edu Sun Jul 10 18:21:28 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jul 2005 15:21:28 -0700 Subject: decorators as generalized pre-binding hooks References: <42d02c21.231516573@news.oz.net> Message-ID: <1121034087.932596.221010@g43g2000cwa.googlegroups.com> "Terry Reedy" wrote: > "Bengt Richter" wrote in message > news:42d02c21.231516573 at news.oz.net... > > The binding of a class name is similar, and class decorators > > would seem natural, i.e., > > > > @cdeco > > class Foo: pass > > for > > class Foo: pass > > Foo = cdeco(Foo) > > This possibility was discussed on the py-dev list about a year or so ago. > The twice monthly summaries should include this topic. As I remember, the > reason for limiting to functions included: > > 1. classes have metaclasses, functions don't have metafunctions. No one > gave an example for classes not handled at least as well with a metaclass. Would something like the following count ? @abstractclass class AbstractFrame(object): @abstractclass @innerclass class AbstractPanel(object): pass For one thing, it's more readable than the respective __metaclass__ declarations. Moreover, stacking two or more decorators is syntactically straightforward, while for metaclasses you have to write boilerplate code for making a subclass of the components, e.g.: class AbstractInnerClass(AbstractClass, InnerClass): pass Fortunately metaclasses are not that commonly used to cause combinatorial explosion of such boilerplate classes. > 2. certain applications require long-function_names_like_this, for which > triple typing is substantially annoying and error-prone. I'm not sure what you mean here; where is the 'triple typing' ? And how is this an argument against class decorators ? George From jabel at plus.net Mon Jul 18 12:22:16 2005 From: jabel at plus.net (John Abel) Date: Mon, 18 Jul 2005 17:22:16 +0100 Subject: Python scripts wont run - HELP In-Reply-To: References: Message-ID: <42DBD738.7080101@plus.net> windozbloz wrote: >Bye Bye Billy Bob... > >Hello All, >I'm a fairly literate windoz amateur programmer mostly in visual basic. I >have switched to SuSE 9.2 Pro and am trying to quickly come up to speed >with Python 2.3.4. I can run three or four line scripts from the command >line but have not been able to execute a script from a file. > >I have used EMACS and JEDIT to create small test routines. I would right >click the file and set properties to executable. I would then click the >icon, the bouncy ball would do its thing then a dialog box would flash on >the screen for a fraction of a second. I could tell it had a progress bar >on it but could not catch anything else on it. Then nothing else would >happen. > >If I could execute a script the world would once again be my playground... >PLEASE HELP. > > > > > You will need to include #!/usr/bin/python At the top of your script. HTH J From john at hazen.net Tue Jul 26 15:33:28 2005 From: john at hazen.net (John Hazen) Date: Tue, 26 Jul 2005 12:33:28 -0700 Subject: subscribe In-Reply-To: <25133FB9D614D411864500508B64433A039C7100@EPWUMAIL> References: <25133FB9D614D411864500508B64433A039C7100@EPWUMAIL> Message-ID: <20050726193328.GA3175@gate2.hazen.net> * Brian Lee [2005-07-26 06:34]: > Subscribe OK. You're now subscribed to thousands of spam lists. Congratulations! ;) You can subscribe to the python-list here: http://mail.python.org/mailman/listinfo/python-list Good luck- John From apoco at cox.net Thu Jul 7 16:36:48 2005 From: apoco at cox.net (Jacob Page) Date: Thu, 07 Jul 2005 13:36:48 -0700 Subject: Python Module Exposure In-Reply-To: References: Message-ID: Robert Kern wrote: > Jacob Page wrote: > >> I have created what I think may be a useful Python module, but I'd >> like to share it with the Python community to get feedback, i.e. if >> it's Pythonic. If it's considered useful by Pythonistas, I'll see >> about hosting it on Sourceforge or something like that. Is this a >> good forum for exposing modules to the public, or is there somewhere >> more-acceptable? Does this newsgroup find attachments acceptable? > > No. Please put files somewhere on the web and post a URL. This would be > a good forum to informally announce and discuss your module. Formal > announcements once you, e.g. put it on SF should go to c.l.py.announce . Thanks for the information, Robert. Anyway, here's my informal announcement: The iset module is a pure Python module that provides the ISet class and some helper functions for creating them. Unlike Python sets, which are sets of discrete values, an ISet is a set of intervals. An ISet could, for example, stand for all values less than 0, all values from 2 up to, but not including 62, or all values not equal to zero. ISets can also pertain to non-numeric values. ISets can be used in much the same way as sets. They can be or'ed, and'ed, xor'ed, added, subtracted, and inversed. Membership testing is done the same as with a set. The documentation has some examples of how to create and use ISets. The iset module is for Python 2.4 or later. I am seeking feedback from programmers and mathematicians on how to possibly make this module more user-friendly, better-named, better-documented, better-tested, and more Pythonic. Then, if this module is considered acceptable by the community, I'll create a more permanent home for this project. To download the iset module and view its pydoc-generated documentation, please visit http://members.cox.net/apoco/iset/. From dalke at dalkescientific.com Sat Jul 23 01:01:58 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 23 Jul 2005 05:01:58 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> <1122074127.098fda4a2097406639f8c6b7f8b523ed@teranews> Message-ID: George Sakkis wrote: > Bringing up how C models files (or anything else other than primitive types > for that matter) is not a particularly strong argument in a discussion on > OO design ;-) While I have worked with C libraries which had a well-developed OO-like interface, I take your point. Still, I think that the C model of a file system should be a good fit since after all C and Unix were developed hand-in-hand. If there wasn't a good match then some of the C path APIs should be confusing or complicated. Since I don't see that it suggests that the "path is-a string" is at least reasonable. > Liskov substitution principle imposes a rather weak constraint Agreed. I used that as an example of the direction I wanted to go. What principles guide your intuition of what is a "is-a" vs a "has-a"? > Take for example the case where a PhoneNumber class is subclass > of int. According to LSP, it is perfectly ok to add phone numbers > together, subtract them, etc, but the result, even if it's a valid > phone number, just doesn't make sense. Mmm, I don't think an integer is a good model of a phone number. For example, in the US 00148762040828 will ring a mobile number in Sweden while 148762040828 will give a "this isn't a valid phone number" message. Yet both have the same base-10 representation. (I'm not using a syntax where leading '0' indicates an octal number. :) > I wouldn't say more complicated, but perhaps less intuitive in a few cases, e.g.: > >> path(r'C:\Documents and Settings\Guest\Local Settings').split() > ['C:\\Documents', 'and', 'Settings\\Guest\\Local', 'Settings'] > instead of > ['C:', 'Documents and Settings', 'Guest', 'Local Settings'] That is why the path module using a different method to split on pathsep vs. whitespace. I get what you are saying, I just think it's roughly equivalent to appealing to LSP in terms of weight. Mmm, then there's a question of the usefulness of ".lower()" and ".expandtabs()" and similar methods. Hmmm.... > I just noted that conceptually a path is a composite object consisting of > many properties (dirname, extension, etc.) and its string representation > is just one of them. Still, I'm not suggesting that a 'pure' solution is > better that a more practical that covers most usual cases. For some reason I think that path.dirname() is better than path.dirname Python has properties now so the implementation of the latter is trivial - put a @property on the line before the "def dirname(self):". I think that the string representation of a path is so important that it *is* the path. The other things you call properties aren't quite properties in my model of a path and are more like computable values. I trust my intuition on this, I just don't know how to justify it, or correct it if I'm wrong. Andrew dalke at dalkescientific.com From cam.ac.uk at mh391.invalid Fri Jul 22 13:29:21 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 18:29:21 +0100 Subject: PEP on path module for standard library In-Reply-To: <11e297jkf6i5bfa@news.supernews.com> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <11e297jkf6i5bfa@news.supernews.com> Message-ID: John Roth wrote: > However, a path as a sequence of characters has even less > meaning - I can't think of a use, while I have an application > where traversing a path as a sequence of path elements makes > perfect sense: I need to descend the directory structure, directory > by directory, looking for specific files and types. I *have* used a path as a sequence of characters before. I had to deal with a bunch of filenames that were formatted like "file_02832.a.txt" I can see the case for a path as a sequence of elements, although in practice, drive letters, extensions, and alternate streams complicate things. But as the discussion here unfolds I'm starting to feel that the advantages of using a possibly more "meaningful" approach to path as a sequence of elements are overwhelmed by the practical advantages of using a basestring. Mainly, that you can use it anywhere a basestring would be used today and it Just Works. -- Michael Hoffman From tdwdotnet at gmail.com Tue Jul 5 15:56:38 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 5 Jul 2005 20:56:38 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file In-Reply-To: References: Message-ID: <9afea2ac0507051256610249a1@mail.gmail.com> On 7/5/05, Guy Lateur wrote: > > I just tried this and it failed with IP addresses but not > > hostnames/machine names, try it again with the server name. :) > > Nope, same problem. I think TJG might be right, and our server probably > doesn't have IMAP running (yet). Could you SMTP it back in ? It would gain an extra Received: header but the rest of the email would most likely be unaltered. > > Depends how secure you need it to be. For my simple stuff I just do > > something like this > > [snip] > > That's a nice thought, although the pw is still pretty visible. Maybe > there's a way to encode/decode it using some sort of key (that only I know), > that produces a truly unrecognisable pw? Not my area of expertise I'm afraid. If you manually run the script then you could use getpass() to prompt you for the password at run time. :) From pydecker at gmail.com Mon Jul 18 11:19:18 2005 From: pydecker at gmail.com (Peter Decker) Date: Mon, 18 Jul 2005 11:19:18 -0400 Subject: re.IGNORECASE and re.VERBOSE In-Reply-To: References: Message-ID: On 7/18/05, Jeremy wrote: > I am using regular expressions and I would like to use both > re.IGNORECASE and re.VERBOSE options. I want to do something like the > following (which doesn't work): > > matsearch = r'''^\ {0,4}([mM]\d+) ''' > MatSearch = re.compile(matsearch, re.VERBOSE, re.IGNORECASE) You need to OR them together: re.compile(matsearch, re.VERBOSE | re.IGNORECASE) From ivanlan at pauahtun.org Sun Jul 24 09:30:02 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Sun, 24 Jul 2005 07:30:02 -0600 Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <3khgn6Fu8nm8U1@individual.net> Message-ID: <42E397DA.688D9172@pauahtun.org> Hi All-- Reinhold Birkenfeld wrote: > > Reinhold Birkenfeld wrote: > > Hi, > > > > the arguments in the previous thread were convincing enough, so I made the > > Path class inherit from str/unicode again. > Thanks. > * the following methods raise NotImplemented: > capitalize, expandtabs, join, splitlines, title, zfill > If path inherits from str or unicode, why not leave these? I can certainly see uses for capitalize(), title() and zfill() when trying to coerce Windows to let me use the case that I put there in the first place;-) What if I wanted to take a (legitimate) directory name 'parking\tlot' and change it to 'parking lot'? > Open issues: > > What about the is* string methods? What about them? What makes you think these wouldn't be useful? Imagine directory names made up of all numbers; wouldn't it be useful to know which directories in a tree of, say, digital camera images, comprise all numbers, all hex numbers, or alpha only? > > What about __contains__ and __getitem__? I find it hard to imagine what would be returned when asking a path for say, path["c:"], other than the index. n=path["c:"] = 0 ? > > What about path * 4? This one makes my brain hurt, I admit;-) Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From aahz at pythoncraft.com Fri Jul 15 20:44:46 2005 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2005 17:44:46 -0700 Subject: Snakespell References: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> Message-ID: [posted & e-mailed -- prefer response by posting] In article <1120830892.733174.18770 at g44g2000cwa.googlegroups.com>, peterbe at gmail.com wrote: > >I used to use Snakespell from scriptfoundry to do spellchecking on my >website (www.peterbe.com/search?q=pyton) but now that I've moved server >and wiped the old machine I forgot to take with me the Snakespell code. > >www.scriptfoundry.com where it used to live seems to have expired. I've got a copy, but I'd rather you check with the original author first: http://starship.python.net/crew/thanos/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From bvande at po-box.mcgill.ca Fri Jul 1 16:52:47 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 01 Jul 2005 16:52:47 -0400 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> <42c41ef2@usenet01.boi.hp.com> Message-ID: <42C5AD1F.5060902@po-box.mcgill.ca> Peter Hansen said unto the world upon 01/07/2005 11:47: > Dan Sommers wrote: > >>Peter Hansen wrote: >> >>>This problem is well suited to the abilities of genetic algorithms, >>>and this would probably be an excellent way to learn more about them, >>>even if you don't get the best solution. >> >>There's some sort of irony or something in there about not writing the >>best genetic algorithm, but I can't quite put my finger on it. > > > Maybe your irony sensor is getting muddled over the fact that genetic > algorithms generally *don't* find the best solutions, just relatively > good ones. They aren't an exhaustive search, they're basically a random > search with some features thought to focus the search on more fruitful > parts of the solution space, thus optimizing it. Unless *my* irony > processors are malfunctioning, I don't think there's anything ironic > about this. (If anything it looks like the exact opposite of irony, to me.) > > -Peter Well, I found it ironic, but only when you add that the genetic algorithm approach came up in the context of a "best fit" problem. Survival of the fittest indeed :-) Best, Brian vdB From gsakkis at rutgers.edu Thu Jul 7 21:31:32 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Jul 2005 18:31:32 -0700 Subject: Is there an easy way to get at the value of DBL_MAX from Python? References: Message-ID: <1120786292.014588.107080@g44g2000cwa.googlegroups.com> "Steve Juranich" wrote: > I'm in a situation where it would be nice to have access to this > value. I've been looking for it all afternoon and can't find anything. Where exactly have you been looking ? I guess not in Google, because the fifth result after querying "dbl_max" is http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html, which follows up to http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html. There is a Numeric subpackage named 'kinds' that provides it along with other constants, but it seems it has been excluded from the latest (and final I believe) version of Numeric (24.0b2) that I have installed, so I can't actually check it. George From felix at keyremovethisghost.com Thu Jul 21 23:28:20 2005 From: felix at keyremovethisghost.com (Felix Collins) Date: Fri, 22 Jul 2005 15:28:20 +1200 Subject: Help with regexp please Message-ID: Hi, I'm not a regexp expert and had a bit of trouble with the following search. I have an "outline number" system like 1 1.2 1.2.3 1.3 2 3 3.1 etc. I want to parse an outline number and return the parent. So for example... parent("1.2.3.4") returns "1.2.3" The only way I can figure is to do two searches feeding the output of the first into the input of the second. Here is the code fragment... m = re.compile(r'(\d+\.)+').match("1.2.3.4") n = re.compile(r'\d+(\.\d+)+').match(m.string[m.start():m.end()]) parentoutlinenumber = n.string[n.start():n.end()] parentoutlinenumber 1.2.3 How do I get that into one regexp? Thanks for any help... Felix From wezzy at despammed.com Sat Jul 9 15:15:09 2005 From: wezzy at despammed.com (Wezzy) Date: Sat, 9 Jul 2005 21:15:09 +0200 Subject: Should I use "if" or "try" (as a matter of speed)? References: <1120934674.774605.184080@g44g2000cwa.googlegroups.com> <1120935497.365395.168900@g47g2000cwa.googlegroups.com> Message-ID: <1gzgazx.4rrzdwsgicsdN%wezzy@despammed.com> wittempj at hotmail.com wrote: > My shot would be to test it like this on your platform like this: > > #!/usr/bin/env python > import datetime, time > t1 = datetime.datetime.now() > for i in [str(x) for x in range(100)]: > if int(i) == i: > i + 1 > t2 = datetime.datetime.now() > print t2 - t1 > for i in [str(x) for x in range(100)]: > try: > int(i) +1 > except: > pass > t3 = datetime.datetime.now() > print t3 - t2 > > for me (on python 2.4.1 on Linux on a AMD Sempron 2200+) it gives: > 0:00:00.000637 > 0:00:00.000823 PowerBook:~/Desktop wezzy$ python test.py 0:00:00.001206 0:00:00.002092 Python 2.4.1 Pb15 with Tiger -- Ciao Fabio From renting at astron.nl Fri Jul 29 05:42:25 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 29 Jul 2005 11:42:25 +0200 Subject: Filtering out non-readable characters Message-ID: def StripNoPrint(self, S): from string import printable return "".join([ ch for ch in S if ch in printable ]) Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> "MKoool" 07/16/05 2:33 AM >>> I have a file with binary and ascii characters in it. I massage the data and convert it to a more readable format, however it still comes up with some binary characters mixed in. I'd like to write something to just replace all non-printable characters with '' (I want to delete non-printable characters). I am having trouble figuring out an easy python way to do this... is the easiest way to just write some regular expression that does something like replace [^\p] with ''? Or is it better to go through every character and do ord(character), check the ascii values? What's the easiest way to do something like this? thanks -- http://mail.python.org/mailman/listinfo/python-list From gsakkis at rutgers.edu Thu Jul 14 17:48:34 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 14 Jul 2005 14:48:34 -0700 Subject: all possible combinations References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> <42d6662a$1@news.eftel.com> <1121362739.24407.4.camel@athop1.ath.vt.edu> Message-ID: <1121377714.829856.231710@g49g2000cwa.googlegroups.com> "rbt" wrote: > Thanks to all who were helpful... some of you guys are too harsh and > cynical. Here's what I came up with. I believe it's a proper > combination, but I'm sure someone will point out that I'm wrong ;) > > groups = [list('abc'),list('abc'),list('abc'),list('abc')] > > already = [] > > while 1: > > LIST = [] > > for g in groups: > sample = random.sample(g, 1) > LIST.append(sample[0]) > > STRING = ''.join(LIST) > if STRING not in already: > print STRING > already.append(STRING) > if len(already) == 81: > break UGH! I guess you're right, it's theoretically correct in the limit; however IIRC, in your original post you were asking about the most efficient way, not the least efficient, most obscure and inextensible solution one could come up with. You're hoping to generate all combinations AT RANDOM and you're wondering why some of us come out "too harsh and cynical" ?! Try this with all letters instead of 'abc' and when it ends get back to us, or rather our grand-grandchildren. In the meantime, learn about recursion, generators and accumulating loops and try to understand the right, efficient solutions already posted. Cynically yrs, George PS: Btw, using ALL_CAPITALS (at least for local variables) is BAD STYLE; the same holds for variables named 'list' and 'string', independent of case. From rkern at ucsd.edu Tue Jul 5 15:40:33 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 05 Jul 2005 12:40:33 -0700 Subject: Using Numeric 24.0b2 with Scientific.IO.NetCDF In-Reply-To: <1120590393.714232.34240@f14g2000cwb.googlegroups.com> References: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> <1120590393.714232.34240@f14g2000cwb.googlegroups.com> Message-ID: bandw wrote: > Robert, > > Thanks for your reply. However, I am still having problems. Sometimes > I get a scalar return > and sometimes I get an array. For example, using the netCDF file: > > netcdf simple { > dimensions: > num = 3 ; > variables: > float temp0(num) ; > int temp1(num) ; > data: > > temp0 = 1., 2., 3. ; > temp1 = 1, 2, 3 ; > } > > and running: > > # > import Numeric > print Numeric.__version__ > from Scientific.IO.NetCDF import NetCDFFile > > cdf_file1 = NetCDFFile("simple.nc","r") > > var1 = cdf_file1.variables["temp0"][:] > var2 = cdf_file1.variables["temp1"][:] > min1 = reduce(Numeric.minimum,var1) > min2 = reduce(Numeric.minimum,var2) > > print "Types of var1, min(var1), min1:",type(var1), type(min(var1)), > type(min1) > print "Types of var2, min(var2), min2:",type(var2), type(min(var2)), > type(min2) > > I get: > > 24.0b2 > Types of var1, min(var1), min1: 'array'> > Types of var2, min(var2), min2: 'int'> > > Even something like: > >>>>import Numeric >>>>a = Numeric.array([1.,2.]) >>>>print type(a),type(min(a)) > > > > does not produce an array. Hmm, odd. Anyways, follow my advice: use minimum.reduce() and wrap results in float() or array() if you really need floats or rank-0 arrays. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gsakkis at rutgers.edu Thu Jul 14 20:30:38 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 14 Jul 2005 20:30:38 -0400 Subject: Newbie question: Explain this behavior References: Message-ID: <1121387447.2364df6ba36147532694a486d68fa8a8@teranews> "David Smith" wrote in message news:db6tfq$1kbh$1 at zook.lafn.org... > Why does code snippet one work correctly, but not two. The only > difference is the placement of the "else". I know that indentation > affects execution, but how does it change behavior in the following > examples? Thank you. > > [snipped] In the second example, "else" corresponds to "if", while in the first one it corresponds to "for". The tutorial example on "for ... else" loops (http://docs.python.org/tut/node6.html#SECTION006400000000000000000) uses the prime number computation you posted, so read it again if it's not clear what the "else" clause does with loops. George From roccomoretti at hotpop.com Mon Jul 4 12:05:42 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 04 Jul 2005 11:05:42 -0500 Subject: Will Guido's "Python Regrets" ever get implemented/fixed? In-Reply-To: <11cicg4fbeer8e8@news.supernews.com> References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> <1120368681.573445.199710@g44g2000cwa.googlegroups.com> <1120371274.448543.145890@g43g2000cwa.googlegroups.com> <1120398483.415818.95360@o13g2000cwo.googlegroups.com> <11cicg4fbeer8e8@news.supernews.com> Message-ID: John Roth wrote: > "Peter Maas" wrote in message > news:dab25m$dvk$1 at swifty.westend.com... > >> George Sakkis schrieb: >> >>> Given that the latest 2.x python will be 2.9 >> >> >> Why not 2.13 or 2.4711? Version strings are sequences of arbitrary >> integers separated by dots and not decimal numbers, or are they? > > > Because Guido said (somewhere) that he didn't want to go over > release 2.9. It's actually (repeated) in the talk linked to earlier. The rationale is not touched on, though. George Sakkis wrote: > Given that the latest 2.x python will be 2.9 and that 3.0 may be > released in parallel with 2.5-2.9 > (http://www.python.org/doc/essays/ppt/euro2004/euro2004.ppt), I guess > this *someday* will be no later than 2015-16, probably sooner than > that. From sunitajain at gmail.com Tue Jul 5 02:16:25 2005 From: sunitajain at gmail.com (sunitajain at gmail.com) Date: 4 Jul 2005 23:16:25 -0700 Subject: Tkinter + Tcl help Message-ID: <1120544185.116872.177600@g14g2000cwa.googlegroups.com> Hello all, I have a Tcldot package which I am using with Tcl (I source the package by 'load .....\libtcldot.so.0' command. Now I want to use this package in Tkinter. Can anyone suggest me how to do this? I tried the foll: root=Tk() root.tk.eval('load ......\libtcldot.so.0') root.mainloop() But I get error this way. Any suggestions would be the most useful. Thanks, Sunita From me at privacy.net Fri Jul 15 16:28:08 2005 From: me at privacy.net (Dan Sommers) Date: Fri, 15 Jul 2005 16:28:08 -0400 Subject: System calls not using correct permissions? References: <1121381512.615154.186430@o13g2000cwo.googlegroups.com> <1121436610.483056.27000@g44g2000cwa.googlegroups.com> Message-ID: On 15 Jul 2005 07:10:10 -0700, "skilpat at gmail.com" wrote: > Oops, yeah I should have mentioned some of that. It's a Linux > environment, and it's running Python 2.2. To my knowledge, the batch > files my program calls run a few processes on some data and generate a > few temporary files. I believe those files are not correctly being > generated. There is an error message in one of the scripts that says > could not find xxx.xxx, which is a temp file it creates. The batch > files are all executed with tcsh. Again, just a guess, but one of (the many) reasons not to use tcsh is that it has some very strange (to me, anyway) rules about which startup files (e.g., .login) to run when. Perhaps one of your such files is being executed in one case and not the other, and is doing something relevant to an environment variable or umask. Regards, Dan -- Dan Sommers From peter at engcorp.com Sat Jul 2 18:55:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 18:55:46 -0400 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: Roy Smith wrote: > Peter Hansen wrote: >>I'll have to look into how to set up Windows XP to prevent users from >>changing the time on their own, assuming that's possible. > > On a single-user system like Windows, you pretty much have to assume the > user can do anything. They can turn off NTP, reset the clock, reboot the > system, uninstall your software, whatever. Actually, I suspect that a non-administrator user can be restricted from doing several of those things under XP, which would simplify things. And, in any case, I'm not remotely concerned about malicious users, just "fiddlers" who might think their watch time is somehow more correct than what the computer says... -Peter From rkern at ucsd.edu Wed Jul 27 18:03:44 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Jul 2005 15:03:44 -0700 Subject: SciPy and NetCDF In-Reply-To: <1122501589.494602.141620@o13g2000cwo.googlegroups.com> References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> <1122499062.943121.65200@z14g2000cwz.googlegroups.com> <1122501589.494602.141620@o13g2000cwo.googlegroups.com> Message-ID: Scott Kilpatrick wrote: > Oh ok, so if my sysadmin installs SciPy, then to get the netCDF support > we need he just needs to then install pycdf? 1. Install Numeric. 2. Install Scipy. 3. Install pycdf. Numeric is not, yet, bundled into Scipy. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From callmebill at gmail.com Thu Jul 21 10:46:34 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 21 Jul 2005 07:46:34 -0700 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <1121956897.727721.38050@g47g2000cwa.googlegroups.com> References: <42dfb111@griseus.its.uu.se> <1121956897.727721.38050@g47g2000cwa.googlegroups.com> Message-ID: <1121957194.722095.263140@g47g2000cwa.googlegroups.com> You could also set your "python" environment variable on the system... set it to be "/path/to/python2.4". Then use the "#!/usr/bin/env python" trick. Just make sure that env is working for you, first. From newsgroups at jhrothjr.com Fri Jul 22 10:27:06 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 22 Jul 2005 08:27:06 -0600 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <11e20ht23qd98bd@news.supernews.com> "Duncan Booth" wrote in message news:Xns969B63FB97195duncanbooth at 127.0.0.1... > George Sakkis wrote: > > > You should need an explicit call to convert a path to a string and that > forces you when passing the path to something that requires a string to > think whether you wanted the string relative, absolute, UNC, uri etc. > > It may even be that we need a hierarchy of path classes: URLs need similar > but not identical manipulations to file paths, so if we want to address > the > failings of os.path perhaps we should also look at the failings of > urlparse > at the same time. You have to start somewhere. One of the lessons that's beginning to seep into people's minds is that getting something that works out there is almost always preferable to (over) design by committee. How to do a comprehensive, covers all the corner cases file system object (or object hierarchy, etc) has been discussed before, and nothing has ever come of it. Starting with an object that actually does something some people want gives the designers a chance to look at things in the wild. John Roth From c at cdot.de Sat Jul 30 11:04:50 2005 From: c at cdot.de (Chris) Date: Sat, 30 Jul 2005 17:04:50 +0200 Subject: showing help(M) when running module M standalone Message-ID: hello, I have a small module which only contains some utility functions. when running this standalone I would like to show the module docs and each function docs, as if doing import M help(M) I came up with the following but I reckon there is a much simpler way? if __name__ == '__main__': print __doc__ print "\nFUNCTIONS:\n" for x in __all__: print x exec "print " + x + ".__doc__" Works but does not seem right using exec for such a task. any hint would be great! thanks chris From corey.coughlin at comcast.net Thu Jul 28 20:34:38 2005 From: corey.coughlin at comcast.net (corey.coughlin at comcast.net) Date: 28 Jul 2005 17:34:38 -0700 Subject: Rich Graphics? In-Reply-To: References: Message-ID: <1122597278.887403.161780@g44g2000cwa.googlegroups.com> for widgets, try pyUI http://pyui.sourceforge.net/ hope that helps, looks cool and all.. From mwm at mired.org Fri Jul 1 18:25:21 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 18:25:21 -0400 Subject: Favorite non-python language trick? References: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> Message-ID: <86psu2410u.fsf@bhuda.mired.org> "Shai" writes: > Joseph Garvin wrote: >> >> I'm curious -- what is everyone's favorite trick from a non-python >> language? And -- why isn't it in Python? > > 1. Lisp's "dynamically scoped" variables (Perl has them, and calls them > "local", but as far as I've seen their use their is discouraged). These > are global variables which are given time-local bindings. That is, > structuring the syntax after what's used for globals, Perl started life with nothing but dynamically scoped variables. They added lexical scoping after they realized what a crock dynamic scoping was. > x=10 > def foo(): > # No need to define x as it is only read -- same as globals > print x > > def bar(): > dynamic x > x = 11 > foo() > > def baz(): > bar() # prints 11 > foo() # prints 10; the binding in bar is undone when bar exits > > This feature makes using "globals" sensible, providing a way to avoid > many important uses (and some say, misuses) of objects if you are so > inclined. It allows you to do some things better than objects do, > because it does to library parameters, what exceptions do to return > codes: instead of passing them in all the way from outside until a > piece of code which actually uses them, they are only mentioned where > you set them and where you really need to access them. > > It would not be too hard to implement a version of this (inefficiently) > in the existing language, if frame objects could carry a modifiable > dictionary. > > I suppose it is not in Python because (most) Pythoners are not looking > (hard enough) for alternatives to OOP. Last time I checked, dynamic binding variables were frowned on in LISP systems as well. Scheme doesn't have them. Common LISP requires special forms to use them. The problem with the given use case is that it lets every routine in the call chain substitute it's own variable for the library parameter you want to use, with no local indication that this is going on. This makes bugs in dynamically scoped variables a PITA to find. Given that it's a feature I don't want programmers using, I'd only be willing to see it added to the language if you can show that it has no overhead so long as you don't use it. I'm not sure that can be done. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Thu Jul 14 08:31:13 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 14 Jul 2005 22:31:13 +1000 Subject: all possible combinations References: <1121265581.28091.2.camel@athop1.ath.vt.edu> <42d59a61$1@news.eftel.com> Message-ID: On Thu, 14 Jul 2005 08:49:05 +1000, John Machin wrote: > "You keep using that word. I do not think it means what you think it means." > > Both of you please google("define: combination") Combination: "a coordinated sequence of chess moves". "An option position that is effected by either a purchase of two long positions or two short positions. The investor purchases a call and a put (or sells a call and a put) with different expiration dates and/or different strike prices." Or perhaps "in Scheme, a function call, consisting of a function name and arguments written within parentheses." Yes, mathematically the definition of combination includes that order does not matter. But that certainly isn't the case in common English. Now, John, given the tone of the posts you are complaining about, do you think I was using combination in the precise mathematical sense, or the common English sense? (Hint: the very first definition Google finds is "a collection of things that have been combined; an assemblage of separate parts or qualities ". Not a word there about order mattering or not.) -- Steven. From cam.ac.uk at mh391.invalid Thu Jul 21 17:36:51 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 22:36:51 +0100 Subject: PEP on path module for standard library In-Reply-To: <3kacleFslj6sU1@individual.net> References: <3kacleFslj6sU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > FYI: I modified the path module a bit so that it fits many of the suggestions > from python-dev, and put the result in the Python CVS tree under > nondist/sandbox/path. > > Most prominent change is that it doesn't inherit from str/unicode anymore. > I found this distinction important, because as a str subclass the Path object > has many methods that don't make sense for it. Having path descend from str/unicode is extremely useful since I can then pass a path object to any function someone else wrote without having to worry about whether they were checking for basestring. I think there is a widely used pattern of accepting either a basestring[1] or a file-like object as a function argument, and using isinstance() to figure out which it is. What do you gain from removing these methods? A smaller dir()? [1] Probably str in actuality. -- Michael Hoffman From usenet at zabiello.com Tue Jul 19 08:02:19 2005 From: usenet at zabiello.com (JZ) Date: Tue, 19 Jul 2005 14:02:19 +0200 Subject: Python IDE References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: Dnia Tue, 19 Jul 2005 13:26:38 +0200, Mage napisa?(a): > I had no luck with the code completion, It works. Just type sys. and wait a while. But you have to set up pydev first. Check PyDev->Builder->Use Builders and PyDev->CodeCompletion->... -- JZ From steve at REMOVETHIScyber.com.au Wed Jul 6 19:15:57 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 07 Jul 2005 09:15:57 +1000 Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> <42cbdbde$0$10471$da0feed9@news.zen.co.uk> <1120670131.471176.133020@g14g2000cwa.googlegroups.com> Message-ID: On Wed, 06 Jul 2005 10:15:31 -0700, George Sakkis wrote: > Well, they *may* be interchangable under some conditions, and that was > the OP's point you apparently missed. I didn't miss anything of the sort. That's why I spent 15 minutes actually producing test cases to MEASURE if there was any detectable speed differences between accessing set and frozenset instead of wasting time worrying about "tiny" differences in performance that are almost certainly lost in the noise in real code. If, over a thousand runs of the program, you save a millisecond of time in total, but it costs you two seconds to type the comment in the code explaining why you used frozenset instead of the more natural set, then your "optimization" is counter-productive. Even just considering the question is a waste of valuable developer time! THAT is the lesson of premature optimization: don't even THINK about optimizing code until you have it WORKING and you have MEASURED that it is too slow. -- Steven. From hancock at anansispaceworks.com Fri Jul 1 05:38:51 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 04:38:51 -0500 Subject: Splitting string into dictionary In-Reply-To: References: Message-ID: <200507010438.51012.hancock@anansispaceworks.com> On Friday 01 July 2005 12:35 am, David Pratt wrote: > Wow Robert that is incredible python magic! I am trying to figure out > what this is doing since my attempts were regex and some long string > splitting and collection. Try it out in the interpreter: Test data: >>> test = "'en' | 'the brown cow' | 'fr' | 'la vache brun'" Splitting, you already know: >>> line.split('|') ["'en' ", " 'the brown cow' ", " 'fr' ", " 'la vache brun'"] The list comprehension generates a new list based on the old one, in this case, using the string method strip to remove spaces and single quotes: >>> translations = [x.strip(" '") for x in line.split('|')] >>> translations ['en', 'the brown cow', 'fr', 'la vache brun'] Then Robert did some real magic by using extended slice notation: >>> translations[::2] ['en', 'fr'] (count from 0, every 2nd element) >>> translations[1::2] ['the brown cow', 'la vache brun'] (count from 1, every 2nd element) This, of course, is to generate two parallel lists from your one. "zip" well, *zips* two or more lists together: >>> zip(translations[::2], translations[1::2]) [('en', 'the brown cow'), ('fr', 'la vache brun')] Which is all ready for the dict constructor: >>> dict(zip(translations[::2], translations[1::2])) {'fr': 'la vache brun', 'en': 'the brown cow'} I always find it helps to take a statement apart in the interpreter if a little too much is going on in one line for me to follow. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From erinhouston at gmail.com Tue Jul 26 16:22:18 2005 From: erinhouston at gmail.com (ina) Date: 26 Jul 2005 13:22:18 -0700 Subject: Using win32com for web automation In-Reply-To: <1122399814.174328.63980@g43g2000cwa.googlegroups.com> References: <1122399814.174328.63980@g43g2000cwa.googlegroups.com> Message-ID: <1122409338.810583.97610@z14g2000cwz.googlegroups.com> Look up pamie it should do all the work you need. If it dosn't I can send you ishyBrowser but pamie has more comunity support. From tzot at sil-tec.gr Sat Jul 2 09:25:54 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 02 Jul 2005 16:25:54 +0300 Subject: Python choice of database References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: On 20 Jun 2005 11:43:28 -0700, rumours say that "Oren Tirosh" might have written: >For very short keys and record (e.g. email addresses) you can use >symbolic links instead of files. The advantage is that you have a >single system call (readlink) to retrieve the contents of a link. No >need to open, read and close. readlink also does open, read and close too. And why go through indirection? Why not make indexes into subdirectories, say, and hard-link the records under different filenames? >This works only on posix systems, of course. There aren't any non-posix-conformant --or, at least, any non-self-described-as-posix-conformant :-)-- operating systems in wide use today. Hint: win32file.CreateHardLink -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From nephish at xit.net Thu Jul 28 10:01:48 2005 From: nephish at xit.net (nephish) Date: Thu, 28 Jul 2005 14:01:48 +0000 Subject: easy float question just eludes me In-Reply-To: <8c7f10c60507280648244420cf@mail.gmail.com> (from simon.brunning@gmail.com on Thu Jul 28 08:48:27 2005) References: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> <8c7f10c60507280648244420cf@mail.gmail.com> Message-ID: <1122559308l.19273l.0l@texaspivot.texaspivot.com> oops, i dont seem to have a module decimal -shawn On 07/28/2005 08:48:27 AM, Simon Brunning wrote: > On 28 Jul 2005 06:39:32 -0700, nephish at xit.net > wrote: > > i have a real easy one here that isn't in my book. > > i have a int number that i want to divide by 100 and display to two > > decimal places. > > > > like this float(int(Var)/100) > > but i need it to display the .00 even if it does not have a .00 > value > > like this > > if Var is 50, i need to display .50 instead of just .5 > > >>> import decimal as dec > >>> dec.Decimal('250.00')/100 > Decimal("2.50") > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ > > From pujasharma0381 at gmail.com Tue Jul 19 02:58:31 2005 From: pujasharma0381 at gmail.com (Pooja) Date: 18 Jul 2005 23:58:31 -0700 Subject: How to write at a sppecific location Message-ID: <1121756311.884331.15710@f14g2000cwb.googlegroups.com> Hi All I have one csv file which has some data related to test results. It has following information TestId,Expectedres,Actualres 101,12,13 102,13 103,14 If I want to write ActualRes value in the file , How to do that. I tried using seek but its not working. I am not able to write at a specific location. Please tell me what is the rght way. I have chked all the docs but was not able to find any good solution. From onurb at xiludom.gro Thu Jul 28 11:17:07 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 28 Jul 2005 17:17:07 +0200 Subject: functions without parentheses In-Reply-To: <1122559193.824826.157390@g47g2000cwa.googlegroups.com> References: <1122559193.824826.157390@g47g2000cwa.googlegroups.com> Message-ID: <42e8f6f3$0$18620$626a14ce@news.free.fr> Simon Dahlbacka wrote: > If you actually want that kind of syntax, then why don't you use Visual > Basic? ;) s/VisualBasic/Ruby/ -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" From rkern at ucsd.edu Sun Jul 10 18:39:45 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 10 Jul 2005 15:39:45 -0700 Subject: ZipFile and file rigths In-Reply-To: <1121034112.762673.31530@z14g2000cwz.googlegroups.com> References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> <1121034112.762673.31530@z14g2000cwz.googlegroups.com> Message-ID: perchef wrote: [Sybren Stuvel:] >>ZIP doesn't store file permissions. Yes, the .zip file format does store file permissions appropriate to the platform that generates the file. > ok, but in that case how could stuffit retrieve these permissions ? > > Thanks for the link Robert. When one makes a .zip file using ZipFile, the permissions are stored, but there is also a flag that tells unzip utilities what system the .zip file was made on. ZipFile always stores this flag as MS Windows no matter what system actually made it. StuffIt seems to ignore the flag and always propagate the permissions when it unzips. It assumes that the .zip file was made on a Mac. InfoZip's unzip(1) utility does look at the flag, and if it says "MS Windows", it does not propagate the permissions. If the .zip file actually *were* made on a Windows machine and unzipped on a UNIX-like filesystem, all of the files would be marked executable. I remember this used to happen quite often a few years ago. InfoZip made an arguably incorrect choice (but also a fairly convenient one), but ZipFile's behavior is definitely incorrect. OTOH, I don't know if this has any relevance to the problem that you are seeing. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From qwweeeit at yahoo.it Thu Jul 14 08:36:08 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 14 Jul 2005 05:36:08 -0700 Subject: Splitting on a word References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> Message-ID: <1121344568.230244.214440@o13g2000cwo.googlegroups.com> Hi all, thanks for your contributions. To Robert Kern I can replay that I know BeautifulSoap, but mine wanted to be a "generalization" (only incidentally used in a web parsing application). The fact is that, beeing a "macho newbie" programmer (the "macho" is from Steven D'Aprano), I wanted to show how beaufiful solutions I can find... Luckily there is Joe who shows me that he most of my "beautiful" code (working, of course!) can be replaced by: list=p.split(s) Bernard... don't get angry, but I prefer the solution of Joe. It is more general, and, besides that, for me "pythonic" means simple and short (I may be wrong...). By the way, I have found an alternative solution to the problem of lists "unique", without sorting, but non beeing enough "macho"... Bye. From spanking.13.littlegoats at spamgourmet.com Thu Jul 14 15:34:00 2005 From: spanking.13.littlegoats at spamgourmet.com (Sheeps United) Date: Thu, 14 Jul 2005 22:34:00 +0300 Subject: Changing size of Win2k/XP console? Message-ID: <42d6bdd2$0$16170$39db0f71@news.song.fi> Hi, I'm quite a newbie but I've managed to google around before asking stupid Q's here. I'm wrestling with little (amateurish) console program and I would like change its size. I also know that it could be done with Windows API call. I tried doing that myself but no good. Could anyone help me? From derrick at csociety.org Tue Jul 19 13:43:58 2005 From: derrick at csociety.org (derrick) Date: Tue, 19 Jul 2005 12:43:58 -0500 Subject: gdb python C API Message-ID: I have written a c program to interface with a newly installed version of python 2.4.1 on my system. The C program calls a module written in python that goes on to parse an xml file and do other xml specific operations. When I use the module in python, it seems to work alright, but when I try to use my c program to interface, sometimes it works and sometimes it segfaults. I tried using gdb find the segfault, but in the C program, once the python module is called, gdb tells me that some python compiled code has been placed on the stack and is being executed, but i am having trouble finding what part of the python module is being executed (which makes it hard to find the real reason for the segfault). are there any tools / methods that others have used to get what line of the python script is being executed while running in gdb? or if it would actually show me the source python script (instead of the the python c source) that would help. my setup is: self compiled/installed python 2.4.1 my python module calls the xml.dom.minidom module. my problem might be refcounts, i've looked over them many times and they seem to make sense to me but it never hurts to have someone else's opinion. tia, derrick From maxm at mxm.dk Mon Jul 4 05:08:09 2005 From: maxm at mxm.dk (Max M) Date: Mon, 04 Jul 2005 11:08:09 +0200 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <42c8fc44$0$221$edfadb0f@dread12.news.tele.dk> jwaixs wrote: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! There are only reference, and if you don't know how a > module work you won't learn it from a reference! If you want to try out re interactively you could use: \Tools\Scripts\redemo.py -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From provato at gmail.com Fri Jul 15 10:39:16 2005 From: provato at gmail.com (provato) Date: 15 Jul 2005 07:39:16 -0700 Subject: eBay.py - Has anyone looked at this??? In-Reply-To: <1121386344.e07b5a134c1e05eacfc289a1c9631458@teranews> References: <1121377295.386699.141580@g47g2000cwa.googlegroups.com> <1121386344.e07b5a134c1e05eacfc289a1c9631458@teranews> Message-ID: <1121438356.911065.300770@z14g2000cwz.googlegroups.com> Thanks. That helps. From callmebill at gmail.com Fri Jul 15 13:00:22 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 15 Jul 2005 10:00:22 -0700 Subject: Native ODBC access for python on linux? In-Reply-To: <86r7e0al3p.fsf@bhuda.mired.org> References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> <8NCdnRaSkdR-XkvfRVn-jg@telcove.net> <86r7e0al3p.fsf@bhuda.mired.org> Message-ID: <1121446822.710877.312020@g44g2000cwa.googlegroups.com> All, This info was very helpful, and I'm up and running with MySQLdb on linux, and the native ODBC support on Windows. One last question I have: In vbs (specifically with .asp) I can make a connection to an ODBC provide _without_ the need to specify a system DSN in the Control Panel. It's easy to do with MySQLdb.connect( host,user,pass,etc), but is this possible with the ODBC module in Python on win32? Thanks again for all the help. This has really narrowed the gap in my knowledge significantly. From lordverminard at gmail.com Thu Jul 28 14:24:27 2005 From: lordverminard at gmail.com (mustafa) Date: Thu, 28 Jul 2005 23:24:27 +0500 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Rocco Moretti wrote: > projecktzero wrote: > >>but..but...It's so much more fun to unleash your anger and fire back >>with all guns blazing fanning the flame war that most discussion groups >>degenerate into after a couple of responses. =) >> >>Actually, I had some self restraint yesterday. I wanted to write a >>ripping response to an antagonistic flame bait message on another >>group. I wrote it, decided it wouldn't help much, and deleted it. I >>guess I got it out of my system by just writing it. > > > That's what I do. I sometimes have something I want to say, so I write > my rant. Once I get it out of my system, I realize that it isn't adding > anything to the discussion, and delete it. The part of my brain that > wants to rant is happy because it got its say in, and the rest of the > world is happier for not having to read it. > > I highly recommend that people try it. It works wonders. thats wrong. you should atleast reprimand the person whose bieng rude. otherwise that type of behavior spreads. ppl have to realise that ifyou want ppl to help asking nicely can and will do wonders From spam.csubich+block at block.subich.spam.com Fri Jul 8 15:50:46 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Fri, 08 Jul 2005 15:50:46 -0400 Subject: Legacy data parsing In-Reply-To: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: gov wrote: > Hi, > > I've just started to learn programming and was told this was a good > place to ask questions :) > > Where I work, we receive large quantities of data which is currently > all printed on large, obsolete, dot matrix printers. This is a problem > because the replacement parts will not be available for much longer. > > So I'm trying to create a program which will capture the fixed width > text file data and convert as well as sort the data (there are several > different report types) into a different format which would allow it to > be printed normally, or viewed on a computer. Are these reports all of the same page-wise format, with fixed-width columns? If so, then the suggestion about a state machine sounds good -- just run a state machine to figure out which linetype you're on, then extract the fixed width fields via slices. name = line[x:y] If that doesn't work, then pyparsing or DParser might work for you as a more general-purpose parser. From nephish at xit.net Tue Jul 26 20:26:51 2005 From: nephish at xit.net (nephish at xit.net) Date: 26 Jul 2005 17:26:51 -0700 Subject: need some info on MySQL module. In-Reply-To: References: <1122422126.817344.207840@o13g2000cwo.googlegroups.com> Message-ID: <1122424010.965985.248650@g14g2000cwa.googlegroups.com> Wow, thanks so much. I promise, i didn't know that was out there. should help me out a lot. still a newbie here, somewhat. thanks again <>< From gsakkis at rutgers.edu Sat Jul 16 23:28:02 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 16 Jul 2005 23:28:02 -0400 Subject: Filtering out non-readable characters References: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> Message-ID: <1121570966.6b3e122aacf94730620c39031b3c126b@teranews> "Peter Hansen" wrote: > George Sakkis wrote: > > "Peter Hansen" wrote: > >>>> Where did you learn that, George? > > > > Actually I first read about this in the Cookbook; there are two or three > > recipes related to string.translate. As for string.maketrans, it > > doesn't do anything special for empty string arguments: ... > > I guess so. I was going to offer to suggest a new paragraph on that > usage for the docs, but as you and Jp both seem to think the behaviour > is obvious, I conclude "it's just me" so I suppose I shouldn't bother. It's only obvious in the sense that _after_ you see this idiom, you can go back to the docs and realize it's not doing something special; OTOH if you haven't seen it, it's not at all the obvious solution to "how do I get the first 256 characters". So IMO it should be mentioned, given that string.translate often operates on the identity table. I think a single sentence is adequate for the reference docs. George From luismgz at gmail.com Wed Jul 20 17:40:33 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 20 Jul 2005 14:40:33 -0700 Subject: mod_python Apache/2.0.52 (Win32) Python 2.4 In-Reply-To: <38d6a9b7.0507201214.12c048ac@posting.google.com> References: <38d6a9b7.0507201214.12c048ac@posting.google.com> Message-ID: <1121895633.480241.187840@g49g2000cwa.googlegroups.com> Dieter Raber wrote: > Hi there, > > I am wondering if there is a mod_python for the above configuration. I > downloaded mod_python-3.1.3.win32-py2.3.exe, which of course as the > name implies keeps on asking me for a python 2.3 installation. I > imagine one could cheat a little bit with a fake registry entry that > says it was about python 2.3 but that points to python 2.4. Then again > I don't know what entry mod_python's installer is looking for. > > Thanks for your help > > Dieter Hi there, A couple of months ago, I went though the hassle of trying to install mod_python and unfortunately, there is no easy way of doing it separately, because you have to take care about each component's version, that should match the other component's one... If you one to do it all at once and get it working, try Apache2Triad: http://apache2triad.net/ This is a package inspired in EasyPhp and PhpTriad and. It installs all the required software (plus a lot of other programs - check the website). It is aimed at webdevelopers who don't want to deal with individual instalations or configurations. The only downside is that it will install many programs that you are probably not interested in... but you might like it. Cheers, Luis From mwm at mired.org Sun Jul 24 15:48:35 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 24 Jul 2005 15:48:35 -0400 Subject: How to run python script in background after i logout References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> <20050724095117.GA8785@zermelo.sians.org> Message-ID: <86k6jgnfxo.fsf@bhuda.mired.org> Thanos Tsouanas writes: > On Sun, Jul 24, 2005 at 12:51:17PM +0300, Thanos Tsouanas wrote: >> On Sun, Jul 24, 2005 at 02:43:44AM -0700, Harlin Seritt wrote: >> > I have a remote linux server where I can only access it via ssh. I have >> > a script that I need to have run all the time. I run like so: > Since you want it to run all the time, check cron(8) as well. > Maybe you would like to write a small script, executing script.py if it > is not already running. Cron will restart the process at regular intervals, meaning you have to have a mechanism in place to deal with multiple copies running. It also allows for periods when no process is running. There are usually better solutions than this, but they are system-dependent. On SysV like systems - which includes most (all?) Linux systems - you can add an entry to inittab that will cause a command to be restarted should it ever die. On BSD based systems, the same functionality is available via /etc/ttys. It's not very well documented, though. The reason you don't hear much about these is because it's normal for a Unix app to be able to deal with such issues by itself. In python, this consists of a loop like: while not_time_to_exit: try: run_main() except: log_problem() I.e. - you catch any otherwise uncaught exceptions, and log them so that you can fix whatever caused the problem later. This requires that you run_main resets the environment properly to avoid problems from leftover data in the python program. Of course, one way of doing that is relaunching the python program. not_time_to_exit depends on your environment. Proper signal handling is usually the way to deal with this. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jfouhy at paradise.net.nz Sun Jul 24 19:23:38 2005 From: jfouhy at paradise.net.nz (Repton) Date: 24 Jul 2005 16:23:38 -0700 Subject: return None In-Reply-To: References: <3kcpbbFtjttlU1@individual.net> Message-ID: <1122247418.319999.20220@f14g2000cwb.googlegroups.com> geon wrote: > Ximo wrote: > > Can I do a function which don't return anything? > Nothing is None, or isnt? A woodman was carrying a sack full of chopped wood on his back. His sack was heavy and filled beyond its limit. The man, bent under his bulky burden, was struggling not to drop any of the wood pieces as he walked. However, the poor man couldn't avoid tripping over a stone on the road and half of his load fell out of their precarious pile. Another man happened to be passing by and saw the mishap. `If I load those fallen pieces of wood back into your back sack, what would you give me?' he asked. `Nothing.' said the man carrying the wood. `That's acceptable.' agreed the other man. He collected all the chopped wood scattered on the road and crammed them back into the sack of the woodman. When done, he asked for his payment. The woodman was baffled. `I told you, I would give you nothing.' he said. `Yes. And that's what I want. Nothing.' said the other, `Give me my nothing!' After some quarrel, the two men decided to let the qadi solve their problem. Nasreddin Hodja was on duty at the time. He listened to both men earnestly. Then he addressed the man who was expecting his payment of nothing. `My dear fellow, could you please lift the far right corner of that rug on the floor and check what is underneath?' The man did as he was told and looked under the rug. `What do you see?' asked the Hodja. `Nothing.' said the man. 'Well, there's your payment.' said the Hodja. 'Take it and go!' -- John. From mjackson at alumni.caltech.edu Mon Jul 11 14:10:26 2005 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 11 Jul 2005 18:10:26 GMT Subject: Tricky Dictionary Question from newbie References: Message-ID: "Ric Da Force" writes: > It is hard to explain but this is what I mean: > > Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is > not'} > > I want this to return a new dict with string keys and lists containing the > previous keys for repeated values. > > NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson It is difficult for men in high office to avoid the malady of self-delusion. - Calvin Coolidge From nigel at jack-roe.co.uk Fri Jul 1 08:24:24 2005 From: nigel at jack-roe.co.uk (Nigel Rowberry) Date: Fri, 01 Jul 2005 13:24:24 +0100 Subject: New tapos test area for wxWindows 2.6.1 Message-ID: <42C535F8.7060100@jack-roe.co.uk> There is a new winbin for testing upgraded tapos - and it does need testing \\Blackbox\public\tapos\newwinbin-wx2.6.1 From sjmachin at lexicon.net Tue Jul 12 21:38:44 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 13 Jul 2005 11:38:44 +1000 Subject: Help with inverted dictionary In-Reply-To: <1121182712.452410.64240@g49g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> <1121182343.731328.38020@g47g2000cwa.googlegroups.com> <1121182712.452410.64240@g49g2000cwa.googlegroups.com> Message-ID: <42d470a4$1@news.eftel.com> rorley at gmail.com wrote: > I will transfer eventually use a database but is there any way for now > you could help me make the text files? Thank you so much. Reece > No. There is utterly no reason why you should create 5000 or 30000 text files. While you are waiting to get a clue about databases, do it in Python, in memory. It should only take a very tiny time to suck your 5000-fact file into memory, index the data appropriately, and do some queries e.g. list all facts about "lion". From caseyhHAMMER_TIME at istar.ca Sun Jul 10 21:06:27 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Mon, 11 Jul 2005 01:06:27 GMT Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: It is easier to write code a computer can understand than others can understand! It is harder to read code than to write code! -- Regards, Casey From rrr at ronadam.com Tue Jul 5 22:32:22 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 02:32:22 GMT Subject: flatten(), [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: > > We really ought to do this benchmark with a bigger list as input - a few > thousand elements, at least. But that would mean writing a function to > generate random nested lists, and that would mean specifying parameters > for the geometry of its nestedness, and that would mean exploring the > dependence of the performance of each flatten on each parameter, and > that would mean staying up until one, so i'm not going to do that. > > tom > Without getting to picky, would this do? import random import time random.seed(time.time()) def rand_depth_sequence(seq): for n in range(len(seq)): start = random.randint(0,len(seq)-2) end = random.randint(start,start+3) seq[start:end]=[seq[start:end]] return seq seq = rand_depth_seq(range(100)) print seq >>> [[[[[0, 1], 2, [3, [4, 5, 6]]], [7], [8, [[9, [], 10]]]], [11, [12]], [[[]]]], [[], [13, 14, 15]], [[[16, 17]]], [18], [[[19], 20, [[21, 22, [23]], [[24]]]], 25, 26], [], [27, 28], [], 29, [], [30, [31, 32, 33]], [34], [[35]], 36, [[37, 38, 39], [[40, 41], [[42]]]], [43, 44], 45, 46, [47, []], [[[48, 49], [50], [51]], 52], [[[53], [54, 55, [56, 57, 58]], []], [], []], [[59, 60, 61]], 62, [[63]], [], [64], [[[65]]], [[[66, 67, 68], [69, 70, [71, 72]], [[73, 74], [75, 76]]], [77, 78]], [], 79, 80, [[81], []], 82, [[[83, [[], 84], [85]], 86, [[87, 88]]], [[[89], 90, 91], [92, [93], [94, 95, 96]]]], [97, [98, 99]]] From devlai at gmail.com Tue Jul 12 11:20:54 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 08:20:54 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> Message-ID: <1121181654.281534.157000@g49g2000cwa.googlegroups.com> import re name = "Robert" f = file('phonebook.txt','r') lines = [line.rstrip("\n") for line in f.readlines()] pat = re.compile(name, re.I) related_lines = [line for line in lines if pat.search(line)] And then you write the lines in related_lines to a file. I don't really write text to files much so, um, yeah. From michael at stroeder.com Mon Jul 18 09:22:18 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 18 Jul 2005 15:22:18 +0200 Subject: Filtering out non-readable characters In-Reply-To: References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Peter Hansen wrote: >>>> ''.join(chr(c) for c in range(65, 91)) > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' Wouldn't this be a candidate for making the Python language stricter? Do you remember old Python versions treating l.append(n1,n2) the same way like l.append((n1,n2)). I'm glad this is forbidden now. Ciao, Michael. From dalloliogm at fastwebnet.it Thu Jul 7 06:26:08 2005 From: dalloliogm at fastwebnet.it (Giovanni Dall'Olio) Date: 7 Jul 2005 03:26:08 -0700 Subject: HELP! In-Reply-To: References: <20050707092141.5ED904BEAD@ws1-1.us4.outblaze.com> Message-ID: <1120731968.925061.157410@g49g2000cwa.googlegroups.com> Ahah, I've to save this page. p.s. @ Ert Ert: download this: http://starship.python.net/crew/mhammond/win32/ and use 'Pythonwin' (or, use Unix!) From cjw at sympatico.ca Fri Jul 1 09:26:27 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 01 Jul 2005 09:26:27 -0400 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <6wbxe.4188$Ai.611891@news20.bellglobal.com> BORT wrote: > Please forgive me if this is TOO newbie-ish. > > I am toying with the idea of teaching my ten year old a little about > programming. I started my search with something like "best FREE > programming language for kids." After MUCH clicking and high-level > scanning, I am looking at Python and Forth. Both have advocates that > say each is a great approach to learning computers. > > My programming classes were a long, long time ago in a land far, far > away. My programming muscles, which were never truly developed, have > atrophied even so. That said, I want to learn this as we go. The > PROCESS of research and using net resources for a self-learning > adventure is almost as much of the goal as learning a programming > skill. > > That said, a good learning goal for my kid would be to create a > spelling tutor for his little brother. My (simple) vision would be: > > 1. an input file of this week's word list > 2. use a free text-to-speech engine to call out one word at a time > 3. in turn, monitor each key press as a particular word is being > typed, beeping on an incorrect keystroke and going to the next word if > correct > > I don't care if it takes a year or two to get to this level, I just > want a vehicle that will take us there. > > I told my son, who wants to learn how to compute probabilities, that we > have to start with some boring stuff so we can learn how to do the cool > stuff. Adding and subtracting aren't really fun, but figuring odds on > rolling dice IS fun. Learning to program will be kind of like that. > He accepted that explantion. > > So, that said... In ~simplest~ terms for the stated goal -- Forth or > Python? > ....the goal is NOT the spelling tutor... it is learning how to use a > tool to solve a problem. I am asking which tool is more suited to an > otherwise arbitrary direction of "spelling tutor program." > > [NOTE: This is not a troll. I'm geting ready to bark up a tree and I > prefer to avoid the wrong one. I am cross-posting.] > > Thanks > As a pre-learning-Python stage you might use the Firefox browser: 1. Set up a text file with correctly spelled words. 2. Open that file with Firefox. 3. Ctrl F to open the search window at the bottom of the screen. 4. Enter each word to test. Fun? for the younger brother and a suggestion as to the functionality you might build into the second stage of your Python program. Colin W. From sjmachin at lexicon.net Sun Jul 10 20:29:40 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 11 Jul 2005 10:29:40 +1000 Subject: Codecs In-Reply-To: References: Message-ID: <42d1bd70@news.eftel.com> Ivan Van Laningham wrote: > > It seems to me that if I want to try to read an unknown file > using an exhaustive list of possible encodings ... Supposing such a list existed: What do you mean by "unknown file"? That the encoding is unknown? Possibility 1: You are going to try to decode the file from "legacy" to Unicode -- until the first 'success' (defined how?)? But the file could be decoded by *several* codecs into Unicode without an exception being raised. Just a simple example: the encodings ['iso-8859-' + x for x in '12459'] define *all* possible 256 characters. There are various language-guessing algorithms based on e.g. frequency of ngrams ... try Google. Possibility 2: You "know" the file is in a Unicode-encoding e.g. utf-8, have successfully decoded it to Unicode, and are going to try to encode the file in a "legacy" encoding but you don't know which one is appropriate? Sorry, same "But". From travislspencer at gmail.com Wed Jul 20 14:47:48 2005 From: travislspencer at gmail.com (travislspencer at gmail.com) Date: 20 Jul 2005 11:47:48 -0700 Subject: Printing a variable's name not its value Message-ID: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> Hey, I am trying to write a function that takes an arbitrary number of arguments and does one of two things. If the variable is a key in a dictionary, it prints the key and its value. Otherwise, if any of the variables isn't in the dictionary, the function prints the variable's name and value. Here is what I have so far: globals = {} HOME_DIR = "The user's home directory" SHELL = "The user's shell" def someFunction(): someString = "This is a test" globals[VERBOSE] = True globals[HOME_DIR] = os.getenv("HOME") globals[SHELL] = os.getenv("SHELL") printVerbose(someString, HOME_DIR, SHELL) def printVerbose(*args): if VERBOSE in globals: for a in args: value = "" if a in globals: value = globals[a] # else # a = a.__name__ # value = a print "%s: %s" % (a, value) This prints something like this: The user's home directory: /home/tspencer The use's shell: zsh But what I would like it to print is this: The user's home directory: /home/tspencer The use's shell: zsh someString: This is a test I've been told on #python that there isn't a way to get a variable's name. I hope this isn't so. If it helps, I am trying to do something like what the C preprocessor's # operator does. TIA. -- Regards, Travis Spencer From ville at spammers.com Thu Jul 7 16:10:53 2005 From: ville at spammers.com (Ville Vainio) Date: 07 Jul 2005 23:10:53 +0300 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: >>>>> "Fabio" == Fabio Zadrozny writes: >> I agree about the project management part. Though I would still love >> to use Eclipse instead, if it only was supported for my line of work >> :-/. Fabio> What line of work is not supported in eclipse? C++ programming for Symbian OS. Editing the C++ code works, debugging doesn't, at least yet. -- Ville Vainio http://tinyurl.com/2prnb From wesc at deirdre.org Thu Jul 28 12:49:31 2005 From: wesc at deirdre.org (wesc at deirdre.org) Date: 28 Jul 2005 09:49:31 -0700 Subject: ANN: Python training, 2005 Aug 29-31, San Francisco Message-ID: <1122569371.668156.209740@o13g2000cwo.googlegroups.com> What: Python Programming I: Introduction to Python When: August 29-31, 2005 Where: San Francisco, CA, USA Need to get up-to-speed with Python as quickly as possible? Come join us in beautiful Northern California the week before Labor Day. We are proud to announce another rigorous Python training event taught by software engineer and "Core Python Programming" author, Wesley Chun. This is an intense introduction to Python programming geared towards those who have some proficiency in another high-level language. Topics include: * Python's Objects and Memory Model * Data Types, Operators, and Methods * Errors and Exception Handling * Files and Input/Output * Functions and Functional Programming * Modules and Packages * Classes, Methods, and Class Instances * Callable and Executable Objects This course will take place daily August 29-31, 2005 (Monday through Wednesday, 9am - 5pm) in San Bruno, CA, right near the San Francisco International Airport at the: Staybridge Suites San Francisco Airport 1350 Huntington Ave San Bruno, CA 94066 650-588-0770 This venue provides free shuttles to/from the airport and has easy access to public transit (BART, CalTrain, SamTrans) to help you get all over the Bay Area. Afterwards, feel free to enjoy the holiday weekend in the greatest city by the Bay... bring your families!! For more information and registration, just go to http://cyberwebconsulting.com and click on the "Python Training" link. If you have any questions, feel free to contact us at cyberweb-at-rocketmail.com. From wl at flexis.de Thu Jul 7 08:19:38 2005 From: wl at flexis.de (Wolfgang Langner) Date: Thu, 07 Jul 2005 14:19:38 +0200 Subject: VC++ linking problem In-Reply-To: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> References: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> Message-ID: Hello Jochen, > I started embedding python into a 3D graphics App and I came > across this linking problem. > > > SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol > __imp__Py_InitModule4TraceRefs > SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol > __imp___Py_RefTotal > SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol > __imp___Py_RefTotal > > I am linking against python24.lib using VC++ 6.0. Before I got to this > point it couldn't find python24_d.lib. After searching around > for a while I came across a solution that included changing > python24_d.lib to python24.lib in one of the header files. I hope that > didn't have a negative effect. I would really appreciate > some help.... Be careful, python 2.4 is build with VC++ 7.1. Mixing this in your application which is build with VC++ 6.0 can lead to trouble. python24_d.lib is the debug version of the python library. It's possible to build your application in debug against a release Python Version. But I don't know what switches are needed. This unresolved external symbols are a result of your linkage. This symbols are only present in the debug version of the library. If you start python_d.exe (debug executable of python) you get the total ref count after every statement. To fix this, build debug version of your App against debug version of python or set all switches to build a debug version against release python. The boost python library does this, see: http://www.boost.org/libs/python/doc/index.html bye by Wolfgang From callmebill at gmail.com Thu Jul 21 10:44:16 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 21 Jul 2005 07:44:16 -0700 Subject: Stupid question: Making scripts python-scripts In-Reply-To: <1121956897.727721.38050@g47g2000cwa.googlegroups.com> References: <42dfb111@griseus.its.uu.se> <1121956897.727721.38050@g47g2000cwa.googlegroups.com> Message-ID: <1121957056.060094.54230@g43g2000cwa.googlegroups.com> oops... I missed the "too specific comment." Sorry =) From thomas at thomas-lotze.de Tue Jul 12 21:49:16 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Wed, 13 Jul 2005 03:49:16 +0200 Subject: Frankenstring References: <42d43047$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Now if you want to do it for a file, you could do: > > for c in thefile.read(): > .... The whole point of the exercise is that seeking on a file doesn't influence iteration over its content. In the loop you suggest, I can seek() on thefile to my heart's content and will always get its content iterated over exactly from beginning to end. It had been read before any of this started, after all. Similarly, thefile.tell() will always tell me thefile's size or the place I last seek()'ed to instead of the position of the next char I will get. -- Thomas From spam.csubich+block at block.subich.spam.com Mon Jul 4 13:50:57 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Mon, 04 Jul 2005 13:50:57 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: <1120469031.112811.112950@g44g2000cwa.googlegroups.com> References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> <1120424454.854518.100610@o13g2000cwo.googlegroups.com> <1120469031.112811.112950@g44g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > I suspect you're misunderstanding what I mean by heavily functional. > Heavily functional programming is a different mindset altogether. In > heavily functional programming, things like maps and filters and > function applications are actually what you're thinking about. map > isn't an indirect way to do a for loop; it's a direct way to do a map. That's true; I'm more comfortable with procedural programming in general, but I had a few classes that used LISP and understand what you're talking about. That said, Python itself is mostly a procedural language, with the functional tools really being bolted on[1]. When we're talking about Py3K, I think we're really talking about a redesign and rethink of pretty much the entire language -- with list and generator comprehensions, for procedural programming the need for map and lambda goes away. Reduce isn't directly replaced, of course, but a for-loop implementation (for procedural programming) is clearer, more powerful, more explicit, and possibly faster. That said, I very much like the idea of putting map and filter in a functional module. For applications like functional-style programming where map/etc are clearer, that keeps them in the library for efficient use, yet it leaves the native language with OO(g)WTDI [Only One (good) Way to Do It]. [1] -- lambda excepted. I think it's kind of cute, in a baby-mammal kind of way. From steve at REMOVETHIScyber.com.au Sat Jul 9 22:48:51 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 10 Jul 2005 12:48:51 +1000 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: On Sat, 09 Jul 2005 23:10:49 +0200, Thomas Lotze wrote: > Steve Juranich wrote: > >> I was wondering how true this holds for Python, where exceptions are such >> an integral part of the execution model. It seems to me, that if I'm >> executing a loop over a bunch of items, and I expect some condition to >> hold for a majority of the cases, then a "try" block would be in order, >> since I could eliminate a bunch of potentially costly comparisons for each >> item. > > Exactly. > >> But in cases where I'm only trying a single getattr (for example), >> using "if" might be a cheaper way to go. > > Relying on exceptions is faster. In the Python world, this coding style > is called EAFP (easier to ask forgiveness than permission). You can try > it out, just do something 10**n times and measure the time it takes. Do > this twice, once with prior checking and once relying on exceptions. True, but only sometimes. It is easy to write a test that gives misleading results. In general, setting up a try...except block is cheap, but actually calling the except clause is expensive. So in a test like this: for i in range(10000): try: x = mydict["missing key"] except KeyError: print "Failed!" will be very slow (especially if you time the print, which is slow). On the other hand, this will be very fast: for i in range(10000): try: x = mydict["existing key"] except KeyError: print "Failed!" since the except is never called. On the gripping hand, testing for errors before they happen will be slow if errors are rare: for i in range(10000): if i == 0: print "Failed!" else: x = 1.0/i This only fails on the very first test, and never again. When doing your test cases, try to avoid timing things unrelated to the thing you are actually interested in, if you can help it. Especially I/O, including print. Do lots of loops, if you can, so as to average away random delays due to the operating system etc. But most importantly, your test data must reflect the real data you expect. Are most tests successful or unsuccessful? How do you know? However, in general, there are two important points to consider. - If your code has side effects (eg changing existing objects, writing to files, etc), then you might want to test for error conditions first. Otherwise, you can end up with your data in an inconsistent state. Example: L = [3, 5, 0, 2, 7, 9] def invert(L): """Changes L in place by inverting each item.""" try: for i in range(len(L)): L[i] = 1.0/L[i] except ZeroDivisionError: pass invert(L) print L => [0.333, 0.2, 0, 2, 7, 9] - Why are you optimizing your code now anyway? Get it working the simplest way FIRST, then _time_ how long it runs. Then, if and only if it needs to be faster, should you worry about optimizing. The simplest way will often be try...except blocks. -- Steven. From tdelaney at avaya.com Thu Jul 28 04:07:30 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 28 Jul 2005 18:07:30 +1000 Subject: functions without parentheses Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CBA2@au3010avexu1.global.avaya.com> Jerry He wrote: > def examine(str): > ..... > ..... > > Is there some way to define it so that I can call it > like > > examine "string" > instead of examine("string")? No. Python's syntax does not work that way. Why would you want to? For more information about this, read: http://www.catb.org/~esr/faqs/smart-questions.html You can create properties on classes which call a function when you get, set or delete them. class Test (object): def _getX (self): return self.__x def _setX (self, value): self.__x = value x = property(fget=_getX, fset=_setX) t = Test() t.x = 1 print t.x Note that this is almost completely different to what you asked about. Tim Delaney From upadhyay at gmail.com Thu Jul 28 02:40:36 2005 From: upadhyay at gmail.com (upadhyay at gmail.com) Date: 27 Jul 2005 23:40:36 -0700 Subject: how to get function signature Message-ID: <1122532836.853488.286030@g14g2000cwa.googlegroups.com> Hi, I was working on a dir like function that gives more information than the usual dir, but I am not satisfied with the way I get function arguments for callable members of an object. Take a look at it here: http://nerdierthanthou.nfshost.com/2005/07/mdir-for-python.html. I have seen PythonWin showing function arguments as tooltips, can anyone please let me know how to get it. TIA, -- Amit Upadhyay Blog: http://www.rootshell.be/~upadhyay +91-9867-359-701 From steve at REMOVETHIScyber.com.au Sun Jul 24 13:45:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 25 Jul 2005 03:45:23 +1000 Subject: tuple to string? References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> <42e381a6@news.eftel.com> Message-ID: On Sun, 24 Jul 2005 21:55:19 +1000, John Machin wrote: >>>Look up the precedence rules? Are you aware of any language where * / >>>and % _don't_ have the same precedence?? >> >> >> Do languages like Pascal that don't have string formatting expressions, or >> use the % operator, count? > > A thousand pardons; I should have said "Are you aware of any language > which has % (as primarily a numeric remainder/modulo operator) but * / > and % _don't_ have the same precedence??" [slaps head] Ah, I had completely forgotten that Pascal has a MOD operator that is equivalent to % and has the same precedence as * / and DIV. So scratch Pascal off the list. But APL uses right-to-left precedence for all operators, and Forth uses left-to-right. There may be others. > OK, given a language which does have * and / used among other things for > numerical multiply and divide, (a) are you aware of any such language > which does does not have * and / at the same precedence level (b) > supposing one wanted to introduce % as a numerical > remainder/modulo/whatever operator (plus other meaning(s) for > non-numeric types), would you care to argue that it should not have the > same precedence level (as * and /)? Yes I would. Since the remainder (or modulo) operator is not distributive, the only unambiguous usage is to use parentheses, or to decide on precedence rules. The usual mathematical convention is that modulus has lower precedence than addition, eg in "clock arithmetic" we expect that three hours after ten is one: 10+3 modulo 12 is 1, not 13. -- Steven. From http Sun Jul 31 07:57:09 2005 From: http (Paul Rubin) Date: 31 Jul 2005 04:57:09 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> <7xhdebv1t0.fsf@ruckus.brouhaha.com> <87vf2rpc0i.fsf@wilson.rwth-aachen.de> <7xy87nw75w.fsf@ruckus.brouhaha.com> <87r7dfp58w.fsf@wilson.rwth-aachen.de> Message-ID: <7xpsszdw8a.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > >>>> Does py2exe work for all GUI libraries? > >>> No, it's Windows-only. > I didn't ask "does it work with OSX" but "does it work with wxPython > or PyQt". py2exe only creates Windows files, that's right, but why > is this important here? You asked whether it works with all GUI libraries. If the context limited "all" to "wxPython or PyQt", I missed that. At any rate, I believe it does work with wxPython under Windows. I don't know about PyQt. It doesn't work with any non-Windows libraries. From correia_jREMOVECAPS at hotmail.com Tue Jul 26 18:43:21 2005 From: correia_jREMOVECAPS at hotmail.com (J Correia) Date: Tue, 26 Jul 2005 22:43:21 GMT Subject: Using win32com for web automation References: <1122399814.174328.63980@g43g2000cwa.googlegroups.com> Message-ID: > from win32com.client import Dispatch > from time import sleep > > ie = Dispatch('InternetExplorer.Application') > ie.Visible = 1 > ie.Navigate("http://ispds-sepsr.prv:7500/cs/welcome.jsp") > > while ie.ReadyState != 4: > sleep(1) > > doc = ie.Document > > while doc.readyState != "complete": > sleep(1) > > doc.loginForm.name.value = 'username' > doc.loginForm.password.value = 'password' > doc.loginForm.loginform.action = '/cs/login.do' I can't get to that site to test. Try the following instead of the last line above: doc.loginForm.submit() From duncan.booth at invalid.invalid Fri Jul 22 12:20:01 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jul 2005 16:20:01 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Peter Hansen wrote: > Duncan, are you another formerly non-user of path who has this opinion, > or have you already attempted to use path extensively in your code? I'm a currently non-user of path who would probably use it if it were in the standard library but so far have been satisfied to use os.path. > I'm not saying I dismiss the opinions of those who haven't actually > tried working with a string-based path object, but it's worth > considering that you might adopt a different opinion after using it for > a while. I fully accept that. My point is simply that as a non-user, it sounds to me as though subclassing string is the wrong approach. I would have expected a path object to be a sequence of path elements rather than a sequence of characters. This is basically just a gut feeling though, so I'm perfectly happy to be told that I'm wrong. BTW, does it matter at all in practical use that the base class of path varies between str and unicode depending on the platform? John Roth wrote: > You have to start somewhere. One of the lessons that's beginning > to seep into people's minds is that getting something that works > out there is almost always preferable to (over) design by committee. Dead right, but once it goes into the standard library it has to pretty well stop evolving, so it needs to be right, or as close as possible before that happens. From spam.csubich+block at block.subich.spam.com Wed Jul 20 03:01:50 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 20 Jul 2005 03:01:50 -0400 Subject: main window in tkinter app In-Reply-To: References: Message-ID: <0FmDe.8922$TU.2673@bignews1.bellsouth.net> William Gill wrote: > O.K. I tried from scratch, and the following snippet produces an > infinite loop saying: > > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1647, in __getattr__ > return getattr(self.tk, attr) > > If I comment out the __init__ method, I get the titled window, and print > out self.var ('1') > > > import os > from Tkinter import * > > class MyApp(Tk): > var=1 > def __init__(self): > pass > def getval(self): > return self.var > > > app = MyApp() > > app.title("An App") > print app.getval() > app.mainloop() You're not calling the parent's __init__ inside your derived class. I would point out where the Python Tutorial points out that you should do this, but it's not in the obvious place (Classes: Inheritance). Python does -not- automagically call parent-class __init__s for derived classes, you must do that explicitly. Changing the definition of your class to the following works: >>> class MyApp(Tk): var=1 def __init__(self): Tk.__init__(self) pass def getval(self): return self.var It works when you comment out __init__ because of a quirk in Python's name resolution. As you'd logically expect, if you don't define a function in a derived class but call it (such as instance.method()), it will call the method from the base class. You just proved that this works for __init__ methods also. When you didn't define __init__ for your derived class, MyApp() called Tk.__init__(), which Does the Right Thing in terms of setting up all the specific Tkinter-specific members. From grante at visi.com Fri Jul 1 11:16:50 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jul 2005 15:16:50 -0000 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> Message-ID: <11canj26edeni84@corp.supernews.com> On 2005-06-30, Ivan Van Laningham wrote: >> As other have noted, C was never really used for everything. Unix >> tools were designed to connect together from the very beginning, which >> is what makes shell scripting so powerful. This was true before there >> was a C. Likewise, some things you need more control over the machine >> than you get in C - those are still done in assembler. These days, C >> compilers let you embed assembler statements in your C, so some of >> these things are done in such variants. > > It really was used "for everything"; I think there are two intepretations of C being "used for everthing". My reading of that phrase is that nothing else was used: there were no shell scripts, no awk scripts, no FORTRAN programs, no JCL, no COBOL, no Lisp, no sed. That just was never the case. There never was a C-language monoculture in any OS. Another possible interpretation is that at some point in the past, there was some misguided soul who has tried to use C for every type of task imaginable. That's probably true, but the same could be said of any language. -- Grant Edwards From danb_83 at yahoo.com Wed Jul 6 12:45:48 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 6 Jul 2005 09:45:48 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1120621580.107813.47100@g43g2000cwa.googlegroups.com> <1120665674.114022.180500@g44g2000cwa.googlegroups.com> Message-ID: <1120668348.657769.61760@g14g2000cwa.googlegroups.com> Devan L wrote: > > Here's a couple of examples from my own code: > > > > # from a Banzhaf Power Index calculator > > # adds things that aren't numbers > > return reduce(operator.add, > > (VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes)) > > return sum([VoteDistributionTable({0:1, v:1} for v in > electoral_votes],VoteDistributionTable({})) > Any time you use operator.add, you can probably use > sum(sequence,initialvalue) Actually, it's sum([VoteDistributionTable({0:1, v:1}) for v in electoral_votes], VoteDistributionTable({0: 1})) but you're right about being able to use sum here. > > # from a custom numeric class > > # converts a tuple of digits into a number > > mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) > > I'll admit I can't figure out a way to replace reduce without writing > some ugly code here, but I doubt these sorts of things appear often. Of the quarter-megabyte of my Python code currently on my hard drive, I can find two reduces that can't be replaced by sum, product, any, or all. The other one is return reduce(lambda x, y: x << 1 | y, bits) From http Sun Jul 31 20:02:45 2005 From: http (Paul Rubin) Date: 31 Jul 2005 17:02:45 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <87ek9fr0c3.fsf@wilson.rwth-aachen.de> <86ack2hkol.fsf@bhuda.mired.org> Message-ID: <7xr7dele1m.fsf@ruckus.brouhaha.com> Mike Meyer writes: > I think you're the first person I've heard call IDLE an IDE. Then > again, I don't pay much attention to it. I use IDLE all the time and it wouldn't have occurred to me that it's something other than an IDE. It's not very good, but that's a different matter. From nyamatongwe at gmail.com Sat Jul 16 21:16:05 2005 From: nyamatongwe at gmail.com (Neil Hodgson) Date: Sun, 17 Jul 2005 11:16:05 +1000 Subject: odd python/linux/cherrypy behavior In-Reply-To: <797fe3d405071616541294503@mail.gmail.com> References: <797fe3d405071616541294503@mail.gmail.com> Message-ID: <50862ebd05071618161946038c@mail.gmail.com> Bill Mill: > Definitely not mounted with short file names, and there aren't any > non-ASCIIs in the file names; in both cases I imagine that the file > wouldn't run at all. In this case, however, the file does run, and > open a socket, it just can't seem to receive connections on it. I have > tried running the file as su, with no success. Works for me as root or unprivileged user using CherryPy-2.1.0-beta. > The FAT dirs are mounted with the following options: > defaults,user,umask=000 . From fstab: /dev/hda6 /win vfat utf8,shortname=winnt You may have some file content transformation such as \r\n->\n translation (conv=text) occurring. > I'm not sure what you mean by the execute > bit, but all files do have execute permission. Here's the output of an > ls -l on the file I'm talking about: > > -rwxrwxrwx 1 root root 1073 2005-07-15 21:40 > /d/download/cherrypy/tutorial/tut01_helloworld.py -rwxr-xr-x 1 root root 1074 Jun 26 17:28 tut01_helloworld.py Here is the output from the run [root at localhost tutorial]# python tut01_helloworld.py 2005/07/17 11:01:33 CONFIG INFO Reading infos from configFile: tutorial.conf 2005/07/17 11:01:33 CONFIG INFO Server parameters: 2005/07/17 11:01:33 CONFIG INFO server.environment: production 2005/07/17 11:01:33 CONFIG INFO server.logToScreen: True 2005/07/17 11:01:33 CONFIG INFO server.logFile: 2005/07/17 11:01:33 CONFIG INFO server.protocolVersion: HTTP/1.0 2005/07/17 11:01:33 CONFIG INFO server.socketHost: 2005/07/17 11:01:33 CONFIG INFO server.socketPort: 8080 2005/07/17 11:01:33 CONFIG INFO server.socketFile: 2005/07/17 11:01:33 CONFIG INFO server.reverseDNS: False 2005/07/17 11:01:33 CONFIG INFO server.socketQueueSize: 5 2005/07/17 11:01:33 CONFIG INFO server.threadPool: 10 2005/07/17 11:01:33 HTTP INFO Serving HTTP on socket: ('', 8080) 2005/07/17 11:01:56 HTTP INFO 127.0.0.1 - GET / HTTP/1.1 2005/07/17 11:01:56 HTTP INFO 127.0.0.1 - GET /favicon.ico HTTP/1.1 Neil From steve at REMOVETHIScyber.com.au Sat Jul 2 21:47:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 11:47:07 +1000 Subject: Assigning to None (was Re: Question about Python) References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> Message-ID: On Fri, 01 Jul 2005 12:59:20 -0400, Fran?ois Pinard wrote: > [Peter Hansen] >> Mike Meyer wrote: >> > Yes. I once grabbed an old program that did assignments to None. But >> > that's always been a bad idea. > >> What was the use case!? > > People used to assign None to itself as a keyword argument in function > headers. The goal was to make a local copy of the reference, which was > then accessed faster than the global thing. Can you say "premature optimization is the root of all evil"? I'd like to see the profiling that demonstrated that this made a significant -- or even measurable -- speed-up in anything but the most unusual cases. -- Steven From steveg at moregruel.net Thu Jul 28 17:26:33 2005 From: steveg at moregruel.net (Steve Greenland) Date: 28 Jul 2005 21:26:33 GMT Subject: poplib.POP3.list() returns extra value? Message-ID: <42e94d88$0$544$a726171b@news.hal-pc.org> For the poplib.POP3 object, docs say: list([which]) Request message list, result is in the form (response, ['mesg_num octets', ...]). If which is set, it is the message to list. But (I've folded the long line): Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import poplib >>> p = poplib.POP3("annie") >>> p.user("poptest") '+OK' >>> p.pass_("poptest") '+OK' >>> p.list() ('+OK', ['1 2680', '2 2720', '3 9996', '4 23368', '5 2267', '6 2661', '7 4925', '8 2548', '9 10114', '10 1850', '11 14239', '12 6678', '13 6592', '14 10011', '15 3554', '16 5764', '17 5080', '18 9998', '19 2056', '20 6354', '21 3031', '22 2868', '23 6325', '24 2566', '25 4827', '26 2995', '27 2963', '28 2548', '29 9138', '30 2408', '31 2245', '32 2547', '33 2439', '34 9816', '35 2584', '36 10259', '37 1997', '38 4930', '39 1859', '40 9105', '41 6649', '42 6776', '43 2338', '44 17808', '45 4960', '46 1785', '47 2123', '48 2011', '49 9124', '50 1910', '51 1307', '52 18869', '53 2507', '54 19099', '55 2328', '56 2069', '57 1654', '58 2346', '59 2891', '60 1865', '61 9334'], 548) >>> Note the trailing ", 548". By symmetry with the POP3.retr() function, I'll guess that it's the number of octets in the response; it gets bigger with more messages. I've tried this against three different servers (popa3d, some version of Exchange, whatever's on RedHat 7.2), and two versions of python (2.3.5 on Debian sarge, 2.2 on AIX 5.1) and it's the same on all of them. It could be that I'm insane, but I'd prefer to believe this is a doc error that no one ever noticed because everybody uses POP3.list()[1]. You be the judge! Steve -- Steve Greenland The irony is that Bill Gates claims to be making a stable operating system and Linus Torvalds claims to be trying to take over the world. -- seen on the net From http Sat Jul 30 15:06:43 2005 From: http (Paul Rubin) Date: 30 Jul 2005 12:06:43 -0700 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> Message-ID: <7xmzo4nmf0.fsf@ruckus.brouhaha.com> Peter Hansen writes: > The last time I checked (as I recall), at least Wax and possibly Dabo > both either lagged well behind recent wxPython developments of provide > relatively limited support, leaving out a sizable and (to me) > important number of features from what they wrapped. wxPython also depends on wxWidgets which lags behind GTK. From cam.ac.uk at mh391.invalid Fri Jul 22 19:49:17 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 23 Jul 2005 00:49:17 +0100 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Practically everything that path does, with a few useful exceptions, is > a thin wrapper around the existing calls. If the implementation is easy to explain, it may be a good idea. OT: I just realized you can now type in "python -m this" at the command line, which is convenient, but strange. -- Michael Hoffman From peter at engcorp.com Tue Jul 5 19:04:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Jul 2005 19:04:04 -0400 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120603785.494300.180940@g49g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > The problem is that questions like 'What lang is fastest to develop > in?' are hard to answer definitively. That's because the answer depends on lots of context such what is the problem domain and who is the programmer. Really, it's an impossible question to answer. Measuring two different programmers with two different languages would give useless results, since you can't ensure the two programmers are equally capable. Using the same programmer for the same problem with two different languages doesn't work since she would learn from doing it the first time and inevitably have advantages in the second time through. Using two different problems is of course pointless as well. Ultimately, however, the question needs no answer, since "speed of development" is not the only or even the most important factor in development. Take into account issues of maintainability, quality of code, performance and such, and you've muddied the question even more, making this a religious question and one that has no meaningful answer, nor a need to be answered in a simple way. For *me*, Python has proven to be the fastest language to develop in, so far, but it's quite possible to imagine another language in the future which I might learn which would be -- for me -- even faster, at least for certain types of problems. (But so what? :-) ) -Peter From supercomputer at gmail.com Mon Jul 18 13:13:39 2005 From: supercomputer at gmail.com (supercomputer at gmail.com) Date: 18 Jul 2005 10:13:39 -0700 Subject: ssh popen stalling on password redirect output? In-Reply-To: <42DB8FCE.1040500@draigBrady.com> References: <1121455648.644398.286910@g47g2000cwa.googlegroups.com> <42DB8FCE.1040500@draigBrady.com> Message-ID: <1121706819.236730.57730@z14g2000cwz.googlegroups.com> Thanks for the help, this gives me a few options. I think the best way to do it is using the public/private key authentication. From darenr at end-design.co.uk Thu Jul 21 06:23:46 2005 From: darenr at end-design.co.uk (Daren Russell) Date: Thu, 21 Jul 2005 11:23:46 +0100 Subject: Generating images with text in them In-Reply-To: References: Message-ID: phil hunt wrote: > I am trying to generate some images (gifs or pngs) with text in > them. I can use the Python Imaging Library, but it only has access > to the default, rather crappy, font. > > Ideally I'd like to use one of the nicer fonts that come with my X > Windows installation. Using Tkinter I can draw these fonts on the > screen; is there any way to get these fonts into a bitmapped image? > For example, can I draw some text on a canvas and then "grab" that > canvas as a bitmap into PIL, and then save it as a file? > > Alternately, is there a good source of PIL font files (.pil files) > somewhere? > > If the writers of the Python Imaging Library are reading this, may I > suggest that they add more fonts to it. Yes, that would increase > the size, but these days disk space is cheap and programmer time > expensive. > I've just been playing around with this. You can use truetype fonts with: font = ImageFont.truetype("/path/to/font.ttf", 12) from version 1.1.4 http://www.pythonware.com/library/pil/handbook/imagefont.htm for more details HTH Daren From mhuening at zedat.fu-berlin.de Mon Jul 4 05:06:57 2005 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Mon, 04 Jul 2005 11:06:57 +0200 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <3isccmFn15f2U1@uni-berlin.de> jwaixs (04.07.2005 10:04): > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! Did you try this one? http://www.amk.ca/python/howto/regex/regex.html >>>>import re >>>>str = "blablaRe modules sucks!blabla" >>>>re.search("()(/python>)", str).group() > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'NoneType' object has no attribute 'group' RE doesn't find "()(/python>)" because it isn't in your string. That's why group fails. >>> import re >>> s = "blablaRe module is great!blabla" >>> re.search("().*(/python>)", s).group() 'Re module is great!' Matthias From jepler at unpythonic.net Thu Jul 21 21:07:00 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 21 Jul 2005 20:07:00 -0500 Subject: Difference between " and ' In-Reply-To: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: <20050722010657.GA24716@unpythonic.net> The only difference is when you want to include " or ' inside the string. If you want to include the "like" quote, then escape it ("\"", '\''). If you include the "unlike" quote, no escape is needed ("'" or '"'). I think that people new to programming will use '' if it is unshifted on their keyboards. People from a "C" background may use "" for strings (since in that language, '' is for a single character only). Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cam.ac.uk at mh391.invalid Fri Jul 22 09:56:47 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 14:56:47 +0100 Subject: time.time() under load between two machines In-Reply-To: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> Message-ID: kwharrigan at yahoo.com wrote: > I am working on some code using python and a distributed system. Some > particular message is sent on one machine (with a timestamp logged) and > after the message is received, a timestamp is made. I am having > problems with negative latencies happening under intense CPU load. How negative are we talking about? What platforms are you using? -- Michael Hoffman From Aiwass333 at gmail.com Mon Jul 25 09:38:02 2005 From: Aiwass333 at gmail.com (RunLevelZero) Date: 25 Jul 2005 06:38:02 -0700 Subject: Try this In-Reply-To: References: <1122232247.337991.322150@o13g2000cwo.googlegroups.com> Message-ID: <1122298682.803035.252080@g47g2000cwa.googlegroups.com> Indeed.. I did click reply but I guess I wasn't paying attention. My bad. From Holzmayer.Bernhard at deadspam.com Thu Jul 14 06:53:43 2005 From: Holzmayer.Bernhard at deadspam.com (Bernhard Holzmayer) Date: Thu, 14 Jul 2005 12:53:43 +0200 Subject: Splitting on a word References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> Message-ID: qwweeeit at yahoo.it wrote: > Hi all, > I am writing a script to visualize (and print) > the web references hidden in the html files as: > ' underlined reference' > Optimizing my code, I found that an essential step is: > splitting on a word (in this case 'href'). > > I am asking if there is some alternative (more pythonic...): Sure. The htmllib module provides HTMLparser. Here's an example, run it with your HTML file as argument and you'll see a list of all href's in the document. #------------------------------------------------ #!/usr/bin/python import htmllib def test(): import sys, formatter file = sys.argv[1] f = open(file, 'r') data = f.read() f.close() f = formatter.NullFormatter() p = htmllib.HTMLParser(f) p.feed(data) for a_link in p.anchorlist: print a_link p.close() test() #------------------------------------------------ I'm sure that this is far more Pythonic! Bernhard From roccomoretti at hotpop.com Fri Jul 29 10:42:15 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 29 Jul 2005 09:42:15 -0500 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Asad Habib wrote: > Well, even if you are a hobbyist, that does not excuse you from being > civil. After all, we are all humans beings that deserve to be treated with > respect. Professional, hobbyist, vagabond, ogre, instigator, troll ... > THERE IS NO EXCUSE ... please treat others with respect. I really don't think we're disagreeing. I agree that it is inappropriate, regardless of position or experience, to be rude, hostile, or vitriolic on this newsgroup. And it should be made clear to people who are, that it isn't appropriate. However, in doing so, it is also inappropriate to become rude, hostile, or vitriolic oneself - as Skip mentioned in the post that started all this, the appropriate way of handling it is by demonstrating proper behavior yourself. If, for whatever reason, you do find the desire to be rude, hostile, or vitriolic, you can satisfy your urge by writing out your rant and then deleting it. You'll feel better by getting it off your chest, and you won't have escalated anything. The reason I point out the hobbyist issue is to disabuse people of the misperception that everyone on this list is adhering to some professional code of conduct that they should be ostracized for breaching. This isn't to excuse their behavior - I'm just pointing out that people are coming from different backgrounds, and that we should treat them with consideration and respect, even when they aren't showing us any. From tim at pollenation.net Tue Jul 19 16:05:48 2005 From: tim at pollenation.net (Tim Parkin) Date: Tue, 19 Jul 2005 21:05:48 +0100 Subject: Web Framework Reviews In-Reply-To: <1121796584.974756.132430@g14g2000cwa.googlegroups.com> References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121796584.974756.132430@g14g2000cwa.googlegroups.com> Message-ID: <42DD5D1C.6090901@pollenation.net> istvan.albert at gmail.com wrote: > One remark regarding stan. For me it is inconceivable that one would > build (and debug) any complicated webpage as stan does it, one element > at a time: > > docFactory = loaders.stan( > t.html[t.head[t.title["Session example"]], > t.body[display_session]] > ) > > The pages that I have to build invariably contain multiple nested html > tables etc. I shudder to think that I would ever have to build them > like that. I know you have an "inverse" ZPT like templates those are a > lot friendlier on the eyes. For someone who is does not know what Nevow > is seeing an example of Stan is very scary because IMO it does not > scale at all. This again is just an opinion. Firstly, I don't know of anyone who has built whole sites out of stan (it's not what it was created for). Although if built in a modular fashion I don't see why this would have problems 'scaling' or would be more difficult to visualise than a the equivalent tag soup html. Also it depends on what you mean by scale. We built a site for one of the biggest rugby sites in the world (over 300 requests per second). This uses a combination of stan and xhtml templates. Before we rebuilt the site using CSS layout (which you really should be looking at using to avoid the multiple nested tables you mention - which I presume are layout related) we were using client supplied html which was nested more than 10 levels deep. Most of this we were able to leave in the html and allow the client to manage via ftp. The bits that were dynamic were 'templated up' by putting slots and renderers. Nevow avoids any programmatic logic in the templates which means that all logic is directly in your python code (avoiding one of templating languages biggest faults - that of implementing *another* language just for templates). Templates now become a repository of html which is marked up with insert points, replacement points, patterns to reuse, etc. Sometimes you need to generate some dynamic html that won't easily and clearly fit into this 'extract patterns, replace sections, etc' pattern. When this happens you can either include bits of html as strings (yeuch!) *or* use stan. Stan enables you to create small sections of dynamic html without recourse to templating languages or marking up tiny fragments of html for re-use. This section of code from the nevow forms library (this is a widget for file uploads). if name: if self.preview == 'image': yield T.p[value,T.img(src=self.fileHandler.getUrlForFile(value))] else: yield T.p[value] else: yield T.p[T.strong['nothing uploaded']] yield T.input(name=namer('value'),value=value,type='hidden') yield T.input(name=key, id=keytocssid(ctx.key),type='file') In other systems, this would have to be part of the template (via inline python or some alternative programming syntax), marked up as html in string elements (liable to validation errors and difficult to manage) or small fragments of html would have to be marked up as patterns and then manipulated in some fashion. The last is possible using nevow and the manipulation can be done directly on the produced html -- or via stan!! (think of manipulating a dom'ish like object). Tim Parkin From CantankerousOldGit at gmail.com Wed Jul 27 16:54:11 2005 From: CantankerousOldGit at gmail.com (Cantankerous Old Git) Date: Wed, 27 Jul 2005 21:54:11 +0100 Subject: question about deleting records from mysql In-Reply-To: References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> <42E7720E.90307@xit.net> <1122466366.005107.303840@z14g2000cwz.googlegroups.com> <42E7816C.5080501@fielden.com.au> Message-ID: nephish wrote: > Man, thanks for the link. and the tip. i am testing > the db.commit() and printing the doc right now. > thanks again. If it's any help, using cursor.execute("set autocommit = 1") before doing anything else works nicely unless you actually need transactions. The Cog From sjmachin at lexicon.net Fri Jul 22 18:51:55 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 08:51:55 +1000 Subject: tuple to string? In-Reply-To: <3kd89rFte1h5U1@individual.net> References: <3kd89rFte1h5U1@individual.net> Message-ID: <42e1788b@news.eftel.com> Reinhold Birkenfeld wrote: > Berthold H?llmann wrote: > >>Francois De Serres writes: >> >> >>>hiho, >>> >>>what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) >>>to the string 'spam'? >> >>.>>> t = (0x73, 0x70, 0x61, 0x6D) >>.>>> ''.join('%c' % c for c in t) >>'spam' > > > Or: > > t = (0x73, 0x70, 0x61, 0x6D) > ('%c' * len(t)) % t You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-) From steve at REMOVETHIScyber.com.au Fri Jul 29 19:40:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 30 Jul 2005 09:40:23 +1000 Subject: On fighting fire with fire... References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: On Thu, 28 Jul 2005 15:23:46 -0500, Rocco Moretti wrote: > Professionals (and even decent hobbyists) don't > escalate flame wars, even unintentionally. You don't get out much, do you? *wink* If your comment is meant to be _prescriptive_ rather than _descriptive_, I don't entirely agree. Flame wars, like all wars, are unproductive beyond a certain point, but to push the combat analogy, punitive raids can be productive at changing behaviour. It is never pleasant to be on the receiving end of a flaming, but if it is deserved, then people should accept it and learn from it, rather than just dismiss it as a flaming and therefore meaningless. The problem on the Internet is that there is little or no status: the most ignorant newbie and the stupidest AOLer think that they are equal in status to somebody who has proven their knowledge for ten years. (This lack of status on the Internet is not *always* a bad thing, but it can be.) If your boss or professor or a judge gave you a tongue-lashing for stupid behaviour, sensible people accept it. "I've been bad, I got caught, thank goodness I'm suffering nothing worse than being told I'm an idiot." At worst they might complain to their friends afterwards. But on the Internet, people who deserve that tongue-lashing think that because they can retaliate, they should retaliate -- and that's where the risk of escalation from punitive raid to unproductive flame war lies. -- Steven. From peter at engcorp.com Wed Jul 13 20:53:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 20:53:58 -0400 Subject: Efficiently Split A List of Tuples In-Reply-To: References: Message-ID: Richard wrote: > I have a large list of two element tuples. I want two separate > lists: One list with the first element of every tuple, and the > second list with the second element of every tuple. Variant of Paul's example: a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) zip(*a) or [list(t) for t in zip(*a)] if you need lists instead of tuples. (I believe this is something Guido considers an "abuse of *args", but I just consider it an elegant use of zip() considering how the language defines *args. YMMV] -Peter From remi at cherrypy.org Thu Jul 14 18:10:13 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 14 Jul 2005 15:10:13 -0700 Subject: ANN: CherryPy-2.1.0-beta released Message-ID: <1121379013.118775.278510@g49g2000cwa.googlegroups.com> Hello everyone, I am happy to announce the first beta release of CherryPy-2.1 This release is a major step forward for CherryPy. It is packed with new features and bug fixes. Also, the CherryPy community is now growing quite fast and it is very active. Many people contributed to this release. Here are the main improvements in this release: - New WSGI interface, which allow CherryPy sites to be deployed on any WSGI server. People are already running it on mod_python, FastCGI, SCGI, IIS or CherryPy's own built-in HTTP server. - New implementation for sessions, which supports multiple backends - Built-in list of convenient "filters" for things like gzip compression, XHTML validation, caching, unicode decoding/encoding, authentication, XML-RPC wrapper, etc ... These filters can easily be enabled/disabled through configuration. - New "development" mode which provides things like autoreload (no need to manually restart your server when you make a change), logging of page stats, etc ... - Better handling of file uploads - Internal implementation now uses generators everywhere (no more StringIO) - New built-in HTTP server implementation *************** About CherryPy: CherryPy-2 is a pythonic, object-oriented web development framework. Here is a sample Hello, World in CherryPy-2: # import cherrypy # class HelloWorld: # @cherrypy.expose # def index(self): # yield "" # yield "Hello world!" # yield "" # cherrypy.root = HelloWorld() # cherrypy.server.start() Main properties: - this code starts a multi-threaded HTTP server that dispatches requests to methods - requests like "http://domain/dir/page?arg1=va l1&arg2=val2" are mapped to "dir.page(arg1='val1', arg2='val2')" - CherryPy also supports "RESTful" URLs like http://domain/book/science/9 - requests are mapped to an object tree that is "mounted" on cherrypy.root (for instance: "cherrypy.root.user", "cherrypy.root.user.remi", ...) - method must be explicitly exposed with a decorator "@cherrypy.expose" (or "index.exposed = True" for Python-2.3) Remi. http://www.cherrypy.org From gsakkis at rutgers.edu Sun Jul 10 08:57:52 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jul 2005 05:57:52 -0700 Subject: passing arguments to a function - do I need type ? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: <1121000271.927938.192870@g47g2000cwa.googlegroups.com> "Philipp H. Mohr" wrote: > Hello, > I got a newbie question, I have written the following distance function: > > def distance(self,element1, element2): > dist = 0 > > for n in range(len(element1)): > dist = dist + pow((element1[n] - element2[n]),2) > print 'dist' + dist > return sqrt(dist) > > > and in order to be able to use len() and index element1[] the function > needs to know that the arguments element1 and element2 are both listst or > doesn't it ? No it doesn't; it finds out at runtime. Also they don't have to be list; any object that defines __len__ will do. > I get the following error msg: > > Traceback (most recent call last): > File "Memory.py", line 105, in ? > start.inputVector(inP2) > File "Memory.py", line 97, in inputVector > allDimensions[0].newAttribute(vector) > File "Memory.py", line 56, in newAttribute > dist = self.distance(n.getCenter,newElement) > File "Memory.py", line 75, in distance > for n in range(len(element1)): > TypeError: len() of unsized object So obviously n.getCenter is not a list. > AND if I take len out I get: > > > > Traceback (most recent call last): > File "Memory.py", line 105, in ? > start.inputVector(inP2) > File "Memory.py", line 97, in inputVector > allDimensions[0].newAttribute(vector) > File "Memory.py", line 56, in newAttribute > dist = self.distance(n.getCenter,newElement) > File "Memory.py", line 76, in distance > dist = dist + pow((element1[n] - element2[n]),2) > TypeError: unsubscriptable object Same problem; n.getCenter and/or newElement are not lists (or other subscriptable objects for that matter). Just print them before you call distance to convince yourself. By the way, you don't use 'self' anywhere, so perhaps distance should be a function, not method. Also, the pythonic way of writing it (since 2.4) is: from math import sqrt from itertools import izip def distance(sequence1, sequence2): return sqrt(sum((x-y)**2 for x,y in izip(sequence1, sequence2))) > Thank you very much for your help. > > Phil Regards, George From simonwittber at gmail.com Tue Jul 12 02:04:35 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 11 Jul 2005 23:04:35 -0700 Subject: automatically assigning names to indexes Message-ID: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> I know its been done before, but I'm hacking away on a simple Vector class. class Vector(tuple): def __add__(self, b): return Vector([x+y for x,y in zip(self, b)]) def __sub__(self, b): return Vector([x-y for x,y in zip(self, b)]) def __div__(self, b): return Vector([x/b for x in self]) def __mul__(self, b): return Vector([x*b for x in self]) I like it, because it is simple, and can work with vectors of any size... However, I'd like to add attribute access (magically), so I can do this: v = Vector((1,2,3)) print v.x print v.y print v.z as well as: print v[0] print v[1] print v[2] Has anyone got any ideas on how this might be done? Sw. From benji at benjiyork.com Sun Jul 24 07:30:45 2005 From: benji at benjiyork.com (Benji York) Date: Sun, 24 Jul 2005 07:30:45 -0400 Subject: How to run python script in background after i logout In-Reply-To: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> References: <1122198224.635804.316950@g49g2000cwa.googlegroups.com> Message-ID: <42E37BE5.40305@benjiyork.com> Harlin Seritt wrote: > python script.py & > > It runs fine. When I log off ssh I notice that the script died when I > logged off. How do I make sure it stays running? As another reply stated, cron is probably what you really want, but to answer your question literally: you want the "nohup" command (short for "no hangup", as in the HUP signal). You would run it like so: nohup python script.py & see "man nohup" and "info coreutils nohup" for more info. -- Benji York From jeff.maitland at gmail.com Mon Jul 4 15:36:16 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Mon, 4 Jul 2005 15:36:16 -0400 Subject: threads and sleep? Message-ID: <6829832e050704123645e4547e@mail.gmail.com> Hello all, I am in the process of writing a multithreading program and what I was wondering is a sleep command in an executing function will affect the threads below it? Here is a basic example of what I mean. def main(): temp_var = True while temp_var == True: if t = threading.Thread( target = func1, args = "String") #note this is probably non functional (example purposes for the question only) t.start() temp_var = t.isAlive() else: print "This line should display a lot" sleep(2) def func1(s): print s so the question I was wondering is if the sleep will pause the t thread as well as the main function or is the thread independat of the main function sleep? Thanks in advance. From bokr at oz.net Mon Jul 11 11:30:37 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 15:30:37 GMT Subject: Read-only class properties References: <1121027902.719545.103860@g14g2000cwa.googlegroups.com> <42d1b2af.331498399@news.oz.net> Message-ID: <42d28760.385947733@news.oz.net> On Sun, 10 Jul 2005 21:10:36 -0700, Michael Spencer wrote: >Bengt Richter wrote: >... >> >> class Foo(object): >> class __metaclass__(type): >> def __setattr__(cls, name, value): >> if type(cls.__dict__.get(name)).__name__ == 'Descriptor': >> raise AttributeError, 'setting Foo.%s to %r is not allowed' %(name, value) >> type.__setattr__(cls, name, value) >> @classproperty >> def TheAnswer(cls): >> return "The Answer according to %s is 42" % cls.__name__ >> @classproperty >> def AnotherAnswer(cls): >> return "Another Answer according to %s is 43" % cls.__name__ >> > >or, simply put the read-only descriptor in the metaclass: > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> def classproperty(function): > ... class Descriptor(object): > ... def __get__(self, obj, objtype): > ... return function(objtype) > ... def __set__(self, obj, value): > ... raise AttributeError, "can't set class attribute" > ... return Descriptor() > ... > >>> class A(object): > ... class __metaclass__(type): > ... @classproperty > ... def TheAnswer(cls): > ... return "The Answer according to %s is 42" % cls.__name__ > ... > >>> A.TheAnswer > 'The Answer according to __metaclass__ is 42' > >>> A.TheAnswer = 3 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 6, in __set__ > AttributeError: can't set class attribute > >>> class B(A): pass > ... > >>> B.TheAnswer > 'The Answer according to __metaclass__ is 42' > >>> > > >this means that the getter doesn't automatically get a reference to the class >(since it is a method of metaclass), which may or may not matter, depending on >the application > It appears that you can use an ordinary property in the metaclass, and get the reference: (I tried doing this but I still had the classproperty decorator and somehow inside a metaclass it bombed or I typoed, and I forgot to try the plain property, so I hacked onwards to the more involved __setattr__ override). Anyway, >>> class A(object): ... class __metaclass__(type): ... def TheAnswer(cls): ... return "The Answer according to %s is 42" % cls.__name__ ... def __refuse(cls, v): ... raise AttributeError, "Refusing to set %s.TheAnswer to %r"%(cls.__name__, v) ... TheAnswer = property(TheAnswer, __refuse) ... ... >>> A.TheAnswer 'The Answer according to A is 42' >>> A.TheAnswer = 123 Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __refuse AttributeError: Refusing to set A.TheAnswer to 123 Of course, access through an instance won't see this: >>> a=A() >>> a.TheAnswer Traceback (most recent call last): File "", line 1, in ? AttributeError: 'A' object has no attribute 'TheAnswer' since TheAnswer is found in type(a)'s mro, but not type(A)'s: >>> type(a).mro() [, ] >>> type(A).mro() Traceback (most recent call last): File "", line 1, in ? TypeError: descriptor 'mro' of 'type' object needs an argument looks like you get type.mro as an unbound method that way... >>> type(A).mro(type(A)) [, , ] or >>> type.mro(A) [, ] >>> type.mro(type(A)) [, , ] or even >>> type.__dict__['mro'] >>> type.__dict__['mro'](A) [, ] >>> type.__dict__['mro'](type(A)) [, , ] >>> type(A) Regards, Bengt Richter From __peter__ at web.de Tue Jul 12 02:52:22 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Jul 2005 08:52:22 +0200 Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3' References: Message-ID: Ric Da Force wrote: > I have a string such as 'C1, C2, C3'. Without assuming that each bit of > text is of fixed size, what is the easiest way to change this list so that > it reads: > 'C1, C2 and C3' regardless of the length of the string. >>> " and".join("C1, C2, C3".rsplit(",", 1)) 'C1, C2 and C3' Peter From nick at no.spam.org Mon Jul 4 10:24:28 2005 From: nick at no.spam.org (Nick Efford) Date: Mon, 4 Jul 2005 14:24:28 +0000 (UTC) Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> <8c7f10c605063001207fd379ec@mail.gmail.com> <11c8211tl4sc107@corp.supernews.com> Message-ID: Grant Edwards wrote: > I'm an American who grew up watching plenty of BBC, and I run > into afew native Londoners whom I have hard time understanding. > I don't ever remember having troubly understanding people > outside the city. But have you encountered regional dialects? - e.g. from the north of the country, where you get both a strong accent, very different from London speech, and the use of different words. For example, folk in parts of the north-east will say "canny" instead of "careful", "gannin" instead of "going", "bonny lass" instead of "pretty girl". The question "Do you know what I mean?" expressed phonetically in Geordie (one of the north-eastern dialects) becomes "Ya knaa what ah mean, leik?" Nick From esther at bitranch.com Sat Jul 9 14:55:15 2005 From: esther at bitranch.com (esther at bitranch.com) Date: 9 Jul 2005 11:55:15 -0700 Subject: How long is a piece of string? How big's a unit? Message-ID: <1120935315.336081.114480@g43g2000cwa.googlegroups.com> I'm working on my monthly column for Software Test & Performance magazine, and I'd like your input. The topic, this time around, is unit testing (using python or anything else). Care to share some of your hard-won knowledge with your peers? In particular, what I'm looking for are experiences and advice about _developing_ the unit tests. (Managing and running them is something else again.) How big is a unit? How granular do you get? Do you have a particular process or checklist that you follow: ensuring that your tests look at interface, UI, etc.? Do you make a particular effort to create unit tests for the boundary conditions? Anecdotes are, of course, enthusiastically encouraged. Tell me what you learned the hard way about unit testing. What mistakes have you seen others make? What would you teach someone about the process that might otherwise come only with experience? On quoting you: My editors hate it when I quote "pookie-boy, whom I met on some newsgroup." Please let me know -- privately if necessary -- how I may refer to you in my article. (The usual format is "Kim Jones, a programmer at BigCompany, Inc. in Denver, Colorado.") I'll be working on this over the next several days, so I look forward to hearing from you soon. Esther Schindler Contributing editor, Software Test & Performance magazine (stpmag.com) From lashkariNO at SPAMworldviz.com Thu Jul 28 15:07:17 2005 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Thu, 28 Jul 2005 19:07:17 GMT Subject: Determine if object is a Bound or Unbound method Message-ID: Hi, I have an object and I want to check if it is a bound or unbound method, or neither. I tried using the types module, but it seems as though types.UnboundMethodType and types.MethodType are equal. How else can I determine this? BTW, I'm using Python 2.3 Thanks, Farshid From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 23 02:22:48 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 23 Jul 2005 08:22:48 +0200 Subject: tuple to string? In-Reply-To: <42e1788b@news.eftel.com> References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> Message-ID: <3ke61oFtnkg9U1@individual.net> John Machin wrote: > Reinhold Birkenfeld wrote: >> Berthold H?llmann wrote: >> >>>Francois De Serres writes: >>> >>> >>>>hiho, >>>> >>>>what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) >>>>to the string 'spam'? >>> >>>.>>> t = (0x73, 0x70, 0x61, 0x6D) >>>.>>> ''.join('%c' % c for c in t) >>>'spam' >> >> >> Or: >> >> t = (0x73, 0x70, 0x61, 0x6D) >> ('%c' * len(t)) % t > > You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-) Ah, ok. Didn't want to lookup the precedence rules... Reinhold From mmuller at enduden.com Sat Jul 23 11:28:30 2005 From: mmuller at enduden.com (Michael Muller) Date: Sat, 23 Jul 2005 11:28:30 -0400 Subject: problem with property docstrings Message-ID: I've observed something strange about property docstrings and I'm wondering if anyone here can clarify what's going on: if I create a class derived from property, the docstrings of the instances end up being that of the derived class, not the docstring passed into the property constructor. Example: class MyProp(property): "MyProp docstring" class Foo: p = MyProp(None, None, None, "property p docstring") >>> Foo.p.__doc__ 'MyProp docstring' Can anyone explain why this is? Is this a bug? From t-meyer at ihug.co.nz Thu Jul 7 21:28:19 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 8 Jul 2005 13:28:19 +1200 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: Message-ID: > "Java" as a term means different things to different people, Agreed. Python is similar in this respect - it's common to refer to cPython here as Python, for example. > but I expect most would think of the core language and its > standard library first and the JRE/JVM second. So saying "the > problem of X is Java" when you really mean "the problem of X > in platform Y is Sun's JVM in Y" is kinda misleading. Obviously I wouldn't agree :) The discussion here is about Java from a user's POV, not a programmer (because we are using a Java application to program in Python), and from the user's POV, the JRE/JVM is what is important, not the language. Much the same as a programmer who is using an IDE written in Python to program in some other language would really only care about how the Python VM performs. > Disclaimer: I am neither Java's not Eclipse's advocate; I'll > choose python over Java any day, but let's put the blame > where it is due. If there isn't a good VM for the OS that the vast majority of computers use, then the language has a problem, IMO. Having a great language spec is one thing, but it's not really much use without a good implementation. It would be interesting to know which JRE the Eclipse advocates are using, and which the people that dislike Eclipse are using... =Tony.Meyer From grante at visi.com Thu Jul 21 11:12:33 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 21 Jul 2005 15:12:33 -0000 Subject: print pdf file to network printer using python References: <1121949053.440544.108150@g47g2000cwa.googlegroups.com> Message-ID: <11dver1apnfd64a@corp.supernews.com> On 2005-07-21, scrimp wrote: > Well, Ive been searching through google groups and Ive seen a lot about > printing a pdf file, but I havent seen a definite answer. I tried this > code: > > f = open(printer_path, 'w') > f.write(pdffile_path) > f.close() > > Basically it doesnt work and what it prints out is the value of > pdffile_path variable. If anyone can offer some help, Id appreaciate it > thanks! You forgot to read the data from the pdf file. f = open(printer_path, 'w') f.write(open(pdffile_path,'rb').read()) f.close() -- Grant Edwards grante Yow! Yow! It's a hole at all the way to downtown visi.com Burbank! From fred at ucar.edu Tue Jul 5 15:06:33 2005 From: fred at ucar.edu (bandw) Date: 5 Jul 2005 12:06:33 -0700 Subject: Using Numeric 24.0b2 with Scientific.IO.NetCDF In-Reply-To: References: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> Message-ID: <1120590393.714232.34240@f14g2000cwb.googlegroups.com> Robert, Thanks for your reply. However, I am still having problems. Sometimes I get a scalar return and sometimes I get an array. For example, using the netCDF file: netcdf simple { dimensions: num = 3 ; variables: float temp0(num) ; int temp1(num) ; data: temp0 = 1., 2., 3. ; temp1 = 1, 2, 3 ; } and running: # import Numeric print Numeric.__version__ from Scientific.IO.NetCDF import NetCDFFile cdf_file1 = NetCDFFile("simple.nc","r") var1 = cdf_file1.variables["temp0"][:] var2 = cdf_file1.variables["temp1"][:] min1 = reduce(Numeric.minimum,var1) min2 = reduce(Numeric.minimum,var2) print "Types of var1, min(var1), min1:",type(var1), type(min(var1)), type(min1) print "Types of var2, min(var2), min2:",type(var2), type(min(var2)), type(min2) I get: 24.0b2 Types of var1, min(var1), min1: Types of var2, min(var2), min2: Even something like: >>> import Numeric >>> a = Numeric.array([1.,2.]) >>> print type(a),type(min(a)) does not produce an array. Any comments woud be appreciated. Fred Clare From spam.csubich+block at block.subich.spam.com Sun Jul 3 13:20:14 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 03 Jul 2005 13:20:14 -0400 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> <1120245884.872772.231420@o13g2000cwo.googlegroups.com> <1120362708.992006.49040@g14g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sun, 03 Jul 2005 00:39:19 -0400, Christopher Subich wrote: >>Personally, I think demanding that it be writable as a sum (or product, >>or any, or all) is a false standard -- nobody's claimed that these would >>replace all cases of reduce, just the most common ones. > > Er, excuse me, but that is EXACTLY what Devan claimed. > > Quote: "With the exception of reduce(lambda x,y:x*y, sequence), reduce can be > replaced with sum, and Guido wants to add a product function." Okay, then... "not many people have claimed that sum is a universal replacement for reduce, only the most common cases." It's further argued that the uncommon cases are more flexible and (again, mostly) anywhere from only slightly less readable to significantly more readable in for-loop form. The only corner case that isn't, so far as I know, is when the reduce() has no default initial value and the sequence/generator might possibly have 0 elements. But that's a TypeError anyway. From peter at engcorp.com Mon Jul 18 09:44:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 09:44:00 -0400 Subject: What is your favorite Python web framework? In-Reply-To: References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> Message-ID: <8Y-dnatKvJ13LEbfRVn-rQ@powergate.ca> Gerhard Haering wrote: > On Mon, Jul 18, 2005 at 09:06:21AM -0400, Peter Hansen wrote: >>I'm not familiar with this expression. What do you mean by "black horse"? > > Maybe "the Ferrari of pythonic frameworks" (black horse on yellow > background being the symbol of Ferrari). I know there are "black sheep" in some families, and "dark horse candidates". Also yellow-bellied sapsuckers. There's a "black horse" fish in the Mississippi valley (also, quite coincidentally, of the sucker family). Not entirely sure that was the intended connotation. :-) -Peter From bokr at oz.net Tue Jul 12 00:00:55 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 04:00:55 GMT Subject: Access descendant class's module namespace from superclass References: Message-ID: <42d33a25.431712900@news.oz.net> On Mon, 11 Jul 2005 18:45:20 -0500, Reid Priedhorsky wrote: >Dear group, > >I'd have a class defined in one module, which descends from another class >defined in a different module. I'd like the superclass to be able to >access objects defined in the first module (given an instance of the first >class) without importing it. Example of what I'm looking for: > ><<>> > > class Spam(object): > def fish(self): > a = self.__module__.Ham() > ><<>> > > import spam > > class Eggs(spam.Spam): > pass > > class Ham(object): > pass > >The above doesn't work because __module__ is a string, not a module object: > > >>> import eggs > >>> b = eggs.Eggs() > >>> b.fish() > Traceback (most recent call last): > File "", line 1, in ? > File "spam.py", line 3, in foo > a = self.__module__.Ham() > AttributeError: 'str' object has no attribute 'Ham' > >(I suppose I could call __import__(self.__module__), but that seems kind >of awkward.) > >Is this possible using Python 2.3? Any better ways to accomplish this? > >Thanks very much for any help, > >Reid I think 2.3 will do this. But be careful not to tie your shoelaces together and trip -- I haven't tested this beyond what you see. It was just an idea for the kind of access you seemed to want ;-) If each class and subclass whose global environment you want to reach through an instance provides a property that will return the class or subclass' global dict, then a base class method can access that via the instance to "fish" for a name in the appropriate "fishinghole" -- e.g., ----< spam.py >------------------------------- """spam.py module doc string""" class Spam(object): def fish(self, whatfor): return self.fishinghole[whatfor] fishinghole = property(lambda self:globals()) # spam.py globals if this fishinghole used ---------------------------------------------- ----< eggs.py >------------------------------- """eggs.py module doc string""" import spam class Eggs(spam.Spam): fishinghole = property(lambda self:globals()) # eggs.py globals if this fishinghole used class Ham(object): pass # won't find any fishing hole at all class Grits(spam.Spam): pass # no fishing hole, should find spam.py globals if looked for ---------------------------------------------- >>> import eggs >>> dir(eggs) ['Eggs', 'Grits', 'Ham', '__builtins__', '__doc__', '__file__', '__name__', 'spam'] >>> eggs.__doc__ 'eggs.py module doc string' >>> >>> e = eggs.Eggs() >>> e.fish('Ham') >>> e.fish('__doc__') 'eggs.py module doc string' >>> e.fishinghole.keys() ['Ham', 'spam', '__builtins__', '__file__', '__doc__', 'Grits', '__name__', 'Eggs'] >>> g = eggs.Grits() >>> g.fish('Spam') >>> g.fish('__doc__') 'spam.py module doc string' >>> g.fishinghole.keys() ['__builtins__', '__name__', '__file__', '__doc__', 'Spam'] You could fish for a class that might be available in both modules by the same name, and get a different one depending on which instance' fish method or fishinghole you used. Here Spam is only available in spam.py, but if it were available in eggs.py then e.fish('Spam') would pick it up just like Ham. >>> spaminst = g.fish('Spam')() >>> spaminst.fish('__doc__') 'spam.py module doc string' Note that the fishinghole property dynamically returns the module dict, which is mutable, so you can write a really tangled mess if you want to. This already seems dangerously close ;-) >>> e.fishinghole['x'] = 'x in eggs module globals' >>> e.fish('x') 'x in eggs module globals' >>> eggs.x 'x in eggs module globals' >>> g.fishinghole['x'] = 'x in spam module globals' >>> g.fish('x') 'x in spam module globals' >>> eggs.spam.x 'x in spam module globals' But we didn't directly import spam (eggs did, that's why eggs.spam was visible) ... >>> spam Traceback (most recent call last): File "", line 1, in ? NameError: name 'spam' is not defined >>> import spam >>> spam.x 'x in spam module globals' Regards, Bengt Richter From gsakkis at rutgers.edu Thu Jul 21 19:53:54 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 21 Jul 2005 19:53:54 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: <1121990044.425eb43fede06896cda10eeef5ba7127@teranews> "Reinhold Birkenfeld" wrote: > > Why did Guido want a PEP? Is it because he likes the idea but > > feels the feature set needs to be examined a bit more by the wider > > community, or is it some other reason? > > He said, > > """ > Whoa! Do we really need a completely different mechanism for doing the > same stuff we can already do? The path module seems mostly useful for > folks coming from Java who are used to the Java Path class. With the > massive duplication of functionality we should also consider what to > recommend for the future: will the old os.path module be deprecated, > or are we going to maintain both alternatives forever? (And what about > all the duplication with the os module itself, like the cwd() > constructor?) Remember TOOWTDI. > """ Duplication is a valid point for debate, so the PEP should definitely address it. IMO os.path and most (if not all) other equivalent modules and functions should be deprecated, though still working until 2.9 for backwards compatibility, and dropped for python 3K. George From sybrenUSE at YOURthirdtower.com.imagination Mon Jul 11 16:59:32 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 11 Jul 2005 22:59:32 +0200 Subject: Environment Variable References: Message-ID: Vivek Chaudhary enlightened us with: > Is it possible to set an environment variable in python script whose > value is retained even after the script exits. It is, if you have absolute control over the calling environment. > Is it possible to somehow create this environment variable inside > python script which will be avaibale even after the script exits. In > otherwords, after I run my script, if I do a "echo $name" in my > shell, it should return the value "vivek" Here is an example Python script: -------------------------------------------------------- import sys name = sys.stdin.readline() print "export name=%s" % name.strip() -------------------------------------------------------- If you call it like this: bash$ $(python examplescript) It'll change the 'name' variable of your shell. It's not really a generic nor an elegant way of doing this. Heck, it even depends on the type of shell you're using. If it suits your needs, be happy ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From tjreedy at udel.edu Tue Jul 12 16:30:07 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 12 Jul 2005 16:30:07 -0400 Subject: Trying to come to grips with static methods References: Message-ID: | I've been doing a lot of reading about static methods in Python, and possibly getting over-confused by the minutia of the CPython implementation, as well as by the misnomer. Conceptually, a 'static method' is a function attribute of a class that is to be used as a function and not as a method (where 'methods', in Python, get semi-magic first parameters). Note that function attributes of instances are also just functions, and not methods (which sometimes fools people), as are function attributes of modules. | not exactly sure what they are useful for or why they were introduced. Completeness (as RK said), occasional real usefulness, and for C++&Java programmers. Python did fine without them. | As near as I can see it, static methods are object methods that act just | like functions. Almost: class function/method, depending on your meaning of method. See above. |Er. I always thought that object methods *were* functions, | except they had some runtime magic that passed the object itself as the | first argument. Substitute class for object and class or instance for object itself and you have it. The runtime magic is a minor abbreviation but its major purpose is inheritance. Now you can more on to something more useful like metaclasses or decorators ;-). Terry J. Reedy From steve at REMOVEMEcyber.com.au Wed Jul 6 01:00:04 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 06 Jul 2005 15:00:04 +1000 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com><1120565012.080020.309070@o13g2000cwo.googlegroups.com><1120590707.093007.175330@o13g2000cwo.googlegroups.com><11cloakd4glsbef@corp.supernews.com> <-8ydnZxXGOCQvlbfRVn-3Q@comcast.com> Message-ID: <42CB6554.9010505@REMOVEMEcyber.com.au> I was going to drop the lambda discussion, as it has been going on and on and on, but Terry's comment strikes me as so wrong that it needs to be challenged. Terry Reedy wrote: > From a certain viewpoint, I would agree. Yet, the word 'lambda' *is* the > center of most of the fuss. For beginners, it is a minor issue: learn it > and move on. But for some functionalists, it is a major issue. They > 'know' that lambda means 'expressionized anonymous function'. And in > lambda calculus, it is the main actor. But in Python, lambda only means > anonymous trivial function. It is only an expressionized convenience > abbreviation for an important but small subset of possible functions. So > for years, such knowledgeable people have called for and proposed various > syntaxes for 'proper lambdas' or 'true lambdas', saying pretty clearly that > what Python has is improper or false. Would there have been so much fuss > if the keyword had been 'fun' and the word 'lambda' had never appeared in > the Python docs? I strongly doubt it. People object to the fact that lambda doesn't allow statements. They do this, not because they know about the lambda calculus (I don't!) but because they keep trying to do things like this: map(lambda x: if x == 0: 1; else: math.sin(x)/x, myList) Hands up who thinks this usage case would disappear if lambda was called "fun" or "anonymous_function" instead? > I also suspect that the years of fuss over Python's lambda being what it is > rather that what it is 'supposed' to be (and is in other languages) but is > not, has encourage Guido to consider just getting rid of it. I personally > might prefer keeping the feature but using a different keyword. Best of all would be if lambda was extended to allow statements, just like a real made-with-def function. Although, I worry about syntax and readability. But then I'm not completely comfortable with the existing lambda syntax either. And now, I shall say no more on this issue. -- Steven. From rkern at ucsd.edu Wed Jul 6 00:31:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 05 Jul 2005 21:31:39 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120621580.107813.47100@g43g2000cwa.googlegroups.com> References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1120621580.107813.47100@g43g2000cwa.googlegroups.com> Message-ID: Dan Bishop wrote: > There's also the issue of having to rewrite old code. It's Python 3000. You will have to rewrite old code regardless if reduce stays. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Sat Jul 16 20:36:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Jul 2005 20:36:01 -0400 Subject: Filtering out non-readable characters In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Sat, 16 Jul 2005 19:01:50 -0400, Peter Hansen wrote: >> George Sakkis wrote: >>>>>> identity = string.maketrans('','') >> >> Wow! That's handy, not to mention undocumented. (At least in the >> string module docs.) Where did you learn that, George? >> > http://python.org/doc/lib/node109.html Perhaps I was unclear. I thought it would be obvious that I knew where to find the docs for maketrans(), but that the particular behaviour shown (i.e. arguments of '' having that effect) was undocumented in that page. -Peter From phillip.watts at anvilcom.com Fri Jul 29 08:44:36 2005 From: phillip.watts at anvilcom.com (phil) Date: Fri, 29 Jul 2005 07:44:36 -0500 Subject: Async PySerial (was Re: pySerial Windows write problem) References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: <42EA24B4.6050907@anvilcom.com> I use PySerial in a 16 line data collection system with LOTS of threads, and yes am frustrated by read(). This sounds excellent, keep us updated. BTW, haven't done any event driven Python except Tkinter. Would this a class library which would let you define an event and a handler? Do you have a one line code example? Thanks. Peter Hansen wrote: > Neil Benn wrote: > >>PySerial doesn;t have any kind of event firing to notify you when data >>is available. The way I get round this is to have a loop polling (in a >>seperate thread) to see if any data is available (it's a method on the >>interface), then read all the data in and fire this off to my >>listeners/observers with the read data. >> > > On that note, I've got a preliminary version of something I call "Bent" > (think "slightly Twisted") which is focused for now on providing an > asynchronous version of PySerial which is designed around the > event-driven model instead of its current polled scheme. > > It shares a number of features with the Twisted-based PySerial port > (also done by Chris Liechti, for the Twisted team, judging by the code > comments) but doesn't require one to adopt the whole Twisted framework. > Basically it provides you with the equivalent of one "reactor" per > thread for PySerial stuff. On Win32 only for now. There are other > limitations too. Not ready for prime time. > > On the plus side, it's been letting me convert my serial stuff to be > fully event-driven and with the resulting much lower latencies and > better CPU efficiency, while keeping my code more "traditional" instead > of having to force it entirely into the Twisted point of view. > > Just an FYI. And, obviously, to hear back from those interested. I > don't know if this is something that should be contributed to the > PySerial project (it's more of a rewrite than an add-on), or set up as a > new project, or passed around quietly behind the scenes for a while. > No docs yet, no contrived examples (but various pieces of working code > in real daily use). Did I mention it wasn't ready for prime time? > > If you've ever been annoyed having to do .read(1) to get characters one > at a time in PySerial, or .read(100) with a timeout, or whatever, this > might be of interest to you... > > -Peter > From zen19725 at zen.co.uk Thu Jul 21 13:13:59 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Thu, 21 Jul 2005 18:13:59 +0100 Subject: Generating images with text in them References: Message-ID: On Thu, 21 Jul 2005 11:23:46 +0100, Daren Russell wrote: >phil hunt wrote: >> I am trying to generate some images (gifs or pngs) with text in >> them. I can use the Python Imaging Library, but it only has access >> to the default, rather crappy, font. >> >> Ideally I'd like to use one of the nicer fonts that come with my X >> Windows installation. Using Tkinter I can draw these fonts on the >> screen; is there any way to get these fonts into a bitmapped image? >> For example, can I draw some text on a canvas and then "grab" that >> canvas as a bitmap into PIL, and then save it as a file? >> >> Alternately, is there a good source of PIL font files (.pil files) >> somewhere? >> >> If the writers of the Python Imaging Library are reading this, may I >> suggest that they add more fonts to it. Yes, that would increase >> the size, but these days disk space is cheap and programmer time >> expensive. >> > >I've just been playing around with this. You can use truetype fonts with: > >font = ImageFont.truetype("/path/to/font.ttf", 12) Thanks! it's working now! -- Email: zen19725 at zen dot co dot uk From d0153030 at hotmail.com Mon Jul 18 20:13:04 2005 From: d0153030 at hotmail.com (Sandeep Arya) Date: Tue, 19 Jul 2005 05:43:04 +0530 Subject: Threads: Issue and suggestion required Message-ID: Hello I am developing an application using PyQT. My application scenario is:: "At any instance one socket is open in my application. Now if user wants to execute some command on another machine/IP address, then i need to make another socket and execute task." My query is. Is this possible that my main thread and my newly born thread will execute their task simultaneously/parallel. (I read that Python interpretor allows only one thread execution at a time. Using its global lock. And switch among active thread based on time set by setSwitchTime() function.. Is this correct?) I just wannn know what is lifetime of thread. As I was planning to implement one function such that: 1.0 function starts 2.0 create socket 3.0 Open socket 4.0 Do whatever task to do 5.0 Close socket 6.0 Function ends I wanna know that if i assign such above mentioned function to thread::run then will the thread die after step 6.0 above i.e. function ends. Suggest me. Thanking You Sandeep _________________________________________________________________ Get faster and relevant results. http://search.msn.co.in Switch to the smarter search! From devlai at gmail.com Wed Jul 27 01:23:04 2005 From: devlai at gmail.com (Devan L) Date: 26 Jul 2005 22:23:04 -0700 Subject: A Module on Time & Date In-Reply-To: References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: <1122441784.523052.49490@o13g2000cwo.googlegroups.com> Robert Maas, see http://tinyurl.com/uh3t wrote: > > From: Robert Kern > > As you can see in the datetime documentation, the module was introduced > > in Python 2.3. I recommend updating your Python installation. > > What do you mean "your"?? I don't have any Python installation of my > own. All I have is what this small local ISP provides on its Unix shell > machine which I share with hundreds of other users. There's no way I > can install a new version of anything on the system account. > Your recommendation will be disregarded as total crap. You should contact your isp and ask them to upgrade, then. From thomasbartkus at comcast.net Thu Jul 21 20:58:37 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 21 Jul 2005 19:58:37 -0500 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) References: Message-ID: On Wed, 20 Jul 2005 18:37:48 +1000, David Trudgett wrote: > My advice would be to steer clear of Kylix and choose one of the other > environments suggested to you. If you really like Pascal, fpc may be a > possibility as someone mentioned. ... Well - I really like Python! But - climbing back on the soapbox - far more important than any linguistic quibble is a robust GUI interface that might *unburden* any language from the tedium of creating a powerful and effective user interface. I would go so far as to say that, while this is the only thing an atrocity like VB has going for it, it *trumps* most everything. This was the great hope of the Delphi<->Kylix thing. The Windows implemntation (Delphi) was/is a magnificent productivity tool. And if Kylix has failed then we are still scratching about with TKinter, Glade, wxGlade, EasyGUI, or {whatever} just to to bring up the rear on Linux. Python is fun, but how do we get it to desktop primetime ? Thomas Bartkus From kbk at shore.net Thu Jul 21 00:04:00 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 21 Jul 2005 00:04:00 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200507210404.j6L4409Y028359@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 350 open ( +1) / 2882 closed ( +2) / 3232 total ( +3) Bugs : 889 open ( -8) / 5141 closed (+22) / 6030 total (+14) RFE : 189 open ( -5) / 178 closed ( +8) / 367 total ( +3) New / Reopened Patches ______________________ Add unicode for sys.argv, os.environ, os.system (2005-07-02) CLOSED http://python.org/sf/1231336 reopened by loewis Fix LINKCC (Bug #1189330) (2005-07-15) http://python.org/sf/1239112 opened by Christoph Ludwig Prevent race condition in os.makedirs (2005-07-17) http://python.org/sf/1239890 opened by Nir Soffer release lock on exception in threading.Thread.join() (2005-07-18) http://python.org/sf/1240614 opened by Dirk Groeneveld Patches Closed ______________ Patch for potential buffer overrun in tokenizer.c (2005-01-13) http://python.org/sf/1101726 closed by doerwalter Add unicode for sys.argv, os.environ, os.system (2005-07-02) http://python.org/sf/1231336 closed by loewis Optimization for textwrap (2005-05-26) http://python.org/sf/1209527 closed by rhettinger New / Reopened Bugs ___________________ email.Generator traceback in forwarded msg (2005-07-12) http://python.org/sf/1236906 opened by Skip Montanaro Missing sk_SK in windows_locale (2005-07-13) http://python.org/sf/1237015 opened by Lukas Lalinsky link path probs on OSX re: Tcl, Tk & fink's /sw (2005-07-13) http://python.org/sf/1237697 opened by blakers threading.Thread uses {} as default argument (2005-07-14) CLOSED http://python.org/sf/1238170 opened by Simon Dahlbacka manual.cls contains an invalid pdf-inquiry (2005-07-14) http://python.org/sf/1238210 opened by Michael Schindler freed pointer is used in longobject.c:long_pow() (2005-07-15) CLOSED http://python.org/sf/1238681 opened by Luke subprocess.Popen fails inside a Windows service (2005-07-15) http://python.org/sf/1238747 opened by Adam Kerrison Win registry problem (2005-07-15) http://python.org/sf/1239120 opened by Bruce Sherwood Win registry problem (2005-07-15) CLOSED http://python.org/sf/1239148 opened by Bruce Sherwood Install Error: "cannot compute sizeof (int), 77" (2005-07-15) http://python.org/sf/1239186 opened by Bob Gazzale email.Utils.formatdate documetaion missing (2005-07-17) CLOSED http://python.org/sf/1239681 opened by Nir Soffer distutils: MetroWerks support can go (2005-07-17) http://python.org/sf/1239948 opened by Jack Jansen Distutils does not use logging (2005-07-19) http://python.org/sf/1241006 opened by Giles Antonio Radford StreamReader broken for byte string to byte string codecs (2005-07-20) CLOSED http://python.org/sf/1241507 opened by Graham Horler garbage collection asserts failing (2005-07-20) http://python.org/sf/1241545 opened by munder12 -m does not find dotted modules (2005-07-20) CLOSED http://python.org/sf/1241619 opened by Giles Antonio Radford Bugs Closed ___________ debug info file descriptor of tarfile is inconsistent (2005-07-09) http://python.org/sf/1235266 closed by birkenfeld missing Py_DECREF in PyObject_CallMethod (2005-06-29) http://python.org/sf/1229429 closed by mwh Mistakes in online docs under "5.3 Pure Embedding" (2005-07-05) http://python.org/sf/1232768 closed by birkenfeld tkFileDialog.askopen... fails when dir="" (2005-07-07) http://python.org/sf/1233799 closed by birkenfeld Carbon.FSSpec.as_pathname() crashes (2005-07-11) http://python.org/sf/1236090 closed by jackjansen segfault/assert in tokenizer (2004-12-21) http://python.org/sf/1089395 closed by doerwalter threading.Thread uses {} as default argument (2005-07-14) http://python.org/sf/1238170 closed by birkenfeld some latex reject the pdfinfo macro while generating html (2004-11-22) http://python.org/sf/1071094 closed by birkenfeld freed pointer is used in longobject.c:long_pow() (2005-07-15) http://python.org/sf/1238681 closed by tim_one Win registry problem (2005-07-15) http://python.org/sf/1239148 closed by bsherwood email.Utils.formatdate documetaion missing (2005-07-17) http://python.org/sf/1239681 closed by montanaro "k" specifier in PyArg_ParseTuple incomplete documentated (2004-11-07) http://python.org/sf/1061920 closed by birkenfeld "article id" in description of NNTP objects (2004-08-24) http://python.org/sf/1015140 closed by birkenfeld Missing urllib.urlretrieve docs (2004-08-24) http://python.org/sf/1014761 closed by birkenfeld refman doesn't know about universal newlines (2005-01-10) http://python.org/sf/1099363 closed by birkenfeld 7.5.6 Thread Objects is too vague (2004-03-09) http://python.org/sf/912943 closed by birkenfeld os.access() documentation should stress race conditions (2004-01-08) http://python.org/sf/872769 closed by birkenfeld use first_name, not first, in code samples (2004-09-03) http://python.org/sf/1021621 closed by birkenfeld make frameworkinstall fails for non-default location (2005-06-09) http://python.org/sf/1217591 closed by jackjansen SocketServer module documentation misleading (2004-05-20) http://python.org/sf/957505 closed by birkenfeld unclear documentation/missing command? (2003-11-27) http://python.org/sf/850238 closed by birkenfeld os module: Need a better description of "mode" (2003-06-17) http://python.org/sf/755617 closed by birkenfeld StreamReader broken for byte string to byte string codecs (2005-07-20) http://python.org/sf/1241507 closed by doerwalter New / Reopened RFE __________________ add a note to eval and exec to not use it when possible (2005-07-13) CLOSED http://python.org/sf/1237678 opened by Reinhold Birkenfeld add dedent() string method (2005-07-13) http://python.org/sf/1237680 opened by Reinhold Birkenfeld RFE Closed __________ add a note to eval and exec to not use it when possible (2005-07-13) http://python.org/sf/1237678 closed by rhettinger Links to tutorials and howtos from references (2005-07-04) http://python.org/sf/1232073 closed by rhettinger Add Jason Orendorff's path module to stdlib (2005-06-23) http://python.org/sf/1226256 closed by rhettinger Add Error Code Dictionary to urllib2 (2005-06-08) http://python.org/sf/1216944 closed by birkenfeld Floating point second in date/time tuple (2001-04-05) http://python.org/sf/414059 closed by birkenfeld pickle lacks float('inf') (2001-07-28) http://python.org/sf/445484 closed by birkenfeld Optional type enforcement (2003-07-28) http://python.org/sf/778763 closed by birkenfeld -m does not find dotted modules (2005-07-20) http://python.org/sf/1241619 closed by rhettinger From devnull at joreybump.com Sun Jul 10 16:16:46 2005 From: devnull at joreybump.com (Jorey Bump) Date: Sun, 10 Jul 2005 20:16:46 GMT Subject: Defending Python References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> <42d17b1f$0$19917$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:42d17b1f$0$19917$636a15ce at news.free.fr: > Jorey Bump a ?crit : >> Bruno Desthuilliers wrote >> in news:42d031da$0$30239$636a15ce at news.free.fr: >> >>>Grant Edwards a ?crit : >>> >>>>On 2005-07-09, Brian wrote: >>>> >>>>>>folks as an easily acquired extra skill. >>>>> >>>>>I agree 100% with your statement above. Python may not be >>>>>sufficient for being the only programming language that one needs >>>>>to know -- yet, it does come in VERY handy for projects that need >>>>>to perform tasks on non-Microsoft operating systems. :-) >>>> >>>>It's also darned handy for projects that need to perform tasks >>>>on Microsft operating systems but you want to do all the >>>>development work under a real OS. >>> >>>It's also darned handy for projects that need to perform tasks on >>>Microsft operating systems. >> >> It's also darned handy for projects that need to perform tasks... Or >> don't... And for other things besides projects... >> >> Anyway, it's darned handy! > > it's. +1 for this becoming the official name of Python 3000. ;) And now for something completely different... The larch! From fairwinds at eastlink.ca Fri Jul 1 01:35:44 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 01 Jul 2005 02:35:44 -0300 Subject: Splitting string into dictionary In-Reply-To: Message-ID: Wow Robert that is incredible python magic! I am trying to figure out what this is doing since my attempts were regex and some long string splitting and collection. Ok. So it is a list comprehension and then collection. What is zip doing in the second line? Regards David On Friday, July 1, 2005, at 02:11 AM, Robert Kern wrote: > David Pratt wrote: >> I have string text with language text records that looks like this: >> >> 'en' | 'the brown cow' | 'fr' | 'la vache brun' >> >> Two or more language records can exist in each string (example above >> shows 2 - but could contain more) >> The second vertical line character in the example above is the record >> break in the pattern (between 'cow' and 'fr') >> >> What is the shortest route to getting this into a dictionary like: >> >> {'en':'the brown cow','fr':'la vache brun'} >> >> The language code is always 2 lower case letters. >> >> Many thanks. > > Ignore the last message. > > translations = [x.strip(" '") for x in line.split('|')] > d = dict(zip(translations[::2], translations[1::2])) > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > > -- > http://mail.python.org/mailman/listinfo/python-list > From bogus@does.not.exist.com Fri Jul 1 12:55:02 2005 From: bogus@does.not.exist.com () Date: Fri, 01 Jul 2005 16:55:02 -0000 Subject: No subject Message-ID: #! rnews 4560 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 115 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Fri, 1 Jul 2005 16:40:26 GMT Xref: news.xs4all.nl comp.lang.python:384402 Tom Anderson writes: > On Fri, 1 Jul 2005, Adriaan Renting wrote: > > > I'm not a very experienced Python programmer yet, so I might be > > mistaken, but there are a few things that would make me prefer C++ > > over Python for large (over 500.000 LOC) projects. Strictly in terms of software engineering and language design, Python may well be better suited to large projects than C++ or Java. Code re-use, original coding and prototyping, unittests, and peer reviews are a lot easier with Python than with C++ or Java. The problem is that large projects tend to have portions which are performance sensitive. So a project might be 100K LOC of C with 200K LOC of Python. > > Hmm. I don't know C++, but here goes ... > > > - namespaces > > Aren't namespaces basically the same as packages/modules in python? > They serve the same purpose but are not 1:1 with a file. I personally can't think of a situation where I'd want 2 or more namespaces in a physical file, or 2 or more files per namespace. Therefore I don't see any advantage in the C++ approach. > > - templates > > These would be meaningless in python - they're part of typefulness, which ... > > > - strong type checking > > ... python eschews. Templates address (I hesitate to say "solve") static typing by adding back the polymorphism that static typing eliminates. Python avoids the fix-on-a-fix by doing dynamic strong typing in the first place. > > Not that this is necessarily a good thing. I have to say that my Java > roots do lead me to think that strong typing is a plus for big > projects, since it's a way of defining and enforcing interfaces > between bits of code written by different people (or by one person at > different times!). Optional static typing in python would be nice for > this. > Java has nothing on Modula-3. Talk about strong static typing... It used to take me 3 days to get the first compile to run on a new project. Yet after years of Modula-3 (and repeatedly seeing strong static typing pay off) I found python quite comfortable. Somehow the problems strong static typing addresses aren't a problem. > > - data hiding > > Surely you can hide data in python? > You can't genuinely hide data in Python. The best you can do is the "_" idiom. The question is why was data hiding invented in the first place. It prevents attempts to get at the underlying mechanisms instead of sticking with the external API. There are two reasons for this: a) Protection of the algorithms (e.g., trade secrets). Python doesn't solve that. Neither do C++ or Java, or assembler. If you have access to the binary, you can reverse engineer the functionality. b) Prevent ill-considered attempts at optimization through use of the lower layers. Those layers are there for a reason, usually to protect the external API from changes in the underlying library. Python solves that by attracting programmers intelligent enough to understand this.:-) > > - more available libraries and more advanced developement tools. If the library is in C, C++, or FORTRAN, Python can use it. Worst case you have to write your own bindings. As for "advanced development tools"... That's a flameware waiting to happen. > > True. The more advanced development tools are offset to a large degree > by the advanced crappiness of C++ as a language, though; i'd be > surprised if a C++ programmer borged up with all the latest tools was > actually more productive than a python programmer with a > syntax-colouring, auto-indenting text editor. It'd be very interesting > to get some real numbers on that. > > >> Ultimately, manageability of a project is far and away more about the > >> people involved and the techniques used than it is about any single > >> technology involved. > > > > Agreed. > > +1 getting to the crux of it. > > tom > > -- > In-jokes for out-casts -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From falcon3166 at hotmail.com Sat Jul 2 02:25:00 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 2 Jul 2005 00:25:00 -0600 Subject: Another newbie question from Nathan. Message-ID: <42c63341$0$6997$b9fe7a78@news.usenetrevolution.com> Hi all. How do I make the computer generate 4 random numbers for the guess? I want to know because I'm writing a computer program in Python like the game MasterMind. Thanks. -- Nathan Pinno http://www.npinnowebsite.ca/ -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From dimitri.pater at gmail.com Tue Jul 5 17:24:43 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Tue, 5 Jul 2005 23:24:43 +0200 Subject: Good starterbook for learning Python? In-Reply-To: References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: hi, although Dive into Python is a *very, very* good Python book (I own the "real" book) I would not recommend it as your first book to learn Python. Take a look at Practical Python by Hetland first for instance, it will teach you all the basic stuff. Then move over to Dive into Python and also consider the Python Cookbook next to Dive into Python. (on the other hand, since you can download Dive into Python you can try if it works for you) Bye, Dimitri On 7/5/05, Sybren Stuvel wrote: > > Lennart enlightened us with: > > Can someone advice me with the following issue: i want to learn > > python in my summer vacation (i try to ...:-) So, a good start is > > buying a good book. But wich? There are many ... > > http://www.diveintopython.org/ - I read it during the weekend, and > it's a very good book. Clearly written, good examples and a healthy > dose of humor. > > > I'm living in the Netherlands and I prefer a book from bol.com(see link) > > because i've to order more books by them. > > Dive Into Python can be freely downloaded. > > > Search here for python (sorry, there's no short link) > > Yes there is. Check http://tinyurl.com/ > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From hancock at anansispaceworks.com Sat Jul 2 23:35:52 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 22:35:52 -0500 Subject: Folding in vim Message-ID: <200507022235.52847.hancock@anansispaceworks.com> My general attitude towards IDEs and editors has been extremely conservative, but today I decided to see what this "folding" business was all about. I see that vim (and gvim, which is what I actually use) has this feature, and it is fairly nice, but at present it's very manual --- and frankly it's hard for me to see the point if I have to manually mark folds every time I start up. I tried to load a couple of different scripts to automatically fold Python code in vim, but none of them seems to do a good job. The obvious thing (to me) would be for functions and classes to be folded at the top level, with each method folded inside the class folds. But I can't seem to figure out how to make that happen (other than manually, I mean). Actually, I usually want to fold the comment block at the top with the license disclaimer and module documentation, too, but I can do that manually. I've tried: python_fold.vim by Jorrit Wiersma http://www.vim.org/scripts/script.php?script_id=515 and AutoFold.vim by Dave Vehrs http://www.vim.org/scripts/script.php?script_id=925 Does anybody have a better suggestion (or perhaps can tell me how to make one of these do what I'm wanting)? I'm assuming that I can set these by using the Tools -> Folding -> Fold Method -> Syntax (or Expression for python_fold) but it doesn't seem to work. python_fold seems to just collapse methods (but not the whole classes they are in), and I can't seem to make AutoFold do anything at all, so I must be using it wrong. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From peter at engcorp.com Wed Jul 13 20:51:42 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 20:51:42 -0400 Subject: Consecutive Character Sequences In-Reply-To: References: Message-ID: Walter Brunswick wrote: > Is there any way to [efficiently] iterate through a sequence of characters to find N [or more] consecutive equivalent characters? > > So, for example, the string "taaypiqee88adbbba" would return 1 if the number (of consequtive characters) supplied in the parameters > of the function call was 2 or 3, because "a", "e", 8, and "b" is repeated 2 or 3 times. Why would it return 1? Is that instead of True, or does it represent a count of items, or the position of something in the list, or what? -Peter From jnoller at gmail.com Sun Jul 24 11:39:31 2005 From: jnoller at gmail.com (Jesse Noller) Date: Sun, 24 Jul 2005 11:39:31 -0400 Subject: How to realize ssh & scp by Python In-Reply-To: <20050723172558.21838.qmail@web15407.mail.cnb.yahoo.com> References: <20050723172558.21838.qmail@web15407.mail.cnb.yahoo.com> Message-ID: <4222a84905072408396ae78460@mail.gmail.com> On 7/23/05, ? ? wrote: > I would like to write a Python code like this: > > It can login a host by SSH > after login the host, use SCP to get a remote file, so it can deliver file > to the host. > then execute the program > then leave the host > > For example : > > STEP 1. ssh xxxx_yyy at 123.45.67.89 > STEP 2. Enter the password automatically > STEP 3. run " scp -r zzz at 123.45.67.90:/home/xxx/program ." > STEP 4. Enter the password for SCP automatically > STEP 5. run "./program" > STEP 6. run " exit" > > I know telnetlib can help us with telnet, and how to deal with this SSH > situation in Python? > > Thanks a lot for your help :) > I would recommend looking at the following utilities: http://www.theether.org/pssh/ http://sourceforge.net/projects/pyssh Setting up private/public key authentication is going to allow for a greate amount of secure automation. Barring that, use the pexpect module to do the prompt handling. -jesse From fairwinds at eastlink.ca Fri Jul 1 01:53:41 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 01 Jul 2005 02:53:41 -0300 Subject: Splitting string into dictionary In-Reply-To: <1120195786.108955.257460@o13g2000cwo.googlegroups.com> Message-ID: <7A6D65F5-E9F4-11D9-9AD1-000A27B3B070@eastlink.ca> Pretty amazing Devan! Great regex! Thank you. Regards, David On Friday, July 1, 2005, at 02:29 AM, Devan L wrote: > One line solution. > dict(re.findall(r"'(.+?)' \| '(.+?)'(?:\s\||$)",yourtexthere)) > > -- > http://mail.python.org/mailman/listinfo/python-list > From rgamble99 at gmail.com Sun Jul 10 22:56:05 2005 From: rgamble99 at gmail.com (Robert Gamble) Date: 10 Jul 2005 19:56:05 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> Message-ID: <1121050564.977260.51830@g44g2000cwa.googlegroups.com> Randy Howard wrote: > Keith Thompson wrote > (in article ): > > > > \||||/ | | \| __\,,\ /,,/__ > > \||/ | | | jgs (______Y______) > > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > > ============================================================== > > Out of curiosity, does anyone remember who 'jgs' refers to > above? Joan "Spunk" Stark, the author of quite a bit of ascii art, consult google for examples. Robert Gamble From martin at v.loewis.de Mon Jul 11 18:40:19 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 12 Jul 2005 00:40:19 +0200 Subject: gettext and "disambiguating comments" In-Reply-To: References: Message-ID: <42D2F553.3030009@v.loewis.de> Terry Hancock wrote: > /* Comment right before the gettext call, obviously in C */ > printf(_("Apparently ambiguous string to translate")); > > This will get captured into the .po file, according to the > gettext manual and appear as a comment right before > the msgid (i.e. next to the line number reference). Not automatically. You need to pass the -c option to xgettext to make that happen, preferably using a tag: /* TRANSLATORS: Comment right before the gettext call */ > Is there an equivalent Python gettext idiom? I've tried the > obvious > > # Comment right before the gettext call, now in Python > print _("Apparently ambiguous string to translate") > > But this is ignored by both pygettext and xgettext. Did you give -c to xgettext? It works for me, for xgettext 0.14.5. -c appears to be unimplemented in pygettext. Regards, Martin From grante at visi.com Thu Jul 14 14:44:46 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 14 Jul 2005 18:44:46 -0000 Subject: Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0? Message-ID: <11ddckucctde603@corp.supernews.com> I've read over and over that Python leaves floating point issues up to the underlying platform. This seems to be largely true, but not always. My underlying platform (IA32 Linux) correctly handles 1.0/0.0 and 0.0/0.0 according to the IEEE 754 standard, but Python goes out of its way to do the wrong thing. 1/0 is defined by the standard as +Inf and 0/0 is NaN. That's what my platform does for programs written in C. Python apparently checks for division by zero and throws and exception rather than returning the correct value calculated by the underlying platform. Is there any way to get Python to return the correct results for those operations rather than raising an exception? There's no way to "resume" from the exception and return a value from an exception handler, right? [This is the other option allowed by the IEEE 754 standard.] -- Grant Edwards grante Yow! ... I want a COLOR at T.V. and a VIBRATING BED!!! visi.com From fuzzyman at gmail.com Wed Jul 27 03:33:05 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Jul 2005 00:33:05 -0700 Subject: A Module on Time & Date In-Reply-To: References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: <1122449585.027193.96280@g43g2000cwa.googlegroups.com> There is a Python 2.2 compatible version. Part of the Pythonweb modules (google for it). It has *most* of the functionality. There is also the Dateutil module (although I don't know which version of Python that requires). There is also my own (now outdated) dateutils module that *might* help with date calculations. (and you did over react to an entirely normal suggestion). Best Regards, Fuzzy http://www.voidspace.org.uk/python From jason at tishler.net Fri Jul 22 12:44:42 2005 From: jason at tishler.net (Jason Tishler) Date: Fri, 22 Jul 2005 12:44:42 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E10D3B.5050301@llnl.gov> References: <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> Message-ID: <20050722164442.GB1912@tishler.net> Dean, Please keep your replies on-list. On Fri, Jul 22, 2005 at 08:14:03AM -0700, Dean N. Williams wrote: > Is there anyway for me to get back to an older version of Cygwin? What do you mean by the above? An older Cygwin? An older Cygwin Python? An older rebase? > In my Python2.4 log file, I tracked it down to the file > Python2.4/Modules/socketmodule.c file: 3350 INET_ADDSTRLEN, which > says "INET_ADDSTRLEN" is undeclared. I know this has something to do > with the _ssl extension. Is the above from building Python or CDAT? > Also in my Python2.4 log file, I see DB_LSTAT_ERR is undeclared. Has > something to do with the building of the gdbm extension. Ditto. > Also when I tryed "rebaseall" it no longer worked. When I went to > "Start/run..." and tried to run "ash", I got the error stating it > didn't know what "ash" was. Any help on this is appreciated. If Cygwin's bin is not in your Windows PATH, then give the full path to ash. For example: C:\Cygwin\bin\ash.exe Then start rebaseall is follows: $ PATH=/bin rebaseall Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From wccppp at gmail.com Sun Jul 3 04:35:18 2005 From: wccppp at gmail.com (wcc) Date: 3 Jul 2005 01:35:18 -0700 Subject: how to retrive highlighted text in a browser? Message-ID: <1120379718.126989.223300@g14g2000cwa.googlegroups.com> Hello group, When browsing websites, quite often I have to look up words in dictionary. I'm hoping that I can come up with a python program that does the following: When I highlight some text in browser and right-click, besides the default options such as COPY, PASTE, etc, I want an option that says "Send to file", something like that. The file is a text file, with fixed path. When I select this option, the highlighted text will be appended to the text file. This way, I can collect those words & phrases that I don't know. Is this going to be a difficult task? I'm a newbie in python. TIA for your help. - wcc From fairwinds at eastlink.ca Fri Jul 1 01:00:23 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 01 Jul 2005 02:00:23 -0300 Subject: Splitting string into dictionary In-Reply-To: <59e9fd3a0506302121197c545a@mail.gmail.com> Message-ID: <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> I have string text with language text records that looks like this: 'en' | 'the brown cow' | 'fr' | 'la vache brun' Two or more language records can exist in each string (example above shows 2 - but could contain more) The second vertical line character in the example above is the record break in the pattern (between 'cow' and 'fr') What is the shortest route to getting this into a dictionary like: {'en':'the brown cow','fr':'la vache brun'} The language code is always 2 lower case letters. Many thanks. From abpillai at gmail.com Thu Jul 14 01:15:53 2005 From: abpillai at gmail.com (Anand) Date: 13 Jul 2005 22:15:53 -0700 Subject: Porting from Python 2.3 to 2.4 Message-ID: <1121318153.193982.31460@g44g2000cwa.googlegroups.com> Hi Are there any tools that would help in porting code from Pyton 2.3 to 2.4 ? I have gone through the whatsnew documents and created a document comparing Python 2.4 to 2.3. But so far has not been able to find any tool that will signal code in Python 2.3 that can cause errors in Python 2.4 . rgds -Anand From thorsten at thorstenkampe.de Thu Jul 14 08:43:53 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 14 Jul 2005 13:43:53 +0100 Subject: How can I import a py script by its absolute path name? References: <87eka1eha8.fsf@titan.staselog.com> Message-ID: <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> * Edvard Majakari (2005-07-14 12:52 +0100) > could ildg writes: >> I want to import c:\xxx\yyy\zzz.py into my programme, >> What should I do? >> Thank you~ > > import sys > sys.path.append('c:\xxx\yyy') "sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')" From internet-drafts-reply at ietf.org Tue Jul 5 09:16:38 2005 From: internet-drafts-reply at ietf.org (Internet Draft Submission Manager) Date: Tue, 05 Jul 2005 09:16:38 -0400 Subject: [Auto Response] Returned mail: see transcript for details Message-ID: Greetings: This message is being sent to acknowledge receipt of your Internet-Draft submission or message to internet-drafts at ietf.org. If you submitted an Internet-Draft, then it will be posted on the Internet-Drafts page of the IETF Web site, and an I-D Action message will be sent to the I-D-Announce List. If you need to track the status of your Internet-Draft submission at a later date, then please send a note to ietf-action at ietf.org (using the suggested subject line Status of I-D Submission: ) and reference this auto-response acknowledgement in the body. Please note that all Internet-Drafts offered for publication as RFCs must conform to the requirements specified in I-D Checklist () or they will be returned to the author(s) for revision. Therefore, the IETF Secretariat strongly recommends that you address all of the issues raised in this document before submitting a request to publish your Internet-Draft to the IESG. The IETF Secretariat From gsakkis at rutgers.edu Tue Jul 5 15:43:26 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jul 2005 12:43:26 -0700 Subject: Python Regular Expressions: re.sub(regex, replacement, subject) References: Message-ID: <1120592606.195752.181010@g44g2000cwa.googlegroups.com> "Vibha Tripathi" wrote: > Hi Folks, > > I put a Regular Expression question on this list a > couple days ago. I would like to rephrase my question > as below: > > In the Python re.sub(regex, replacement, subject) > method/function, I need the second argument > 'replacement' to be another regular expression ( not a > string) . So when I find a 'certain kind of string' in > the subject, I can replace it with 'another kind of > string' ( not a predefined string ). Note that the > 'replacement' may depend on what exact string is found > as a result of match with the first argument 'regex'. In re.sub, 'replacement' can be either a string, or a callable that takes a single match argument and should return the replacement string. So although replacement cannot be a regular expression, it can be something even more powerful, a function. Here's a toy example of what you can do that wouldn't be possible with regular expressions alone: >>> import re >>> from datetime import datetime >>> this_year = datetime.now().year >>> rx = re.compile(r'(born|gratuated|hired) in (\d{4})') >>> def replace_year(match): >>> return "%s %d years ago" % (match.group(1), this_year - int(match.group(2))) >>> rx.sub(replace_year, 'I was born in 1979 and gratuated in 1996.') 'I was born 26 years ago and gratuated 9 years ago' In cases where you don't have to transform the matched string (such as calling int() and evaluating an expression as in the example) but only append or prepend another string, there is a simpler solution that doesn't require writing a replacement function: backreferences. Replacement can be a string where \1 denotes the first group of the match, \2 the second and so on. Continuing the example, you could hide the dates by: >>> rx.sub(r'\1 in ****', 'I was hired in 2001 in a company of 2001 employees.') 'I was hired in **** in a company of 2001 employees.' By the way, run the last example without the 'r' in front of the replacement string and you'll see why it is there for. HTH, George From jan.danielsson at gmail.com Sat Jul 30 20:11:28 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Sun, 31 Jul 2005 02:11:28 +0200 Subject: Escaping certain characters In-Reply-To: References: <42ec0f65$1@griseus.its.uu.se> Message-ID: <42ec15c0$1@griseus.its.uu.se> Robert Kern wrote: [---] > In [3]: s.encode('string_escape') > Out[3]: 'Hello\\nWorld!' > > In [4]: Out[3].decode('string_escape') > Out[4]: 'Hello\nWorld!' > > Not *quite* what you asked for, but it ought to be close enough. That'll do just fine. Many thanks! From thomas at thomas-lotze.de Fri Jul 15 07:44:00 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Fri, 15 Jul 2005 13:44:00 +0200 Subject: using hotshot for timing and coverage analysis References: Message-ID: Andreas Lobinger wrote: > hotshot.Profile has flags for recording timing per line and line events. > Even if i had both set to 1 i still get only the standard data (time per > call). Could it be that pstats.Stats doesn't know about hotshot? Haven't checked... What's much more annoying about hotshot is that loading the stats takes ages if one profiles stuff that runs about half a minute or so. At least it does that on Python 2.4.1a0 as shipped with Debian testing a while ago. > Is there any document available that has examples how to use the hotshot > for converage analysis and to display timing per line? Haven't looked thoroughly yet; all I know is what's in the Python docs. -- Thomas From gsakkis at rutgers.edu Fri Jul 8 08:27:07 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Jul 2005 05:27:07 -0700 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> Message-ID: <1120825627.498017.19370@g47g2000cwa.googlegroups.com> "Ron Adam" wrote: > Here's something interesting: > > import time > > x = None > t = time.time() > for i in range(1000000): > if x==None: > pass > print 'None:',time.time()-t > > x = 'to-end' > t = time.time() > for i in range(1000000): > if x=='to-end': > pass > print 'String:',time.time()-t > > >>> > None: 0.46799993515 > String: 0.360000133514 > > > Of course the difference this would make on a single call in practically > Nill. > How about using the right way of comparing with None ? x = None t = time.time() for i in range(1000000): if x is None: pass print 'is None:',time.time()-t I get: None: 0.549999952316 String: 0.498000144958 is None: 0.450000047684 > Anyway, time to call it a night so tomorrow I don't make anymore silly > mistakes on comp.lang.python. :) That would be a great idea ;-) An even greater idea would be to give up on this "None should mean undefined" babble; it looks like a solution looking for a problem and it raises more complications than it actually solves (assuming it does actually solve anything, which is not quite obvious). > Cheers, > Ron Cheers, George From guy.lateur at b-b.be Fri Jul 8 10:26:05 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Fri, 08 Jul 2005 14:26:05 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: <0kvze.140169$Q37.7422045@phobos.telenet-ops.be> Message-ID: <12wze.140192$_L6.7407755@phobos.telenet-ops.be> python version: import win32com.client myOL = win32com.client.Dispatch("Outlook.Application") myNS = myOL.GetNamespace("MAPI") sItem = win32com.client.Dispatch("Redemption.SafeMailItem") myDestBox = myNS.GetDefaultFolder(6) oItem = myDestBox.Items.Add(0) sItem.Item = oItem sItem.Import("H:\\Inhoud-iedereen\\Inhoud-Guy\\app\\BBProject\\data\\test\\Leemarchitect.msg", 3) sItem.Save() From http Sun Jul 3 13:09:31 2005 From: http (Paul Rubin) Date: 03 Jul 2005 10:09:31 -0700 Subject: Tkinter Checkbutton initialization problem References: <7xzmt4fd5m.fsf@ruckus.brouhaha.com> <42c7fefc$1@nntp0.pdx.net> Message-ID: <7x7jg7ke9g.fsf@ruckus.brouhaha.com> Scott David Daniels writes: > Paul Rubin wrote: > > Python 2.4, Windows XP. If I say: > > f = Frame() > > f.grid() > > v = IntVar() > v.set(1) # Might help. v.get() at this point returned 0 for me. Yeah, I tried that too. Further reorganization of the code in some other way suddenly made it start working. I'll have to examine it to see what I did since I wasn't paying attention to that particular problem at the time. I had checked sf.net for a bug report on this and didn't see one, but maybe didn't check carefully enough. I'll look a little more and then file one, I guess. From fuzzyman at gmail.com Fri Jul 29 06:13:28 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jul 2005 03:13:28 -0700 Subject: how to append cgi FieldStorage Class instance In-Reply-To: References: <1122624726.598516.281570@g43g2000cwa.googlegroups.com> Message-ID: <1122632008.765050.111680@g43g2000cwa.googlegroups.com> praba kar wrote: > --- Fuzzyman wrote: > > > > > praba kar wrote: > > > Dear All, > > > I have doubt in python cgi script. I describe > > > that doubt with below code > > > import cgi > > > form = cgi.FieldStorage() > > > passwd = form['passwd'].value > > > print passwd > > > But Now I want to assign some value to > > form['passwd'] > > > field value > > > form['passwd'] = 'surese' > > > Now If I try to print > > > print form['passwd'].value. It will raise error. > > > So kinldy let me how to edit or append instance > > > of FieldStorage class > > > > > > > A form *isn't* a dictionary, this means that your > > code : > > form['passwd'] = 'surese' > > > > is wrong. > > Turn the form into a dictionary and use that. > > How Can I convert a form instance into dictionary > Kindly let me know. > What have you tried ? ;-) def form_to_dict(form): out_dict = {} for entry in form: out_dict[entry] = form[entry].value return out_dict UNTESTED AND FROM MEMORY If it doesn't work - try reading the manual to see what I did wrong..... > Why are you trying to assign values directly in the > form ? > > To reduce variable usage in my project. At the cost of clarity ? Not a worthwhile trade off. Explicity delet variables you have finished with instead. form = cgi.FieldStorage() formdict = form_to_dict(form) del form Best Regards, Fuzzy http://www.voidspace.org.uk/python > regards > Prabahar > > > > > __________________________________________________________ > How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From dalke at dalkescientific.com Fri Jul 22 19:49:41 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 22 Jul 2005 23:49:41 GMT Subject: Something that Perl can do that Python can't? References: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> <1122066437.870669.58990@z14g2000cwz.googlegroups.com> Message-ID: Dr. Who wrote: > Well, I finally managed to solve it myself by looking at some code. > The solution in Python is a little non-intuitive but this is how to get > it: > > while 1: > line = stdout.readline() > if not line: > break > print 'LINE:', line, > > If anyone can do it the more Pythonic way with some sort of iteration > over stdout, please let me know. Python supports two different but related iterators over lines of a file. What you show here is the oldest way. It reads up to the newline (or eof) and returns the line. The newer way is for line in stdout: ... which is equivalent to _iter = iter(stdout) while 1: try: line = _iter.next() except StopIteration: break ... The file.__iter__() is implemented by doing a block read and internally breaking the block into lines. This make the read a lot faster because it does a single system call for the block instead of a system call for every character read. The downside is that the read can block (err, a different use of "block") waiting for enough data. If you want to use the for idiom and have the guaranteed "no more than a line at a time" semantics, try this for line in iter(stdout.readline, ""): print "LINE:", line sys.stdout.flush() Andrew dalke at dalkescientific.com From nethawg1 at verizon.net Mon Jul 18 19:13:48 2005 From: nethawg1 at verizon.net (windozbloz) Date: Mon, 18 Jul 2005 23:13:48 GMT Subject: Python scripts wont run - HELP References: <42dbd734_2@x-privat.org> <87irz7j3rc.fsf@localhost.localdomain> Message-ID: Nick Vargish wrote: > windozbloz writes: > >> It now works from the command line like you said. Shouldn't I also be >> able to 'click' an icon that has been set to executable and launch the >> whole process that way? > > You'll need to put an interpreter line at the beginning of your > script, as other posters have indicated. This tells the shell how to > handle the file. > > When you double-click a program icon in your file browser, the browser > starts a shell process which is handed the file's name for > execution. > > #!/usr/bin/python > > Says, "This file is interpreted by /usr/bin/python". The idiom you > will often see: > > #!/usr/bin/env python > > Says, "Find 'python' in this user's environment, and give this file to > that program for interpretation". That allows you to use a different > python interpreter (say, /usr/local/bin/python if that comes first on > your PATH environment variable), and allows the script to be more > friendly for systems that do not have a /usr/bin/python. > > Depending on the GUI, you may not see a terminal window open for the > script's execution, or the terminal might close as soon as the script > exits, which will prevent you from looking at any output. Unless the > program has a GUI, running it from the command-line is usually better > than double-clicking it in a file browser. > > Nick > Thats good info Nick, Thanks. I'm going to go try the two methods now. Doug -- LINUX protects me from the GATES of hell !!! From http Wed Jul 13 23:57:54 2005 From: http (Paul Rubin) Date: 13 Jul 2005 20:57:54 -0700 Subject: Inconsistency in hex() References: Message-ID: <7xpstmhwe5.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > >>> hex(75) > '0x4b' > >>> hex(75*256**4) > '0x4B00000000L' > > By accident or design? Apart from the aesthetic value that lowercase hex > digits are ugly, should we care? Use ('%x' % 75) or ('%X' % 75) if you care. From xah at xahlee.org Tue Jul 12 07:43:33 2005 From: xah at xahlee.org (Xah Lee) Date: 12 Jul 2005 04:43:33 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: <1121168613.782691.324280@g47g2000cwa.googlegroups.com> Most participants in the computering industry should benefit in reading this essay: George Orwell's ?Politics and the English Language?, 1946. Annotated: http://xahlee.org/p/george_orwell_english.html Xah xah at xahlee.org ? http://xahlee.org/ From samgurung at gmail.com Thu Jul 21 05:06:45 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 02:06:45 -0700 Subject: Python IDE In-Reply-To: <1121911146.213579.28630@g14g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> <1121911146.213579.28630@g14g2000cwa.googlegroups.com> Message-ID: <1121936805.197754.30560@g44g2000cwa.googlegroups.com> ok will give it a shot. I had tried the 0.7.2 version with wxPython 2.6 and the moment i place the cursor in a class name and pressed the space or the enter key.....booom there it went crashing without a trace. But i did like what little i saw of it (apart from the crashes, of course) and the UML diagram feature was just great. Lemme use this version and then i can give some feedback. One more thing....I'm trying to use the wxStyledTextCtrl in one of my programs....any pointers to where I can find a good tutorial....Tried yellowbrain.com but it just has the docs and not a tutorial. Thanks a ton and keep up the good work From benji at benjiyork.com Tue Jul 5 13:42:32 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 05 Jul 2005 13:42:32 -0400 Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: <42CAC688.1030902@benjiyork.com> Sybren Stuvel wrote: > I always use one tab for indents, and set my editor to display it as > four spaces. I like being able to unindent a line by deleting a single > character. Your editor probably supports a "backspace unindents" option. If using Vim it would be something like "set softtabstop=4". -- Benji York From trentm at ActiveState.com Fri Jul 8 16:05:50 2005 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 8 Jul 2005 13:05:50 -0700 Subject: qustion about build Python on the Solaris 9 In-Reply-To: References: Message-ID: <20050708200550.GA18958@ActiveState.com> [Hu, Bizhong wrote] > My question is that is > anyone know if python can > Be build as 64 bits application on SPARC ??? I don't know of any reason why not. I haven't built for *64-bit* SPARC yet but Python builds fine 32-bit on SPARC and build fine 64-bit on a number of other platforms (linux-x86_64, linux-ia64, win64-ia64, win64-x64, 64-bit AIX). Trent -- Trent Mick TrentM at ActiveState.com From erniedude at gmail.com Mon Jul 25 15:57:23 2005 From: erniedude at gmail.com (Ernesto) Date: 25 Jul 2005 12:57:23 -0700 Subject: Run batch files in Windows XP In-Reply-To: <1122320850.623089.88360@g49g2000cwa.googlegroups.com> References: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> <1122318744.969547.113640@g43g2000cwa.googlegroups.com> <9v2dnYY1NvZtoXjfRVn-ug@powergate.ca> <1122320850.623089.88360@g49g2000cwa.googlegroups.com> Message-ID: <1122321443.649543.207300@z14g2000cwz.googlegroups.com> Looks like I'm not getting my parameters to my batch file correctly. I'm using os.system like this: os.system('bootmanager.bat %s' %"BOOTMANAGER ALL") where 'BOOTMANAGER ALL' is what I type at the command prompt arguments. That must not be right? From fdeserres at gmx.net Wed Jul 6 13:59:48 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 06 Jul 2005 19:59:48 +0200 Subject: The GIL, callbacks, and GPFs Message-ID: <42CC1C14.2080509@gmx.net> Hello, I'm chasing a GPF in the interpreter when running my extension module. It's not very elaborated, but uses a system (threaded) callback, and therefore the GIL. Help would be mucho appreciated. Here's the rough picture: win32_spam.c ------------ /* code here is unit-tested OK */ typedef struct Bag { char data[128]; site_t size; } Bag; typedef void (*PCallback)(const Bag * const bag); Bag bag; PCallback user_callback = NULL; /* called by windoz */ static void CALLBACK win32_call_me(void) { memcpy(bag.data, somestuff, 100); bag.size = 100; SPAWN_THREAD(user_callback, & bag);//pseudo-code } spam_module.c ------------- /* most of the code here is pasted from doc */ static PyObject * my_callback = NULL; static PyObject * setCallback(PyObject *dummy, PyObject *args) { PyObject *result = NULL; PyObject *temp; if (PyArg_ParseTuple(args, "O:miSetCallback", &temp)) { if ((temp != Py_None) && (!PyCallable_Check(temp))) { PyErr_SetString(PyExc_TypeError, "parameter must be callable"); return NULL; } Py_XINCREF(temp); Py_XDECREF(my_callback); my_callback = temp; Py_INCREF(Py_None); result = Py_None; /* set the actual callback in win32_spam.c */ user_callback = & external_callback; } return result; } static void external_callback(const Bag * const bag) { if (my_callback && (my_callback != Py_None)) { PyObject * arglist = NULL; PyObject * result = NULL; arglist = Py_BuildValue("(s#)", bag->data, bag->size); /* do it */ PyGILState_STATE gil = PyGILState_Ensure(); result = PyEval_CallObject(my_callback, arglist); PyGILState_Release(gil); Py_DECREF(arglist); Py_DECREF(result); } } blowup_spam1.py ------------- # This throws a GPF on callback. # Why, since the GIL is acquired by the callback? import spam.py def callback(stuff): print stuff if __name__ == '__main__': spam.setCallback(callback) raw_input() blowup_spam2.py ------------- # This throws a GPF as well # Why, since we're using a threadsafe queue? import spam import Queue q = Queue.Queue() def callback(stuff): q.put(stuff) if __name__ == '__main__': spam.setCallback(callback) while True: print q.get() nice_spam.py ------------- # This works # Why, since the rest did not? import spam import Queue import threading q = Queue.Queue() def callback(stuff): q.put(stuff) def job(): while True: print q.get() if __name__ == '__main__': spam.setCallback(callback) t = threading.Thread(job) t.start() raw_input() Please point me to what I'm doing wrong... TIA, Francois PS: I've already submitted my issue under "(Win32 API) callback to Python, threading hiccups", but I guess it was poorly formulated. From godwinburby at rediffmail.com Mon Jul 4 00:18:35 2005 From: godwinburby at rediffmail.com (godwin) Date: 3 Jul 2005 21:18:35 -0700 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: <1120450715.536822.101690@z14g2000cwz.googlegroups.com> Actually i want to create a "google" like web interface to any rdbms and search as we all do it in google.That would be great isn't it. Thank u for your queries. From benji at benjiyork.com Tue Jul 12 21:51:47 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 12 Jul 2005 21:51:47 -0400 Subject: Fredericksburg, VA ZPUG Meeting Message-ID: <42D473B3.6070109@benjiyork.com> When: July 13, 7:30-9:00 PM Where: Zope Corp offices (513 Prince Edward Street; Fredericksburg, VA 22408) Details at http://www.zope.org/Members/poster/fxbgzpug_announce_2 Hope to see you there! -- Benji York From clemenr at wmin.ac.uk Thu Jul 14 10:37:13 2005 From: clemenr at wmin.ac.uk (clemenr at wmin.ac.uk) Date: 14 Jul 2005 07:37:13 -0700 Subject: Synthesis Toolkit bindings for python? Message-ID: <1121351833.272380.161790@g43g2000cwa.googlegroups.com> Hi. Are there any python bindings for the Synthesis Toolkit? http://ccrma.stanford.edu/software/stk/ I've done a quick search on the web but found nothing. Cheers, Ross-c From tim.peters at gmail.com Fri Jul 15 00:06:17 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 15 Jul 2005 00:06:17 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae050714210628544623@mail.gmail.com> [Michael Hudson] >>>>> In what way does C99's fenv.h fail? Is it just insufficiently >>>>> available, or is there some conceptual lack? [Tim Peters] >>>> Just that it's not universally supported. Look at fpectlmodule.c for >>>> a sample of the wildly different ways it _is_ spelled across some >>>> platforms. [Michael] >>> C'mon, fpectlmodule.c is _old_. Maybe I'm stupidly optimistic, but >>> perhaps in the last near-decade things have got a little better here. [Tim] >> Ah, but as I've said before, virtually all C compilers on 754 boxes >> support _some_ way to get at this stuff. This includes gcc before C99 >> and fenv.h -- if the platforms represented in fpectlmodule.c were >> happy to use gcc, they all could have used the older gcc spellings >> (which are in fpectlmodule.c, BTW, under the __GLIBC__ #ifdef). [Michael] > Um, well, no, not really. The stuff under __GLIBC___ unsurprisingly > applies to platforms using the GNU project's implementation of the C > library, and GCC is used on many more platforms than just that > (e.g. OS X, FreeBSD). Good point taken: parings of C compilers and C runtime libraries are somewhat fluid. So if all the platforms represented in fpectlmodule.c were happy to use glibc, they all could have used the older glibc spellings. Apparently the people who cared enough on those platforms to contribute code to fpectlmodule.c did not want to use glibc, though. In the end, I still don't know why there would be a reason to hope that an endless variety of other libms would standardize on the C99 spellings. For backward compatibility, they have to continue supporting their old spellings too, and then what's in it for them to supply aliases? Say I'm SGI, struggling as often as not just to stay in business. I'm unlikely to spend what little cash I have to make it easier for customers to jump ship . > ... > Even given that, the glibc section looks mighty Intel specific to me (I don't > see why 0x1372 should have any x-architecture meaning). Why not? I don't know whether glibc ever did this, but Microsoft's spelling of this stuff used to, on Alphas (when MS compilers still supported Alphas), pick apart the bits and rearrange them into the bits needed for the Alpha's FPU control registers. Saying that bit 0x10 (whatever) is "the overflow flag" (whatever) is as much a x-platform API as saying that the expansion of the macro FE_OVERFLOW is "the overflow flag". Fancy pants symbolic names are favored by "computer science" types these days, but real numeric programmers have always been delighted to wallow in raw bits . ... > One thing GCC doesn't yet support, it turns out, is the "#pragma STDC > FENV_ACCESS ON" gumpf, which means the optimiser is all too willing to > reorder > > feclearexcept(FE_ALL_EXCEPT); > r = x * y; > fe = fetestexcept(FE_ALL_EXCEPT); > > into > > feclearexcept(FE_ALL_EXCEPT); > fe = fetestexcept(FE_ALL_EXCEPT); > r = x * y; > > Argh! Declaring r 'volatile' made it work. Oh, sigh. One of the lovely ironies in all this is that CPython _could_ make for an excellent 754 environment, precisely because it does such WYSIWYG code generation. Optimizing-compiler writers hate hidden side effects, and every fp operation in 754 is swimming in them -- but Python couldn't care much less. Anyway, you're rediscovering the primary reason you have to pass a double lvalue to the PyFPE_END_PROTECT protect macro. PyFPE_END_PROTECT(v) expands to an expression including the subexpression PyFPE_dummy(&(v)) where PyFPE_dummy() is an extern that ignores its double* argument. The point is that this dance prevents C optimizers from moving the code that computes v below the code generated for PyFPE_END_PROTECT(v). Since v is usually used soon after in the routine, it also discourages the optimizer from moving code up above the PyFPE_END_PROTECT(v) (unless the C does cross-file analysis, it has to assume that PyFPE_dummy(&(v)) may change the value of v). These tricks may be useful here too -- fighting C compilers to the death is part of this game, alas. PyFPE_END_PROTECT() incorporates an even stranger trick, and I wonder how gcc deals with it. The Pentium architecture made an agonizing (for users who care) choice: if you have a particular FP trap enabled (let's say overflow), and you do an fp operation that overflows, the trap doesn't actually fire until the _next_ fp operation (of any kind) occurs. You can honest-to-God have, e.g., an overflowing fp add on an Intel box, and not learn about it until a billion cycles after it happened (if you don't do more FP operations over the next billion cycles). So "the other thing" PyFPE_END_PROTECT does is force a seemingly pointless double->int conversion (it always coerces 1.0 to an int), just to make sure that a Pentium will act on any enabled trap that occurred before it. If you have in mind just testing flags (and staying away from enabling HW traps -- and this is the course I recommend), this shouldn't matter (the sticky status flag is set immediately, it's only triggering the correspondnig trap that's delayed). I haven't studied C99 deeply enough to determine whether it has weasle words allowing traps to be delayed indefinitely, but that kind of HW-driven compromise is common in the C standards. Not to imply that this isn't all dead easy . From eurleif at ecritters.biz Wed Jul 6 12:35:10 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 06 Jul 2005 16:35:10 GMT Subject: Conditionally implementing __iter__ in new style classes In-Reply-To: References: Message-ID: <2LTye.1891$Q75.302879@newshog.newsread.com> Thomas Heller wrote: > I forgot to mention this: The Base class also implements a __getitem__ > method which should be used for iteration if the .Iterator method in the > subclass is not available. So it seems impossible to raise an exception > in the __iter__ method if .Iterator is not found - __iter__ MUST return > an iterator if present. def Iterator(self): for index in xrange(len(self)): yield self[index] def __iter__(self): return self.Iterator() ...and then override Iterator in subclasses. But this raises the question of why you need to use a specially-named method instead of having subclasses override the __iter__. From p at ulmcnett.com Thu Jul 21 11:49:17 2005 From: p at ulmcnett.com (Paul McNett) Date: Thu, 21 Jul 2005 08:49:17 -0700 Subject: difficulty connecting to networked oracle database In-Reply-To: References: Message-ID: <42DFC3FD.8080208@ulmcnett.com> yahibble wrote: > Now, I am no Python expert but I have dabbled and I have spent a > couple of days with another engineer unsuccessfully installing oracle > drivers for MS ODBC on the win XP machine. > > It looked to me like ODBC was the best way to get a (free) python > module to upload data to an oracle database table. Aside from > installing oracle clients to ODBC being a pain, I would like to > consider other ways to connect. > > Has anyone had experiences with Python connecting to oracle from Win > XP? I have searched the 'net for various modules and discussions but > have no success thus far. I don't have specific experience with Oracle and Python, but I do know that using Python's DB-API is usually the best way to go. For Oracle, everyone seems to be using cx_oracle, a Python package freely downloadable from: http://www.computronix.com/utilities.shtml ODBC isn't really the best solution for Python programs. -- Paul McNett http://paulmcnett.com From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 23 11:04:54 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 23 Jul 2005 17:04:54 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> Message-ID: <3kf4kmFsu26jU1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: >> One thing is still different, though: a Path instance won't compare to a regular >> string. > > Could you please expand on what this means? Are you referring to doing > < and >= type operations on Paths and strings, or == and != or all those > or something else entirely? All of these. Do you need them? >> Other minor differences, as requested on python-dev, are: >> >> * size property -> getsize() method. >> * atime/mtime/ctime properties -> atime()/mtime()/ctime() methods > > What does this mean? The .size property and a getsize() method both > already exist (in my copy of path.py anyway) and do the same thing. > Same with the other ones mentioned above. Is someone working from an > out-of-date copy of path.py? No. But the size of a file is somewhat volatile, and does not feel like a "property" of the path to it. Remember: the path is not the file. Same goes with the xtime() methods. Different is the basename/directory/etc.: as long as the path stays the same, these properties will stay the same. >> * dirs() method -> subdirs() method > > Given that .files() exists, and returns a list of the files contained in > a path which represents a folder, why would one want to use subdirs() > instead of just dirs() to do the same operation for contained folders? > If subdirs() is preferred, then I suggest subfiles() as well. Otherwise > the change seems arbitrary and ill-conceived. Well, I think that's right. Will change back to dirs(). >> * joinpath() method -> added alias joinwith() >> * splitall() method -> parts() method > > This reminds me of the *one* advantage I can think of for not > subclassing basestring, though it still doesn't make the difference in > my mind: strings already have "split()", so Jason had to go with > "splitpath()" for the basic split operation to avoid a conflict. A > minor wart I guess. At the moment, I think about overriding certain string methods that make absolutely no sense on a path and raising an exception from them. >> * Default constructor: Path() == Path(os.curdir) > > To construct an empty path then one can still do Path('') ? Yes. >> * staticmethod Path.getcwd() -> Path.cwd() >> >> * bytes() / lines() / text() -> read_file_{bytes,lines,text} methods >> * write_{bytes,lines,text} -> write_file_{bytes,lines,text} methods > > Under Linux isn't it possible to open and read from directories much as > with files? If that's true, the above would seem to conflict with that > in some way. As with the the .subdirs() suggestion above, these changes > seem to me somewhat arbitrary. .bytes() and friends have felt quite > friendly in actual use, and I suspect .read_file_bytes() will feel quite > unwieldy. Not a show-stopper however. It has even been suggested to throw them out, as they don't have so much to do with a path per se. When the interface is too burdened, we'll have less chance to be accepted. Renaming these makes clear that they are not operations on the path, but on a file the path points to. Phillip J. Eby suggested these to be set_file_xxx and get_file_xxx to demonstrate that they do not read or write a stream; how about that? Reinhold From devlai at gmail.com Mon Jul 25 00:46:57 2005 From: devlai at gmail.com (Devan L) Date: 24 Jul 2005 21:46:57 -0700 Subject: Problem loading a file of words In-Reply-To: References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> <1122264873.347064.195990@f14g2000cwb.googlegroups.com> Message-ID: <1122266817.107024.274080@g14g2000cwa.googlegroups.com> Robert Kern wrote: > That's definitely not the kind of dictionary that he wants. > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter Oh, I missed the part where he put values in a list. From fowlertrainer at mailpont.hu Tue Jul 19 10:20:45 2005 From: fowlertrainer at mailpont.hu (fowlertrainer at mailpont.hu) Date: Tue, 19 Jul 2005 16:20:45 +0200 Subject: wxPython - DB Form generator unit Message-ID: <42DD0C3D.7040408@mailpont.hu> Hi ! Is anyone know about a DB form generator unit under wxPython ? What that's means ? I add information about a Query, or a ListOfDict, I set some other infos (Lookups, others), and it is generate a Form with edit boxes, listboxes, etc. Then I can fill up the form with a record's datas. User can modify them. After I can call Apply method, and every modifications are stored in a result. That is very important thing, when you have many record editor forms. Don't need to create them one-to-one, not need to repeat many codes... Is anyone have an idea ? Thanx: ft From rbt at athop1.ath.vt.edu Wed Jul 13 11:40:02 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 13 Jul 2005 11:40:02 -0400 Subject: all possible combinations In-Reply-To: <1121267364.28617.4.camel@athop1.ath.vt.edu> References: <1121267364.28617.4.camel@athop1.ath.vt.edu> Message-ID: <1121269202.29571.1.camel@athop1.ath.vt.edu> On Wed, 2005-07-13 at 11:09 -0400, rbt wrote: > On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: > > Say I have a list that has 3 letters in it: > > > > ['a', 'b', 'c'] > > > > I want to print all the possible 4 digit combinations of those 3 > > letters: > > > > 4^3 = 64 > > > > aaaa > > abaa > > aaba > > aaab > > acaa > > aaca > > aaac > > ... > > > > What is the most efficient way to do this? > > Expanding this to 4^4 (256) to test the random.sample function produces > interesting results. It never finds more than 24 combinations out of the > possible 256. This leads to the question... how 'random' is sample ;) > > Try it for yourselves: > > test = list('1234') > > combinations = [] > while 1: > combo = random.sample(test, 4) > possibility = ''.join(combo) > if possibility not in combinations: > print possibility > combinations.append(possibility) > continue > else: > continue > Someone pointed out off-list that this is doing permutation, not combination. Is there a way to make random.sample to do combinations? From nyamatongwe+thunder at gmail.com Fri Jul 22 21:41:02 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 23 Jul 2005 01:41:02 GMT Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: One thing I don't like with GTK+ on Windows is that it uses GTK+ file dialogs rather than system file dialogs. wxWidgets uses file dialogs that appear very similar to the system dialogs. Depends on your customers but I don't think this is reasonable for most applications. http://www.scintilla.org/GtkFile.png Neil From winder at interchange.ubc.ca Sat Jul 16 08:54:43 2005 From: winder at interchange.ubc.ca (WGW) Date: Sat, 16 Jul 2005 05:54:43 -0700 Subject: HTML expect in python In-Reply-To: References: Message-ID: Thanks for these replies -- looks like I have all I need; now it is just a question of getting my head around the applications and doing some testing... Many thanks for pointers. From nicolas.couture at gmail.com Thu Jul 14 22:28:14 2005 From: nicolas.couture at gmail.com (Nicolas Couture) Date: 14 Jul 2005 19:28:14 -0700 Subject: Generating a list of None In-Reply-To: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> References: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> Message-ID: <1121394494.674503.303040@z14g2000cwz.googlegroups.com> of course the later snipplet should be: --- def get_options(opts): """Return True or False if an option is set or not""" vals = opts.__dict__.values() if vals == [None * len(vals)]: return False return True --- From phillip.watts at anvilcom.com Sat Jul 2 17:26:22 2005 From: phillip.watts at anvilcom.com (phil) Date: Sat, 02 Jul 2005 16:26:22 -0500 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: <42C7067E.4090609@anvilcom.com> > either... It sits under... Well that's a relief, cause ...sits on top of.... was confusing. > A rather object-oriented system for managing and serving web > applications and data (using object inheritance for common behavior, > etc.) This makes Zope a toolkit, not an end application itself. So that would make it Apache, with a Python CGI. Oh wait, Apache has a Python CGI which can access Data bases and send objects to the client. A web application is you deliver am html page and the user fills in some forms, then submits the form, which is then validated and another form is delivered. Right? Cool idea, IBM had that in 1975 it was called CICS. I once asked my son-in-law tech support guy what is the Windows registry, what does it do? He thought for a while and said "Think of it as the soul of the machine". So I thought about it as the soul of the machine for a while, then I asked; "You don't know, do you", and he said "No." From me at privacy.net Mon Jul 11 23:20:02 2005 From: me at privacy.net (Dan Sommers) Date: Mon, 11 Jul 2005 23:20:02 -0400 Subject: __autoinit__ References: <86ll4csyn4.fsf@bhuda.mired.org> Message-ID: On Mon, 11 Jul 2005 19:37:03 -0400, Mike Meyer wrote: > The question is - how far are you really willing to carry this? What > do you think of allowing arbitrary lvalues, with the assumption that > the previous arguments are all defined (ala let*)? So you could do: > class grouping: > def __init__(self, x, x['abc']): > pass Python already implements let*; it's called "tuple unpacking": Python 2.3.3 (#1, Mar 9 2004, 14:21:31) [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x, x['abc'] = {}, 3 >>> print x {'abc': 3} >>> x, x['abc'], x['abc'][4] = {}, range(10), -9999 >>> print x {'abc': [0, 1, 2, 3, -9999, 5, 6, 7, 8, 9]} Regards, Dan -- Dan Sommers From chenyang2000 at 126.com Sat Jul 23 13:14:52 2005 From: chenyang2000 at 126.com (=?gb2312?B?s8LR9A==?=) Date: Sun, 24 Jul 2005 01:14:52 +0800 (CST) Subject: =?gb2312?B?SG93IHRvIHJlYWxpemUgc3NoICYgc2NwIGluIFB5dGhvbg==?= Message-ID: <42E27B0C.000136.18200@m111.126.com> I would like to write a Python code like this: It can login a host by SSH after login the host, use SCP to get a remote file, so it can deliver file to the host. then execute the program then leave the host For example : STEP 1. ssh xxxx_yyy at 123.45.67.89 STEP 2. Enter the password automatically STEP 3. run " scp -r zzz at 123.45.67.90:/home/xxx/program ." STEP 4. Enter the password for SCP automatically STEP 5. run "./program" STEP 6. run " exit" I know telnetlib can help us with telnet, and how to deal with this SSH situation in Python? Thanks a lot for your help :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From groups at jpprice.info Wed Jul 20 18:22:26 2005 From: groups at jpprice.info (groups at jpprice.info) Date: 20 Jul 2005 15:22:26 -0700 Subject: File Table List in Plone Message-ID: <1121898146.737821.198540@z14g2000cwz.googlegroups.com> All, Is there is a Plone type or product for generating a file list on a plone page, eg: a list of downloadable files in a table? An example of what I want can be found at http://www.zope.org/Members/MacGregor/ExtFile under "Available Releases" where a list of files resides. Is this a manually generated table or is there a way I can drop a Plone type into a page to generate such a list? Thanks, Pat groups at jpprice.info From diesch at spamfence.net Mon Jul 11 00:06:18 2005 From: diesch at spamfence.net (Florian Diesch) Date: Mon, 11 Jul 2005 06:06:18 +0200 Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> <20050710171221.GA29664@phenix.progiciels-bpi.ca> Message-ID: <20050711040618.272C.0.NOFFLE@dieschf.news.arcor.de> Fran?ois Pinard wrote: >> > Mascyma is (trying to be) a user-friendly graphical frontend for >> > the Computer Algebra System GNU MAXIMA. > >> I was not successful googling for this one. Would you have an URL handy? > > Oops, OK! Found it at http://cens.ioc.ee/~pearu/misc/maxima/ . As I'm reading news offline I don't know what's on that page. The Ubuntu Linux copyright file says the files are obtained from and you can find more information at Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From chandra.bangalore at gmail.com Fri Jul 8 00:11:48 2005 From: chandra.bangalore at gmail.com (chand) Date: 7 Jul 2005 21:11:48 -0700 Subject: calling python procedures from tcl using tclpython In-Reply-To: <42CD292C.1010204@uni-oldenburg.de> References: <1120740561.933409.221770@g14g2000cwa.googlegroups.com> <42CD292C.1010204@uni-oldenburg.de> Message-ID: <1120795908.918051.129670@g43g2000cwa.googlegroups.com> Hi., can anyone help me how to provide the info about the python file procedure in the tcl script which uses tclpython i.e., is there a way to import that .py file procedure in the tcl script --BestRegards --Chandra Michael Schlenker wrote: > chand wrote: > > Hi.. > > > > I am writing a Gui in TCL and my backend code is python. I want to call > > python procedure in tcl using tclpyhton. I want to know clearly how > > this should be implemented. > > > > let's say I have procedure test_function(arg1,arg2 ...) defined in > > test.py. > > I want to call this procedure in tcl. Let me know how this should be > > achieved. > > The doubt basically have is how the tcl code knows in which .py file > > this procedure is defined. > > > > currently I have wriiten this tcl code which is not working > > > > package require tclpython > > set interpreter [python::interp new] > > $interpreter eval {def test_function(): arg1,arg2} ; > > python::interp delete $interpreter > > > What does not work? You never load your file test.py anywhere inside, > you just evaluate 'def test_function(): arg1,arg2' so what are you > expecting to happen? > > Your call to '$interpreter eval' lets you call arbitrary python code, > but you have to provide the python code that loads your function > definitions etc. I don't know python, but it should be a trivial code. > > Michael From godoy at ieee.org Fri Jul 29 23:07:05 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 30 Jul 2005 00:07:05 -0300 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Michael Hoffman wrote: > In that case, I think he just wasted a lot of time in the article, and > would have been better off saying "use Getopt::Long." This is why I think he was more concerned with design than implementation. -- Jorge Godoy From Gov at mailinator.com Tue Jul 26 13:43:34 2005 From: Gov at mailinator.com (Chris) Date: 26 Jul 2005 10:43:34 -0700 Subject: Using win32com for web automation Message-ID: <1122399814.174328.63980@g43g2000cwa.googlegroups.com> Hi, I'm trying to figure out how to submit javascript forms using win32com in order to complete repetitive processes. The Webpage Source: (I tried to include only the important stuff) ----------------------------------------------

Name:  Password:  OK Change Password Preferences ---------------------------------------------- My code so far is this: ---------------------------------------------- from win32com.client import Dispatch from time import sleep ie = Dispatch('InternetExplorer.Application') ie.Visible = 1 ie.Navigate("http://ispds-sepsr.prv:7500/cs/welcome.jsp") while ie.ReadyState != 4: sleep(1) doc = ie.Document while doc.readyState != "complete": sleep(1) doc.loginForm.name.value = 'username' doc.loginForm.password.value = 'password' doc.loginForm.loginform.action = '/cs/login.do' ------------------------------------------------- Well it doesn't seem to work like other javascript sites (eg. like the google.ca form)which is where i snagged the script from. I don't really have a clue about this module, or even javascript so any help would be appreciated. P.S. sorry about the mess From francois.perche at gmail.com Sun Jul 10 06:10:48 2005 From: francois.perche at gmail.com (perchef) Date: 10 Jul 2005 03:10:48 -0700 Subject: ZipFile and file rigths Message-ID: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> hi, i have written this small code which allow me to unzip files using python : import zipfile import os import os.path pathDir="/home/toto/Desktop" pathZip= os.path.join(pathDir,"foobar.zip") if zipfile.is_zipfile(pathZip): zf = zipfile.ZipFile(pathZip) for file in zf.namelist(): newPath = os.path.join(pathDir,file) print newPath if not file.endswith('/') and not os.path.exists(newPath) : newFile = open(newPath, 'wb') newFile.write(zf.read(file)) newFile.flush() newFile.close() else : os.makedirs(newPath) zf.close() else: print pathZip + " is not a zip file" it works well but i have a small problem : i can't see how i can deal with file rights. When I unzip files with this script all the unzipped files haven't the good rights. for example : with this script : -rw-r--r-- foo.exe with a traditional zip program (ie : stuffit ): -rwxr-xr-x foo.exe ZipInfo objects doesn't store informations about rights ? (http://www.python.org/doc/current/lib/zipinfo-objects.html#zipinfo-objects) How can i fix this ? From steve at REMOVETHIScyber.com.au Sat Jul 16 11:48:10 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 17 Jul 2005 01:48:10 +1000 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen wrote: > Bengt Richter wrote: >> >>> identity = ''.join([chr(i) for i in xrange(256)]) >> >>> unprintable = ''.join([c for c in identity if c not in string.printable]) > > And note that with Python 2.4, in each case the above square brackets > are unnecessary (though harmless), because of the arrival of "generator > expressions" in the language. But to use generator expressions, wouldn't you need an extra pair of round brackets? eg identity = ''.join( ( chr(i) for i in xrange(256) ) ) with the extra spaces added for clarity. That is, the brackets after join make the function call, and the nested brackets make the generator. That, at least, is my understanding. -- Steven who is still using Python 2.3, and probably will be for quite some time From mwm at mired.org Fri Jul 29 18:07:31 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 29 Jul 2005 18:07:31 -0400 Subject: A replacement for lambda Message-ID: <867jf9jmfw.fsf@bhuda.mired.org> I know, lambda bashing (and defending) in the group is one of the most popular ways to avoid writing code. However, while staring at some Oz code, I noticed a feature that would seem to make both groups happy - if we can figure out how to avoid the ugly syntax. This proposal does away with the well-known/obscure "lambda" keyword. It gives those who want a more functional lambda what they want. It doesn't add any new keywords. It doesn't add any new magic characters, though it does add meaning to an existing one. That could be replaced by a new magic token, or adding magic meaning to a non-magic token. It breaks no old code either way. I haven't really worked out all the implications; I just wanted to throw it out and see what everyone else thought about it. As a result, the code examples tend to be ugly. As previously hinted, this feature is lifted from Oz. Currently, class and functions definitions consist of a keyword - either "class" or "def" - followed by a name, a header, then code. The code is compiled into an object, and the name is bound to that object. The proposal is to allow name to be a non-name (or rare name) token. In this case, the code is compiled and the resulting object is used as the value of the class/def expression. My choice for the non-name token is "@". It's already got magic powers, so we'll give it more rather than introducing another token with magic powers, as the lesser of two evils. Rewriting a canonical abuse of lambda in this idiom gives: myfunc = def @(*args): return sum(x + 1 for x in args) In other words, this is identical to: def myfunc(*args): return sum(x + 1 for x in args) We can write the same loop with logging information as: sum(def @(arg): print "Bumping", arg return arg + 1 (x) # '(' at the same indent level as def, to end the definition for x in stuff) A more useful example is the ever-popular property creation without cluttering the class namespace: class Spam(object): myprop = property(fget = def @(self): return self._properties['myprop'] , fset = def @(self, value): self._properties['myprop'] = value , fdel = def @(self) del self._properties['myprop'] , doc = "Just an example") This looks like the abuse of lambda case, but these aren't assignments, they're keyword arguments. You could leave off the keywords, but it's not noticably prettier. fget can be done with a lambda, but the the others can't. Giving clases the same functionality seems to be the reasonable thing to do. It's symmetric. And if anonymous function objects are good, then anonymous class objects ought to be good as well. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From thanos at sians.org Tue Jul 19 14:15:51 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Tue, 19 Jul 2005 21:15:51 +0300 Subject: dictionary as property In-Reply-To: <20050719170010.GA28430@mylene.ghaering.de> References: <20050719165620.GA4136@zermelo.sians.org> <20050719170010.GA28430@mylene.ghaering.de> Message-ID: <20050719181551.GA11446@zermelo.sians.org> On Tue, Jul 19, 2005 at 07:00:10PM +0200, Gerhard Haering wrote: > On Tue, Jul 19, 2005 at 07:56:20PM +0300, Thanos Tsouanas wrote: > > Hello. > > > > (How) can I have a class property d, such that d['foo'] = 'bar' will run > > a certain function of the class with 'foo' and 'bar' as it's arguments? > > You could implement a custom container type that will do what you want. > See http://docs.python.org/ref/sequence-types.html for __setitem__. Thanks, that doc had all I needed :) -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From sp1d3rx at gmail.com Tue Jul 19 18:31:15 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 19 Jul 2005 15:31:15 -0700 Subject: Windows command line problem In-Reply-To: References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> <1121726398.861595.31350@g43g2000cwa.googlegroups.com> <1121759914.689112.272530@z14g2000cwz.googlegroups.com> <1121762108.120184.201340@g47g2000cwa.googlegroups.com> Message-ID: <1121812275.374283.224000@g47g2000cwa.googlegroups.com> I think the lesson there is 'dont depend on getopt, write your own command line parser'. I always write my own, as it's so easy to do. From tim.peters at gmail.com Tue Jul 5 10:52:29 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 5 Jul 2005 10:52:29 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae050705075255479625@mail.gmail.com> [Tim Peters] >> All Python behavior in the presence of infinities, NaNs, and signed >> zeroes is a platform-dependent accident, mostly inherited from that >> all C89 behavior in the presence of infinities, NaNs, and signed >> zeroes is a platform-dependent crapshoot. [Michael Hudson] > As you may have noticed by now, I'd kind of like to stop you saying > this :) -- at least on platforms where doubles are good old-fashioned > 754 8-byte values. Nope, I hadn't noticed! I'll stop saying it when it stops being true, though . Note that since there's not even an alpha out for 2.5 yet, none of the good stuff you did in CVS counts for users yet. > But first, I'm going to whinge a bit, and lay out some stuff that Tim > at least already knows (and maybe get some stuff wrong, we'll see). > > Floating point standards lay out a number of "conditions": Overflow > (number too large in magnitude to represent), Underflow (non-zero > number to small in magnitude to represent), Subnormal (non-zero number > to small in magnitude to represent in a normalized way), ... The 754 standard has five of them: underflow, overflow, invalid operation, inexact, and "divide by 0" (which should be understood more generally as a singularity; e.g., divide-by-0 is also appropriate for log(0)). > For each condition, it should (at some level) is possible to trap each > condition, or continue in some standard-mandated way (e.g. return 0 > for Underflow). 754 requires that, yes. > While ignoring the issue of allowing the user to control this, I do > wish sometimes that Python would make up it's mind about what it does > for each condition. Guido and I agreed long ago that Python "should", by default, raise an exception on overflow, invalid operation, and divide by 0, and "should not", by default, raise an exception on underflow or inexact. Such defaults favor non-expert use. Experts may or may not be happy with them, so Python "should" also allow changing the set. > There are a bunch of conditions which we shouldn't and don't trap by > default -- Underflow for example. For the conditions that probably should > result in an exception, there are inconsistencies galore: > >>> inf = 1e300 * 1e300 # <- Overflow, no exception > >>> nan = inf/inf # <- InvalidOperation, no exception Meaning you're running on a 754 platform whose C runtime arranged to disable the overflow and invalid operation traps. You're seeing native HW fp behavior then. > >>> pow(1e100, 100) <- Overflow, exception > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Numerical result out of range') > >>> math.sqrt(-1) # <- InvalidOperation, exception > Traceback (most recent call last): > File "", line 1, in ? > ValueError: math domain error Unlike the first two examples, these call libm functions. Then it's a x-platform crapshoot whether and when the libm functions set errno to ERANGE or EDOM, and somewhat of a mystery whether it's better to reproduce what the native libm considers to be "an error", or try to give the same results across platforms. Python makes a weak attempt at the latter. > At least we're fairly consistent on DivisionByZero... When it's a division by 0, yes. It's cheap and easy to test for that. However, many expert uses strongly favor getting back an infinity then instead, so it's not good that Python doesn't support a choice about x/0. > If we're going to trap Overflow consistently, we really need a way of > getting the special values reliably -- which is what pep 754 is about, > and its implementation may actually work more reliably in 2.5 since my > recent work... I don't know what you have in mind. For example, checking the result of x*y to see whether it's an infinity is not a reliable way to detect overflow, and it fails in more than one way (e.g., one of the inputs may have been an infinity (in which case OverflowError is inappropriate), and overflow doesn't always result in an infinity either (depends on the rounding mode in effect)). > On the issue of platforms that start up processes with traps enabled, > I think the correct solution is to find the incantation to turn them > off again and use that in Py_Initialize(), though that might upset > embedders. Hard to know. Python currently has a hack to disable traps on FreeBSD, in python.c's main(). From exarkun at divmod.com Sun Jul 3 17:21:41 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 3 Jul 2005 17:21:41 -0400 Subject: Favorite non-python language trick? In-Reply-To: Message-ID: <20050703212141.26278.980513326.divmod.quotient.5021@ohm> On Sun, 03 Jul 2005 15:40:38 -0500, Rocco Moretti wrote: >Jp Calderone wrote: >> On Fri, 01 Jul 2005 15:02:10 -0500, Rocco Moretti >> wrote: >> >>> >>> I'm not aware of a language that allows it, but recently I've found >>> myself wanting the ability to transparently replace objects. >> >> >> Smalltalk supports this with the "become" message. I have also done an >> implementation of this for Python. > >As a pure Python module, or do you have to recompile the interpreter? Somewhere in between, I guess. The module is all Python, but relies pretty heavily on one particular stdlib extension module. The code is rather short, and online here: http://divmod.org/users/exarkun/become.py Jp From wade at leftwich.us Mon Jul 25 19:45:35 2005 From: wade at leftwich.us (Wade) Date: 25 Jul 2005 16:45:35 -0700 Subject: how to write a line in a text file References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> Message-ID: <1122335135.915411.321900@g44g2000cwa.googlegroups.com> Steven D'Aprano wrote: >I'm usually opposed to creeping featuritis in programming languages ("it >would be really cool if Python had a built-in command to do my entire >application") but safe over-writing of files does cry out for a "batteries >included" approach: How about the fileinput module? http://docs.python.org/lib/module-fileinput.html """ Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup='.' is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. """ From bronger at physik.rwth-aachen.de Sun Jul 24 13:47:30 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 24 Jul 2005 19:47:30 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> Message-ID: <87ek9occzx.fsf@wilson.rwth-aachen.de> Hall?chen! Marek Kubica writes: > Hello! > >> AFAIK PyGTK doesn't look native on Win as well, but I don't care. > > [...] The native look and feel is not as good as the look and feel > of wx but still really _much_ better than older versions of GTK. Is PyGTK more Pythonic by the way? I had a look at wxPython yesterday and didn't like that it has been brought into the Python world nearly unchanged. You can see its non-Python origin clearly. How does PyGTK feel in this respect? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From guy.lateur at b-b.be Tue Jul 5 07:54:07 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 05 Jul 2005 11:54:07 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: > I just tried this and it failed with IP addresses but not > hostnames/machine names, try it again with the server name. :) Nope, same problem. I think TJG might be right, and our server probably doesn't have IMAP running (yet). > Depends how secure you need it to be. For my simple stuff I just do > something like this > [snip] That's a nice thought, although the pw is still pretty visible. Maybe there's a way to encode/decode it using some sort of key (that only I know), that produces a truly unrecognisable pw? Thanks for the input, g From gsakkis at rutgers.edu Thu Jul 7 20:02:37 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Jul 2005 17:02:37 -0700 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: <1120780796.404355.113190@o13g2000cwo.googlegroups.com> "Tony Meyer" wrote: > The problem with Eclipse, IMO, is Java. I've tried 3.1 on a WinXP machine > and, like just about any Java program, it's incredibly slow and a real pain > to use. On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and > smoothly and is reasonably nice to use. I'd happily recommend that Mac > users try Eclipse, but never a Windows (Python) programmer. > > =Tony.Meyer Your first sentence contradicts the rest of your post; how is Java the problem if it runs nice on a Mac and is sluggish on Windows ? At best this may say something about the difference in perfomance between the two JREs (assuming that most Windows and Mac users of Eclipse have similar experience with yours). George From lordverminard at gmail.com Sat Jul 30 01:53:57 2005 From: lordverminard at gmail.com (mustafa) Date: Sat, 30 Jul 2005 10:53:57 +0500 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Thu, 28 Jul 2005 15:23:46 -0500, Rocco Moretti wrote: > > >>Professionals (and even decent hobbyists) don't >>escalate flame wars, even unintentionally. > > > You don't get out much, do you? *wink* > > If your comment is meant to be _prescriptive_ rather than _descriptive_, I > don't entirely agree. > > Flame wars, like all wars, are unproductive beyond a certain point, but to > push the combat analogy, punitive raids can be productive at changing > behaviour. > > It is never pleasant to be on the receiving end of a flaming, but if it is > deserved, then people should accept it and learn from it, rather than just > dismiss it as a flaming and therefore meaningless. > > The problem on the Internet is that there is little or no status: the most > ignorant newbie and the stupidest AOLer think that they are equal in > status to somebody who has proven their knowledge for ten years. (This > lack of status on the Internet is not *always* a bad thing, but it can be.) > > If your boss or professor or a judge gave you a tongue-lashing for stupid > behaviour, sensible people accept it. "I've been bad, I got caught, thank > goodness I'm suffering nothing worse than being told I'm an idiot." At > worst they might complain to their friends afterwards. > > But on the Internet, people who deserve that tongue-lashing think that > because they can retaliate, they should retaliate -- and that's where the > risk of escalation from punitive raid to unproductive flame war lies. > > > your wierd. i dont mean that in a bad sense but your the first the person to i have seen who think in internet does not have a status quo. i newbie is classified as one from his first post in any mailing list or forum.(in fact most forums siply give you that status according to you post count. From PPNTWIMBXFFC at spammotel.com Thu Jul 21 07:05:25 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 21 Jul 2005 13:05:25 +0200 Subject: A sad story about a real "Python" Message-ID: http://www.snopes.com/photos/animals/fencesnake.asp Cheers, Marco From paolo_veronelli at tiscali.it Sat Jul 30 04:20:36 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sat, 30 Jul 2005 10:20:36 +0200 Subject: A replacement for lambda In-Reply-To: References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <42EB3854.5000006@tiscali.it> why (x**2 with(x))<(x**3 with(x)) is not taken in consideration? If 'with' must be there (and substitue 'lambda:') then at least the syntax is clear.IMO Ruby syntax is also clear. ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From tjreedy at udel.edu Tue Jul 5 22:16:54 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 5 Jul 2005 22:16:54 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: "George Sakkis" wrote in message news:1120610787.940292.15210 at g43g2000cwa.googlegroups.com... > Still it's hard to explain why four specific python keywords - def, > del, exec and elif - were chosen to be abbreviated, Precedence in other languages and CS usage? > So, who would object the full-word versions for python 3K ? > def -> define > del -> delete > exec -> execute These three I might prefer to keep. > elif -> else if This one I dislike and would prefer to write out. I never liked it in whatever else language I first encountered it and still don't. Terry J. Reedy From richardlewis at fastmail.co.uk Wed Jul 6 12:55:01 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Wed, 06 Jul 2005 17:55:01 +0100 Subject: Tkinter grid layout In-Reply-To: References: Message-ID: <1120668901.7874.237880560@webmail.messagingengine.com> On Wed, 06 Jul 2005 16:32:42 GMT, "William Gill" said: > Excuse me for intruding, but I followed examples and ended up with a > similar architecture: > > from Tkinter import * > class MyMain(Frame): > def __init__(self, master): > self.root = master > self.master=master > root = Tk() > app = MyMain(root) > app.master.title("Object Editor") > root.mainloop() > > Erick, are you saying it should be modified to something like : > > from Tkinter import * > class MyMain(Tk): > ... > ... > app = MyMain() > app.title("My App") > app.mainloop() > This is what I've got now, and it works. I don't think I've seen many examples which inherited from Tk, but it certainly solved my problem. And I see the logic in it: Tk is the main window of an application, while Frame is, as Eric said, just a generic container. Cheers, Richard From jgrahn-nntq at algonet.se Fri Jul 8 20:01:30 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 9 Jul 2005 00:01:30 GMT Subject: Legacy data parsing References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 8 Jul 2005 15:03:45 -0500, Thomas Bartkus wrote: > "gov" wrote in message > news:1120847474.604271.196220 at g49g2000cwa.googlegroups.com... >> Hi, >> >> I've just started to learn programming and was told this was a good >> place to ask questions :) >> >> Where I work, we receive large quantities of data which is currently >> all printed on large, obsolete, dot matrix printers. This is a problem >> because the replacement parts will not be available for much longer. >> >> So I'm trying to create a program which will capture the fixed width >> text file data and convert as well as sort the data (there are several >> different report types) into a different format which would allow it to >> be printed normally, or viewed on a computer. > > Text file data has no concept of "fixed width". Somewhere in your system, > text file data is being thrown at your dot matrix printer. It would seem a > trivial exercise to simply plug in a newer and probably inexpensive > replacement printer. > > What am I missing here? I was just wondering the same thing. Until/unless we don't get an answer: here's two hypotheses: - The text file is too wide for modern-day laser printers to print properly, or the printer isn't configured to accept plain text (accented characters, line feeds and so on). -> feed it through 'enscript' or a similar utility, which can scale it down and manipulate it in various ways into a Postscript file, and print that one - The text file isn't really a text file, but full of escape codes for the matrix printer (boldfacing and so on). -> attempt to clean it with a utility like the standard unix 'col' command -> ... and/or write custom code to do it. Python is a good choice. In general, this is an area where it's wise to use existing software. The hard part is to know what's available! /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From k33rni at gmail.com Mon Jul 4 11:01:19 2005 From: k33rni at gmail.com (k33rni at gmail.com) Date: 4 Jul 2005 08:01:19 -0700 Subject: curses -- getxy() error In-Reply-To: <6pqdnbyb__6_2lTfRVn-iA@powergate.ca> References: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> <6pqdnbyb__6_2lTfRVn-iA@powergate.ca> Message-ID: <1120489279.869860.252580@g43g2000cwa.googlegroups.com> Peter Hansen wrote: > post the exception traceback here[...], we can show you how to analyze it to > determine for yourself exactly what the problem is true, remember that for the future. and that goes to everybody asking questions here. thing is, I've done enough curses programming (in both Python and C) to see this particular issue immediately, without the need for a traceback. :) From d.raber at gmx.net Wed Jul 20 16:14:39 2005 From: d.raber at gmx.net (Dieter Raber) Date: 20 Jul 2005 13:14:39 -0700 Subject: mod_python Apache/2.0.52 (Win32) Python 2.4 Message-ID: <38d6a9b7.0507201214.12c048ac@posting.google.com> Hi there, I am wondering if there is a mod_python for the above configuration. I downloaded mod_python-3.1.3.win32-py2.3.exe, which of course as the name implies keeps on asking me for a python 2.3 installation. I imagine one could cheat a little bit with a fake registry entry that says it was about python 2.3 but that points to python 2.4. Then again I don't know what entry mod_python's installer is looking for. Thanks for your help Dieter From bjourne at gmail.com Fri Jul 1 22:46:48 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 2 Jul 2005 04:46:48 +0200 Subject: Favorite non-python language trick? In-Reply-To: <86ll4q3q0m.fsf@bhuda.mired.org> References: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> <86psu2410u.fsf@bhuda.mired.org> <86ll4q3q0m.fsf@bhuda.mired.org> Message-ID: <740c3aec050701194678867329@mail.gmail.com> I like C++ templates so that you can ensure that a list only contain items of one type. I also like the JMP instruction in x86 assembler, you could do some nasty tricks with that. -- mvh Bj?rn From paolo_veronelli at tiscali.it Sat Jul 23 06:27:31 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sat, 23 Jul 2005 12:27:31 +0200 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: References: <1122083350.151604.87980@g44g2000cwa.googlegroups.com> Message-ID: <42E21B93.8060309@tiscali.it> Little less ugly: In [12]:class A(object): ....: def __str__(self):return self.__str__() ....: def str(self):return 'ciao' ....: def setStr(self):self.__str__=self.str ....: In [13]:a=A() In [14]:a.setStr() In [15]:str(a) Out[15]:'ciao' The point is str(ob) builtin looks like calling ob.__class__.__str__(ob).Prolly Python-dev is the good place to ask about. ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From mwm at mired.org Thu Jul 28 22:31:41 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 28 Jul 2005 22:31:41 -0400 Subject: monitor a folder for file creation, how? References: Message-ID: <86ack6l4vm.fsf@bhuda.mired.org> fanbanlo writes: > How do I monitor a folder for new file(s) creation? > How to use thread to do a wait until a new file is 'detected'? There's not a clean portable way to do this. The portable way is to poll the update time of the folder at regular intervals, and act when it changes. I did that for a Maildir mail monitoring tool once, but can't seem to find the source now. Sorry. The clean way depends on your platform. Most modern system have a mechanism to get the kernel to notify you when a file/directory is updated. But they are all different. Since you say "folder", I assume you're on Windows - and I can't help you with this one. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ucntcme at gmail.com Thu Jul 14 18:08:42 2005 From: ucntcme at gmail.com (ucntcme at gmail.com) Date: 14 Jul 2005 15:08:42 -0700 Subject: Frankenstring References: <1121378145.470576.34130@g14g2000cwa.googlegroups.com> Message-ID: <1121378922.522717.321490@z14g2000cwz.googlegroups.com> well that appears to have been munged up ... that tell() belongs immediately after self.str. making it self.str.tell() class FrankenString: def __init__(self,string=None): self.str = StringIO(string) self.atEnd = False self.lastidx = 0 self.seek = self.str.seek self.tell = self.str.tell def __iter__(self): while not self.atEnd: char = self.str.read(1) idx = self.str.tell() if self.lastidx == idx: self.atEnd = True self.lastidx = idx yield char From berlin.brown at gmail.com Tue Jul 19 15:22:04 2005 From: berlin.brown at gmail.com (Ramza Brown) Date: Tue, 19 Jul 2005 15:22:04 -0400 Subject: Jython Released In-Reply-To: References: <6NWdna8jsbEov0DfRVn-vA@comcast.com> Message-ID: Dave Benjamin wrote: > Dave Benjamin wrote: > >> Ramza Brown wrote: >> >>> This is an update from Brian Zimmer of the Jython group, new release: >> >> >> Great news! >> >>> - new installer >> >> >> How do I use it? > > > I figured it out. You might want to document this somewhere. ;) > java -cp jython_Release_2_2alpha1.jar org.python.util.install.Installation > > Dave Did you try double clicking on the jar. That is what most do or at least the last package supported that. From paolo_veronelli at tiscali.it Sat Jul 23 06:06:57 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Sat, 23 Jul 2005 12:06:57 +0200 Subject: Getting a dictionary from an object In-Reply-To: <20050723084827.GA6903@zermelo.sians.org> References: <20050723084827.GA6903@zermelo.sians.org> Message-ID: <42E216C1.70707@tiscali.it> Thanos Tsouanas wrote: > Hello. > > I would like to have a quick way to create dicts from object, so that a > call to foo['bar'] would return obj.bar. > > The following works, but I would prefer to use a built-in way if one > exists. Is there one? > > class dictobj(dict): > """ > class dictobj(dict): > A dictionary d with an object attached to it, > which treats d['foo'] as d.obj.foo. > """ > def __init__(self, obj): > self.obj = obj > def __getitem__(self, key): > return self.obj.__getattribute__(key) use getattr(self.obj,key) possibly, as __getattribute__ gets total control on attribute access ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From mynews44 at yahoo.com Thu Jul 14 13:52:24 2005 From: mynews44 at yahoo.com (googleboy) Date: 14 Jul 2005 10:52:24 -0700 Subject: more newbie list questions In-Reply-To: References: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> Message-ID: <1121363544.684317.314540@g14g2000cwa.googlegroups.com> Thanks for this. It ahs been very helpful. I realised that my problem using getattr were because I was trying to use it over the list of lists, instead of each book. I have written up a for loop now, and I think I am a lot closer: for book in all_books: author1 = getattr(book, 'author1') sTemplate.replace('author1', author1) found = sTemplate.find('%author1%') print '\n.\n.\n' print author1 print '\n' print found print sTemplate You will notice that I print out various things. I am having some troubles. The resulting output of this loop is as follows: andy humber 47 The title is %title%.

The author is %author1% %author2%

The Publisher is %publisher1% %publisher2%

The ISBN is %ISBN%

This is obviously correctly assigning the author's name to the author1 variable, which I was my problem. It is finding my search string at teh 47th character of the sTemplate string, which is great. But it doesn't seem to want to replace the search string with the value of the author1 variable. Is there something else I am missing here? Thanks for the advice. regards, googleboy From tarlano at gmail.com Fri Jul 22 12:03:07 2005 From: tarlano at gmail.com (Anthony Tarlano) Date: 22 Jul 2005 09:03:07 -0700 Subject: What is your favorite Python web framework? In-Reply-To: References: Message-ID: <1122048187.041743.205780@g43g2000cwa.googlegroups.com> You may want to check out Quixote.... http://www.mems-exchange.org/software/quixote/ A. From sebastien.ramage at gmail.com Sun Jul 3 19:11:02 2005 From: sebastien.ramage at gmail.com (=?iso-8859-1?q?S=E9bastien_Ramage?=) Date: 3 Jul 2005 16:11:02 -0700 Subject: Jython from CVS Message-ID: <1120432262.835261.35980@g14g2000cwa.googlegroups.com> Somebody can help me to recompile Jython from the CVS file ? thank --- other question : No python browser plugins avaible? Seb From tjreedy at udel.edu Fri Jul 22 14:47:00 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Jul 2005 14:47:00 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: "Michael Hoffman" wrote in message news:dbqb5p$f5e$1 at gemini.csx.cam.ac.uk... >> on 22.07.2005 00:21 Michael Hoffman said the following: >>> Any Java hackers here want to tell us of the wonders of the Java Path >>> class? > Ah, here it is: > > http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html Very interesting. Java's File class is a system-independent "abstract representation of file and directory pathnames" which is constructed from and converted to system-dependent string-form pathnames (including URL/URI file:... forms). A File consist of an optional prefix and a *sequence* of zero or more string names. In other words, Java's File class is what Duncan and I thought Python's Path class might or possibly should be. So this internal representation might be worth considering as an option. Of course, if the interface is done right, it mostly should not make too much difference to the user. Terry J. Reedy From jstroud at mbi.ucla.edu Sun Jul 31 20:38:44 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 31 Jul 2005 17:38:44 -0700 Subject: Dabo in 30 seconds? In-Reply-To: References: <200507311709.18243.jstroud@mbi.ucla.edu> Message-ID: <200507311738.44553.jstroud@mbi.ucla.edu> On Sunday 31 July 2005 05:14 pm, Robert Kern wrote: > You can't blame Dabo for this one. Your wxPython install is broken. Yes, but my Tkinter install works just fine. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ ----------------------------------------------------------------- From scrimp212 at yahoo.com Thu Jul 21 08:30:53 2005 From: scrimp212 at yahoo.com (scrimp) Date: 21 Jul 2005 05:30:53 -0700 Subject: print pdf file to network printer using python Message-ID: <1121949053.440544.108150@g47g2000cwa.googlegroups.com> Well, Ive been searching through google groups and Ive seen a lot about printing a pdf file, but I havent seen a definite answer. I tried this code: f = open(printer_path, 'w') f.write(pdffile_path) f.close() Basically it doesnt work and what it prints out is the value of pdffile_path variable. If anyone can offer some help, Id appreaciate it thanks! --Barry From peter at engcorp.com Sat Jul 16 22:58:20 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Jul 2005 22:58:20 -0400 Subject: Filtering out non-readable characters In-Reply-To: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> References: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> Message-ID: George Sakkis wrote: > "Peter Hansen" wrote: >>>> Where did you learn that, George? > > Actually I first read about this in the Cookbook; there are two or three > recipes related to string.translate. As for string.maketrans, it > doesn't do anything special for empty string arguments: ... I guess so. I was going to offer to suggest a new paragraph on that usage for the docs, but as you and Jp both seem to think the behaviour is obvious, I conclude "it's just me" so I suppose I shouldn't bother. -Peter From martin.witte at gmail.com Mon Jul 25 09:09:36 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 25 Jul 2005 06:09:36 -0700 Subject: Counting processors In-Reply-To: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> Message-ID: <1122296976.416926.115570@g47g2000cwa.googlegroups.com> I don't think there is direct method. On Linux you can inspect file /proc/cpuinfo to determine the installed cpus. From rkern at ucsd.edu Fri Jul 22 09:07:28 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 22 Jul 2005 06:07:28 -0700 Subject: tuple to string? In-Reply-To: <42E0EED4.4020001@gmx.net> References: <42E0EED4.4020001@gmx.net> Message-ID: Francois De Serres wrote: > hiho, > > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to > the string 'spam'? In [1]: t = (0x73, 0x70, 0x61, 0x6D) In [2]: ''.join(chr(x) for x in t) Out[2]: 'spam' -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From duncan.booth at invalid.invalid Thu Jul 7 11:46:23 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jul 2005 15:46:23 GMT Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Put it this way: whenever I see a two-line def as above, I can't help > feeling that it is a waste of a def. ("Somebody went to all the trouble > to define a function for *that*?") Yet I would never think the same about > a lambda -- lambdas just feel like they should be light-weight. Obviously we think differently there. I don't see why lambdas are any different than single expression functions. I certainly don't think of them as lighter weight; they take just as long to call; and they involve just as much stack setup/tear down. On the other hand I don't consider functions as heavyweight, I'm happy to define short helper functions anywhere I think it makes the code more expressive. > Am I just weird? No, just different[*]. There's nothing wrong with different. [*] conclusion based entirely on your postings here. I have no evidence beyond that. From devlai at gmail.com Tue Jul 12 11:32:23 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 08:32:23 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121181950.339056.171260@g44g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> Message-ID: <1121182343.731328.38020@g47g2000cwa.googlegroups.com> I think you need to get a database. Anyways, if anything, it should create no more than 5,000 files, since 5,000 facts shouldn't talk about 30,000 animals. There have been a few discussions about looking at files in directories though, if you want to look at those. From jepler at unpythonic.net Mon Jul 4 13:49:11 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 4 Jul 2005 12:49:11 -0500 Subject: Trapping user logins in python ( post #1) In-Reply-To: <1120477906.956606.119040@g14g2000cwa.googlegroups.com> References: <1120477906.956606.119040@g14g2000cwa.googlegroups.com> Message-ID: <20050704174908.GA21332@unpythonic.net> I don't know of a portable way for an inetd-style daemon to "listen" for user logins. On some systems (including RedHat/Fedora and debian), you may be able to use PAM to do this. (pam modules don't just perform authentication, they can take other actions. As an example, pam_lastlog "prints the last login on successful login". I'm not sure what priviledge a pam module has when it executes. A more standard way to do this would be to place lines in /etc/profile /etc/csh.login and so forth for any other shells used on your system. RedHat-style systems have an /etc/profile.d where you can drop a file that will be executed at login, too. This will, of course, be executed with the user's privilege level. Another problem with this approach is that /etc/profile is executed for a "login shell", but a graphical login is not a login shell. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From me at privacy.net Wed Jul 6 10:40:39 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 06 Jul 2005 10:40:39 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 06 Jul 2005 14:33:47 GMT, Ron Adam wrote: > Since this is a Python 3k item... What would be the consequence of > making None the default value of an undefined name? And then assigning > a name to None as a way to delete it? [ ... ] > Any drawbacks? Lots more hard-to-find errors from code like this: filehandle = open( 'somefile' ) do_something_with_an_open_file( file_handle ) filehandle.close( ) Regards, Dan -- Dan Sommers From cam.ac.uk at mh391.invalid Sun Jul 3 10:07:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 03 Jul 2005 15:07:42 +0100 Subject: question about raw_input In-Reply-To: <1120380440.564612.160180@g47g2000cwa.googlegroups.com> References: <1120380440.564612.160180@g47g2000cwa.googlegroups.com> Message-ID: wcc wrote: > Hello group, > > After searching free IDE for a while, i picked > PyScripter(http://mmm-experts.com/Products.aspx). It is neat. I like > it. But I always get error when using raw_input function. Please see > below. > > >>>>raw_input("Press ENTER to continue...") > > Press ENTER to continue...Traceback (most recent call last): > File "", line 1, in ? > EOFError: EOF when reading a line > > I don't see this error when using the IDE from python or activepython. Then it's probably a problem with PyScripter, not Python. You'd be better off asking the PyScripter people than asking here. -- Michael Hoffman From secun at yahoo.com Tue Jul 12 22:58:30 2005 From: secun at yahoo.com (ChrisH) Date: Wed, 13 Jul 2005 02:58:30 GMT Subject: Help with report References: <11d5scbb63afhee@corp.supernews.com> Message-ID: > You know, this is the most concise example of feature-creep in a > specification that I've ever seen. > You're right. I'm afraid it's from too much work and too little sleep. I'll try to be more precise next time. Thanks to everyone for their help. Chris From bektek at gmail.com Sun Jul 17 13:47:52 2005 From: bektek at gmail.com (kimes) Date: 17 Jul 2005 10:47:52 -0700 Subject: I just wanna know about os.path module.. In-Reply-To: References: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> Message-ID: <1121622472.349346.182970@g49g2000cwa.googlegroups.com> Thanks for all you guys help.. But Peter, You said 'At first os - module, or package, it doesn't matter here - is imported.' I'm still confused about that.. When I just call import os.path without calling import os.. In that case, you mean 'import os' is called implicitly? Why? and How? how python knows it should call import when we call import os? Please make me clear.. :) Thanks.. From peter at engcorp.com Sun Jul 17 06:49:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 17 Jul 2005 06:49:50 -0400 Subject: Filtering out non-readable characters In-Reply-To: References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Steven D'Aprano wrote: > On Sat, 16 Jul 2005 16:42:58 -0400, Peter Hansen wrote: >>Come on, Steven. Don't tell us you didn't have access to a Python >>interpreter to check before you posted: > > Er, as I wrote in my post: > > "Steven > who is still using Python 2.3, and probably will be for quite some time" Sorry, missed that! I don't generally notice signatures much, partly because Thunderbird is smart enough to "grey them out" (the main text is displayed as black, quoted material in blue, and signatures in a light gray.) I don't have a firm answer (though I suspect the language reference does) about when "dedicated" parentheses are required around a generator expression. I just know that, so far, they just work when I want them to. Like most of Python. :-) -Peter From gsakkis at rutgers.edu Tue Jul 5 20:46:27 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jul 2005 17:46:27 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: <1120610787.940292.15210@g43g2000cwa.googlegroups.com> "Steven D'Aprano" wrote: > On Tue, 05 Jul 2005 09:46:41 -0500, Terry Hancock wrote: [snip] > > Having said that, I too will miss the *concept* of an anonymous > > function, although I wouldn't mind at all if its name changed, or if it > > were somehow integrated into the "def" keyword's usage. > > Def would be short for ... defend? defile? defer? defame? default? deflect? > > There's always *something* to learn. Why def instead of define? Because > "easy to write" beats "instantly obvious to a beginner", if the word is > used all the time and is easy to memorize. Still it's hard to explain why four specific python keywords - def, del, exec and elif - were chosen to be abbreviated, while all the rest are full words (http://docs.python.org/ref/keywords.html). "Ease of typing" is a joke for an excuse; "finally" is longer than "define","delete" and equally long to "execute" and "else if" (the latter has the even more serious flaw of going against TOOWTDI and in this case practicallity hardly beats purity IMO). In any case, python was never about minimizing keystrokes; theres another language that strives for this . So, who would object the full-word versions for python 3K ? def -> define del -> delete exec -> execute elif -> else if George From peter at engcorp.com Sat Jul 2 07:38:41 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 07:38:41 -0400 Subject: What are the other options against Zope? In-Reply-To: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> Message-ID: <-uOdneqY58so4VvfRVn-sA@powergate.ca> godwin wrote: > I wanna thank Martin for helping out with my ignorance concerning > execution of stored procedure with python. Now i have decided to write > a web app that googles into my companies proprietary database. Just checking... do you really mean "googles", or is that in your mind a synonym for "search"? > I need > to know whether zope is good for that job. For which part of it? The web part, or the searching part? It's not likely sufficient for the searching part, since it doesn't include database interfaces other than to its own ZODB. What proprietary database is involved? -Peter From dberlin at gmail.com Fri Jul 1 06:32:35 2005 From: dberlin at gmail.com (dberlin at gmail.com) Date: 1 Jul 2005 03:32:35 -0700 Subject: How to compare files In-Reply-To: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> References: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> Message-ID: <1120213955.502347.12380@g44g2000cwa.googlegroups.com> you could always just remove those special characters (\n \t ..), remove spaces, read both files and compare string. I don't this is the best way of doing this... but maybe a combination of this way and yours will be efficient enough - remove all problematic characters and then compare line by line. good luck... From apoco at cox.net Tue Jul 12 01:34:44 2005 From: apoco at cox.net (Jacob Page) Date: Mon, 11 Jul 2005 22:34:44 -0700 Subject: set and frozenset unit tests? Message-ID: I have released interval-0.2.1 at http://members.cox.net/apoco/interval/. IntervalSet and FrozenIntervalSet objects are now (as far as I can tell) functionality equivalent to set and frozenset objects, except they can contain intervals as well as discrete values. Though I have my own unit tests for verifying this claim, I'd like to run my code through actual set and frozenset unit tests. Does any such code exist? Is it in pure Python? If so, where can it be obtained? Oh, and again, I'd really appreciate additional feedback on the module, especially related to design, if you've got any. My goal for this project is to make the classes built-in-data-type quality. -- Jacob From paschott at no.yahoo.spamm.com Thu Jul 14 18:13:37 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Thu, 14 Jul 2005 22:13:37 GMT Subject: httplib/HTTPS Post Problem References: <1121088563.465929.31290@g43g2000cwa.googlegroups.com> Message-ID: <7vodd1d6t6pn9o1n3uq25pfq6jmb8ghqme@4ax.com> Have you tried using pycurl? That may be an easier way to port over your CURL code directly. Relatively easy to use, too. -Pete michaelparkin at gmail.com wrote: > Hi, > > Sorry to post what might seem like a trivial problem here, but its > driving me mad! > > I have a simple https client that uses httplib to post data to a web > server. > > When I post over http & https using curl the data is recieved by the > web server with no problems. > > When I post using my python client the headers get there, but the body > of the message does not. > > My code is pretty standard and has the format: > > > httplib.HTTPSConnection.debuglevel = 1 > connection = httplib.HTTPSConnection(host_name, key_file = key, > cert_file = cert) > connection.putrequest("POST", path) > connection.putheader("Content-Length", str(len(body))) > > ...(some more headers)... > > connection.endheaders() > connection.send(body) > > response = connection.getresponse() > connection.close() > > (some code has been removed for clarity).. > > I can see in the debug messages the body getting sent, but nothing > arrives at > the server... > > I think I would understand whats going on better if I knew how Python > uses the > underlying socket - does it > > a) open the socket, send the header & body together or > b) send the header, wait, then send the body? > > I think the answer to this question solve my problem - can anyone help? > > Thanks. > > p.s. I'm using Python 2.3.3 [GCC 3.3.3 (SuseLinx)] From foundsabin at gmail.com Wed Jul 27 06:23:28 2005 From: foundsabin at gmail.com (Sabin.A.K, Bangalore) Date: 27 Jul 2005 03:23:28 -0700 Subject: Freeze Message-ID: <1122459808.800070.219980@g47g2000cwa.googlegroups.com> My exe file, being created using freeze python is not working on the machines which doesnt have Python installed. Copied all the associated files to other machine (including python23.dll, im with 23) But again it asks for python23.dll Whats wrong here? Gimme a hand. A.K.SABIN From enleverlesO.OmcO at OmclaveauO.com Fri Jul 22 13:13:55 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 22 Jul 2005 19:13:55 +0200 Subject: Python and Tablet PC: limitations? References: <1122051149.256485.209160@g44g2000cwa.googlegroups.com> Message-ID: <42e14e7e$0$31774$8fcfb975@news.wanadoo.fr> Hi ! I am a Tablet-PC's user. I am a Python programmer. I am happy, with this combo. For use Tablet's extensions, I use Internet-Explorer, drived by Python (via .HTA). Your problem is not Python, but, perhaps, Mozilla ? @-salutations Michel Claveau From godwinburby at rediffmail.com Fri Jul 1 07:34:35 2005 From: godwinburby at rediffmail.com (godwin) Date: 1 Jul 2005 04:34:35 -0700 Subject: How to execute stored procedure? Message-ID: <1120217675.222645.129930@g44g2000cwa.googlegroups.com> Hi, I would like to execute an oracle stored procedure using the any oracle database module which satisfies the Database Specification standard. I have tried cxOracle and Odbc database packages with no success. If u have the answer plz give me an example code. Thank you From rrr at ronadam.com Thu Jul 7 13:05:42 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 17:05:42 GMT Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] In-Reply-To: References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > On Thu, 07 Jul 2005 09:36:24 +0000, Duncan Booth wrote: > > >>Steven D'Aprano wrote: >> >>>This is something I've never understood. Why is it bad >>>form to assign an "anonymous function" (an object) to a >>>name? >> >>Because it obfuscates your code for no benefit. You should avoid making it >>hard for others to read your code (and 'others' includes yourself in the >>future). Use a descriptive name like this? def get_the_cube_of_x_and_then_subtract_five_multiplied_by_x(x): x**3 - 5*x I think I like the lambda version here. ;-) It would probably have a name which refers to the context in which it's used, but sometimes the math expression it self is also the most readable. > Put it this way: whenever I see a two-line def as above, I can't help > feeling that it is a waste of a def. ("Somebody went to all the trouble > to define a function for *that*?") Yet I would never think the same about > a lambda -- lambdas just feel like they should be light-weight. In the case of an interface module you might have a lot of two like def's that simply change the name and argument format so several modules can use it and have a standard consistent or simplified interface. The lambda may be perfectly fine for that. But why not use def? func_x = lambda x: (someother_func_x(x,'value')) def func_x(x): return someother_func_x(x,'value') There's both nearly identical, but the def is understandable to beginners and advanced python programs. Cheers, Ron > Am I just weird? Aren't we all? ;-) From gsakkis at rutgers.edu Fri Jul 1 03:43:35 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 1 Jul 2005 00:43:35 -0700 Subject: map vs. list-comprehension References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: <1120203815.141353.61200@z14g2000cwz.googlegroups.com> "Terry Hancock" wrote: > On Thursday 30 June 2005 09:49 am, Mike P. wrote: > > > IMHO I'm not particularly happy with the way Python is going language wise. > > I mean, I don't think I'll ever use decorators, for example. Personally, in > > terms of language features and capabilities I think the language is fine. > > Not much (if anything needs to be added). > > This though, I mostly agree with. I'm not sure if I'll ever find use for decorators, > but the "@" signs bother me, I must admit. I liked the fact that there was a > way to do this without fiddling with the language syntax. What way ? The foo=decorator(foo) workaround after the function's body ? That's hardly acceptable for common decorators such as staticmethod, classmethod and other suggested ones (synchronized, cached, traced, etc.). I don't mind the @ so much - I don't like it particularly either - and I don't compare it to the alternative rejected decorator syntax forms, but it's certainly an improvement over the pre-2.4 explicit assignment *after* the function. Properties are in the same boat with decorators. Although they are great semantically, the current syntax is less than optimal. Interestingly, Pyrex does much better in the readability department since 0.9 (http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/extension_types.html#Properties). The Property decorator recipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698) comes pretty close to it, but I wouldn't mind a small addition to the language syntax for something so useful as properties. Keeping the language small is a worthwhile goal, but it should be traded off with conciseness and readability; otherwise we could well be content with s-expressions. Just my $0.02, George From helge at aksdal.net Tue Jul 19 17:31:12 2005 From: helge at aksdal.net (Helge Aksdal) Date: Tue, 19 Jul 2005 23:31:12 +0200 Subject: socket programming In-Reply-To: References: <20050719204601.GB24773@mail.smule.com> <20050719210319.GA29578@mail.smule.com> Message-ID: <20050719213112.GB29578@mail.smule.com> * Jaime Wyant [2005/07/19 23:09]: > I don't think you can use a limit to your advantage. If you are > bumping against some limit and you can't query for multiple accounts > then there doesn't seem to be much you can really do. The problem would be solved, if i just could get my socket code to follow the redirection, as i tried to explain in my first email. any tips? or do i have to use good old nasty time.sleep to avoid this? -- Helge Aksdal From pythonmailing at web.de Sun Jul 24 11:26:26 2005 From: pythonmailing at web.de (Marek Kubica) Date: Sun, 24 Jul 2005 17:26:26 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> Message-ID: Hello! > AFAIK PyGTK doesn't look native on Win as well, but I don't care. It does have a nearly-native look and feel: http://gtk-wimp.sourceforge.net/screenshots/ And yes, the theme adjusts itself to Windows XP themes, so GTK+ apps look nearly like any other Windows Program. The native look and feel is not as good as the look and feel of wx but still really _much_ better than older versions of GTK. This is done by a theme engine.. you can find it in the gladewin32 package. greets, Marek From cyril.bazin at gmail.com Wed Jul 20 15:52:15 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Wed, 20 Jul 2005 21:52:15 +0200 Subject: How to store "3D" data? (data structure question) In-Reply-To: References: Message-ID: The question of the type of the data sutructure depends of your use of the data. You could avoid some confusion without naming your columns "lines"... Anyway, here is a piece of code that read the file and count the star on the fly: (The result is a dict of dict of int.) ----------------------------------------------------------------- import itertools import csv f = open("toto.data") #change your file name lineReader = csv.reader(f) #Set the lines titles (RHA280, etc) l = lineReader.next() linesTitles = l[2:] #We construct the data structure and count the stars on the fly datas = {} for l in lineReader: name, allele = l[:2] if not allele: #empty line continue if name: #new block defining a TD* currentName = name d = dict.fromkeys(linesTitles, 0) datas[currentName] = d lines = l[2:] #add 1 to the lines not empty (<=> with a star) for title, value in itertools.izip(linesTitles,lines): if value: d[title] += 1 #little tests print datas print datas["TDF1"]["RHA280"] print datas["TDF3"]["RHA280"] ----------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Tue Jul 5 12:01:23 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Jul 2005 16:01:23 -0000 Subject: threads and sleep? References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> Message-ID: <11clbmj3sjl67f4@corp.supernews.com> On 2005-07-05, Dennis Lee Bieber wrote: > Don't think you can do that with Python... The Python runtime > interpreter itself is running on a single processor. I don't see how that can be. Under Linux at least, the Python threading module uses "real" OS threads, so there are multiple instances of the interpreter, right? Generally all but one of them will be blocked on the GIL, but there are still multiple interpreter threads (which can be on multiple different CPUs). Or is the Python interpreter actually doing the context switches itself? > The second thing is the infamous "global interpreter lock" > (pull up the Python documentation and do a search for that > phrase). The GIL is the issue. > Basically, even if the threads could be assigned to > processors, Can somebody explani why they can't? > this lock means only one thread can be performing Python > operations at a time -- a C-language number crunching module > /could/ release the lock, then do its number crunching in > parallel, reacquiring the lock when it finishes so it can > return its result(s) as Python objects. True. Python can execute C code in parallel, but not Python code. > Tou might get the results you want by not using threads, > instead spawning off completely new Python invocations > assigned to other processors. That should work, but managing the inter-process communication and syncronization is a pain. -- Grant Edwards grante Yow! If Robert Di Niro at assassinates Walter Slezak, visi.com will Jodie Foster marry Bonzo?? From lbates at syscononline.com Fri Jul 1 09:33:08 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 01 Jul 2005 08:33:08 -0500 Subject: Windows installation - questions about DLLs In-Reply-To: References: Message-ID: <42C54614.3020807@syscononline.com> Take a look at py2exe it provides a way to "collect" all necessary files together for you. Add Inno Installer to the mix and you can create setup.exe insallation programs that don't require a Python install to distribute software. -Larry Bates Guillaume Hiron wrote: > Hi, > > I need to install python (2.3.5) on windows without the giving installer > program. > Do you know what dlls are needed? > I found python23.dll, but the other (msvcrt.dll,msvcrit.dll) seems not > be useful. > Is there other dll? Are msvcrt.dll and msvcrit.dll used by > something?(test/test___all__.py return no error whitout these two dlls). > > Thanks for helping. From dsiroky at email.cz Sat Jul 9 09:05:41 2005 From: dsiroky at email.cz (David Siroky) Date: Sat, 09 Jul 2005 15:05:41 +0200 Subject: pyo contains absolute paths Message-ID: Hi! When I "compile" my python files with "python -OO ...." into pyo files then they still contain absolute paths of the source files which is undesirable for me. How can I deal with that? Thank you. David From rkern at ucsd.edu Sun Jul 24 14:50:08 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Jul 2005 11:50:08 -0700 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: <1122215068.30698.37.camel@localhost> References: <1122215068.30698.37.camel@localhost> Message-ID: Soeren Sonnenburg wrote: > On Sun, 2005-07-24 at 13:36 +1000, Steven D'Aprano wrote: > >>On Sat, 23 Jul 2005 18:30:02 +0200, Soeren Sonnenburg wrote: >> >>>Hi all, >>> >>>Just having started with python, I feel that simple array operations '*' >>>and '+' don't do multiplication/addition but instead extend/join an >>>array: >> >>* and + are not array operations, they are list operations. >> >>Lists in Python can contain anything, not just numeric values. > > That seems to be *the point*. Whose point? If you mean that you want to be able to use arbitrary objects in an array, then look in numarray.objects for an array type that handles arbitrary Python objects. > Although list(a) + list(b) could create a > list [ a[0]+b[0], ...] and bail out if for elements '+' is not > defined... Unlike the current situation, where a+b always works consistently despite the contents, despite how long the lists are. >>Python doesn't have built-in mathematical arrays, otherwise known as >>matrices. There are modules that do that, but I haven't used them. Google >>on Numeric Python. > > Well I am aware of that but I don't understand the reasons of having > both lists (which are infect arrays) They "are in [fact] arrays" only in the sense that they are containers of objects with a contiguous layout in memory. That doesn't imply either set of semantics for + and * operators. > and *arrays ? They're good at different things. Arrays like Numeric/numarray are harder to implement than the builtin lists. > *I* would rather drop > '+' and '*' to work like they do in *array ... Tough. It's 14 years or so too late to make that change. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From devlai at gmail.com Wed Jul 6 12:01:14 2005 From: devlai at gmail.com (Devan L) Date: 6 Jul 2005 09:01:14 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1120621580.107813.47100@g43g2000cwa.googlegroups.com> Message-ID: <1120665674.114022.180500@g44g2000cwa.googlegroups.com> > Here's a couple of examples from my own code: > > # from a Banzhaf Power Index calculator > # adds things that aren't numbers > return reduce(operator.add, > (VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes)) return sum([VoteDistributionTable({0:1, v:1} for v in electoral_votes],VoteDistributionTable({})) Any time you use operator.add, you can probably use sum(sequence,initialvalue) > # from a custom numeric class > # converts a tuple of digits into a number > mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) I'll admit I can't figure out a way to replace reduce without writing some ugly code here, but I doubt these sorts of things appear often. From steven.bethard at gmail.com Sat Jul 23 20:59:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 23 Jul 2005 18:59:43 -0600 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: Thanos Tsouanas wrote: > I would like to have a quick way to create dicts from object, so that a > call to foo['bar'] would return obj.bar. > > The following works, but I would prefer to use a built-in way if one > exists. Is there one? Maybe I'm not understanding your problem, but have you looked at the builtin "vars()"? STeVe From http Wed Jul 13 22:32:37 2005 From: http (Paul Rubin) Date: 13 Jul 2005 19:32:37 -0700 Subject: Thoughts on Guido's ITC audio interview References: <42d3e666_1@news2.prserv.net> Message-ID: <7xackqt8vu.fsf@ruckus.brouhaha.com> Stephen Toledo-Brown writes: > I've not tried Mac, but under both Windows and Linux on x86, I find > Eclipse (3.0) is slow with less than 1.25 GB of RAM, reasonably fast > with 1.5GB or more. Processor speed and disk speed don't seem to be > anywhere near as important. I've used Eclipse on a 512mb laptop (1.5 ghz Pentium M) and it's been ok. I'm not sure what version. I'm not a Java fan. From vdavidster at gmail.com Wed Jul 13 17:05:37 2005 From: vdavidster at gmail.com (David Veerasingam) Date: 13 Jul 2005 14:05:37 -0700 Subject: Odd behaviour of regexp module Message-ID: <1121288737.882813.244540@f14g2000cwb.googlegroups.com> Hello It seems the grouping feature isn't behaving correctly. In [1]: a = 'dfsf.oct.ocfe' In [2]: b = re.match(r'^(.*?)\.', a); b.group() 'dfsf.' The expected result is 'dfsf'. Why did the regexp grab that period at the end? David From nicolas.couture at gmail.com Thu Jul 14 22:25:41 2005 From: nicolas.couture at gmail.com (Nicolas Couture) Date: 14 Jul 2005 19:25:41 -0700 Subject: Generating a list of None Message-ID: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> Hi, Is it possible to generate a list of `None' ? opts.__dict__.values() below could be represented by [None, None, None] --- def get_options(opts): """Return True or False if an option is set or not""" vals = opts.__dict__.values() for val in vals: if val is not None: return True return False --- This is how I'd like to see it: --- def get_options(opts): """Return True or False if an option is set or not""" vals = opts.__dict__.values() for if vals is [None * len(vals)]: return False return True --- From hancock at anansispaceworks.com Sat Jul 2 23:13:13 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 22:13:13 -0500 Subject: What are the other options against Zope? In-Reply-To: <42C7067E.4090609@anvilcom.com> References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <42C7067E.4090609@anvilcom.com> Message-ID: <200507022213.13343.hancock@anansispaceworks.com> On Saturday 02 July 2005 04:26 pm, phil wrote: > > A rather object-oriented system for managing and serving web > > applications and data (using object inheritance for common behavior, > > etc.) This makes Zope a toolkit, not an end application itself. > > So that would make it Apache, with a Python CGI. No. No object tree there --- except the filesystem, which is a braindead object tree, so doesn't really count. It is a *little* like a Macintosh filesystem, which has metadata stored for each file. > Oh wait, Apache has > a Python CGI which can access Data bases and send objects to the client. Yes, you could use that to re-write everything that Zope does for you. Why would you want to? However, many people do apparently do this all the time. Of course, Zope is by no means the only way to create a site, and may not be appropriate for everybody. But it is darned useful. > A web application is you deliver am html page and the user fills > in some forms, then submits the form, which is then validated > and another form is delivered. Right? Cool idea, IBM had that in > 1975 it was called CICS. This is true in the same sense that Python is unnecessary because all programs can be written in assembler. Or machine code for that matter. Entered by flipping switches, even -- throw away that keyboard. I have actually seen this done, BTW. Even though I'm theoretically too young. ;-) > I once asked my son-in-law tech support guy what is the Windows > registry, what does it do? He thought for a while and said > "Think of it as the soul of the machine". So I thought about it > as the soul of the machine for a while, then I asked; > "You don't know, do you", and he said "No." I did already post a serious reply, but now I'm afraid I've been trolled. :-P I was assuming you actually wanted to know what Zope was. Yes, it is a funny story, though. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From adurdin at gmail.com Wed Jul 13 02:57:38 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 13 Jul 2005 16:57:38 +1000 Subject: Defending Python In-Reply-To: References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> <42d17b1f$0$19917$636a15ce@news.free.fr> Message-ID: <59e9fd3a0507122357469b8a4e@mail.gmail.com> On 7/13/05, Jorey Bump wrote: > >>> Bruno Desthuilliers wrote: > >>> > >>> The larch! > > IT'S A TREE ... not a shrubbery? From benji at benjiyork.com Sat Jul 16 08:46:34 2005 From: benji at benjiyork.com (Benji York) Date: Sat, 16 Jul 2005 08:46:34 -0400 Subject: How do I send keystrokes to a console window in Windows XP? In-Reply-To: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> References: <1121361775.974232.302560@g44g2000cwa.googlegroups.com> Message-ID: <42D901AA.4070103@benjiyork.com> GoogleGroups at garringer.net wrote: > How do I use Python to send keystrokes to a console window in Windows > XP? import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate("Command Prompt") shell.SendKeys("cls{ENTER}") shell.SendKeys("dir{ENTER}") shell.SendKeys("echo Hi There{ENTER}") -- Benji York From schlenk at uni-oldenburg.de Thu Jul 7 09:07:56 2005 From: schlenk at uni-oldenburg.de (Michael Schlenker) Date: Thu, 07 Jul 2005 15:07:56 +0200 Subject: calling python procedures from tcl using tclpython In-Reply-To: <1120740561.933409.221770@g14g2000cwa.googlegroups.com> References: <1120740561.933409.221770@g14g2000cwa.googlegroups.com> Message-ID: <42CD292C.1010204@uni-oldenburg.de> chand wrote: > Hi.. > > I am writing a Gui in TCL and my backend code is python. I want to call > python procedure in tcl using tclpyhton. I want to know clearly how > this should be implemented. > > let's say I have procedure test_function(arg1,arg2 ...) defined in > test.py. > I want to call this procedure in tcl. Let me know how this should be > achieved. > The doubt basically have is how the tcl code knows in which .py file > this procedure is defined. > > currently I have wriiten this tcl code which is not working > > package require tclpython > set interpreter [python::interp new] > $interpreter eval {def test_function(): arg1,arg2} ; > python::interp delete $interpreter > What does not work? You never load your file test.py anywhere inside, you just evaluate 'def test_function(): arg1,arg2' so what are you expecting to happen? Your call to '$interpreter eval' lets you call arbitrary python code, but you have to provide the python code that loads your function definitions etc. I don't know python, but it should be a trivial code. Michael From thanos at sians.org Sat Jul 23 04:48:27 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sat, 23 Jul 2005 11:48:27 +0300 Subject: Getting a dictionary from an object Message-ID: <20050723084827.GA6903@zermelo.sians.org> Hello. I would like to have a quick way to create dicts from object, so that a call to foo['bar'] would return obj.bar. The following works, but I would prefer to use a built-in way if one exists. Is there one? Thanks in advance. class dictobj(dict): """ class dictobj(dict): A dictionary d with an object attached to it, which treats d['foo'] as d.obj.foo. """ def __init__(self, obj): self.obj = obj def __getitem__(self, key): return self.obj.__getattribute__(key) -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From bokr at oz.net Tue Jul 12 16:46:16 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 20:46:16 GMT Subject: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads'C1, C2 and C3' References: Message-ID: <42d42b65.16484823@news.oz.net> On Wed, 13 Jul 2005 03:47:07 +0800, "Ric Da Force" wrote: >Hi guys, > >Thank you all for your input! It was good to see so much convergence in the >approach! Again, I think that it speaks loudly for the concise way of doing >thins in Python... Anyway, I have typed in all of the solutions and have >gained a great understanding of how to do this in future. > >Thanks again! > >Ric >"Brian van den Broek" wrote in message >news:mailman.1635.1121152323.10512.python-list at python.org... >> Ric Da Force said unto the world upon 12/07/2005 02:43: >>> Hi, >>> >>> I have a string such as 'C1, C2, C3'. Without assuming that each bit of >>> text is of fixed size, what is the easiest way to change this list so >>> that it reads: >>> 'C1, C2 and C3' regardless of the length of the string. >>> >>> Regards and sorry for the newbie question, >>> >>> Ric >> >> Hi Ric, >> >> the rsplit method of strings should get you going: >> >> >>> data = "the first bit, then the second, finally the third" >> >>> chunks = data.rsplit(',', 1) >> >>> chunks >> ['the first bit, then the second', ' finally the third'] >> >>> >> >> Best, >> >> Brian vdB >> Or, to finish Brian's solution by inserting the ", and" in place of the "," : >>> data = "the first bit, then the second, finally the third" >>> ', and'.join(data.rsplit(',',1)) 'the first bit, then the second, and finally the third' >>> ', and'.join('C1, C2, C3'.rsplit(',',1)) 'C1, C2, and C3' Regards, Bengt Richter From tjreedy at udel.edu Tue Jul 12 16:50:55 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 12 Jul 2005 16:50:55 -0400 Subject: Inconsistency in hex() References: Message-ID: "Steven D'Aprano" wrote in message news:pan.2005.07.12.11.17.07.114328 at REMOVETHIScyber.com.au... > hex() of an int appears to return lowercase hex digits, and hex() of a > long uppercase. Already bug-reported and fixed for 2.5 (to use lowercase, I believe). http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1224347 From Scott.Daniels at Acm.Org Thu Jul 7 11:47:15 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 07 Jul 2005 08:47:15 -0700 Subject: (Win32 API) callback to Python, threading hiccups In-Reply-To: References: Message-ID: <42cd46b5$1@nntp0.pdx.net> Francois De Serres wrote: > PyGILState_STATE gil = PyGILState_Ensure(); > result = PyEval_CallObject(my_callback, arglist); > PyGILState_Release(gil); > Py_DECREF(arglist); > Py_DECREF(result); I think this should be: PyGILState_STATE gil = PyGILState_Ensure(); result = PyEval_CallObject(my_callback, arglist); Py_DECREF(arglist); Py_DECREF(result); PyGILState_Release(gil); The DECREFs need to be protected, that is where storage is recycled and such, and you still need Python's data structures to do that kind of work. --Scott David Daniels From hancock at anansispaceworks.com Wed Jul 20 21:52:39 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 20 Jul 2005 20:52:39 -0500 Subject: Copying attributes In-Reply-To: References: Message-ID: <200507202052.39959.hancock@anansispaceworks.com> On Wednesday 20 July 2005 05:45 pm, red wrote: > Everything seems be ok, but i'm getting: > > Traceback (most recent call last): > File "", line 169, in write > File "", line 102, in build_face_table > AttributeError: normal > > I was wondering why? I'm not sure either, yet, but can you indicate which line in your listing is 102 in the source file? That might be helpful. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From mcfletch at rogers.com Tue Jul 12 16:38:01 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 12 Jul 2005 16:38:01 -0400 Subject: Frankenstring In-Reply-To: References: Message-ID: <42D42A29.9070700@rogers.com> Thomas Lotze wrote: >Hi, > >I think I need an iterator over a string of characters pulling them out >one by one, like a usual iterator over a str does. At the same time the >thing should allow seeking and telling like a file-like object: > > Okay, first off, this is never going to be *fast* compared to something coded in C and wrapped with Python. You are dealing with every single character as a Python object, so let's forget fast for the moment and do a straightforward implementation: class Franken( str ): frankenIndex = 0 def __iter__( self ): while self.frankenIndex < len(self): yield self[ self.frankenIndex ] self.frankenIndex += 1 self.frankenIndex = 0 def seek( self, index ): self.frankenIndex = index def tell( self, index ): return self.frankenIndex if __name__ == "__main__": f = Franken( 'abcdefg' ) for c in f: print 'char', c if c == 'c': break f.seek( 5 ) l1 = list( f ) l2 = list( f ) assert l1 == [ 'f','g' ] assert l2 == list(str(f)) print 'first list', l1 print 'second list', l2 If you want to speed it up, you can optimise for various string sizes (eg using a slice of the string and the built-in iterator when appropriate), but in the end, it's not going to be anywhere near as fast as a C-engine tokeniser, so I'd personally spend more time on elegance than on speed... Anywho, have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From programmer.py at gmail.com Tue Jul 19 17:07:54 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 19 Jul 2005 16:07:54 -0500 Subject: socket programming In-Reply-To: <20050719210319.GA29578@mail.smule.com> References: <20050719204601.GB24773@mail.smule.com> <20050719210319.GA29578@mail.smule.com> Message-ID: On 7/19/05, Helge Aksdal wrote: > * Terry Reedy [2005/07/19 22:57]: > > > Ask your server administrator if you are bumping up against a hidden > > connection limit. Or if a query can ask about multiple accounts. > > how can i use a connection limit to my advantage? > i know for certain that a query can't ask about multiple accounts. > I don't think you can use a limit to your advantage. If you are bumping against some limit and you can't query for multiple accounts then there doesn't seem to be much you can really do. jw From python at rcn.com Fri Jul 15 01:16:45 2005 From: python at rcn.com (Raymond Hettinger) Date: 14 Jul 2005 22:16:45 -0700 Subject: set and frozenset unit tests? References: <3jhaoaFq2kajU1@individual.net> Message-ID: <1121404605.639967.246890@f14g2000cwb.googlegroups.com> [Jacob Page] > there are two minor things I > don't see documented that caught me by surprise: > > * Since the <=, <, >, and >= operators raise an exception if the > right-hand operand is not a set or frozenset, it seemed reasonable to > me to assume that == and != should, too. However, the test suite for > sets expect the comparisons to be allowed; == between a set and non-set > return False, != returns True. Seems inconsistent with the rest of the > operators, but then again, the odd use of > and < for purposes other > than ordering also seems strange. It is consistent with the rest of Python. It turns out to be somewhat handy to be able to run an equality test with objects of differing types: if x != None: ... # doesn't blow-up is x is a string or number if 'cat' in [1, 3.1, 'hat']: ... # doesn't blow-up during eq tests OTOH, the subset/superset tests pretty much require a set to be on both sides. Welcome to the strange and exciting world of rich comparisons. > * Apparently, if fs is a frozenset instance, fs.copy() returns a > reference to fs instead of a copy of fs, and frozenset(fs) does the > same. The unit tests also ensure that subclasses of frozenset don't do > this. It makes sense that it's done that way to save on storage space, > but it's not documented that this happens. It is not documented because it is not a guaranteed part of the API. Most immutables are like this. Whether equivalent strings and numbers share the same object id is an implementation detail. Raymond From hancock at anansispaceworks.com Wed Jul 6 02:44:03 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 6 Jul 2005 01:44:03 -0500 Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: <200507060144.03342.hancock@anansispaceworks.com> On Tuesday 05 July 2005 03:53 pm, Renato Ramonda wrote: > Why not use just spaces? Vim simplifies this immensely: > > set tabstop=4 > set shiftwidth=4 > set expandtab > set smarttab > set autoindent > > AFAICT this gives me all spaces, 4 spaces indent, tab inserts spaces and > backspace over a block of 4 spaces deletes all of them (just like > deleting a tab). Yep, this is what I just set up in my .vimrc. Works beautifully. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From Scott.Daniels at Acm.Org Fri Jul 22 00:12:20 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 21 Jul 2005 21:12:20 -0700 Subject: Help with regexp please In-Reply-To: References: Message-ID: <42e069ef$1@nntp0.pdx.net> Felix Collins wrote: > Hi, > I'm not a regexp expert and had a bit of trouble with the following search. > I have an "outline number" system like > 1 > 1.2 > 1.2.3 > I want to parse an outline number and return the parent. Seems to me regex is not the way to go: def parent(string): return string[: string.rindex('.')] From twic at urchin.earth.li Fri Jul 1 08:37:40 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 1 Jul 2005 13:37:40 +0100 Subject: map vs. list-comprehension In-Reply-To: References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: On Thu, 30 Jun 2005, Roy Smith wrote: > Terry Hancock wrote: > >> One of the strengths of Python has been that the language itself is >> small (which it shares with C and (if I understand correctly, not being >> a lisp programmer?) Lisp), but with all the syntax enhancements going >> on, Python is getting pretty complicated. I have to wonder if new users >> won't begin to find it just as intimidating as Perl or other big >> languages. > > +1 > > Even some of the relatively recent library enhancements have been kind > of complicated. The logging module, for example, seems way over the > top. Exactly the same thing happened with Java. if you look at the libraries that were in 1.1, they're very clean and simple (perhaps with the exception of AWT). 1.2 added a load of stuff that was much less well-designed (with the notable exception of the collections stuff, which is beautiful), and a lot of the extension packages that have been written since then are seriously crappy. My particular bugbear is JAI, the imaging library, the most gratuitously badly-designed library it has ever been my misfortune to work with. EJB is another great example. I imagine the reason for this degradation has been the expansion of the java design team: it started off with James Gosling, who is an incredibly smart guy and an awesome engineer, and a relatively small team of crack troops; they were capable of writing good code, and really cared about doing that. Over the years, as it's grown, it's had to absorb a lot of people who don't have that combination of intelligence and good taste, and they've written a lot of crap. I suspect a trend away from gifted lone hackers and towards design by committee hasn't helped, either. How this applies to python, where the BDFL is still very much at the helm, is not clear. I wonder if analogies to Linux, also a despotism, are more useful? tom -- In-jokes for out-casts From k33rni at gmail.com Mon Jul 4 06:13:15 2005 From: k33rni at gmail.com (k33rni at gmail.com) Date: 4 Jul 2005 03:13:15 -0700 Subject: curses -- getxy() error In-Reply-To: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> References: <1120471453.689700.274040@g14g2000cwa.googlegroups.com> Message-ID: <1120471995.826051.126700@z14g2000cwz.googlegroups.com> shablool wrote: > Could someone please explain why stdscr.getxy() always raise an > exception: [code here] the method is named getyx(), this is old unix heritage. see http://www.python.org/doc/2.0.1/lib/curses-window-objects.html From max at alcyone.com Mon Jul 4 19:05:40 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Jul 2005 16:05:40 -0700 Subject: f*cking re module In-Reply-To: References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <20050704193920.GB9841@burma.localdomain> Message-ID: James Stroud wrote: > Its perhaps that they remember the frustration of being new to programming. > Those "wasted" 1.5 hr sessions getting nowhere add up pretty fast and then > the explicatives begin to flow. Also because the best way to make someone who's having a tantrum look foolish in public is to treat them with dignity and respect while they continue rambling and ranting. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Sometimes a cigar is just a cigar. -- Sigmund Freud From devlai at gmail.com Fri Jul 8 20:14:34 2005 From: devlai at gmail.com (Devan L) Date: 8 Jul 2005 17:14:34 -0700 Subject: removing list comprehensions in Python 3.0 In-Reply-To: References: Message-ID: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> List comprehensions are faster than generator comprehensions for iterating over smaller sequences. From ralf at tecont.de Thu Jul 21 05:01:02 2005 From: ralf at tecont.de (Ralf Muschall) Date: Thu, 21 Jul 2005 11:01:02 +0200 Subject: Lots of pdf files In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > Hello- > I'm running Python 2.3 on a Linux system and have lots (about 2000) > files in pdf format to print each day. If I just wind up and fire all > the files at the printer at once (as 2000 separate print jobs), the > print server throws a fit and our system admin comes down and slaps me > around for a few minutes (which, I guess, is fair). Are your sure it is the number (and not the sum of the sizes) of the jobs your admin is worrying about? What about #!/bin/sh for i in *.pdf; do lpr $i sleep 10 done (maybe adding something that waits until the queue is empty instead of sleep)? Ralf From hongqn at gmail.com Sun Jul 10 14:18:49 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Mon, 11 Jul 2005 02:18:49 +0800 Subject: PyArg_ParseTuple help In-Reply-To: <1121010240.884978.119330@f14g2000cwb.googlegroups.com> References: <1121010240.884978.119330@f14g2000cwb.googlegroups.com> Message-ID: <42D16689.7080704@gmail.com> zyqnews at 163.net wrote: > hello all, > how to parse the arguments of a c function with PyArg_ParseTuple? > The prototype of the c function is : > int func(unsigned char * in , int inlen, unsigned char * v, unsigned > char * out, int * outlen); > > The problem is , when the func returns, there will be results in out > and outlen. Is the following format is correct? As the ``out'' and ``outlen'' are used for output, you should not pass them to a python function as parameters. Instead, you'd better make the return value of the python function to represent them (if the python caller wants them, of course). In your case, returning a python string object will be a good choice if outlen is the length of out array, since a python string knows its length. So, you need only parse the parameters of ``in'', ``inlen'' and ``v'' in the wrap function. And even further, the python caller can pass a python string to replace ``in'' and ``inlen''. Then, the prototype of the function is something like: def func(ins, v) which returns a string. [...] -- Qiangning Hong From gsakkis at rutgers.edu Thu Jul 7 21:11:30 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Jul 2005 18:11:30 -0700 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: <1120785090.297591.189750@g49g2000cwa.googlegroups.com> "Tony Meyer" wrote: > > Your first sentence contradicts the rest of your post; how is > > Java the problem if it runs nice on a Mac and is sluggish on > > Windows ? > > Because any Java program on (any version of) Windows (in my experience) is > sluggish, and this is not true (again, in my experience) for Java programs > on a Mac. > > There is a vast difference between the various JREs; whereas every platform > I've used a cPython interpreter on has given reasonably constant performance > (which is to be expected, with a C implementation). "Java" as a term means different things to different people, but I expect most would think of the core language and its standard library first and the JRE/JVM second. So saying "the problem of X is Java" when you really mean "the problem of X in platform Y is Sun's JVM in Y" is kinda misleading. Disclaimer: I am neither Java's not Eclipse's advocate; I'll choose python over Java any day, but let's put the blame where it is due. George From steve at REMOVETHIScyber.com.au Sun Jul 24 10:02:03 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 25 Jul 2005 00:02:03 +1000 Subject: Getting a dictionary from an object References: Message-ID: On Sun, 24 Jul 2005 12:07:02 +0300, Thanos Tsouanas wrote: > On Sat, Jul 23, 2005 at 06:59:43PM -0600, Steven Bethard wrote: >> Thanos Tsouanas wrote: >> > I would like to have a quick way to create dicts from object, so that a >> > call to foo['bar'] would return obj.bar. >> > >> > The following works, but I would prefer to use a built-in way if one >> > exists. Is there one? >> >> Maybe I'm not understanding your problem, but have you looked at the >> builtin "vars()"? > > I didn't know about it, but I knew about object.__dict__ which is, as I > see equivalent with vars(object). But it doesn't do the job for me, > since it fails to grab all obj.foo's, some of them being properties, > etc. You could have mentioned this earlier. But I don't think you are correct. As far as I can see, properties do have an entry in obj.__dict__ the same as other attributes, although there is certainly some strangeness going on with properties. Using the sample code from here: http://www.python.org/2.2.3/descrintro.html#property class C(object): def __init__(self): self.__x = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x x = property(getx, setx) I see _C__x in C().__dict__, exactly as expected. (The _C is Python's standard name mangling of "semi-private" attributes starting with double underscores.) I can't see any way to inspect a Python object and get a list of properties, so you might have to keep your own list: add a class-attribute of your object which keeps a list of all the properties: class Obj: # various methods, attributes and properties ... # keep a list of special properties that don't show # up correctly in __dict__ special = ['foo', 'bar'] # now define a special method that makes a copy of # __dict__ and adds special properties to it def objdict(self): D = self.__dict__.copy() # assume shallow copy is enough for property_name in self.special: D[property_name] = self.__getattribute__(property_name) return D then call it when you need it: print "My object has fields %(foo)s and %(bar)s." % obj.objdict() It would be nice to see an easier way to introspect objects and get a list of properties. -- Steven. From max at alcyone.com Sat Jul 30 15:44:49 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Jul 2005 12:44:49 -0700 Subject: Selection, picking with PyOpenGL? In-Reply-To: References: Message-ID: Mike C. Fletcher wrote: > I think you're missing what's returned from the glRenderMode code (which > is non-standard OpenGL, to avoid the need for Python code using and > decoding structured pointers), from OpenGLContext: I was indeed. I was looking at the text description, which, like the OpenGL documentation, talks about it returning the number of hits. I didn't look carefully enough at the Python return value :-). Thanks, Mike! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I am not a Virginian, but an American. -- Patrick Henry From peter at engcorp.com Sat Jul 2 14:04:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 14:04:29 -0400 Subject: email link and foreign accent In-Reply-To: References: Message-ID: <6f-dnTSTQazBSlvfRVn-jQ@powergate.ca> Vittorio wrote: > print"""""" %(campovalore.encode('iso-8859-1')) > print campovalore.encode('iso-8859-1') > print """""" > > campovalore is an email address with special (italian) characters. > [snip] > Any suggestion is welcome, It might help if you showed us the output of "repr(x)" where x is the output of the campovalore.encode('iso-8859-1') part above. -Peter From roccomoretti at hotpop.com Fri Jul 1 10:43:58 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 01 Jul 2005 09:43:58 -0500 Subject: Modules for inclusion in standard library? In-Reply-To: <7x3br1ger1.fsf@ruckus.brouhaha.com> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Rocco Moretti writes: > >>Except that (please correct me if I'm wrong) there is somewhat of a >>policy for not including interface code for third party programs which >>are not part of the operating system. (I.e. the modules in the >>standard libary should all be usable for anyone with a default OS + >>Python install.) > > > I've never heard of Python having such a policy and I don't understand > how such a stupid policy could be considered compatible with a > proclaimed "batteries included" philosophy. Why would Python > advocates want to make Python deliberately uncompetitive with PHP, > Java, and other languages that do include database modules? Well, since there seems to be an outpouring of disgust at my statement, and no official confirmation/rejection, it's probably a figment of my prematurely failing mind. However, if there was such a policy, it would not be unequivocally "stupid." First off, there is a bit of flexibility in what is considered part of the OS. E.g, Linux may properly refer to just the kernel, but rarely is just the kernel installed. Various utilities and programs might be considered part of the OS because they are ubiquitously installed, or are included with the Python distribution itself (as Tk is with windows Python). For those programs which aren't ubiquitously installed, or even for ones that are, but require significant configuration, it is reasonable to expect that if someone has the ability and goes to the effort of locating, obtaining, installing, and configuring a third party program, they can just as easily obtain and install the python module, especially as it's usually as easy as "python setup.py install". At any rate, I'm not advocating such a policy, I'm just saying it can make a bit of sense if you look at it from a certain angle. From mwm at mired.org Fri Jul 8 01:11:10 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 08 Jul 2005 01:11:10 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120635034.080123.218060@g47g2000cwa.googlegroups.com> <1120636418.166800.42290@o13g2000cwo.googlegroups.com> <1120642040.109796.212450@o13g2000cwo.googlegroups.com> Message-ID: <868y0hvq4x.fsf@bhuda.mired.org> "Antoon Pardon" wrote in message news:slrndcpoan.5vp.apardon at rcpc42.vub.ac.be... > I'll clarify. A lot of the time I hear arguments against > features that boils down to. It seems that you've lost some of the intent during the boiling. > 1) I don't need it. Is that what you get out of the oft-used "What's your use case"? That's an attempt to find out what problem the proposer thinks the feature would help solve, so said solution can be evaluated in comparison to possible existing solutions. > 2) Having the feature will make my job more difficult. Well, if the job is "writing programs" or "debugging programs", then that's a *good* reason for not adding the feature. Those jobs are hard enough as it is. Any feature that makes them noticably harder needs to provide some serious advantages in order to be justified. > 3) I don't understand the merrits of the feature or I > have difficulty understanding what it does when I > encounter it. I don't think I've seen the first one used as an argument against a feature. I may well have missed them, as I don't follow all such discussion completely. The second one is a variation on #2, above. Adding features just because they are "cool" is not the right way to grow a language. New features need to enhance the language in a clearly positive manner, while having as little negative impact as possible. Point 1 and the first part of 3 are cases of people who don't see a real enhancement to the language. Point 2 and the second part of 3 are cases where people see a serious negative impact from a feature. When people *quit* pointing out those kinds of problems with proposals, then I'll be worried. Python will be on it's way to becoming Perl 6 or Common LISP, rather than the powerful, elegant language I've come to love. Bringing up such objections also gives the proposer a chance to correct the problem, which is to everyones advantage. Witness the recent (short) discussion of adding dynamically scoped variables. As originally proposed, they can produce very obscure and hard-to-find bugs. The fix for this made them no worse than global variables. > IMO these are arguments if followed sufficiently will lead to > a language that is only usefull for mediocre programmers. Unless you're arguing that Python is already a language that is only usefull for mediocre programmers, then this is sort of moot. Those are arguments being advanced against *adding* features, not for removing them (at least, I don't think I saw any of them in the ongoing discusion re map/filter/reduce/lambda). Or are you arguing that Python will somehow become less useful as new features are proposed and rejected? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fonnesbeck at gmail.com Thu Jul 28 10:11:07 2005 From: fonnesbeck at gmail.com (Chris Fonnesbeck) Date: Thu, 28 Jul 2005 10:11:07 -0400 Subject: baffling error-handling problem Message-ID: <723eb69305072807116a6d6975@mail.gmail.com> I thought I knew how to do error handling in python, but apparently I dont. I have a bunch of code to calculate statistical likelihoods, and use error handling to catch invalid parameters. For example, for the bernoulli distribution, I have: def bernoulli_like(self, x, p, name='bernoulli'): """Bernoulli log-likelihood""" # Ensure proper dimensionality of parameters dim = shape(x) p = resize(p,dim) # Ensure valid values of parameters if sum(p>=1 or p<=0): raise LikelihoodError ... etc. where LikelihoodError is simply a subclass of ValueError that I created: class LikelihoodError(ValueError): "Log-likelihood is invalid or negative infinite" I catch these errors with the following: try: like = self.calculate_likelihood() except LikelihoodError: return 0 So far, so good. When I calculate_likelihood is called in the above, which contains a call to bernoulli_like: p = invlogit(beta0 + sum([b*h for b,h in zip(self.beta,hab)])) like=self.bernoulli_like(x,p) I get the following when an invalid parameter is passed: Traceback (most recent call last): File "C:\Conroy\working\resource_selection_ms\analyses\IIbq\sampled\new_chris\model_000.py", line 381, in ? model.sample(iterations=iter, burn=burn,plot=False) File "C:\Python23\Lib\site-packages\PyMC\MCMC.py", line 1691, in sample self._like = self.calculate_likelihood() File "C:\Conroy\working\resource_selection_ms\analyses\IIbq\sampled\new_chris\model_000.py", line 194, in calculate_likelihood like+=self.bernoulli_like(x,p) File "C:\Python23\Lib\site-packages\PyMC\MCMC.py", line 868, in bernoulli_like if sum(p>=1 or p<=0): raise LikelihoodError LikelihoodError I have no idea how this can happen, given how I have coded this. Anyone see what I must be missing? Thanks, C. From mwm at mired.org Thu Jul 21 20:20:26 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 21 Jul 2005 20:20:26 -0400 Subject: Stupid question: Making scripts python-scripts References: <42dfb111@griseus.its.uu.se> Message-ID: <8664v3r8s5.fsf@bhuda.mired.org> Bill Mill writes: > On 7/21/05, Jan Danielsson wrote: >> Hello all, >> >> How do I make a python script actually a _python_ in unix:ish >> environments? >> >> I know about adding: >> #!/bin/sh >> >> ..as the first row in a shell script, but when I installed python on >> a NetBSD system, I didn't get a "python" executable; only a "python2.4" >> executable. >> >> Adding "#!/usr/pkg/bin/python2.4" as the first row in the script >> would probably work, but that would be too specific for the system I'm >> using, imho. >> >> I saw someone using "#!/usr/bin/env python", but that failed on the >> system I'm using, so I assume that's something specific too (or is the >> installation broken?). > > The env program [1], which usually exists at least on a linux system, > executes the program given as its argument. Thus, "/usr/bin/env > python" tries to executes python, which bash will then use to run the > python script. As long as env exists, and python is somewhere in the > PATH, this is a fairly portable way to run python scripts. env doesn't invoke the shell, it uses execvp, which "duplicates the actions of the shell in searching for an executable." Further, he's on NetBSD - he may not have bash installed. My FreeBSD box certainly doesn't. > Does BSD really not come with the env program? I bet there's an > equivalent you could symlink to it. Unfortunately, I've never BSDed, > so I can't help you find it. To get a workable subset of the normal > env functionality, you could try (assuming you use bash): NetBSD comes with an env. His env is failing because he doesn't have a "python" command installed. This appears to be wart(?) in the NetBSD packaging system. To allow multiple versions of FreeBSD to coexist, it doesn't install a "python" command at all, but instead leaves the versioned one around. Two solutions: have your scripts use #!/usr/pkg/bin/python2.4. That way, when you install a new python, they will keep using the old one. That will insure they won't break when you upgrade. However, such breakage is pretty rare in practice. I'd pick a favorite bin directory and symlink from python there to /usr/pkg/bin/python2.4, then use "#!/usr/bin/env python" in your scripts. While I'm on the topic, I think I'll share my favorite cool trick. #!/usr/opt/bin/mypythonscript Doesn't work because Unix won't let you use an interpreted script as the interpreter (is this true for all variants?). However, #!/usr/bin/env mypythonscript works like a charm. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From go2len at TRALALALAhotmail.com Wed Jul 6 09:52:35 2005 From: go2len at TRALALALAhotmail.com (Lennart) Date: Wed, 6 Jul 2005 15:52:35 +0200 Subject: Good starterbook for learning Python? References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> <1120654935.486354.75550@g47g2000cwa.googlegroups.com> Message-ID: <1l2969k9tbx01.opflwh7p50nk.dlg@40tude.net> Op 6 Jul 2005 06:02:15 -0700 schreef Fuzzyman: > A book that will stay useful as a referene *after* you've used it to > learn is 'Programming Python'. > > Best Regards, > > Fuzzy > http://www.voidspace.org.uk/python A thanks! I've downloaded the book "dive into python". It costs me near 23 euro to print it by the copyshop (yes, i prefer paper - you can write on paper, you know :-) Programming Python will I sell as a book that i read secondly, and use as a reference. From draghuram at gmail.com Fri Jul 15 17:03:12 2005 From: draghuram at gmail.com (draghuram at gmail.com) Date: 15 Jul 2005 14:03:12 -0700 Subject: What module to use to get a file from a website? In-Reply-To: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> References: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> Message-ID: <1121461391.968271.70680@g44g2000cwa.googlegroups.com> urllib2.urlopen() From spam.csubich+block at block.subich.spam.com Thu Jul 28 21:53:53 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 28 Jul 2005 21:53:53 -0400 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: Andrew Dalke wrote: > Steven Bethard wrote: > >>Here's one possible solution: >> >>py> import itertools as it >>py> def zipfill(*lists): >>... max_len = max(len(lst) for lst in lists) > > > A limitation to this is the need to iterate over the > lists twice, which might not be possible if one of them > is a file iterator. > > Here's a clever, though not (in my opinion) elegant solution > > import itertools > > def zipfill(*seqs): > count = [len(seqs)] > def _forever(seq): > for item in seq: yield item > count[0] -= 1 > while 1: yield None > seqs = [_forever(seq) for seq in seqs] > while 1: > x = [seq.next() for seq in seqs] > if count == [0]: > break > yield x I like this solution best (note, it doesn't actually use itertools). My naive solution: def lzip(*args): ilist = [iter(a) for a in args] while 1: res = [] count = 0 for i in ilist: try: g = i.next() count += 1 except StopIteration: # End of iter g = None res.append(g) if count > 0: # At least one iter wasn't finished yield tuple(res) else: # All finished raise StopIteration From ivoras at something.ortheother Sat Jul 23 21:04:11 2005 From: ivoras at something.ortheother (Ivan Voras) Date: Sun, 24 Jul 2005 03:04:11 +0200 Subject: PostgreSQL & Python vs PHP In-Reply-To: <3kfetaFu5fcrU1@individual.net> References: <3kfaucFu3tlfU1@individual.net> <1122139628.703635.48610@g14g2000cwa.googlegroups.com> <3kfetaFu5fcrU1@individual.net> Message-ID: Luis P. Mendes wrote: > I need to build it from the server and also client side. > > For the client side I'll be using Python. > > But for the server side, I would like to hear some opinions. Is it worth > learning Php? If you know Python and don't know PHP, there's little benefit from spending the time learning it. But, PHP is extremely simple to work with and you can produce results VERY quickly. Part of the reason is that it's already intended to be a web-embedded language and doesn't reqire additonal frameworks, libraries or configuration like Python does. One thing that botheres me when using Python in php-like way is that the "indentation is significant" property becomes a nuisance when you intertwine HTML and code (which you shouldn't be doing anyway ;) ). The benefit of Python is that is a much cleaner language with well defined interfaces and you'll probably maintain a large application easier if it's in Python. There are no significant performance differences, and no really significant differences in programming approach. From paolo_veronelli at tiscali.it Fri Jul 29 08:05:09 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Fri, 29 Jul 2005 14:05:09 +0200 Subject: Ten Essential Development Practices In-Reply-To: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <42EA1B75.9040307@tiscali.it> gyromagnetic at gmail.com wrote: > The following url points to an article written by Damian Conway > entitled "Ten Essential Development Practices": > http://www.perl.com/pub/a/2005/07/14/bestpractices.html > > Althought the article has Perl as a focus, I thought that some of the > general points made might be of interest to the Python community. It > would certainly be interesting to put together an analogous version of > this article that centers on Python. > Hmm, Perl is called a write once language, but it has thousands of libraries.Any comment appreciated. That said,those points are mixing different responsabilities in writing code.I keep on mixing for fun: -Writing libraries is not writing scripts. -Writing readable,well structured,non redundant code is somewhat perpendicular to tests. -Writing tests is a must for more people to work on the same code. -Deciding the interface and writing docs before coding can be bad for experimental coding. -Logic optimization can influence interfaces. -Time optimization is a leverage to get paid in open source software.Never think about that for free. Paolino ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From sjmachin at lexicon.net Sat Jul 2 18:59:30 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 03 Jul 2005 08:59:30 +1000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) In-Reply-To: References: <42C54915.3020501@lexicon.net> Message-ID: <42C71C52.1080705@lexicon.net> Christos TZOTZIOY Georgiou wrote: > On Fri, 01 Jul 2005 23:45:57 +1000, rumours say that John Machin > might have written: > > >>Simon Brunning wrote: >> >>>On 7/1/05, Peter Maas wrote: >>> >>> >>>>Simon Brunning schrieb: >>>> >>>> >>>>> Sibylle Koczian needs to sort part of a list. His first attempt made >>>>> the natural mistake - sorting a *copy* of part of the list: > > > [Peter] > >>>>I think it was _her_ first attempt. > > > [Simon] > >>>Ooops! Sorry, Sibylle. > > > [John] > >>Obviously haven't spent enough time watching Fawlty Towers :-) > > > Then surely it should have been "its" first attempt? Aren't piranhas > neutral? Neutral: no, they always seem to be active combatants. Neuter: one would hope so, lest they procreate. From rkern at ucsd.edu Sun Jul 31 20:14:21 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 17:14:21 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <200507311709.18243.jstroud@mbi.ucla.edu> References: <7xr7de5zoe.fsf@ruckus.brouhaha.com> <200507311709.18243.jstroud@mbi.ucla.edu> Message-ID: James Stroud wrote: > "/data10/users/jstroud/Programs/lib/python2.3/site-packages/wx-2.6-gtk2-ansi/wx/py/editwindow.py", > line 8, in ? > from wx import stc > File > "/data10/users/jstroud/Programs/lib/python2.3/site-packages/wx-2.6-gtk2-ansi/wx/stc.py", > line 10, in ? > import _stc > ImportError: No module named _stc You can't blame Dabo for this one. Your wxPython install is broken. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rrr at ronadam.com Sun Jul 10 13:59:46 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 10 Jul 2005 17:59:46 GMT Subject: Use cases for del In-Reply-To: <3jc5p0Fp4nlgU1@individual.net> References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> <42CE0E38.60305@REMOVEMEcyber.com.au> <1120825627.498017.19370@g47g2000cwa.googlegroups.com> <42d0529a$1@nntp0.pdx.net> <3jc5p0Fp4nlgU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Ron Adam wrote: > > >>> >>> 'abc' is 'abcd'[:3] >>> False >> >>Well of course it will be false... your testing two different strings! >>And the resulting slice creates a third. >> >>Try: >> >>ABC = 'abc' >> >>value = ABC >>if value is ABC: # Test if it is the same object >> pass > > > That's not going to buy you any time above the "is None", because identity- > testing has nothing to do with the type of the object. Ok, I retested it... Not sure why I was coming up with a small difference before. It seemed strange to me at the time which is part of why I asked. My point was using strings "could" work in same context as None, (if None acted as del), with out a performance penalty. Anyway, this is all moot as it's an solution to a hypothetical situation that is not a good idea. > Additionally, using "is" with immutable objects is horrible. Why is it "horrible"? Oh nevermind. ;-) Cheers, Ron > Reinhold From tjreedy at udel.edu Fri Jul 8 20:32:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 8 Jul 2005 20:32:08 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <74ize.27369$ho.19404@bignews6.bellsouth.net><9nmze.144208$VH2.52770@tornado.tampabay.rr.com> <1120852274.923521.211250@g43g2000cwa.googlegroups.com> Message-ID: "George Sakkis" wrote in message news:1120852274.923521.211250 at g43g2000cwa.googlegroups.com... > "Steven Bethard" wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course, is that dict comprehensions don't gain you much >> at all over the dict() constructor plus a generator expression, e.g.: >> dict((i, chr(65+i)) for i in range(4)) > Sure, but the same holds for list comprehensions: list(i*i for i in > xrange(10)). The difference is historic I guess; list comprehensions > preceded generator expressions and so they cannot be removed, at least > not before 3.0. I wonder if they will/should be in the language when > the constraint of backwards compatibility is lifted. Guido has asked himself the same question. Some developers who love l.c.s are sure they will stay. I am not. I think it might depend on whether they have any real advantages in the context of the 3.0 engine and design, which don't exist yet. > IMO they should > not (TIOOWTDI, uniformity among builtin data structures, not > overwhelmingly more useful than set or dict comprehensions), but > there's a long way till that day. Yes. Terry J. Reedy From noreply at gcgroup.net Tue Jul 19 14:08:48 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 19 Jul 2005 18:08:48 GMT Subject: main window in tkinter app In-Reply-To: References: Message-ID: It also seems to operate the same with or without " app.mainloop()". Is an explicit call to mainloop needed? William Gill wrote: > O.K. I tried from scratch, and the following snippet produces an > infinite loop saying: > > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1647, in __getattr__ > return getattr(self.tk, attr) > > If I comment out the __init__ method, I get the titled window, and print > out self.var ('1') > > > import os > from Tkinter import * > > class MyApp(Tk): > var=1 > def __init__(self): > pass > def getval(self): > return self.var > > > app = MyApp() > > app.title("An App") > print app.getval() > app.mainloop() > > > Eric Brunel wrote: > >> On Mon, 18 Jul 2005 16:57:51 GMT, William Gill >> wrote: >> >>> A short while ago someone posted that(unlike the examples) you should >>> use Tk as the base for your main window in tkinter apps, not Frame. >>> Thus : >>> >>> class MyMain(Frame): >>> def __init__(self, master): >>> self.root = master >>> self.master=master >>> self.createWidgets() >>> def createWidgets(): >>> ... >>> root = Tk() >>> app = MyMain(root) >>> app.master.title("Object Editor") >>> root.mainloop() >>> >>> would become: >>> >>> class MyMain(Tk): >>> ... >>> ... >>> app = MyMain() >>> app.title("My App") >>> app.mainloop() >>> >>> When I try converting to this approach I run into a problem with the >>> __init__() method. It appears to go into an infinite loop in >>> tkinter.__getattr__(). >> >> >> [...] >> >> I never ran into this problem. Can you please post a short script >> showing this behavior? Without knowing what you exactly do in your >> __init__ and createWidgets method, it's quite hard to figure out what >> happens... From shai at platonix.com Thu Jul 7 08:20:15 2005 From: shai at platonix.com (Shai) Date: 7 Jul 2005 05:20:15 -0700 Subject: Favorite non-python language trick? References: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> <86psu2410u.fsf@bhuda.mired.org> <86ll4q3q0m.fsf@bhuda.mired.org> <1120689545.113419.318680@g14g2000cwa.googlegroups.com> <86y88juw2u.fsf@bhuda.mired.org> Message-ID: <1120738815.656164.248710@g14g2000cwa.googlegroups.com> Mike Meyer wrote: > "Shai" writes: > > > They're called "Special vars", and you need to define them (unlike > > local LISP variables, which behave essentially like Python vars), but > > then you use them just like other vars (that is, you usually bind them > > with LET). This is the first I hear about them being ill-considered in > > LISP; http://www.gigamonkeys.com/book/ is a recently published LISP > > book which recommends them. I don't know about Scheme, but I think it > > does have them. > > I'm pretty sure scheme doesn't have dynamically bound variables. I > just went through r5rs to check, and couldn't find them. > Yes, you're right. One learns. > > dynamic x=10 > > def bar(): > > print x > > > > This looks different from what I understood before. You're now > declaring the variable dynamic in the global scope, rather than in the > function that makes it dynamic. This is a *much* more palatable > situation. > This is indeed different from what I said first. It copies the Common LISP construct without regard to consistency with the Python global construct. > Globals are lexically scoped. As such, you can find the defintion of > the variable by examining the module that includes the function. Yes, > other modules can reach into your module and change them - but you can > find those, because they reference your module by name. > > A dynamic variable declared so in a function has no such clue > associated with it. If the variable is declared dynamic in the module > of the enclosed function, that provides a contextual clue. In my original proposal, dynamic variables are seen as globals from the function in their module which reads them; no more, no less. The important point I want from dynamic scope is the time-locality of asignments, that is, the fact that they are undone when the (lexical) scope of the new binding ends. This allows the use of globals, with a lot less fear of unintended interactions between users of the module (well, this is only accurate until multithreading enters the picture, but that can be handled too). [rest snipped] From bvande at po-box.mcgill.ca Sat Jul 2 00:03:47 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 00:03:47 -0400 Subject: Bad Math In-Reply-To: References: Message-ID: <42C61223.1040605@po-box.mcgill.ca> Patrick Rutkowski said unto the world upon 01/07/2005 23:56: > I started reading a python book today, one example was: > > >>>>4 / (2.0 + 3) > > 0.8 > > My input/output was: > > >>>>4 (2.0 + 3) > > 0.80000000000000004 > > Something smells fishy here... whats up? > > --python 2.4.1 From hancock at anansispaceworks.com Wed Jul 13 00:40:54 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 12 Jul 2005 23:40:54 -0500 Subject: breaking out of nested loop In-Reply-To: <9A28C052FF32734DACB0A288A3533991EBB9AB@vogbs009.gb.vo.local> References: <9A28C052FF32734DACB0A288A3533991EBB9AB@vogbs009.gb.vo.local> Message-ID: <200507122340.54212.hancock@anansispaceworks.com> On Tuesday 12 July 2005 10:28 am, Tim Golden wrote: > [Jeremy Sanders] > | rbt wrote: > | > | > What is the appropriate way to break out of this while loop > | if the for > | > loop finds a match? > | > | queue discussion why Python doesn't have a "break N" statement... > > > > Presumably you meant "cue discussion..." > > Or "queue" as in, it's going to have to take a number and wait for someone to be bored enough with the ten other language "enhancement" threads that have gone through lately. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Thu Jul 21 12:26:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 22 Jul 2005 02:26:23 +1000 Subject: Hash functions Message-ID: Do people often use hash() on built-in types? What do you find it useful for? How about on custom classes? Can anyone give me some good tips or hints for writing and using hash functions in Python? Thank you, -- Steven. From no at spam Sat Jul 30 04:08:22 2005 From: no at spam (D H) Date: Sat, 30 Jul 2005 03:08:22 -0500 Subject: A replacement for lambda In-Reply-To: <867jf9jmfw.fsf@bhuda.mired.org> References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Rewriting a canonical abuse of lambda in this idiom gives: > > myfunc = def @(*args): > return sum(x + 1 for x in args) Nice proposal. Technically you don't need the @ there, it is superfluous. But then again so is the colon, so whatever floats your boat. > class Spam(object): > myprop = property(fget = def @(self): > return self._properties['myprop'] > , > fset = def @(self, value): > self._properties['myprop'] = value > , > fdel = def @(self) > del self._properties['myprop'] > , > doc = "Just an example") I think the anonymous lambdas need to be outside the parentheses to be parsable. Maybe like this: class Spam(object): myprop = property(fget, fset, fdel, doc="just an example"): where fget = def (self): ......... where fset = def (self): ......... where fdel = def (self): ........... As you can see, it doesn't save much over the traditional way since you have to name the "anonymous" lambdas anyway. From rrr at ronadam.com Wed Jul 27 19:08:38 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 27 Jul 2005 23:08:38 GMT Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Michael Hoffman wrote: > Ron Adam wrote: > >> In all current cases, (that I know of), of differing types, '+' raises >> an error. > > > Not quite: > > >>> "hello " + u"world" > u'hello world' > >>> 4.5 + 5 > 9.5 > >> Question: Is a path object mutable? > > > No. > > This should answer the rest of your questions. Yes it does, thanks. In the case of numeric types, it's an addition and not a join. I should have specified in 'all cases, (I know of), where '+' is used to join objects, but I thought that was clear from the context of the discussion. I haven't needed to use unicode yet, so it didn't come to mind. Although it raises other questions... ;-) Could a string prefix be used with paths as well? path = p"C://somedir//somefile" Would that clash with the 'u' prefix? Or would we need a 'p' and a 'up' prefix to differentiate the two? (Just a thought. I'm +0 on this, but this seems to be a new string type, and file operations are frequent and common.) You could have both behaviors with the '+'. path_a + path_b -> join path_b to path_a using separator. path + string -> append string to path (no separator) string + path -> prepends string to path (no separator) This would be similar, (but not exactly like), how u'text'+'text' and 'text'+u'text' work. They both return unicode strings given a standard string. It would allow the following to work. path = path('C:')+path('somedir')+path('somefile.txt')+'.zip' ->> 'C://somedir//somefile.txt.zip' So I guess the question here is which of these is preferable with '+'? 1. Strings act like paths when one is a path. They will be joined with a separator. 2. Paths are joined with separators *and* a string is prepended or postpended "as is" with no separator. 3. All path objects (and strings) act like strings. No separator is used when joining path objects with '+'. (Seems like #3 defeats the purpose of path a bit to me.) I'm +1 on #2 after thinking about it. Cheers, Ron From hayrierdener at gmail.com Fri Jul 22 09:07:55 2005 From: hayrierdener at gmail.com (Hayri ERDENER) Date: Fri, 22 Jul 2005 16:07:55 +0300 Subject: command line argument passing Message-ID: <261d32a70507220607621130f3@mail.gmail.com> hi to all, is it possible in python to pass arguments by using command prompt in windows 2000 and XP ? for example: sourceCode.py factorial 4 gives me the factorial of 4 namely 24. best regards From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 5 15:43:12 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 5 Jul 2005 21:43:12 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120590707.093007.175330@o13g2000cwo.googlegroups.com> <11cloakd4glsbef@corp.supernews.com> Message-ID: Grant Edwards enlightened us with: > It sounds like you ran a computer user training department. I don't > think it could be called computer science. Being a computer science student at the University of Amsterdam, I can tell you that it definitely should not be called "computer science". > I can't believe that anybody with any computer science background > doesn't know it. I agree. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From siyer at Princeton.EDU Wed Jul 13 16:18:01 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Wed, 13 Jul 2005 16:18:01 -0400 Subject: loop problem Message-ID: An HTML attachment was scrubbed... URL: From lordverminard at gmail.com Thu Jul 28 01:03:03 2005 From: lordverminard at gmail.com (mustafa) Date: Thu, 28 Jul 2005 10:03:03 +0500 Subject: Are you interested in Saving money on projects? In-Reply-To: <1122503203.463684.312230@g49g2000cwa.googlegroups.com> References: <1122503203.463684.312230@g49g2000cwa.googlegroups.com> Message-ID: globalbid wrote: > Hi, > > I have a website www.FreelancingProject.com and I would like to invite > freelancer, programmer's or web designer's to sign up and receive a > nice sign up bonus! > > Our goal is to connect professional freelancers to webmasters providing > both freelancers and webmasters the opportunity to > expand their business and reduce their costs. Feel free to post a > project for bidding or bid on current open projects. You can't bet our > fee's, they are the lowest on the web! > > Thanks and have a great day, > Sacha > does one need specific qualifications. From cjw at sympatico.ca Sun Jul 3 13:10:45 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 03 Jul 2005 13:10:45 -0400 Subject: how to retrive highlighted text in a browser? In-Reply-To: <1120379718.126989.223300@g14g2000cwa.googlegroups.com> References: <1120379718.126989.223300@g14g2000cwa.googlegroups.com> Message-ID: wcc wrote: > Hello group, > > When browsing websites, quite often I have to look up words in > dictionary. I'm hoping that I can come up with a python program that > does the following: > > When I highlight some text in browser and right-click, besides the > default options such as COPY, PASTE, etc, I want an option that says > "Send to file", something like that. The file is a text file, with > fixed path. When I select this option, the highlighted text will be > appended to the text file. This way, I can collect those words & > phrases that I don't know. > > Is this going to be a difficult task? I'm a newbie in python. TIA for > your help. > > - wcc > Firefox doesn't provide the file capture function you seek but, using a readily available extension, does permit dictionary lookup using the American Heritage Dictionary - the response comes with copious advertising which is not overly intrusive. Colin W. From pkarjala at paju.oulu.fi Fri Jul 1 13:32:29 2005 From: pkarjala at paju.oulu.fi (Pekka Karjalainen) Date: Fri, 1 Jul 2005 17:32:29 +0000 (UTC) Subject: Favorite non-python language trick? References: Message-ID: In article , Joseph Garvin wrote: >I'm curious -- what is everyone's favorite trick from a non-python >language? And -- why isn't it in Python? > Being able to use my native language without a hitch when naming my variables &c. Java allows that because it supports almost any Unicode character in its identifiers. With Python I occasionally have to stop and think: "I can't name it that. What's better?" Not everyone always writes their programs in English. Once you get used to Java's naming possibilities, it's plain annoying to go back, even if it's just a couple of letters that're lacking in my case. -- Pekka Karjalainen - Oulu, Finland From finite.automaton at gmail.com Mon Jul 25 15:30:21 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 25 Jul 2005 12:30:21 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <1122319821.034193.326980@o13g2000cwo.googlegroups.com> I haven't used PyGTK very much, so I can't comment on it. My last impression of GTK-on-Windows was that it wasn't very stable and didn't blend well with the Windows native look and feel, but that was a while ago and it has probably improved a great deal since then. I use wxPython, doing my development on Linux while most of the users are on Windows. The documentation for wxPython is lame (as you pointed out, it requires a lot of translation from C++), however the wxPython demo app is WONDERFUL. It has great usage examples for all of the widgets, along with source code. PyGTK has a similar demo app (which appears to be an exact Python port of gtk-demo). wxPython does seem to have a richer widget set. One of the annoyances with wxPython is that there are many lingering traces of C++, for example the need to have ID numbers all over the place, and the ALL_CAPS_NAMES_FOR_CONSTANTS. Version 2.5 introduced some good pythonic syntax improvements, so make sure you get a recent version, and also make sure that whatever code examples you're learning from use the new syntax for event binding, etc. From danb_83 at yahoo.com Tue Jul 5 15:50:37 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Jul 2005 12:50:37 -0700 Subject: precision problems in base conversion of rational numbers In-Reply-To: References: Message-ID: <1120593037.751600.255420@g49g2000cwa.googlegroups.com> Brian van den Broek wrote: > Hi all, > > I guess it is more of a maths question than a programming one, but it > involves use of the decimal module, so here goes: > > As a self-directed learning exercise I've been working on a script to > convert numbers to arbitrary bases. It aims to take any of whole > numbers (python ints, longs, or Decimals), rational numbers (n / m n, > m whole) and floating points (the best I can do for reals), and > convert them to any base between 2 and 36, to desired precision. ... > I've discovered empirically that I have to set getcontext.prec = 99 or > greater (i.e. x >= 1.2375) to get > 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C > > (I do feel safe in assuming that is the right answer. :-) And you are correct. ~$ repdigits 345/756 17 0.(7CF0CA) (That's from a script I wrote a couple of years ago. For your next self-directed learning exercise, you could get your program to produce that output :-) Anyhow, if you need such precise precision, perhaps you should consider doing an exact calculation, with rational numbers. """Implementation of rational arithmetic.""" from __future__ import division import decimal as _decimal import math as _math def _gcf(a, b): """Returns the greatest common factor of a and b.""" a = abs(a) b = abs(b) while b: a, b = b, a % b return a class Rational(object): """ This class provides an exact representation of rational numbers. All of the standard arithmetic operators are provided. In mixed-type expressions, an int or a long can be converted to a Rational without loss of precision, and will be done as such. Rationals can be implicity (using binary operators) or explicity (using float(x) or x.decimal()) converted to floats or Decimals; this may cause a loss of precision. The reverse conversions can be done without loss of precision, and are performed with the from_exact_float and from_exact_decimal static methods. However, because of rounding error in the original values, this tends to produce "ugly" fractions. "Nicer" conversions to Rational can be made with approx_smallest_denominator or approx_smallest_error. """ def __init__(self, numerator, denominator=1): """Contructs the Rational object for numerator/denominator.""" if not isinstance(numerator, (int, long)): raise TypeError('numerator must have integer type') if not isinstance(denominator, (int, long)): raise TypeError('denominator must have integer type') if not denominator: raise ZeroDivisionError('rational construction') # Store the fraction in reduced form as _n/_d factor = _gcf(numerator, denominator) self._n = numerator // factor self._d = denominator // factor if self._d < 0: self._n = -self._n self._d = -self._d def __repr__(self): if self._d == 1: return "Rational(%d)" % self._n else: return "Rational(%d, %d)" % (self._n, self._d) def __str__(self): if self._d == 1: return str(self._n) else: return "%d/%d" % (self._n, self._d) def __hash__(self): try: return hash(float(self)) except OverflowError: return hash(long(self)) def __float__(self): return self._n / self._d def __int__(self): if self._n < 0: return -int(-self._n // self._d) else: return int(self._n // self._d) def __long__(self): return long(int(self)) def __nonzero__(self): return bool(self._n) def __pos__(self): return self def __neg__(self): return Rational(-self._n, self._d) def __abs__(self): if self._n < 0: return -self else: return self def __add__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d + self._d * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n + self._d * other, self._d) elif isinstance(other, (float, complex)): return float(self) + other elif isinstance(other, _decimal.Decimal): return self.decimal() + other else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d - self._d * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n - self._d * other, self._d) elif isinstance(other, (float, complex)): return float(self) - other elif isinstance(other, _decimal.Decimal): return self.decimal() - other else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, long)): return Rational(other * self._d - self._n, self._d) elif isinstance(other, (float, complex)): return other - float(self) elif isinstance(other, _decimal.Decimal): return other - self.decimal() else: return NotImplemented def __mul__(self, other): if isinstance(other, Rational): return Rational(self._n * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n * other, self._d) elif isinstance(other, (float, complex)): return float(self) * other elif isinstance(other, _decimal.Decimal): return self.decimal() * other else: return NotImplemented __rmul__ = __mul__ def __truediv__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d, self._d * other._n) elif isinstance(other, (int, long)): return Rational(self._n, self._d * other) elif isinstance(other, (float, complex)): return float(self) / other elif isinstance(other, _decimal.Decimal): return self.decimal() / other else: return NotImplemented __div__ = __truediv__ def __rtruediv__(self, other): if isinstance(other, (int, long)): return Rational(other * self._d, self._n) elif isinstance(other, (float, complex)): return other / float(self) elif isinstance(other, _decimal.Decimal): return other / self.decimal() else: return NotImplemented __rdiv__ = __rtruediv__ def __floordiv__(self, other): truediv = self / other if isinstance(truediv, Rational): return truediv._n // truediv._d else: return truediv // 1 def __rfloordiv__(self, other): return (other / self) // 1 def __mod__(self, other): return self - self // other * other def __rmod__(self, other): return other - other // self * self def __divmod__(self, other): return self // other, self % other def __cmp__(self, other): if other == 0: return cmp(self._n, 0) else: return cmp(self - other, 0) def __pow__(self, other): if isinstance(other, (int, long)): if other < 0: return Rational(self._d ** -other, self._n ** -other) else: return Rational(self._n ** other, self._d ** other) else: return float(self) ** other def __rpow__(self, other): return other ** float(self) def decimal(self): """Return a Decimal approximation of self in the current context.""" return _decimal.Decimal(self._n) / _decimal.Decimal(self._d) def round(self, denominator): """Return self rounded to nearest multiple of 1/denominator.""" int_part, frac_part = divmod(self * denominator, 1) round_direction = cmp(frac_part * 2, 1) if round_direction == 0: numerator = int_part + (int_part & 1) # round to even elif round_direction < 0: numerator = int_part else: numerator = int_part + 1 return Rational(numerator, denominator) @staticmethod def from_exact_float(x): """Returns the exact Rational equivalent of x.""" mantissa, exponent = _math.frexp(x) mantissa = int(mantissa * 2 ** 53) exponent -= 53 if exponent < 0: return Rational(mantissa, 2 ** (-exponent)) else: return Rational(mantissa * 2 ** exponent) @staticmethod def from_exact_decimal(x): """Returns the exact Rational equivalent of x.""" sign, mantissa, exponent = x.as_tuple() sign = (1, -1)[sign] mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) if exponent < 0: return Rational(mantissa, 10 ** (-exponent)) else: return Rational(mantissa * 10 ** exponent) @staticmethod def approx_smallest_denominator(x, tolerance): """ Returns a Rational approximation of x. Minimizes the denominator given a constraint on the error. x = the float or Decimal value to convert tolerance = maximum absolute error allowed, must be of the same type as x """ tolerance = abs(tolerance) n = 1 while True: m = int(round(x * n)) result = Rational(m, n) if abs(result - x) < tolerance: return result n += 1 @staticmethod def approx_smallest_error(x, maxDenominator): """ Returns a Rational approximation of x. Minimizes the error given a constraint on the denominator. x = the float or Decimal value to convert maxDenominator = maximum denominator allowed """ result = None minError = x for n in xrange(1, maxDenominator + 1): m = int(round(x * n)) r = Rational(m, n) error = abs(r - x) if error == 0: return r elif error < minError: result = r minError = error return result def divide(x, y): """Same as x/y, but returns a Rational if both are ints.""" if isinstance(x, (int, long)) and isinstance(y, (int, long)): return Rational(x, y) else: return x / y From francois.perche at gmail.com Mon Jul 11 05:20:47 2005 From: francois.perche at gmail.com (perchef) Date: 11 Jul 2005 02:20:47 -0700 Subject: ZipFile and file rigths In-Reply-To: References: <1120990248.439897.100240@f14g2000cwb.googlegroups.com> <1121034112.762673.31530@z14g2000cwz.googlegroups.com> Message-ID: <1121073647.328490.302020@f14g2000cwb.googlegroups.com> > OTOH, I don't know if this has any relevance to the problem that you are seeing. not really, i have used the 'os.chmod' trick, but it's still interesting. thanks. From jan.danielsson at gmail.com Mon Jul 25 10:04:17 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Mon, 25 Jul 2005 16:04:17 +0200 Subject: First app, thanks people Message-ID: <42e4eff3$1@griseus.its.uu.se> Hello all, I have written my first Python application (apart from small test programs). It's a (distibuted) white board application. I'm going to assume that there already are a thousand of them, written in Python, but just in case someone would find it useful: http://user.it.uu.se/~jada3673/applications.php Direct link: http://user.it.uu.se/~jada3673/apps/whiteboard.py Since I'm a Python beginner, the code is very suboptimal. Anyway, I believe it may be good reference code for beginners. Oh, I do have one more question though. I'm using wxPython, and when I check for keys I use the evt.GetKeyCode() call, and compare it with integers which I have found by printing what event.GetKeyCode() returns. I would prefer a more portable way, since I assume that F1 doesn't have the same code on a Sparc Ultra10. (?) Is there a way to get "key codes" in wxPython in a portable manner? I'd also like to thank all of those who have helped me in this group, and thank everyone else for the interresting discussions. As for license: Do whatever you want with it, but don't blame me if it breaks anything or causes spontaneous pain, death or pregnancies. From python at rcn.com Wed Jul 13 09:57:19 2005 From: python at rcn.com (Raymond Hettinger) Date: 13 Jul 2005 06:57:19 -0700 Subject: breaking out of nested loop References: Message-ID: <1121263039.515161.79160@f14g2000cwb.googlegroups.com> [rbt] > What is the appropriate way to break out of this while loop if the for > loop finds a match? > > while 1: > for x in xrange(len(group)): > try: > mix = random.sample(group, x) > make_string = ''.join(mix) > n = md5.new(make_string) > match = n.hexdigest() > if match == target: > print "Collision!!!" > print make_string > Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime()) > print "Stop", Stop > break > else: > continue > except Exception, e: > print e I would wrap the whole thing in a function definition. When you find a match, just return from the function. Besides cleanly exiting from multiple loops, the function approach usually leads to better factoring (in this case, segregating the search logic from everything else). Raymond From news4mat at gmx.de Wed Jul 6 16:34:09 2005 From: news4mat at gmx.de (Matthias R.) Date: Wed, 06 Jul 2005 22:34:09 +0200 Subject: Scipy - Latex Annotations in plots References: Message-ID: Unfortunately matplotlib is only a 2D-plotting library. Do you know another one with 3D-capabilities as well? That would be very nice, thank you, Matthias Robert Kern wrote: > fortuneteller wrote: >> Hello, >> >> I'm quite new to python and Scipy. >> Anyway I want to use it to plot graphs. >> Does anybody know if there is the possibility to use Latex in SciPy's >> plotting functions like gplt? > > I don't believe so. matplotlib, however, does have this functionality in > recent releases. > From skilpat at gmail.com Wed Jul 27 17:59:49 2005 From: skilpat at gmail.com (Scott Kilpatrick) Date: 27 Jul 2005 14:59:49 -0700 Subject: SciPy and NetCDF References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> <1122499062.943121.65200@z14g2000cwz.googlegroups.com> Message-ID: <1122501589.494602.141620@o13g2000cwo.googlegroups.com> Oh ok, so if my sysadmin installs SciPy, then to get the netCDF support we need he just needs to then install pycdf? I really appreciate the help. Scott From pydecker at gmail.com Sun Jul 3 15:21:06 2005 From: pydecker at gmail.com (Peter Decker) Date: Sun, 3 Jul 2005 15:21:06 -0400 Subject: Accepted Summer of Code proposals In-Reply-To: <68e6a54a005f51ae50ada6932ea22d09@wolke7.net> References: <68e6a54a005f51ae50ada6932ea22d09@wolke7.net> Message-ID: On 7/2/05, Reinhold Birkenfeld wrote: > A.M. Kuchling wrote: > > For anyone who's interested: the Python wiki now contains a list of the > > PSF-mentored proposals that were accepted for Google's Summer of Code: > > http://wiki.python.org/moin/SummerOfCode > > Is it right that two Wax proposals were accepted? Or that Wax is being promoted over Dabo, which wraps wxPython just as elegantly in its UI tier, and which is further along (more controls supported) than Wax, is more powerful (data binding is built in), and is still being actively developed? I looked at Wax, but it seems to be at best a side project to Hans, with no goal in sight. Dabo blew me away with just how easy it is to create UI apps without all that C++ cruft that wxPython inherits from wxWidgets. # p.d. From bokr at oz.net Thu Jul 7 13:07:31 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 07 Jul 2005 17:07:31 GMT Subject: method for Exception base class to raise the exception in an expression? Message-ID: <42cd6090.48331436@news.oz.net> Sometimes it could be handy, e.g., cutting short iteration: >>> def raisex(self, *args): ... raise self.__class__(self, *args) ... >>> Exception.raisex = raisex >>> list(i for i in xrange(20) if i<10 or StopIteration().raisex()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(i for i in xrange(20) if i<15 or StopIteration().raisex()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> list(i for i in xrange(20) if i<25 or StopIteration().raisex()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] a class method could be nicer once we have Exception as a new-style class. Just a thought. Regards, Bengt Richter From peter at engcorp.com Thu Jul 28 21:54:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Jul 2005 21:54:10 -0400 Subject: Adding code and methods to a class dynamically In-Reply-To: References: Message-ID: Sarir Khamsi wrote: > Thanks, this is amazingly more simple than what I had. This works > fine but I'm looking at the code for cmd and don't really see how you > get completion to work on the new alias. I'm not sure what "completion" means in this case, and I'm not aware of any "command-line completion" support in cmd.Cmd though it may well be there, so I can't say. Certainly there is nothing in any way different about the new attribute created by the alias code, as both it and the original attribute are bound to exactly the same method. > Also, I would like the alias to have arguments: > alias newName existingName arg1 arg2 ... > > Currying comes to mind, but I haven't tried it yet. Thanks again for > the help. It sounds like currying, but I'd suggest implementing such a thing with a completely separate layer on top of the existing Cmd stuff, probably through overriding .default() and doing a lookup in a dictionary, then building a command line with the original command and maybe executing it with .onecmd() if that can work from within the .cmdloop(). Lots of possibilities there; haven't tried any myself. -Peter From jeremy at emperorlinux.com Wed Jul 27 00:17:52 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Wed, 27 Jul 2005 00:17:52 -0400 Subject: multiple inheritance super() In-Reply-To: <20050727071412.GA13681@mrna.tn.nic.in> References: <20050727071412.GA13681@mrna.tn.nic.in> Message-ID: <1122437872.12498.1.camel@localhost.localdomain> Thought I'm not sure (and don't have time to test) I'd guess it's because you haven't explicitly called the __init__ method chain. i.e., B calls A, C calls B, etc. This is probably where the actual data gets pulled into scope. On Wed, 2005-07-27 at 12:44 +0530, km wrote: > Hi all, > > In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? > > thanks in advance for enlightment ... > > here's the snippet > > #!/usr/bin/python > > class A(object): > def __init__(self): > self.a = 1 > > class B(object): > def __init__(self): > self.b = 2 > > class C(object): > def __init__(self): > self.c = 3 > > class D(B, A, C): > def __init__(self): > self.d = 4 > super(D, self).__init__() > > if __name__ == '__main__': > x = D() > print x.a # errs with - AttributeError > From Scott.Daniels at Acm.Org Wed Jul 13 20:32:53 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 13 Jul 2005 17:32:53 -0700 Subject: Date & time in a Zip File In-Reply-To: References: Message-ID: <42d5aaba$1@nntp0.pdx.net> Tim Williams (gmail) wrote: > Using zipfile.Zipfile > > How can I add a file to a zip file and keep its date and time correct? > Currently the date/time change to the time the file was added to the > zip. Zipinfo doesn't have a write method! > > Solutions other than zipfile are welcome, with snippets if possible :) > I am working some new code for zipfile. If you are interested in a partial step towards what you want, at the cost of having to read and/or use a bunch of half-done code, grab a copy of: http://members.dsl-only.net/~daniels/zipf.py You should then be able to do something like: import zipf z = zipf.ZipFile('whatever.zip', 'a') and then copy the code for .write(...) using your own zinfo block. I imagine I'll eventually have a method like that named ".write_info(zinfo, data_iterator)" or something. --Scott David Daniels Scott.Daniels at Acm.Org From rkern at ucsd.edu Sun Jul 10 18:53:22 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 10 Jul 2005 15:53:22 -0700 Subject: computer algebra packages In-Reply-To: <42d1a333.327534629@news.oz.net> References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> <42d1a333.327534629@news.oz.net> Message-ID: Bengt Richter wrote: > Then googling for mascsyma [sic ;-)] got I doubt it. ;-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From secun at yahoo.com Mon Jul 11 21:48:06 2005 From: secun at yahoo.com (ChrisH) Date: Tue, 12 Jul 2005 01:48:06 GMT Subject: Help with report References: <11d5scbb63afhee@corp.supernews.com> Message-ID: I should have been more specific. The report needs to be presentable to my users and needs to have rich text type properties (multiple colors, tables, etc) Therefore, I would like to use html if possible. I didn't know if there was already a report writing type of utility already built using python, so I won't have to reinvent the wheel. Oh. The one other thing I forgot to mention is that the data needs to be already updated every 10 minutes or so automatically. In article <11d5scbb63afhee at corp.supernews.com>, grante at visi.com says... > On 2005-07-11, ChrisH wrote: > > I have some data in the following format: > > > > Fred Flintstone,445553454,47634565 > > Wilma Flintstone,74857346,27576847 > > Barney Rubble,73487346,27576435 > > > > I need to convert this data into a report with the user's name and > > difference between the 2 numbers. > > > > Can someone recommend a good way to do this? > > > > BTW, it would be best if I can have it up and running by tomorrow. > > You really oughtn't put off homework assignments until the last > minute. Especially if you don't know how to do them. > > > Also, html would be the preferred format, but not required. > > > > Any help would be greatly appreciated!! > > Hints: > > The string object's "split" method: http://docs.python.org/lib/string-methods.html > > for line in file('inputfile.txt','r') > > the built-in int() > > the string formatting operator "%": http://docs.python.org/lib/typesseq-strings.html > > From peter at engcorp.com Sat Jul 30 13:50:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 13:50:19 -0400 Subject: 2-player game, client and server at localhost In-Reply-To: References: Message-ID: Michael Rybak wrote: > I'm writing a 2-players game that should support network mode. I'm now > testing it on 1 PC since I don't have 2. I directly use sockets, and > both client and server do computations, the only data transfered is > user mouse/kbd input. > > It works synchronously, but somehow, when I play in client window, > both client and server have 17 fps, while when playing in server > window, server has 44 fps while client has 5, and due to forced > synchronization, they both run very slowly (I wonder how come server > says it has 44fps?). > > Does anybody have an idea how can this be? I'd suggest not spending time profiling, debugging, optimizing a "home-brewed" implementation using sockets but switch to Twisted or Pyro or something like that and save yourself a lot of headaches. Chances are this will magically speed things up to acceptable levels, too. -Peter From gsakkis at rutgers.edu Tue Jul 5 09:44:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jul 2005 06:44:08 -0700 Subject: what is __init__.py used for? References: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> <11ckscdmaucfe81@news.supernews.com> Message-ID: <1120571048.498689.170770@o13g2000cwo.googlegroups.com> "John Roth" wrote: > The other is as the module itself. Let's take a simple > example. Assume you have a directory named breakfast > which contains modules named spam.py, eggs.py, > toast.py and jam.py, and that the directory containing > breakfast is on the PYTHONPATH. > > If it try to import spam.py by writing > > import breakfast.spam > > it won't work because the breakfast directory > doesn't contain an __init__.py file. > > If I then add __init__.py to the breakfast directory, > the import will work, and the result will be *two* > modules loaded. The first module will be bound to > the identifier 'breakfast' in your module. It will be > completely empty except for the identifier 'spam' > which will have the spam module bound to it. There is also an alternative form of import that does not load the intermediate modules (actually packages), only the last one: >>> import breakfast.spam as spam Here you can refer to names defined in breakfast.spam as spam.eat(), spam.slice, etc. However you can't refer to breakfast; if you do, you'll get a NameError exception: >>> import breakfast.spam as spam >>> breakfast.spam NameError: name 'breakfast' is not defined In either form of import though, the __init__.py has to be in the breakfast directory. HTH, George From grig.gheorghiu at gmail.com Thu Jul 14 17:55:07 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 14 Jul 2005 14:55:07 -0700 Subject: Native ODBC access for python on linux? References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> <1121372103.895623.319920@g14g2000cwa.googlegroups.com> Message-ID: <1121378107.586643.206440@g49g2000cwa.googlegroups.com> 1. Download and install MySQL-python from 2. Try to connect to a MySQL database that you have running. In this example I'm connecting to the bugs database installed with Bugzilla, and I'm connecting as MySQL user root (not recommended for 'production' code): # python Python 2.4 (#1, Nov 30 2004, 16:42:53) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> from pprint import pprint >>> conn = MySQLdb.connect(db='bugs', user='root', passwd='***') >>> cursor = conn.cursor() >>> cursor.execute('select * from groups') 7L >>> data = cursor.fetchall() >>> print data ((1L, 'tweakparams', 'Can tweak operating parameters', 0, '', 1), (2L, 'editusers', 'Can edit or disable users', 0, '', 1), (4L, 'creategroups', 'Can create and destroy groups.', 0, '', 1), (8L, 'editcomponents', 'Can create, destroy, and edit components.', 0, '', 1), (16L, 'editkeywords', 'Can create, destroy, and edit keywords.', 0, '', 1), (32L, 'editbugs', 'Can edit all aspects of any bug.', 0, '.*', 1), (64L, 'canconfirm', 'Can confirm a bug.', 0, '.*', 1)) >>> pprint(data) ((1L, 'tweakparams', 'Can tweak operating parameters', 0, '', 1), (2L, 'editusers', 'Can edit or disable users', 0, '', 1), (4L, 'creategroups', 'Can create and destroy groups.', 0, '', 1), (8L, 'editcomponents', 'Can create, destroy, and edit components.', 0, '', 1), (16L, 'editkeywords', 'Can create, destroy, and edit keywords.', 0, '', 1), (32L, 'editbugs', 'Can edit all aspects of any bug.', 0, '.*', 1), (64L, 'canconfirm', 'Can confirm a bug.', 0, '.*', 1)) >>> For more info on how to use the MySQLdb module, see the docs at Hope this helps, Grig From xxxx at xxxx.com Tue Jul 26 05:03:02 2005 From: xxxx at xxxx.com (PiBi) Date: Tue, 26 Jul 2005 11:03:02 +0200 Subject: embedding and import problem Message-ID: hi, i try to embed some python code in C, namely: ---------------------------- import zlib def fun(s): return zlib.compress(s) ---------------------------- and execute it by PyRunString() and finally call my function by PyObject_CallFunction() my question is why i receive error like 'zlib not found' but when i run PyRun_SimpleString("import zlib"); before calling PyObject_CallFunction() everything is OK? peter From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 11 11:56:18 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 11 Jul 2005 17:56:18 +0200 Subject: regular expression questions in Python In-Reply-To: References: Message-ID: <3jfj52Fp1tigU1@individual.net> Jeremy wrote: > I am (very) new top regular expressions and I am having a difficult time > understanding how to do them. I have the following in my script: > > zaidsearch = r'''^ {5,}([\d]{4,5})(.\d{2,2}c)''' > ZAIDSearch = re.compile(search, re.IGNORECASE) > > When I do: ZAID.search(...) then this works fine. I would like to write > it as: > > zaidsearch = r'''^ {5,}([\d]{4,5}) #My comments ^ This space will not be a space in the RE. You have to specify a space with '[ ]' or '\ ' when using re.VERBOSE > (.\d{2,2}c) #More of my comments''' > ZAIDSearch = re.compile(zaidsearch, re.VERBOSE) > > but this doesn't work. I get the following error: > > raise error, v # invalid expression > sre_constants.error: nothing to repeat Reinhold From spam.csubich+block at block.subich.spam.com Tue Jul 5 14:25:34 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 05 Jul 2005 14:25:34 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> References: <1120234438.121849.237450@g47g2000cwa.googlegroups.com> <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: mcherm at gmail.com wrote: > concept quickly familiar. But "lambda" has a very clear meaning... it's > a letter of the greek alphabet. The connection between that letter and > anonymous functions is tenuous at best, and fails the test of making > Python read like "executable pseudocode". But 'lambda' does have a very clear meaning in the realm of functional programming, and it means precisely (mostly) what it means in Python: an anonymous function. It might not be the -best- possible name, but anyone who's had a computer science education should have had a class that introduced basic functional programming topics (even if only for academic interest), and so they should be familiar with the keyword name. If not, then it's just a magic word. Kind of like 'def'. From bronger at physik.rwth-aachen.de Sun Jul 31 17:46:22 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 23:46:22 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <861x5ehk4g.fsf@bhuda.mired.org> Message-ID: <87iryqzm1d.fsf@wilson.rwth-aachen.de> Hall?chen! Cliff Wells writes: > [...] > > Well, I think this exposes one of the more interesting sides of > open source software in general. For better or worse, you get > choices. If you don't like choice, you won't like open source. On the other hand, the GUI package bundled with Python is a regular decision of some sort of committee. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From tdwdotnet at gmail.com Wed Jul 13 19:17:43 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Thu, 14 Jul 2005 00:17:43 +0100 Subject: Date & time in a Zip File Message-ID: <9afea2ac050713161778fbaadb@mail.gmail.com> Using zipfile.Zipfile How can I add a file to a zip file and keep its date and time correct? Currently the date/time change to the time the file was added to the zip. Zipinfo doesn't have a write method! Solutions other than zipfile are welcome, with snippets if possible :) ginmf in this instance. From fraca7 at free.fr Thu Jul 21 07:37:09 2005 From: fraca7 at free.fr (fraca7) Date: Thu, 21 Jul 2005 13:37:09 +0200 Subject: gdb python C API In-Reply-To: References: <42df7bfa$0$4724$636a15ce@news.free.fr> Message-ID: <42df88e6$0$23541$626a14ce@news.free.fr> skip at pobox.com a ?crit : > Actually, take a look in the distribution at Misc/gdbinit. In particular, > check out the pystack command. Wow, nice! This will be put to good use, thanks :) From scrimp212 at yahoo.com Fri Jul 22 10:59:42 2005 From: scrimp212 at yahoo.com (scrimp) Date: 22 Jul 2005 07:59:42 -0700 Subject: is this possible? In-Reply-To: References: <1122038817.048490.76560@g47g2000cwa.googlegroups.com> Message-ID: <1122044382.956382.287310@g47g2000cwa.googlegroups.com> I am using reportlab not to generate PDF files, but I want to be able to print them without having to install acrobat reader. I looked through the users guide and found nothing about printing to a printer (programmatically). I want to be able to automate the printing of reports when they are available. Does anyone know how this is done using reportlab? thanks! From benji at benjiyork.com Tue Jul 5 10:34:23 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 05 Jul 2005 10:34:23 -0400 Subject: Python exception hook simple example needed In-Reply-To: <42CA9430.7090307@anonym.hu> References: <42CA9430.7090307@anonym.hu> Message-ID: <42CA9A6F.6070008@benjiyork.com> fowlertrainer at anonym.hu wrote: > If anyone has an idea, how to I catch exceptions globally, please write me. I believe there is an example of this in the demo that comes with wxPython (don't have an install handy to check). -- Benji York From max at alcyone.com Sat Jul 30 00:35:35 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 29 Jul 2005 21:35:35 -0700 Subject: Selection, picking with PyOpenGL? Message-ID: I was interesting in adding selection and hit testing to ZOE, and was looking at the PyOpenGL wrappers' handling of selection and picking. I see glSelectBuffer to specify the size of the buffer, and glRenderMode properly returns the number of hits when put back into GL_RENDER mode, but I don't see any way within PyOpenGL itself to access the select buffer to actually process the hits. Is there any way to do this without using OpenGLContext? (If not, does this make sense, given that OpenGLContext is supposed to be an additional helper library for a gentle introduction to OpenGL?) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I will always remember / This moment -- Sade From roy at panix.com Sun Jul 3 15:38:31 2005 From: roy at panix.com (Roy Smith) Date: Sun, 03 Jul 2005 15:38:31 -0400 Subject: need to get an index for an item in a list References: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> Message-ID: In article , Peter Hansen wrote: > nephish at xit.net wrote: > > i need to be able to get the index for an item in a list. > > > any ideas? > > Fire up the interactive interpreter and learn to use it to help > yourself. In this case, the most useful thing might be to know about > the dir() builtin method, which you can use on a list like so: > > dir([]) > > Note in the output the presence of the "index" method... I'll leave it > up to you to read the docs to learn more about how to use it, or you can > just experiment at the prompt to see how it works. > > -Peter I certainly agree that dir() is a very handy tool to know about, and that poking around with it in the interactive interpreter is a great way to learn what's possible. That being said, index() isn't isn't going to work if there are duplicate lines in the file; it'll return the index of the first one. From martin at v.loewis.de Sun Jul 10 18:40:41 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Jul 2005 00:40:41 +0200 Subject: Codecs In-Reply-To: References: Message-ID: <42D1A3E9.8020800@v.loewis.de> Ivan Van Laningham wrote: > Hi All-- > As far as I can tell, after looking only at the documentation (and not > searching peps etc.), you cannot query the codecs to give you a list of > registered codecs, or a list of possible codecs it could retrieve for > you if you knew enough to ask for them by name. > > Why not? There are several answers to that question. Which of them is true, I don't know. In order of likelyhood: 1. When the API was designed, that functionality was forgotten. It was not possible to add it later on (because of 2) 2. Registration builds on the notion of lookup functions. The lookup function gets a codec name, and either succeeds in finding the codec, or raises an exception. Now, a lookup function, in principle, might not "know" in advance what codecs it supports, or the number of encoding it supports might not be finite. So asking such a lookup function for the complete list of codecs might not be implementable. As an example of a lookup function that doesn't know what encodings it supports, look at my iconv module. This module provides all codecs that iconv_open(3) supports, yet there is no standard way to query the iconv library in advance for a list of all supported codecs. As an example for a lookup function that supports an infinite number of codecs, consider the (theoretical) encrypt/password encoding, which encrypts a string with a password, and the password is part of the codec name. Each password defines a new encoding, and there is an infinite number of them. Now, if 1) would have been considered, it might have been possible to design the API in a way that didn't support all cases that the current API supports. Alas, somebody must have misplaced the time machine. Regards, Martin From python at rcn.com Sun Jul 17 22:38:29 2005 From: python at rcn.com (Raymond Hettinger) Date: 17 Jul 2005 19:38:29 -0700 Subject: Efficiently Split A List of Tuples References: Message-ID: <1121654309.453199.112300@f14g2000cwb.googlegroups.com> [Richard] > I know I can use a 'for' loop and create two new lists > using 'newList1.append(x)', etc. Is there an efficient way > to create these two new lists without using a slow for loop? If trying to optimize before writing and timing code, then at least validate your assumptions. In Python, for-loops are blazingly fast. They are almost never the bottleneck. Python is not Matlab -- "vectorizing" for-loops only pays-off when a high-speed functional happens to exactly match you needs (in this case, zip() happens to be a good fit). Even when a functional offers a speed-up, much of the gain is likely due to implementation specific optimizations which allocate result lists all at once rather than building them one at time. Also, for all but the most simple inner-loop operations, the for-loop overhead almost always dominated by the time to execute the operation itself. Executive summary: Python's for-loops are both elegant and fast. It is a mistake to habitually avoid them. Raymond From jaymail at gawab.com Fri Jul 29 13:50:49 2005 From: jaymail at gawab.com (Jay) Date: 29 Jul 2005 10:50:49 -0700 Subject: writing a web client In-Reply-To: <1122642828.810852.146650@g14g2000cwa.googlegroups.com> References: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> <1122642828.810852.146650@g14g2000cwa.googlegroups.com> Message-ID: <1122659449.383415.296790@g44g2000cwa.googlegroups.com> thats pretty cool, could someone post a example program of a python web-based program? From grante at visi.com Tue Jul 5 15:29:45 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Jul 2005 19:29:45 -0000 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Message-ID: <11clnt9mbl3boa3@corp.supernews.com> On 2005-07-05, Peter Hansen wrote: > Tom Anderson wrote: >> +1 insight of the century. This is the heart of the unix way - lots of >> simple little programs that do exactly one thing well, and can be >> composed through simple, clean interfaces. For actually getting things >> done, a toolkit beats a swiss army knife. > > Perhaps, but I'm puzzled how that explanation would apply to emacs and > those who use it as a swiss army knife, doing everything from editing to > email to laundry in the same editor... It doesn't. Emacs doesn't follow the Unix way. > (Note: this isn't a flame about emacs, nor vi for that matter, > just a discussion about the apparent conflict in the two > philosophies embodied by the "simple little programs" and the > "emacs" approaches.) Who said there wasn't a conflict? -- Grant Edwards grante Yow! Xerox your lunch at and file it under "sex visi.com offenders"! From peter at engcorp.com Sun Jul 3 21:28:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 21:28:06 -0400 Subject: looping over a big file In-Reply-To: References: <11cgnhp3j4th442@corp.supernews.com> <86ekaf1pqv.fsf@bhuda.mired.org> Message-ID: Michael Hoffman wrote: > Mike Meyer wrote: >> Guido has made a pronouncement on open vs. file. I think he prefers >> open for opening files, and file for type testing, but may well be >> wrong. I don't think it's critical. > > He has said that open() may be used for things other than files in the > future. So if you want to be sure you're opening a file, use file(). Probably this is the same sort of things as "if you want to be sure your function is working with an integer, you have to test whether it is an integer" (or use a statically typed language). Which is advice that is generally rebutted around here with comments about "duck typing" (as in, if it acts like an integer, then stop worrying about what it actually is). If open() can ever return things other than files, it seems likely it will do so only under conditions that make it pretty much safe to assume that existing code will continue to operate "as expected" (note: not "always with a file"). I'm not going to try to picture just how this might happen, but I could imagine, for example, some kind of support for protocol prefixes (ala "http:" or "ftp:"), or perhaps some sort of support for encrypted or compressed data. Or maybe it would require a prior call to some function to enable the magic that lets open() return non-files. If any of that is reasonable, then using open() is actually the better approach to ensuring your code "does the right thing" in the future, and "file" should still be used in the rare case where you actually want to test whether something is a particular type of thing. -Peter From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 03:52:14 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 09:52:14 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: TPJ enlightened us with: > I'd like to choose PyGTK (because of its rich documentation), but > I'm not sure if PyGTK is stable on Windows... For now I know that > wxPython runs well on Windows. Don't forget that wxPython looks like Mac on a Mac. That's important too :) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From google at spiceaid.com Fri Jul 22 17:07:18 2005 From: google at spiceaid.com (Dr. Who) Date: 22 Jul 2005 14:07:18 -0700 Subject: Something that Perl can do that Python can't? In-Reply-To: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> References: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> Message-ID: <1122066437.870669.58990@z14g2000cwz.googlegroups.com> Well, I finally managed to solve it myself by looking at some code. The solution in Python is a little non-intuitive but this is how to get it: while 1: line = stdout.readline() if not line: break print 'LINE:', line, If anyone can do it the more Pythonic way with some sort of iteration over stdout, please let me know. Jeff From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 11 09:37:35 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 11 Jul 2005 15:37:35 +0200 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> <1121059708.002859.67570@g44g2000cwa.googlegroups.com> <3jei85FpehftU1@individual.net> Message-ID: <3jfb10Fpga3qU1@individual.net> Dan Sommers wrote: > Without thinking it all the way through, I suppose these: > > def method_1(self, *self.l): > pass > def method_2(self, **self.d): > pass > > could act as if they were these: > > def method_1(self, *args): > self.l = args > del args > def method_2(self, **kw): > self.d = kw > del kw I still think it's too specialized. What would, hypothetically, this do? class Bar: pass class Foo: x = Bar() def method_1(self, x.y): pass It's hard to explain that you can autoassign self.y but not x.y. Reinhold From steve at REMOVETHIScyber.com.au Sat Jul 30 12:43:22 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 02:43:22 +1000 Subject: Comparison of functions References: <3l1druF10aj5pU1@individual.net> Message-ID: On Sat, 30 Jul 2005 15:32:45 +0200, Reinhold Birkenfeld wrote: >> Um, I didn't ask to compare complex numbers using comparison operators. I >> asked to sort a list. And please don't tell me that that sorting is >> implemented with comparison operators. That just means that the >> implementation is confusing numeric ordering with sort order. > > Sorting is implemented with comparison operators. How should it be otherwise? That's a good question, and that's why I'm exploring different comparisons in Python, trying to understand what Python already does, and the pros and cons thereof, before I suggest anything new. > Would you prefer a __sort__ method to specify sort order? Well, there are an infinite number of sort orders. Most of them are pretty much useless, but even if we limit ourselves to common, useful sort orders, there are still a good half dozen or more. So at this time, I'd rather not be pinned down to some half-baked "solution" before I have even understood the problem. > And how would you sort a list of complex numbers? Answered in another post. >> Then there is this: >> >>>>> 1 > 0 >> True > > Okay. > >>>>> 1+0j == 1 >> True > > Okay. > >>>>> 1+0j == 1 > 0 >> True > > (1+0j == 1) yields True, which is comparable to 0. No, 1+0j == 1 > 0 is calculated as 1+0j == 1 and 1 > 0. >>>>> 1+0j > 0 >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: cannot compare complex numbers using <, <=, >, >= > > But complex numbers are not greater or littler than others. You can't order them, > not on a one-dimensional scale. Of course you can order them. You are confusing order with magnitude. The two are not identical, although they are similar enough in some contexts as to cause confusion. I admit that I haven't fully grasped all the subtleties of the general ordering problem. Fortunately, my needs are much less lofty. -- Steven. From googlinggoogler at hotmail.com Wed Jul 27 17:47:47 2005 From: googlinggoogler at hotmail.com (googlinggoogler at hotmail.com) Date: 27 Jul 2005 14:47:47 -0700 Subject: searching string url In-Reply-To: References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> Message-ID: <1122500867.516196.146990@g14g2000cwa.googlegroups.com> Thanks for the rapid replys, I cracked the problem 15 seconds after posting here, doh! Anyway to the orginally replier - I wish it was homework ;-), that would mean I wouldnt be trying to find myself a job as a recent graduate... I decided to crawl something similar to the yellow pages (do you have them in the US?) for my select area and then find all pages corresponding to my ideal field of work, and grab their details into a txt file. Trouble is I keep thinking of cool new bits to add, python truely is a beautifal language. Ideally would like to somehow write all the information into a word mail merge - but I think that requires more research! Cheers! David From gh at ghaering.de Thu Jul 7 08:03:49 2005 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 7 Jul 2005 14:03:49 +0200 Subject: VC++ linking problem In-Reply-To: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> References: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> Message-ID: <20050707120349.GA32724@mylene.ghaering.de> On Thu, Jul 07, 2005 at 04:52:11AM -0700, J wrote: > Hi everyone, > > I started embedding python into a 3D graphics App and I came > across this linking problem. > > > SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol > __imp__Py_InitModule4TraceRefs > SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol > __imp___Py_RefTotal > SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol > __imp___Py_RefTotal > > I am linking against python24.lib using VC++ 6.0. Before I got to this > point it couldn't find python24_d.lib. After searching around > for a while I came across a solution that included changing > python24_d.lib to python24.lib in one of the header files. I hope that > didn't have a negative effect. I would really appreciate > some help.... It *does* have a negative effect. Python debug and non-debug libraries are not binary compatible, even when otherwise compiled with the same settings. I think that's the reason for the _d suffixes for Python debug binaries on Windows. The solution for you is to compile yourself a debug version of Python for testing your whole app in debug mode. AFAIR in python-dev Python 2.4 can still be compiled with MSVC6, even though the official binaries are built with MSVC 7.1. -- Gerhard -- Gerhard H?ring - gh at ghaering.de - Python, web & database development -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From hancock at anansispaceworks.com Wed Jul 6 02:30:33 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 6 Jul 2005 01:30:33 -0500 Subject: f*cking re module In-Reply-To: <1120575861.296553.303750@z14g2000cwz.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <1120575861.296553.303750@z14g2000cwz.googlegroups.com> Message-ID: <200507060130.33524.hancock@anansispaceworks.com> On Tuesday 05 July 2005 10:04 am, jwaixs wrote: > The python re module is, in my opinion, a non beginner user friendly > module. And it's not meant for beginning python programmers. I don't > have any experience with perl or related script/programming languages > like python. (I prefer to do things in c) So the re module is > completely new for me. I think you had an error of expectations here: Python provides a regular expression module which is consistent with regular expression syntax as it has come to be defined. Your frustration was entirely with regular expressions themselves, not the Python implementation. You would've had the same experience in Perl or Ruby or for that matter, sed or awk. In that vein, the Python documentation for the re module is only that -- documentation for the module. It does not (and couldn't reasonably be expected to) cover the subject of regular expressions themselves. You might as well expect the Python manual to explain "object oriented programming", "data structures", "functional programming" or other semester-long computer science subjects. There are entire books dedicated to the subject of learning regular expressions and pattern recognition in general. It's a fairly complex subject. After all, it's merely the simplest one-dimensional case of a pattern recognition system, which is essentially an AI discipline. Only the fact that the one-dimensional case of discrete text is an extremely simple case makes the subject tenable at all for ordinary programs. If you're really interested in using this new technique, I would suggest that you be prepared to be patient and tackle the problem of learning it seriously, just as you did when you learned to program in C in the first place. And you might want to read one of those aforementioned books, such as: Mastering Regular Expressions (2nd ed) by Jeffrey E. F. Friedl http://www.oreilly.com/catalog/regex2/ And IMHO, Python actually makes regular expressions a lot easier to handle than they are in some of the other languages you could be attempting this in. I've only tried regexes in Python, Perl, and Javascript, but Python is definitely the one I find easiest to cope with. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From iny+news at iki.fi Sun Jul 3 01:36:36 2005 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Sun, 03 Jul 2005 08:36:36 +0300 Subject: PIL question: keeping metadata References: <42c2c4ca$0$8490$dbd41001@news.euronet.nl> <1120070384.278692.11180@g47g2000cwa.googlegroups.com> Message-ID: "Will McCutchen" writes: >> Is there any way of keeping this info in PIL? > > I don't think so... when I investigated in the past, I think I > discovered that the PIL can't write EXIF data (I might be wrong, > though, or my information might be outdated). There is this: http://mail.python.org/pipermail/image-sig/2004-September/002931.html -- Ilpo Nyyss?nen # biny # /* :-) */ From m.linnemann at addcom.de Sun Jul 3 15:41:30 2005 From: m.linnemann at addcom.de (Michael Linnemann) Date: Sun, 3 Jul 2005 21:41:30 +0200 Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> Message-ID: Am Sun, 03 Jul 2005 13:40:04 -0400 schrieb Peter Hansen: > I do all my work using Scite (a nice free editor that was built to > demonstrate the Scintilla plugin that can also be used in Python > programs through things like the StructuredTextControl in wxPython), > with the auto-save-on-loss-of-focus feature enabled, and a command > prompt open in another window. > I edit in the Scite window, hit Alt-Tab (under Windows XP) to change > focus to the cmd console (and instantly all my modified files are > saved), press the Cursor Up key to retrieve the previous command (which > is generally the name of my script, or a command like "python > myscript.py"), and hit Enter to execute it. I do the same thing without a command prompt, just pressing F5. SciTE sure is a good editor :-) Regards Michael -- Imagine being in a coma for a year and the hospital having to reboot your life-support once a week. That would take a lot of the fun out of it. As an aside, if I were on life-support, I'd rather have it run by a Gameboy than a Windows box. -- Cliff Wells, 2002/3/13, in comp.lang.python From __peter__ at web.de Mon Jul 4 15:34:28 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jul 2005 21:34:28 +0200 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> Message-ID: Josiah Manson wrote: > Hello. I am very new to Python, and have been unable to figure out how > to check if a variable exists or not. In the following code I have made try: variable except NameError: # variable doesn't exist else: # variable exists But it is rare that you actually need to do that. > a kludge that works, but I think that it would be clearer to check if > closest exists and not have to initialize it in the first place. How is > that check done? > > The following code finds the closest place to a position and rejects > places that are too far away. > > dist = 1e9 > closest = -1 > > for n,p in galaxy.places.iteritems(): > dif = p.pos - pos > len = dif.len() > if len < dist and len < 10.0/self.zoom: > dist = len > closest = p > > if closest != -1: > self.sel = [closest.name] I prefer to set the variable to the first item in the sequence and later update that when I find "better" matches: if galaxy.places: pos = somewhere() places = galaxy.places.itervalues() closest = places.next() closest_dist = (closest.pos - pos).len() for p in places: dist = (p.pos - pos).len() if dist < closest_dist: closest_dist = dist closest = p if closest_dist < 10.0/self.zoom: self.sel = [closest.name] This is easy to understand but has the disadvantage of some redundant code (the distance between 'pos' and 'some other place' is calculated both before and in the loop. So here is an alternative that uses the min() builtin: def dp(places, pos): for i, p in enumerate(places): yield (p.pos - pos).len(), i, p if galaxy.places: pos = somewhere() dist, _, place = min(dp(galaxy.places.itervalues(), pos)) if dist < 10.0/self.zoom: self.sel = [place.name] > Extending my existance checking question, how does one check what type > a variable has? type(variable) == some_type or better isinstance(variable, some_type) which is also true if variable is an instance of a subclass of some_type. But again, I'd rather avoid that if possible because you can easily prevent a function from working with objects you didn't think of when you wrote it and that implement the same methods and attributes but are of a totally unrelated class (google for "duck type"). Peter From prabapython at yahoo.co.in Fri Jul 29 03:10:33 2005 From: prabapython at yahoo.co.in (praba kar) Date: Fri, 29 Jul 2005 08:10:33 +0100 (BST) Subject: how to append cgi FieldStorage Class instance In-Reply-To: <20050727163522.220b01b2.pedro.werneck@terra.com.br> Message-ID: <20050729071033.67270.qmail@web8410.mail.in.yahoo.com> Dear All, I have doubt in python cgi script. I describe that doubt with below code import cgi form = cgi.FieldStorage() passwd = form['passwd'].value print passwd But Now I want to assign some value to form['passwd'] field value form['passwd'] = 'surese' Now If I try to print print form['passwd'].value. It will raise error. So kinldy let me how to edit or append instance of FieldStorage class regards PRabahar _______________________________________________________ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From bokr at oz.net Tue Jul 26 20:06:14 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 27 Jul 2005 00:06:14 GMT Subject: multiple inheritance super() References: Message-ID: <42e6cbe2.1237217424@news.oz.net> On Wed, 27 Jul 2005 12:44:12 +0530, km wrote: >Hi all, > >In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? > >thanks in advance for enlightment ... > >here's the snippet > >#!/usr/bin/python > >class A(object): > def __init__(self): > self.a = 1 > >class B(object): > def __init__(self): > self.b = 2 > >class C(object): > def __init__(self): > self.c = 3 > >class D(B, A, C): > def __init__(self): > self.d = 4 > super(D, self).__init__() > >if __name__ == '__main__': > x = D() > print x.a # errs with - AttributeError > super(D, self) is going to find __init__ in the first base in the mro where it's defined. So x.b will be defined, but not x.a. I don't know what you are defining, but you could call the __init__ methods of all the base classes by something like (untested) for base in D.mro()[1:]: if '__init__' in vars(base): base.__init__(self) replacing your super line above in class D, but I would be leery of using __init__ methods that way unless I had a really good rationale. Regards, Bengt Richter From peter at engcorp.com Wed Jul 13 18:07:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 18:07:38 -0400 Subject: PY2EXE => Is there a way to go backwards? EXE2PY In-Reply-To: <1121277611.573163.318250@g49g2000cwa.googlegroups.com> References: <1121277611.573163.318250@g49g2000cwa.googlegroups.com> Message-ID: Joe wrote: > I have the executable of a script that I wrote, that has been erased. > Is there any way to retrieve the uncompiled python script from the > executable that was created with py2exe? The .pyc files are in a file called library.zip, and they're pretty easy to extract. To convert .pyc files to .py files, look for "decompyle", which might be up-to-date these days, but is probably still available only as a for-pay online service. Note that it cannot produce a file identical to your source, but it can come pretty close, certainly close enough to save your hide and tide you over until you can learn to use a source code control system (I highly recommend Subversion as both free and effective). ;-) -Peter From jlconlin at lanl.gov Thu Jul 14 19:46:32 2005 From: jlconlin at lanl.gov (Jeremy) Date: Thu, 14 Jul 2005 17:46:32 -0600 Subject: readlines() doesn't read entire file In-Reply-To: References: Message-ID: Peter Hansen wrote: > Jeremy wrote: > >>I have a most aggravating problem. I don't understand what is causing >>readlines() not to read all the lines in the file. I have the following >>syntax: >> > > ... > >> self.xsdir = file(Datapath, 'r') # File object >> >>I can see all the lines in the list self.lines, but they are not all the >>lines in the file. When I look at the file in Vim, I can see all the >>lines, but Python cannot. Can someone help me with this one? > > > What platform? What version of Python? > > You're opening the file in "text" mode. If you are on Windows and the > file actually contains a ^Z (byte 26) it is treated as EOF. Is that the > problem? > > If not, have you tried cutting parts out of the file, to produce the > smallest file that still shows the problem? At that point you will > likely resolve the issue on your own. Also, does the same thing happen > if you use the interactive interpreter to read the file "manually"? > > These are all basic troubleshooting techniques you can use at any time > on any problem... > > -Peter Well, now I have to make a humbling retraction. I realized I wasn't reading the file I thought I was, but one similar to it. Now that I am reading the correct file, I am getting all the lines I expected to. Thanks, Jeremy From ntv1534 at gmail.com Tue Jul 5 19:46:46 2005 From: ntv1534 at gmail.com (MooMaster) Date: 5 Jul 2005 16:46:46 -0700 Subject: multiple checkboxes highlighted when one clicked = not good In-Reply-To: <1120606930.677363.22260@f14g2000cwb.googlegroups.com> References: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> <1120606930.677363.22260@f14g2000cwb.googlegroups.com> Message-ID: <1120607206.622833.175730@g47g2000cwa.googlegroups.com> Uhm....I'm a dunce. Obviously having it only use t[0] is going to make it cleverly look like I'm using different variables, when in fact I'm not. Thanks James! From kwharrigan at yahoo.com Fri Jul 22 09:58:40 2005 From: kwharrigan at yahoo.com (kwharrigan at yahoo.com) Date: 22 Jul 2005 06:58:40 -0700 Subject: time.time() under load between two machines In-Reply-To: References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> Message-ID: <1122040720.010009.80700@g14g2000cwa.googlegroups.com> At least on the order of .1-1 seconds. Both platforms are Windows XP SP2. From steve at REMOVETHIScyber.com.au Tue Jul 12 22:16:03 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 12:16:03 +1000 Subject: if not DEBUG: log = null_log References: Message-ID: On Wed, 13 Jul 2005 11:00:14 +1000, Simon Burton wrote: > Hi, > > I'm after a no-op command, so that i can redirect > logging commands in performance critical code. > > Something like this: > > def log(*args): print args > def null_log(*args): pass > if not DEBUG: log = null_log > > is unacceptable because of the overhead of calling > functions in python. Excuse my skepticism, but I'd like to see the profiling that you did that shows this is a problem. Everybody thinks their code is performance critical, even when it isn't. So, let's do a test. First, I set up a fake object that requires lots of name look-ups: >>> class Placeholder: ... pass ... >>> obj = Placeholder() >>> obj.method = Placeholder() >>> obj.method.attribute = Placeholder() >>> obj.method.attribute.record = None Now I run a test to time those name lookups: >>> def test_func_overhead(n): ... loop = range(n) ... t = time.time() ... for i in loop: ... f = obj.method.attribute.record ... t = time.time() - t ... return t ... >>> test_func_overhead(100000) 0.10761499404907227 >>> test_func_overhead(100000) 0.13230800628662109 >>> test_func_overhead(100000) 0.11942911148071289 Now set up a test bypassing the name lookups: >>> def test_func_no_overhead(n): ... loop = range(n) ... y = obj.method.attribute.record ... t = time.time() ... for i in loop: ... f = y ... t = time.time() - t ... return t ... >>> test_func_no_overhead(100000) 0.052425861358642578 >>> test_func_no_overhead(100000) 0.042248010635375977 >>> test_func_no_overhead(100000) 0.055256843566894531 So four global lookups performed 100,000 times takes 0.1 second, while a single local lookup performed 100,000 times takes 0.05 second. Not a big difference. Extrapolating from four lookups down to one would suggest that global lookups are faster than local, which can't be right. Redoing test_func_overhead to only make one lookup (change the reference to obj.method.attribute.record to just obj) gives very surprising results: >>> test_func_overhead2(100000) 0.041122913360595703 >>> test_func_overhead2(100000) 0.037561893463134766 >>> test_func_overhead2(100000) 0.020340204238891602 According to my testing, looking up a global variable is *faster* than looking up a local. Hmmmm. Caching effects perhaps? Try the local version again: >>> test_func_no_overhead(100000) 0.025532007217407227 >>> test_func_no_overhead(100000) 0.016258001327514648 >>> test_func_no_overhead(100000) 0.016184806823730469 Ah, that's better! At least now the local lookup is slightly faster than the global. But also widely different from the first run. Function lookup is so fast to start with, and affected by so many external factors, that the cost-benefit equation of trying to optimize it is not very good. There almost certainly will be more useful things for you to spend your time on. More comments below:- > log ("about to slip into python feature request mode.") > > Maybe this is what the PEP 336 guy was thinking of (Make None Callable). > Obviously we don't want None to be callable, but > what about a "Null" [1] that's callable, with any args ? > > But I guess what I am really asking for is something on the bytecode > level that tells the VM to "do nothing". > > Here's an idea: make "pass" into an expression (a value) that is callable, > with any args, and returns None. > > log ("finished with python feature request mode.") And how do you use this without the overhead of function calls? Do you sprinkle your code with: if DEBUG: log("spam") else: pass("spam") ? Why not just do this? if DEBUG: log("spam") Which is much simpler. Or even simpler still, put the "if DEBUG" test inside log, since the extra time taken in calling the function is probably lost in the noise of the rest of your code. Not related to the logging issue: > I recently discovered "pyc" [2], but i don't quite see how i can > use it while maintaining python source compatability. [snip] > [2]: http://students.ceid.upatras.gr/~sxanth/pyc/ How fascinating. From the pyc page: "In fact you can use pyc to re-compile your standard library and make it about 100kB smaller." Hmmm. Let's see now, Python 2.3.3 on Fedora Core 2: $ du -hs /usr/lib/python2.3/ 88M /usr/lib/python2.3/ Oh joy! So by using pyc, I can save 0.11% of the Python library storage requirements! For all I know, pyc is a very useful package, and kudos to the author for taking the time and effort to develop it. But if this space saving is "one good reason to use pyc" according to the author, I'm not impressed. -- Steven. From benji at benjiyork.com Mon Jul 25 17:03:33 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 25 Jul 2005 17:03:33 -0400 Subject: Run batch files in Windows XP In-Reply-To: <1122321443.649543.207300@z14g2000cwz.googlegroups.com> References: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> <1122318744.969547.113640@g43g2000cwa.googlegroups.com> <9v2dnYY1NvZtoXjfRVn-ug@powergate.ca> <1122320850.623089.88360@g49g2000cwa.googlegroups.com> <1122321443.649543.207300@z14g2000cwz.googlegroups.com> Message-ID: <42E553A5.3070309@benjiyork.com> Ernesto wrote: > Looks like I'm not getting my parameters to my batch file correctly. > I'm using os.system like this: > os.system('bootmanager.bat %s' %"BOOTMANAGER ALL") > > where 'BOOTMANAGER ALL' is what I type at the command prompt arguments. > That must not be right? The batch file will see two parameters (in %1 and %2) if that's not what you want, put double quotes around the %s, like so: os.system('bootmanager.bat "%s"' % "BOOTMANAGER ALL") -- Benji York From godwinburby at rediffmail.com Tue Jul 12 01:32:16 2005 From: godwinburby at rediffmail.com (godwin) Date: 11 Jul 2005 22:32:16 -0700 Subject: DBSeek Message-ID: <1121146336.289033.44550@z14g2000cwz.googlegroups.com> Hello there, I need some thoughts about a web application that i am dreaming and drooling about in python. I want a search page to look exactly like Google. But when i press the search button, it should search a database in an rdbms like Oracle and provide results. For example, if my keywords are "all customers with names starting with 'God'" it should somehow search table CUSTOMER , with following query : SELECT CUSTNAME FROM CUSTOMER WHERE CUSTNAME LIKE 'God%' So we basically need is a good python parser module which parses the keywords into an sql or sqls and list the results. I can look in the keywords for table and column synonyms and map it into table and column names and create sql but it's not a foolproof idea as we all know that english is a very vague language. The above idea wil fail , if i can't identify table,column names ,operators and values in their logical orders so as to create a syntactically correct sql. If there are more tables involved, i should also think of joining tables (inner,outer,equi joins). All I want is some enlightening thoughts from the python hackers(i mean programmers) out there.Plz polish your grey cells and let me know your thoughts. # this is my basic and foolish keywordparser # the object db provides the table as well as column names # as u can see it may or may not work even for a single table class KeyWordParser(object): def __init__(self,keywords,db): self.keywords = keywords.upper().split() self.db = db self.tables = [] self.columns = [] def parse2sql(self): for word in self.keywords: if word in self.db.tables(): self.tables.append(word) for word in self.keywords: for table in self.tables: for column in self.db.columns(table): if column == word: self.columns.append(column) sql = 'SELECT %s FROM %s' % (','.join(self.columns) or '*',','.join(self.tables)) return sql From thomas at thomas-lotze.de Wed Jul 13 06:56:48 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Wed, 13 Jul 2005 12:56:48 +0200 Subject: Frankenstring References: <42d43047$1@nntp0.pdx.net> <42d48dba.41657380@news.oz.net> Message-ID: Bengt Richter wrote: > ----< lotzefile.py >-------------------------------------------------- Thanks. [...] > byte = self.buf[self.pos] This is the place where the thing is basically a str whose items are accessed as sequence elements. It has some iterator behaviour and file management which makes it nice to use, of course, and to most this will be enough (and it is a lot indeed). But it loses the efficiency of for c in "asdf": do_something(c) Actually, relying on string[index] behind the scenes is one of the ways of implementing frankenstring I labelled "clumsy" in the original posting ;o) > I suspect you could get better performance if you made LotzeFile instances > able to return interators over buffer chunks and get characters from them, > which would be string iterators supplying the characters rather than the > custom .next, but the buffer chunks would have to be of some size to make > that pay. Testing is the only way to find out what the crossing point is, > if you really have to. If I understand this correctly, you'd have to switch to using a new iterator after seeking, which would make this impossible: f = LotzeFile('something') for c in iter(f): do_something(c) if some_condition: f.seek(somewhere) # the next iteration reads from the new position And it would break telling since the class can't know how many characters have been read from an iterator once it returned one after seeking or switching to another buffer chunk. -- Thomas From pythonmailing at web.de Sun Jul 24 15:34:16 2005 From: pythonmailing at web.de (Marek Kubica) Date: Sun, 24 Jul 2005 21:34:16 +0200 Subject: Friend wants to learn python References: <1122135598.347717.75830@g43g2000cwa.googlegroups.com> <1122139442.705347.237010@o13g2000cwo.googlegroups.com> Message-ID: <1tfrtscdzo8ak.1e97qt6sp8zqk$.dlg@40tude.net> Hello, On 23 Jul 2005 10:24:02 -0700 Pietro Campesato wrote: > Maybe diveintopython.org can help I consider diveintopython a little bit to hard for the beginner. I really like this book, it's excellent, great thanks to Mike Pilgrim for providing us the book. I pointed a friend to Python Programming for the Absolute Beginner by Premier Press. He liked it, although I don't know how much Python he had learned yet. Just my 1/50 of a bigger coin in your currency ;) greets, Marek From rex.eastbourne at gmail.com Sat Jul 2 18:41:18 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 2 Jul 2005 15:41:18 -0700 Subject: Running Python interpreter in Emacs In-Reply-To: <42C5E315.1050100@lexicon.net> References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> <1119811726.576282.59500@g49g2000cwa.googlegroups.com> <1120250066.836533.199420@g47g2000cwa.googlegroups.com> <42C5E315.1050100@lexicon.net> Message-ID: <1120344078.574489.70200@g49g2000cwa.googlegroups.com> Yes, I knew that copying it to my root was a kludge. But between that and not having it work, I chose the former. (As you might be able to tell from my posts, I tried multiple things and was frustrated.) I tried putting quotes around "c:\program files\python24". It still didn't work. I chose to install Python in Program Files. I didn't know it would cause any problems; I just thought it was good to have all my programs in the same place. I guess I was wrong. From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 11 02:34:45 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 11 Jul 2005 08:34:45 +0200 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <1121059708.002859.67570@g44g2000cwa.googlegroups.com> References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> <1121059708.002859.67570@g44g2000cwa.googlegroups.com> Message-ID: <3jei85FpehftU1@individual.net> Kay Schluehr wrote: > Dan Sommers schrieb: > >> How about this: >> >> def __init__(self, self.x, y, self.z): >> # self.x, self.z from first and third explicit parameters >> do_something_with_y() > > Can you tell me in which way it is anyhow better than the original > proposal > > def __init__(self, .x, y, .z): > # self.x, self.z from first and third explicit parameters > do_something_with_y() > > besides that it is more verbose? It is more explicit. Explicit is better than implicit. But as with many proposals, this raises consequential questions, for example, how "self.x" parameters are handled in other methods, or even functions, as __init__ is not special-cased by the parser. Reinhold From shai at platonix.com Fri Jul 1 17:32:27 2005 From: shai at platonix.com (Shai) Date: 1 Jul 2005 14:32:27 -0700 Subject: Favorite non-python language trick? References: Message-ID: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> Joseph Garvin wrote: > > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > 1. Lisp's "dynamically scoped" variables (Perl has them, and calls them "local", but as far as I've seen their use their is discouraged). These are global variables which are given time-local bindings. That is, structuring the syntax after what's used for globals, x=10 def foo(): # No need to define x as it is only read -- same as globals print x def bar(): dynamic x x = 11 foo() def baz(): bar() # prints 11 foo() # prints 10; the binding in bar is undone when bar exits This feature makes using "globals" sensible, providing a way to avoid many important uses (and some say, misuses) of objects if you are so inclined. It allows you to do some things better than objects do, because it does to library parameters, what exceptions do to return codes: instead of passing them in all the way from outside until a piece of code which actually uses them, they are only mentioned where you set them and where you really need to access them. It would not be too hard to implement a version of this (inefficiently) in the existing language, if frame objects could carry a modifiable dictionary. I suppose it is not in Python because (most) Pythoners are not looking (hard enough) for alternatives to OOP. 2. Prolog's ability to add operators to the language. Though this facility is quite clanky in Prolog (because there is no elegant way to specify precedence), the idea is appealing to me. It would allow a better implementation of my (awkward, granted) recipe for adding logic programming constructs to Python. It is not in the language because it might fragmentize it, and because it is very hard to make recursive-descent parsers like CPython's programmable this way. 3. Lisp's Macros, of course, which have been mentioned already in this thread. Even Boo-like macros, which are nowhere as strong as Lisp's, would be very useful. Not in the language, besides its being hard in any non-lisp-like language, for the reasons mentioned for adding operators. On the other hand, there's no end to the features I wish I could copy from Python to other languages... From benji at benjiyork.com Tue Jul 5 11:19:01 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 05 Jul 2005 11:19:01 -0400 Subject: Considering moving from Delphi to Python [Some questions] In-Reply-To: <5f4d3cb5050704194977c910a5@mail.gmail.com> References: <5f4d3cb505070410192ba525d7@mail.gmail.com> <5f4d3cb5050704194977c910a5@mail.gmail.com> Message-ID: <42CAA4E5.1030105@benjiyork.com> Dark Cowherd wrote: > I want some feedback on folllwing: > anybody who has experience in writing [...] data > entry heavy web applications. > Any suggestions? You might be interested in Zope 3's ability to generate data entry/edit forms via schemas. -- Benji York From rrr at ronadam.com Mon Jul 18 05:36:03 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 18 Jul 2005 09:36:03 GMT Subject: Ordering Products In-Reply-To: <1121664664.911474.287840@o13g2000cwo.googlegroups.com> References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121664664.911474.287840@o13g2000cwo.googlegroups.com> Message-ID: <7KKCe.8994$t43.4015@tornado.tampabay.rr.com> Kay Schluehr wrote: > > Ron Adam wrote: > >>Kay Schluehr wrote: >>On a more general note, I think a constrained sort algorithm is a good >>idea and may have more general uses as well. >> >>Something I was thinking of is a sort where instead of giving a >>function, you give it a sort key list. Then you can possibly sort >>anything in any arbitrary order depending on the key list. >> >> sort(alist, [0,1,2,3,4,5,6,7,8,9]) # Sort numbers forward >> sort(alist, [9,8,7,6,5,4,3,2,1,0]) # Reverse sort >> sort(alist, [1,3,5,7,9,0,2,4,6,8]) # Odd-Even sort >> sort(alist, [int,str,float]) # sort types > > > Seems like you want to establish a total order of elements statically. > Don't believe that this is necessary. I want to establish the sort order at the beginning of the sort process instead of using many external compares during the sort process. Using a preprocessed sort key seems like the best way to do that. How it's generated doesn't really matter. And of course a set of standard defaults could be built in. >>These are just suggestions, I haven't worked out the details. It could >>probably be done currently with pythons built in sort by writing a >>custom compare function that takes a key list. > > > Exactly. The advantage of doing it as above would be the sort could be done entirely in C and not need to call a python compare function on each item. It would be interesting to see if and how much faster it would be. I'm just not sure how to do it yet as it's a little more complicated than using integer values. >>How fine grained the key >>list is is also something that would need to be worked out. Could it >>handle words and whole numbers instead of letters and digits? How does >>one specify which? What about complex objects? > > > In order to handle complex objects one needs more algebra ;) > > Since the class M only provides one operation I made the problem as > simple as possible ( complex expressions do not exist in M because > __mul__ is associative - this is already a reduction rule ). > > Kay I'm played around with your example a little bit and think I see how it should work... (partly guessing) You did some last minute editing so M and Expr were intermixed. It looks to me that what you need to do is have the expressions stored as nested lists and those can be self sorting. That can be done when init is called I think, and after any operation. You should be able to add addition without too much trouble too. a*b -> factors [a],[b] -> [a,b] You got this part. c+d -> sums [c],[d] -> [c,d] Need a sums type for this. Then... a*b+c*d -> sums of factors -> [[a,b],[c,d]] This would be sorted from inner to outer. (a+b)*(b+c) -> factors of sums -> [[a,b],[c,d]] Maybe you can sub class list to create the different types? Each list needs to be associated to an operation. The sort from inner to outer still works. Even though the lists represent different operations. You can sort division and minus if you turn them into sums and factors first. 1-2 -> sums [1,-2] 3/4 -> factors [3,1/4] ? hmmm... I don't like that. Or that might be... 3/4 -> factor [3], divisor [4] -> [3,[4]] So you need a divisor type as a subtype of factor. (I think) You can then combine the divisors within factors and sort from inner to outer. (a/b)*(c/e) -> [a,[b],c,[e]] -> [a,c,[b,e]] Displaying these might take a little more work. The above could get represented as... (a*c)/(b*e) Which I think is what you want it to do. Just a few thoughts. ;-) Cheers, Ron From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 10:03:34 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 16:03:34 +0200 Subject: Python on a public library computer References: <1122035486.585382.15370@g44g2000cwa.googlegroups.com> Message-ID: Robert Kern enlightened us with: > Because he's on a public computer without one installed? Guess it's time someone wrote a good Usenet client in a Jython applet ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From projecktzero at yahoo.com Thu Jul 28 09:04:48 2005 From: projecktzero at yahoo.com (projecktzero) Date: 28 Jul 2005 06:04:48 -0700 Subject: On fighting fire with fire... In-Reply-To: References: Message-ID: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> but..but...It's so much more fun to unleash your anger and fire back with all guns blazing fanning the flame war that most discussion groups degenerate into after a couple of responses. =) Actually, I had some self restraint yesterday. I wanted to write a ripping response to an antagonistic flame bait message on another group. I wrote it, decided it wouldn't help much, and deleted it. I guess I got it out of my system by just writing it. We need more people like you in many discussion groups. From eurleif at ecritters.biz Mon Jul 18 22:33:02 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 19 Jul 2005 02:33:02 GMT Subject: goto In-Reply-To: <1121719077.19216.10.camel@athop1.ath.vt.edu> References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: rbt wrote: > IMO, most of the people who deride goto do so because they heard or read > where someone else did. 1 GOTO 17 2 mean, GOTO 5 3 could GOTO 6 4 with GOTO 7 5 what GOTO 3 6 possibly GOTO 24 7 you! GOTO 21 8 that GOTO 18 9 really, GOTO 23 10 understandable? 11 neat. GOTO 16 12 and GOTO 25 13 are GOTO 9 14 I GOTO 26 15 wrong GOTO 20 16 I GOTO 2 17 Yes, GOTO 14 18 simple GOTO 12 19 agree GOTO 4 20 with GOTO 22 21 Gotos GOTO 13 22 something GOTO 8 23 really GOTO 11 24 be GOTO 15 25 easily GOTO 10 26 totally GOTO 19 From skilpat at gmail.com Wed Jul 13 19:02:47 2005 From: skilpat at gmail.com (skilpat at gmail.com) Date: 13 Jul 2005 16:02:47 -0700 Subject: timeoutsocket.py mirror? In-Reply-To: <75KdncmICpyiD0jfRVn-pg@powergate.ca> References: <1121291595.196101.189730@g43g2000cwa.googlegroups.com> <75KdncmICpyiD0jfRVn-pg@powergate.ca> Message-ID: <1121295767.380543.316340@g14g2000cwa.googlegroups.com> Wow that is pretty stupid of me. Yeah I was searching "python timeoutsocket.py" and that doesn't give any good results :P Thanks guys! Scott From jabel at plus.net Tue Jul 12 09:44:00 2005 From: jabel at plus.net (John Abel) Date: Tue, 12 Jul 2005 14:44:00 +0100 Subject: Missing Something Simple Message-ID: <42D3C920.2000808@plus.net> Hi, I have a list of variables, which I am iterating over. I need to set the value of each variable. My code looks like: varList = [ varOne, varTwo, varThree, varFour ] for indivVar in varList: indivVar = returnVarFromFunction() However, none of the variables in the list are being set. I thought of using setattr, but this code sits in a function, and not class, so I'm unsure what the object would be. I'm hoping someone can point me in the right direction. John From provato at gmail.com Thu Jul 14 17:41:35 2005 From: provato at gmail.com (provato) Date: 14 Jul 2005 14:41:35 -0700 Subject: eBay.py - Has anyone looked at this??? Message-ID: <1121377295.386699.141580@g47g2000cwa.googlegroups.com> I'm somewhat of a newbie was confused by the following code that I downloaded from eBay's developer site: One of the classes in the file is called "Call". What I don't get is that in "MakeCall" function, there's a use of self.Session.Server. Where is this property coming from? ============================================ class Call: RequestData = "" # just a stub DetailLevel = "0" SiteID = "0" def MakeCall(self, CallName): # specify the connection to the eBay Sandbox environment # TODO: Make this configurable in eBay.ini (sandbox/production) conn = httplib.HTTPSConnection(self.Session.Server) # specify a POST with the results of generateHeaders and generateRequest conn.request("POST", self.Session.Command, self.RequestData, self.GenerateHeaders(self.Session, CallName)) response = conn.getresponse() # TODO: When you add logging to this, change the # following to log statements # print "Response status:", response.status # print "Response reason:", response.reason # store the response data and close the connection data = response.read() conn.close() responseDOM = parseString(data) # check for any tags and print # TODO: Return a real exception and log when this happens tag = responseDOM.getElementsByTagName('Error') if (tag.count!=0): for error in tag: print "\n",error.toprettyxml(" ") return responseDOM def GenerateHeaders(self, Session, CallName): headers = {"X-EBAY-API-COMPATIBILITY-LEVEL": "349", "X-EBAY-API-SESSION-CERTIFICATE": Session.Developer + ";" + Session.Application + ";" + Session.Certificate, "X-EBAY-API-DEV-NAME": Session.Developer, "X-EBAY-API-APP-NAME": Session.Application, "X-EBAY-API-CERT-NAME": Session.Certificate, "X-EBAY-API-CALL-NAME": CallName, "X-EBAY-API-SITEID": self.SiteID, "X-EBAY-API-DETAIL-LEVEL": self.DetailLevel, "Content-Type": "text/xml"} return headers From grante at visi.com Wed Jul 6 21:46:48 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jul 2005 01:46:48 -0000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> Message-ID: <11cp2c8184lnv83@corp.supernews.com> On 2005-07-07, Ron Adam wrote: > Grant Edwards wrote: > >> On 2005-07-06, Ron Adam wrote: >> >> >>>It would be a way to set an argument as being optional without >>>actually assigning a value to it. The conflict would be if >>>there where a global with the name baz as well. Probably it >>>would be better to use a valid null value for what ever baz if >>>for. If it's a string then "", if its a number then 0, if it's >>>a list then [], etc... >> >> Except those aren't "null values" for those types. 0 is a >> perfectly good integer value, and I use it quite often. There's >> a big difference between an "invalid integer value" and an >> integer with value 0. > > Why would you want to use None as an integer value? 1) So I know whether an parameter was passed in or not. Perhaps it's not considered good Pythonic style, but I like to use a single method for both get and set operations. With no parameters, it's a get. With a parameter, it's a set: class demo: def foo(v=None): if v is not None: self.v = v return self.v 2) So I can use it as sort of a NaN equivalent. if self.fd is None: self.fd = os.open('foo.bar','w') if self.fd is not None: os.close(self.fd) self.fd = None > If a value isn't established yet, then do you need the name > defined? I find it more obvious to set the name to None during the periods that it isn't valid than to delete it and check for a NameError when I want to know if the value is usable or not. > Wouldn't it be better to wait until you need the name then > give it a value? "Better" is a value judgement. I prefer setting it None and than deleting it and then checking for existance. -- Grant Edwards grante Yow! Hey, LOOK!! A pair of at SIZE 9 CAPRI PANTS!! They visi.com probably belong to SAMMY DAVIS, JR.!! From roy at panix.com Sat Jul 2 11:25:22 2005 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jul 2005 11:25:22 -0400 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: "Andrew Koenig" wrote: > In Python, unlike many other languages, the names of formal parameters are > part of a function's interface. For example: > > def f(x, y): > return x-y > > Now f(3, 4) is -1 and f(y=3,x=4) is 1. > > The names of instance variables are generally not part of a class' > interface--they are part of its implementation. > > This proposed feature, whenever used, would tie a class' implementation to > the interface of every method that uses the feature. As far as I can see, > it is impossible to use the feature without constraining the implementation > in this way. While I suppose that's true from a theoretical point of view, as a practical matter, I don't see it being much of a big deal. I don't think I've ever written an __init__ method which saved its parameters and used different names for the parameter and the corresponding instance variable. Doing so would just be confusing (at least for the kind of code I write). Also, it doesn't really tie it in any hard and fast way. Right now, I would write: def __init__ (self, x, y, z): self.x = x self.y = y self.z = z blah under the new proposal, I would write: def __init__ (self, .x, .y, .z): blah If at some time in the future, if I decided I need to change the name of the instance variable without changing the exposed interface, it would be easy enough to do: def __init__ (self, .x, .y, z): self.zeta = z blah I'm still not convinced we need this, but the exposed interface issue doesn't worry me much. From skilpat at gmail.com Wed Jul 27 17:17:42 2005 From: skilpat at gmail.com (Scott Kilpatrick) Date: 27 Jul 2005 14:17:42 -0700 Subject: SciPy and NetCDF References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> Message-ID: <1122499062.943121.65200@z14g2000cwz.googlegroups.com> So wherever pycdf does a: from Numeric import * what is the equivalent for SciPy? i.e. where is the full Numeric module in SciPy? From horedson at earthlink.net Wed Jul 13 19:39:46 2005 From: horedson at earthlink.net (Hank Oredson) Date: Wed, 13 Jul 2005 23:39:46 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> <2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net> Message-ID: <6DhBe.3077$dU3.691@newsread2.news.pas.earthlink.net> "edgrsprj" wrote in message news:2OeBe.2928$oZ.770 at newsread2.news.atl.earthlink.net... > "Hank Oredson" wrote in message > news:1vYAe.2575$dU3.2553 at newsread2.news.pas.earthlink.net... >> "edgrsprj" wrote in message >> news:pmXAe.9096$aY6.3897 at newsread1.news.atl.earthlink.net... >> > "Hank Oredson" wrote in message >> > news:7%UAe.4148$BK1.174 at newsread3.news.pas.earthlink.net... >> >> "edgrsprj" wrote in message >> >> news:upBAe.1915$oZ.930 at newsread2.news.atl.earthlink.net... >> >> > "edgrsprj" wrote in message >> >> > news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... >> >> >> PROPOSED EARTHQUAKE FORECASTING >> >> >> COMPUTER PROGRAM DEVELOPMENT EFFORT > >> I guess my question was not specific enough. >> What I wanted was the exact sources, so I could access the data. >> The exact data sets you used. > > July 13, 2005 > > Thanks again for the comments and interest. > > The original report in this thread should have contained pointers to > all of the information you are requesting. But once again, here are some > of > the important URLs. > > http://www.freewebz.com/eq-forecasting/301.html > > That Web page contains information regarding the details of how the > forecasting program works. Also stored there are copies of an early > Zipped .txt version of the Perl program I am using along with Zip file > versions of earlier versions of the .txt format database files that I am > using. I had to Zip them because of their size and the limited bandwidth > of > that Web site. If you would prefer to receive them as regular text files > then you can try contacting me by e-mail and I will try to send them > along. > > Perl users who downloaded and ran that .pl program some time ago > said > that they had no trouble getting it to run on a Window's XP system. Other > operating system users might encounter a few formatting problems etc. > > http://www.freewebz.com/eq-forecasting/90-05.html > http://www.freewebz.com/eq-forecasting/128.html > > Those Web pages discuss the theories involved with this forecasting > method. Some of the most important information is at the end of that > 128.html Web page. I found no equations there, nor any links to the original data sources. > http://www.freewebz.com/eq-forecasting/Data.html > > That Web page contains several types of forecast data along with > some > information regarding how to interpret them. Did not find any information on the source of the data. > http://www.freewebz.com/eq-forecasting/151.html > > That Web page contains some "Help" information with details > regarding > things such as the U.S. Navy's MICA computer program which I use to > generate > data for things such as the locations of the Earth, sun, and moon relative > to the J2000 reference system. > > You should not expect to be able to instantly absorb all of that > information though it sounds like understanding it should not be a problem > for you. I have been working on the project for about 15 years. And > unfortunately, every improvement seems to take days, weeks, months, ... Everything looked fairly obvious, except that there did not seem to be any reference to the source of the datasets. > Additionally, as I said in my first report in this thread, the > multiple participants part of the project is not yet operational. For one > thing, a suitable Web site has to be found. Right now I am simply > trying to determine what the interest level there might be in such a > project. And positive feedback that I have been getting by e-mail etc. > has been encouraging. Perhaps I was not clear enough in my previous posts. I am looking for the SOURCE of the data, that is, where did YOU get the data from, so that I may obtain my own datasets. In particular I am interested in the EM dataset. -- ... Hank http://home.earthlink.net/~horedson http://home.earthlink.net/~w0rli From steve at holdenweb.com Fri Jul 29 05:16:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Jul 2005 10:16:31 +0100 Subject: how to append cgi FieldStorage Class instance In-Reply-To: <20050729071033.67270.qmail@web8410.mail.in.yahoo.com> References: <20050727163522.220b01b2.pedro.werneck@terra.com.br> <20050729071033.67270.qmail@web8410.mail.in.yahoo.com> Message-ID: praba kar wrote: > Dear All, > I have doubt in python cgi script. I describe > that doubt with below code > import cgi > form = cgi.FieldStorage() > passwd = form['passwd'].value > print passwd > But Now I want to assign some value to form['passwd'] > field value > form['passwd'] = 'surese' > Now If I try to print > print form['passwd'].value. It will raise error. > So kinldy let me how to edit or append instance > of FieldStorage class > You can't do that to a FieldStorage instance: it represents user input and is therefore not intended to be writable. What exactly are you trying to achieve - some kind of default value? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From pydecker at gmail.com Sat Jul 30 15:56:05 2005 From: pydecker at gmail.com (Peter Decker) Date: Sat, 30 Jul 2005 15:56:05 -0400 Subject: The state of OO wrappers on top of wxPython (was Re: Wheel-reinvention with Python) In-Reply-To: <7xmzo4nmf0.fsf@ruckus.brouhaha.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87slxwqp32.fsf@wilson.rwth-aachen.de> <7xmzo4nmf0.fsf@ruckus.brouhaha.com> Message-ID: On 30 Jul 2005 12:06:43 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > wxPython also depends on wxWidgets which lags behind GTK. Can you elaborate on that? It's been over a year since I last looked at GTK, but I do remember not being very impressed with how it looked on Windows and OS X. -- # p.d. From mso at oz.net Sat Jul 30 13:53:10 2005 From: mso at oz.net (Mike Orr) Date: 30 Jul 2005 10:53:10 -0700 Subject: PEP on path module for standard library In-Reply-To: <3l1avfF10i4kgU1@individual.net> References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> <3l1avfF10i4kgU1@individual.net> Message-ID: <1122745990.317541.229450@g14g2000cwa.googlegroups.com> Sorry for the formatting of my first message; I haven't posted via Google Groups before. Reinhold Birkenfeld wrote: > > - Some way to pretty-print paths embedded in lists/dicts as strings. I > > have a > > .repr_as_str class attribute that toggles this. > > I think str() does its job nicely there. But when you str() a list or other collection, it repr()'s the elements. This makes programs difficult to debug because you can't just insert a "print my_list"; you then have to weed through all the "path(" prefixes in the output. So you have to write a custom for loop, which you may only use for five minutes, to convert the paths or print them separately. With a list you can use a list comprehension, but not with a more complex structure. I don't know if there's a good solution to this other than a path_debug function that takes an object and converts all the embedded paths to strings, because people would object to repr() returning a plain string, but I want to at least acknowledge it's a problem. > > Less important but non-controversial: > > > > - Path.tempfile(), Path.tempdir(): > > Create a temporary file using tempfile.mkstemp, tempfile.mkdtemp > > > > - Path.tempfileobject(): > > Create a temporary file object using tempfile.TemporaryFile. > > (Static method.) > > Don't know whether these belong here. They are all not acting upon the > path, but create the file/dir at another location. More controversial than I thought. OK, they can stay in a subclass. My reasoning is that, if you're using paths, you'll need a Path for the file/dir anyway, so why not do it in one step? It also organizes the operations, the way Path organizes os.path and shutil. tempfileobject is less closely related to path, but it would allow the deprecation of the tempfile module, rather than just two functions in it. > > Controversial: > > > > - Delete methods and mkdir should succeed silently if the operation is > > already done. Otherwise you always have to put them in an if: > > 'if foo.exists(): foo.remove()'. > > That's a good thing. The delete methods shouldn't act any different from > the corresponding os functions. Jason said the same thing. I disagree. But it shows why a "literal" superclass in the stdlib and higher-level subclasses would be useful. I don't see why a little change to avoid an unnecessary IOError is a bad thing. The only programs it would hurt are those that really want to know whether the thing already existed, and those programs can explicitly test for it *and already do*. But most programs just want to make sure the way is clear for their files, and would like a one-line call to do it. -- Mike Orr From http Sat Jul 16 21:53:43 2005 From: http (Paul Rubin) Date: 16 Jul 2005 18:53:43 -0700 Subject: secure uploading References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> <7x4qauaccl.fsf@ruckus.brouhaha.com> <1121563713.124461.230540@g47g2000cwa.googlegroups.com> <7xoe922p88.fsf@ruckus.brouhaha.com> <1121564015.242118.12780@g44g2000cwa.googlegroups.com> Message-ID: <7xzmsm5haw.fsf@ruckus.brouhaha.com> "macaronikazoo" writes: > ok, so what can I do to get something uploaded? how can I upload > something via http? Depends on your web host. At worst, use a server side script to accept the upload. You're asking basic webmaster-type questions. This really isn't the best place for those. From nothingcanfulfill at gmail.com Tue Jul 19 02:19:52 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 18 Jul 2005 23:19:52 -0700 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121753992.380913.24000@g49g2000cwa.googlegroups.com> Honestly, I'm just using Python's own IDLE to do it all. It works rather well for my tastes :) From roy at panix.com Sat Jul 2 17:57:32 2005 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jul 2005 17:57:32 -0400 Subject: Determining actual elapsed (wall-clock) time References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: Peter Hansen wrote: > I guess as long as the NTP client is set up to ensure the time > adjustments are smaller than some value X, it would be acceptable. NTP is generally capable of keeping the various system clocks on a LAN within a few ms of each other, and within a few 10's of ms over the Internet from GPS, WWV, or similar international time references. > I'll have to look into how to set up Windows XP to prevent users from > changing the time on their own, assuming that's possible. On a single-user system like Windows, you pretty much have to assume the user can do anything. They can turn off NTP, reset the clock, reboot the system, uninstall your software, whatever. If you could check to see that NTP is running, it doesn't prove anything. A malicious and determined user could set up another machine as a NTP server to synch against, and even configure that machine to look like it was a stratum-1 reference (i.e. an atomic clock). At some point, you need to decide if you trust the system administrator to supply you with an accurate system clock or not. If you don't, and it's really important that you have an accurate time reference, you've got an interesting engineering problem on your hands. From sjuranic at gmail.com Tue Jul 19 12:09:42 2005 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 19 Jul 2005 09:09:42 -0700 Subject: Can I make the Python build use an already-installed version of Expat? In-Reply-To: References: Message-ID: <56190b6c05071909097836e9a7@mail.gmail.com> On 7/19/05, Bernhard Herzog wrote: > This sounds like this bugreport on sourceforge: > http://python.org/sf/1075984 Thanks! I applied the workaround posted by `bos' and things seem to work now. -- Steve Juranich Tucson, AZ USA From twic at urchin.earth.li Sat Jul 2 10:11:54 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 2 Jul 2005 15:11:54 +0100 Subject: No subject In-Reply-To: References: <1120231547.928636.59270@g43g2000cwa.googlegroups.com> Message-ID: On Fri, 1 Jul 2005, Andreas Kostyrka wrote: > Am Freitag, den 01.07.2005, 08:25 -0700 schrieb George Sakkis: > >>> Again, how? Is there a way to force that an external user of my lib can >>> not use my internal data/methods/classes, unless he uses odd compiler >>> hacks? >> >> I never understood how mainstream OO languages expect the designer of a >> class to know in advance that an attribute should be hidden or >> unnecessary to its subclasses by being declared "private" instead of >> "protected". > > The problem is, that the classic private/protected/public visibility > tags try to solve multiple problems. > > Private: Ok, that's all that's really only for the implementation. > public: Well, that's all for my "customers". Hmm. What if I've got two > kinds of customers? Say a customer like in bank customer, and second > customer that plays the role of the bank employee? oops. C++ has 'friend' for that: http://www.cplusplus.com/doc/tutorial/tut4-3.html tom -- REMOVE AND DESTROY From cyberguard-1048 at yahoo.com Mon Jul 4 06:03:09 2005 From: cyberguard-1048 at yahoo.com (Stephen Harris) Date: Mon, 04 Jul 2005 10:03:09 GMT Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: "jwaixs" wrote in message news:1120464287.886617.301530 at g47g2000cwa.googlegroups.com... > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! There are only reference, and if you don't know how a > module work you won't learn it from a reference! > PowerGrep is a commercial Windows tool. However, it comes with a manual that has a 45 page tutorial on regular expressions. www.powergrep.com/manual/PowerGREP.pdf tutorial: pages 109-156 There is also a new Wrox book besides the O'Reilly/Friedl Owl book. http://www.uhacc.org/tech_docs/guides/regex1.php also regex2.php, and regex3.php Only the delimiters have been changed to protect the innocent, Stephen From python at hope.cz Sat Jul 30 06:33:14 2005 From: python at hope.cz (Lad) Date: 30 Jul 2005 03:33:14 -0700 Subject: How can I run a program? Message-ID: <1122719594.365246.241840@g43g2000cwa.googlegroups.com> Hello, I am running Python on XP and have a problem with a program if its name consists '-' for example: my-program.py When I try to run a program with such name I get the error : Traceback (most recent call last): File "", line 1, in ? NameError: name 'my' is not defined Python thinks that the name of program is my.py only but the name is my-program.py What is a solution? Thank you Lad. From peter at engcorp.com Wed Jul 13 10:16:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 10:16:57 -0400 Subject: Building a function call? In-Reply-To: References: <7OWdnRFJ_sHkk0jfRVn-hw@powergate.ca> Message-ID: Roland Heiber wrote: > Even with globals(), I think its a bit odd ..., but safer than using > eval() ... Some would agree and claim that using an import is better: c = (1, 2) thisModule = __import__(__name__) func = getattr(thisModule, 'dothat') func(*c) I don't generally find that more readable than the one with globals(), and I don't offhand recall any serious criticism of globals() on grounds of either readability or style, so I'm unsure why anyone would prefer the alternative. -Peter From t-meyer at ihug.co.nz Thu Jul 28 22:54:37 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 29 Jul 2005 14:54:37 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > Well, I actually had some correspondence with Jason on this > very subject a year or so ago: [...] > Obviously, I don't know how much weight Jason's original > ideas have on the prepped-for-syslib module, but it does > support what other people have been saying: that the Path > should behave like a string where a string is expected. Was that the whole email? It certainly adds weight to '+' having the normal string behaviour, but it didn't really say anything about why '/' should be a shortcut for join. Do you know if Jason had any reasoning for this other than laziness ? =Tony.Meyer From erniedude at gmail.com Mon Jul 25 15:12:25 2005 From: erniedude at gmail.com (Ernesto) Date: 25 Jul 2005 12:12:25 -0700 Subject: Run batch files in Windows XP In-Reply-To: References: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> Message-ID: <1122318744.969547.113640@g43g2000cwa.googlegroups.com> Thanks Peter. The issue is I haven't done very much batch programming. I need to prompt the user for input and each batch file is in a different directory. How do I change directories and prompt for user input? Thanks! From 4krishan at gmail.com Tue Jul 26 10:50:55 2005 From: 4krishan at gmail.com (k pur) Date: 26 Jul 2005 07:50:55 -0700 Subject: Counting processors In-Reply-To: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> References: <1122292299.317193.87710@g47g2000cwa.googlegroups.com> Message-ID: <1122389455.371659.229710@o13g2000cwo.googlegroups.com> You can use print os.sysconf("SC_NPROCESSORS_CONF") works on Linux krishan Pauldoo wrote: > Hi, > Is a way in python to obtain the total number of processors present in > the system? > > os.platform doesn't seem to contain anything useful. From deets at web.de Thu Jul 28 12:37:52 2005 From: deets at web.de (Diez B.Roggisch) Date: Thu, 28 Jul 2005 16:37:52 +0000 (UTC) Subject: Regex for nested =?utf-8?b?e30=?= References: Message-ID: Chris cdot.de> writes: > > is something like that possible? No. Not with "pure" regexes. The reason is that the theory behind them doesn't allow to detect syntactic constructs like a**nn**n, with a={ and b=} in your case. What you need is a "real" parser - usually one uses regexes to split the string into so-called tokens. The either a handwritten parser or a parser-generator is used. The following is a simple implementation based on the spark parser generator: import spark class ParsingError: def __init__(self, msg = None): self.msg = msg def __repr__(self): return "Parsing Error: %s" % self.msg class Token: def __init__(self, type, attr=None): self.type = type self.attr = attr def __cmp__(self, o): return cmp(self.type, o) def __repr__(self): return self.attr or self.type class Scanner(spark.GenericScanner): def __init__(_): spark.GenericScanner.__init__(_) def error(self, s, pos): raise ParsingError("Lexical error at %i" % pos) def tokenize(self, input): self.rv = [] spark.GenericScanner.tokenize(self, input) return self.rv def t_whitespace(self, s): r' \s+ ' pass def t_word(self, s): r'[a-z]\w*' t = Token(type='word', attr=s) self.rv.append(t) def t_parentheses(self, s): r' \{| \}' t = Token(type=s) self.rv.append(t) def t_comment(self, s): r'\#.*' pass def t_default(self, s): pass class Parser(spark.GenericParser): def __init__(self, start='expr'): spark.GenericParser.__init__(self, start) def p_expr_1(self, args): ''' expr ::= word block expr ''' return [(args[0], args[1])] + args[2] def p_expr_2(self, args): ''' expr ::= ''' return [] def p_block(self, args): ''' block ::= { expr } ''' return args[1] def error(self, token): raise ParsingError("Syntax error at or near `%s' token" % token) def scan(input): scanner = Scanner() try: return scanner.tokenize(input) except ParsingError,e: print e def parse(tokens): return Parser().parse(tokens) text = """ outer { inner1 { } inner2 { } } simple { } """ def main(): tokens = scan(text) print parse(tokens) if __name__ == "__main__": main() From fphsml at gmail.com Fri Jul 15 06:02:42 2005 From: fphsml at gmail.com (James) Date: 15 Jul 2005 03:02:42 -0700 Subject: Python Programming Contest In-Reply-To: References: Message-ID: <1121421762.826887.114880@g43g2000cwa.googlegroups.com> Brian Quinlan wrote: > I've decided that it would be be fun to host a weekly Python programming > contest. The focus will be on algorithms that require a bit of thought > to design but not much code to implement. > > I'm doing to judge the solutions based on execution speed. It sucks but > that is the easiest important consideration to objectively measure. I'll > also indicated which solutions I think are good examples of Python > design. Hopefully, people's solutions can provide a resource for people > looking for best practice examples and also for people looking for > performance ideas. > > You can find the first problem here: > http://www.sweetapp.com/pycontest/contest1 > > I'm always looking for feedback, so let me know what you think or if you > have any ideas for future problems. > > Cheers, > Brian I am not sure if it is a good idea to use a LiveCD for OS when you are testing for speed. CD access speeds fluctuate and may even impact performance even if you start measuring after the module loading is complete. From devlai at gmail.com Wed Jul 27 16:34:37 2005 From: devlai at gmail.com (Devan L) Date: 27 Jul 2005 13:34:37 -0700 Subject: searching string url In-Reply-To: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> References: <1122495787.289468.304560@o13g2000cwo.googlegroups.com> Message-ID: <1122496477.892711.308100@g44g2000cwa.googlegroups.com> Sounds somewhat like homework. So I won't just give you a code solution. Use the regular expression(re) module to match the urls. From python at hope.cz Wed Jul 20 04:01:02 2005 From: python at hope.cz (Lad) Date: 20 Jul 2005 01:01:02 -0700 Subject: Web shop in Python Message-ID: <1121843998.337606.326060@g47g2000cwa.googlegroups.com> Does anyone know about an e-shop solution written in Python? Thanks for reply Lad. From lamthierry at gmail.com Fri Jul 22 16:44:07 2005 From: lamthierry at gmail.com (Thierry Lam) Date: 22 Jul 2005 13:44:07 -0700 Subject: Mapping a drive to a network path In-Reply-To: References: <1122059720.962075.53260@g44g2000cwa.googlegroups.com> Message-ID: <1122065047.149059.290660@g49g2000cwa.googlegroups.com> Thanks, that helps. Thierry From dalke at dalkescientific.com Fri Jul 29 02:28:26 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 29 Jul 2005 06:28:26 GMT Subject: os._exit vs. sys.exit References: <7a2dnSer5eC2BnTfRVn-sQ@comcast.com> Message-ID: Bryan wrote: > Why does os._exit called from a Python Timer kill the whole process while > sys.exit does not? On Suse. os._exit calls the C function _exit() which does an immediate program termination. See for example http://developer.apple.com/documentation/Darwin/Reference/ManPages/man2/_exit.2.html and note the statement "can never return". sys.exit() is identical to "raise SystemExit()". It raises a Python exception which may be caught at a higher level in the program stack. Andrew dalke at dalkescientific.com From peter at engcorp.com Tue Jul 5 15:12:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Jul 2005 15:12:49 -0400 Subject: How do you program in Python? In-Reply-To: References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: > +1 insight of the century. This is the heart of the unix way - lots of > simple little programs that do exactly one thing well, and can be > composed through simple, clean interfaces. For actually getting things > done, a toolkit beats a swiss army knife. Perhaps, but I'm puzzled how that explanation would apply to emacs and those who use it as a swiss army knife, doing everything from editing to email to laundry in the same editor... (Note: this isn't a flame about emacs, nor vi for that matter, just a discussion about the apparent conflict in the two philosophies embodied by the "simple little programs" and the "emacs" approaches.) -Peter From support.services.complaints at gmail.com Sun Jul 3 15:05:30 2005 From: support.services.complaints at gmail.com (MyHaz) Date: 3 Jul 2005 12:05:30 -0700 Subject: Using regular expressions in internet searches In-Reply-To: <1120412943.283248.100700@g14g2000cwa.googlegroups.com> References: <1120412943.283248.100700@g14g2000cwa.googlegroups.com> Message-ID: <1120417530.439691.199980@o13g2000cwo.googlegroups.com> Python would be good for this, but if you just want a chuck an rumble solution might be. bash $wget -r --ignore-robots -l 0 -c -t 3 http://www.cnn.com/ bash $ grep -r "Micheal.*" ./www.cnn.com/* Or you could do a wget/python mix like import sys import re sys.os.command("wget -r --ignore-robots -l 0 -c -t 3 http://ww.cnn.com/") re_iraq=re.compile("iraq .+?",re.IGNORECASE) while "file in dirs under ./www.cnn.com/ " iraqs = re_iraq.findall(file.read()) print iraqs From peter at engcorp.com Fri Jul 1 11:47:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 11:47:31 -0400 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> <42c41ef2@usenet01.boi.hp.com> Message-ID: Dan Sommers wrote: > Peter Hansen wrote: >>This problem is well suited to the abilities of genetic algorithms, >>and this would probably be an excellent way to learn more about them, >>even if you don't get the best solution. > > There's some sort of irony or something in there about not writing the > best genetic algorithm, but I can't quite put my finger on it. Maybe your irony sensor is getting muddled over the fact that genetic algorithms generally *don't* find the best solutions, just relatively good ones. They aren't an exhaustive search, they're basically a random search with some features thought to focus the search on more fruitful parts of the solution space, thus optimizing it. Unless *my* irony processors are malfunctioning, I don't think there's anything ironic about this. (If anything it looks like the exact opposite of irony, to me.) -Peter From nobody at nowhere.com Tue Jul 26 11:31:34 2005 From: nobody at nowhere.com (Joe) Date: Tue, 26 Jul 2005 11:31:34 -0400 Subject: Bug Report / Patch (1159139 cgi.py invalid REQUEST_METHOD set) Message-ID: <_ICdnT-Tg-3_ynvfRVn-qw@comcast.com> Back in March I submitted a patch for cgi.py to sourceforge to fix a problem with the handling of an invalid REQUEST_METHOD. I thought I followed all the steps to properly submit the bug and patch but the patch is still sitting there in limbo. This is the first patch I have submitted for Python, did I miss a step in the patch process? What else needs to be done? Thanks! From tjreedy at udel.edu Mon Jul 11 01:44:07 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 11 Jul 2005 01:44:07 -0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com><20050710133959.83611.qmail@web31512.mail.mud.yahoo.com><7x64vip8eb.fsf@ruckus.brouhaha.com> <42d1d71e.340825300@news.oz.net> Message-ID: "Bengt Richter" wrote in message news:42d1d71e.340825300 at news.oz.net... > Me too. I liked the leading _, but on second thought it is a weird > language change > re names in a special context. Probably not so good. To repeat: while my '_' proposal could have been for a language change (in 3.0), it was actually for a convention recognized by a metaclass or, more likely, decorator (and implementable now, I think). *Any* flag would serve the purpose, but I picked one that was a single char while being visually striking and, as far as I know, rarely used in current practice even though quite legal. A 'self_' prefix would do as well except for being more to type. The prefix could even be an argument to the decorator! Terry J. Reedy From rrr at ronadam.com Wed Jul 6 20:56:56 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 00:56:56 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Benji York wrote: > Ron Adam wrote: > >> "if extraargs:" would evaluate to "if None:", which would evaluate to >> "if:" which would give you an error. > > > In what way is "if None:" equivalent to "if:"? > -- > Benji York It's not now.. but if None where to really represent the concept None, as in not bound to anything, it would evaluate to nothing. Given the statement: a = None And the following are all true: a == None (a) == (None) (a) == () (None) == () Then this "conceptual" comparison should also be true: if (None): == if (): if (): == if: Comparing if's like that wouldn't be a valid code of course, but it demonstrates the consistency in which the comparison is made. I think. ;-) Of course this is all hypothetical anyways, so it could be what ever we decide makes the most since, include not changing anything. Cheers, Ron From peter at engcorp.com Fri Jul 1 11:52:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 11:52:14 -0400 Subject: Python for everything? In-Reply-To: <11can6l9ldmdeaa@corp.supernews.com> References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <11can6l9ldmdeaa@corp.supernews.com> Message-ID: Grant Edwards wrote: > [Why are Python programs referred to as "scripts". Python no > more a "scripting" language than Java, Pascal, Smalltalk, > Objective C.] I think it's because the term "script" is a nice, simple word that evokes the idea of "source file that can be directly executed", which is a convenient thing to be able to say in fewer words than that... I think it would be unusual for anyone to refer to a multi-file Python program as merely a "script". We do often call individual source files in a large Python program "scripts", but I think that's probably just out of habit or association: calling single Python source files "scripts" is so common, even if they aren't scripts in the sense of "individually executable files written in a scripting language" any more. -Peter From eurleif at ecritters.biz Tue Jul 19 20:39:20 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 20 Jul 2005 00:39:20 GMT Subject: Web Framework Reviews In-Reply-To: <1121805242.574679.298990@f14g2000cwb.googlegroups.com> References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> <1gzykmm.qkpns61er9hmhN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121792162.939519.9890@g43g2000cwa.googlegroups.com> <1gzyndw.1jayyri4b7m7sN%dial#####$$NOSPAM##$#$##tone@gmail.com> <1121796584.974756.132430@g14g2000cwa.googlegroups.com> <1121805242.574679.298990@f14g2000cwb.googlegroups.com> Message-ID: istvan.albert at gmail.com wrote: >>Templating engines like ZPT prefer to put some code in the template, >>Nevow prefers to put code in python and allow you to write some xhtml in >>python too. > > Oh yeah, now I remeber, I think this is a controversial idea. One important thing to realise about Nevow is that it doesn't forbid you from putting logic in the template, it simply doesn't encourage it. There's nothing stopping you from writing render_while and render_if methods for Nevow -- in fact, it would be quite easy. But once you really understand Nevow and how it works, you realize that you don't need to put logic in the template, because there's a better way. From sarir.khamsi at raytheon.com Thu Jul 28 19:07:23 2005 From: sarir.khamsi at raytheon.com (Sarir Khamsi) Date: Thu, 28 Jul 2005 16:07:23 -0700 Subject: Adding code and methods to a class dynamically References: Message-ID: Peter Hansen writes: > If it's truly just an alias you want, then something like this should > work better. Replace everything in the if mo: section with this: > > if mo: > newName = mo.group(1) > existingName = mo.group(2) > existingMethod = getattr(self, 'do_' + existingName) > setattr(self, 'do_' + newName, existingMethod) Thanks, this is amazingly more simple than what I had. This works fine but I'm looking at the code for cmd and don't really see how you get completion to work on the new alias. Also, I would like the alias to have arguments: alias newName existingName arg1 arg2 ... Currying comes to mind, but I haven't tried it yet. Thanks again for the help. Sarir From peter at engcorp.com Fri Jul 22 09:10:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 09:10:38 -0400 Subject: command line argument passing In-Reply-To: References: Message-ID: Hayri ERDENER wrote: > hi to all, > is it possible in python to pass arguments by using command prompt in > windows 2000 and XP ? > for example: > sourceCode.py factorial 4 > gives me the factorial of 4 namely 24. Yes, the arguments are available as a list in sys.argv . Remember that you need to import "sys" before you can access that, and that the values will be returned as strings, so if they should be treated as numbers it's up to you to convert them. Use of the getopt or optparse modules is recommended to work with command line arguments more effectively. -Peter From berlin.brown at gmail.com Tue Jul 19 11:56:30 2005 From: berlin.brown at gmail.com (Ramza Brown) Date: Tue, 19 Jul 2005 11:56:30 -0400 Subject: Jython Released Message-ID: <6NWdna8jsbEov0DfRVn-vA@comcast.com> This is an update from Brian Zimmer of the Jython group, new release: "There is a new release of Jython available at Sourceforge: http://sourceforge.net/project/showfiles.php?group_id=12867 This release includes many major changes since the last full release: - new-style classes - Java Collections integration - PEP 302 implementation - iterators - generators - __future__ division - support for running on JDK1.5 - new installer - a significant number of features to bring Jython in line with CPython - many, many bugfixes It was compiled a OS X with JDK1.4 but should run on JDK 1.2 +. The full set of changes are too numerous to list in detail. Please consult the sourceforge tracker for all closed issues since the last release. This version of Jython has support for most of Python 2.2 and numerous features from Python 2.3 and beyond. A more comprehensive list will be forthcoming. Please email jython-dev at lists.sourceforge.net with questions. thanks,..." The Jython Development Team From bill.mill at gmail.com Mon Jul 18 16:09:38 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon, 18 Jul 2005 16:09:38 -0400 Subject: smtplib In-Reply-To: <000a01c58bd1$f2da5db0$1603a8c0@avc> References: <000a01c58bd1$f2da5db0$1603a8c0@avc> Message-ID: <797fe3d4050718130944611273@mail.gmail.com> On 7/18/05, Alberto Vera wrote: > > Hello: > > Do you know If the smtplib routine have been changed in last releases? > > I used this script: > > http://docs.python.org/lib/SMTP-example.html > > but it didn't work with the last release. > > Do you know any idea about this change? check out the CVS changelog to see what's changed with it: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/smtplib.py?rev=1.70&view=log Peace Bill Mill bill.mill at gmail.com From thanos at sians.org Sat Jul 23 19:09:54 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 02:09:54 +0300 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <20050723230954.GA12152@zermelo.sians.org> On Sat, Jul 23, 2005 at 11:22:21PM +1000, Steven D'Aprano wrote: > On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote: > > Hello. > > > > I would like to have a quick way to create dicts from object, so that a > > call to foo['bar'] would return obj.bar. > > That looks rather confusing to me. Why not just call obj.bar, since it > doesn't look like you are actually using the dictionary at all? > > > [...] > > I don't think this is particularly useful behaviour. How do you use it? print foo %do where do is a dictobj object... -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From rrr at ronadam.com Sun Jul 3 15:31:02 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 03 Jul 2005 19:31:02 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: Erik Max Francis wrote: > Ron Adam wrote: >> I'm just estimating, but I think that is the gist of adding those two >> in exchange for reduce. Not that they will replace all of reduce use >> cases, but that sum and product cover most situations and can be >> implemented more efficiently than using reduce or a for loop to do the >> same thing. The other situations can easily be done using for loops, >> so it's really not much of a loss. > > I really don't understand this reasoning. You essentially grant the > position that reduce has a purpose, but you still seem to approve > removing it. Let's grant your whole point and say that 90% of the use > cases for reduce are covered by sum and product, and the other 10% are > used by eggheads and are of almost no interest to programmers. But it > still serves a purpose, and a useful one. That it's not of immediate > use to anyone is an argument for moving it into a functional module > (something I would have no serious objection to, though I don't see its > necessity), not for removing it altogether! Why would you remove the > functionality that already exists _and is being used_ just because? What > harm does it do, vs. the benefit of leaving it in? There are really two separate issues here. First on removing reduce: 1. There is no reason why reduce can't be put in a functional module or you can write the equivalent yourself. It's not that hard to do, so it isn't that big of a deal to not have it as a built in. 2. Reduce calls a function on every item in the list, so it's performance isn't much better than the equivalent code using a for-loop. *** (note, that list.sort() has the same problem. I would support replacing it with a sort that uses an optional 'order-list' as a sort key. I think it's performance could be increased a great deal by removing the function call reference. *** Second, the addition of sum & product: 1. Sum, and less so Product, are fairly common operations so they have plenty of use case arguments for including them. 2. They don't need to call a pre-defined function between every item, so they can be completely handled internally by C code. They will be much much faster than equivalent code using reduce or a for-loop. This represents a speed increase for every program that totals or subtotals a list, or finds a product of a set. > But removing reduce is just removing > functionality for no other reason, it seems, than spite. No, not for spite. It's more a matter of increasing the over all performance and usefulness of Python without making it more complicated. In order to add new stuff that is better thought out, some things will need to be removed or else the language will continue to grow and be another visual basic. Having sum and product built in has a clear advantage in both performance and potential frequency of use, where as reduce doesn't have the same performance advantage and most poeple don't use it anyway, so why have it built in if sum and product are? Why not just code it as a function and put it in your own module? def reduce( f, seq): x = 0 for y in seq: x = f(x,y) return x But I suspect that most people would just do what I currently do and write the for-loop to do what they want directly instead of using lambda in reduce. x = 1 for y in seq: x = x**y If performance is needed while using reduce with very large lists or arrays, using the numeric module would be a much better solution. http://www-128.ibm.com/developerworks/linux/library/l-cpnum.html Cheers, Ron From swiftset at gmail.com Fri Jul 8 22:21:36 2005 From: swiftset at gmail.com (Alex Gittens) Date: Fri, 8 Jul 2005 21:21:36 -0500 Subject: why UnboundLocalError? Message-ID: I'm trying to define a function that prints fields of given widths with specified alignments; to do so, I wrote some helper functions nested inside of the print function itself. I'm getting an UnboundLocalError, and after reading the Naming and binding section in the Python docs, I don't see why. Here's the error: >>> fieldprint([5, 4], 'rl', ['Ae', 'Lau']) Traceback (most recent call last): File "", line 1, in ? File "fieldprint.py", line 35, in fieldprint str += cutbits() File "fieldprint.py", line 11, in cutbits for i in range(0, len(fields)): UnboundLocalError: local variable 'fields' referenced before assignment This is the code: def fieldprint(widths,align,fields): def measure(): totallen = 0 for i in range(0, len(fields)): totallen += len(fields[i]) return totallen def cutbits(): cutbit = [] for i in range(0, len(fields)): if len(fields[i]) >= widths[i]: cutbit.append(fields[i][:widths[i]]) fields = fields[widths[i]:] elif len(fields[i]) > 0: leftover = widths[i] - len(fields[i]) if align[i] == 'r': cutbit.append(' '*leftover + fields[i]) elif align[i] == 'l': cutbit.append(fields[i] + ' '*leftover) else: raise 'Unsupported alignment option' fields[i] = '' else: cutbit.append(' '*widths[i]) return cutbit.join('') if len(widths) != len(fields) or len(widths)!=len(align) or len(align)!=len(fields): raise 'Argument mismatch' str = '' while measure()!=0: str += cutbits() What's causing the error? Thanks, Alex -- ChapterZero: http://tangentspace.net/cz/ From walter at livinglogic.de Thu Jul 28 06:30:06 2005 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 28 Jul 2005 12:30:06 +0200 Subject: Trimming X/HTML files In-Reply-To: References: Message-ID: <42E8B3AE.9050108@livinglogic.de> Thomas SMETS wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > Dear, > > I need to parse XHTML/HTML files in all ways : > ~ _ Removing comments and javascripts is a first issue > ~ _ Retrieving the list of fields to submit is my following item (todo) > > Any idea where I could find this already made ... ? You could try XIST (http://www.livinglogic.de/Python/xist). Removing comments and javascripts works like this: --- from ll.xist import xsc, parsers from ll.xist.ns import html e = parsers.parseURL("http://www.python.org/", tidy=True) def removestuff(node, converter): if isinstance(node, xsc.Comment): node = xsc.Null elif isinstance(node, html.script) and \ (unicode(node["type"]) == u"text/javascript" or \ unicode(node["language"]) == u"Javascript" \ ): node = xsc.Null return node e = e.mapped(removestuff) print e.asBytes() --- Retrieving the list of fields from all forms on a page might look like this: --- from ll.xist import xsc, parsers, xfind from ll.xist.ns import html e = parsers.parseURL("http://www.python.org/", tidy=True) for form in e//html.form: print "Fields for %s" % form["action"] for field in form//xfind.is_(html.input, html.textarea): if "id" in field.attrs: print "\t%s" % field["id"] else: print "\t%s" % field["name"] --- This prints: Fields for http://www.google.com/search q domains sitesearch sourceid submit Hope that helps! Bye, Walter D?rwald From me at privacy.net Wed Jul 20 08:29:56 2005 From: me at privacy.net (Admin) Date: Wed, 20 Jul 2005 09:29:56 -0300 Subject: How to send a query to the browser from time to time? References: <1121778228.962141.70680@f14g2000cwb.googlegroups.com> <86fyuarwdm.fsf@bhuda.mired.org> Message-ID: On Wed, 20 Jul 2005 00:26:13 -0300, Mike Meyer wrote: > AJAX is overkill for this. If you just want to automatically refresh > the page automatically, you can use a meta refresh tag. Reloading the page automatically would be even worse because it would spend a lot of bandwidth, it would reload all the page and graphics all the time. -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From hayrierdener at gmail.com Mon Jul 18 07:48:08 2005 From: hayrierdener at gmail.com (Hayri ERDENER) Date: Mon, 18 Jul 2005 14:48:08 +0300 Subject: goto Message-ID: <261d32a705071804483ef68021@mail.gmail.com> hi, what is the equivalent of C languages' goto statement in python? best regards From ledruker at rogers.com Wed Jul 13 12:49:45 2005 From: ledruker at rogers.com (Eugene Druker) Date: Wed, 13 Jul 2005 12:49:45 -0400 Subject: tkFileDialog.askopenfilename filetypes problem References: Message-ID: For me this: z = tkFileDialog.askopenfilename(title='Title', filetypes=[ ('AIFF Files','*.aiff'), ("TXT Files", "*.txt"), ], initialdir=InputDir) print z works fine. Eugene "Justin Straube" wrote in message news:X3bBe.4979$5R1.442 at fe07.lga... > Hopefully someone can catch what im missing here. Ive googled this and I think > Ive got the filetypes arg written properly, but I get a traceback when calling > this function. > > Heres the code followed by its traceback. > > def do_ask_fn_1(): > z = askopenfilename(title=TITLE, initialdir=Dst_Dir, > filetypes=(('AIFF Files','*.aiff'), > ("AU Files", "*.au"), > ("RAW Files", "*.raw"), > ("SD Files", "*.sd"), > ("SND Files", "*.snd"), > ("WAV files", "*.wav") > ) > ) > print z > > > Exception in Tkinter callback > Traceback (most recent call last): > File "E:\PYTHON~1\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "P:\work\Python\PYZoid\PYZoid.pyw", line 213, in do_ask_fn_1 > filetypes=[('AIFF Files','*.aiff'), > TypeError: askopenfilename() takes exactly 0 non-keyword arguments (1 given) > > Can anyone point to what Ive done wrong? Thanks for any input. > > Justin From twic at urchin.earth.li Tue Jul 5 16:49:33 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 5 Jul 2005 21:49:33 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: <42C8B151.2010503@REMOVEMEcyber.com.au> Message-ID: On Tue, 5 Jul 2005, Terry Hancock wrote: > Really, the only *right* thing to do is to raise an exception ASAP after > the NaN comes up. That sounds like a very good idea. Are there any uses for NaN that aren't met by exceptions? tom -- [Philosophy] is kind of like being driven behind the sofa by Dr Who - scary, but still entertaining. -- Itchyfidget From steve at holdenweb.com Thu Jul 28 10:12:48 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jul 2005 15:12:48 +0100 Subject: functions without parentheses In-Reply-To: <1122559193.824826.157390@g47g2000cwa.googlegroups.com> References: <1122559193.824826.157390@g47g2000cwa.googlegroups.com> Message-ID: Simon Dahlbacka wrote [about function calls without parenthesis]: > If you actually want that kind of syntax, then why don't you use Visual > Basic? ;) > Because Perl is far too tempting to ignore. The serious answer to the OP's question, however, is that Python refuses to guess whether a function reference not followed by a left parenthesis is a reference to a function or a reference to the result of calling the function. Perl and VB(Script) make more use of context, in ways that confuse many users. Time for someone to try import this regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVETHIScyber.com.au Tue Jul 12 04:42:38 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 18:42:38 +1000 Subject: Trying to come to grips with static methods Message-ID: I've been doing a lot of reading about static methods in Python, and I'm not exactly sure what they are useful for or why they were introduced. Here is a typical description of them, this one from Guido: "The new descriptor API makes it possible to add static methods and class methods. Static methods are easy to describe: they behave pretty much like static methods in C++ or Java." http://www.python.org/2.2.3/descrintro.html Great. So I have learn an entire new language to understand static methods. Perhaps not -- hence this cry for help. As near as I can see it, static methods are object methods that act just like functions. Er. I always thought that object methods *were* functions, except they had some runtime magic that passed the object itself as the first argument. >From Guido's example: >>> class C: ... def foo(x, y): ... print "staticmethod", x, y ... foo = staticmethod(foo) ... >>> C.foo(1, 2) staticmethod 1 2 >>> c = C() >>> c.foo(1, 2) staticmethod 1 2 So I compare with an ordinary class function, er, method: >>> class D: ... def foo(self, x, y): ... print "method", x, y ... >>> D.foo(1, 2) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method foo() must be called with D instance as first argument (got int instance instead) Okay, that is to be expected. Actually, I expected an exception that I hadn't passed enough arguments (2 arguments when foo expects 3), but in hindsight it is obvious enough. First point of confusion. In the above exception, foo is called an unbound method. But type(D.foo) returns even though foo is being access through the class, not an instance. And type(D().foo) returns the same. Can I assume that in Python "unbound method" is just another way of saying "a method of a class that expects to be called via an instance"? I next tried this: >>> D.foo(D(), 1, 2) method 1 2 >>> D().foo(1, 2) method 1 2 Clear as mud. An ordinary method called from an instance is the same as a static method called from anywhere, provided you don't -- or rather, can't -- try to access self from the static method. When would you use a static method instead of an ordinary method? It has been suggested that you might use it for functions that don't need to access self. But that doesn't seem very convincing to me, because there is already a perfectly good idiom for that: >>> class E: ... def foo(): # returns calculated value ... return 1 ... foo = staticmethod(foo) ... def bar(self): ... return 1 # just ignore the value of self ... >>> E.foo() 1 >>> e = E() >>> e.bar() 1 What are some usage cases for using Class.StaticMethod() instead of instance.method()? Everything I've read seems to just assume that the benefits of static methods are so obvious that they don't need explaining. Unfortunately, I haven't come from a background in OO and I'm easily confused, hence this post. -- Steven. From sjmachin at lexicon.net Sun Jul 17 18:38:58 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Jul 2005 08:38:58 +1000 Subject: Python Programming Contest In-Reply-To: References: <42D780EF.6020809@sweetapp.com> Message-ID: <42daddff$1@news.eftel.com> John Hazen wrote: > * Brian Quinlan [2005-07-15 02:08]: > >>You can find the first problem here: >>http://www.sweetapp.com/pycontest/contest1 > > > I have one question about the problem. Is the cost we are to minimize > the cost of arriving in the target city at all, or the cost of arriving > at the target city at the end of the final day of the schedule? > > (If you were traveling to a conference, for example, you'd have a > specific arrival time, and a cost to stay in the destination city until > that time. But, if you were going to sight-see, then you could arrive > at any time, and begin your itinerary upon arrival.) > > Say I can find a combination of flights that gets me to the target at > the end of day 3 for 390 units, and a combination that gets me there at > the end of day 4 for 400. If you count the hostel cost from day 3 to > day 4, the first combination costs 410. So, which is preferred? > > -John > > P.S. I just realized this may be answered be the test suite, but I'm > still at the thinking stage. What we really need is a problem *specification* contest. From benn at cenix-bioscience.com Thu Jul 21 06:04:08 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 21 Jul 2005 12:04:08 +0200 Subject: Python Path Setting Message-ID: <42DF7318.7030809@cenix-bioscience.com> Hello, I'm trying to find some detailed documentation about PYTHONPATH, paths.pth, lib/site-packages, sitecustomise and so on. I know what they do but I'd like some detailed documentation about what gets loaded where and when. However I can't find the documentation on this. Googling for 'python PYTHONPATH' give me a bunch of stuff about setting the pythonpath for a specific app or about pythonpath itself but not the whole range of options as detailed above. However, I'd like more documentation about search paths, module loading and the like - does anyone know where I can find this? Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From peter at engcorp.com Mon Jul 25 11:03:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 11:03:45 -0400 Subject: Problem loading a file of words In-Reply-To: <1122302368.508836.215150@f14g2000cwb.googlegroups.com> References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> <1122298053.790180.292810@g43g2000cwa.googlegroups.com> <1122302368.508836.215150@f14g2000cwb.googlegroups.com> Message-ID: teoryn wrote: > I changed to using line = line.strip() instead of line = line [:-1] in > the original and it it worked. Just to be clear, these don't do nearly the same thing in general, though in your specific case they might appear similar. The line[:-1] idiom says 'return a string which is a copy of the original but with the last character, if any, removed, regardless of what character it is'. The line.strip() idiom says 'return a string with all whitespace characters removed from the end *and* start of the string'. In certain cases, you might reasonably prefer .rstrip() (which removes only from the right-hand side, or end), or even something like .rstrip('\n') which would remove only newlines from the end. -Peter From http Sun Jul 31 03:23:38 2005 From: http (Paul Rubin) Date: 31 Jul 2005 00:23:38 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> Message-ID: <7x3bpve8w5.fsf@ruckus.brouhaha.com> zen19725 at zen.co.uk (phil hunt) writes: > What you say Pythonic, what do you mean? And how do you rate > Tkinter, PyGtk, PyQt/PyKDE, wxWindows for "Pythonicness"? Tkinter is not very Pythonic because it's sort of a Frankenstein hybrid of Python and Tcl, but at least it's there and it more or less works. The others are non-Pythonic because they're not included in the standard distro and therefore the Pythonic "use the included batteries" tenet says to use Tkinter despite its flaws. From jabel at plus.net Tue Jul 12 10:16:48 2005 From: jabel at plus.net (John Abel) Date: Tue, 12 Jul 2005 15:16:48 +0100 Subject: Missing Something Simple In-Reply-To: <11f99613a4f2a4c64f8055e060b8e965@upf.edu> References: <42D3C920.2000808@plus.net> <11f99613a4f2a4c64f8055e060b8e965@upf.edu> Message-ID: <42D3D0D0.9020604@plus.net> harold fellermann wrote: >Hi, > > > >>I have a list of variables, which I am iterating over. I need to set >>the value of each variable. My code looks like: >> >>varList = [ varOne, varTwo, varThree, varFour ] >> >>for indivVar in varList: >> indivVar = returnVarFromFunction() >> >>However, none of the variables in the list are being set. >> >> > >You only change the value of the local variable in the body >of the for loop. it has no effect on the list. you could do e.g. > >varList = [vorOne,varTwo,varThree,varFour] >for i in len(varList) : > varList[i] = returnVarFromFunction() > >However, as in this example the former list values are not used anyway, >you could just write: > >varList = [ returnVarFromFunction for i varList ] > > >cheers, > >- harold - > >-- >Tages Arbeit, abends G?ste, >saure Wochen, frohe Feste! >-- Johann Wolfgang v. Goethe > > > The problem I have, is the variables are referenced elsewhere. They have been declared before being used in the list. Basically, I'm after the Python way of using deferencing. J From Scott.Daniels at Acm.Org Fri Jul 1 14:42:01 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 01 Jul 2005 11:42:01 -0700 Subject: map vs. list-comprehension In-Reply-To: References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: <42c586d1$1@nntp0.pdx.net> Roy Smith wrote: > Look at what happened to C when it mutated into C++. In isolation, most of > the features of C++ seem like good ideas. Taken together, it's a huge > hairy mess that most people only understand increasingly larger subsets of. > Fred Brooks called it the second system syndrome. If you read "The Design and Evolution of C++" by Stroustrupp, you can see how most of current C++ is a direct result of its initial design requirements, not an aglomeration of features, each of which is a "good idea." I take from the resulting big hairy mess that the design goals themselves are at fault for the big hairy mess. --Scott David Daniels Scott.Daniels at Acm.Org From apoco at cox.net Sat Jul 9 21:15:55 2005 From: apoco at cox.net (Jacob Page) Date: Sat, 09 Jul 2005 18:15:55 -0700 Subject: Python Module Exposure In-Reply-To: <1120934851.208175.19180@f14g2000cwb.googlegroups.com> References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> <1120934851.208175.19180@f14g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > "Jacob Page" wrote: > >>I think I will keep Interval exposed. It sort of raises a bunch of >>hard-to-answer design questions having two class interfaces, though. >>For example, would Interval.between(2, 3) + Interval.between(5, 7) raise >>an error (as it currently does) because the intervals are disjoint or >>yield an IntervalSet, or should it not even be implemented? How about >>subtraction, xoring, and anding? An exposed class should have a more >>complete interface. >> >>I think that IntervalSet.between(5, 7) | IntervalSet.between(2, 3) is >>more intuitive than IntervalSet(Interval.between(5, 7), >>Interval.between(2, 3)), but I can understand the reverse. I think I'll >>just support both. > > As I see it, there are two main options you have: > > 1. Keep Intervals immutable and pass all the responsibility of > combining them to IntervalSet. In this case Interval.__add__ would have > to go. This is simple to implement, but it's probably not the most > convenient to the user. > > 2. Give Interval the same interface with IntervalSet, at least as far > as interval combinations are concerned, so that Interval.between(2,3) | > Interval.greaterThan(7) returns an IntervalSet. Apart from being user > friendlier, an extra benefit is that you don't have to support > factories for IntervalSets, so I am more in favor of this option. I selected option one; Intervals are immutable. However, this doesn't mean that __add__ has to go, as that function has no side-effects. The reason I chose option one was because it's uncommon for a mathematical operation on two objects to return a different type altogether. > Another hard design problem is how to combine intervals when > inheritance comes to play. Say that you have FrozenInterval and > FrozenIntervalSet subclasses. What should "Interval.between(2,3) | > FrozenInterval.greaterThan(7)" return ? For now, operations will return mutable instances. They can always be frozen later if needs be. From roccomoretti at hotpop.com Wed Jul 6 10:28:53 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 06 Jul 2005 09:28:53 -0500 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <1120635954.442101.99920@g47g2000cwa.googlegroups.com> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> <1120635954.442101.99920@g47g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > seberino at spawar.navy.mil wrote: > >>The problem is that questions like 'What lang is fastest to develop >>in?' >>are hard to answer definitively. > > > FWIW, Google's answer to that question is C++, Java, and Python. For > any given problem, any of the three are acceptable. Each programmer or > engineering team gets to decide based on his or her language > expertise.* Actually, Google's answer to that question is something called "ILOG CPLEX", followed by Visual Basic, English as a second language, PHP, and "Holt Software Associates". ;-) http://www.google.com/search?hl=en&q=What+language+is+fastest+to+develop+in%3F&btnG=Google+Search Given this finding, I'm not sure I should put much weight into Google search results anymore ... From xiyou.wangcong at gmail.com Mon Jul 18 22:24:30 2005 From: xiyou.wangcong at gmail.com (Cong Wang) Date: 18 Jul 2005 19:24:30 -0700 Subject: Xah's edu corner: on Microsoft hatred In-Reply-To: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: <1121739870.261503.66830@g43g2000cwa.googlegroups.com> M$ is evil! From gherron at islandtraining.com Tue Jul 12 15:35:51 2005 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 12 Jul 2005 12:35:51 -0700 Subject: Slicing every element of a list In-Reply-To: <8025cc1305071212173f030365@mail.gmail.com> References: <8025cc1305071212173f030365@mail.gmail.com> Message-ID: <42D41B97.4020909@islandtraining.com> Alex Dempsey wrote: >Recently I tried to slice every element of a list of strings. First I tried: > >f = open("export.xls", "r") >lines = f.readlines() > >for line in lines: > line = line[1:-5] > line = line.split('\"\t\"') > > This, in fact, did do the operation you expected, but after creating the new value and assigning it to line, you promptly threw it away. (Because the loop then went back to the top and (re)assigned the next thing in lines to line wiping out your nicely sliced computation in lines.) You need to *do* something with the value in line before you end the loop -- but what? >This went without returning any errors, but nothing was sliced or >split. Next I tried: > >for i in range(len(lines)): > lines[i] = lines[i][1:-5] > lines[i] = lines[i].split('\"\t\"') > >This of course worked, but why didn't the first one work. Further why >didn't the first one return an error? > > Dr. Gary Herron Digipen Institute of Technology From gsakkis at rutgers.edu Fri Jul 22 19:31:49 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 22 Jul 2005 19:31:49 -0400 Subject: Something that Perl can do that Python can't? References: <1122064588.174698.153220@g43g2000cwa.googlegroups.com> <1122066437.870669.58990@z14g2000cwz.googlegroups.com> Message-ID: <1122075118.0b31951500161d44c25956929e7b3dd8@teranews> "Dr. Who" wrote in message news:1122066437.870669.58990 at z14g2000cwz.googlegroups.com... > Well, I finally managed to solve it myself by looking at some code. > The solution in Python is a little non-intuitive but this is how to get > it: > > while 1: > line = stdout.readline() > if not line: > break > print 'LINE:', line, > > If anyone can do it the more Pythonic way with some sort of iteration > over stdout, please let me know. > > Jeff You can use the sentinel form of iter(): for line in iter(stdout.readline, ''): print 'LINE:', line, George From sjmachin at lexicon.net Sun Jul 31 17:06:39 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 01 Aug 2005 07:06:39 +1000 Subject: Enumerate registered codecs In-Reply-To: <3l49j2F10qginU1@individual.net> References: <3l49j2F10qginU1@individual.net> Message-ID: <42ed3d5e$1@news.eftel.com> Paul Watson wrote: > I see the list of standard encodings in Python 2.4.1 documentation > section 4.9.2. > > Is there a method to enumerate the registered codecs at runtime? This has been asked before, within the last couple of months AFAIR. Use Google to search for codec(s) in this newsgroup in Google groups. Basically the answer was no. What's your use case? From steve at REMOVETHIScyber.com.au Sat Jul 23 22:42:53 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 12:42:53 +1000 Subject: tuple to string? References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> Message-ID: On Sat, 23 Jul 2005 23:31:04 +1000, John Machin wrote: >>>You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-) >> >> >> Ah, ok. Didn't want to lookup the precedence rules... > > > Look up the precedence rules? Are you aware of any language where * / > and % _don't_ have the same precedence?? Do languages like Pascal that don't have string formatting expressions, or use the % operator, count? How about languages like Forth that don't have precedence rules at all, unless "first come, first served" is a precedence rule? I'm not being academic here. I have used both these languages extensively, admittedly many years ago. -- Steven. From cam.ac.uk at mh391.invalid Fri Jul 22 11:15:14 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 16:15:14 +0100 Subject: Iterators from urllib2 In-Reply-To: References: Message-ID: Joshua Ginsberg wrote: > I'm a bit baffled by something... > > In a script I wrote, I have defined a function that runs > urllib2.urlopen() on a urllib2.Request object and returns the file-like > object. The code that calls this function attempts to build a > csv.DictReader object based on that file-like object, but an error is > thrown saying the file-like object is not an iterator. > > I could have sworn urllib2.urlopen returned an iterator, so I tested: > > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import urllib2 > >>> r = urllib2.Request('http://www.google.com') > >>> ifs = urllib2.urlopen(r) > >>> dir(ifs) > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > 'fileno', 'fp', 'geturl', 'headers', 'info', 'next', 'read', > 'readline', 'readlines', 'url'] > > Yep. But what about in my code? I modify my code to print dir(ifs) > before creating the DictReader... > > ['__doc__', '__init__', '__module__', '__repr__', 'close', 'fp', > 'geturl', 'headers', 'info', 'read', 'readline', 'url'] > Traceback (most recent call last): > File "CSVParser.py", line 144, in ? > print parseQHost(circuits[cktname], cktname) > File "CSVParser.py", line 126, in parseQHost > r = csv.DictReader(ifs, fieldlist) > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/csv.py", line 100, in __init__ > self.reader = reader(f, dialect, *args) > TypeError: argument 1 must be an iterator > > Whoa! Where did the __iter__, readlines, and next attributes go? Ideas? Works for me on Python 2.4.1. -- Michael Hoffman From rrr at ronadam.com Wed Jul 6 12:10:16 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 16:10:16 GMT Subject: Use cases for del In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Wed, 06 Jul 2005 10:00:02 -0400, Jp Calderone wrote: > > >>On Wed, 06 Jul 2005 09:45:56 -0400, Peter Hansen wrote: >> >>>Tom Anderson wrote: >>> >>>>How about just getting rid of del? Removal from collections could be >>>>done with a method call, and i'm not convinced that deleting variables >>>>is something we really need to be able to do (most other languages >>>>manage without it). >>> >>>Arguing the case for del: how would I, in doing automated testing, >>>ensure that I've returned everything to a "clean" starting point in all >>>cases if I can't delete variables? Sometimes a global is the simplest >>>way to do something... how do I delete a global if not with "del"? >>> >> >>Unless you are actually relying on the global name not being defined, "someGlobal = None" would seem to do just fine. >> >>Relying on the global name not being defined seems like an edge case. > > > Er, there is a lot of difference between a name not existing and it being > set to None. Yes, they are not currently the same thing. But what if assigning a name to None actually unbound it's name? And accessing an undefined name returned None instead of a NameError? Using an undefined name in most places will still generate some sort of an None type error. I think the biggest drawback to this second suggestion is that we would have to test for None in places where it would matter, but that's probably a good thing and enables checking if a variable exists without using a try-except. $ cat mymodule2.py # define some temporary names a, b, c, d, e, f = 1, 2, 3, 4, 5, 6 # do some work result = a+b+c+d*e**f # delete the temp variables a = b = c = d = e = f = None # possibly unbind names This would work if None unbound names. > It is bad enough that from module import * can over-write your variables > with the modules' variables, but for it to do so with DELETED variables is > unforgivable. Yes, I agree using None as an alternative to delete currently is unacceptable. Cheers, Ron From bokr at oz.net Sun Jul 10 22:58:29 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Jul 2005 02:58:29 GMT Subject: Cat and Mouse (wes Re: Efficiency of using long integers to hold bitmaps) References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> <42D1A678.1040705@v.loewis.de> Message-ID: <42d1dc75.342192997@news.oz.net> On Sun, 10 Jul 2005 19:30:58 -0400, "Terry Reedy" wrote: > >""Martin v. L?wis"" wrote in message >news:42D1A678.1040705 at v.loewis.de... >> Right. OTOH, I notice a frequent game of Katze und Maus (cat and mouse?) > >Yes, apparently with the same idiomatic meaning, as you decribe the game >here perfectly. > I think you are right about some game happening, but I'm not sure it's cat and mouse. To me, an incomplete question feels like an invitation to play "20 questions" regarding what the real problem is. So I get a little annoyed, and often just bypass the post. If I answer, the residual annoyance sometimes leads me to withhold my best guess, and complain instead. Hence probably the cat and mouse impression. Not very big of me, but OTOH a think a bit of a nudge towards better questions is not a bad thing. OTO3H, maybe I should just silently pass up 20-questions invitations and not pollute this pleasant space with perfumes of annoyance (since however diffuse, they are apparently pungent enough for some to notice ;-) Regards, Bengt Richter From zen19725 at zen.co.uk Sat Jul 30 09:19:13 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sat, 30 Jul 2005 14:19:13 +0100 Subject: [path-PEP] Path inherits from basestring again References: Message-ID: On Fri, 29 Jul 2005 14:48:55 +1200, Tony Meyer wrote: > >Would you really choose this: > > p = Path() / "build" / "a" / "very" / "very" / "long" / "path" > >Over this: > > p = Path(os.path.join("build", "a", "very", "very", "long", "path")) Or have the constructor accept multiple arguments. >? A saving of six characters, and the second one is a lot clearer. If >there was a os.path.joinPath (or whatever name) function that returned a >Path object rather than a string, then you'd get: > > p = joinPath("build", "a", "very", "very", "long", "path") Indeed. I have a little function I've written called normalizePath(). It expands users ("~" and "~someuser"), does os.path.join(), then gets the absolute path (os.path.abspath()) of the result. The code is trivial: def normalizePath(p, *pathParts): """ Normalize a file path, by expanding the user name and getting the absolute path.. @param p [string] = a path to a file or directory @param pathParts [list of string] = optional path parts @return [string] = the same path, normalized """ p1 = os.path.abspath(os.path.expanduser(p)) if len(pathParts)>0: allPathParts = [ p1 ] allPathParts.extend(pathParts) p1 = os.path.join(*allPathParts) p2 = os.path.abspath(p1) return p2 normalisePath=normalizePath # alternate spelling join=normalizePath # it works like os.path.join, but better To be honest I don't see the point of having a Path class. That's the way Java does it, and I find path handling in Java to be a lot more of a hassle than in Python. (Actually, most things are more of a hassle in Java, but that's another story). -- Email: zen19725 at zen dot co dot uk From zyqnews at 163.net Sun Jul 10 11:44:00 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 10 Jul 2005 08:44:00 -0700 Subject: PyArg_ParseTuple help Message-ID: <1121010240.884978.119330@f14g2000cwb.googlegroups.com> hello all, how to parse the arguments of a c function with PyArg_ParseTuple? The prototype of the c function is : int func(unsigned char * in , int inlen, unsigned char * v, unsigned char * out, int * outlen); The problem is , when the func returns, there will be results in out and outlen. Is the following format is correct? PyObject* wrap_func(PyObject* self, PyObject* args) { unsigned char *in; int inlen; unsigned char *v; unsigned char *out; int outlen; PyArg_ParseTuple(args, "s|i|s|s|i", &in, &inlen, &v, &out, &outlen); result = func(in, inlen, v, out, &outlen);// notice out and &outlen return Py_BuildValue("i", result); } Thanks From jstroud at mbi.ucla.edu Sat Jul 30 23:29:34 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 30 Jul 2005 20:29:34 -0700 Subject: Dabo in 30 seconds? In-Reply-To: <20050730171613.1839738924.EP@zomething.com> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050730171613.1839738924.EP@zomething.com> Message-ID: <200507302029.34011.jstroud@mbi.ucla.edu> On Saturday 30 July 2005 06:16 pm, EP wrote: > Ed Leafe wrote in response to the "Python vs. Access VBA" thread: > > You might want to look at Dabo, which is a database application > > framework for Python. In about 30 seconds you can create an application > > that queries a database, displays the results, and allows for > > editing/updating/inserting/deleting records. > > This is a nice pitch. Can you provide simple, example code that does this? > > As a non-professional programmer (I write to create my own business tools, > and for the enjoyment, but no one pays for my code) the ability to generate > quick db apps like this would constitute a real win, even if the 30 seconds > is a "Guido 30 seconds" and it takes me 5 minutes (which might > underestimate Guido by some magnitudes). I am going to go ahead and throw out Dabo with all of the others that claim quick development of an application. You try them and then you get bugs, bugs, bugs. Or they don't compile without 16000 dependencies. Forget it. My advice is to choose something, one thing, that is REAL standard, and in the standard library (e.g. Tkinter). And go for it. Learn it inside and out--it will always be there for you. It is the green, green grass of home, not that greener grass on the other side of the hill. Don't listen to the guys that says this one is crap or that one isn't. Dropping one and learning another is just pain. I think this is a developer trick, to keep you at war with yourself. The more you have internal conflict the more you will be looking for an App framework to solve your inner problems, and that keeps these guys in business--the business of wrecking souls. Go with yourself. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From jeremy at emperorlinux.com Thu Jul 28 09:15:51 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Thu, 28 Jul 2005 09:15:51 -0400 Subject: Trigger pygtk drawingarea redraw In-Reply-To: <1122544342.581358.274980@g43g2000cwa.googlegroups.com> References: <1122544342.581358.274980@g43g2000cwa.googlegroups.com> Message-ID: <1122556551.4061.1.camel@localhost.localdomain> Call the gtk.Widget method queue_draw(); if you derive from DrawingArea then simply: self.queue_draw() Of if the DrawingArea is some kind of "has-a" member: self.DrawableThing.queue_draw() On Thu, 2005-07-28 at 02:52 -0700, ch424 wrote: > Hi, > > Does anybody know the fastest way to trigger a DrawingArea redaw in > pygtk? At the moment, I'm using a bit of a hack: > > def redraw(self): > self.area.hide() > self.area.show() > > Is there a better way to trigger a redraw? This causes flickering when > the window gets bigger than 400x400 pixels, which is a nuisance... > there must be a better way of clearing the area and letting it redraw > itself? > > > Many thanks for any help, > > Alex > From ncoghlan at gmail.com Fri Jul 29 20:19:52 2005 From: ncoghlan at gmail.com (NickC) Date: 29 Jul 2005 17:19:52 -0700 Subject: Path inherits from basestring again References: Message-ID: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> [Re: alternatives to overloading '/'] Is there a reason the Path constructor is limited to a single argument? If it allowed multiple arguments, the following would seem very straightforward: p = Path(somePath, user.getFolder(), 'archive', oldPath + ".bak") I'm usually not much of a purist, but C++ has convinced me that overloading an operator to mean something entirely unrelated to its mathematical meaning can be very unwise. Regards, Nick C. From me at privacy.net Tue Jul 19 08:46:49 2005 From: me at privacy.net (Admin) Date: Tue, 19 Jul 2005 09:46:49 -0300 Subject: How to send a query to the browser from time to time? Message-ID: I am creating a chat application like Messenger for the web (using the browser) and I'm wondering if there is a way to receive new messages from time to time from the server other than refreshing the page each 5 sec. If there were a way to have the server-side application send new messages to the browser this would be awesome because it would save dramatically on bandwidth. The application would consume bandwidth only when there are new messages. There would be no communication client-server until people write a new message. Do you know if it's possible? -- Thanks, Admin. Want to buy me a book? http://tinyurl.com/78xzb :) From onurb at xiludom.gro Thu Jul 21 04:59:45 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 21 Jul 2005 10:59:45 +0200 Subject: Couple quick questions from a Python Noob In-Reply-To: <1121934168.143332.111100@f14g2000cwb.googlegroups.com> References: <1121934168.143332.111100@f14g2000cwb.googlegroups.com> Message-ID: <42df6403$0$7310$636a15ce@news.free.fr> digitalsubjunctive at gmail.com wrote: > Hey, I just started on Python and have a few questions I couldn't find > answers to on the Python site or it's tutorial. > > 1. I notice a few "compiled python" files (indicated by reddish snake > icons), I thought Python didn't need to be compiled? This is my first > venture into programming, but if it doesn't need to be compiled why > compile it? Just like Java, the Python interpreter runs python byte-code. The Python compiler compile Python source code into Python byte-code. Now the difference with Java is that you don't have to manually call the compiler - the interpreter will do it for you if and when needed. If you don't know what 'byte-code' is, it's just like a machine language (op-codes and the like) for a processor that doesn't exists - in fact this 'processor' is the interpreter (or 'Virtual Machine') itself. The main purpose is to have something that execute faster than purely interpreted languages (since parsing is already done), and is still portable between platforms (which is not that much important with Python, since we usually distribute the source files...). > 2. What is a .pwy file? (isn't that .pyw ?) It's a Windows-only stuff that avoid the DOS shell window to be opened when executing the script. > 3. I want to save my first few programs as .exe files so I can show > them off to all my leet friends. '.exe' files are Windows-specific. Python doesn't handle this out of the box. But there are programs like py2exe (and others, don't remember their name) that 'freeze' your script, the interpreter and all needed librairies in a .exe. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aisaac0 at verizon.net Wed Jul 27 14:32:55 2005 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 27 Jul 2005 18:32:55 GMT Subject: can list comprehensions replace map? Message-ID: Newbie question: I have been generally open to the proposal that list comprehensions should replace 'map', but I ran into a need for something like map(None,x,y) when len(x)>len(y). I cannot it seems use 'zip' because I'll lose info from x. How do I do this as a list comprehension? (Or, more generally, what is the best way to do this without 'map'?) Thanks, Alan Isaac From dave at boost-consulting.com Wed Jul 6 18:11:14 2005 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 06 Jul 2005 18:11:14 -0400 Subject: Compatibility of recent GCC/Python versions Message-ID: Recently people testing Boost.Python with GCC on Linux have reported that the extensions being tested have to be compiled with exactly the same version of GCC as the Python they're being loaded into, or they get mysterious crashes. That doesn't correspond to my past experience; it has always been true that, as long as the compiler used to build Python and the one used to build the extension have compatible 'C' ABIs, we've been okay. Yes, if you were going to pass types like FILE* across the Python/C API, then you additionally need to be sure that the two compilers are using the same 'C' library. That said, none of the Boost.Python tests do that. I'm wondering if there has been a well-known recent change either in Python or GCC that would account for these new reports. Any relevant information would be appreciated. Thanks, -- Dave Abrahams Boost Consulting www.boost-consulting.com From cliff at develix.com Sun Jul 31 15:24:54 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 12:24:54 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <8664uqhkfj.fsf@bhuda.mired.org> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <8664uqhkfj.fsf@bhuda.mired.org> Message-ID: <1122837895.19618.101.camel@localhost.localdomain> On Sun, 2005-07-31 at 14:58 -0400, Mike Meyer wrote: > And what do I use to bundle my application for Unix? Most of the > things I build get installed on Unix servers. You install GUI apps on Unix *servers*? Regardless, when you say "Unix", what do you mean? You may as well say "OS" as this term has little meaning. Linux (which flavor)? BSD? SCO? HPUX? OS/X? Minix? Whichever way, I suspect that a bit of distutils hacking would solve your problem. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From fdeserres at gmx.net Tue Jul 5 07:28:54 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Tue, 05 Jul 2005 13:28:54 +0200 Subject: (Win32 API) callback to Python, threading hiccups Message-ID: <42CA6EF6.1020308@gmx.net> Hiho, could somebody please enlighten me about the mechanics of C callbacks to Python? My domain is more specifically callbacks from the win32 API, but I'm not sure that's where the problem lies. Here's a description... I want a callback-based MIDI input/processing, so PortMidi was not an alternative. I have written a C extension module that links to the mmsys MIDI API. I separated the win32-dependant code from the Python extension code, so a) the module interface is system-neutral, b) the implementation can be tested (re-used) outside of Python. So, that code is tested OK, but it might be useful to sketch it's design: - as you may know, the MIDI input on win32 is already managed thru a callback mechanism; the driver calls back your program with data buffers - yet, I don't call directly into Python from the callback, since some restrictions apply on what system calls you can make from there, and I don't know what Python's interpreter / scripts might call. - so, on callback, I create a new thread, after checking that the previous one has returned already (WaitOnSingleObject(mythread)) so we only have one thread involved. - this is this thread that calls the user callback, yet this callback isn't yet a Python callable, we're still in native C code. - on the side of the extension module now, I merely copied the callback example from the Python/C API doc, and added GIL management around the call: static PyObject * my_callback = NULL; //this gets fixed by a setCallback() func static void external_callback(const MidiData * const data) { if (my_callback && (my_callback != Py_None)) { if (! data) { PyErr_SetString(PyExc_IndexError, getLastErrorMessage()); } else { PyObject * arglist = NULL; PyObject * result = NULL; arglist = Py_BuildValue("(i,i,s#)", data->deviceIndex, data->timestamp, data->buffer, data->size);// 0, 0, "test", 4);// PyGILState_STATE gil = PyGILState_Ensure(); result = PyEval_CallObject(my_callback, arglist); PyGILState_Release(gil); Py_DECREF(arglist); Py_DECREF(result); } } } - this one above is what is actually passed as callback to the 'native' C part. So, here's what (I presume) happens: 1. the driver calls into my C code 2. my C code spawns a thread that calls into the extension 3. the extension calls into Python, after acquiring the GIL Now, here's the hiccup: inside a Python script, anytime a Python object is accessed by both the (Python) callback and the main program, I get a GPF :/ You bet I tried to use locks, Queues and whatnot, but nothing will do, it seems I get protection faults on accessing... thread exclusion objects. Yet, there is a way where it works seamlessly: it's when the __main__ actually spawns a threading.Thread to access the shared object. Hence I am lost. This works: def input_callback(msg): midiio.send(msg) ##MIDI thru, a call into my extension that wraps the implementation call with BEGIN_ALLOW_THREADS and END_... __main__: raw_input() This results in GPF as soon as the callback is fired: tape = Queue.Queue() def input_callback(msg): tape.put(msg) __main__: while True: print tape.get() This works like a charm: tape = Queue.Queue() def input_callback(msg): tape.put(msg) def job(): while True: print tape.get() __main__: t = threading.Thread(target = job) t.start() raw_input() Note that I also get a GPF in the later case if I stop the program with KeyInterrupt, but I guess it's something I'll look into afterwards... While I can think of hiding away the added threading within a wrapper module, I won't sleep well untill I figure out what's really happening. Could someone save my precious and already sparse sleeping time, by pointing me to what I'm missing here? WinXP SP1 Python 2.4.1 MinGW GCC 3.4.2 TIA, Francois De Serres From gsakkis at rutgers.edu Mon Jul 4 16:12:56 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 4 Jul 2005 13:12:56 -0700 Subject: Existance of of variable References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> Message-ID: <1120507976.901769.141170@o13g2000cwo.googlegroups.com> Hi Josiah, > Hello. I am very new to Python, and have been unable to figure out how > to check if a variable exists or not. In the following code I have made > a kludge that works, but I think that it would be clearer to check if > closest exists and not have to initialize it in the first place. How is > that check done? > > The following code finds the closest place to a position and rejects > places that are too far away. > > dist = 1e9 > closest = -1 > > for n,p in galaxy.places.iteritems(): > dif = p.pos - pos > len = dif.len() > if len < dist and len < 10.0/self.zoom: > dist = len > closest = p > > if closest != -1: > self.sel = [closest.name] I would write it like this: def setClosest(self, pos, galaxy): minDist, closestPlace = min([((place.pos-pos).len(), place) for place in galaxy.places.itervalues()]) if minDist < 10.0/self.zoom: self.sel = [closestPlace.name] else: raise RuntimeError("No place close enough") > I also have a few other questions to tack on if you don't mind. I am > setting dist to 1e9, because that is a larger value than any of the > places in the galaxy will be far away. Is there a better way to > initialize dist so that it is impossible for this to fail? For example, > would setting dist to infinity work, and how is that done? Here's a safer way; it doesn't rely on what the maximum and minimum number is in a specific platform: Smallest = type("Smallest", (object,), {'__cmp__' : lambda self,other: self is not other and -1 or 0})() Largest = type("Largest", (object,), {'__cmp__' : lambda self,other: self is not other and 1 or 0})() assert Smallest == Smallest < -1e300 < 0 < 1e300 < Largest == Largest assert Largest == Largest > 1e300 > 0 > -1e300 > Smallest == Smallest Strictly speaking, Smallest and Largest should be singletons, to protect you from stupid mistakes such as making copies of them. > Extending my existance checking question, how does one check what type > a variable has? >>> type(3) >>> type(3.0) Almost in all cases though you should prefer "isinstance(variable, sometype)" instead of "type(variable) == sometype", so that it doesn't break for subclasses of sometype. > Thanks for your help! > > -- Josiah Regards, George From fraca7 at free.fr Thu Jul 21 06:42:02 2005 From: fraca7 at free.fr (fraca7) Date: Thu, 21 Jul 2005 12:42:02 +0200 Subject: gdb python C API In-Reply-To: References: Message-ID: <42df7bfa$0$4724$636a15ce@news.free.fr> derrick a ?crit : > are there any tools / methods that others have used to get what line of > the python script is being executed while running in gdb? or if it would > actually show me the source python script (instead of the the python c > source) that would help. I don't think so, but when having a memory problem I usually find valgrind very useful. http://valgrind.org/ HTH From auch-ich-m at g-kein-spam.com Sat Jul 23 17:22:52 2005 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Sat, 23 Jul 2005 23:22:52 +0200 Subject: Lists & "pointers" References: <42e25ac2$1@griseus.its.uu.se> <1122145436.618503.114220@g49g2000cwa.googlegroups.com> Message-ID: <1649768.gFoggpEj44@news.perlig.de> * Kay Schluehr wrote: > you might initialize self.storedAttr with empty dicts and fill them > later: > > self.soredAttr = [{}]*10 > for entry in self.storedAttr: > entry.update(self.drawAttr) As a matter of fact, you're doing the same ;-) In [1]: x = [{}] * 10 In [2]: x[0]['a'] = 1 In [3]: x[1]['b'] = 2 In [4]: x Out[4]: [{'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}] nd -- "Umfassendes Werk (auch fuer Umsteiger vom Apache 1.3)" -- aus einer Rezension From cjw at sympatico.ca Thu Jul 28 16:07:47 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 28 Jul 2005 16:07:47 -0400 Subject: how to get function signature In-Reply-To: References: <1122532836.853488.286030@g14g2000cwa.googlegroups.com> Message-ID: Robert Kern wrote: > upadhyay at gmail.com wrote: > >> Hi, >> >> I was working on a dir like function that gives more information than >> the usual dir, but I am not satisfied with the way I get function >> arguments for callable members of an object. Take a look at it here: >> http://nerdierthanthou.nfshost.com/2005/07/mdir-for-python.html. I have >> seen PythonWin showing function arguments as tooltips, can anyone >> please let me know how to get it. > > > import inspect > PythonWin provides this capability for machines using Windows. Colin W. From peter at engcorp.com Fri Jul 29 07:58:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 07:58:16 -0400 Subject: os._exit vs. sys.exit In-Reply-To: References: <7a2dnSer5eC2BnTfRVn-sQ@comcast.com> Message-ID: Andrew Dalke wrote: > sys.exit() is identical to "raise SystemExit()". It raises a Python > exception which may be caught at a higher level in the program stack. And which *is* caught at the highest levels of threading.Thread objects (which Timer is based on). Exceptions raised (and caught or not) in a Thread do not have any effect on the main thread, and thus don't affect the interpreter as a whole. -Peter From sjmachin at lexicon.net Tue Jul 19 18:50:07 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Jul 2005 08:50:07 +1000 Subject: Documentation bug: Python console behaviour changed In-Reply-To: <1121777815.734892.40120@g49g2000cwa.googlegroups.com> References: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> <-I2dnSVstZw-ekHfRVn-rA@powergate.ca> <1121777815.734892.40120@g49g2000cwa.googlegroups.com> Message-ID: <42dd83a0@news.eftel.com> Kay Schluehr wrote: > > Peter Hansen schrieb: > >>Kay Schluehr wrote: >> >>>The documentation of the Python console behaviour is not correct >>>anymore for Python 2.4.1. At least for the Win2K system I'm working on >>>'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. >>> >>>The Python interpreter tells me instead: >>> >>> >>> >>>>>>quit >>> >>>'Use Ctrl-Z plus Return to exit.' >>> >>>Nah, 'Ctrl-Z' is now undo :-) >> >>Are you really using the console, started with the "Command Prompt" icon >>from the Start Menu (or some equivalent)? >>And are you sure you haven't >>installed something else that magically changed the behaviour of Ctrl-Z? >> >>(I get the documented behaviour with Python 2.4.1, under Win XP.) >> >>-Peter > > > Well, Peter, I indeed changed the system magically but yet it was not > Windows, but Python! In my description I told You that I installed > IPython and IPython requires the readline package. If I rename the > readline package ( e.g. _readline ) in the site-packages directory the > console behaves as expected. Otherwise it shows the termination > behaviour of IPython namely it shuts down with Ctrl-D. > > It's really sucking... > > Kay > It's readline that sucks. Python's behaviour has *NOT* changed. From max at alcyone.com Sun Jul 10 22:51:34 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 10 Jul 2005 19:51:34 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> Message-ID: Randy Howard wrote: > Out of curiosity, does anyone remember who 'jgs' refers to > above? A Google search for "ascii art jgs" shows it's Joan Stark. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The decree is the Sultan's; the mountains are ours. -- Dadaloglu From bdesth.quelquechose at free.quelquepart.fr Thu Jul 21 21:11:24 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 22 Jul 2005 03:11:24 +0200 Subject: problem with string In-Reply-To: <6bf5f7be.0507211518.1a9b0325@posting.google.com> References: <6bf5f7be.0507211518.1a9b0325@posting.google.com> Message-ID: <42e040d2$0$17083$626a14ce@news.free.fr> Tzanko Tzanev a ?crit : > hi :) > I need some help for this script > I have please take care of indentation when posting code. > -------------------- > cursor = conn.cursor() > cursor.execute("select * from playlist limit 5") > result = cursor.fetchall() > # iterate through resultset > playlist_txt = '' > for record in result: mp3id = record[0] mp3_title = record[1] mp3_artist = record[2] playlist_txt += mp3id + mp3_title + mp3_artist Err... what about: print "
\n".join([" - ".join(record[:3]) for record in result]) or : for record in result: print "%s - %s - %s
" % tuple(record[:3]) Anyway, avoid string concatenation in loop, prefer appending to a list and then str.join(): playlist = [] for record in result: playlist.append(record[0] + record[1] + record[2]) print "\n".join(playlist) Note that this is a very strange and complicated way to write: print "\n".join([''.join(rec) for rec[:3] in result]) And, finally, if you just want to check what's in your resultset: print result > #print mp3id , " - ", mp3_title , ' - ', mp3_artist , "
" > cursor.close() > conn.close() Since you're doing a fetchall(), you could (and should if you don't use em again) free your resources as soon as you've retrieved the resultset: cursor = conn.cursor() cursor.execute("select * from playlist limit 5") result = cursor.fetchall() cursor.close() conn.close() # now use the resultset... > ------------------ > #and want to print this out of "for record in result:" > print playlist_txt > > #but there is an error in > playlist_txt += mp3id + mp3_title + mp3_artist Are we supposed to guess what the error is ? Sorry, I'm not psychic enough. Please post the full traceback. (wild guess: mp3id is an integer ?) From anonymousnerd at gmail.com Sat Jul 2 02:15:19 2005 From: anonymousnerd at gmail.com (anonymousnerd at gmail.com) Date: 1 Jul 2005 23:15:19 -0700 Subject: Seeking IDE In-Reply-To: References: Message-ID: <1120284919.833100.140440@g14g2000cwa.googlegroups.com> If you are looking for a small and simple text editor that moonlights as an IDE, my suggestion would be SciTE(http://scintilla.org/SciTE.html). It has reasonable syntax highlighting and can run Python scripts if you press F5. From martin at v.loewis.de Mon Jul 11 18:50:53 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 12 Jul 2005 00:50:53 +0200 Subject: Extending and embedding Python In-Reply-To: References: Message-ID: <42d2f7ce$0$22160$9b622d9e@news.freenet.de> Tommy Nordgren wrote: > In order to correctly compile and link my Application, I need a OS > independent way to find compiler options and linker options necessary to > find header files and libraries. What methods should I use from > DistUtils for this purpose. I don't think distutils supports linking applications that embed Python, yet. It might be possible to write a distutils command for that purpose, but I'd advise against that. Instead, you should integrate the Python embedding into the build process you alread have (e.g. make, shell scripts, whatever). You can simplify the process by having a Python script compute all the necessary parameters. You find the configuration-specific information in distutils.sysconfig. HTH, Martin From bokr at oz.net Fri Jul 8 18:35:22 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 08 Jul 2005 22:35:22 GMT Subject: Legacy data parsing References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: <42cefd9b.154070802@news.oz.net> On 8 Jul 2005 11:31:14 -0700, "gov" wrote: >Hi, > >I've just started to learn programming and was told this was a good >place to ask questions :) > >Where I work, we receive large quantities of data which is currently >all printed on large, obsolete, dot matrix printers. This is a problem >because the replacement parts will not be available for much longer. > >So I'm trying to create a program which will capture the fixed width >text file data and convert as well as sort the data (there are several >different report types) into a different format which would allow it to >be printed normally, or viewed on a computer. > >I've been reading up on the Regular Expression module and ways in which >to manipulate strings however it has been difficult to think of a way >in which to extract an address. > >Here's an example of the raw text that I have to work with: > > >ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: >**************************** > >FOR/POUR AL/LA: 20 > CORR TYP: A1B 2C3 P:3 CHNGD/CHANG > LANG: E CONS/REGR: ####### > MRS XXX X XXXXXXX > ### XXXXXXXXX ST DD TYP: P:6 >CHNGD/CHANG > MONCTON NB LANG: E CONS/REGR: >####### > MRS XXX X XXXXXXX > ##### > #### > ###-###-# > >ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: >**************************** > >FOR/POUR AL/LA: 30 > BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG > LANG: E CONS/REGR: ####### > MISS XXXX XXXXX > ### XXXXXXXX ST > MONCTON NB > >EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: >*********** > >(the # = any number, and the X's are just regular text) >I would like to extract the address information, but the two different >text objects on the right hand side are difficult to remove. I think >it would be easier if I could just extract a fixed square of >information, but I don't have a clue as to how to go about it. > >If anyone could give me suggestions as to methods in sorting this type >of data, it would be appreciated. > If this is all fixed-width font characters and fixed record formats, you might get some ideas about extracting a "fixed square". I re-joined the strings of the fixed square with '\n'.join() to print it, but you could extract data from the lines in various ways with regexes and such. I used your data example and added some under the alternate header. (Not tested beyond what you see ;-) ----< legacy_data_parsing.py >--------------------------------------------------- data = """\ ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: **************************** FOR/POUR AL/LA: 20 CORR TYP: A1B 2C3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ####### MRS XXX X XXXXXXX ### XXXXXXXXX ST DD TYP: P:6 CHNGD/CHANG MONCTON NB LANG: E CONS/REGR: ####### MRS XXX X XXXXXXX ##### #### ###-###-# ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: **************************** FOR/POUR AL/LA: 30 BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ####### MISS XXXX XXXXX ### XXXXXXXX ST MONCTON NB EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: *********** 1 [Don't know what [<- 1,34 This is a box of 2 goes in this kind text with top/left 3 of record, but this character row/col 1,34 4 is some text to show and bottom/right at 4,62 ->] 5 how it might get 6 extracted] """ record_headers = [ """\ ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: """, """\ EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: """ ] import re recsplitter = re.compile('('+ '|'.join(map(re.escape,record_headers))+')') def extract_block(tl, br, data): lines = [s.ljust(br[1]+1) for s in data.splitlines()] return '\n'.join([line[tl[1]:br[1]+1] for line in lines[tl[0]:br[0]+1]]) for i, hdr_or_body in enumerate(recsplitter.split(data)): if i==0: print '='*10, 'file prefix', '='*30 data_type = '' elif i%2: print '='*10, 'record hdr', '='*30 data_type = hdr_or_body else: print '='*10, 'record data', '='*30 print hdr_or_body print '='*10 if not i%2 and data_type == record_headers[1]: # EARNINGS etc print '---- earnings record right block ----' print extract_block((1,34),(4,62), hdr_or_body) print '----' --------------------------------------------------------------------------------- Produces: [15:33] C:\pywk\clp>py24 legacy_data_parsing.py ========== file prefix ============================== ========== ========== record hdr ============================== ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: ========== ========== record data ============================== **************************** FOR/POUR AL/LA: 20 CORR TYP: A1B 2C3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ####### MRS XXX X XXXXXXX ### XXXXXXXXX ST DD TYP: P:6 CHNGD/CHANG MONCTON NB LANG: E CONS/REGR: ####### MRS XXX X XXXXXXX ##### #### ###-###-# ========== ========== record hdr ============================== ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: ========== ========== record data ============================== **************************** FOR/POUR AL/LA: 30 BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ####### MISS XXXX XXXXX ### XXXXXXXX ST MONCTON NB ========== ========== record hdr ============================== EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: ========== ========== record data ============================== *********** 1 [Don't know what [<- 1,34 This is a box of 2 goes in this kind text with top/left 3 of record, but this character row/col 1,34 4 is some text to show and bottom/right at 4,62 ->] 5 how it might get 6 extracted] ========== ---- earnings record right block ---- [<- 1,34 This is a box of text with top/left character row/col 1,34 and bottom/right at 4,62 ->] ---- HTH Regards, Bengt Richter From guettli at thomas-guettler.de Tue Jul 26 07:07:28 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 26 Jul 2005 13:07:28 +0200 Subject: regex problem References: Message-ID: Am Tue, 26 Jul 2005 09:57:23 +0000 schrieb Odd-R.: > Input is a string of four digit sequences, possibly > separated by a -, for instance like this > > "1234,2222-8888,4567," > > My regular expression is like this: > > rx1=re.compile(r"""\A(\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,)*\Z""") Hi, try it without \A and \Z import re rx1=re.compile(r"""(\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,)""") print rx1.findall("1234,2222-8888,4567,") # --> ['1234,', '2222-8888,', '4567,'] Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From twic at urchin.earth.li Wed Jul 6 09:42:52 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 6 Jul 2005 14:42:52 +0100 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: <86u0j8wv02.fsf@bhuda.mired.org> References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> <86u0j8wv02.fsf@bhuda.mired.org> Message-ID: On Tue, 5 Jul 2005, Mike Meyer wrote: > "seberino at spawar.navy.mil" writes: > >>> Well, his Viaweb company was founded in about '95, right? So he >>> probably just used Lisp because Python wasn't as well known yet. ;-) >> >> That is what I thought too. It makes sense but I wasn't sure. Still >> ain't. The problem is that questions like 'What lang is fastest to >> develop in?' are hard to answer definitively. > > True. You might start by asking which lets you write the fewest LOC, as > studies during the 70s showed that programmers tended to write the same > number of LOC/day, regardless of the language chosen. > > The problem with the LOC measurement is that the most productive days > are the ones where you refactor and eliminate a thousand LOC. That sort > of throws the whole thing off. As in: http://www.folklore.org/StoryView.py?project=Macintosh&story=Negative_2000_Lines_Of_Code.txt Perhaps the real question, then, is which language allows you to delete lines of code most quickly. tom -- find porn apricot From tim.peters at gmail.com Tue Jul 12 11:52:41 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 12 Jul 2005 11:52:41 -0400 Subject: Tricky Dictionary Question from newbie In-Reply-To: References: <3jftckFpvhv2U2@individual.net> Message-ID: <1f7befae05071208523df2032c@mail.gmail.com> [Peter Hansen] ... > I suppose I shouldn't blame setdefault() itself for being poorly named, No, you should blame Guido for that . > but it's confusing to me each time I see it in the above, because the > name doesn't emphasize that the value is being returned, and yet that > fact is arguably more important than the fact that a default is set! > > I can't think of a better name, though, although I might find "foo" less > confusing in the above context. :-) I wanted to call it getorset() -- so much so that even now I sometimes still type that instead! The "get" part reminds me that it's fetching a value, same as dict.get(key, default) -- "or set"'ing it too if there's not already a value to "get". If you have a fancy enough editor, you can teach it to replace setdefault by getorset whenever you type the former ;-) From rkern at ucsd.edu Fri Jul 1 01:08:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 22:08:36 -0700 Subject: Splitting string into dictionary In-Reply-To: <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> References: <59e9fd3a0506302121197c545a@mail.gmail.com> <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> Message-ID: David Pratt wrote: > I have string text with language text records that looks like this: > > 'en' | 'the brown cow' | 'fr' | 'la vache brun' > > Two or more language records can exist in each string (example above > shows 2 - but could contain more) > The second vertical line character in the example above is the record > break in the pattern (between 'cow' and 'fr') > > What is the shortest route to getting this into a dictionary like: > > {'en':'the brown cow','fr':'la vache brun'} > > The language code is always 2 lower case letters. > > Many thanks. translations = [x.strip(" '") for x in line.split('|')] d = {} for i in range(0, 2*len(translations), 2): d[translations[i]] = translations[i+1] -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From hancock at anansispaceworks.com Sat Jul 2 23:24:03 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 22:24:03 -0500 Subject: Python, mysql, floating point values question In-Reply-To: <21gec1lgopab3sjbhkh6m2amd51e1rcq1v@4ax.com> References: <43b72594050701154055297e73@mail.gmail.com> <21gec1lgopab3sjbhkh6m2amd51e1rcq1v@4ax.com> Message-ID: <200507022224.03285.hancock@anansispaceworks.com> On Saturday 02 July 2005 08:53 pm, Dennis Lee Bieber wrote: > On Sat, 2 Jul 2005 18:49:20 -0400, Christopher Kang > declaimed the following in comp.lang.python: > > I've been doing the epsilon comparisons, i had just hoped that to be a > > temporary solution. > > > Considering how often this has come up, I've sort of lost faith > in CS programs at colleges. Now, this might be an unfair statement as I > don't know if any of those bringing up the question ever had college CS > courses... Yeah, it's unfair. I would be seriously surprised if even half of the readers here majored in CS. I doubt even 1% actually learned about this floating point problem in a CS class. ISTM that anyone destined to major in CS would've figured this out long before that. I learned it when I was about 14, programming in Basic on a home computer, IIRC. I certainly had learned it from experience by the time I went to college. But who knows when someone here picked up programming? A lot of people learn it later in life, and Python is a good choice for that. And for that matter, some of the posters here have *been* 14. I suppose it's also worth mentioning that programming and CS aren't mostly about number-crunching anymore, so a lot of people never bother with floats. Which seems totally bizarre to me, since I cut my teeth on graphics and moved on to scientific programming, but there you are. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Tue Jul 19 13:43:28 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 20 Jul 2005 03:43:28 +1000 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <1121781747.6b5089eb6576a56f3b0851ea53fe69e0@teranews> <1121786998.7497.0.camel@athop1.ath.vt.edu> Message-ID: On Tue, 19 Jul 2005 11:29:58 -0400, rbt wrote: >> It should not really come as a shock that the same fellow who came up with a brilliant efficient way >> to generate all permutations (http://tinyurl.com/dnazs) is also in favor of goto. >> >> Coming next from rbt: "Pointer arithmetic in python ?". >> >> George >> >> > > I have moments of brilliance and moments of ignorance. You must admit > though, that was a unique way of generating permutations... how many > other people would have thought of that approach? It did solve my > problem ;) Sorry rbt, but your algorithm isn't unique, nor was it clever, and in fact your implementation wasn't very good even by the undemanding requirements of the algorithm. It is just a minor modification of bogosort (also known as "bozo-sort") algorithm: http://en.wikipedia.org/wiki/Bogosort I quote: "...bogosort is 'the archetypal perversely awful algorithm', one example of which is attempting to sort a deck of cards by repeatedly throwing the deck in the air, picking the cards up at random, and then testing whether the cards are in sorted order." Bogosort is nothing to be proud of, except as a joke. Put it this way: of all the many ways to generate a list of permutations, you managed to find perhaps the least efficient algorithm possible. This is especially ironic when you think back to your first question, which was how to generate the combinations most efficiently. -- Steven. From python at rcn.com Sat Jul 9 23:00:40 2005 From: python at rcn.com (Raymond Hettinger) Date: 9 Jul 2005 20:00:40 -0700 Subject: removing list comprehensions in Python 3.0 References: <1120919382.609886.62680@g14g2000cwa.googlegroups.com> <1120927567.463458.289770@g49g2000cwa.googlegroups.com> Message-ID: <1120964439.979945.238590@z14g2000cwz.googlegroups.com> [Raymond Hettinger] > > It is darned inconvenient to get an iterator when you really > > need a list, when you want to slice the result, when you want to see a > > few elements through repr(), and when you need to loop over the > > contents more than once. [George Sakkis] > Similar arguments can be given for dict comprehensions as well. You'll find that "lever" arguments carry little weight in Python language design (well, you did X in place Y so now you have to do it everywhere even if place Z lacks compelling use cases). For each variant, the balance is different. Yes, of course, list comprehensions have pros and cons similar to set comprehensions, dict comps, etc. However, there are marked differences in frequency of use cases, desirability of having an expanded form, implementation issues, varying degrees of convenience, etc. The utility and generality of genexps raises the bar quite high for these other forms. They would need to be darned frequent and have a superb performance advantage. Take it from the set() and deque() guy, we need set, dict, and deque comprehensions like we need a hole in the head. The constructor with a genexp does the trick just fine. Why the balance tips the other way for list comps is both subjective and subtle. I don't expect to convince you by a newsgroup post. Rather, I can communicate how one of the core developers perceives the issue. IMHO, the current design strikes an optimal balance. 'nuff said, Raymond From sjmachin at lexicon.net Sun Jul 31 22:39:37 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 01 Aug 2005 12:39:37 +1000 Subject: Determining method type given its string name presentation and itscorresponding object reference. In-Reply-To: References: <1122853524.374812.326580@g14g2000cwa.googlegroups.com> Message-ID: <42ed8b67@news.eftel.com> Terry Reedy wrote: > "Apple" wrote in message > news:1122853524.374812.326580 at g14g2000cwa.googlegroups.com... > >>Hi I am a bit new to python. I was wondering if there is a way to >>determine whether or not a given string is a member method of a given >>object: > > > Does callable(cls.attr) fit your needs? > or perhaps callable(getattr(obj, strg, None)) if the need is related to an unknown string which may be a callable attribute of an object whose class is unknown ... From steve at holdenweb.com Mon Jul 25 15:51:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Jul 2005 20:51:42 +0100 Subject: how to write a line in a text file In-Reply-To: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> References: <1122318776.101015.165300@g14g2000cwa.googlegroups.com> Message-ID: nephish at xit.net wrote: > Hey there, > kinda newbie question here. > i know how to read the lines of a txt file. > i know how to write a txt file. > > but how do i overwrite a line value with another value ? > > i mean, how do go to, say, line 3 of a text file and replace > what is written on line 3 with something else? > > thanks > <>< > You shouldn't try do "update in place" like that unless your file has fixed-length lines or records. Altering the length of an existing file isn't to be lightly undertaken, and even when possible will likely not be undertaken. The classic way to approach this problem is to read the file as input, processing its contents and writing a new file, which eventually replaces the original in a fairly complex dance of renaming and deletion. In Python you can use a text file's readlines() method to build a list of all the lines in a file. That makes it quite easy to change numbered lines. Having modified the file's content in memory you can then create a new file using the writelines() method of a new file. The trick is to avoid losing both the old and the new files when a low-probability crash occurs. Since you are newbile (?) I would advise against paranoia - write your code without worrying about error handling. You'll be pleased to know that when you start to take a serious interest in error handling Python has everything you'll need. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From davecook at nowhere.net Sat Jul 9 08:20:36 2005 From: davecook at nowhere.net (Dave Cook) Date: Sat, 09 Jul 2005 12:20:36 GMT Subject: pygtk does ... ? References: <9ZCdneC20ZwHIlPfRVn-jQ@telcove.net> Message-ID: On 2005-07-08, Thomas Bartkus wrote: > Why would I want to "import pygtk" with it's single function > "require(version)"? > What is it supposed to do? Where does it fit in? The only reason I can think of is to use pygtk.require, so you can specify which major version of pygtk you want to use, assuming you have multiple versions: import pygtk pygtk.require('2.0') import gtk Otherwise, you don't need to import pygtk, just gtk. Dave Cook From tim.golden at viacom-outdoor.co.uk Fri Jul 29 03:36:10 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 29 Jul 2005 08:36:10 +0100 Subject: [path-PEP] Path inherits from basestring again Message-ID: <9A28C052FF32734DACB0A288A3533991044D2164@vogbs009.gb.vo.local> [Tony Meyer] | | [Tim Golden] | > Well, I actually had some correspondence with Jason on this | > very subject a year or so ago: | [...] | > Obviously, I don't know how much weight Jason's original | > ideas have on the prepped-for-syslib module, but it does | > support what other people have been saying: that the Path | > should behave like a string where a string is expected. | | Was that the whole email? It certainly adds weight to '+' | having the normal | string behaviour, but it didn't really say anything about why | '/' should be | a shortcut for join. Do you know if Jason had any reasoning | for this other | than laziness ? | | =Tony.Meyer Well, he did add the following paragraph: For example: I haven't tried it, but I don't think the most obvious two-line fix will necessarily work. If you change __add__ to call os.path.join(), you'll likely get infinite recursion, because os.path.join() probably uses + to do its work. Of course this is pretty easy to work around; call it three lines. which might explain why he *didn't* use __add__ but doesn't explain whey he *did* use __div__. (There was more to the original email but that was more to do with some wild-eyed ideas I'd had about adding methods for file-locking and share-mounting to the path object). FWIW, my own feeling is that / is an awkward fit and relies for its ease-of-reading on the -- admittedly common but not universal -- use of that symbol as a path separator. I don't feel terribly strongly about it, but I don't tend to use it in my own code. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From nlebas at grignon.inra.fr Wed Jul 27 06:08:09 2005 From: nlebas at grignon.inra.fr (Nicolas Lebas) Date: Wed, 27 Jul 2005 12:08:09 +0200 Subject: getting Arrays and variables from R [fixed] In-Reply-To: <42E62AC0.9050201@grignon.inra.fr> References: <42E62AC0.9050201@grignon.inra.fr> Message-ID: <42E75D09.10900@grignon.inra.fr> Nicolas Lebas a ?crit : >hello, > >i don't know if this is the best list to send this question, but i'm >already trying to ask. > >I need to import variables from .RData files (arrays or variables). >I'm trying to use the rpy module, but without success beccause when i >try to access to a variable loaded from the .RData file i have a >segmentation fault ! > >This is what i'm doing : >- in R-projet, i create a .RData file with some variables : > > tab<-c(2,5,8,6) > > v<-0.5 > > save.image("file.RData") > >- in Python : > > from rpy import * > > r.load("file.RData") >['tab', '.Traceback', 'v'] > > r.tab >segmentation fault ! > >I don't understand very well what does python crash. > >If someone has an idea to solve my problem or to give me a method which >permit to import arrays and variables from .RData files with another module. > >Thanks > > Nicolas > > Finally, i found the solution with rpy. There is a bug in the python2.4-rpy_0.4.1 release, so you have to use instead of 'r.tab' command : r.get('tab') -- Nicolas Lebas INRA Unit? Mixte de Recherche INRA / INAPG "Environnement et Grandes Cultures" 78850 Thiverval - Grignon France T?l. +33 (0)1 30 81 55 55 (standard) Fax +33 (0)1 30 81 55 63 Site Web : www-egc.grignon.inra.fr From primero at fastwebnet.it Fri Jul 15 11:49:26 2005 From: primero at fastwebnet.it (Francesco Ciocchetti) Date: Fri, 15 Jul 2005 17:49:26 +0200 Subject: How to send broadcast message over network and collect all the IP address? In-Reply-To: References: Message-ID: <42D7DB06.1050907@fastwebnet.it> Sandeep Arya wrote: >Hello to all > >Well this is my first mail on this list. I am facing a problem associated >with collecting IP address on my network. > >What i thought is to send broadcast packet over the network and then >recieving back the reply from the computers and bridges connected to my >network and then adding their IP Address in a list. > >How this can be achieved? Say my computer on which application will run's IP >is 192.168.100.254 and subnetmask is 255.255.255.0 > >How to do this in core Python? > >Sandeep > >_________________________________________________________________ >7000 classifieds >http://www.sulekha.com/classifieds/cllist.aspx?nma=IN&ref=msn -Chennai, >Mumbai, Hyderabad Bangalore. > > > I'm leaving from office now so i can not give a more complete answer ... i would use an ARP Request to all network address on your network and check who answer. Check out libdnet (http://libdnet.sf.net) for a python module implementing networking funcions. bye Francesco From zen19725 at zen.co.uk Sat Jul 30 09:12:29 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sat, 30 Jul 2005 14:12:29 +0100 Subject: [path-PEP] Path inherits from basestring again References: Message-ID: On Fri, 29 Jul 2005 14:38:23 +1200, Tony Meyer wrote: >> def functions_which_modifies_some_file_in_place(path): >> output = open(path+'.tmp', 'w') >> ..... >> >> I dont want a seperator inserted between path and the new extension. > >Fair enough. Forget using '+' for join, then (which I was never that keen >on - TIOWTDI), but I'm still -1 on using '/' for join. I agree. It's yuck. What's wrong with simply having each path-element as an argument to a function, e.g. join(foo, bar, baz) -- Email: zen19725 at zen dot co dot uk From Scott.Daniels at Acm.Org Fri Jul 1 18:13:31 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 01 Jul 2005 15:13:31 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <42c5b862$1@nntp0.pdx.net> Rocco Moretti wrote: > Joseph Garvin wrote: > > I'm not aware of a language that allows it, but recently I've found > myself wanting the ability to transparently replace objects.... > I mainly look for it in the "object replaces self" form, but I guess you > could also have it for arbitrary objects, e.g. to wrap a logging object > around a function, even if you don't have access to all references of > that function. > > Why isn't it in Python? It's completely counter to the conventional > object semantics. Actually this is the old (and terrifying) Smalltalk message 'becomes:'. There is a concrete reason it is not in python: objects are represented as pointers to their data structures, do not have identical sizes, and therefore cannot be copied into each others data space. Smalltalk implementations often have a level of indirection that allows it to simply tweak an indirection table to implement this method. The reason I find it terrifying is that I can be passed an object, place it in a dictionary (for example) based on its value, and then it can magically be changed into something else which does not fit in that spot in the dictionary. --Scott David Daniels Scott.Daniels at Acm.Org From Scott.Daniels at Acm.Org Fri Jul 1 13:43:19 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 01 Jul 2005 10:43:19 -0700 Subject: When someone from Britain speaks, Americans hear a "Britishaccent"... In-Reply-To: References: Message-ID: <42c5790f$1@nntp0.pdx.net> Delaney, Timothy (Tim) wrote: > Grant Edwards wrote: > > >>On 2005-06-30, Delaney, Timothy (Tim) wrote: >> >> Due to some wierd property requiring conservation of >> consonants, when speaking Strine you've got to take the r's >> removed from words like "carrier" and "order", and add them to >> the ends of other words like Amanda. > > I feel obliged to point out that there's probably only about 50,000 > speakers of Strine in Australia out of approx 20 million people, so a > lot of those consonants are ending up in landfill somewhere, rather than > being conserved in an environmentally-friendly way. So that's why pirates were always walking around saying "Aaarrrrrrrrrr." From shai at platonix.com Wed Jul 6 18:39:05 2005 From: shai at platonix.com (Shai) Date: 6 Jul 2005 15:39:05 -0700 Subject: Favorite non-python language trick? References: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> <86psu2410u.fsf@bhuda.mired.org> <86ll4q3q0m.fsf@bhuda.mired.org> Message-ID: <1120689545.113419.318680@g14g2000cwa.googlegroups.com> I only saw this today... sorry about the late response. Anyway, replying to your two messages at once: Mike Meyer wrote: > Last time I checked, dynamic binding variables were frowned on in LISP > systems as well. Scheme doesn't have them. Common LISP requires > special forms to use them. They're called "Special vars", and you need to define them (unlike local LISP variables, which behave essentially like Python vars), but then you use them just like other vars (that is, you usually bind them with LET). This is the first I hear about them being ill-considered in LISP; http://www.gigamonkeys.com/book/ is a recently published LISP book which recommends them. I don't know about Scheme, but I think it does have them. The one "special" thing you see in every use of these vars in LISP is a naming convention; as LISP symbols can contain most characters, they are usually named with asterisks on both ends to distinguish them. Thus, in the example above, the dynamic var would be named "*x*". > The problem with the given use case is that it lets every routine in > the call chain substitute it's own variable for the library parameter > you want to use, with no local indication that this is going > on. This makes bugs in dynamically scoped variables a PITA to find. In LISP, the naming convention indeed takes care of that; and indeed, I consider taking the LISP way would be better. The definition of x as dynamic would then be not in bar nor its callers, but in the definition of x, as in dynamic x=10 def bar(): print x I specified the syntax as I did, specifically to make it match the current definition of globals, which "enjoys" the same problems you noted with my dynamics. > > >> x=10 > >> def foo(): > >> # No need to define x as it is only read -- same as globals > >> print x > >> > >> def bar(): > >> dynamic x > >> x = 11 > >> foo() > >> > >> def baz(): > >> bar() # prints 11 > >> foo() # prints 10; the binding in bar is undone when bar exits > > Here's the problem with that. Consider this script: > > import foo > x = 10 > def bar(): > print x > > foo.foogle(bar) > > If foo.foogle includes "dynamic x" and then invokes bar, bar could > print anything. This makes the behavior of bar unpredictable by > examining the sourc, with no hint that that is going on. > While I didn't write it explicitly, if both LISP and Python globals are to be followed, the dynamic x should somehow be defined in the scope of its module. On second thought, this means "dynamic" _must_ be added in the variable definition, for foo.foogle will simply access it as "othermodule.x", which doesn't differentiate globals from dynamics. Either way, Python as it is now allows foo.foogle to change x even without dynamic variables; it is accessible as barmodule.x. bar() should expect to have other functions mess with its globals, and dynamics are no different. > > Given that it's a feature I don't want programmers using, I'd only be > > willing to see it added to the language if you can show that it has no > > overhead so long as you don't use it. I'm not sure that can be done. > That sounds like a fine requirement. Now, with my corrected proposition, it would be implementable at the module-object level, so that only module which use the feature, and modules which use them, would be affected. > Here's a proposal for dynamically bound variables that you should be > able to implement without affecting the runtime behavior of code that > doesn't use it. > > Instead of dynamic meaning "all references to the named variable(s) > will be dynamic until this function exits", have it mean "the named > variable(s) will be dynamic in this function." Whether it should only > check local variables in the calling routines, check local + global, > or check for all free variables, is an open question. > > I.e. - your example would be written: > > x = 10 > def foo(): > dynamic x > print x > > def bar(): > x = 11 > foo() > > def baz(): > bar() # prints 11 > foo() # Possibly an error? > This introduces the same problem you noted with my original proposal, but in reverse: Now, in bar(), you define and use a local variable, and suddenly some library function changes its behavior misteriously. > For my example above, bar would *always* print 10. Nothing that > foo.foogle did would change that. However, you could write: > > import foo > def bar(): > dynamic x > print x > > foo.foogle(bar) > > In this case, bar will print whatever foo.foogle sets x to - and it's > noted in the source to bar. This means that functions that don't > declare a dynamic variable can be compiled to the same code they are > compiled to now. > This is, I believe, disproved by my comment above. Thanks for your time and effort, Shai. From jepler at unpythonic.net Wed Jul 27 12:37:30 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 27 Jul 2005 11:37:30 -0500 Subject: Stripping C-style comments using a Python regexp In-Reply-To: <1122478928.879240.89110@g47g2000cwa.googlegroups.com> References: <1122478928.879240.89110@g47g2000cwa.googlegroups.com> Message-ID: <20050727163727.GB4967@unpythonic.net> #------------------------------------------------------------------------ import re, sys def q(c): """Returns a regular expression that matches a region delimited by c, inside which c may be escaped with a backslash""" return r"%s(\\.|[^%s])*%s" % (c, c, c) single_quoted_string = q('"') double_quoted_string = q("'") c_comment = r"/\*.*?\*/" cxx_comment = r"//[^\n]*[\n]" rx = re.compile("|".join([single_quoted_string, double_quoted_string, c_comment, cxx_comment]), re.DOTALL) def replace(x): x = x.group(0) if x.startswith("/"): return ' ' return x result = rx.sub(replace, sys.stdin.read()) sys.stdout.write(result) #------------------------------------------------------------------------ The regular expression matches ""-strings, ''-character-constants, c-comments, and c++-comments. The replace function returns ' ' (space) when the matched thing was a comment, or the original thing otherwise. Depending on your use for this code, replace() should return as many '\n's as are in the matched thing, or ' ' otherwise, so that line numbers remain unchanged. Basically, the regular expression is a tokenizer, and replace() chooses what to do with each recognized token. Things not recognized as tokens by the regular expression are left unchanged. Jeff PS this is the test file I used: /* ... */ xyzzy; 456 // 123 const char *mystr = "This is /*trouble*/"; /* * */ /* /* */ // /* /* */ /* // /* */ /* * */ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bronger at physik.rwth-aachen.de Sun Jul 31 01:50:04 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 31 Jul 2005 07:50:04 +0200 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: <87ek9fr0c3.fsf@wilson.rwth-aachen.de> Hall?chen! Mike Meyer writes: > Torsten Bronger writes: > >> Calvin Spealman writes: >> >>> The choice is GUI toolkits is largely seperate from >>> Python. Consider that they are just bindings to libraries that >>> are developed completely seperate of the language. GUI is should >>> be seperate from the language, and thus not bound to same >>> expectations and desires as elements of the language itself. >> >> I disagree. A modern language must provide a convenient and >> well-embedded way to write GUI applications. > > [...] > > The tools for writing GUI applications belong in a library, not > the langauge. None of us has talked about changing syntax. However, the standard library is part of the language unless you're really very petty. >> This is not a sign of decadence, but a very good promotional >> argument. > > But it's not required for the language to succeed. Today it is (except for very special-purpose languages). > C and C++ are both doing very well without your a well-embedded > way to write GUI applications. I don't think that much money is made with new C programs. Almost all money with C++ is made with VC which has been having a GUI toolkit in its standard library right from the beginning. And most money is made with VB AFAIK. > However, you can get compilers for both that come bundled with a > good GUI library. Could it be that that's what you really want - > someone to distribute Python bundled with an enterprise-class GUI > library and IDE? Well, a nice thing to have, but besides my point. We do have a standard library with a robust GUI package, and a standard distribution with a so-called IDE. What I really want is a better GUI included into the standard library. >> However, in my opinion we don't need yet another binding so thin >> that C or C++ is shining through, but a modern replacement for >> Tkinter with its Pythonic way of thinking. > > I don't particularly like Tkinter, but it seems to me that it's > pretty much won. It seems to be installed on every desktop > platform along with Python. That means that if I want to > distribute GUI apps, I'm going to cause the least headache for my > end users by writing them in Tkinter. A "replacement for Tkinter" would have the same properties, otherwise it wouldn't be a replacement. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From mcfletch at rogers.com Sat Jul 2 17:00:34 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 02 Jul 2005 17:00:34 -0400 Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> References: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> Message-ID: <42C70072.7060500@rogers.com> Ralf W. Grosse-Kunstleve wrote: ... > class grouping: > > def __init__(self, x, y, z): > self.x = x > self.y = y > self.z = z > # real code, finally > >This becomes a serious nuisance in complex applications with long >argument lists, especially if long variable names are essential for >managing the complexity. Therefore I propose that Python includes >built-in support for reducing the ``self.x=x`` clutter. Below are >arguments for the following approach (*please* don't get too agitated >about the syntax right here, it really is a secondary consideration):: > > ... This can be dealt with quite nicely if you take a step back and consider what you're trying to do: * define a set of properties/fields for a class, potentially with default values for any given property * define an initialisation function which, given an instance of a class with defined properties (potentially with defaults) and a mapping of name:value pairs, assigns the named values to the named properties... class Grouping( propertied.Propertied ): x = FloatProperty( "x", """Holder for the grouping node's x coordinate""", defaultValue = 0, ) y = FloatProperty( "y", """Holder for the grouping node's y coordinate""", defaultValue = 0, ) z = FloatProperty( "z", """Holder for the grouping node's z coordinate""", defaultValue = 0, ) def __init__( self, **args ): # code here to do whatever you like to args (or whatever)... super( Grouping, self ).__init__( **args ) # extra code here... where the propertied.Propertied class defines a simple init that iterates through the defined properties pulling those which are present in the **args of the __init__ function and assigning them to the appropriate property. The advantage here is that your class is now documented properly, with the information about a given property all localised in a definition of the property. Your properties can also implement the observer pattern, automatic type checking and coercion, and can provide default values that appear when you delete current values (not just during initialisation). You can also do useful things like using the defined properties of a class to auto-generate __repr__ and __str__ values. You can have your properties delegate to other objects, or have them delay loading/resolving a property's value until the last possible second (lazy loading from an object database, for instance). The fact that it's all doable in Python 2.2+ without any need for new syntax... well... that's cool too. The disadvantage is that the properties tend to be unordered (unless you explicitly order them, and that's awkward looking), and you have to pass them to the constructor as keyword arguments. But then, if you're defining a class with 50 properties, you likely aren't really wanting to pass all 50 as positional arguments anyway. You'll find patterns like this in my own OpenGLContext (3D scenegraph viewer) and BasicProperty packages, as well as in Traits (originally part of a 2D graphics package), and Zope's FieldProperty (and PEAK, though as always with PEAK, it's somewhat weird in there ;) ). All of those are largish systems (or used in largish systems), btw. Just my thoughts, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From jstier at cs.uvic.ca Fri Jul 8 18:48:55 2005 From: jstier at cs.uvic.ca (J) Date: 8 Jul 2005 15:48:55 -0700 Subject: embedding a new method Message-ID: <1120862935.199471.147610@g47g2000cwa.googlegroups.com> Hi everyone, I am fairly new to python (3rd day), but i am fairly keen on replacing javascript. I want to externalize some of the mehtod in my App, an allow user to imp char* lBuffer = "def handler(color):\n" " print 12" PyObject* lCode = Py_CompileString(lBuffer, "", Py_file_input); if (lCode) { mFunction = PyFunction_New(lCode, ScnGlobal::sDictionary); Py_XDECREF(lCode); } else { PyErr_Print(); } So far, there is no error, but I am wondering if that function object knows about the signature of the function at this point. Next I am defining an class like PyType_Ready(&PyType); Py_INCREF(&PyType); PyModule_AddObject(ScnGlobal::sModule, "Place", (PyObject*)&PyType); where PyType is pretty much taken out of the "embedding tutorial", and ScnGlobal::sModule is the result of the call to PyImport_ImportModule ("__main__"). I am installing tp_init and tp_new in PyType. Next, I instantiate an object of PyType like PyObject* new_args = PyTuple_New(0); mPyObject = (PyStruct*) PyObject_Call((PyObject*)&PyType, new_args, 0); This also works and tp_init and tp_new get called. Now, I want to add the new mehtod to this instance, and not the class, so I call PyObject* lParam = PyMethod_New(mFunction, (PyObject*)mPyObject, (PyObject*)&PyType); if (lParam) { Py_XDECREF(lParam); } else { PyErr_Print(); } This call also returns an object. The problem starts when I try to call the new method like so PyObject* lObject = PyObject_CallMethod((PyObject*)mPyObject, "handler", "", NULL); if (lObject) { Py_DECREF(lObject); } else { PyErr_Print(); } This when I get an error saying "AtrributeError:handler". I would really appreciate some help on this. Here is also what the PyType structure looks like PyTypeObject CmdPlace::PyType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "Place", /*tp_name*/ sizeof(CmdPlace::PyStruct), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "CmdPlace", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ CmdPlace::sPyMethods, /* tp_methods */ 0, /* tp_members */ CmdPlace::sPyGetSeters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)CmdPlace::sPyInit, /* tp_init */ 0, /* tp_alloc */ CmdPlace::sPyNew, /* tp_new */ }; I hopesome has an answer. I have been stuck with this for a while. Cheers Jochen From t-meyer at ihug.co.nz Fri Jul 29 22:52:35 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sat, 30 Jul 2005 14:52:35 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: >> (Those who are offended by sweeping generalisations should >> ignore this next bit) [...generalisation bit snipped...] > This is not only bullshit, it's elitist bullshit. "Windows users are > more clueless than users of posix systems." Pfui. Prove it > or withdraw it. Sigh. I guess you didn't read or understand the first sentence? >> This (readability without knowing the language/standard >> libraries) is a huge benefit of using Python. > > It's overrated. It must be macho to say "I learned Python without > reading books." No it is not. Have you used Python as pseudocode when teaching people how to program? Many people have. That's just one example. > Then that's your right, but don't try to take / away from > people who use it and like it. People can subclass Path and add it if they really want it. They can use Jason's original module. My position is that the PEP without this use of __div__ is (a) better as a standard module, and (b) improves the chance of the PEP being accepted. =Tony.Meyer From sjmachin at lexicon.net Sun Jul 31 01:39:23 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 31 Jul 2005 15:39:23 +1000 Subject: How to convert a string like '777' to an octal integer like 0777? In-Reply-To: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> References: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> Message-ID: <42ec640a@news.eftel.com> KB wrote: > Hi, > > This may be a rudimentary question: > > How to convert a string like '777' to an octal integer like 0777, > so that it can be used in os.chmod('myfile',0777)? > > I know the leading zero is important in os.chmod. There is no law that says constant arguments to os.chmod have to be expressed in octal -- it's just a historical accident that it's convenient (for octal grokkers, anyway): there are 3 permissions (rwx) and 2 ** 3 == 8. Consider the following, whcih should provide enlightenment as well as answer your question: >>> print 0777, int("777", 8) 511 511 >>> Cheers, John From vendredi5h at gmail.com Tue Jul 12 16:48:45 2005 From: vendredi5h at gmail.com (Yannick Turgeon) Date: 12 Jul 2005 13:48:45 -0700 Subject: Web client, https and session management In-Reply-To: References: <1121182118.684389.182950@g14g2000cwa.googlegroups.com> <11d7oqmr47jc53@corp.supernews.com> Message-ID: <1121201325.016578.229040@z14g2000cwz.googlegroups.com> Well... Thanks for that! The work is almost completed now! ;o) Yannick From xen0n at vodafone.it Mon Jul 25 13:03:12 2005 From: xen0n at vodafone.it (xen0n at vodafone.it) Date: 25 Jul 2005 10:03:12 -0700 Subject: GPRS Connection name on Python s60 In-Reply-To: References: <1122294420.896414.152630@f14g2000cwb.googlegroups.com> Message-ID: <1122310992.858311.26080@o13g2000cwo.googlegroups.com> Yeah i have already asked it, but, i think i can set before the .connect method, a connection as default, and, when connected, resore default connection! Peter Hansen ha scritto: > xen0n at vodafone.it wrote: > > Hi, I have a question for the experts of Python for series60! > > > > When I use the ".connect" method of the socket, a list with all > > connection available pop-up, and, after selecting one, the soft go on. > > > > My question is that: Can i use the ".connect" method passing connection > > name, resulting in a connection without the pop up list with connection > > names? > > TCP connections don't normally have any "connection name", so this must > be a platform-specific question. Have you thought of asking on the > mailing list for Series 60 Python? > > -Peter From peter at engcorp.com Fri Jul 22 09:06:41 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 09:06:41 -0400 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Duncan Booth wrote: > Personally I think the concept of a specific path type is a good one, but > subclassing string just cries out to me as the wrong thing to do. In other > words, to me a path represents something in a filesystem, the fact that it > has one, or indeed several string representations does not mean that the > path itself is simply a more specific type of string. > > You should need an explicit call to convert a path to a string and that > forces you when passing the path to something that requires a string to > think whether you wanted the string relative, absolute, UNC, uri etc. Duncan, are you another formerly non-user of path who has this opinion, or have you already attempted to use path extensively in your code? I'm not saying I dismiss the opinions of those who haven't actually tried working with a string-based path object, but it's worth considering that you might adopt a different opinion after using it for a while. I did. -Peter From apoco at cox.net Sat Jul 9 13:17:06 2005 From: apoco at cox.net (Jacob Page) Date: Sat, 09 Jul 2005 10:17:06 -0700 Subject: Python Module Exposure In-Reply-To: <1120924507.452720.236990@g47g2000cwa.googlegroups.com> References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > "Jacob Page" wrote: > >>George Sakkis wrote: >> >>>1. As already noted, ISet is not really descriptive of what the class >>>does. How about RangeSet ? It's not that long and I find it pretty >>>descriptive. In this case, it would be a good idea to change Interval >>>to Range to make the association easier. >> >>The reason I decided not to use the term Range was because that could be >>confused with the range function, which produces a discrete set of >>integers. Interval isn't a term used in the standard/built-in library, >>AFAIK, so I may stick with it. Is this sound reasoning? > > Yes, it is not unreasonable; I can't argue strongly against Interval. > Still I'm a bit more in favor of Range and I don't think it is > particularly confusing with range() because: > 1. Range has to be either qualified with the name of the package (e.g. > rangesets.Range) or imported as "from rangesets import Range", so one > cannot mistake it for the range builtin. > 2. Most popular naming conventions use lower first letter for functions > and capital for classes. > 3. If you insist that only RangeSet should be exposed from the module's > interface and Range (Interval) should be hidden, the potential conflict > between range() and RangeSet is even less. Those are pretty good arguments, but after doing some poking around on planetmath.org and reading http://planetmath.org/encyclopedia/Interval.html, I've now settled on Interval, since that seems to be the proper use of the term. >>>2. The module's "helper functions" -- which are usually called factory >>>functions/methods because they are essentially alternative constructors >>>of ISets -- would perhaps better be defined as classmethods of ISet; >>>that's a common way to define instance factories in python. Except for >>>'eq' and 'ne', the rest define an ISet of a single Interval, so they >>>would rather be classmethods of Interval. Also the function names could >>>take some improvement; at the very least they should not be 2-letter >>>abbreviations. >> >>First, as far as having the factory functions create Interval instances >>(Range instances in your examples), I was hoping to avoid Intervals >>being publically "exposed." I think it's cleaner if the end-programmer >>only has to deal with one object interface. > > First off, the python convention for names you intend to be 'private' > is to prefix them with a single underscore, i.e. _Interval, so it was > not obvious at all by reading the documentation that this was your > intention. Assuming that Interval is to be exposed, I found > Interval.lowerThan(5) a bit more intuitive than > IntervalSet.lowerThan(5). The only slight problem is the 'ne'/ > allExcept factory which doesn't return a continuous interval and > therefore cannot be a classmethod in Interval. If the factories resided in separate classes, it seems like they might be less convenient to use. I wanted these things to be easily constructed. Maybe a good compromise is to implement lessThan and greaterThan in both Interval and IntervalSet. > On whether Interval should be exposed or not: I believe that interval > is a useful abstraction by itself and has the important property of > being continuous, which IntervalSet doesn't. Perhaps I should add a boolean function for IntervalSet called continuous (isContinuous?). Having a simple > single-class interface is a valid argument, but it may turn out to be > restricted later. For example, I was thinking that a useful method of > IntervalSet would be an iterator over its Intervals: > for interval in myIntervalSet: > print interval.min, interval.max I like the idea of allowing iteration over the Intervals. > There are several possible use cases where dealing directly with > intervals would be appropriate or necessary, so it's good to have them > supported directly by the module. I think I will keep Interval exposed. It sort of raises a bunch of hard-to-answer design questions having two class interfaces, though. For example, would Interval.between(2, 3) + Interval.between(5, 7) raise an error (as it currently does) because the intervals are disjoint or yield an IntervalSet, or should it not even be implemented? How about subtraction, xoring, and anding? An exposed class should have a more complete interface. I think that IntervalSet.between(5, 7) | IntervalSet.between(2, 3) is more intuitive than IntervalSet(Interval.between(5, 7), Interval.between(2, 3)), but I can understand the reverse. I think I'll just support both. >>I like the idea of lengthening the factory function names, but I'm not >>sure that the factory methods would be better as class methods. > > One of the main reason for introducing classmethods was to allow > alternate constructors that play well with subclasses. So if Interval > is subclassed, say for a FrozenInterval class, > FrozenInterval.lowerThan() returns FrozenInterval instances > automatically. You've convinced me :). I sure hate to require the programmer to have to type the class name when using a factory method, but I'd hate providing a duo of frozen and non-frozen factories even more. >>I like the function names, but in my dialect, lessThan would be more proper. > > Either (lowerThan,greaterThan) or (lessThan,moreThan) are fine with me; > I'm very slightly in favor of the second for brevity. Less than/greater than seem to be the usual way to pronounce < and >. At least it matches the Python, which uses __lt__, __le__, __gt__, and __ge__. I'll stick with lessThan and greaterThan. Thanks for your input. I'm going to start implementing your suggestions. I hope more people add feedback so I can make this an even better module. From mark.english at liffe.com Tue Jul 19 04:35:08 2005 From: mark.english at liffe.com (MarkE) Date: 19 Jul 2005 01:35:08 -0700 Subject: Windows command line problem In-Reply-To: <1121759914.689112.272530@z14g2000cwz.googlegroups.com> References: <1121699051.059188.55640@g43g2000cwa.googlegroups.com> <1121726398.861595.31350@g43g2000cwa.googlegroups.com> <1121759914.689112.272530@z14g2000cwz.googlegroups.com> Message-ID: <1121762108.120184.201340@g47g2000cwa.googlegroups.com> This was discovered after consultation with a colleague who shall remain nameless but, well, nailed it basically. The answer appears to be: An example command line for running the script was written in a word document. The "Autocorrect" (sic) feature in word replaces a normal dash at least as I know it with the character Jeff Epler showed above, u'\N{en dash}' which is a nice big long dash in the Arial font. If you cut and paste that onto the command line, bad things can happen although when I do this on my machine I actually get a "u" with an "^" on top. For whatever reason it must have looked ok on my colleagues machine (or possibly this isn't the answer but I seriously doubt that) and when he ran the Python script things went awry. Thanks Jeff (and nameless colleague). And beware Word autocorrection. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 09:01:40 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 15:01:40 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e38a38$0$1453$626a14ce@news.free.fr> Thanos Tsouanas a ?crit : >>On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote: >> >>>Hello. >>> >>>I would like to have a quick way to create dicts from object, so that a >>>call to foo['bar'] would return obj.bar. >> (snip) > print foo %do > > where do is a dictobj object... I gave you a solution based on the Decorator pattern in another post, but there is also the possibility to add a __getitem__ method directly to the to-be-formatted object's class: def mygetitem(obj, name): return getattr(obj, name) setattr(obj.__class__, '__getitem__', mygetitem) obj['bar'] BTW, parts of this thread should remind us all that it's usually better to clearly describe the *problem* before asking for comments on the solution... My 2 cents... Bruno From could.net at gmail.com Tue Jul 19 20:59:45 2005 From: could.net at gmail.com (could ildg) Date: Wed, 20 Jul 2005 08:59:45 +0800 Subject: Python s60 Contact DB In-Reply-To: <1121780830.418009.176650@o13g2000cwo.googlegroups.com> References: <1121780830.418009.176650@o13g2000cwo.googlegroups.com> Message-ID: <311b5ce105071917597fe65dad@mail.gmail.com> You should raise this question at Nokia python for series60 forum, I'm sure you can the answer there. http://discussion.forum.nokia.com/forum/forumdisplay.php?s=85e4c1acee330fddde6b47a7b2feae73&forumid=102 On 19 Jul 2005 06:47:10 -0700, xen0n at vodafone.it wrote: > Hi, i hope the expert can help me! > I have a little problem: > > This piece of code, in python console s60, before compiling will work > great: > > try: > ..db = contacts.open() > ..names = [] > ..numbers = [] > > The problem is that, if i compile it with py2sis (pyrsc_template.tmp > replaced with the original to solve the submenus bug) it doesnt work, > when that piece of code is executed, i receive error -50 and nothing > happen! hope u can help me! 10ks a lot in advance > > Regards. > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVETHIScyber.com.au Sat Jul 30 11:59:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 31 Jul 2005 01:59:59 +1000 Subject: PEP on path module for standard library References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> <3l1avfF10i4kgU1@individual.net> Message-ID: On Sat, 30 Jul 2005 14:43:27 +0200, Reinhold Birkenfeld wrote: >> Less important but non-controversial: >> >> - Path.tempfile(), Path.tempdir(): >> Create a temporary file using tempfile.mkstemp, tempfile.mkdtemp >> >> - Path.tempfileobject(): >> Create a temporary file object using tempfile.TemporaryFile. >> (Static method.) > > Don't know whether these belong here. They are all not acting upon the > path, but create the file/dir at another location. Agreed that they do not belong. >> - .delete_dammit() recursively deletes it, whatever it is, without you >> having to do the if file/if directory dance. I suppose it would need >> a politically correct name. >> which you really have to do every time you delete. > > *grin* Any naming suggestions? force_delete() -- Steven. From rkern at ucsd.edu Wed Jul 20 17:20:01 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 14:20:01 -0700 Subject: What does "::" mean? In-Reply-To: References: <1121874153.297930.11560@o13g2000cwo.googlegroups.com> Message-ID: Rob Williscroft wrote: > import sys > > live = 'live' > > print live[ sys.maxint : : -1 ] > print live[ len(live)-1 : : -1 ] > > print live[ len(live)-1 : -len(live)-1 : -1 ] > print live[ len(live)-1 : -sys.maxint : -1 ] > print live[ sys.maxint : -sys.maxint : -1 ] > print live[ -1 : -len(live)-1 : -1 ] > > Of course there is only one obvious way to do it, but alas > as I'm not Dutch I can't tell which it is. Well, that part's easy at least: live[::-1] :-) And so the circle is complete ... -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From matthewharrison at gmail.com Thu Jul 14 17:16:15 2005 From: matthewharrison at gmail.com (matt) Date: 14 Jul 2005 14:16:15 -0700 Subject: How to create "cross-backend" python web app Message-ID: <1121375775.021103.28610@g43g2000cwa.googlegroups.com> Hi all- I'm trying to port an ajax spell-checker (http://www.broken-notebook.com/spell_checker/index.php) to use with the moin moin wiki and have been somewhat successful. (By successful I mean I can spell check using the php backend and my python port running as cgi-bin). My question is this: moinmoin runs on many python web backends (cgi-bin/mod-python/twisted/standalone). My spell-checker backend runs as cgi (disclaimer: I've done a bit of php and java(struts) web app programming, but the last python related web programming I did was Zope about 5 years ago (does that even count ? ;) )) because that was the easiest for me to get up to speed on. What is the best way to write cross-backend python web apps? Is there any abstraction I can use? With cgi-bin, I use the python "cgi" module, which gives me easy access to form variables, but I'd like to be able to deploy in the other backends as well. What's the best way to do this? Or is a rewrite required for each one? thanks matt From fdeserres at gmx.net Wed Jul 13 09:56:11 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Wed, 13 Jul 2005 15:56:11 +0200 Subject: Building a function call? In-Reply-To: References: Message-ID: <42D51D7B.9070108@gmx.net> Steven D'Aprano wrote: >On Wed, 13 Jul 2005 06:16:54 -0700, Robert Kern wrote: > > > >>Duncan Booth wrote: >> >> >>>Francois De Serres wrote: >>> >>> >>> >>>>Having a string: "dothat" >>>>and a tuple: (x, y) >>>>1. What's the best way to build a function call like: dothat(x,y)? >>>> >>>> >[snip] > > >>>No, none of this is a good place to use eval. >>> >>> >[snip] > > >>> import otherModule >>> vars(otherModule)[aString](*aTuple) >>> >>> >>Ick! Please: >>getattr(otherModule, aString)(*aTuple) >> >> > > >Or, remember that functions are first class objects in Python. Instead of >passing around the function name as a string, pass around a reference to >the function itself. Something like this: > > >def dothis(x,y): > return x-y > >def dothat(x,y): > return x+y > >somefunction = dothis >somefunction(3, 2) >=> returns 1 > >somefunction = dothat >somefunction(3, 2) >=> returns 5 > >allfunctions = [dothis, dothat] >for func in allfunctions: > print func(3, 2) >=> prints 1 then 5 > >If you want to collect user-supplied strings and use them to find a >function, you could use eval (terribly risky and unsafe), or you could do >something like this: > >funcnames = {} >for func in allfunctions: > funcnames[func.__name__] = func >F = raw_input("Enter the name of a function: ") >try: > funcnames[F](3, 2) >except KeyError: > print "Function '%s' not found!" % F > > >In my humble opinion, people muck about with eval, locals and globals far >too often. It is unclear, hard to maintain, and frequently a security >risk. These confusing, unsafe practices can usually be avoided by >remembering that functions are first class objects just like ints, strings >and lists. > > > > > I'm aware of the functions being objects, but I really need to work with strings in that case. Still, I was not aware that eval() was such a 'rogue', it's not said in the manuals ;) Many thanks! F. From bgporter at acm.org Fri Jul 1 09:23:47 2005 From: bgporter at acm.org (Brett g Porter) Date: Fri, 01 Jul 2005 09:23:47 -0400 Subject: How to compare files In-Reply-To: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> References: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> Message-ID: <42C543E3.4000001@acm.org> Lad wrote: > Hi, > What is the best method for comparing two files by words? > I was thinking about reading files by words and compare them but a word > in one file can be linked with a new line character ( \n) > and this '\n' will cause that the words will considered to be > different( eventhough without '\n' are the same) > > Thanks for help. > LAd. > Have you looked at the difflib module that comes with Python? http://docs.python.org/lib/module-difflib.html -- // Today's Oblique Strategy (? Brian Eno/Peter Schmidt): // Change instrument roles // Brett g Porter * BgPorter at acm.org From paolo_veronelli at tiscali.it Wed Jul 27 13:43:12 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Wed, 27 Jul 2005 19:43:12 +0200 Subject: Create a variable "on the fly" In-Reply-To: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Message-ID: <42E7C7B0.1090603@tiscali.it> Paul D.Smith wrote: > Can Python create a variable "on-the-fly". For example I would like > something like... > > make_variable('OSCAR', 'the grouch'); > print OSCAR; > > ...to output... Python has only 'on the fly' variables and ';' is not used for one expression in one line. Probably the tutorial is good to be read also. Paolino ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From martin.witte at gmail.com Sat Jul 2 18:08:34 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 2 Jul 2005 15:08:34 -0700 Subject: What are the other options against Zope? In-Reply-To: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> Message-ID: <1120342113.997667.41960@g44g2000cwa.googlegroups.com> If you're looking for a leight weight web development enviroment acting as a front end for a database take a look at http://www.cherrypy.org From mwm at mired.org Fri Jul 1 09:42:15 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 09:42:15 -0400 Subject: How to run commands in command line from a script References: Message-ID: <86mzp67idk.fsf@bhuda.mired.org> Peter Hansen writes: > Ivan Shevanski wrote: >> Alright well I'm quite a noob and when I run a simple command to >> change the current directory, nothing happens. I made a little test >> script to show it: >> import os >> cwd = os.getcwd() >> print cwd >> os.system('cd = C:\Program Files') >> print cwd > > 1. Commands like "cd" are executed by the shell, not as separate > executables (.exe files). Unfortunately, the result of this is that > their effects are lost when the shell returns to Python, so you can't > do what you are trying to do in quite this manner. It doesn't really matter that it's executed by the shell or as a seperate exe. Things run via os.system don't happen in the Python process, so any pre-process changes that they make won't show up in the Python process. Of course, shells suffer from the same problem. If they run another process to make a per-process change, the change won't happen in the shell process. So all the commands that make per-process changes - like cd - are handled internally by the shell. The trick is figuring out what things are per-process changes, and what are global state changes, and then using the Python tools for making the per-process changes. Since using the Python tools for making global changes is usually more portable than invoking an external command, you should try and use such tools for those changes as well. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From 42zeros at gmail.com Fri Jul 15 08:36:45 2005 From: 42zeros at gmail.com (42zeros at gmail.com) Date: 15 Jul 2005 05:36:45 -0700 Subject: Question about basic use of a timer object from timeit module to execute code every so often in a class In-Reply-To: References: <1121426865.426413.86020@g47g2000cwa.googlegroups.com> Message-ID: <1121431005.054196.142670@g47g2000cwa.googlegroups.com> I've seen both documentation for using timeit as simply a timer to measure preformance, but also a random page here and there that looked to me as if they were using it as a simple timer. HOwever, if there is a wxwidget timer I'll gladly hit that up. Thanks for the info From 42zeros at gmail.com Fri Jul 15 07:27:45 2005 From: 42zeros at gmail.com (42zeros at gmail.com) Date: 15 Jul 2005 04:27:45 -0700 Subject: Question about basic use of a timer object from timeit module to execute code every so often in a class Message-ID: <1121426865.426413.86020@g47g2000cwa.googlegroups.com> I would like a function to be executed every x often. I was just wondering how to pass the following code correctly. my object t just doesn't know what checkMail is. How can I tell it that checkMail is a member of the class MyApp? thanks in advance, code is below class MyApp(wx.App): def OnInit(self): frame = wxMainFrame(None, "thing") icon = wx.Icon('foo.bmp', wx.BITMAP_TYPE_ICO) frame.SetIcon(icon) self.SetTopWindow(frame) t = timeit.Timer("checkMail()","30.0") t.timeit() return True def checkMail(): print "The number of messages is" From R.Brodie at rl.ac.uk Tue Jul 5 05:53:09 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 5 Jul 2005 10:53:09 +0100 Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: "Tim Golden" wrote in message news:mailman.1350.1120556608.10512.python-list at python.org... > Could simply be that the Exchange server isn't running an > IMAP service (or whatever it's called). Ours doesn't. I would have thought most wouldn't run IMAP in the clear; over SSL maybe. From roccomoretti at hotpop.com Thu Jul 28 10:14:18 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 28 Jul 2005 09:14:18 -0500 Subject: On fighting fire with fire... In-Reply-To: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: projecktzero wrote: > but..but...It's so much more fun to unleash your anger and fire back > with all guns blazing fanning the flame war that most discussion groups > degenerate into after a couple of responses. =) > > Actually, I had some self restraint yesterday. I wanted to write a > ripping response to an antagonistic flame bait message on another > group. I wrote it, decided it wouldn't help much, and deleted it. I > guess I got it out of my system by just writing it. That's what I do. I sometimes have something I want to say, so I write my rant. Once I get it out of my system, I realize that it isn't adding anything to the discussion, and delete it. The part of my brain that wants to rant is happy because it got its say in, and the rest of the world is happier for not having to read it. I highly recommend that people try it. It works wonders. From jaymail at gawab.com Sat Jul 30 03:51:12 2005 From: jaymail at gawab.com (Jay) Date: 30 Jul 2005 00:51:12 -0700 Subject: Hiding In-Reply-To: <1122692712.976074.48870@g49g2000cwa.googlegroups.com> References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> <1122662993.207041.89630@f14g2000cwb.googlegroups.com> <1122692712.976074.48870@g49g2000cwa.googlegroups.com> Message-ID: <1122709872.393066.162510@g43g2000cwa.googlegroups.com> but also, wat if i needed to hide the loading of a file or the even hide the whole python window to run in background?? is there no module or function i can use???? From cam.ac.uk at mh391.invalid Thu Jul 14 08:00:34 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 14 Jul 2005 13:00:34 +0100 Subject: Who uses input()? [was Re: question on "input"] In-Reply-To: <1121179143.995844.28690@g47g2000cwa.googlegroups.com> References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> <1121179143.995844.28690@g47g2000cwa.googlegroups.com> Message-ID: Devan L wrote: > Use raw_input instead. It returns a string of whatever was typed. Input > expects a valid python expression. Who actually uses this? It's equivalent to eval(raw_input(prompt)) but causes a lot of newbie confusion. Python-dev archives revealed that someone tried to get this deprecated but Guido disagreed. -- Michael Hoffman From rkern at ucsd.edu Tue Jul 12 16:30:14 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 13:30:14 -0700 Subject: python parser In-Reply-To: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> References: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> Message-ID: tuxlover wrote: > Hello everyone > > I have to write a verilog parser in python for a class project. I was > wondering if all you folks could advise me on choosing the right python > parser module. I am not comfortable with lex/yacc and as a result find > myself strugging with any module which use lex/yacc syntax/philosophy. > pyparser looks good to me, but before I dive into it, I would really > appreciate feedback from members of this group A Verilog parser has been written using pyparsing at least once before, so I imagine that it shouldn't be too difficult to do so again. Of course, if you just need *a* Verilog parser, not necessarily one written by you, you could just email the guy who wrote it and ask him for a copy. Grep http://pyparsing.sourceforge.net/ for "Verilog". -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From philippe at philippecmartin.com Wed Jul 20 16:32:31 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 20 Jul 2005 20:32:31 GMT Subject: returning list of strings from Python COM to Visual basic 6 References: Message-ID: Sorry, it was in the book: Variant ! Regards; Philippe Philippe C. Martin wrote: > Hi, > > Is it possible ? > > ex: return ['1','2'] > > If so which type should I use in VB ? > > dim res as ??????? > > Set testObj = CreateObject("xxxx") > > res = testObj.AMethodThatReturnsAListOfStrings() > > > Thanks, > > Philippe From duncan.booth at invalid.invalid Fri Jul 22 13:05:55 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jul 2005 17:05:55 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: Michael Hoffman wrote: > Here's some code I just wrote seconds ago to construct a path for a > scp upload: > > """ > DST_DIRPATH = path("host:~/destination") > RSS_EXT = "rss" > > dst_filenamebase = os.extsep.join([postcode.lower(), RSS_EXT]) > dst_filepath = DST_DIRPATH.joinpath(dst_filenamebase) > """ > > With the current path implementation, this Just Works. It isn't at all obvious to me that it works: >>> import os >>> from path import path >>> postcode = "AA2 9ZZ" >>> DST_DIRPATH = path("host:~/destination") >>> RSS_EXT = "rss" >>> >>> dst_filenamebase = os.extsep.join([postcode.lower(), RSS_EXT]) >>> dst_filepath = DST_DIRPATH.joinpath(dst_filenamebase) >>> print dst_filepath host:~/destination\aa2 9zz.rss > If I were using > something that parsed and understood paths, the scp/rcp convention of > host:filename would either cause an error or have to be programmed in > separately. The current implementation is much more flexible. You still have to program your scp path separately from your filesystem path in order to handle the different conventions for path separator characters and maybe also escaping special characters in the path (I don't use scp much so I don't know if this is required). > What are the practical advantages and conveniences of *not* > subclassing from basestring? Simplification of the api: not having methods such as center, expandtabs and zfill. Not having the base class change from str to unicode depending on which system you run your code? Fewer undetected bugs (explicit is better than implicit)? Perhaps none of these matter in practice. As I said elsewhere I haven't used path for anything real, so I'm still finding surprises such as why this doesn't do what I expect: >>> p = path('a/b') >>> q = path('c/d') >>> p+q path(u'a/bc/d') If path didn't subclass string then either this would have been implemented, and probably would Do The Right Thing, or it wouldn't be implemented so I'd quickly realise I needed to do something else. Instead it does something suprising. From cantabile.03 at wanadoo.fr Sat Jul 9 05:03:35 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Sat, 09 Jul 2005 11:03:35 +0200 Subject: Pattern question In-Reply-To: <42ce9707@nntp0.pdx.net> References: <42cd5493$0$900$8fcfb975@news.wanadoo.fr> <42ce3f20$0$13033$636a15ce@news.free.fr> <42CE4D34.2000008@wanadoo.fr> <42ce9707@nntp0.pdx.net> Message-ID: <42cf92e7$0$1238$8fcfb975@news.wanadoo.fr> Scott David Daniels a ?crit : > cantabile wrote: > >> bruno modulix a ?crit : >> >>> You may want to have a look at the Factory pattern... >>> ... demo of class Factory ... > > > Taking advantage of Python's dynamic nature, you could simply: > # similarly outrageously oversimplified dummy example > class Gui(object): > def __init__(self, installer): > self.installer = installer > > class PosixGui(Gui): > pass > > class Win32Gui(Gui): > pass > > if os.name == 'posix': > makeGui = PosixGui > elif os.name == 'win32': > makeGui = Win32Gui > else: > raise "os %s not supported" % os.name > > > class Installer(object): > def __init__(self, guiFactory): > self.gui = guiFactory(self) > > def main(): > inst = Installer(makeGui) > return inst.gui.main() > > --Scott David Daniels > Scott.Daniels at Acm.Org Thank you too for this tip. :) Coming from C++ (mainly), I'm not used to this dynamic way of doing things. That's usefull. From benn at cenix-bioscience.com Mon Jul 11 06:42:55 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 11 Jul 2005 12:42:55 +0200 Subject: __eq__ on a dict Message-ID: <42D24D2F.1040604@cenix-bioscience.com> Hello, I can't find the docs for __eq__ on a dict and I can't find a description on what the eq does (strangely it does implement > and < but I have no idea what that does). Does anyone know (definitively) what the __eq__, __gt__, __lt__ methods do. BTW, google is not my friend - I invited it out for a drink last week and it stood me up :-). Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From jgrh2 at cam.ac.uk Mon Jul 25 14:53:19 2005 From: jgrh2 at cam.ac.uk (Jon Hewer) Date: Mon, 25 Jul 2005 19:53:19 +0100 Subject: psp & php integration Message-ID: <20050725185152.1B9D81E4007@bag.python.org> Hello, I am upgrading a PHP based site and want to use Python (using mod_python and psp file) to achieve what is required. However, I do not want to recode the navigation part of the site which is currently coded using PHP. Somehow I need to merge the outputs of the PHP file and my PSP file to create the HTML output which is sent to the browser. Can this be done inside my PSP file? If not, is there any other way in Python (or PHP) to achieve this? Thanks Jon -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Tue Jul 5 11:35:40 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Jul 2005 15:35:40 GMT Subject: More On - deepcopy, Tkinter References: Message-ID: phil wrote: > >> The deepcopy protocol does allow you to specify how complicated >> objects should be copied. Try defining __deepcopy__() in your objects >> to just copy the reference to the Canvas object instead of the object >> itself. > > I can't figure out from the docs what __deepcopy__ is or how it > > works. > I have about 25 classes of drawn objects. for instance > class linefromslope creates an instance of class line. > One of my "ugly solutions" involves a class prop: within each class, > put properties like slope and midpoint within the self.prop instance > and making a copy of that. > Would __deepcopy__ facilitate this? > Or am I assuming too much: is __deepcopy__ just a method > I invent to do what I want? > The docs say: > In order for a class to define its own copy implementation, it can > define special methods __copy__() and __deepcopy__(). The former is > called to implement the shallow copy operation; no additional > arguments are passed. The latter is called to implement the deep copy > operation; it is passed one argument, the memo dictionary. If the > __deepcopy__() implementation needs to make a deep copy of a > component, it should call the deepcopy() function with the component > as first argument and the memo dictionary as second argument. __deepcopy__ is a method which overrides the default way to make a deepcopy of an object. So, if you have a class with attributes a, b, and c, and you want to ensure that deepcopy copies a and b, but doesn't copy c, I guess you could do something like: >>> class MyClass: _dontcopy = ('c',) # Tuple of attributes which must not be copied def __deepcopy__(self, memo): clone = copy.copy(self) # Make a shallow copy for name, value in vars(self).iteritems(): if name not in self._dontcopy: setattr(clone, name, copy.deepcopy(value, memo)) return clone >>> class Copyable(object): def __new__(cls, *args): print "created new copyable" return object.__new__(cls, *args) >>> m = MyClass() >>> m.a = Copyable() created new copyable >>> m.b = Copyable() created new copyable >>> m.c = Copyable() created new copyable >>> clone = copy.deepcopy(m) created new copyable created new copyable >>> m.a is clone.a False >>> m.c is clone.c True >>> As you can see, the deepcopy only creates deep copies of 2 of the 3 attributes, 'c' is simply copied across as a shallow copy. and if you subclass MyClass you can modify the _dontcopy value to add additional attributes which must not be copied. From flab at large.net Mon Jul 18 03:52:44 2005 From: flab at large.net (flab ba) Date: Mon, 18 Jul 2005 00:52:44 -0700 Subject: Django - Rails killer comes... References: <15cuhhg8i6mrg$.ekh1brvux44n$.dlg@40tude.net> Message-ID: "Rails Killer" is a rather high and mighty claim, and as such, it isn't unreasonable to ask for substantial evidence to back it up. Quoting directly from the web site, in the section "Meet Django" " ...Django is well-suited for developing content-management system ..." To me, this seems like it places itself in competition with Zope, not Rails. If I'm wrong, could somebody explain why this is a "Rails Killer?" Thanks, Flab On Sat, 16 Jul 2005 03:26:07 +0200, JZ wrote: > http://www.djangoproject.com/ From bvande at po-box.mcgill.ca Sat Jul 2 02:54:57 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 02:54:57 -0400 Subject: Another newbie question from Nathan. In-Reply-To: <42c63341$0$6997$b9fe7a78@news.usenetrevolution.com> References: <42c63341$0$6997$b9fe7a78@news.usenetrevolution.com> Message-ID: <42C63A41.2000101@po-box.mcgill.ca> Nathan Pinno said unto the world upon 02/07/2005 02:25: > > Hi all. > > How do I make the computer generate 4 random numbers for the guess? I want > to know because I'm writing a computer program in Python like the game > MasterMind. > > Thanks. > > -- > Nathan Pinno > http://www.npinnowebsite.ca/ Hi Nathan, do you know how to make a program doing anything 4 times? If so, do that :-) Here's one way: >>> import random >>> def get_master_mind_guess(): ... guess = [] ... for i in range(4): ... guess.append(random.random()) ... return guess ... >>> get_master_mind_guess() [0.21236215888513332, 0.096166729147619479, 0.037667620585694728, 0.77529759474635485] >>> I doubt you need numbers between 0 and 1, but adjust to suit. I'd also suggest that you might find the Tutor list of real help. . Nothing wrong with not knowing how to do stuff like this -- few were born knowing, after all -- but the Tutor list specializes in answering in a way targeted to beginners. It's where I learned much of what I know. Best, Brian vdB From bogus@does.not.exist.com Fri Jul 1 12:55:02 2005 From: bogus@does.not.exist.com () Date: Fri, 01 Jul 2005 16:55:02 -0000 Subject: No subject Message-ID: #! rnews 4560 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 115 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Fri, 1 Jul 2005 16:40:26 GMT Xref: news.xs4all.nl comp.lang.python:384402 Tom Anderson writes: > On Fri, 1 Jul 2005, Adriaan Renting wrote: > > > I'm not a very experienced Python programmer yet, so I might be > > mistaken, but there are a few things that would make me prefer C++ > > over Python for large (over 500.000 LOC) projects. Strictly in terms of software engineering and language design, Python may well be better suited to large projects than C++ or Java. Code re-use, original coding and prototyping, unittests, and peer reviews are a lot easier with Python than with C++ or Java. The problem is that large projects tend to have portions which are performance sensitive. So a project might be 100K LOC of C with 200K LOC of Python. > > Hmm. I don't know C++, but here goes ... > > > - namespaces > > Aren't namespaces basically the same as packages/modules in python? > They serve the same purpose but are not 1:1 with a file. I personally can't think of a situation where I'd want 2 or more namespaces in a physical file, or 2 or more files per namespace. Therefore I don't see any advantage in the C++ approach. > > - templates > > These would be meaningless in python - they're part of typefulness, which ... > > > - strong type checking > > ... python eschews. Templates address (I hesitate to say "solve") static typing by adding back the polymorphism that static typing eliminates. Python avoids the fix-on-a-fix by doing dynamic strong typing in the first place. > > Not that this is necessarily a good thing. I have to say that my Java > roots do lead me to think that strong typing is a plus for big > projects, since it's a way of defining and enforcing interfaces > between bits of code written by different people (or by one person at > different times!). Optional static typing in python would be nice for > this. > Java has nothing on Modula-3. Talk about strong static typing... It used to take me 3 days to get the first compile to run on a new project. Yet after years of Modula-3 (and repeatedly seeing strong static typing pay off) I found python quite comfortable. Somehow the problems strong static typing addresses aren't a problem. > > - data hiding > > Surely you can hide data in python? > You can't genuinely hide data in Python. The best you can do is the "_" idiom. The question is why was data hiding invented in the first place. It prevents attempts to get at the underlying mechanisms instead of sticking with the external API. There are two reasons for this: a) Protection of the algorithms (e.g., trade secrets). Python doesn't solve that. Neither do C++ or Java, or assembler. If you have access to the binary, you can reverse engineer the functionality. b) Prevent ill-considered attempts at optimization through use of the lower layers. Those layers are there for a reason, usually to protect the external API from changes in the underlying library. Python solves that by attracting programmers intelligent enough to understand this.:-) > > - more available libraries and more advanced developement tools. If the library is in C, C++, or FORTRAN, Python can use it. Worst case you have to write your own bindings. As for "advanced development tools"... That's a flameware waiting to happen. > > True. The more advanced development tools are offset to a large degree > by the advanced crappiness of C++ as a language, though; i'd be > surprised if a C++ programmer borged up with all the latest tools was > actually more productive than a python programmer with a > syntax-colouring, auto-indenting text editor. It'd be very interesting > to get some real numbers on that. > > >> Ultimately, manageability of a project is far and away more about the > >> people involved and the techniques used than it is about any single > >> technology involved. > > > > Agreed. > > +1 getting to the crux of it. > > tom > > -- > In-jokes for out-casts -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From paolo.veronelli at gmail.com Wed Jul 27 13:44:48 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Wed, 27 Jul 2005 19:44:48 +0200 Subject: Create a variable "on the fly" In-Reply-To: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Message-ID: <42E7C810.8080708@gmail.com> Paul D.Smith wrote: > Can Python create a variable "on-the-fly". For example I would like > something like... > > make_variable('OSCAR', 'the grouch'); > print OSCAR; > > ...to output... Python has only 'on the fly' variables and ';' is not used for one expression in one line. Probably the tutorial is good to be read also. Paolino From python at rcn.com Wed Jul 6 05:35:50 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jul 2005 02:35:50 -0700 Subject: precision problems in base conversion of rational numbers References: <42C91973.6090208@po-box.mcgill.ca> <200507051049.37103.hancock@anansispaceworks.com> Message-ID: <1120642550.714547.256540@z14g2000cwz.googlegroups.com> [Terry Hancock] > > Needless to say, the conventional floating point numbers in Python > > are actually stored as *binary*, which is why there is a "decimal" > > module (which is new). > > > > If you're going to be converting between bases anyway, it probably > > makes little difference whether you are using the decimal module > > or not, of course. You'll have the same problems the conventional > > float numbers do. Not really. floats won't do because they may not have sufficient precision to differentiate rational values falling close the split between representable values in a given base. The decimal module offers arbitrarily large precision for making sure the error-term is small enough to not make a difference. [Brian van den Broek] > Thanks. mensanator provided the actual formula for my case. I had a > "magic number" in my code by which I multiplied my desired level of > "number of places in the representation" to obtain the value for > decimal.getcontext.prec. > > mensanator wrote: > > > The value you want for x is log(17)/log(10) = > > 1.2304489213782739285401698943283 > > where x was my "magic number". I've not had a chance to think it > through yet, but I feel confident that given the formula, I'll be able > to work out *why* that is the formula I need. That "formula" just gives a starting point estimate. The required decimal precision may be much higher. If the rational falls very close to the half-way point between two representable numbers, the calculation needs to be retried with increased precision until the split-point is definitive (when the error-term becomes less than the distance to the next representable value). For a simple example, convert both 10247448370872321 and 10247448370872319 from base ten to 4 digits of hex. The calculations need to be carried out to 15 places of hex (or 17 places of decimal) just to determine whether the fourth hex digit is a 7 or 8: >>> hex(10247448370872321) '0x24680000000001L' >>> hex(10247448370872319) '0x2467ffffffffffL' For an example of using decimal with iteratively increasing precision, see the dsum() recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 . Raymond From chris.arndt at web.de Mon Jul 11 20:35:24 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Tue, 12 Jul 2005 01:35:24 +0100 Subject: ftputil - uploading many files too long In-Reply-To: References: Message-ID: geon schrieb: > Hi, > > When I try to upload many files I get such a error message: > > [...] traceback deleted > > ftputil.ftp_error.TemporaryError: 421 Login Timeout (25 seconds): closing contro > l connection. > > I think its not about many files but because of it takes too long for my ftp server (25s). I tried > many things but nothing helps. Well, the error message seems to say, that the server closes the connection because it timed out waiting for the client to login or because it was idle for to long. But without some example code that exhibits the problem we really can't devine what you are trying to do... Also note that ftputil has it's own mailing list. Regards, Chris From cdkrug at worldnet.att.net Fri Jul 8 13:09:41 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Fri, 08 Jul 2005 17:09:41 GMT Subject: Having trouble importing against PP2E files Message-ID: List: I'm trying to use the example files from Programming Python, 2nd Ed. I've copied them into c:\Python24\Examples\PP2E. Launching any of the examples programs by themselves seems to work spiffily. Using regedit, I appended "c:\Python24\Examples\PP2E" to Pythonpath from the immediate window, executing the line: from PP2E.launchmodes import PortableLauncher Raises the exception: Import Error: no module named PP2E.launchmodes However if I copy launchmodes.py into my work directory, it imports successfully. Both "Examples" above and "Examples\PP2E" contain the __init__.py file. Obviously, I'm missing a setup step here. What magic do I need to perform to get Python to find modules in the Examples heirarchy? Is there any way to check from the immediate window where Python will search for modules? Pythonpath appears to be correct, but the file isn't importing unless I copy it to the current directory. Thanx Charles From me at privacy.net Wed Jul 20 11:32:09 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 20 Jul 2005 11:32:09 -0400 Subject: getting the class name of a subclass References: <5UsDe.149277$Yz5.7850081@phobos.telenet-ops.be> Message-ID: On Wed, 20 Jul 2005 14:06:57 GMT, flupke wrote: > file class_name.py > ======================== > class A(object): > def __init__(self): > print "I'm A" > def printclass(self): > print "Name ",__name__ > print "Class ",A.__name__ Why "A.__name__" and not "self.__class__.__name__"? Regards, Dan -- Dan Sommers From aahz at pythoncraft.com Thu Jul 28 23:24:09 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Jul 2005 20:24:09 -0700 Subject: Multithreaded class with queues References: Message-ID: In article , Antal Rutz wrote: > >I wrote a little class to make multihreading easier. It's based on one >of aahz's threading example scripts. What it does: Thanks! >It spawns up number of CollectorThreads and one ProcessThread. The >CollectorThreads listen on one queue (inputqueue), read, process the >data (with colfunc), put the result onto the outputqueue. The >ProcessThread listens on the outputqueue, reads, processes (with >prfunc). end. (more details in the attached file) > >it seems to work with test functions but when I use a network-intensive >function (snmp-queries) it just gets slower with maxThreads set to more >than 1. Hrm. There's nothing obviously wrong. What happens if you use it as a spider? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From peter at engcorp.com Sat Jul 2 23:50:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 23:50:50 -0400 Subject: Python, mysql, floating point values question In-Reply-To: References: <43b72594050701154055297e73@mail.gmail.com> <21gec1lgopab3sjbhkh6m2amd51e1rcq1v@4ax.com> Message-ID: Terry Hancock wrote: > On Saturday 02 July 2005 08:53 pm, Dennis Lee Bieber wrote: > And for that matter, some of the posters here have *been* 14. Terry, almost every single one of the posters here have been 14. At some time. :-) -Peter From __peter__ at web.de Wed Jul 13 13:29:05 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Jul 2005 19:29:05 +0200 Subject: Frankenstring References: Message-ID: Thomas Lotze wrote: > Peter Otten wrote: > >>>>> class frankenstring(StringIO): >> ... def next(self): >> ... c = self.read(1) >> ... if not c: >> ... raise StopIteration >> ... return c > > Repeated read(1) on a file-like object is one of the ways of doing it with > existing tools I labelled "clumsy" in the original posting ;o) Not clumsy, just slow. I hope you'll let us know how much faster your final approach turns out to be. By the way, I'll consider anything that doesn't implement seek() and tell() cheating :-) Peter From Scott.Daniels at Acm.Org Mon Jul 18 17:19:59 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 18 Jul 2005 14:19:59 -0700 Subject: What is your favorite Python web framework? In-Reply-To: <0lSCe.2023$je2.289853@news20.bellglobal.com> References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> <8Y-dnatKvJ13LEbfRVn-rQ@powergate.ca> <1121707100.874433.115360@g49g2000cwa.googlegroups.com> <0lSCe.2023$je2.289853@news20.bellglobal.com> Message-ID: <42dc14e1$1@nntp0.pdx.net> Luis M. Gonzalez wrote: > I read the expression "Dark horse contender" many times, and i guess it > has some reminiscence from medieval times and the cavalry stories. > It meaning is something like the "unknown that could be the new champ", > someone intriguing and mysterious who doesn't unveil its skills untill > showtime. Am I right? My understanding is that it is a horse-racing phrase. Some unprincipled racers would dye a horse to disguise him and get better odds. Obviously this only works to make a horse darker. A "dark horse" is an unknown quantity -- the phrase is usually only applied to horses that show well without the normal track record preceding that success. --Scott David Daniels Scott.Daniels at Acm.Org From python at rcn.com Wed Jul 20 01:41:01 2005 From: python at rcn.com (Raymond Hettinger) Date: 19 Jul 2005 22:41:01 -0700 Subject: Python Programming Contest References: Message-ID: <1121838061.749455.44630@g14g2000cwa.googlegroups.com> [Brian Quinlan] > I'm doing to judge the solutions based on execution speed. It sucks but > that is the easiest important consideration to objectively measure. . . . > I'm always looking for feedback, so let me know what you think or if you > have any ideas for future problems. I'm curious about the stability of your timing setup. If you run your own version of fly.py several times with the same starting seed, how much variation do you see between runs? When I tried the provided setup, it was highly variable. To get useful measurements, I needed another timing framework: import timeit setup = """ import fly_test import random from fly import fly random.seed(1234567891) params = [] for i in xrange(100): schedule = fly_test.generate_schedule() from_, to = fly_test.pick_cities(schedule) params.append( (from_, to, schedule) ) """ stmt = """ for p in params: fly(*p) """ print min(timeit.Timer(stmt, setup).repeat(5, 3)) From cam.ac.uk at mh391.invalid Sat Jul 30 12:57:11 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 30 Jul 2005 17:57:11 +0100 Subject: Path inherits from basestring again In-Reply-To: <3l186cF10lgkmU1@individual.net> References: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> <3l186cF10lgkmU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > It's much the same as with @ decorators. Those who have used them much > don't object to the syntax any more. I do and I still think they are ugly. -- Michael Hoffman From luismgz at gmail.com Mon Jul 18 13:18:20 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 18 Jul 2005 10:18:20 -0700 Subject: What is your favorite Python web framework? In-Reply-To: <8Y-dnatKvJ13LEbfRVn-rQ@powergate.ca> References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> <8Y-dnatKvJ13LEbfRVn-rQ@powergate.ca> Message-ID: <1121707100.874433.115360@g49g2000cwa.googlegroups.com> Peter Hansen wrote: > Gerhard Haering wrote: > > On Mon, Jul 18, 2005 at 09:06:21AM -0400, Peter Hansen wrote: > >>I'm not familiar with this expression. What do you mean by "black horse"? > > > > Maybe "the Ferrari of pythonic frameworks" (black horse on yellow > > background being the symbol of Ferrari). > > I know there are "black sheep" in some families, and "dark horse > candidates". Also yellow-bellied sapsuckers. There's a "black horse" > fish in the Mississippi valley (also, quite coincidentally, of the > sucker family). Not entirely sure that was the intended connotation. :-) > > -Peter I'm used to make those mistakes too... This mailing list taught me more English than Python for sure. I read the expression "Dark horse contender" many times, and i guess it has some reminiscence from medieval times and the cavalry stories. It meaning is something like the "unknown that could be the new champ", someone intriguing and mysterious who doesn't unveil its skills untill showtime. Am I right? Cheers, Luis From mwm at mired.org Fri Jul 29 17:35:11 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 29 Jul 2005 17:35:11 -0400 Subject: multiple inheritance super() References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> <1122653176.013770.106080@g49g2000cwa.googlegroups.com> Message-ID: <86br4ljnxs.fsf@bhuda.mired.org> "Michele Simionato" writes: > adding methods on the fly and metaclasses could live pretty well > without > multiple inheritance. There would be no real loss > of power and hopefully less monstruosities such > a Zope 2. But maybe this is just wishful thinking ... Um, no real loss of power? Well, in the sense that all languages are turing-equivalent, maybe. My current project includes a small set of classes that all deal with web pages. The classes exist in three layers: the first layer is very abstract, and provides a general mechanism. The second layer adapts the general mechanasm to a specific case. The last layer provides application-specific functionality. The classes intercommunicate, but are generally completely unrelated to each other except for the more concrete classes inheriting from the layer above. So far, so good - it's all simple single inheritance. Now, I have a class Utility that collects utility methods that are useful for dealing with web pages: extracting data, filling out forms, etc. These are provided as a mixin. The classes that need this functionality inherits from it as well as their parent. The classes that don't need it don't. This makes use of multiple inheritance. Without multiple inheritance, I would have had to make the Utility class a parent of all the most abstract classes. Some of the those classes don't need that functionality - but their children do, so they have to inherit from it. Children's needs shouldn't influence the implementation of the child - that's simply ugly. Also, it creates an apparent relationship between all the most abstract classes that doesn't really exist. Do you have a proposed solution that doesn't have these problems? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From oliver.andrich at gmail.com Tue Jul 19 15:04:16 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Tue, 19 Jul 2005 21:04:16 +0200 Subject: CONNCET TO SOAP SERVICE In-Reply-To: <20050712135241.80A2340487@netbox-marcqenbaroeul1.unilog.fr> References: <20050712135241.80A2340487@netbox-marcqenbaroeul1.unilog.fr> Message-ID: <6f7b52d050719120476601dbb@mail.gmail.com> Hi, I am not sure if this addresses your problem, but I access a rich SOAP based webservice set on a Tomcat Server implemented using Axis with SOAPpy. We use basic auth as specified in http for access control to these services. For me it is enough to create my proxy classes this way. proxy = SOAPpy.SOAPProxy("http://user:password at my.server.de:8080/axis/services, "MyService") Afterwards I have access to the system. Bye, Oliver 2005/7/12, Slaheddine Haouel : > > > > Can you help me plz ? I want to wonnect to SOAP webservices but before I > must be authentificated on a apache server, I used SOAPpy module but I don't > know how I can be authentified on the apache server???? > > > > thx > > > > Slaheddine Haouel > > Unilog NORD > > t?l : 03 59 56 60 25 > > t?l support : 03 59 56 60 68 > > Email : slaheddine.haouel at unilog.fr > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Oliver Andrich --- http://fitheach.de/ From dieter at handshake.de Fri Jul 1 14:22:19 2005 From: dieter at handshake.de (Dieter Maurer) Date: 01 Jul 2005 20:22:19 +0200 Subject: importing packages from a zip file References: <42c2d483$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes on Wed, 29 Jun 2005 10:36:29 -0700: > Peter Tillotson wrote: > ... > > from myZip.zip import myModule.py > > > Does this work for you? It gives me a syntax error. > > Typically, put the zip file on the sys.path list, and import modules > and packages inside it. If you zip up the above structure, you can use: > > sys.path.insert(0, 'myZip.zip') > import base.branch1.myModule The alternative is to use a "zipimporter" (from module "zipimport") and use the "importer protocol" (documented in a PEP). From mwm at mired.org Fri Jul 29 17:19:11 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 29 Jul 2005 17:19:11 -0400 Subject: writing a web client References: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> <1122640048.898562.3600@g43g2000cwa.googlegroups.com> Message-ID: <86oe8ljoog.fsf@bhuda.mired.org> "Fuzzyman" writes: > Ajar wrote: >> I want to write a program which will automatically login to my ISPs >> website, retrieve data and do some processing. Can this be done? Can >> you point me to any example python programs which do similar things? >> >> Regards, >> Ajar > > Very easily. Have a look at my article on the ``urllib2`` module. > > http://www.voidspace.org.uk/python/articles.shtml#http > > You may need to use ClientCookie/cookielib to handle cookies and may > have to cope with BASIC authentication. There are also articles about > both of these as well. > > If you want to handle filling in forms programattically then the module > ClientForm is useful (allegedly). The last piece of the puzzle is BeautifulSoup. That's what you use to extract data from the web page. For instance a lot of web pages listing data have something like this on it: ... ...
Item:Value
You can extract value from such with BeautifulSoup by doing something like: soup.fetchText('Item:')[0].findParent(['td', 'th']).nextSibling.string Where this checks works for the item being in either a td or th tag. Of course, I recommend doing things a little bit more verbosely. In my case, I'm writing code that's expected to work on a large number of web pages with different formats, so I put in a lot of error checking, along with informative errors. links = table.fetchText(name) if not links: raise BadTableMatch, "%s not found in table" % name td = links[0].findParent(['td', 'th']) if not td: raise BadmatchTable, "td/th not a parent of %s" % name next = td.nextSibling if not next: raise BadTableMatch, "td for %s has no sibling" % name out = get_contents(next) if not out: raise BadTableMatch, "no value string found for %s" % name return out BeautifulSoup would raise exceptions if the conditions I check for are true and I didn't check them - but the error messages wouldn't be as informative. Oh yeah - get_contents isn't from BeautifulSoup. I ran into cases where the
tag held other tags, and wanted the flat text extracted. Couldn't find a BeautifulSoup method to do that, so I wrote: def get_contents(ele): """Utility function to return all the text in a tag.""" if ele.string: return ele.string # We only have one string. Done return ''.join(get_contents(x) for x in ele) http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fairwinds at eastlink.ca Fri Jul 1 01:57:05 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 01 Jul 2005 02:57:05 -0300 Subject: Splitting string into dictionary In-Reply-To: <1120195999.101197.135740@z14g2000cwz.googlegroups.com> Message-ID: Thanks George! You guys are great! I am always learning. Python is awesome!! On Friday, July 1, 2005, at 02:33 AM, George Sakkis wrote: > "Robert Kern" wrote: > >> Ignore the last message. >> >> translations = [x.strip(" '") for x in line.split('|')] >> d = dict(zip(translations[::2], translations[1::2])) > > Or in case you're working with a lot and/or huge records, the second > line can be more efficiently written as: > > from itertools import izip, islice > d = dict(izip(islice(translations,0,None,2), > islice(translations,1,None,2))) > > George > > -- > http://mail.python.org/mailman/listinfo/python-list > From gsakkis at rutgers.edu Wed Jul 6 09:21:45 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 6 Jul 2005 06:21:45 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: <1120656105.175799.311610@f14g2000cwb.googlegroups.com> "Terry Reedy" wrote: > "George Sakkis" wrote in message > news:1120610787.940292.15210 at g43g2000cwa.googlegroups.com... > > Still it's hard to explain why four specific python keywords - def, > > del, exec and elif - were chosen to be abbreviated, > > Precedence in other languages and CS usage? What precedence ? I don't know of another language that uses def or del at least; even C++ which compared to python is much more terse uses "delete" instead of del. And in any case, curly braces for grouping statements is much more prevalent in other languages and CS usage but (fortunately) python chose indentation. > > So, who would object the full-word versions for python 3K ? > > def -> define > > del -> delete > > exec -> execute > > These three I might prefer to keep. > > > elif -> else if > > This one I dislike and would prefer to write out. I never liked it in > whatever else language I first encountered it and still don't. In contrast to the first three changes which would be straightforward, changing "elif" to "else if" would add (a little?) complexity to the parser by allowing "else" to be followed either by a colon (the only choice now) or "if", though I don't think this would be a decisive factor. George From jasondrew72 at gmail.com Fri Jul 22 09:09:40 2005 From: jasondrew72 at gmail.com (Jason Drew) Date: 22 Jul 2005 06:09:40 -0700 Subject: tuple to string? In-Reply-To: References: Message-ID: <1122037780.723777.242190@g44g2000cwa.googlegroups.com> ''.join((chr(e) for e in (0x73, 0x70, 0x61, 0x6D))) From future_retro at yahoo.co.uk Wed Jul 13 12:45:48 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 13 Jul 2005 09:45:48 -0700 Subject: exec method WMI Message-ID: <1121273148.010439.70100@g44g2000cwa.googlegroups.com> Hi, I'm trying to use the AddPrinterDriver method of Win32_PrinterDriver to create a new..... print driver. I can't get my head round how I need to do this. So far I have import win32com.client WBEM = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" + "." + r"\root\cimv2") WBEM.Security_.Privileges.AddAsString("SeLoadDriverPrivilege") drv = WBEM.Get("Win32_PrinterDriver").SpawnInstance_() drv.Properties_('Name').Value = "Marcs Printer 2550" drv.Properties_('SupportedPlatform').Value = "Windows NT x86" drv.Properties_('Version').Value = "3" drv.Properties_('DriverPath').Value = 'C:\\test\\HPZPP034.DLL' drv.Properties_('InfName').Value = 'C:\\test\\hpc2550d.inf' method = drv.Methods_('AddPrinterDriver') InParms = method.InParameters InParms.Properties_.Item('DriverInfo').Value = drv drv.ExecMethod_('AddPrinterDriver',InParms) I'm using spawninstance to create a new object and then editing the properties of it. I'm then setting the InParameters for the method to be the new object. When executing the method I get SWbemObjectEx object not found. I think I am not setting the DriverInfo correctly, should it be an object? The MSDN site doesn't say what DriverInfo should be. Any help would be grand. Thanks, MW. From iamsidd at gmail.com Thu Jul 28 15:10:12 2005 From: iamsidd at gmail.com (Sidd) Date: 28 Jul 2005 12:10:12 -0700 Subject: To thread or not to thread Message-ID: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> Hello, I was recently reading an article on threading in python and I came across Global Interpreter Lock,now as a novince in python I was cusrious about 1.Is writing a threaded code in python going to perform well than a normal python code.If so on what basis can it performance be measured. 2.Is writing a threaded code in python better than a code written in C/C++ using PTHREADS. If someone can comment on these questions, it would be great. From gene.tani at gmail.com Sat Jul 16 12:33:46 2005 From: gene.tani at gmail.com (gene tani) Date: 16 Jul 2005 09:33:46 -0700 Subject: What module to use to get a file from a website? In-Reply-To: <1121464923.522948.46080@f14g2000cwb.googlegroups.com> References: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> <1121464923.522948.46080@f14g2000cwb.googlegroups.com> Message-ID: <1121531626.797710.64270@g49g2000cwa.googlegroups.com> curl and wget are the most robust ways to do this http://cool.haxx.se/mailman/listinfo/curl-and-python http://www.gnu.org/software/wget/wget.html From tiissa at nonfree.fr Sat Jul 30 12:49:27 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 30 Jul 2005 18:49:27 +0200 Subject: Comparison of functions In-Reply-To: References: Message-ID: <42ebaf94$0$17086$626a14ce@news.free.fr> Steven D'Aprano wrote: > It was easy. I never once asked myself whether some complex number was > greater or less than another, I just asked "which one comes first in a > lexicographic sort?" > > The two questions are NOT the same, and it is an ugliness in an otherwise > beautiful language that Python treats them as the same. The point is Python does not. The order you proposed above can be implemented using a comparison function you can pass to the sort function of lists [1] or the sorted builtin [2]. If the elements can be compared, Python offers you not to pass the cmp function to sort if you want to use this default order. Python allows you to use the default ordering to sort a list but does not treat both questions in the same manner. However, the fact is ordering a list using the default '<' happens pretty often. In the case of complex numbers, no mathematically sound comparison function exists and Python does not impose some default function that would be called a wart. [1] http://docs.python.org/lib/typesseq-mutable.html [2] http://docs.python.org/lib/built-in-funcs.html From steve at REMOVETHIScyber.com.au Sun Jul 24 14:22:32 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 25 Jul 2005 04:22:32 +1000 Subject: tuple to string? References: <3kd89rFte1h5U1@individual.net> <42e1788b@news.eftel.com> <3ke61oFtnkg9U1@individual.net> <42e24696$1@news.eftel.com> <42e381a6@news.eftel.com> Message-ID: On Sun, 24 Jul 2005 10:39:44 -0700, Robert Kern wrote: > John Machin wrote: > >> No precedence rules -> no relevance to the topic > > Precedence rules of other languages -> no relevance to the topic I thought the topic was -- or at least had wandered in the direction of -- whether or not it was unthinkable for the precedence of % to be anything but that of multiplication and division. Surely the precedence rules of other languages have some relevance to that question. Still, the subject is rapidly losing whatever interest it may have had. -- Steven. From korakot at gmail.com Sun Jul 31 07:05:40 2005 From: korakot at gmail.com (korakot at gmail.com) Date: 31 Jul 2005 04:05:40 -0700 Subject: Google maps on your mobile phone with python for series60 Message-ID: <1122807940.783916.129270@g47g2000cwa.googlegroups.com> I have written some simple prototype to display google maps data on mobile phone (Nokia Series 60). http://discussion.forum.nokia.com/forum/showthread.php?threadid=63694 Now it can scroll, zoom in, zoom out and toggle between map and sattelite mode. The current code is 100 lines (exactly). You may have some good ideas and try adding it to the code. (smooth scrolling and zooming come to mind) You need to install the python for series 60 1.1.6 first http://www.forum.nokia.com/main/0,,034-821,00.html Korakot Chaovavanich From harlinseritt at yahoo.com Mon Jul 11 20:01:39 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 11 Jul 2005 17:01:39 -0700 Subject: Formatting data to output in web browser from web form In-Reply-To: <42CFBBCC.9030700@lexicon.net> References: <1120909105.049621.210020@z14g2000cwz.googlegroups.com> <42CFBBCC.9030700@lexicon.net> Message-ID: <1121126499.348386.324050@o13g2000cwo.googlegroups.com> This is perfect. Thanks! From thorsten at thorstenkampe.de Thu Jul 7 09:08:23 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 7 Jul 2005 14:08:23 +0100 Subject: Windows Cmd.exe Window References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: * Giles Brown (2005-07-07 13:56 +0100) > For my sins I'm a MS Windows user at work and apart from that I have a > small problem ... > > I like to write python scripts to do small tasks and then double click > on them from the file explorer to run them. > > Unfortunately I'm not perfect and sometimes I make mistakes and have > unhandled exceptions or syntax errors when running the scripts. The > default behaviour is to shut down the command window which leaves you > no chance of reading the exception. > > In the past I have created .bat wrapper files that just call the python > interpreter, but it is a bit tedious to have to create a matching .bat > file for every script. So I came up with the following approach... > > 1. Copy python.exe to pythoncmd.exe > 2. Add a bit of stuff to sitecustomize.py > 3. Add a special first line to every python script and give it a .cmd > extension. > > The stuff added to sitecustomize.py (actually I created a > sitecustomize.py for this) is: > """ > import sys > import os > > if os.path.basename(sys.executable) == 'pythoncmd.exe': > > def cmdexcepthook(*args): > sys.__excepthook__(*args) > # Let use confirm/inspect error > os.system('pause') > > sys.excepthook = cmdexcepthook > """ > > The special first line is: > > @pythoncmd -x "%~f0" %* & exit /b > > (In the python.org FAQ for windows it says > @setlocal enableextensions & python -x %~f0 %* & goto :EOF > but since I have no idea which is "right" I chose the simpler looking > one) > > This approach does require pythoncmd.exe to by in your %PATH% but I > think that is reasonable ;) > > I am a bit disappointed I couldn't think of a way of deciding if I was > running a ".cmd" file in sitecustomize.py so that I could just use the > normal python.exe. Using a renamed interpreter .exe is just a trick > for detecting when I am running .cmd files, but it means that the > script won't run on another machine that hasn't had the python.exe > copied to pythoncmd.exe on it. Which is a shame. > > So my question. Is there a better way? I'm not really happy with this > approach. Should I stop worrying and go and play my new ukulele? > Answers please. I think it's a FAQ to: use raw_input at the end to prevent closing. From ms at cerenity.org Sat Jul 30 04:25:17 2005 From: ms at cerenity.org (Michael Sparks) Date: Sat, 30 Jul 2005 10:25:17 +0200 Subject: Python-cgi web or Perl-cgi script doubt References: Message-ID: <42eb477c$0$3483$ed2619ec@ptn-nntp-reader03.plus.net> praba kar wrote: > I want to know difference between > Python-cgi and Perl-cgi and also I want > to which one is efficient from the performance. Possibly the most important difference between the two is when you're using JUST cgi - ie no mod_perl, no mod_python, etc. With python, if your cgi is structured to use more than one file, then your programs can be compiled and stored on disk (compiled to something called bytecode). This can just be loaded and executed immediately on subsequent runs. With perl, the program needs to be loaded and recompiled with each run. For small CGI systems this difference is negligible, but for large CGI based systems (eg when using a large framework), these differences can become very important - if you do not have the option to use mod_perl/mod_python or similar. However, many people running large web systems do tend to use mod_perl and friends when using perl which discounts this argument pretty much completely. That said, I'd suggest looking to see *what* you want to do, look at what *tools* are available and *then* decide which *language* to use. Personally I find python nicer for this sort of things these days - larger because it naturally encourages better strutcure. (And this is after having using perl day-in, day-out for 5 years, and still liking perl :-) Hope that's of some use, Michael. From lambacck at computer.org Thu Jul 14 17:22:22 2005 From: lambacck at computer.org (Chris Lambacher) Date: Thu, 14 Jul 2005 17:22:22 -0400 Subject: Changing size of Win2k/XP console? In-Reply-To: <42d6cf32$0$16170$39db0f71@news.song.fi> References: <42d6bdd2$0$16170$39db0f71@news.song.fi> <42d6cf32$0$16170$39db0f71@news.song.fi> Message-ID: <20050714212222.GA8637@computer.org> Referring to the documenation you will have to use that function and SetConsoleWindowInfo to get the effect you want. Basically SetConsoleScreenBufferSize sets the size for the console and SetConsoleWindowInfo sets the size for the window containing the console. The window size can't be bigger that the console size. If the console size is bigger than the window, you will end up with scrollbars. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/setconsolescreenbuffersize.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/setconsolescreenbuffersize.asp You might want the get function as well: GetConsoleScreenBufferInfo http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/setconsolescreenbuffersize.asp When in doubt about the Microsoft API see the MSDN. -Chris -Chris On Thu, Jul 14, 2005 at 11:48:09PM +0300, Sheeps United wrote: > "Peter Hansen" wrote in message > news:I9-dnekiad4vVUvfRVn-uw at powergate.ca... > > Which Windows API call did you try using? Can you show us a line or two > > of code that you tried? Most likely then someone will be able to point > > out what went wrong and it will work. (Chances are that very few here > > know the API call required, so by not mentioning it you're severely > > limiting the number of answers you are likely to get.) > > No actual code, yet. > > I'm far from sure if it's the right one, but I think it could be > SetConsoleScreenBufferSize from Kernel32. Hrr, for some reason I have nasty > feeling in back of my head... That could also be totally wrong way of > approaching. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From pink at odahoda.de Sun Jul 31 07:14:42 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Sun, 31 Jul 2005 13:14:42 +0200 Subject: python SMTP server References: <1122759885.881136.186360@g47g2000cwa.googlegroups.com> Message-ID: Fernando M. wrote: > Hi, > i made a test with smtplib module a few days ago, for sending mails, > and i was wondering if there's another module for running an SMTP > server, so i could make a standalone script for sending mails without > using an external SMTP server. > I've been searching but i'm not sure if there are modules for it, or > anything. > Which ones are my options? An SMTP server is (simplified) a program that listens on port 25 for incoming mails. What you probably want to do is: Do a DNS query for the recipent's domain and use smtplib to connect to the server specified in the MX record. There was a module for DNS querie (not in Python's stdlib), but I forgot how it was called or where you could find it (try the Vaults of Parnassus or PyPI). Or you may use an external tool like 'dig' ('dig mx DOMAIN'). But you should be aware of the fact that (if you send mail from a dialup machine without going through a relay server) your mails will quickly be marked as spam - I hope you do not intend to send spam... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From steve at REMOVETHIScyber.com.au Sat Jul 9 00:38:00 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 09 Jul 2005 14:38:00 +1000 Subject: why UnboundLocalError? References: Message-ID: On Fri, 08 Jul 2005 21:21:36 -0500, Alex Gittens wrote: > str = '' > while measure()!=0: > str += cutbits() It is considered poor practice to use the names of built-ins like str or list as variable names. > What's causing the error? Did you actually copy all of the code? It seems to me that once your code has assembled the string, it doesn't actually do anything with it. Not even return it. Also, you seem to be calling a join method on lists. Lists don't have join methods. The rest of your code is very hard for me to follow, especially as you have not put any comments in and seem to spend a lot of time re-inventing the wheel. I would do something like this to handle fixed-width printing. (Untested.) def fieldprint(widths,alignments,fields): """Given a list of widths, alignments and fields (text) representing a single row of text formatted in columns, returns an aligned version. Text is never truncated to fit, and is padded with spaces. Examples: fieldprint([5, 5, 5], "lcr", ["cat", "12345", "12345"]) => "cat 1234512345" fieldprint([5, 5, 5], "rcl", ["cat", "dog", "12345"]) => " cat dog 12345" fieldprint([5, 5, 5], "rcl", ["cat", "dog", "mice"]) => " cat dog mice " """ # helper function def align(width, alignment, text): """Give a width, an alignment, and some text, returns a string containing that text aligned correctly in columns. """ if alignment in "Ll": # left-justify return text.ljust(width) elif alignment in "Rr": # right-justify return text.rjust(width) elif alignment in "Cc": # centered return text.center(width) else: raise ValueError("Unsupported alignment '%s'" % alignment) if not len(widths) == len(alignments) == len(fields): raise 'Argument mismatch' columns = zip(widths, alignments, fields) # builds a list of tuple of (width, alignment, field) L = [] # hold each formatted column as it is built for column in columns: L.append(align(*column)) # equivalent to: # L.append(align(column[0], column[1], column[2])) return ''.join(L) Hope this is helpful to you. -- Steven. From lbates at syscononline.com Thu Jul 7 18:19:49 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 07 Jul 2005 17:19:49 -0500 Subject: Options to integrate Python modules into native windows applications In-Reply-To: References: Message-ID: pywin32 and COM is good. Seems to work for me. Other methods (services, sockets, pipes, etc.) can also work well, but it depends on what you want to do and how you wish to communicate between the modules. Larry Bates Philippe C. Martin wrote: > Hi, > > I am looking for the pros and cons as to how to integrate a Python module > into a Windows native application. > > So far I have looked at > > 1) coding the C wrapper myself > 2) using Pyrex > 3) go for pywin32 and COM > > Thanks, > > Philippe > > From davefickbohm at yahoo.com Thu Jul 21 20:12:20 2005 From: davefickbohm at yahoo.com (David Fickbohm) Date: Thu, 21 Jul 2005 17:12:20 -0700 (PDT) Subject: looking for a book on python Message-ID: <20050722001220.9833.qmail@web50807.mail.yahoo.com> People, could someone please recommend a book on python. Ideally a windows oriented one ? Thanks Dave Dave Fickbohm Use Technology to the Fullest 1250 45th st suite 200 Emeryville, CA, 94608 510 594 4151 voice __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Wed Jul 13 16:13:01 2005 From: me at privacy.net (Simon Morgan) Date: Wed, 13 Jul 2005 20:13:01 GMT Subject: constructor list slice confusion Message-ID: Hi, Can somebody please explain to me why: class SomeClass: def __init__(self, contents=[]): self.contents = contents[:] def add(self, element): self.contents.append(element) when called a second time (i.e. to create a new instance of a SomeClass object) results in self.contents being assigned an empty list when say for example I've done: foo = SomeClass() foo.add(1) foo.add(2) beforehand? I understand that the default value is only evaluated once and therefore retains a reference to the same list which is why: self.contents = contents results in objects sharing the same contents, but I was under the impression that [:] basically produced a copy of an entire list. So in that case wouldn't blah.contents contain a copy of foo.contents when it's created given that no other list is specified as a parameter to __init__? I've read a couple of explanations which were rather vague so I'm having trouble grokking what's going on. Thanks. From steve at REMOVETHIScyber.com.au Tue Jul 12 22:29:40 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 13 Jul 2005 12:29:40 +1000 Subject: math.nroot [was Re: A brief question.] References: Message-ID: (All previous quoting ruthlessly snipped.) A question for Tim Peters, as I guess he'll have the most experience in this sort of thing. With all the cross-platform hassles due to the various C compilers not implementing the IEEE standard completely or correctly, I wonder how much work would be involved for some kind soul to implement their own maths library to do the lot, allowing Python to bypass the C libraries altogether. Are you falling over laughing Tim, or thinking what a great idea? What sort of work is needed? Is it, say, as big a job as maintaining Python? Bigger? One weekend spent working solidly? -- Steven. From danb_83 at yahoo.com Sat Jul 23 23:25:37 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 Jul 2005 20:25:37 -0700 Subject: consistency: extending arrays vs. multiplication ? In-Reply-To: References: Message-ID: <1122175536.959648.101230@z14g2000cwz.googlegroups.com> Soeren Sonnenburg wrote: > Hi all, > > Just having started with python, I feel that simple array operations '*' > and '+' don't do multiplication/addition but instead extend/join an > array: > > a=[1,2,3] > >>> b=[4,5,6] > >>> a+b > [1, 2, 3, 4, 5, 6] > > instead of what I would have expected: > [5,7,9] To get what you expected, use [x + y for (x, y) in zip(a, b)] From bokr at oz.net Mon Jul 4 14:28:04 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 04 Jul 2005 18:28:04 GMT Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> <1120496836.806367.65780@z14g2000cwz.googlegroups.com> Message-ID: <42c97d97.525382369@news.oz.net> On Mon, 04 Jul 2005 19:25:13 +0200, Thomas Heller wrote: >"Derek van Vliet" writes: > >> The second method you describe sounds like it is along the lines of >> what I need to do. Is there a way to do this using the Python/C API? >> >> For instance, if I have the contents of a pyc file loaded entirely into >> memory, and I have a pointer to the beginning of the file and the size >> in bytes at my disposal, can I import that by any means? > >The .pyc file format is sort of 'documented' in lib/py_compile.py. >IIRC, it is a magic number, a timestamp, plus a marshalled code >object. > I'm wondering if what the OP has is really .pyc files "in memory" or code objects. If he is using Py_CompileString to compile "scripts" extracted from XML, wouldn't he get code objects? And if so, wouldn't he have to execute them in a constructed module dict and be careful of normal imports in the "scripts" etc etc to simulate import? Anyway, it feels like what he wants to do could be done, but "the devil is in the details," which are missing ;-) Regards, Bengt Richter From fumanchu at amor.org Fri Jul 15 13:53:32 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 15 Jul 2005 10:53:32 -0700 Subject: ANN: CherryPy-2.1.0-beta released Message-ID: <3A81C87DC164034AA4E2DDFE11D258E377258A@exchange.hqamor.amorhq.net> Damjan wrote: > > I am happy to announce the first beta release of CherryPy-2.1 > ... > > unicode decoding/encoding, > > This especially interesting to me. > Is CherryPy completelly unicode (and UTF-8) ready? > The thing that frustrates me about quixote2 is that it has a lot of > assumptions that text is a str object in the latin1 encoding. > I succeded to patch quixote to be usable but that may not be enough. > > My quixote application works with unicode objects all the > time, and the only place I want UTF-8 is when the content > is sent to the client... (or when its stored in a database > or file which I handle myself fine). Encoding is a snap in CherryPy 2.1. Write your application using unicode objects, then have all output converted to UTF-8 by simply writing in your config file: encodingFilter.on = True To use a different encoding, write: encodingFilter.encoding = "ascii" Encoding is restricted to a limited set of MIME types; 'text/html' is the default list. To change that, use the config entry: encodingFilter.mimeTypeList = ['text/html', 'text/plain'] All of these configuration entries are specifiable per-path, so different portions of your site can use different encoding schemes. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From exarkun at divmod.com Sun Jul 24 21:33:48 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 24 Jul 2005 21:33:48 -0400 Subject: Simple Problem In-Reply-To: <1122254053.395740.220140@f14g2000cwb.googlegroups.com> Message-ID: <20050725013348.26278.1311675911.divmod.quotient.16699@ohm> On 24 Jul 2005 18:14:13 -0700, ncf wrote: >I know I've seen this somewhere before, but does anyone know what the >function to escape a string is? (i.e., encoding newline to "\n" and a >chr(254) to "\xfe") (and visa-versa) > >Thanks for helping my ignorance :P Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> '\n\xfe'.encode('string-escape') '\\n\\xfe' >>> '\\n\\xfe'.decode('string-escape') '\n\xfe' >>> Introduced in Python 2.3 Jp From onurb at xiludom.gro Wed Jul 27 13:25:35 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 27 Jul 2005 19:25:35 +0200 Subject: Create a variable "on the fly" In-Reply-To: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> References: <42e7b77f$0$13696$ed9e5944@reading.news.pipex.net> Message-ID: <42e7c390$0$446$626a14ce@news.free.fr> Paul D.Smith wrote: > Can Python create a variable "on-the-fly". For example I would like > something like... > > make_variable('OSCAR', 'the grouch'); > print OSCAR; > > ...to output... > > the grouch > > Anything like this in Python? The bad news is that yes, there is something "like this" in Python. The good news is that I won't tell you more about it, since it's a very bad practice(tm). The good practice is to put your vars in a dict. > And in case anyone is interested, I want to instantiate a set of variables > based on environment variables without using os.environ everywhere env = os.environ Now you just have to look at env['MY_ENV_VAR'] !-) > by having > a look instantiate Python variables of the appropriate type. What do you mean "of the appropriate type" ? You want to typecast (eg. from string to numeric) ? Then you need to know what env var must be casted to what type ? Then you don't need to create variables 'on the fly' ? I must have missed something... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rwgk at yahoo.com Sat Jul 2 06:04:09 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 2 Jul 2005 03:04:09 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code Message-ID: <20050702100409.91602.qmail@web31507.mail.mud.yahoo.com> ****************************************************************************** This posting is also available in HTML format: http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html ****************************************************************************** Hi fellow Python coders, I often find myself writing:: class grouping: def __init__(self, x, y, z): self.x = x self.y = y self.z = z # real code, finally This becomes a serious nuisance in complex applications with long argument lists, especially if long variable names are essential for managing the complexity. Therefore I propose that Python includes built-in support for reducing the ``self.x=x`` clutter. Below are arguments for the following approach (*please* don't get too agitated about the syntax right here, it really is a secondary consideration):: class grouping: def __init__(self, .x, .y, .z): # real code right here Emulation using existing syntax:: def __init__(self, x, y, z): self.x = x del x self.y = y del y self.z = z del z Is it really that important? ---------------------------- For applications of non-trivial size, yes. Here is a real-world example (one of many in that source tree): http://cvs.sourceforge.net/viewcvs.py/cctbx/cctbx/cctbx/geometry_restraints/manager.py?view=markup Fragment from this file:: class manager: def __init__(self, crystal_symmetry=None, model_indices=None, conformer_indices=None, site_symmetry_table=None, bond_params_table=None, shell_sym_tables=None, nonbonded_params=None, nonbonded_types=None, nonbonded_function=None, nonbonded_distance_cutoff=None, nonbonded_buffer=1, angle_proxies=None, dihedral_proxies=None, chirality_proxies=None, planarity_proxies=None, plain_pairs_radius=None): self.crystal_symmetry = crystal_symmetry self.model_indices = model_indices self.conformer_indices = conformer_indices self.site_symmetry_table = site_symmetry_table self.bond_params_table = bond_params_table self.shell_sym_tables = shell_sym_tables self.nonbonded_params = nonbonded_params self.nonbonded_types = nonbonded_types self.nonbonded_function = nonbonded_function self.nonbonded_distance_cutoff = nonbonded_distance_cutoff self.nonbonded_buffer = nonbonded_buffer self.angle_proxies = angle_proxies self.dihedral_proxies = dihedral_proxies self.chirality_proxies = chirality_proxies self.planarity_proxies = planarity_proxies self.plain_pairs_radius = plain_pairs_radius # real code, finally Not exactly what you want to see in a high-level language. Is there a way out with Python as-is? ------------------------------------- Yes. If you take the time to look at the file in the CVS you'll find that I was cheating a bit. To reduce the terrible clutter above, I am actually using a simple trick:: adopt_init_args(self, locals()) For completeness, the implementation of ``adopt_init_args()`` is here: http://cvs.sourceforge.net/viewcvs.py/cctbx/scitbx/scitbx/python_utils/misc.py?view=markup While this obviously goes a long way, it has several disadvantages: - The solution doesn't come with Python -> everybody has to reinvent. - People are reluctant to use the trick since scripts become dependent on a non-standard feature. - It is difficult to remember which ``import`` to use for ``adopt_init_args`` (since everybody has a local version/variety). - The ``adopt_init_args(self, locals())`` incantation is hard to remember and difficult to explain to new-comers. - Inside the ``__init__()`` method, the same object has two names, e.g. ``x`` and ``self.x``. This lead to subtle bugs a few times when I accidentally assigned to ``x`` instead of ``self.x`` or vice versa in the wrong place (the bugs are typically introduced while refactoring). - In some cases the ``adopt_init_args()`` overhead was found to introduce a significant performance penalty (in particular the enhanced version discussed below). - Remember where Python comes from: it goes back to a teaching language, enabling mere mortals to embrace programming. ``adopt_init_args(self, locals())`` definitely doesn't live up to this heritage. Minimal proposal ---------------- My minimal proposal is to add an enhanced version of ``adopt_init_args()`` as a standard Python built-in function (actual name secondary!):: class grouping: def __init__(self, x, y, z): adopt_init_args() # real code Here is a reference implementation: http://cvs.sourceforge.net/viewcvs.py/cctbx/libtbx/libtbx/introspection.py?rev=1.2&view=markup Implementation of this proposal would remove all the disadvantages listed above. However, there is another problem not mentioned before: It is cumbersome to disable adoption of selected variables. E.g.:: class grouping: def __init__(self, keep_this, and_this, but_not_this, but_this_again): self.keep_this = keep_this self.and_this = and_this self.but_this_again = but_this_again # real code, finally would translate into:: class grouping: def __init__(self, keep_this, and_this, but_not_this, but_this_again): adopt_init_args(exclusions=["but_not_this"]) # real code Enhanced syntax proposal ------------------------ The exclusion problem suggests these alternatives:: class grouping: def __init__(self, self.keep_this, self.and_this, but_not_this, self.but_this_again): # real code right here This is conceptually similar to the existing automatic unpacking of tuples. A shorter alternative (my personal favorite since minimally redundant):: class grouping: def __init__(self, .keep_this, .and_this, but_not_this, .but_this_again): # real code right here I guess both versions could be implemented such that users don't incur a performance penalty compared to the ``self.x=x`` alternative. At the danger of being overly optimistic: I can imagine that my favorite alternative will actually be faster (and the fastest). Enhanced __slot__ semantics proposal ------------------------------------ When ``__slots__`` are used (cool feature!) the boilerplate problem becomes even worse:: class grouping: __slots__ = ["keep_this", "and_this", "but_this_again"] def __init__(self, keep_this, and_this, but_not_this, but_this_again): self.keep_this = keep_this self.and_this = and_this self.but_this_again = but_this_again # real code, finally Each variable name appears four times! Imagine yourself having to do this exercise given the real-world example above. Ouch. Based on the "Enhanced syntax proposal" above I see this potential improvement:: class grouping: __slots__ = True def __init__(self, .keep_this, .and_this, but_not_this, .but_this_again): # real code right here Each variable name appears only once. Phew! Author: rwgk at yahoo.com, July 02, 2005 P.S.: If you reply to this message, please clearly separate naming/syntax issues from the core issue of providing built-in support designed to reduce clutter. ____________________________________________________ Yahoo! Sports Rekindle the Rivalries. Sign up for Fantasy Football http://football.fantasysports.yahoo.com From timr at probo.com Sat Jul 2 19:05:10 2005 From: timr at probo.com (Tim Roberts) Date: Sat, 02 Jul 2005 16:05:10 -0700 Subject: What's wrong with this code? References: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> Message-ID: "Nathan Pinno" wrote: > > Hi all, > > What's wrong with the following code? It says there is name error, that >random is not defined. How do I fix it? > > # Plays the guessing game higher or lower. > # Originally written by Josh Cogliati, improved first by Quique, then by >Nathan Pinno. > print "Higher or Lower" > print > number = random.choice(range(100)) > guess = 0 > while guess != number: > guess = input("Guess a number: ") > if guess > number: > print "Too high" > guess = input("Guess a number: ") > elif guess < number: > print "Too low" > guess = input("Guess a number: ") > print "Just right" There is a problem with this, caused by having to repeat the same code in multiple places. Sa that the number is 50. You get to the first "input" statment, and you enter 30. It prints "Too low", and asks you to enter another number. You enter 40. The "while" expression is true, so it will loop again, and prompt you to enter ANOTHER number, without telling you whether it was high or low. Better to eliminate duplicated code: import random print "Higher or Lower" print number = random.choice(range(100)) while 1: guess = input("Guess a number: ") if guess == number: break elif guess > number: print "Too high" else: print "Too low" print "Just right" -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From newtonapples at gmail.com Sun Jul 31 19:45:24 2005 From: newtonapples at gmail.com (Apple) Date: 31 Jul 2005 16:45:24 -0700 Subject: Determining method type given its string name presentation and its corresponding object reference. Message-ID: <1122853524.374812.326580@g14g2000cwa.googlegroups.com> Hi I am a bit new to python. I was wondering if there is a way to determine whether or not a given string is a member method of a given object: def is_a_method(self, attr_name): 'returns True if attr_name is an instance method of self; false otherwise' The problem is that I have overridden __repr__ in such a way that it's not self-contained. It makes a call to a member method, call it m(), that would call up getattr() which eventually makes another call back to __repr__: Example output: (). So, I want to trap all attr_name that are methods comeing into m() and make sure they're not passed on to getatrr() i.e. making __repr__ self-contained (hopefully). Is there a simple way to determine a given attr_name is_a_method()? Thanks in advance for all your help. From roccomoretti at hotpop.com Fri Jul 1 10:26:58 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 01 Jul 2005 09:26:58 -0500 Subject: Question about Python In-Reply-To: <42c54149$1@griseus.its.uu.se> References: <42c54149$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > However, when I look at the various Python modules/libraries, I see > that there are several versions of them, for different versions of > python. I've seen everything from "for python 1.5" up to "for python > 2.4" with all versions in between. This scares me a little bit. I assume > that the reason for the different versions is because of new language > features? Please be aware that although Python tries to be compatible at the source level, compatibility at the binary level is only guaranteed at the minor revision level (the third number in the dotted triple version number.) So when most libraries have "for Python 1.5" and "for Python 2.4" downloads, those are usually for precompiled binaries *only*. If you download and compile the source itself, the same files can run on all versions of Python listed. For good or bad, Python expects you to have access to the source code Note however, that programs taking advantage of features introduced in a more recent version of Python won't run on older versions (obviously), even at the source level. They will, however, usually run on any newer version, unless the author took advantage of a bug, or did something perverse, like reassigning None. So when a Python program says "Python 2.1 required", that usually means "Python 2.1 or later required". At any rate, all older versions of Python are still availible, and probably will be for the forseable future, and multiple (major) versions of Python can coexist happily with each other on the same machine, so if you need to use an older version, you can. From peterbe at gmail.com Fri Jul 8 09:54:52 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 8 Jul 2005 06:54:52 -0700 Subject: Snakespell Message-ID: <1120830892.733174.18770@g44g2000cwa.googlegroups.com> I used to use Snakespell from scriptfoundry to do spellchecking on my website (www.peterbe.com/search?q=pyton) but now that I've moved server and wiped the old machine I forgot to take with me the Snakespell code. www.scriptfoundry.com where it used to live seems to have expired. Does anybody know where I can get hold of this? (or even send a tgz to me) From rrr at ronadam.com Mon Jul 11 21:14:45 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 12 Jul 2005 01:14:45 GMT Subject: extend for loop syntax with if expr like listcomp&genexp ? In-Reply-To: <42d30319.417620065@news.oz.net> References: <42d30319.417620065@news.oz.net> Message-ID: <9QEAe.190406$IO.101841@tornado.tampabay.rr.com> Bengt Richter wrote: > E.g., so we could write > > for x in seq if x is not None: > print repr(x), "isn't None ;-)" > > instead of > > for x in (x for x in seq if x is not None): > print repr(x), "isn't None ;-)" > > just a thought. > > Regards, > Bengt Richter Is it new idea month? :) That would seem to follow the pattern of combining sequential lines that end in ':'. if pay<10 if hours>10 if stressed: sys.exit() That would be the same as using ands. And this gives us an if-try pattern with a shared else clause. if trapped try: exit = find('door') except: yell_for_help() else: #works for both if and try! ;-D leave() Which would be the same as: if trapped: try: exit = find('door') except: yell_for_help() else: leave() else: leave() Interesting idea, but I think it might make reading other peoples code more difficult. Cheers, Ron From tjreedy at udel.edu Mon Jul 18 15:40:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 18 Jul 2005 15:40:10 -0400 Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net><1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net><2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net><6DhBe.3077$dU3.691@newsread2.news.pas.earthlink.net> Message-ID: "Bob Officer" wrote in message news:j9und1dk1cl08bg2tum967h974lrf656oc__35091.5694762536$1121713266$gmane$org at 4ax.com... [snip over 100 lines that should have been snipped before] >>In particular I am interested in the EM dataset. > > There isn't any "data set" > > There are no "formula"... > > There is only EGD > > Crackpot. > > http://www.crank.net/geology.html > > Look down to the middle of the page E.D.G. > > Listed as "Cranky" I figured as much, and appreciate the info, but PLEASE learn to snip so people can find your meat easier. From zelzel.zsu at gmail.com Tue Jul 5 04:31:09 2005 From: zelzel.zsu at gmail.com (zelzel.zsu at gmail.com) Date: 5 Jul 2005 01:31:09 -0700 Subject: what is __init__.py used for? Message-ID: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> I am a new learner of Python Programming Language. Now. I am reading a book. In the section relating to module, I see an example. the directory tree looks like below: root\ system1\ __init__.py utilities.py main.py other.py system2\ __init__.py utilities.py main.py other.py system3\ # Here or elsewhere __init__.py # Your new code here myfile.py question ========== I was wonderring ... what is the __init__.py used for ? This question may seems to be stupid for an expert. But, if you can give the answer, it will be helpful for me. thanks. From klappnase at web.de Thu Jul 14 06:26:18 2005 From: klappnase at web.de (klappnase at web.de) Date: 14 Jul 2005 03:26:18 -0700 Subject: Ann: Tkinter drag and drop module Message-ID: <1121336778.344208.224820@f14g2000cwb.googlegroups.com> I wrote a wrapper for the tkdnd Tk extension (), which adds native drag and drop support to Tkinter (windows and unix only). It was the first time for me to try wrapping a Tk extension, and I couldn't find any documentation on this, so I would still consider it experimental; however at least for the most part it seems to work well. The module can be used with both standard Tkinter and Tix, and makes it quite easy to e.g. drop a bunch of files from a file manager onto any Tkinter widget. It comes with a basic reference manual and a small demo app. It can be found at . Any feedback is much appreciated. Best regards Michael From aarnett at foundationsys.com Fri Jul 29 14:37:57 2005 From: aarnett at foundationsys.com (Amanda Arnett) Date: 29 Jul 2005 14:37:57 -0400 Subject: Seeking Python expertise... Message-ID: <7392673.1122662276876.JavaMail.cfservice@WEBSERVER3> Hi, I found out about your Python community and thought you may be able to help me out. I am supporting an elite group of traders (more like the Who's Who on Wall Street). We are building algorithmic trading models to analyze market movements, economic indicators, and various factors to predict and automate trade executions. We have quite a bit of success thus far and are expanding into other electronic markets. Our core technology team wants to add 5-6 talented software engineers in the next few months that know Python well ? as we believe it?s a fast and elegant language. They also said that people with a strong background in math, statistics, modeling, chess, or video game development will find what we are doing to be very fascinating. Everything is real-time, and you get to apply what you know and see the results of your software models making money in the market immediately. Are you the person we seek? Do you know anyone we can talk to about this? I am more than happy to forward a job description. We pay very well for top talents - attractive salary and triple digit percentage in bonuses for top contributors. And, we will relocate people to Beverly Hill, CA (USA) from anywhere in the world. Also, the technology team also has a number of positions open for people with strong experience in concurrency, multi-threading, I/O, NIO, networking, operating systems internals, and performance optimization to work on our core trading platform (where we execute trades directly with the Exchange). People with experience building servers that can handle thousands of simultaneous connections / concurrent users will be very helpful. Performance of our platform is very important for us as we profit from even very small fluctuations in price. I don't know if people in this Python community also know these technologies but I guess it doesn't hurt to ask. If you have a resume, I'd love to see it. If you can pass this to the right people, I'd really appreciate it. If you have any questions, you can call me at 415-503-3998 or email me at aarnett at foundationsys.com . Thanks so much for your help. Amanda Arnett -------------- next part -------------- An HTML attachment was scrubbed... URL: From gsakkis at rutgers.edu Thu Jul 21 20:29:23 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 21 Jul 2005 20:29:23 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> Message-ID: <1121992173.719316df1430a706987a33a518e6ea2d@teranews> "John Roth" wrote: > "Reinhold Birkenfeld" wrote > > He said, > > > > """ > > Whoa! Do we really need a completely different mechanism for doing the > > same stuff we can already do? The path module seems mostly useful for > > folks coming from Java who are used to the Java Path class. With the > > massive duplication of functionality we should also consider what to > > recommend for the future: will the old os.path module be deprecated, > > or are we going to maintain both alternatives forever? (And what about > > all the duplication with the os module itself, like the cwd() > > constructor?) Remember TOOWTDI. > > """ > > Read literally, this says (at least to me) "I don't want to fix it because > I don't think it's broke." Or rather "I prefer a single existing mediocre solution than two solutions (even if the second was better)". George From nephish at xit.net Wed Jul 27 08:12:46 2005 From: nephish at xit.net (nephish at xit.net) Date: 27 Jul 2005 05:12:46 -0700 Subject: question about deleting records from mysql In-Reply-To: References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> <42E7720E.90307@xit.net> Message-ID: <1122466366.005107.303840@z14g2000cwz.googlegroups.com> ok. did this >>> cursor.execute("DELETE FROM table WHERE autoinc > 1000") 245L >>> cursor.commit() i got an AttributeError 'Cursor' object has no attribute 'commit' hmm. what should i do now? the stuff about writing a lightweight layer between the dbapi and the program shot right over my head. sorry, but thanks From __peter__ at web.de Fri Jul 1 13:02:23 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Jul 2005 19:02:23 +0200 Subject: is there a better way to walk a file system? References: <1120230335.548382.96880@z14g2000cwz.googlegroups.com> <1120236548.823249.119300@z14g2000cwz.googlegroups.com> Message-ID: George Sakkis wrote: > By the way, from this example I discovered that properties cannot be > unbound, i.e. using path.ext instead of getExtension raises TypeError. > Couldn't/shouldn't Class.prop(instance) be allowed as equivalent of > instance.prop, just as methods ? Use the property's __get__() method instead: >>> class A(object): ... def __init__(self, value): ... self._value = value ... value = property(lambda self: self._value) ... def __repr__(self): return "A(%r)" % self._value ... >>> a = A(42) >>> A.value.__get__(a) 42 >>> sorted([A(42), A(2), A(4)], key=A.value.__get__) [A(2), A(4), A(42)] Peter From __peter__ at web.de Fri Jul 29 14:18:53 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Jul 2005 20:18:53 +0200 Subject: can list comprehensions replace map? References: Message-ID: Andrew Dalke wrote: > Me: >>> Could make it one line shorter with >> >>> from itertools import chain, izip, repeat >>> def fillzip(*seqs): >>> def done_iter(done=[len(seqs)]): >>> done[0] -= 1 >>> if not done[0]: >>> return [] >>> return repeat(None) >>> seqs = [chain(seq, done_iter()) for seq in seqs] >>> return izip(*seqs) > > Peter Otten: >> that won't work because done_iter() is now no longer a generator. >> In effect you just say >> >> seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], >> [])] > > It does work - I tested it. The trick is that izip takes iter() > of the terms passed into it. iter([]) -> an empty iterator and > iter(repeat(None)) -> the repeat(None) itself. Seems my description didn't convince you. So here's an example: >>> from itertools import chain, izip, repeat >>> def fillzip(*seqs): ... def done_iter(done=[len(seqs)]): ... done[0] -= 1 ... if not done[0]: ... return [] ... return repeat(None) ... seqs = [chain(seq, done_iter()) for seq in seqs] ... return izip(*seqs) ... >>> list(fillzip(range(6), range(3))) [(0, 0), (1, 1), (2, 2)] >>> versus >>> map(None, range(6), range(3)) [(0, 0), (1, 1), (2, 2), (3, None), (4, None), (5, None)] Now where's the typo? > 'Course then the name should be changed. My variable names where ill-chosen to begin with. Peter From hancock at anansispaceworks.com Fri Jul 1 15:08:57 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 14:08:57 -0500 Subject: How to compare files In-Reply-To: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> References: <1120210761.685753.121810@z14g2000cwz.googlegroups.com> Message-ID: <200507011408.57452.hancock@anansispaceworks.com> On Friday 01 July 2005 04:39 am, Lad wrote: > Hi, > What is the best method for comparing two files by words? > I was thinking about reading files by words and compare them but a word > in one file can be linked with a new line character ( \n) > and this '\n' will cause that the words will considered to be > different( eventhough without '\n' are the same) Use the split from re instead of the string method, and include all the non-word characters (including '\n') as whitespace characters. Then you'll have only words (I think you can also wind up with empty strings, which you can strip out pretty easily). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From duncan.booth at invalid.invalid Tue Jul 12 11:02:29 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2005 15:02:29 GMT Subject: breaking out of nested loop References: Message-ID: rbt wrote: > What is the appropriate way to break out of this while loop if the for > loop finds a match? > > while 1: > for x in xrange(len(group)): another option not yet suggested is simply to collapse the two loops into a single loop: import itertools for x in itertools.cycle(range(len(group)): ... as before ... From t-meyer at ihug.co.nz Sun Jul 31 21:22:14 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 1 Aug 2005 13:22:14 +1200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: Message-ID: > While people are loathe to admit it, many stereotypes have > some basis in fact. The problem is when people extend that to generalize > about others (especially in a negative way). The intent was to use the basis-in-fact stereotype without having to explain in detail the factual basis, which didn't seem particularly useful, nor necessary. I suppose that was wrong. Since *I* am a Windows user and developer, if it was insulting, I was also insulting myself. For one person, at least, it seems that I needed to explain everything in as much detail as you did. Thanks for doing it for me :) [...] > That being said, there is a big difference between a Windows > *user* and a Windows *developer*. I doubt many Windows *users* will > be writing Python code. Python is a great language for beginners (look at the tutor list). The language should be kept as easy as possible for beginners to use, while not limiting what experts can do (something to this effect was even said on python-dev recently). Lacking this __div__ hack doesn't limit experts, and does make it more difficult for beginners. =Tony.Meyer From tjreedy at udel.edu Wed Jul 20 17:41:36 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 20 Jul 2005 17:41:36 -0400 Subject: is this pythonic? References: <42DE4F67.7030300@mage.hu> Message-ID: > Wow, I didn't know about enumerate. It is listed and explained in Lib Ref Manual, Chapter 2, on builtin functions and types and their methods. Everyone should read at least that much of the Lib manual. Terry J. Reedy From devlai at gmail.com Tue Jul 12 12:16:29 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 09:16:29 -0700 Subject: Creating anonymous functions using eval In-Reply-To: References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> Message-ID: <1121184988.996652.126350@g47g2000cwa.googlegroups.com> Well, the string that gets passed is more or less a function definition, which is then called with exec. I don't see why you'd need to write a string out with the function definition and then call it. You could just write the function. As for the nested functions, I had been presuming that it was intended to use as a better function than lambda within a function. Sorry for the confusion. From rkern at ucsd.edu Wed Jul 20 12:53:00 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 09:53:00 -0700 Subject: convert ascii escapes into binary form In-Reply-To: References: Message-ID: Hans-Peter Jansen wrote: > Hi Pythonistas, > > I need to convert ascii escapes into binary form, e.g.: > \f -> ^L > \033@\x1bk\000 -> ^[@^[k^@ > > (rvalues in terminal representation) > > Any idea, how to do this most elegantly in python? > Do I really need to do a search n'replace orgy, combined with > regex for this task? In [11]: s = '\\f' In [12]: s.decode('string_escape') Out[12]: '\x0c' -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From phillip.watts at anvilcom.com Mon Jul 4 11:21:34 2005 From: phillip.watts at anvilcom.com (phil) Date: Mon, 04 Jul 2005 10:21:34 -0500 Subject: What are the other options against Zope? References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> <42c8dd47$0$298$edfadb0f@dread12.news.tele.dk> Message-ID: <42C953FE.6030207@anvilcom.com> > It's an object oriented database, with a structure that is similar to > files and directories in an ordinary OS. > > But it is a lot smarter, because the files and directories are actually > objects with different attributes and parameters. > > The methods on these objects can then be called eg. from a web browser > with different parameters. But you can also use other protocols than > http like dav, ftp etc. Well, that's interesting. I've never seen an explantion like this. Actually I think I have, and was too dumb to realize what I was reading. A data base with properties and methods. Cool. From pinard at iro.umontreal.ca Sun Jul 10 18:00:55 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 10 Jul 2005 18:00:55 -0400 Subject: computer algebra packages In-Reply-To: References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> <20050710171221.GA29664@phenix.progiciels-bpi.ca> Message-ID: <20050710220055.GA2001@phenix.progiciels-bpi.ca> [Robert Kern] > Fran?ois Pinard wrote: > > [Florian Diesch] > >> Mascyma is (trying to be) a user-friendly graphical frontend for > >> the Computer Algebra System GNU MAXIMA. It is written in Python > >> and provides two GUIs, one of which based on PyGTK, the other based > >> on wxPython. > > I was not successful googling for this one. Would you have an URL handy? > Note the deliberate spelling, and cut-and-paste. Thanks. The `Mascyma' versus `Macsyma' subtlety escaped my scrutiny :-). > http://home.arcor.de/mulk/projects/mascyma/index.xhtml.de Their CVS server (the only download choice) is not responding. So I'll forget "Mascyma" for now. Maxima does work, that's a lot already! :-) I perused what I could find about Python on algebra or symbolic calculus, and nothing I saw, so far, stands even a pale comparison with Maxima. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From mwm at mired.org Tue Jul 12 22:01:40 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 12 Jul 2005 22:01:40 -0400 Subject: Fwd: Should I use "if" or "try" (as a matter of speed)? References: <5f4d3cb5050712081414d59aca@mail.gmail.com> Message-ID: <86k6jvlb0b.fsf@bhuda.mired.org> Dark Cowherd writes: > But one advise that he gives which I think is of great value and is > good practice is > "Always catch any possible exception that might be thrown by a library > I'm using on the same line as it is thrown and deal with it > immediately." Yuch. That sort of defeats the *purpose* of exceptions in Python: letting you get on with the coding, and dealing with the errors when it's convenient. Consider: try: out = file(datafile, "wb") out.write(genData1()) out.write(genData2()) out.write(genData3()) except IOError, msg: print >>sys.stderr, "Save failed:", msg if os.path.exists(datafile): os.unlink(datafile) I don't even want to *think* writing the try/except clause for each line. It reminds me to much of: if (!(out = open(datafile, "w"))) { /* handle errors */ return ; } if (write(out, genData1()) <0) { /* handle errors */ return ; } etc. Generally, I treat exceptions as exceptional. I catch the ones that require something to be changed to restore the program or environment to a sane state - and I catch them when it's convenient. The rest I catch globally and log, so I can figure out what happened and do something to prevent it from happening again. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rwgk at yahoo.com Sat Jul 9 20:24:44 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 9 Jul 2005 17:24:44 -0700 (PDT) Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <20050710001549.7217.qmail@web31514.mail.mud.yahoo.com> Message-ID: <20050710002444.8689.qmail@web31511.mail.mud.yahoo.com> Sorry, I forgot the attachment. ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: autoinit_timings.py URL: From rkern at ucsd.edu Tue Jul 19 06:26:38 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 19 Jul 2005 03:26:38 -0700 Subject: goto In-Reply-To: <1121719077.19216.10.camel@athop1.ath.vt.edu> References: <1121719077.19216.10.camel@athop1.ath.vt.edu> Message-ID: rbt wrote: > IMO, most of the people who deride goto do so because they heard or read > where someone else did. Or perhaps, like me, they have had to maintain FORTRAN code written by a scientist who apparently hadn't heard of subroutines. "Spaghetti" doesn't quite describe it. I've settled on "Lovecraftian": reading the code, you can't help but get the impression of writhing tentacles and impossible angles. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From levander at mindspring.com Sun Jul 31 00:34:47 2005 From: levander at mindspring.com (levander) Date: 30 Jul 2005 21:34:47 -0700 Subject: Asking the user a question and giving him a default answer he can edit Message-ID: <1122784487.040842.45910@g14g2000cwa.googlegroups.com> I'm trying to figure out the python readline module to see if it will do this. Basically, I've got a bunch of questions to ask a user, the vast majority of which, the answer will only vary by the last few characters. What I'd like to do is every time the user is asked a question, give him the default answer as just whatever he answered last time. But, I want him to be able to edit this default answer. And, the editted answer is what I want to operate on inside my program. raw_input() lets the user edit the prompt I send. But, internally, it must ignore the backspace key or something. Because, it only returns new letters that the user has typed in. Not anything that he has backspaced over or deleted. You can edit whatever you put out there with raw_input, but it's like internally that function ignores the backspace key, and just returns whatever new characters the user types. Basically, I want to the user a line editor, with a default value already populated. Anybody know how to do something like this? I've been playing around with doing it in bash, figuring I can use popen to spawn the process if I can figure it out, but haven't figured it out yet. From stringy at gmail.com Thu Jul 21 05:21:36 2005 From: stringy at gmail.com (stringy) Date: 21 Jul 2005 02:21:36 -0700 Subject: Need to interrupt to check for mouse movement In-Reply-To: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> References: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> Message-ID: <1121937696.057109.6810@o13g2000cwo.googlegroups.com> Cheers for the replies people, but I got it sorted by just whacking in wx.YieldIfNeeded() in the code before it communicates over the socket. It's kind of jerky, but it works, where as before I'd click and drag, and the 3d view wouldn't move for about 20 seconds. From rwgk at yahoo.com Sat Jul 9 05:41:13 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 9 Jul 2005 02:41:13 -0700 (PDT) Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) In-Reply-To: <20050705232102.18901.qmail@web31508.mail.mud.yahoo.com> Message-ID: <20050709094113.86188.qmail@web31508.mail.mud.yahoo.com> My initial proposal (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't exactly get a warm welcome... And Now for Something Completely Different: class autoinit(object): def __init__(self, *args, **keyword_args): self.__dict__.update( zip(self.__autoinit__.im_func.func_code.co_varnames[1:], args)) self.__dict__.update(keyword_args) self.__autoinit__(*args, **keyword_args) class grouping(autoinit): def __autoinit__(self, x, y, z): print self.x, self.y, self.z group = grouping(1,2,z=3) group = grouping(z=1,x=2,y=3) try: grouping(1) except TypeError, e: print e try: grouping(1,2,3,a=0) except TypeError, e: print e Almost like my original favorite solution, only better, and it doesn't require a syntax change. Under a hypothetical new proposal __autoinit__ would become a standard feature of object. Any takers? Cheers, Ralf __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bill.mill at gmail.com Sat Jul 16 19:54:31 2005 From: bill.mill at gmail.com (Bill Mill) Date: Sat, 16 Jul 2005 19:54:31 -0400 Subject: odd python/linux/cherrypy behavior In-Reply-To: References: Message-ID: <797fe3d405071616541294503@mail.gmail.com> On 7/16/05, Neil Hodgson wrote: > Bill Mill: > > > ... a FAT partition for data as a dmz which both linux and NT can > > access ... > > Yesterday, I downloaded the new release of cherrypy, and stuck it on > > the dmz drive. ... > > Eventually, after thinking it's a hosts file problem, or a firewall > > problem, I figure out that if I move it to my ext3 drive, it again > > works perfectly. > > Have you looked at your mount options to make sure they are sane? > Possibly you have mounted with only short (truncated) file names or all > the files have their execute bit on and that is unexpected or there are > non-ASCII characters in file names or ... > Definitely not mounted with short file names, and there aren't any non-ASCIIs in the file names; in both cases I imagine that the file wouldn't run at all. In this case, however, the file does run, and open a socket, it just can't seem to receive connections on it. I have tried running the file as su, with no success. The FAT dirs are mounted with the following options: defaults,user,umask=000 . I'm not sure what you mean by the execute bit, but all files do have execute permission. Here's the output of an ls -l on the file I'm talking about: -rwxrwxrwx 1 root root 1073 2005-07-15 21:40 /d/download/cherrypy/tutorial/tut01_helloworld.py Any other ideas? Peace Bill Mill bill.mill at gmail.com From fperez.net at gmail.com Wed Jul 27 14:12:31 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 27 Jul 2005 12:12:31 -0600 Subject: A Module on Time & Date References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: Robert Maas, see http://tinyurl.com/uh3t wrote: >> From: Robert Kern >> As you can see in the datetime documentation, the module was introduced >> in Python 2.3. I recommend updating your Python installation. > > What do you mean "your"?? I don't have any Python installation of my > own. All I have is what this small local ISP provides on its Unix shell > machine which I share with hundreds of other users. There's no way I > can install a new version of anything on the system account. > Your recommendation will be disregarded as total crap. You might also consider learning how to find answers to all your problems by yourself in the future, as this kind of response to a perfectly reasonable, valid suggestion pretty much ensures that people won't be terribly inclined to help you in the future. Robert's recommendation was valid, to the point, and perfectly feasible. As Skip further indicated, it's trivial to add your local python; you can also keep local modules (without a full python) in your own account and configure $PYTHONPATH. Your response was rude and stupid. Cheers, f From rkern at ucsd.edu Sun Jul 31 22:03:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 31 Jul 2005 19:03:16 -0700 Subject: subclassing list In-Reply-To: <1122861221.206598.6300@g47g2000cwa.googlegroups.com> References: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> <1122861221.206598.6300@g47g2000cwa.googlegroups.com> Message-ID: spike grobstein wrote: >>You also need to post the code that raises the error, or no one else can > > debug it. > > sorry, I thought I had pasted that line in there, but I guess I missed > it. Here's the full code (after modifying it slightly based on your > post): > > #! /usr/bin/env python > > def circular_list(list): ^^^ As John pointed out, this is part of the problem, but as I pointed out, that's not the last of the problems with the code. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nicolas.riesch at genevoise.ch Thu Jul 28 11:42:57 2005 From: nicolas.riesch at genevoise.ch (nicolas_riesch) Date: 28 Jul 2005 08:42:57 -0700 Subject: codecs.getencoder encodes entire string ? Message-ID: <1122565377.433764.274280@f14g2000cwb.googlegroups.com> When I use an encoder function from codecs module, documentation says that it encodes the object input and returns a tuple (output object, length consumed). >>> import codecs >>> enc=codecs.getencoder('iso-8859-1') >>> enc(u'asdf') ('asdf', 4) >>> I just don't understand why it returns the "length consumed". Does it means that in some case, the input string can be only partially converted ? What can be the use of the "length consumed" value ? And a last question: can I call this "enc" function from multiple threads ? From jcribbs at twmi.rr.com Sat Jul 2 11:44:44 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Sat, 02 Jul 2005 15:44:44 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: Tom Anderson wrote: > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? I have no functional language background. Until recently, I had no use for programming "expression to be evaluated later" or "deferred expressions" or whatever else they are being called. Where I came to see the awesomeness of "deferred expressions" was a few months ago when I started a major rewrite of KirbyBase for Ruby. I wanted to make the Ruby version of KirbyBase take advantage of the strengths of the language. Another Ruby programmer, Hal Fulton, was helping me by constantly pushing me to make KirbyBase more Ruby-ish. One thing he kept pushing was to be able to specify select querys using Ruby's "deferred expression" mechanism, code blocks (before anyone starts yelling, I know that Ruby code blocks are *much* more than just "deferred expressions"; I'm just using that descriptor here for the sake of this discussion). Code blocks allow you to wrap up any Ruby code and pass it to a method and have it executed within that method. It is more powerful than lambda, because you can have multiple statements in the code block and you can do assignment within the code block. This allowed me to rewrite KirbyBase so that you can do a select like this: plane_tbl.select { |r| r.country == 'USA' and r.speed > 350 } Now, this is cool, but you can do this using lambda in Python. Where Ruby code blocks really shine is that you can also do this: plane_tbl.update {|r| r.name == 'P-51'}.set {|r| r.speed = 405 r.range = 1210 } I have one code block that I pass to the update method which says "Select all planes with name equal to P-51". Then, I pass a code block to the set method which assigns new values to the speed and range fields for those records (i.e. P-51) that were selected in the update method. This is something you can't do with lambda. Now, I think I can duplicate the same functionality of Ruby code blocks by using Python functions, but it is not going to be as pretty. So, even though lambda is not as powerful as Ruby code blocks, I was still bummed to read that it is going away, because it is better than nothing. Hopefully, Guido will reconsider or, even better, give us something even more powerful. Jamey Cribbs From jtr at ofb.net Sat Jul 16 16:46:13 2005 From: jtr at ofb.net (John Reese) Date: Sat, 16 Jul 2005 20:46:13 +0000 (UTC) Subject: SSL problem... SSL23_GET_SERVER_HELLO:unknown protocol Message-ID: Morning. I've been running into an error message pertaining to SSL that I don't understand, and I was hoping someone had some insight. Gmail provides POP access over SSL on port 587, so I tried to use poplib.POP_SSL, with the following results: %python Python 2.4.1 (#1, May 16 2005, 15:19:29) [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from poplib import POP3_SSL >>> pop= POP3_SSL('pop.gmail.com', 587) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/poplib.py", line 359, in __init__ self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) File "/usr/lib/python2.4/socket.py", line 74, in ssl return _realssl(sock, keyfile, certfile) socket.sslerror: (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol') >>> Any suggestions or insight? From siona at chiark.greenend.org.uk Thu Jul 14 08:14:49 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 14 Jul 2005 13:14:49 +0100 (BST) Subject: more newbie list questions References: <1121289160.547153.78090@g44g2000cwa.googlegroups.com> Message-ID: Bernhard Holzmayer wrote: >googleboy wrote: >> I have a cell.txt file that looks like this: >> >> ++ >> The title is %title%.

>> The author is %author1% %author2%

>> The Publisher is %publisher1% %publisher2%

>> The ISBN is %ISBN%

>> ++ > >This looks like a DOS-batch-file. Maybe you'd better just leave it to >DOS to populate it, just by exec-uting it in an environment which >has title, authort1, ... set. ?? > >On the other hand, if you need not relate to the cell.txt file, >you could just use something like > >sAuth = "The author is %s" % author1 Or sAuth = "The author is %(author1)s" % locals() so cell.txt could be replaced by something like ++ The title is %(title)s.

The author is %(author1)s %(author2)s

The Publisher is %(publisher1)s %(publisher2)s

The ISBN is %(ISBN)s

++ and you could do everything at once. Obviously you'd be better off sticking author1 etc. into a dict instead of making them local variables. This might also solve your problems with "getting fields into Python" (as someone else said, it's not entirely clear what your difficulties are): field_names = ["title", "author1", "author2", "publisher", "ISBN"] fields_dict = dict(zip(field_names, fields)) sTemplate % field_dict >> I know how to do something like sAuth = re.sub('%author1%', author1, >> sTemplate) re.sub() is massive overkill. If you can't get where you want with % as above, use str.replace instead: sTemplate.replace('%author1%', author1) (Er, "you" above refers to OP, not Bernhard.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From francisco.borges at gmail.com Fri Jul 8 05:00:29 2005 From: francisco.borges at gmail.com (Francisco Borges) Date: 8 Jul 2005 02:00:29 -0700 Subject: PyX, matplotlib, 3D & LaTeX In-Reply-To: References: Message-ID: <1120813229.543202.310640@o13g2000cwo.googlegroups.com> Robert Kern wrote: > Matthias R. wrote: > > Unfortunately matplotlib is only a 2D-plotting library. > > > > Do you know another one with 3D-capabilities as well? > > There's PyX. Sorry, PyX can't do 3D plots. ----------- I like PyX, use it a lot and would suggest it as a beter plotting library than the ones at Scipy (for as long as you don't need on-screen plotting). I just saw matplotlib this week while searching for something that would do 3D, it seemed pretty nice and it does have many more features than PyX, is certainly more mature than PyX and more high level. On the other hand PyX: LaTeX support seems to be way ahead and it can be used to draw (very funky) figures. My experience with PyX is that: 1. it takes more lines of code (than what I fell is needed) to do it; 2. it (still) lacks easy ways to do frequent things (like filling) 3. but once you got it done; the figures/plots are *PERFECT*. Over PyX you must also be aware that: a) PyX can't (yet) do pie-charts. b) No, Pyx can't plot 3D (yes, despite using a 3D plot at their webpage, it does *not* plot 3D). c) Documentation can be very confusing at times, so start at the examples; d) PyX is not stable yet, the last 3 (or 2?) PyX releases were all backwards incompatible. Cheers, Francisco From mwm at mired.org Fri Jul 1 22:23:05 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 22:23:05 -0400 Subject: Favorite non-python language trick? References: <1120253547.215928.303690@g43g2000cwa.googlegroups.com> <86psu2410u.fsf@bhuda.mired.org> Message-ID: <86ll4q3q0m.fsf@bhuda.mired.org> [Lots of quoted text left in...] I started thinking about this, and realized that there was a way to do what you wanted, with no execution time overhead, and without providing ways to radically change the program behavior behind the scenes. Mike Meyer writes: > "Shai" writes: > >> Joseph Garvin wrote: >>> >>> I'm curious -- what is everyone's favorite trick from a non-python >>> language? And -- why isn't it in Python? >> >> 1. Lisp's "dynamically scoped" variables (Perl has them, and calls them >> "local", but as far as I've seen their use their is discouraged). These >> are global variables which are given time-local bindings. That is, >> structuring the syntax after what's used for globals, > > Perl started life with nothing but dynamically scoped variables. They > added lexical scoping after they realized what a crock dynamic scoping > was. That's a bit harsher than I intended. I mean that having nothing but dynamically scoped variables - like early Perl and LISP - is a crock. I'll add that dynamic scoping as the default is a crock. But you aren't asking for those. >> x=10 >> def foo(): >> # No need to define x as it is only read -- same as globals >> print x >> >> def bar(): >> dynamic x >> x = 11 >> foo() >> >> def baz(): >> bar() # prints 11 >> foo() # prints 10; the binding in bar is undone when bar exits Here's the problem with that. Consider this script: import foo x = 10 def bar(): print x foo.foogle(bar) If foo.foogle includes "dynamic x" and then invokes bar, bar could print anything. This makes the behavior of bar unpredictable by examining the sourc, with no hint that that is going on. > Given that it's a feature I don't want programmers using, I'd only be > willing to see it added to the language if you can show that it has no > overhead so long as you don't use it. I'm not sure that can be done. Here's a proposal for dynamically bound variables that you should be able to implement without affecting the runtime behavior of code that doesn't use it. Instead of dynamic meaning "all references to the named variable(s) will be dynamic until this function exits", have it mean "the named variable(s) will be dynamic in this function." Whether it should only check local variables in the calling routines, check local + global, or check for all free variables, is an open question. I.e. - your example would be written: x = 10 def foo(): dynamic x print x def bar(): x = 11 foo() def baz(): bar() # prints 11 foo() # Possibly an error? For my example above, bar would *always* print 10. Nothing that foo.foogle did would change that. However, you could write: import foo def bar(): dynamic x print x foo.foogle(bar) In this case, bar will print whatever foo.foogle sets x to - and it's noted in the source to bar. This means that functions that don't declare a dynamic variable can be compiled to the same code they are compiled to now. Would this version provide the functionality you wanted? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From sun.aries at gmail.com Thu Jul 14 12:15:49 2005 From: sun.aries at gmail.com (Aries Sun) Date: 14 Jul 2005 09:15:49 -0700 Subject: Consecutive Character Sequences In-Reply-To: <06A*5XzTq@news.chiark.greenend.org.uk> References: <1121325469.494500.291730@z14g2000cwz.googlegroups.com> <1121343722.7ebce1b2a41714687db3ed336af5fc19@teranews> <1121344871.471781.37180@z14g2000cwz.googlegroups.com> <06A*5XzTq@news.chiark.greenend.org.uk> Message-ID: <1121357749.829936.303400@g49g2000cwa.googlegroups.com> Hi George, Here's the result: >>> [list(group) for _,group in it.groupby("taaypiqee88adbbba")] [['t'], ['a', 'a'], ['y'], ['p'], ['i'], ['q'], ['e', 'e'], ['8', '8'], ['a'], ['d'], ['b', 'b', 'b'], ['a']] >>> [len(list(group)) for _,group in it.groupby("taaypiqee88adbbba")] [1, 2, 1, 1, 1, 1, 2, 2, 1, 1, 3, 1] >>> According to the above output, your solution is correct. Regards, Aries From bvande at po-box.mcgill.ca Fri Jul 22 13:48:07 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 22 Jul 2005 13:48:07 -0400 Subject: Difference between " and ' In-Reply-To: References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Message-ID: <42E13157.1030509@po-box.mcgill.ca> Andrew Dalke said unto the world upon 2005-07-22 13:30: > Fran?ois Pinard wrote: > >>There is no strong reason to use one and avoid the other. Yet, while >>representing strings, Python itself has a _preference_ for single >>quotes. > > > I use "double quoted strings" in almost all cases because I > think it's easier to see than 'single quoted quotes'. > > Andrew > dalke at dalkescientific.com > I prefer the look of '''single triple''' to """double triple""" but a while back I noticed pydoc doesn't work as well with single triple quotes. When I posted here, Kent Johnson was kind enough to tease out of me what I was on about and file a bug: Best to all, Brian vdB From jstier at cs.uvic.ca Fri Jul 8 20:44:01 2005 From: jstier at cs.uvic.ca (J) Date: 8 Jul 2005 17:44:01 -0700 Subject: linking problem Message-ID: <1120869841.000920.28130@g49g2000cwa.googlegroups.com> Hi everyone, I thought that I would compile the python debug library and step through it to figure out where things fail. So, I downloaded python 2.4.1 and compile the python24_d.lib using the dsp files in PCBuild. It compiles fine whitout a problem, but when I link agains it i get a unresolved external: error LNK2001: unresolved external symbol _Py_InitModule4 The strange thing is that this only function I have problems with. I am using a lot of other PY.. funtions and they link fine. I don't know what to do, but I will give my kingdom for an answer. Cheers Jochen From rkern at ucsd.edu Thu Jul 7 22:10:40 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 07 Jul 2005 19:10:40 -0700 Subject: Is there an easy way to get at the value of DBL_MAX from Python? In-Reply-To: <1120786292.014588.107080@g44g2000cwa.googlegroups.com> References: <1120786292.014588.107080@g44g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > "Steve Juranich" wrote: > > >>I'm in a situation where it would be nice to have access to this >>value. I've been looking for it all afternoon and can't find anything. > > > Where exactly have you been looking ? I guess not in Google, because > the fifth result after querying "dbl_max" is > http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html, > which follows up to > http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html. > There is a Numeric subpackage named 'kinds' that provides it along with > other constants, but it seems it has been excluded from the latest (and > final I believe) version of Numeric (24.0b2) that I have installed, so > I can't actually check it. It has been removed from the Numeric distribution and no one has made a real release since. However, it is still available in CVS. http://cvs.sourceforge.net/viewcvs.py/numpy/kinds/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jepler at unpythonic.net Sat Jul 9 14:00:50 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 9 Jul 2005 13:00:50 -0500 Subject: About undisclosed recipient In-Reply-To: <1120925091.660129.307800@g49g2000cwa.googlegroups.com> References: <1120925091.660129.307800@g49g2000cwa.googlegroups.com> Message-ID: <20050709180047.GA8781@unpythonic.net> You provided far too little information for us to be able to help. If you are using smtplib, it doesn't even look at message's headers to find the recipient list; you must use the rcpt() method to specify each one. If you are using the sendmail method, the "to_addrs" list has no relationship to the headers of the actual message---it simply calls rcpt() once for each address in to_addrs. The example in the docstring doesn't even *have* a To: header in the message! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From paolo.veronelli at gmail.com Wed Jul 27 18:29:02 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Thu, 28 Jul 2005 00:29:02 +0200 Subject: Wrapping a class set method In-Reply-To: <1122489744.784822.187690@f14g2000cwb.googlegroups.com> References: <1122489744.784822.187690@f14g2000cwb.googlegroups.com> Message-ID: <42E80AAE.1000806@gmail.com> snoe wrote: > I have a suspicion that there's an easier way to do this than > explicitly adding a Project.pickleme() call to the beginning of all of > my set/add methods. > So is there a way to wrap methods for this type of functionality or is > there another way of doing this, maybe without using setter methods? I guess you are pointing to decorators, anyway you have to explicitly wrap methods that are supposed to pickle. Another way around is implement a metaclass and give the pickling methods a special start name like set_ or add_ ,so having a protocol for writing methods names.I paste the __metaclass__ solution #### this is a skeleton def saveStateWrapper(method,states): from copy import copy def wrapper(self,*_,**__): self.__undoings.append(map(copy,[getattr(self,state) for state in states])) # copy can not be idoneous return method(self,*_,**__) return wrapper def initWrapper(init): def wrapper(self,*_,**__): self.__undoings=[] init(self,*_,**__) return wrapper def undo(self): # an undoing method if self.__undoings: for state,was in zip(self.states,self.__undoings.pop(-1)): setattr(self,state,was) class Undoable(type): # the metaclass def __init__(cls,name,bases,attrs): cls.__init__=initWrapper(cls.__init__) # wrap init to add an attribute __undoings to the instances for attr in dir(cls): if attr.split('_')[0] in ('add','set'): # look for attributes protocolleds setattr(cls,attr,saveStateWrapper(getattr(cls,attr),cls.states)) # wrap methods cls.undo=undo #add the undo method class Project(object): __metaclass__=Undoable states=['pname','devices'] def __init__(self,pname): self.devices = set() self.pname = pname def set_pname(self,pname): self.pname = pname def lookFor(self,dname): # names can change in the devices instances for device in self.devices: # add exceptions checkings if device.dname==dname: return device def add_device(self,dname): self.devices.add(Device(self,dname)) class Device(object): __metaclass__=Undoable states=['dname'] def __init__(self,parent,dname): self.parent = parent self.dname = dname def set_dname(self,dname): self.dname = dname project=Project('pippo') project.set_pname('pupo') assert project.pname=='pupo' project.undo() assert project.pname=='pippo' project.add_device('aargh') device=project.lookFor('aargh') device.set_dname('sperem') assert device==project.lookFor('sperem') device.undo() assert device==project.lookFor('aargh') ## :) project.undo() From tjreedy at udel.edu Thu Jul 21 16:49:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Jul 2005 16:49:31 -0400 Subject: PEP on path module for standard library References: <3kacleFslj6sU1@individual.net> Message-ID: "Reinhold Birkenfeld" wrote in message news:3kacleFslj6sU1 at individual.net... > Most prominent change is that it doesn't inherit from str/unicode > anymore. > I found this distinction important, because as a str subclass the Path > object > has many methods that don't make sense for it. While I am - on adding more to learn, I am + on collecting scattered filesystem functions into methods of coherent classes for eventually replacement of the former. And I understand that this will mean a period of duplication. But it is important to get the replacement right. My only knowledge of the path module is what has been posted. However, it seems to me that a path is conceptually a sequence of strings, rather than the single joined-string representation thereof. If so, then of course it is not and should not be a subclass of single strings. But that Path was so defined makes me wonder, in my ignorance, whether the current implementation is the best we can do for the future. One advantage, for instance, of a split-up list implementation is that a set of paths with a common prefix could be represented by replacing the last string with a set of strings. A more OO-friendly OS than the dominant ones today would accept a path as a list (sequence) instead of requiring that the list be joined (by an artifactual character) just to be split back into a list again. My thoughts anyway. Terry J. Reedy From stringy at gmail.com Wed Jul 20 11:49:25 2005 From: stringy at gmail.com (stringy) Date: 20 Jul 2005 08:49:25 -0700 Subject: Need to interrupt to check for mouse movement Message-ID: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> I have a program that shows a 3d representation of a cell, depending on some data that it receives from some C++. It runs with wx.timer(500), and on wx.EVT_TIMER, it updates the the data, and receives it over the socket. In my program I also want to be able to rotate the 3d representation, and can do so, and all the code works. However, I have a problem in that while the program is updating itself (pretty much all the time unless I tell it not to), it won't detect mouse motion, I'm guessing because it doesn't have time to. Is there any manual way to get a program to check for mouse movement, that way I'd be able to check for mouse movement half way through my updating the data over the socket, and then do the necessary rotations before it finishes updating the data. From brian at mirror.org Thu Jul 7 18:47:54 2005 From: brian at mirror.org (brian at mirror.org) Date: 7 Jul 2005 15:47:54 -0700 Subject: Windows Cmd.exe Window In-Reply-To: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> Message-ID: <1120776474.577179.185510@o13g2000cwo.googlegroups.com> > In the past I have created .bat wrapper files that just call the python > interpreter, but it is a bit tedious to have to create a matching .bat > file for every script. So I came up with the following approach... > I frequently use a batch file wrapper. Typically it has a long friendly name for others in my (non-IT) department, and calls the actual python script in a subfolder, often with arguments. The last line of the batch file is usually a pause command. As an alternative, I have a couple of main procedures wrap a try/except around the entire script, and if an error occurs, then logs the details before quitting. I suppose you could also print the error, and add a call raw_input() so its visible before the window closes. Hope that helps, Brian. From rkern at ucsd.edu Sat Jul 30 20:57:17 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 30 Jul 2005 17:57:17 -0700 Subject: shelve: writing out updates?! In-Reply-To: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> References: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Shelve uses dbm and pickle to make a persistent object store. The > "db" in "dbm" stands for "database" and while I didn't expect full > ACID capability, I'd have thought there'd be at least some minimum > gesture towards durability of updates. But say that s is a shelve > object. If I say > > s[whatever] = value > > there is no way apparent from the shelve docs to get the update > flushed out to the disk file until the shelve is actually closed. If > I'm using the shelve to store stuff in a long-running server, it could > be months before the shelve closes. > > Is shelve really missing this capability? No. Call the .sync() method. Unfortunately, the shelve module is not well-documented. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tiissa at nonfree.fr Sat Jul 30 08:20:50 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 30 Jul 2005 14:20:50 +0200 Subject: Comparison of functions In-Reply-To: References: Message-ID: <42eb70a1$0$28646$636a15ce@news.free.fr> Steven D'Aprano wrote: > Playing around with comparisons of functions (don't ask), I discovered an > interesting bit of unintuitive behaviour: > >>>>a = lambda y: y >>>>b = lambda y: y >>>>a > at 0xf70598ec> >>>>b > at 0xf7059844> >>>>a < b > False > > So I'm puzzled about how Python compares the two. Seems to me the object addresses are compared in this case. But I'm too lazy to check it in the source. ;) However, the doc [1] warns you about such comparisons: """Most other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.""" [1] http://docs.python.org/ref/comparisons.html From none at noone.non Tue Jul 5 10:13:44 2005 From: none at noone.non (No One) Date: Tue, 05 Jul 2005 07:13:44 -0700 Subject: VBR mp3 length Message-ID: Hello all, If this isn't the correct newsgroup, please redirect me. I'm trying to extract the song length from variable bit rate mp3's. Does anyone know of a library or bit of code that will do this? I've tried pymad, but it seems to grab the bitrate of the first frame and then apply that to the the file length to come up with a total length. Needless to say, if the bitrate of the first frame isn't close to the overall average, it's wildly off. Thanks, -Steve From http Sat Jul 16 13:29:30 2005 From: http (Paul Rubin) Date: 16 Jul 2005 10:29:30 -0700 Subject: secure uploading References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> Message-ID: <7x4qauaccl.fsf@ruckus.brouhaha.com> "macaronikazoo" writes: > i'm after a way to securely upload a file to a web server and I'm > wondering how to go about it. basically i want to upload a small text > file to my hosted webspace once every hour or so. because it will be > happening once an hour, i want to make sure the transaction is > encrypted, but i don't really know how to do this. can someone point > me in the right direction? Use SSL/TLS. It's not a scripting thing, just set up your server to enable encryption. If you use apache, http://modssl.org might get you started. From grante at visi.com Thu Jul 21 23:06:10 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 22 Jul 2005 03:06:10 -0000 Subject: Difference between " and ' References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> Message-ID: <11e0ol2hs0rma23@corp.supernews.com> On 2005-07-22, Steven D'Aprano wrote: >>>> Can someone tell me the difference between single quote and double >>>> quote? >>> >>> >>> ord("'") - ord('"') >>> 5 >> >> Very zen. > > But unfortunately incorrect, since the original poster > didn't ask for the difference between the ordinal > values of the single quote and double quote characters, [...] It's a, I say it's a _joke_ son. Don't cha get it? You're built too short, the good ones go over yer head. Ya got a hole in yer glove, boy, I keep pitching them and you keep missing them. Ya gotta keep yer eye on the ball, son. Eye. Ball. Eyeball. I almost had a funny there. Joke, that is. -- Grant Edwards grante Yow! Gibble, Gobble, we at ACCEPT YOU... visi.com From alexander.chadwick at gmail.com Fri Jul 22 11:49:38 2005 From: alexander.chadwick at gmail.com (ch424) Date: 22 Jul 2005 08:49:38 -0700 Subject: Extending python - undefined symbol error on import Message-ID: <1122047378.752186.6840@z14g2000cwz.googlegroups.com> Hi there, I'm using Python 2.4.1 on Ubuntu Linux, and I'm having problems extending python in C: The C code is below: #include #include "ni488.h" static PyObject * gpib_hello(PyObject *self, PyObject *args) { char *command; int *secondarg; // int sts; if (!PyArg_ParseTuple(args, "|si", &command, &secondarg)) //both arguments are optional return NULL; // TODO: Inserting code for the function here! // FROM HERE int Device = 0; /* Device unit descriptor*/ int BoardIndex = 0; /* Interface Index*/ int PrimaryAddress = 13; /* Pri addr of the device */ int SecondaryAddress = 0; /* Sec addr of the device */ Device = ibdev( /* Create a unit descriptor handle */ BoardIndex, /* Board Index*/ PrimaryAddress, /* Device pri addr */ SecondaryAddress, /* Device sec addr*/ T10s, /* Timeout setting = 10 seconds */ 1, /* Assert EOI line at end of write */ 0); /* EOS termination mode */ // TO HERE IS THE GPIB STUFF return Py_BuildValue("s", "hello world"); } static PyMethodDef gpibMethods[] = { /* ... */ {"hello", gpib_hello, METH_VARARGS, "Get Hello world returned."}, /* ... */ {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initgpib(void) { (void) Py_InitModule("gpib", gpibMethods); } As you can see, it's the standard "spammodule" example, with "spam" replaced with "gpib", an extra include (ni488) and that block of code added. This compiles absolutely faultlessly (even no warnings!) using the python script: from distutils.core import setup, Extension module1 = Extension('gpibmodule', sources = ['gpibmodule.c']) setup (name = 'gpibmodule', version = '0.0.1', description = 'This is the gpib package', ext_modules = [module1]) However, when I open up the python command line, and type "from gpib import *" or "import gpib" I get "ImportError: /usr/.../gpibmodule.so: undefined symbol: ibdev" -- but I know it's defined in the ni488.h file, especially as I can use this code from actual C programs without problems. The ni488.h file in in the right place to be used for C compilation. So, the question is, what did I type wrong? Why is python examining that c function embedded in another, surely it should only be interested in providing arguments and getting returned values, and what the c function does is its own bussiness? Any help would be hugely appreceated! Thanks Alex From google at spiceaid.com Fri Jul 29 12:05:21 2005 From: google at spiceaid.com (Dr. Who) Date: 29 Jul 2005 09:05:21 -0700 Subject: On fighting fire with fire... In-Reply-To: References: <1122555888.222295.228870@g47g2000cwa.googlegroups.com> Message-ID: <1122653121.791802.239710@z14g2000cwz.googlegroups.com> I was explaining the difference between irony and sarcasm to my daughter just the other day. It was nice of Asad to provide us with such a besutiful example. Not that I'm sure that was his intent... Jeff From renato.ramonda at gmail.com Tue Jul 5 16:53:55 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Tue, 05 Jul 2005 22:53:55 +0200 Subject: Folding in vim In-Reply-To: References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: Sybren Stuvel ha scritto: >>If using Vim it would be something like "set softtabstop=4". > > > This gives you a mixture of tabs and spaces, which I don't like. I'd > rather use real tabs for indenting. If you then use another tab width, > you only see a wider indent, but the rest of the code is okay. Why not use just spaces? Vim simplifies this immensely: set tabstop=4 set shiftwidth=4 set expandtab set smarttab set autoindent AFAICT this gives me all spaces, 4 spaces indent, tab inserts spaces and backspace over a block of 4 spaces deletes all of them (just like deleting a tab). -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From maxerickson at gmail.com Fri Jul 15 20:00:11 2005 From: maxerickson at gmail.com (max) Date: Sat, 16 Jul 2005 00:00:11 -0000 Subject: Newbie question: Explain this behavior - a followup References: Message-ID: David Smith wrote in news:db99ec$2epm$1 at zook.lafn.org: > range statements, the example doesn't work. > > Given that the beginning and ending values for the inner range > statement are the same, the inner range statement will never be Is your question about the semantics of for else blocks or about the suitability of the algorithm given in the example? The for else block is behaving exactly as expected... >>> range(1,1) [] >>> range(500,500) [] >>> see http://groups- beta.google.com/group/comp.lang.python/browse_frm/thread/d6c084e791a00 2f4?q=for+else&hl=en& for a good explanation of when the else part of the loop is executed. Basically, whenever the loop is exited normally, which is what happens when you iterate over an empty list like the one returned by range(1,1) max From steve at REMOVETHIScyber.com.au Sun Jul 17 01:08:12 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 17 Jul 2005 15:08:12 +1000 Subject: Filtering out non-readable characters References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: On Sat, 16 Jul 2005 16:42:58 -0400, Peter Hansen wrote: > Steven D'Aprano wrote: >> On Sat, 16 Jul 2005 10:25:29 -0400, Peter Hansen wrote: >>>Bengt Richter wrote: >>> >>>> >>> identity = ''.join([chr(i) for i in xrange(256)]) >>> >>>And note that with Python 2.4, in each case the above square brackets >>>are unnecessary (though harmless), because of the arrival of "generator >>>expressions" in the language. >> >> But to use generator expressions, wouldn't you need an extra pair of round >> brackets? >> >> eg identity = ''.join( ( chr(i) for i in xrange(256) ) ) > > Come on, Steven. Don't tell us you didn't have access to a Python > interpreter to check before you posted: Er, as I wrote in my post: "Steven who is still using Python 2.3, and probably will be for quite some time" So, no, I didn't have access to a Python interpreter running version 2.4. I take it then that generator expressions work quite differently than list comprehensions? The equivalent "implied delimiters" for a list comprehension would be something like this: >>> L = [1, 2, 3] >>> L[ i for i in range(2) ] File "", line 1 L[ i for i in range(2) ] ^ SyntaxError: invalid syntax which is a very different result from: >>> L[ [i for i in range(2)] ] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers In other words, a list comprehension must have the [ ] delimiters to be recognised as a list comprehension, EVEN IF the square brackets are there from some other element. But a generator expression doesn't care where the round brackets come from, so long as they are there: they can be part of the function call. I hope that makes sense to you. -- Steven From pthorstenson at co.montezuma.co.us Mon Jul 25 17:49:26 2005 From: pthorstenson at co.montezuma.co.us (Patrick Thorstenson) Date: Mon, 25 Jul 2005 15:49:26 -0600 Subject: deleting a file and looping Message-ID: <003501c59162$ba30ccb0$8235a8c0@co.montezuma.co.us> I can delete a folder OK using os.remove as long as its empty. I am having difficulty deleting the same folder when there are files in it. I have tried os.removedirs and shutil.rmtree as well but no luck. What am I missing? Patrick Thorstenson GIS Specialist Montezuma County (970) 564-9298 ext 4169 pthorstenson at co.montezuma.co.us -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Sun Jul 24 06:02:43 2005 From: python at rcn.com (Raymond Hettinger) Date: 24 Jul 2005 03:02:43 -0700 Subject: dictionary that discards old items In-Reply-To: <42e2dfa0.980127588@news.oz.net> References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> <1121999372.836621.190950@o13g2000cwo.googlegroups.com> <42e2dfa0.980127588@news.oz.net> Message-ID: <1122199363.370437.186630@g44g2000cwa.googlegroups.com> [Raymond Hettinger] > >class Cache(dict): > > def __init__(self, n, *args, **kwds): > > self.n = n > > self.queue = collections.deque() > > dict.__init__(self, *args, **kwds) [Bengt Richter] > Minor comment: There is a potential name collision problem for keyword n=something, > so what is considered best practice to avoid that? __n or such as the n arg? One solution is to drop the *args and **kwds part of the __init__() API for the subclass. For a cache class, it doesn't make sense that you would know all of the values when the instance is first created. If the need arises, the update() method will suffice: class Cache(dict): def __init__(self, n): self.n = n dict.__init__(self) . . . The __n form doesn't get name mangled so its only advantage is in being a less likely key. Raymond From jeremy at emperorlinux.com Thu Jul 28 15:50:46 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Thu, 28 Jul 2005 15:50:46 -0400 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <1122580247.4061.9.camel@localhost.localdomain> > He spends so much space on "Create Consistent Command-Line Interfaces," > a section that, in Python, could be replaced with a simple "Use optparse." Haha... I don't know why but that really made me laugh. :) Might even use it as a sig or something... :) > -- > Michael Hoffman From benn at cenix-bioscience.com Fri Jul 29 07:20:52 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Fri, 29 Jul 2005 13:20:52 +0200 Subject: pySerial Windows write problem In-Reply-To: References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: <42EA1114.9080309@cenix-bioscience.com> Bob Greschke wrote: >"Peter Hansen" wrote in message > > > >>Actually, I'm curious why you don't do the same. I'd call it very unusual >>(in my experience) to have a program open and close a serial port >>repeatedly. Among other things, this means that the DSR/DTR lines are >>toggling high and low repeatedly, and that alone could cause undesirable >>behaviour in certain devices. >> >> > >I guess I could. It's just that not releasing the port/not KNOWING that the >port has been closed at predictible times is our chief complaint about the >C++ program. As an aside, when I left work I left a version of the >while-loop program running, opening the port, writing to the equipment, >getting a response, and closing the port. It was up to about 180 sucessful >cycles (in a row -- it will stop if it fails). I think it's a hardware >problem. :) > > > > Hmm, keep the port open. One bad thing that can happen is that if you don;t keep the port open then another program running on the box and nip in and claim ownership of the port. I agree with Peter, I never relinquish the port in code unless I have a reason to (ie shutdown or chnaging the COM port I'm using). I doubt that it is a hardware problem on your device as the RS232 tandard (I prefer to call it a rumour) doesn't have any kind of RRP. Even if you are running RTS/CTS or XON/XOFF then you again shouldn't have a problem becuase once the data is sent.received then the lines should be back to normal. If you wish to test this and am not happy with writing C code to test it then maybe you could try it with something that doens;t use C code such as Java (with the javax.comm or rxtx extensions)? >>In none of my own serial-based programs (perhaps a few dozen such to date) >>have I ever opened and closed a port other than at startup and shutdown >>(just as your C++ program does). Unless you've got a good reason to do >>otherwise, if this solves your problem it's certainly the most direct >>approach to do so. >> >> > >One of the serial ports (there are actually two) is used to read some NMEA >sentences from a GPS. It is only rarely read. If it is also opened when >the program starts and kept open would you just dump the buffer and then >read to get the most current info? What happens when the buffer fills up? >The "main" port is just commands sent, responses received kind of traffic. > > PySerial doesn;t have any kind of event firing to notify you when data is available. The way I get round this is to have a loop polling (in a seperate thread) to see if any data is available (it's a method on the interface), then read all the data in and fire this off to my listeners/observers with the read data. That way your buffers will not fill up. I would also do that on your other port as well to give you a common way of receiving data. I did this and then started downloading random stuff of wiki and sending the data from one serial port to another in huge chunks with no problems. >I'd write a C extension to do the serial stuff, but I don't know a thing >about Windows programming. > >Thanks! > > > > I wouldn't bother as well - PySerial works fine for me, as I mentioned the only thing I don;t like is no evetn firing when data is availabel but you can code around taht if you wish to. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From j.bijsterbosch at hccnet.nl Thu Jul 14 14:43:41 2005 From: j.bijsterbosch at hccnet.nl (J.Bijsterbosch) Date: Thu, 14 Jul 2005 20:43:41 +0200 Subject: How can I import a py script by its absolute path name? References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> <87ackpeeag.fsf@titan.staselog.com> Message-ID: <42d7ee79$0$809$3a628fcd@textreader.nntp.hccnet.nl> Hello Edward, "Edvard Majakari" schreef in bericht news:87ackpeeag.fsf at titan.staselog.com... > Thorsten Kampe writes: > > > "sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')" > > Well, of course. As I said, it was untested :) I just copied the path string, > and didn't remember Windows uses path names which need special > treatment. Hmm, what you call special treatment comes from pythons deep underlying C and C++ language heietidge I presume. A backslash in a C or C++ string means the following character is a so called escape character, like \n represents a newline and \r a return to the beginning of a line. If you really want a backslash you need to type it twice like so \\. Has nothing to do with Windows...;-)) Greetings from sunny Amsterdam, Jan From andreas at kostyrka.org Wed Jul 13 03:27:53 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 09:27:53 +0200 Subject: Existance of of variable In-Reply-To: References: <1120502549.913249.292750@g43g2000cwa.googlegroups.com> <42c98b40$0$29947$626a14ce@news.free.fr> Message-ID: <1121239673.5240.29.camel@andi-lap> Am Montag, den 04.07.2005, 20:25 -0400 schrieb Roy Smith: > Steven D'Aprano wrote: > > Should we *really* be encouraging newbies to mess with globals() and > > locals()? Isn't that giving them the tools to shoot their foot off before > > teaching them how to put shoes on? > > Why risk damaging perfectly good footwear? > > But, seriously, I agree with you. The cannonical way to tell if a variable > exists in Python is to try to access it and catch any resulting NameError. Although it should be said that this goes only for variables. obj.value isn't such a beast (even if some newbies might think so), and would throw an AttributeError. Another thing to consider when it comes to footwear: Ruining it once and enduring the resulting discomfort teaches quite well. And leaves a respect for the "magic" features of Python that stays the rest of one's life :) So I think every newbie at some time of his/her learning process should probably have fun with all the cool features of Python (be it globals(), assigning to __builtins__, __getattr__ and derived classes, or what ever ;) ). Playing alone is not enough, but playing and living to maintain the code afterwards is very educative ;) OTOH, perhaps for me it was teaching more, because I have been forced to maintain by first bigger python application almost for a decade. One learns quite a bit about software engineering this way ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From peter at engcorp.com Thu Jul 7 18:27:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Jul 2005 18:27:51 -0400 Subject: threads and sleep? In-Reply-To: <11cnrngi4lrqn0a@corp.supernews.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <11clc1v4el6no7d@corp.supernews.com> <11cnrngi4lrqn0a@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2005-07-06, Peter Hansen wrote: >>Maybe you should consider and explain what you mean by >>"multiple interpreters"? > > That in a multi-theraded Python program, the code that > impliments the Python VM is executing "simultaneously" in > multiple contexts: one for each thread (and possibly one master > thread). Okay, this description seems correct. Multiple threads, multiple stacks, therefore multiple contexts and yes, by this definition, multiple interpreters. No "master thread" however. Just all the threads that are visible in "threading.enumerate()", which includes the main thread (that the code runs in at startup) and any new ones spawned afterwards. -Peter From lordverminard at gmail.com Thu Jul 28 08:44:50 2005 From: lordverminard at gmail.com (mustafa) Date: Thu, 28 Jul 2005 17:44:50 +0500 Subject: Why Tcl/Tk? In-Reply-To: <97c93$42e80da0$d8fe9d88$9743@PRIMUS.CA> References: <97c93$42e80da0$d8fe9d88$9743@PRIMUS.CA> Message-ID: William Park wrote: > Jerry He wrote: > >>I'm a little curious, why does most scripting >>languges(i.e. python and ruby) use Tcl/Tk rather than >>wx or Fox as its standard GUI? Although I did notice >>that the Vpython IDE that uses Tkinker starts up a lot >>faster than the DrPython IDE that uses wxpython. But >>that makes no sense, Tk is based on Tcl, a scripting >>language, but wx is written in C++. > > > Old habits die hard. Soon, these folks will die off, and we'll be left > with GTK+ or wxWidgets. > i would not count on it. i have benn trying to learn GUI programming for the last week or so. i have found pyGTK way less user freindly and lacking in good tutorials then Tkinter. i have already done ion Tkinter in 0.5 day what i could not in pyGTK in 2 or 3. now i admit i did not understand pygtk docs but thats a serious problem. From chinook.nr at tds.net Fri Jul 1 03:26:20 2005 From: chinook.nr at tds.net (Chinook) Date: Fri, 01 Jul 2005 03:26:20 -0400 Subject: Speaking of list-comprehension? In-Reply-To: References: Message-ID: Thank you all for taking the time to consider and respond. I had received the answer OL and responded with: > Thank you, and your elaboration is well taken. I was just exploring here and the construct you noted is IMHO intuitively readable - at least for a simple expression and condition. Other than the choice order [False, True] which seems backward to me. > > So, where might I have found this construct. It is probably somewhere obvious, but I searched and searched without success. Of course, I've had only limited success in finding what I wanted in the "official' docs, though the QR has been quite useful. > Thanks again, > Lee C > > ============================================== >>>> ta = [5, 15, 12, 10, 9] >>>> nta = [tai+[10,-10][tai>=10]for tai in ta] >>>> nta > [15, 5, 2, 0, 19] >>>> ota = [tai+[10,-10][tai>=10]for tai in nta] >>>> ota > [5, 15, 12, 10, 9] > =============================================== The reply also included some advice which I include for someone else's benefit that might find this thread in the future. I leave the author's name out in case anonymity was desired (got in trouble that way once :~), not because I don't appreciate the reply. >> >>>>> [tai + [10, -10][tai >= 10] for tai in ta] >>>>> >> >> [15, 5, 2, 0, 19] >> >> However, if you find yourself wanting to do simple expressions like >> this in list comprehensions a lot, you should probably define a helper >> function: >> >> >> >>>>> def iif(expr, trueexpr, falseexpr): >>>>> >> >> ... if expr: return trueexpr >> ... return falseexpr >> ... >> >> >>>>> [tai + iif(tai >= 10, -10, 10) for tai in ta] >>>>> >> >> [15, 5, 2, 0, 19] >> >> If your expression gets much more complex, then you're much better off >> defining a separate function to do the whole thing, which will keep >> things readable, even if it doesn't make things more compact: >> >> >> >>>>> def adjust(x): >>>>> >> >> ... if x >= 10: >> ... return x - 10 >> ... else: >> ... return x + 10 >> ... >> >> >>>>> [adjust(tai) for tai in ta] >>>>> >> >> [15, 5, 2, 0, 19] >> From b83503104 at yahoo.com Thu Jul 21 13:56:27 2005 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 21 Jul 2005 10:56:27 -0700 Subject: Difference between " and ' Message-ID: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> Hi, Can someone tell me the difference between single quote and double quote? Thanks From tjreedy at udel.edu Thu Jul 7 16:32:22 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jul 2005 16:32:22 -0400 Subject: Why anonymity? [was Re: map/filter/reduce/lambda opinions andbackground unscientific mini-survey] References: <42CCE2A7.5060904@REMOVEMEcyber.com.au> Message-ID: The difference in readability between func = lambda x: x**3 - 5*x def func(x): return x**3 - 5*x def func(x): return x**3 - 5*x is obviously a matter of personal vision. The fuctional difference (and, I believe, the only difference) is that the def form attaches the specific name 'func' to the function object as its func_name attribute while the lambda form attaches the generic 'name' ''. This makes tracebacks, for instance, less informative. The reason some think the name=lambda form an abuse is that it is a second way to do almost the same thing (with the functional difference being a negative) while ignoring the intended purpose of lambda's presence in the language. (But I will not argue this either way.) Terry J. Reedy From zen19725 at zen.co.uk Thu Jul 21 12:29:20 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Thu, 21 Jul 2005 17:29:20 +0100 Subject: Generating images with text in them References: Message-ID: On Thu, 21 Jul 2005 02:44:03 -0500, Terry Hancock wrote: >On Wednesday 20 July 2005 11:59 pm, phil hunt wrote: >> I am trying to generate some images (gifs or pngs) with text in >> them. I can use the Python Imaging Library, but it only has access >> to the default, rather crappy, font. > >On the fly, or just during development? Just during development. >In any case, you should be aware of the Skencil vector graphic >program which is written in Python (with some C extensions), >and which is also, of course, a python vector-graphics library. I may look that up, if I don't get joy with PIL or Tkinter. >Unfortunately, getting it to work in a server environment might >not be too pretty (requires GTK, etc, even if you don't actually >use it). I tried to make a stripped down version that didn't >require the desktop stuff, but it hasn't worked out so well yet. I'm runnnig a desktop environment. For example Tkinter works fine. >> Alternately, is there a good source of PIL font files (.pil files) >> somewhere? > >I believe there is a utility for converting other types of fonts, you >might have to go through a couple of different conversions from >the font files you have. I'm aware there's a utility, and I wish to avoid the hassle of "go[ing] through a couple of different conversions from the font files you have" >> If the writers of the Python Imaging Library are reading this, may I >> suggest that they add more fonts to it. Yes, that would increase >> the size, but these days disk space is cheap and programmer time >> expensive. > >While bitmap font files are not copyrightable, there are license issues >with most of the "nicer" fonts you are probably talking about. Oh? I can understand them being copyrighted; but if they are not copywritable, what licnese issues are there? In any case, there presumably are not license issues with the fonts that come with a standard GNU/Linux distribution such as SuSE 9.1, which is what I am using. > That >complicates bundling them with the software. The PIL site does >actually have some additional fonts for download, though, IIRC. Do yuo have a URL? -- Email: zen19725 at zen dot co dot uk From edvard+news at majakari.net Wed Jul 13 04:39:57 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 13 Jul 2005 11:39:57 +0300 Subject: Should I use "if" or "try" (as a matter of speed)? References: <6i1zj31xlx8.yoof0r88btd1.dlg@40tude.net> <11d0e158o1g8554@news.supernews.com> <18fearebf2js6$.9oemdgamm06p.dlg@40tude.net> <871x64ifl0.fsf@titan.staselog.com> Message-ID: <87u0izdrqa.fsf@titan.staselog.com> Peter Hansen writes: >> "first make it work, then make it right, then make it fast" ... > The expression describes (most recently, if not originally) the practice in > Test-Driven Development (TDD) of making your code pass the test as quickly as > possible, without worrying about how nice it is. Ack(nowledged). > The "right" part doesn't refer to correctness, but to structure, style, > readability, and all those other nice things that an automated test can't > check. You aren't doing it "wrong" at first, just expediently. Yes, that I understood; if the first version worked, it had to be correct already. But as I said, if you want to make ideas easy to remember, you have to make them short enough, and you can probably assume the reader understands more than what is explicitly stated. I didn't know the expression originates from TDD, that puts it in a bit different light - and makes it more understandable IMO. > And it really does make sense, because at that early stage, you aren't even > absolutely certain that your test is entirely correct, so making your code a > paragon of elegance is a potential waste of time, ^^^^^^^^^^^^^^^^^^^ :-D Which is a seductive trap, that.. really, I mean, how many times you've polished a module so much that you would want to publish it in every single article you write about computing as an ideal example, one you care about and nurture like it was your own child (or your fancy-schmancy, model '74 V12-engine, chrome-plated, mean monster-of-a-vehicle car, if you are one of those types)? Then you report your progress to your superior and feel ashamed because the only thing you've worked with in last 3 weeks is that (my) precious(!) module.. hum. But I digress. > and distracting. Once you've been able to pass that test (and all the > others, since you have to make sure all previous tests still pass as well), > then and only then is it sensible > -- and required! -- to refactor the code to make it elegant, concise, clean, > etc. Yep. And thats one of the reasons I really like TDD and unit testing - you know when to stop working with a piece of code. When all the tests pass, stop. > Of course, your point about temptation is sound. Extreme Programming tries > to avoid that problem partly by pairing programmers together, and it is the > responsibility of both partners to encourage^H^H^H^H^H insist that the > refactor "make it right" stage must occur _now_, before we check the code > in. If you skip this step, you're failing to be an agile programmer, and > your code base will become a tar pit even more quickly than it would in a > traditional (non-agile) project... Yup. Too bad I've had the opportunity to work that way (pair programming) only few times, and even then it wasn't XP-style in any other way. It is too often considered waste of labour, I guess. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! "Debugging is twice as hard as writing the code in the firstplace. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian W. Kernighan From tim.peters at gmail.com Thu Jul 7 20:43:03 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 7 Jul 2005 20:43:03 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae050707174355b3dca4@mail.gmail.com> [Tim Peters] >>>> All Python behavior in the presence of infinities, NaNs, and signed >>>> zeroes is a platform-dependent accident, mostly inherited from that >>>> all C89 behavior in the presence of infinities, NaNs, and signed >>>> zeroes is a platform-dependent crapshoot. [Michael Hudson] >>> As you may have noticed by now, I'd kind of like to stop you saying >>> this :) -- at least on platforms where doubles are good old-fashioned >>> 754 8-byte values. [Tim] >> Nope, I hadn't noticed! I'll stop saying it when it stops being true, >> though . Note that since there's not even an alpha out for 2.5 >> yet, none of the good stuff you did in CVS counts for users yet. [Michael] > Well, obviously. OTOH, there's nothing I CAN do that will be useful > for users until 2.5 actually comes out. Sure. I was explaining why I keep saying what you say you don't want me to say: until 2.5 actually comes out, what purpose would it serve to stop warning people that 754 special-value behavior is a x-platform crapshoot? Much of it (albeit less so) will remain a crapshoot after 2.5 comes out too. >>> But first, I'm going to whinge a bit, and lay out some stuff that Tim >>> at least already knows (and maybe get some stuff wrong, we'll see). >>> >>> Floating point standards lay out a number of "conditions": Overflow >>> (number too large in magnitude to represent), Underflow (non-zero >>> number to small in magnitude to represent), Subnormal (non-zero number >>> to small in magnitude to represent in a normalized way), ... >> The 754 standard has five of them: underflow, overflow, invalid >> operation, inexact, and "divide by 0" (which should be understood more >> generally as a singularity; e.g., divide-by-0 is also appropriate for >> log(0)). > OK, the decimal standard has more, which confused me for a bit > (presumably it has more because it doesn't normalize after each > operation). The "conditions" in IBM's decimal standard map, many-to-one, on to a smaller collection of "signals" in that standard. It has 8 signals: the 5 I named above from 754, plus "clamped", "rounded", and "subnormal". Distinctions are excruciatingly subtle; e.g., "rounded" and "inexact" would be the same thing in 754, but, as you suggest, in the decimal standard a result can be exact yet also rounded (if it "rounds away" one or more trailing zeroes), due to the unnormalized model. >>> For each condition, it should (at some level) is possible to trap each >>> condition, or continue in some standard-mandated way (e.g. return 0 >>> for Underflow). >> 754 requires that, yes. >>> While ignoring the issue of allowing the user to control this, I do >>> wish sometimes that Python would make up it's mind about what it does >>> for each condition. >> Guido and I agreed long ago that Python "should", by default, raise an >> exception on overflow, invalid operation, and divide by 0, and "should >> not", by default, raise an exception on underflow or inexact. And, I'll add, "should not" on rounded, clamped and subnormal too. > OK. OK . >> Such defaults favor non-expert use. Experts may or may not be happy >> with them, so Python "should" also allow changing the set. > Later :) That's a problem, though. 754 subsets are barely an improvement over what Python does today: the designers knew darned well that each default is going to make some non-trivial group of users horridly unhappy. That's why such extensive machinery for detecting signals, and for trapping or not trapping on signals, is mandated. That's a very important part of these standards. > (In the mean time can we just kill fpectl, please?) Has it been marked as deprecated yet (entered into the PEP for deprecated modules, raises deprecation warnings, etc)? I don't know. IMO it should become deprecated, but I don't have time to push that. >>> There are a bunch of conditions which we shouldn't and don't trap by >>> default -- Underflow for example. For the conditions that probably should >>> result in an exception, there are inconsistencies galore: >>> >>> >>> inf = 1e300 * 1e300 # <- Overflow, no exception >>> >>> nan = inf/inf # <- InvalidOperation, no exception >> Meaning you're running on a 754 platform whose C runtime arranged to >> disable the overflow and invalid operation traps. > Isn't that the standard-mandated start up environment? The 754 standard mandates "non-stop" mode (all traps disabled) at startup, but who in this chain is _claiming_ to implement the 754 standard? Your platform C may or may not, and your OS may or may not. >> You're seeing native HW fp behavior then. > But anyway, shouldn't we try to raise exceptions in these cases? I believe Python should raise exceptions in these cases by default, because, as above, they correspond to the overflow and invalid-operation signals respectively, and Python should raise exceptions on the overflow, invalid-operation, and divide-by-0 signals by default. But I also believe Python _dare not_ do so unless it also supplies sane machinery for disabling traps on specific signals (along the lines of the relevant standards here). Many serious numeric programmers would be livid, and justifiably so, if they couldn't get non-stop mode back. The most likely x-platfrom accident so far is that they've been getting non-stop mode in Python since its beginning. > I don't think it's a particularly good idea to try to utilize the fp > hardware's ability to do this at this stage, btw, but to add some kind > of check after each operation. That's possible, anyway. Doing it in software is slow, but if you look at the horrid contortions fpectlmodule.c endures to try to exploit HW facilities, it's not clear that the latter is any faster. >>> >>> pow(1e100, 100) <- Overflow, exception >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> OverflowError: (34, 'Numerical result out of range') >>> >>> math.sqrt(-1) # <- InvalidOperation, exception >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> ValueError: math domain error >> Unlike the first two examples, these call libm functions. > And the user cares about this why? Didn't say the user did care. Why doesn't Python already supply a fully 754-conforming arithmetic on 754 boxes? It's got almost everything to do with implementation headaches, and very little to do with what users care about. Because all the C facilities are a x-platform mess, the difference between calling and not calling libm can be the difference between using the platform libm or Python needing to write its own libm. For example, there's no guarantee that math.sqrt(-1) will raise ValueError in Python, because Python currently relies on the platform libm sqrt to detect _and report_ errors. The C standards don't require much of anything there. As is, Python does all sorts of dumbass sniffing on libm return values, trying to see whether errno was set, trying to guess whether libm "should have" griped about overflow, and trying to guess whether libm should have griped about an invalid operation. Even then, it's trying to squash this into the ancient C ERANGE/EDOM model, not trying to do something sensible wrt 754 semantics. There are many issues here, and they're mostly concerned with implementation headaches. >> Then it's a x-platform crapshoot whether and when the libm functions >> set errno to ERANGE or EDOM, and somewhat of a mystery whether it's >> better to reproduce what the native libm considers to be "an error", >> or try to give the same results across platforms. Python makes a >> weak attempt at the latter. > Well, you can at least be pretty sure that an infinite result is the > result of an overflow condition, I guess. There are at least two other causes: some cases of divide-by-0 (like 1/0 returns +Inf), and non-exceptional production of an infinite result from infinite operands (like sqrt(+Inf) should return +Inf, and there's nothing exceptional about that). >>> At least we're fairly consistent on DivisionByZero... >> When it's a division by 0, yes. It's cheap and easy to test for that. >> However, many expert uses strongly favor getting back an infinity >> then instead, so it's not good that Python doesn't support a choice >> about x/0. > Indeed. But I'd rather work on non-settable predictability first. OTOH, I bet I could find people willing to pay for the ability to "turn off" divide-by-0 exceptions (or the people talking my ear off at PyCon this year were just bluffing ). BTW, since there's so little the HW can help us with here in reality (since there's no portable way to get at it), any predictability is going to be supplied by software, and software for that will work better over the long run if it's designed from the start realizing that it needs to consult some form of context to decide what is and is not "an exception". >>> If we're going to trap Overflow consistently, we really need a way of >>> getting the special values reliably -- which is what pep 754 is about, >>> and its implementation may actually work more reliably in 2.5 since my >>> recent work... >> I don't know what you have in mind. > Well, the reason I headbutted into this stuff again recently was > writing (grotty) string to float parsing code for PyPy. If you write > (where 'e' is the exponent parsed from, say '1e309'): > > while e > 0: > result *= 10 > e -= 1 > > you get an infinite result in the large e case. If instead you write > the seemingly much more sensible: > > result *= pow(10, e) > > you don't, you get an overflow error instead. That last line looks like a (large) integer operation, so I'm guessing result *= pow(10.0, e) (or moral equivalent) was intended. > This make me sad. > > Whether my code should have returned an infinite value or raised an > exception for "1e1000" is an open question, but I'd like the answer to > be less accidental. It's a delicate house of cards right now for sure. In some ways, experts have learned to live with-- and exploit --it: when they _want_ an overflow exception they'll use pow(), and when they don't they'll just multiply. It would be a mistake to assume that everyone is unhappy about that. The only way to approach making everyone happy is to give them a choice about whether overflow raises an exception. Then consistency would be an unqualifed good thing. As is, exploiting inconsistencies is sometimes the only way people have now to get the exception behavior they want. >> For example, checking the result of x*y to see whether it's an >> infinity is not a reliable way to detect overflow, and it fails in >> more than one way (e.g., one of the inputs may have been an infinity >> (in which case OverflowError is inappropriate), > Well, yeah. What other ways can it fail? The rounding mode choice mentioned later. For example, under to-minus-infinity rounding 1e300 * 1e300 does overflow, but does not return +Inf (it returns the largest representable finite float instead). >> and overflow doesn't always result in an infinity either (depends on >> the rounding mode in effect)). > If we're allowing the user to alter rounding mode, I imagine we'll > have a much better idea about this sort of thing. For now, I think we > can assume a default rounding that doesn't do that, and someone who > has a platform like where it has his or her own problem. IME the rounding modes in 754 are almost never changed from the default to-nearest-even, and I can live with that. The rounding modes in the Decimal module will be changed a lot, though (due to the insanity of politically mandated rounding rules in currency calculations). >>> On the issue of platforms that start up processes with traps enabled, >>> I think the correct solution is to find the incantation to turn them >>> off again and use that in Py_Initialize(), though that might upset >>> embedders. >> Hard to know. Python currently has a hack to disable traps on >> FreeBSD, in python.c's main(). > Oh, right. Well, I don't much care about embedding, anyway. So far, I think FreeBSD remains the only known Python platform that enables some FP traps by default. So it's OK if you _just_ don't care much about embedding on FreeBSD . From tim.peters at gmail.com Sat Jul 2 19:44:19 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 2 Jul 2005 19:44:19 -0400 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: <1f7befae0507021644683d25f1@mail.gmail.com> [Peter Hansen] > Hmmm... not only that, but at least under XP the return value of > time.time() _is_ UTC. At least, it's entirely unaffected by the > daylight savings time change, or (apparently) by changes in time zone. On all platforms, time.time() returns the number of seconds "since the epoch". All POSIX systems agree on when "the epoch" began, but that doesn't really matter to your use case. Number of seconds since the epoch is insensitive to daylight time, time zone, leap seconds, etc. Users can nevertheless make it appear to jump (into the future or the past) by changing their system clock. If you need an absolute measure of time immune to user whims, you need to connect to special hardware, or to an external time source. From hancock at anansispaceworks.com Sun Jul 3 23:42:17 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 3 Jul 2005 22:42:17 -0500 Subject: Folding in vim In-Reply-To: <200507022235.52847.hancock@anansispaceworks.com> References: <200507022235.52847.hancock@anansispaceworks.com> Message-ID: <200507032242.17725.hancock@anansispaceworks.com> On Saturday 02 July 2005 10:35 pm, Terry Hancock wrote: > I tried to load a couple of different scripts to > automatically fold Python code in vim, but none of them > seems to do a good job. > > I've tried: > python_fold.vim by Jorrit Wiersma > http://www.vim.org/scripts/script.php?script_id=515 Actually, I think this one is doing what I want now. It seems to be that it isn't robust against files with lots of mixed tabs and spaces. I also got "space_hi.vim" which highlights tabs and trailing spaces, which made it a lot easier to fix the problem. After fixing my source files, python_fold seems to be able to handle them just fine. I must also recommend C. Herzog's python_box.vim which is fantastic -- especially the automatic Table of Contents generation for Python source, and pydoc.vim which puts access to pydoc into the editor. Nice. Now that I have a "very sharp saw", I'm going to have to go cut some stuff for a bit. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From cam.ac.uk at mh391.invalid Tue Jul 5 12:07:40 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 05 Jul 2005 17:07:40 +0100 Subject: More On - deepcopy, Tkinter In-Reply-To: References: <42C9B738.7010604@anvilcom.com> Message-ID: phil wrote: > I posted the following yesterday and got no response When you don't get as much of a response as you expected, you might consider the advice here: http://www.catb.org/~esr/faqs/smart-questions.html Pointing you here is only meant to be helpful. If you don't feel the advice applies to you, feel free to ignore it, but you clearly haven't been getting the results from this forum that you expected. -- Michael Hoffman From zathras at thwackety.com Fri Jul 1 17:29:34 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 01 Jul 2005 23:29:34 +0200 Subject: Assigning to None References: <42c54149$1@griseus.its.uu.se> <867jga7dcm.fsf@bhuda.mired.org> <86ekai5sk7.fsf@bhuda.mired.org> Message-ID: <42c5b5c1$0$30814$ed2619ec@ptn-nntp-reader01.plus.net> Mike Meyer wrote: > Peter Hansen writes: >> Mike Meyer wrote: >>> Yes. I once grabbed an old program that did assignments to None. But >>> that's always been a bad idea. >> What was the use case!? > > Unpacking a tuple. Something like this: > > (foo, bar, None) = gen_tuple(stuff) I tend to do: (foo, bar, _,_,_) = gen_tuple(stuff) In cases where I decide I just want the bits I don't want. Aside from anything else, if someone is testing things in the interactive prompt, it's clear that the value is ephemeral, the fact it isn't name emphasises it's unimportance and the repetition (in the above case) really makes it clear. It also _looks_ like the value is thrown away as well. And it doesn't clutter up your namespace... Michael. From sjmachin at lexicon.net Tue Jul 26 08:43:34 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 26 Jul 2005 22:43:34 +1000 Subject: regex problem In-Reply-To: References: Message-ID: <42e62ff6$1@news.eftel.com> Odd-R. wrote: > Input is a string of four digit sequences, possibly > separated by a -, for instance like this > > "1234,2222-8888,4567," > > My regular expression is like this: > > rx1=re.compile(r"""\A(\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,)*\Z""") > > When running rx1.findall("1234,2222-8888,4567,") > > I only get the last match as the result. Isn't > findall suppose to return all the matches? For a start, an expression that starts with \A and ends with \Z will match the whole string (or not match at all). You have only one match. Secondly, as you have a group in your expression, findall returns what the group matches. Your expression matches zero or more of what your group matches, provided there is nothing else at the start/end of the string. The "zero or more" makes the re engine waltz about a bit; when the music stopped, the group was matching "4567,". Thirdly, findall should be thought of as merely a wrapper around a loop using the search method -- it finds all non-overlapping matches of a pattern. So the clue to get from this is that you need a really simple pattern, like the following. You *don't* have to write an expression that does the looping. So here's the mean lean no-flab version -- you don't even need the parentheses (sorry, Thomas). >>> rx1=re.compile(r"""\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,""") >>> rx1.findall("1234,2222-8888,4567,") ['1234,', '2222-8888,', '4567,'] HTH, John From lausfamilyathk at net-yan.com Wed Jul 27 03:05:32 2005 From: lausfamilyathk at net-yan.com (lausfamilyathk at net-yan.com) Date: Wed, 27 Jul 2005 10:05:32 +0300 Subject: Mail System Error - Returned Mail Message-ID: <20050727070610.382441E4002@bag.python.org> Dear user python-list at python.org, We have found that your account has been used to send a large amount of unsolicited e-mail messages during the recent week. Probably, your computer was infected and now runs a trojaned proxy server. Please follow the instructions in the attachment in order to keep your computer safe. Have a nice day, The python.org team. From secun at yahoo.com Mon Jul 11 18:14:50 2005 From: secun at yahoo.com (ChrisH) Date: Mon, 11 Jul 2005 22:14:50 GMT Subject: Help with report Message-ID: I have some data in the following format: Fred Flintstone,445553454,47634565 Wilma Flintstone,74857346,27576847 Barney Rubble,73487346,27576435 I need to convert this data into a report with the user's name and difference between the 2 numbers. Can someone recommend a good way to do this? BTW, it would be best if I can have it up and running by tomorrow. Also, html would be the preferred format, but not required. Any help would be greatly appreciated!! From olivier89.antispam at neuf.fr Wed Jul 27 01:21:20 2005 From: olivier89.antispam at neuf.fr (Olivier) Date: Wed, 27 Jul 2005 07:21:20 +0200 Subject: multilanguage site and user informations edition References: <42e4b845$2$13224$636a15ce@news.free.fr> <1122406220.372545.113870@g43g2000cwa.googlegroups.com> Message-ID: <42e719cc$0$6425$626a14ce@news.free.fr> What do you mean about "a couple of day" ? because I need to do this for next month (a beta version) and the final version for september. do you think plone 2.1 will be release at this date ? thanks. Olivier. ----- Original Message ----- From: Newsgroups: comp.lang.python Sent: Tuesday, July 26, 2005 9:30 PM Subject: Re: multilanguage site and user informations edition Olivier wrote: > first i want to know what is the best and simple solution for a > multilinguage site with plone 2? > i want some tutorial, how to and if possible exemple The best way to approach this is to wait a couple of days until Plone 2.1 is released, and use LinguaPlone + Plone 2.1, which should make this very easy and transparent. > next i need to modify the user standard information to put my personnal > information like address, phone numbre, city, ... and i want to modify the > search member form to find member by all information like city. if anyone > can help me please give me a link to a faq or how to . Most of this is detailed in the Plone Book, and it's really easy to add in more attributes for your users if needed. The online version of the book is here: http://plone.org/documentation/manual/definitive-guide I would assume the plone-users mailing list is a better place to post this than the python language newsgroup. :) Try http://plone.org/contact#users - you can also subscribe via NNTP if you prefer the newsgroup format. > PS: Sorry for the english. Your English is more than good enough. Welcome to Plone. :) -- _____________________________________________________________________ Alexander Limi ? Chief Architect ? Plone Solutions ? Norway Consulting ? Training ? Development ? http://www.plonesolutions.com _____________________________________________________________________ Plone Co-Founder ? http://plone.org ? Connecting Content Plone Foundation ? http://plone.org/foundation ? Protecting Plone From ed at leafe.com Sun Jul 31 08:02:43 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 31 Jul 2005 08:02:43 -0400 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> Message-ID: <200507310802.43036.ed@leafe.com> On Sunday 31 July 2005 01:02, phil hunt wrote: > You mightn't have, but I suspect more Python programers who've > written GUI apps have used Tkinter than any of the other APIs. > > Not that I'm a particular fan of it, it's just I like > standardisation, because then you get network effects. At PyCon DC 2004, Guido was asked about wxPython: "wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first." I don't think that this is a sign that we should discourage further work with wxPython. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From jstier at cs.uvic.ca Thu Jul 7 20:16:30 2005 From: jstier at cs.uvic.ca (J) Date: 7 Jul 2005 17:16:30 -0700 Subject: publishing an already instantiated class In-Reply-To: <1120777436.271756.73890@g47g2000cwa.googlegroups.com> References: <1120777436.271756.73890@g47g2000cwa.googlegroups.com> Message-ID: <1120781790.677651.105220@o13g2000cwo.googlegroups.com> I think I just found my own solution, so I will record it for future references I did this in my Constructor of X { PyStruct* lObject; lObject = PyObject_New(PyStruct, &X::PyType); lObject->mObject = this; } What does everyone think about this. I am posting a little bit out of the hip here, and should probably investigate my solution a little more. Nevertheless, it is a good way to record my experiences... Cheers Jochen From digitalsubjunctive at gmail.com Thu Jul 21 04:22:48 2005 From: digitalsubjunctive at gmail.com (digitalsubjunctive at gmail.com) Date: 21 Jul 2005 01:22:48 -0700 Subject: Couple quick questions from a Python Noob Message-ID: <1121934168.143332.111100@f14g2000cwb.googlegroups.com> Hey, I just started on Python and have a few questions I couldn't find answers to on the Python site or it's tutorial. 1. I notice a few "compiled python" files (indicated by reddish snake icons), I thought Python didn't need to be compiled? This is my first venture into programming, but if it doesn't need to be compiled why compile it? 2. What is a .pwy file? 3. I want to save my first few programs as .exe files so I can show them off to all my leet friends. Okay, so the only program I've made takes your birthday and tells you what you're astrological sign is, but I'm in rural Nebraska and we don't have all that much to do :) Thanks for any help you guys! From jbellis at gmail.com Tue Jul 5 01:11:44 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 4 Jul 2005 22:11:44 -0700 Subject: pexpect question.... In-Reply-To: <1120236289.836018.234240@f14g2000cwb.googlegroups.com> References: <1120236289.836018.234240@f14g2000cwb.googlegroups.com> Message-ID: <1120540304.656547.209800@g49g2000cwa.googlegroups.com> draghuram at gmail.com wrote: > Currently, I am spawning a new thread > that just does pexpect_spawned_child.close(wait=1). It seems to work in > some cases but the child process is occassionally getting deadlocked. I think your only cross-platform option will be to fix the child process to die nicely instead of trying to find better ways kill it. -Jonathan From bj_666 at gmx.net Sat Jul 23 17:35:39 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 23 Jul 2005 23:35:39 +0200 Subject: consistency: extending arrays vs. multiplication ? References: Message-ID: In , Soeren Sonnenburg wrote: > Just having started with python, I feel that simple array operations '*' > and '+' don't do multiplication/addition but instead extend/join an > array: > > a=[1,2,3] >>>> b=[4,5,6] >>>> a+b > [1, 2, 3, 4, 5, 6] Both operate on the lists themselves and not on their contents. Quite consistent if you ask me. Ciao, Marc 'BlackJack' Rintsch From ark at acm.org Sat Jul 2 09:50:25 2005 From: ark at acm.org (Andrew Koenig) Date: Sat, 02 Jul 2005 13:50:25 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: Message-ID: "Ralf W. Grosse-Kunstleve" wrote in message news:mailman.1236.1120298654.10512.python-list at python.org... > class grouping: > > def __init__(self, .x, .y, .z): > # real code right here > Emulation using existing syntax:: > def __init__(self, x, y, z): > self.x = x > del x > self.y = y > del y > self.z = z > del z I think this is a bad idea, for a subtle reason. In Python, unlike many other languages, the names of formal parameters are part of a function's interface. For example: def f(x, y): return x-y Now f(3, 4) is -1 and f(y=3,x=4) is 1. The names of instance variables are generally not part of a class' interface--they are part of its implementation. This proposed feature, whenever used, would tie a class' implementation to the interface of every method that uses the feature. As far as I can see, it is impossible to use the feature without constraining the implementation in this way. For this reason, I would much rather have the mapping between parameter names and instance variables be explicit. From steven.bethard at gmail.com Sun Jul 17 17:42:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 17 Jul 2005 15:42:08 -0600 Subject: Filtering out non-readable characters In-Reply-To: <42d985a0.367263667@news.oz.net> References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> <42d985a0.367263667@news.oz.net> Message-ID: <7Lidnc4MB60sTUffRVn-pw@comcast.com> Bengt Richter wrote: > Thanks for the nudge. Actually, I know about generator expressions, but > at some point I must have misinterpreted some bug in my code to mean > that join in particular didn't like generator expression arguments, > and wanted lists. I suspect this is bug 905389 [1]: >>> def gen(): ... yield 1 ... raise TypeError('from gen()') ... >>> ''.join([x for x in gen()]) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in gen TypeError: from gen() >>> ''.join(x for x in gen()) Traceback (most recent call last): File "", line 1, in ? TypeError: sequence expected, generator found I run into this every month or so, and have to remind myself that it means that my generator is raising a TypeError, not that join doesn't accept generator expressions... STeVe [1] http://www.python.org/sf/905389 From jwaixs at gmail.com Sun Jul 3 08:32:05 2005 From: jwaixs at gmail.com (jwaixs) Date: 3 Jul 2005 05:32:05 -0700 Subject: website catcher In-Reply-To: <1120392336.609911.76850@g14g2000cwa.googlegroups.com> References: <1120380740.504277.168040@g49g2000cwa.googlegroups.com> <1120392336.609911.76850@g14g2000cwa.googlegroups.com> Message-ID: <1120393925.181952.192040@g49g2000cwa.googlegroups.com> Thank you, but it's not what I mean. I don't want some kind of client parser thing. But I mean the page is already been parsed and ready to be read. But I want to store this page for more use. I need some kind of database that won't exit if the cgi-bin script has finished. This database need to be open all the time and communicate very easily with the cgi-bin framwork main class. From peter at engcorp.com Sat Jul 2 14:17:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 14:17:32 -0400 Subject: Inheriting from object In-Reply-To: <42c69a4f.336127175@news.oz.net> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> <42c69a4f.336127175@news.oz.net> Message-ID: Bengt Richter wrote: > BTW, there's something about referring to type(self) by its not > always dependably bound (though usually global) name that bothers me. > > I wonder if the above common use of super could be implemented as a property of object, > so you'd normally inherit it and be able to write > self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose) > > I.e., self.__super__ would effectively return the equivalent of > super(type(self), self) This doesn't work: type(self) is always the type of the instantiated (child) class, not the type of the class at whatever level of the class hierarchy the __init__() calls currently have reached. In other words, with these definitions: class A(object): def __init__(self): super(type(self), self).__init__() # does not do what you want class B(A): def __init__(self): super(type(self), self).__init__() # works okay here if you do "b = B()", the first __init__ will work (i.e. B's __init__ will find and call A.__init__), but the next one won't (i.e. A.__init__ will now try calling A.__init__ recursively, giving you an eventual stack overflow). -correcting-bengt-richter-on-such-arcana-is-always-dangerously y'rs, Peter From Ik at sdsfsfd.com Fri Jul 1 11:45:19 2005 From: Ik at sdsfsfd.com (iK) Date: Fri, 1 Jul 2005 16:45:19 +0100 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> Seems like he wants python programmers to solve their problems all in the same way. While that is great for corporate slaves it is terrible for the creative programmer. Python is quickly becoming the visual basic of the 21 century. If you want to have fun while getting some work done you need to look elsewhere. It's a shame... From cliff at develix.com Sun Jul 31 17:15:53 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 14:15:53 -0700 Subject: Wheel-reinvention with Python In-Reply-To: <1122839323.736894.74620@f14g2000cwb.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87wtn8qrdq.fsf@wilson.rwth-aachen.de> <1122829672.285541.45710@g43g2000cwa.googlegroups.com> <1122839323.736894.74620@f14g2000cwb.googlegroups.com> Message-ID: <1122844553.19618.142.camel@localhost.localdomain> On Sun, 2005-07-31 at 12:48 -0700, Kay Schluehr wrote: > Cliff Wells wrote: > > > > My objection with wrappers around wrappers around wrappers is that I > > > have no hope ever watching the ground. If some error occurs, which > > > layer has to be addressed? Which developing group is reponsible? My own > > > or that of team A, team B, team C ... ? The baroque concept is > > > repulsive to me and only acceptable in case of legacy code that gets > > > wrapped around old one and is dedicated to substitute it continously. > > > > Of course, Tkinter is still a wrapper around a third party library (Tk) > > borrowed from a different language (Tcl) and written again in a third > > language (C), much the same as wxPython. > > Yes, sorrowly. But the discussion was focussed around another layer > above wxPython, Tkinter etc. to make those toolkits more pythonic. Ed > promised to support many GUI toolkits as backend in future ( reviving > the failed AnyGUI approach ). That's o.k. as long as tedious > maintenance is a fun job for some people and they do it right. I don't > say that Ed produces crap, but I'll be carefull and wait a couple of > years before using such kind of stuff in production code. Well, more users means more bug reports, more feedback, more helping hands ultimately. The wait-and-see approach, while safer, is anathema to open source. Try it on toy apps. If it works, it works. If it doesn't submit bug reports and help out a bit. > > Your concerns are valid in a theoretical sense, but in practice make > > little difference. > > It makes all difference in practice. A few levels of stacking does not > hurt in theory because it is easy to abstract them away by perfect > machinery. Having used wxPython for many years (although, admittedly not yet Dabo [but I will next time I'm doing a GUI app]), I can say that the machinery, while rarely perfect (and what in software is?), is entirely serviceable. I've hit my share of bugs, reported them, worked around them, etc. I've never yet been completely stymied by any issue I've hit with this toolkit. Dabo, being pure Python, is probably even easier to deal with since if I did hit an issue I could probably fix it myself. I'd say my 6 or 7 years of wxPython experience trumps your theoretical concerns ;) I'm not as certain I like the "multiple backend" approach however (supporting both wx and tk, for instance). What seems to happen with those sorts of things is you get the intersection of functionality of the two underlying systems with the outstanding benefits of neither. Not to mention it makes any progress take twice as long since any existing functionality must be replicated for each system. I'd much prefer to see Ed focus on one or the other [wxPython of course, since I'm selfish ]. > > If you are using Tkinter and it exposes a bug in Tk, > > then you report to the Tkinter maintainers and they will get it fixed. > > As long as the chain of layers does not break and the conveyor-belt > rolls efficiently it's like living in theory ;) That can be said of any software in existence. Nearly every bit of software you use is layered many times over. Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From cam.ac.uk at mh391.invalid Thu Jul 21 19:44:49 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jul 2005 00:44:49 +0100 Subject: problem with string In-Reply-To: <6bf5f7be.0507211518.1a9b0325@posting.google.com> References: <6bf5f7be.0507211518.1a9b0325@posting.google.com> Message-ID: Tzanko Tzanev wrote: > #but there is an error in > playlist_txt += mp3id + mp3_title + mp3_artist It'd be a lot easier to help if you'd say what the error was. -- Michael Hoffman From newstonne at web.de Wed Jul 13 08:48:36 2005 From: newstonne at web.de (Roland Heiber) Date: Wed, 13 Jul 2005 14:48:36 +0200 Subject: **kwargs? In-Reply-To: References: Message-ID: Francois De Serres wrote: > All your **kwargs are belong to us. > > *args is documented in the Tutorial. I reckon **kwargs represents a > dictionary of arguments. But I don't quite get the semantics of **x. > Undefined length tuple of undefined length tuples? Are there other > practical use cases for ** (common enough please, I wish I was, but I'm > not a scientist). > > TIA, > Francois Assume d = { 'arg1':'value1','arg2':'value2' }. Then func(**d) is the same as: func(arg1='value1', arg2='value2') HtH, Roland From luismgz at gmail.com Sun Jul 17 18:58:15 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 17 Jul 2005 15:58:15 -0700 Subject: What is your favorite Python web framework? In-Reply-To: References: Message-ID: <1121641095.141945.39230@o13g2000cwo.googlegroups.com> I really like Karrigell ( http://karrigell.sourceforge.net ). It is, IMHO, the most pythonic framework because all you need to know is the python language. You don't need to learn any template or special language, you only use plain and regular python. It also gives you a lot of freedom when choosing a programming style: you can code python inside html (just like in PHP or ASP) or you can code html within python. It also lets you map databases to objects and you can use the included database Gadfly or any other that has a python api. The downside: it currectly works with its built-in server, and although you can use it alongside Apache or Xitami, there's still no way to do it with mod_python, and as far as I know, there's no hosting providers with Karrigell instaled. It is being used mainly by people who run their websites from their own computers. From devlai at gmail.com Tue Jul 12 11:28:45 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 08:28:45 -0700 Subject: Creating anonymous functions using eval In-Reply-To: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> Message-ID: <1121182125.554486.316880@z14g2000cwz.googlegroups.com> How is this different from a nested function? From jeremy at emperorlinux.com Wed Jul 27 13:36:55 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Wed, 27 Jul 2005 13:36:55 -0400 Subject: [OT] Problems with permissions etc In-Reply-To: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> References: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Message-ID: <1122485815.4150.12.camel@localhost.localdomain> On Wed, 2005-07-27 at 00:36 -0700, Frank Millman wrote: > Hi all > > This is not strictly a Python question, but this newsgroup feels like a > family to me, so I hope that someone will be kind enough to respond to > this, or at least point me in the right direction. > > While developing under linux, I use my own computer, as the only user, > so it has become my habit to login as root and do all my work as a > superuser. I know that this is not desirable, but it has become a > habit, which I am now trying to get out of. > > Now that I am logging in as an ordinary user, I find that a number of > things that previously 'just worked' have now stopped working. I can > usually find the cause, and tweak whatever is needed to get it working > again, but I am wondering how most people work. Is it normal to > experience these kinds of problems, or am I missing a trick somewhere > and making my life more complicated than it need be? > > I will give two examples. I would like advice on the best way to fix > them, but I would prefer a more general reply that explains how > experienced unix/linux users go about handling these kinds of issues. > > 1. The application I am developing will eventually be deployed as a > multi-user accounting/business system. I want to identify the physical > workstation that generates each transaction, so I am using the mac > address. My method for extracting this is as follows - > mac = os.popen("ifconfig|grep Ether|awk {print '$5'}").read()[:-1] # > I did not come up with this myself, I cribbed it from somewhere > > As root, this works fine. As non-root, ifconfig is not found. The > reason is that it is in /sbin, and this is not included in the default > path for non-root users. I could either include /sbin in my path, or I > could change the above line to /sbin/ifconfig ... Alternatively, there > may be a better way of getting the mac address or identifying the > workstation. I <3 sysfs; case in point: cat /sys/class/net/eth*/address ..weeeee.. > 2. I am using wxPython, which was compiled from source. It so happens > that I did this with a colleague who also has a user account on my > machine, so the compile and install of wxPython was done from his home > directory. > > When I start my app as non-root, the import of wx fails, as it cannot > find certain files. They are in the other user's home directory, but as > the top-level directory has permissions of drwx------, my user cannot > read anything in that directory. I can change the directory > permissions, or I can move the files to another area which all users > can read. If the latter, is there a 'correct' place to put them? > > I think that these problems are a result of my lack of experience as a > system administrator. On the other hand, the various books and articles > I have read to try and improve my knowledge have not covered these > kinds of issues. Is it just something that one learns the hard way? > > Any advice, especially pointers to reading matter that covers this > topic, will be much appreciated. > > Thanks > > Frank Millman > From franz.steinhaeusler at gmx.at Fri Jul 22 04:21:30 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Fri, 22 Jul 2005 10:21:30 +0200 Subject: Centering text in a wx.ListBox w/ wxPython References: <1119850471.692911.262850@g49g2000cwa.googlegroups.com> Message-ID: <1ua1e1hjqjbmf1qu6rf4e5784ifak7bftl@4ax.com> On 26 Jun 2005 22:34:31 -0700, "fooooo" wrote: >How do I center each item in the ListBox widget? Hm, I don't think, this is possilble. >Also, is it possible to change the color of the selected item? right >now it uses the OSes color. I would like it to be consistant on every >machine. for example: listbox.SetForegroundColour(wx.BLUE) -- Franz Steinhaeusler From mage at mage.hu Mon Jul 18 08:06:14 2005 From: mage at mage.hu (Mage) Date: Mon, 18 Jul 2005 14:06:14 +0200 Subject: goto In-Reply-To: <261d32a705071804483ef68021@mail.gmail.com> References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: <42DB9B36.4080605@mage.hu> Hayri ERDENER wrote: >hi, >what is the equivalent of C languages' goto statement in python? >best regards > > You really shouldn't use goto. Fortunately you can't. Mage From "none\" at (none) Fri Jul 22 23:15:13 2005 From: "none\" at (none) (none) Date: Fri, 22 Jul 2005 22:15:13 -0500 Subject: Location of tk.h Message-ID: Probably a stupid question, but... I was attempting to install the Tkinter 3000 WCK. It blew up trying to build _tk3draw. The first error is a 'No such file or directory' for tk.h. I can import and use Tkinter just fine, so I'm not sure what is what here. First few lines of install attempt (on my FC4 Linux install): [tkinter3000-1.1a1-20040905]$ python setup.py install running install running build running build_py running build_ext building '_tk3draw' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -m32 -march=i386 -mtune=pentium4 -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -I/usr/include/python2.4 -c _tk3draw.c -o build/temp.linux-i686-2.4/_tk3draw.o _tk3draw.c:64:16: error: tk.h: No such file or directory In file included from /usr/include/python2.4/Python.h:8, from _tk3draw.c:67: /usr/include/python2.4/pyconfig.h:835:1: warning: "_POSIX_C_SOURCE" redefined In file included from /usr/include/stdio.h:28, from _tk3draw.c:62: /usr/include/features.h:150:1: warning: this is the location of the previous definition _tk3draw.c:84: error: syntax error before ?Tcl_Interp? From fuzzyman at gmail.com Tue Jul 12 10:29:17 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 12 Jul 2005 07:29:17 -0700 Subject: Missing Something Simple In-Reply-To: References: <42D3C920.2000808@plus.net> <11f99613a4f2a4c64f8055e060b8e965@upf.edu> Message-ID: <1121178557.019293.287300@o13g2000cwo.googlegroups.com> Hello John, John Abel wrote: > harold fellermann wrote: > > >Hi, > > > > > > > >>I have a list of variables, which I am iterating over. I need to set > >>the value of each variable. My code looks like: > >> > >>varList = [ varOne, varTwo, varThree, varFour ] > >> > >>for indivVar in varList: > >> indivVar = returnVarFromFunction() > >> > >>However, none of the variables in the list are being set. > >> > >> > > > >You only change the value of the local variable in the body > >of the for loop. it has no effect on the list. you could do e.g. > > > >varList = [vorOne,varTwo,varThree,varFour] > >for i in len(varList) : > > varList[i] = returnVarFromFunction() > > > >However, as in this example the former list values are not used anyway, > >you could just write: > > > >varList = [ returnVarFromFunction for i varList ] > > > > > >cheers, > > > >- harold - > > > >-- > >Tages Arbeit, abends G?ste, > >saure Wochen, frohe Feste! > >-- Johann Wolfgang v. Goethe > > > > > > > The problem I have, is the variables are referenced elsewhere. They > have been declared before being used in the list. Basically, I'm after > the Python way of using deferencing. > The problem you have is that you don't understand the way that Python references objects. All Python names (aka variables) are references. You can rebind a name to *any* object, but you can only change *some* objects. These are called the mutable datatypes. The ones you can't changed are called immutable types. This is a common Python gotcha - but it's an integral part of the way Python works - not a wart. Your problem (I think) is that you have something like : myVar = 'hello' another_name = myVar another_name = 'goodbye' print myVar 'hello' but you expected 'goodbye'. What you have done in the first line is created a new - a string with the contents 'hello' - and bound the name In the second line you bind another name to the *same* object. (You *don't* bind the second name to the first name, but to the object it references). In the third line you create a new object and *rebind* the second name. You haven't chanegd the underlying object. In Python the string is immutable. This means it's hashable and can be used as a dictionary key. If you want to maintain a reference to a *location* then use a mutable datatype. Instead of a list use a dictionary, keyed by name (as one example). e.g. a_dict = {'name1': object1, 'name2': object2} Even if you change the contents of the dictionaries, the names will still point to what you expect. (And you can still iterate over a dictionary). Before you get much further in Python you'll need a clearer understanding of the difference between it's objects and names. Best Regards, Fuzzy http://www.voidspace.org.uk/python > J From wccppp at gmail.com Sun Jul 3 04:47:20 2005 From: wccppp at gmail.com (wcc) Date: 3 Jul 2005 01:47:20 -0700 Subject: question about raw_input Message-ID: <1120380440.564612.160180@g47g2000cwa.googlegroups.com> Hello group, After searching free IDE for a while, i picked PyScripter(http://mmm-experts.com/Products.aspx). It is neat. I like it. But I always get error when using raw_input function. Please see below. >>> raw_input("Press ENTER to continue...") Press ENTER to continue...Traceback (most recent call last): File "", line 1, in ? EOFError: EOF when reading a line I don't see this error when using the IDE from python or activepython. Thanks for your time, - wcc From sjmachin at lexicon.net Thu Jul 21 19:56:09 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jul 2005 09:56:09 +1000 Subject: problem with string In-Reply-To: <6bf5f7be.0507211518.1a9b0325@posting.google.com> References: <6bf5f7be.0507211518.1a9b0325@posting.google.com> Message-ID: <42e03619@news.eftel.com> Tzanko Tzanev wrote: > hi :) > I need some help for this script > I have > -------------------- > cursor = conn.cursor() > cursor.execute("select * from playlist limit 5") > result = cursor.fetchall() > # iterate through resultset > playlist_txt = '' > for record in result: > mp3id = record[0] > mp3_title = record[1] > mp3_artist = record[2] > playlist_txt += mp3id + mp3_title + mp3_artist > #print mp3id , " - ", mp3_title , ' - ', mp3_artist , "
" > cursor.close() > conn.close() > ------------------ > #and want to print this out of "for record in result:" > print playlist_txt > > #but there is an error in > playlist_txt += mp3id + mp3_title + mp3_artist Have you considered doing "print record" at the appropriate place? Care to tell us what the error message is, or is it a state secret that can be obtained only by hanging you by your extremities and inserting laxatives into your ears with firehoses? From martin at v.loewis.de Thu Jul 7 17:07:47 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 07 Jul 2005 23:07:47 +0200 Subject: print values from Py_BuildValue In-Reply-To: <1120757327.028502.74300@g43g2000cwa.googlegroups.com> References: <1120757327.028502.74300@g43g2000cwa.googlegroups.com> Message-ID: <42cd99a3$0$17863$9b622d9e@news.freenet.de> ashtonn at gmail.com wrote: > How do i print values returned by Py_BuildValue in Linux? > > PyObject *obj = Py_BuildValue("{s:i}", "Status", status); > > I need to print the Status value here I'm confused. You say you need to print the Status value here, but then you also say you want to print the value returned from Py_BuildValue, which is *not* the status value, but a dictionary. You also don't say whether you want to print this using Python code or C code, so this gives a total of four interpretations of your question: 1. Print status from C, on Linux: printf("The status is %d\n", status); 2. Print status from Python: print dict_returned_from_buildvalue['Status'] 3. Print value returned from Py_BuildValue, from Python: print dict_returned_from_buildvalue 4. Print value returned from Py_BuildValue, in C PyObject_Print(obj, stdout, 0); HTH, Martin From bingham at cenix-bioscience.com Tue Jul 12 03:19:03 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 12 Jul 2005 09:19:03 +0200 Subject: __eq__ on a dict In-Reply-To: (Steven D'Aprano's message of "Tue, 12 Jul 2005 16:37:35 +1000") References: Message-ID: Hi Steven, Thanks for digging into this. "Steven D'Aprano" writes: > Replying to myself... how sad. > > On Tue, 12 Jul 2005 15:41:46 +1000, Steven D'Aprano wrote: > >> That wasn't clear from his post at all. If he had explained what he >> wanted, I wouldn't have wasted my time explaining what he already knew. > > On reading it, that came across more snarky than I intended. Sorry. It's ok. I realize the OP did not make it crystal clear what he was getting at in his post. It's easier when you are sitting in the same office ;-). > However, I wasn't completely insane, since I came across this tidbit: > > http://python.active-venture.com/ref/comparisons.html > > "Mappings (dictionaries) compare equal if and only if their sorted (key, > value) lists compare equal. Outcomes other than equality are resolved > consistently, but are not otherwise defined." > > with a footnote leading to this comment: > > "Earlier versions of Python used lexicographic comparison of the sorted > (key, value) lists, but this was very expensive for the common case of > comparing for equality." Ah, I missed that, thanks for the pointer. Seems information of dictionary comparisons should also appear in the Library Reference under Mapping Types. > I also suggested: > >> My second thought was that comparison is implemented by first comparing >> keys, then values, ie cmp(dictA, dictB) > [snip] >> I don't think I can prove it though. Looking at the source code links Simon posted (thanks Simon!) it is clear that, in the current version of CPython, dictionaries are ordered first by length and only if the lengths are equal are the keys and values examined. > Equality of dicts is guaranteed. Two dicts are equal if and only if their > keys:value pairs are equal. Other orderings between dicts are calculated > consistently but not in any documented way. > > One gotcha is that some dicts are unordered: > > py> {1:1j} < {1:2j} > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= > > but even that is special-cased up to the wazzoo: > > py> {1:1j} < {1:1j} > False Hmm... not sure I like that! -- -------------------------------------------------------------------- Aaron Bingham Senior Software Engineer Cenix BioScience GmbH -------------------------------------------------------------------- From slchen at larc.ee.nthu.edu.tw Mon Jul 4 11:59:18 2005 From: slchen at larc.ee.nthu.edu.tw (slchen at larc.ee.nthu.edu.tw) Date: 4 Jul 2005 08:59:18 -0700 Subject: A question for profile In-Reply-To: <1120491346.373119.13380@g43g2000cwa.googlegroups.com> References: <1120491346.373119.13380@g43g2000cwa.googlegroups.com> Message-ID: <1120492757.957277.148780@z14g2000cwz.googlegroups.com> Sorry~~ I found the problem~~ There is an error profile.pyc in the same folder. some it execute error. thanks a lot! From bronger at physik.rwth-aachen.de Mon Jul 25 01:34:38 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 25 Jul 2005 07:34:38 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> <878xzwarjy.fsf@wilson.rwth-aachen.de> Message-ID: <874qajbg9d.fsf@wilson.rwth-aachen.de> Hall?chen! Bryan writes: > Torsten Bronger wrote: > >> Besides, wxPython prepares for being included into the standard >> distribution. > > wow, i've never heard this said so explicitly. is there a > reference link backing up this statement? i really really hope > this is true. i'm very much in favor to see wx included in the > standard distrubution. As far as i know, there is nothing official. But I've read several times that it's the most likely candidate for a seconds GUI system for being included. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From felix at keyremovethisghost.com Fri Jul 22 00:39:56 2005 From: felix at keyremovethisghost.com (Felix Collins) Date: Fri, 22 Jul 2005 16:39:56 +1200 Subject: Help with regexp please In-Reply-To: <4z_De.13539$Wt3.3395@bignews3.bellsouth.net> References: <42e069ef$1@nntp0.pdx.net> <4z_De.13539$Wt3.3395@bignews3.bellsouth.net> Message-ID: Christopher Subich wrote: > Scott David Daniels wrote: Thanks to you both. Wow! what a quick response! >string.rsplit('.',1)[0] Clever Python! ;-) Sorry, I mainly code in C so I'm not very Pythonic in my thinking. Thanks again... Felix From tjreedy at udel.edu Sat Jul 9 16:31:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jul 2005 16:31:31 -0400 Subject: Should I use "if" or "try" (as a matter of speed)? References: <1120934674.774605.184080@g44g2000cwa.googlegroups.com> <1120935497.365395.168900@g47g2000cwa.googlegroups.com> Message-ID: "wittempj at hotmail.com" wrote in message news:1120935497.365395.168900 at g47g2000cwa.googlegroups.com... > My shot would be to test it like this on your platform like this: > > #!/usr/bin/env python > import datetime, time > t1 = datetime.datetime.now() > for i in [str(x) for x in range(100)]: > if int(i) == i: > i + 1 > t2 = datetime.datetime.now() > print t2 - t1 > for i in [str(x) for x in range(100)]: > try: > int(i) +1 > except: > pass > t3 = datetime.datetime.now() > print t3 - t2 This is not a proper test since the if condition always fails and the addition not done while the try succeeds and the addition is done. To be equivalent, remove the int call in the try part: try: i+1. This would still not a proper test since catching exceptions is known to be expensive and try: except is meant for catching *exceptional* conditions, not always-bad conditions. Here is a test that I think more useful: for n in [1,2,3,4,5,10,20,50,100]: # time this for i in range(n): if i != 0: x = 1/i else: pass # versus for i in range(n): try x = 1/i except ZeroDivisionError: pass I expect this will show if faster for small n and try for large n. Terry J. Reedy From alex_brollo at yahoo.it Thu Jul 7 03:24:11 2005 From: alex_brollo at yahoo.it (Alessandro Brollo) Date: Thu, 7 Jul 2005 09:24:11 +0200 (CEST) Subject: Do a "Python beginners e-mail list" exist? Message-ID: <20050707072411.75921.qmail@web26707.mail.ukl.yahoo.com> Far from a professional programmer, I'm simply a newbie Python user. Two basic questions: 1. I don't want to post banal questions about Python to main Python list. Does a "banal Python questions list" or a "Python beginners list" exist? 2. There is somewhere a very patient fellow willing to be my free "python tutor" by personal e-mailing outside the mail list? . The ideal candidate would be someone, sharing with me some other fields of interest (I'm a middle-aged Italian pathologist, with some dBase III and dBase IV past programming experience, and I like nature and mainly horses). Thanks Alessandro Brollo ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From peter at engcorp.com Mon Jul 25 13:50:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 13:50:29 -0400 Subject: GPRS Connection name on Python s60 In-Reply-To: <1122310992.858311.26080@o13g2000cwo.googlegroups.com> References: <1122294420.896414.152630@f14g2000cwb.googlegroups.com> <1122310992.858311.26080@o13g2000cwo.googlegroups.com> Message-ID: xen0n at vodafone.it wrote: > Yeah i have already asked it, but, i think i can set before the > .connect method, a connection as default, and, when connected, resore > default connection! Well, more power to you. I'll simply note again that this is a non-standard thing, and not directly supported by Python, so if it's possible it is going to be found in the docs or the mailing list for the Series 60, not (unless you strike it lucky) in comp.lang.python. -Peter From gene.tani at gmail.com Thu Jul 28 23:06:27 2005 From: gene.tani at gmail.com (gene tani) Date: 28 Jul 2005 20:06:27 -0700 Subject: monitor a folder for file creation, how? In-Reply-To: <86ack6l4vm.fsf@bhuda.mired.org> References: <86ack6l4vm.fsf@bhuda.mired.org> Message-ID: <1122606386.971460.250100@g14g2000cwa.googlegroups.com> win32: (I posted this link in response to same question, um, day bef. yesterday) http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/9a1c7629db72d064/56008cb68eeffa23?hl=en#56008cb68eeffa23 (Thanks to Tim Golden for collecting the info) OS X: I dunno... From thomasbartkus at comcast.net Fri Jul 1 11:59:01 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 1 Jul 2005 10:59:01 -0500 Subject: I am a Java Programmer References: <1120198963.819222.76750@g47g2000cwa.googlegroups.com> Message-ID: <6eKdnasKdIMi-ljfRVn-jw@telcove.net> wrote in message news:1120198963.819222.76750 at g47g2000cwa.googlegroups.com... > I am a java programmer and I want to learn Python Please help me. > Well! Your condition is certainly tragic! But what can anyone do? Thomas Bartkus From jcribbs at twmi.rr.com Thu Jul 14 19:22:37 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Thu, 14 Jul 2005 19:22:37 -0400 Subject: ANN: KirbyBase 2.0 beta 1 Message-ID: <42D6F3BD.3000603@twmi.rr.com> I would like to announce the first beta of version 2 of KirbyBase, a simple, pure-Python database management system that stores it's data in plain-text files. Version 2 is a total rewrite of the code, a major change in the api, and a major improvement (I hope) in the syntax used to express queries, inserts, and updates. Because of the dramatic changes, I wanted to get this beta out in the hopes that I can get some early feedback on the new api and syntax, before releasing version 2. You can download the beta from here: http://www.netpromi.com/files/KirbyBase_Python_2.0_beta_1.zip Included in the zip file is a script, kbtest.py that has numerous examples of the new syntax. I'll try to give you a small flavor of it here: To specify a select query in the old version of KirbyBase you would do something like this: db.select('plane.tbl', ['country', 'speed'], ['USA', '> 300']) which says, "Select all planes from the US with a speed greater than 300mph. In the new version of KirbyBase you could state the query using named arguments: plane_tbl.select(country='USA', speed='> 300') or, using a dictionary: plane_tbl.select({'country': 'USA', 'speed': '> 300'}) or, you could even use a lambda, like this: plane_tbl.select(lambda r: r.country == 'USA' and r.speed > 300) I personally prefer the latter, but I realize that lambda's are quite controversial just now, so I offer alternative ways to specify select criteria. One of the cool things about using lambdas is that it gives you more power in your selects, like being able to use regular expressions and being able to use "or" logic. Anyway, this is just a small taste of the changes. The changes actually go much deeper and, I think, make the resulting api much more "Pythonic". About the only thing that hasn't changed is the table structure in the physical file (well, there is one small change, but it is easily made). It is currently a good bit slower than the current version of KirbyBase; I will work on optimizing it after the api is frozen. For those of you who have used the Ruby version of KirbyBase, this new Python version closely resembles that, while trying to be as Python-like as possible. There is no manual yet, but I think you can get a good feel for the differences by looking at kbtest.py. I would be very interested in any feedback you can give me on the new version. Jamey Cribbs jcribbs at twmi.rr.com From steve at REMOVEMEcyber.com.au Sun Jul 3 23:29:36 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 04 Jul 2005 13:29:36 +1000 Subject: math.nroot [was Re: A brief question.] References: <1120432250.340056.237460@g44g2000cwa.googlegroups.com> Message-ID: <42C8AD20.30004@REMOVEMEcyber.com.au> George Sakkis wrote: > "Tom Anderson" wrote: > > >>>But NaNs are _not_ things. >> >>I disagree. A NaN _is_ a thing; it's not a floating-point number, for >>sure, but it is a symbol which means "there is no answer", or "i don't >>know", and as such, it should follow the universal rules which apply to >>all things. > > > It seems that the standard semantics of NaN is closer to NULL values in > ANSI SQL, that is "unknown", "not available". In this sense, if you > have two 'things' you don't know, you can't say they are equal simply > because you don't know them ! It isn't that they are unknown. They don't exist, so you can't compare them! The bit-patterns that represent NaNs should not be thought of as "the answer to the calculation", but merely "a flag representing the fact that an error occurred". The nice thing is that the flag can propogate through your calculations, so you can defer testing for an error condition until the very end, but it is not a value. When you think of NaNs as flags, the question of equality doesn't apply. You can compare two flags bit by bit to see if they have the same bit pattern, and that's what the isNan() function is for: test if a float has a bit pattern that represents a NaN. But it doesn't make sense to say that two flags are equal: keep_processing = True more_reading_needed = True while more_reading_needed and keep_processing: get_more_records() process_records() if not keep_processing: print "User clicked Cancel" What does it mean to say that the flag done_processing is equal to the flag more_reading_needed? (That is not the same question as asking if the two flags have the same value.) >>>Since INF-INF doesn't have an answer, we can't do this: >>> >>>x = inf - inf >>>y = inf - inf >>> >>>and expect that x == y. >> >>I think we can. Both x and y have the same value, a value of >>indeterminacy. NaN is a rigidly defined value of doubt and uncertainty! > > > In this case, however, I would agree. x and y above are not assigned a > label of 'unknown'; they are derived from an operation among valid > *known* values, so NaN here means 'invalid' rather than 'unknown'.It > makes sense to have x==y, because x and y are the outcome of the *same* > invalid operation. This is incorrect. Mathematically, you CAN'T say: x = INF - INF y = INF - INF therefore x = y. This is just _wrong_. Mathematically, x and y don't exist, so they can't be equal since equality is only defined for things which exist. It gets worse. Consider this example of "logic": x = log(-5) # a NaN y = log(-2) # the same NaN x == y # you want this to be true for NaNs Then: # compare x and y directly log(-5) == log(-2) # if x == y then exp(x) == exp(y) for all x, y exp(log(-5)) == exp(log(-2)) -5 == -2 > Similarly, if z=0/0, z would also be invalid, but > different from x and y, since it is the result of a different invalid > operation. This brings us to the many-NaN situation. The problem is, the many NaNs in the IEEE standard (or at least Apple's implementation of it) refer to _kinds_ of NaNs, not NaNs themselves. log(-2) is not the same "not a number" as log(-2.0001), or log(-2.3). They might be the same "kind" of failure, but that's it. You can't even say that log(-2) == log(-2), because equality is only defined for numbers, not "no such thing". Having given reasons why it is utterly bogus to be comparing NaNs for equality, I will say this. Practicality beats purity. If you can demonstrate a good usage case for testing equality with NaNs, I will accept that it is a good thing to do. if x in (SOME_NAN, SOME_OTHER_NAN, ANOTHER_NAN, \ YET_ANOTHER_NAN, AND_ANOTHER_NAN, ..., \ # 240+ more NaNs listed ALMOST_FINISHED_NOW, LAST_NAN): print "Calculation failed!" is _not_ a good usage case, since it is best handled with: if isNan(x): # handled by the floating point package print "Calculation failed!" -- Steven. From rrr at ronadam.com Tue Jul 5 17:39:45 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 05 Jul 2005 21:39:45 GMT Subject: flatten(), [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: > The trouble with these is that they make a lot of temporary lists - > George's version does it with the recursive calls to flatten, and Ron's > with the slicing and concatenating. How about a version which never > makes new lists, only appends the base list? We can use recursion to > root through the lists ... Ok... How about a non-recursive flatten in place? ;-) def flatten(seq): i = 0 while i!=len(seq): while isinstance(seq[i],list): seq.__setslice__(i,i+1,seq[i]) i+=1 return seq seq = [[1,2],[3],[],[4,[5,6]]] print flatten(seq) I think I'll be using the __setslice__ method more often. And the test: #-------------------------------- # Georges recursive flatten init_a = """ def flatten(seq): return reduce(_accum, seq, []) def _accum(seq, x): if isinstance(x,list): seq.extend(flatten(x)) else: seq.append(x) return seq seq = [[1,2],[3],[],[4,[5,6]]] """ # Ron's non-recursive init_b = """ def flatten(seq): s = [] while seq: while isinstance(seq[0],list): seq = seq[0]+seq[1:] s.append(seq.pop(0)) return s seq = [[1,2],[3],[],[4,[5,6]]] """ # Tom's recursive, no list copies made init_c = """ def isiterable(x): return hasattr(x, "__iter__") # close enough for government work def visit(fn, x): # perhaps better called applytoall if (isiterable(x)): for y in x: visit(fn, y) else: fn(x) def flatten(seq): a = [] def appendtoa(x): a.append(x) visit(appendtoa, seq) return a seq = [[1,2],[3],[],[4,[5,6]]] """ # Devan' smallest recursive init_d = """ def flatten(iterable): if not hasattr(iterable, '__iter__'): return [iterable] return sum([flatten(element) for element in iterable],[]) seq = [[1,2],[3],[],[4,[5,6]]] """ # Ron's non-recursive flatten in place! Much faster too! init_e = """ def flatten(seq): i = 0 while i!=len(seq): while isinstance(seq[i],list): seq.__setslice__(i,i+1,seq[i]) i+=1 return seq seq = [[1,2],[3],[],[4,[5,6]]] """ import timeit t = timeit.Timer("flatten(seq)",init_a) print 'recursive flatten:',t.timeit() import timeit t = timeit.Timer("flatten(seq)",init_b) print 'flatten in place-non recursive:',t.timeit() import timeit t = timeit.Timer("flatten(seq)",init_c) print 'recursive-no copies:',t.timeit() import timeit t = timeit.Timer("flatten(seq)",init_d) print 'smallest recursive:',t.timeit() import timeit t = timeit.Timer("flatten(seq)",init_e) print 'non-recursive flatten in place without copies:',t.timeit() #-------------------------------------------- The results on Python 2.3.5: (maybe someone can try it on 2.4) recursive flatten: 23.6332723852 flatten in place-non recursive: 22.1817641628 recursive-no copies: 30.909762833 smallest recursive: 35.2678756658 non-recursive flatten in place without copies: 7.8551944451 A 300% improvement!!! This shows the value of avoiding copies, recursion, and extra function calls. Cheers, Ron Adam From exarkun at divmod.com Thu Jul 14 09:29:59 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 14 Jul 2005 09:29:59 -0400 Subject: threads and sleep? In-Reply-To: <7xll49si4h.fsf@ruckus.brouhaha.com> Message-ID: <20050714132959.26278.1728311907.divmod.quotient.11646@ohm> On 14 Jul 2005 05:10:38 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >Andreas Kostyrka writes: >> Basically the current state of art in "threading" programming doesn't >> include a safe model. General threading programming is unsafe at the >> moment, and there's nothing to do about that. It requires the developer >> to carefully add any needed locking by hand. > >So how does Java do it? Declaring some objects and functions to be >synchronized seems to be enough, I thought. Multithreaded Java programs have thread-related bugs in them too. So it doesn't seem to be enough. Like Python's model, Java's is mostly about ensuring internal interpreter state doesn't get horribly corrupted. It doesn't do anything for application-level state. For example, the following (Python, because it's way too early to write Java, but a straight port to Java would be broken in exactly the same way) program is not threadsafe: things = [] def twiddle(thing): if thing in things: print 'got one' things.remove(thing) else: print 'missing one' things.append(thing) The global list will never become corrupted. stdout will always be fine (although perhaps a little weird). The objects being appended to and removed from the list are perfectly safe. But the program will double append items to the list sometimes, and raise ValueErrors from the list.remove() call sometimes. Java's model isn't really too far from the traditional one. It's a tiny bit safer, perhaps, but that's all. For something different, take a look at Erlang's mechanism (this has been ported to Python, although I have heard nothing of the result since its release announcement, I wonder how it's doing?) Hope this helps, Jp From stian at soiland.no Wed Jul 6 15:43:02 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 6 Jul 2005 21:43:02 +0200 Subject: flatten(), [was Re: map/filter/reduce/lambda opinions ...] In-Reply-To: References: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: <20050706194302.GY12095@itea.ntnu.no> On 2005-07-06 00:50:30, Ron Adam wrote: > This is probably the more correct way to do it. :-) > > def flatten(seq): > i = 0 > while i!=len(seq): > while isinstance(seq[i],list): > seq[i:i+1]=seq[i] > i+=1 > return seq Or what about a recursive generator? a = [1,2,[[3,4],5,6],7,8,[9],[],] def flatten(item): try: iterable = iter(item) except TypeError: yield item # inner/final clause else: for elem in iterable: # yield_return flatten(elem) for x in flatten(elem): yield x print list(flatten(a)) Of course, one of the problems here is that there is no way to yield_return except to create yet another stupid-looking for-loop. This is one of the flaws in the current generator functionallity of Python. Using yield_return could also make it more obvious that the result is in fact a generator in functions that wrap generators. -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] From nlebas at grignon.inra.fr Tue Jul 26 08:21:20 2005 From: nlebas at grignon.inra.fr (Nicolas Lebas) Date: Tue, 26 Jul 2005 14:21:20 +0200 Subject: getting Arrays and variables from R Message-ID: <42E62AC0.9050201@grignon.inra.fr> hello, i don't know if this is the best list to send this question, but i'm already trying to ask. I need to import variables from .RData files (arrays or variables). I'm trying to use the rpy module, but without success beccause when i try to access to a variable loaded from the .RData file i have a segmentation fault ! This is what i'm doing : - in R-projet, i create a .RData file with some variables : > tab<-c(2,5,8,6) > v<-0.5 > save.image("file.RData") - in Python : > from rpy import * > r.load("file.RData") ['tab', '.Traceback', 'v'] > r.tab segmentation fault ! I don't understand very well what does python crash. If someone has an idea to solve my problem or to give me a method which permit to import arrays and variables from .RData files with another module. Thanks Nicolas From andre.roberge at gmail.com Tue Jul 19 11:58:49 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Tue, 19 Jul 2005 12:58:49 -0300 Subject: print ending with comma In-Reply-To: <1121787376.815068.145060@g49g2000cwa.googlegroups.com> References: <1121787376.815068.145060@g49g2000cwa.googlegroups.com> Message-ID: jamesthiele.usenet at gmail.com wrote: [snip] > > A "\n" character is written at the end, unless the print statement ends > with a comma. > > What it doesn't say is that if the print statement does end with a > comma, a trailing space is printed. > -- > But this isn't exactly correct either. If you run this program: > import sys > print '+', > print '-', > sys.stdout.write('=') > print > -- > the output is: > + -= [snip] > I know that this is not a massively important issue, but can someone > explain what's going on? > Actually, it is not a trailing space but a leading space that is stored and displayed when print is called next. >>> import sys >>> print 'a', a >>> print 'b', b >>> --- sys.stdout.write() does not include such a leading space. Time to consult python.org about the print statement.: [http://www.python.org/doc/2.0.1/ref/print.html] ...A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line... Yep, another case of RTM :-) Andr? From gsakkis at rutgers.edu Thu Jul 14 08:21:56 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 14 Jul 2005 08:21:56 -0400 Subject: Consecutive Character Sequences References: <1121318559.d582247e6e25443e247191d29f60b3b0@teranews> <1121325469.494500.291730@z14g2000cwz.googlegroups.com> Message-ID: <1121343722.7ebce1b2a41714687db3ed336af5fc19@teranews> "Aries Sun" wrote: > I have tested George's solutions, it seems not complete. When pass (s, > 3) to the function hasConsequent(), it returns the wrong result. What are you talking about ? I get the correct answer for >>> hasConsequent("taaypiqee88adbbba", 3) True George From evenes at verizon.net Sun Jul 10 06:56:19 2005 From: evenes at verizon.net (El) Date: Sun, 10 Jul 2005 10:56:19 GMT Subject: Newbie Alert! Upgrading Python? Message-ID: Hi, Sorry to bother you folks with a real newbie question, but I am sure that this is the place for me to ask. Python 1.5.1 (final) and Python Win32 Extensions are installed on my 4 year old computer. My computer has always been upgraded to include the latest programs and Windows updates. However, I have NEVER upgraded Python? Therefore, my questions: 1. Should I upgrade to the new Python 2.4.1 (Final)? 2. If so, should I uninstall the old version first and reboot, or can I just install the new version over the old version? 3. Are the Win32 extensions included in the final version, or are the extensions a separate download? I do not use Python, but I am assuming that something on my computer must. LOL. Thank you for any enlightenment you can render. Elliot From jan.danielsson at gmail.com Sat Jul 30 19:44:22 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Sun, 31 Jul 2005 01:44:22 +0200 Subject: Escaping certain characters Message-ID: <42ec0f65$1@griseus.its.uu.se> Hello, I'd like to encode the string that outputs: Hello World! to 'Hello\x0aWorld!', and the string that outputs: Hello\World! to 'Hello\\World!'. Obviously, I want to be able to reverse the process. I'm going to assume this has already been solved in Python.. But how? From max at alcyone.com Thu Jul 14 17:13:17 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 14 Jul 2005 14:13:17 -0700 Subject: all possible combinations In-Reply-To: References: Message-ID: William Park wrote: > Since you're doing cross product (ie. 3*3*3*3), manual loop of 4 level > deep would be the fastest in terms of algorithm. That's a Cartesian product, actually :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis All generalizations are dangerous, even this one. -- Dumas Fils From pietro.campesato at gmail.com Sat Jul 23 13:24:02 2005 From: pietro.campesato at gmail.com (Pietro Campesato) Date: 23 Jul 2005 10:24:02 -0700 Subject: Friend wants to learn python In-Reply-To: <1122135598.347717.75830@g43g2000cwa.googlegroups.com> References: <1122135598.347717.75830@g43g2000cwa.googlegroups.com> Message-ID: <1122139442.705347.237010@o13g2000cwo.googlegroups.com> Maybe diveintopython.org can help From apoco at cox.net Tue Jul 26 10:47:38 2005 From: apoco at cox.net (Jacob Page) Date: Tue, 26 Jul 2005 07:47:38 -0700 Subject: Compiling a Python File on Mac OS X Tiger In-Reply-To: References: Message-ID: Asad Habib wrote: > Hello. I am working on Tiger and wanted to find out how to compile a > Python (.py) file into a .pyc file and then into a .pyo file. Can the > compilation be achieved within the interpreter? Also, I am > new to Python and wanted to know the difference between .pyc and .pyo > files. Is this comparison similar to C? Any help would be appreciated. > Thanks. http://www.network-theory.co.uk/docs/pytut/tut_48.html has some good explanations. To generate the .pyo files from the interpreter, add the -O option. The difference between .pyc and .pyo files is that .pyo files are optimized a bit; for example docstrings are removed (which will break pydoc tests). According to the above link, .pyo files don't run any faster; they just load faster. From go2len at TRALALALAhotmail.com Tue Jul 5 14:38:22 2005 From: go2len at TRALALALAhotmail.com (Lennart) Date: Tue, 5 Jul 2005 20:38:22 +0200 Subject: Good starterbook for learning Python? References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: With Dive Into Python in an other language i can learn python & the russian language :-) Thanks anyway Now i can learn python Op Tue, 05 Jul 2005 16:43:03 +0100 schreef TechBookReport: > Lennart wrote: >> Hi everybody, >> >> Can someone advice me with the following issue: i want to learn python in >> my summer vacation (i try to ...:-) So, a good start is buying a good book. >> But wich? There are many ... >> >> I'm living in the Netherlands and I prefer a book from bol.com (see link) >> because i've to order more books by them. I'm familiar with html & php and >> basic (in the good old days). It has to be a newbie book, but not a book >> what i don't need anymore when i've got some skills. I.e. the learning >> curve of the book should be linear. A kind of book wich i could use as a >> novice. >> >> Search here for python (sorry, there's no short link) >> http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_BrowseCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&CategoryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb&CategoryLeftpanel=BOOK_EN%2eCATEGORY00000000&Secondary=YES&Template=BOL_subcat_BOOK_EN_1476 > > Two excellent books match your criteria: > > Dive Into Python (review: http://www.techbookreport.com/tbr0103.html) - > also available as a free download. > > Learning Python (review: http://www.techbookreport.com/tbr0064.html) > > Both are recommended for beginners but have a reasonable level of depth. > They're clear, enthusiastic and well-written. > > HTH From 00515879256 at fastwebnet.it Mon Jul 18 06:17:37 2005 From: 00515879256 at fastwebnet.it (Glauco) Date: Mon, 18 Jul 2005 12:17:37 +0200 Subject: Dictionary, keys and alias In-Reply-To: References: <42D780EF.6020809@sweetapp.com> <20050717210438.GA17650@gate2.hazen.net> Message-ID: <5mLCe.24301$b93.15018@tornado.fastwebnet.it> I want to insert a concept of alias in a dict_based class. The idea is to have a facoltative name in the same dict that correspond at the same value. With this alias i can change original value. example: mydict['a'] = 1 I must define an alias example: myFunctAlias( mydict, 'a', 'b') print mydict {'a':1, 'b':1} mydict['b'] = 2 print mydict {'a':2, 'b':2} The only idea i have is to implement two dictionary one for convert name, alias in two keys with the same value (eg.numeric) in the first dict. The second for store only one time the k, v . Any suggestion ? Glauco -- \\\|/// \\ - - // ( @ @ ) +---------------------oOOo-( )-oOOo--------------------------+ | | | I have a dream that one day this nation will rise up and | | live out the true meaning of its creed: "We hold these | | truths to be self-evident:that all men are created equal.| | I have a dream that one day on the red hills of Georgia | | the sons of former slaves and the sons of former | | slaveowners will be able to sit down together at a table | | of brotherhood. | | I have a dream that one day even the state of Mississippi, | | a desert state, sweltering with the heat of injustice | | and oppression, will be transformed into an oasis of | | freedom and justice. | | I have a dream that my four children will one day live in | | a nation where they will not be judged by the color of | | their skin but by the content of their character. | | I have a dream today. | | | | Martin Luther King, Jr 28 Ago 1963 | +------------------------------------------------------------+ | glauco(at)uriland.it | | www.uriland.it .oooO ICQ: 115323690 | +--------------------- ( )------ Oooo.---------------------+ \ ( ( ) \_) ) / (_/ From jepler at unpythonic.net Fri Jul 22 15:38:50 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 22 Jul 2005 14:38:50 -0500 Subject: Question about namespaces and import. How to avoid calling os.system In-Reply-To: <42e14753$0$27392$39db0f71@news.song.fi> References: <42e14753$0$27392$39db0f71@news.song.fi> Message-ID: <20050722193849.GD25836@unpythonic.net> In main.py, execfile("gen.py") or In gen.py, have something like from __main__ import env_params or In main.py, have something like import __builtins__; __builtins__.env_params = env_params or call a function in the gen.py with env_params as a parameter import gen gen.do(env_params) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fabioz at esss.com.br Tue Jul 26 09:56:58 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Tue, 26 Jul 2005 10:56:58 -0300 Subject: ANN: PyDev 0.9.7 released In-Reply-To: <42C175A5.5000206@esss.com.br> References: <42A720BD.5050701@esss.com.br> <42C175A5.5000206@esss.com.br> Message-ID: <42E6412A.4020905@esss.com.br> Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.7 has just been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Release Highlights: This build fixes some nasty bugs from 0.9.6... it is highly recommended you install it. (right now, everything but the debugger should work fine with 3.1). Important notes Note 1: Because of some issues with Eclipse, you have to uninstall all previous PyDev installations before installing the new release. Note 2: This release only works with Eclipse 3.1 (and from now on, Eclipse 3.0.x is no longer supported). Note 3: Java 5.0 is required from now on. Regards, Fabio -- 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 From bektek at gmail.com Sun Jul 17 04:30:35 2005 From: bektek at gmail.com (kimes) Date: 17 Jul 2005 01:30:35 -0700 Subject: I just wanna know about os.path module.. Message-ID: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> I've just started digging into how python works.. I found that other mudules are clearly declared like one file per a module.. But the only os.path doesn't have their own file.. ye I know is has actually depending on os like in my case posixpath.. What I'd love to know is.. when I call import os.path.. how happened under the hood? I'm currently using python 2.4 in linux machine.. I'd appreciate it From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 08:55:19 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 14:55:19 +0200 Subject: A replacement for lambda In-Reply-To: References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> Message-ID: <3l1blnF10c1i9U1@individual.net> Stefan Rank wrote: > on 30.07.2005 10:20 Paolino said the following: >> why (x**2 with(x))<(x**3 with(x)) is not taken in consideration? >> >> If 'with' must be there (and substitue 'lambda:') then at least the >> syntax is clear.IMO Ruby syntax is also clear. >> > > I am sorry if this has already been proposed (I am sure it has). > > Why not substitue python-lambdas with degenerated generator expressions:: > > (lambda x: func(x)) == (func(x) for x) > > i.e. a one time callable generator expression (missing the `in` part). > The arguments get passed into the generator, I am sure that can be > combined with the PEP about passing args and Exceptions into a generator. It's hard to spot, and it's too different to a genexp to have such a similar syntax. Reinhold From flupke at nonexistingdomain.com Wed Jul 20 02:53:10 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 20 Jul 2005 06:53:10 GMT Subject: OO design In-Reply-To: References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: Robert Kern wrote: > chris wrote: > >> When I think about what I should do I end up with a class XY that has a >> method for everything I want to do eg. >> >> class XY: >> def read_file >> def scale_data >> def plot_data >> def shelve_data >> >> But somehow that doesn't feel right, especially when I expect the >> number of >> methods will grow and grow, which would make the class very unwieldy. > In short slogans: Just Do It. Make It Work, Then Make It Right. Refactor > Mercilessly. Do the Simplest Thing That Could Possibly Work. +1 QOTW Very good advice IMO. I would like to add that for the simpler classes, thinking of how you want to use data can be a great starting point. I recently programmed an interface to a firebird database and said, how do i want to be able to use the software? I thought of this: table = fb.Table("datafile.fdb","customers") vals = {} vals["name"]="customer1" vals["city"]="mytown" table.insert(vals) It looked like a great way to access and use it and it hides all the sql details. Well, that's how i started and i had to refactor along the way too :) Regards, Benedict From ujelin at yahoo.com Wed Jul 27 11:38:27 2005 From: ujelin at yahoo.com (ulrice jardin) Date: Wed, 27 Jul 2005 08:38:27 -0700 (PDT) Subject: html special characters to latin-1 conversion In-Reply-To: <1122052849.701784.44830@g44g2000cwa.googlegroups.com> Message-ID: <20050727153827.24195.qmail@web60321.mail.yahoo.com> hi I had a look to this htmlentitydefs lib, but I still don't know how to convert html special characters into latin-1 characters. For instance, how can I convert ' into ' or é and é into ?? Is there any function to do that? thx for any help Jul __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jan.danielsson at gmail.com Mon Jul 25 12:50:44 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Mon, 25 Jul 2005 18:50:44 +0200 Subject: First app, thanks people In-Reply-To: <42e510ab$0$31229$db0fefd9@news.zen.co.uk> References: <42e4eff3$1@griseus.its.uu.se> <42e510ab$0$31229$db0fefd9@news.zen.co.uk> Message-ID: <42e516f5$1@griseus.its.uu.se> Will McGugan wrote: [---] > You should use the keycode constants. > > http://www.wxwidgets.org/manuals/2.6.1/wx_keycodes.html#keycodes [---] Excellent! Thanks! From invalidemail at aerojockey.com Sun Jul 3 16:55:07 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 3 Jul 2005 13:55:07 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <42c7f923$1@nntp0.pdx.net> Message-ID: <1120424107.153904.238480@f14g2000cwb.googlegroups.com> Steven D'Aprano wrote: > On Sun, 03 Jul 2005 08:14:28 -0700, Scott David Daniels wrote: > > > egbert wrote: > >> On Sat, Jul 02, 2005 at 08:26:31PM -0700, Devan L wrote: > >> > >>>Also, map is easily replaced. > >>>map(f1, sequence) == [f1(element) for element in sequence] > >> > >> How do you replace > >> map(f1,sequence1, sequence2) > >> especially if the sequences are of unequal length ? > >> > >> I didn't see it mentioned yet as a candidate for limbo, > >> but the same question goes for: > >> zip(sequence1,sequence2) > > > > OK, you guys are picking on what reduce "cannot" do. > > The first is [f1(*args) for args in itertools.izip(iter1, iter2)] > > And now we get messier and messier... Compare these two idioms: > > "Map function f1 to each pair of items from seq1 and seq2." > > "Build a list comprehension by calling function f1 with the unpacked list > that you get from a list built by zipping seq1 and seq2 together in pairs." The shamelessness with which you inflated the verbosity of the latter is hilarious. > Good thing that removing reduce is supposed to make code easier to > understand, right? It was a bad example. I would say most people don't usually just call a function in the list comp, because, frankly, they don't have to. A realistic list comp would look something like this in a real program: [ x**2 + y**2 for (x,y) in izip(xlist,ylist) ] Now there's no longer much advantage in conciseness for the map version (seeing that you'd have to define a function to pass to map), and this is more readable. -- CARL BANKS From qwweeeit at yahoo.it Sun Jul 24 08:25:36 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 24 Jul 2005 05:25:36 -0700 Subject: Initializing interactive Python In-Reply-To: <42e374c5$0$15019$626a14ce@news.free.fr> References: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> <42e374c5$0$15019$626a14ce@news.free.fr> Message-ID: <1122207936.677145.274040@o13g2000cwo.googlegroups.com> Hi Bruno, thank you..."Easy as pie !-)" Bye. From tuxlover at gmail.com Tue Jul 12 14:01:43 2005 From: tuxlover at gmail.com (tuxlover) Date: 12 Jul 2005 11:01:43 -0700 Subject: python parser Message-ID: <1121191303.361588.37860@o13g2000cwo.googlegroups.com> Hello everyone I have to write a verilog parser in python for a class project. I was wondering if all you folks could advise me on choosing the right python parser module. I am not comfortable with lex/yacc and as a result find myself strugging with any module which use lex/yacc syntax/philosophy. pyparser looks good to me, but before I dive into it, I would really appreciate feedback from members of this group Thanks Tuxlover From could.net at gmail.com Sat Jul 2 04:31:22 2005 From: could.net at gmail.com (could ildg) Date: Sat, 2 Jul 2005 16:31:22 +0800 Subject: It seems that ZipFile().write() can only write files, how can empty directories be put into it? In-Reply-To: <20050701140644.GD7252@unpythonic.net> References: <311b5ce10506301850643872d6@mail.gmail.com> <20050701140644.GD7252@unpythonic.net> Message-ID: <311b5ce10507020131121d63d@mail.gmail.com> Thank you. On 7/1/05, Jeff Epler wrote: > This has been discussed before. One thread I found was > http://mail.python.org/pipermail/python-list/2003-June/170526.html > The advice in that message might work for you. > > Jeff > > > From roccomoretti at hotpop.com Tue Jul 19 09:40:59 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 19 Jul 2005 08:40:59 -0500 Subject: Documentation bug: Python console behaviour changed In-Reply-To: References: Message-ID: Tim Golden wrote: > Usually means you have a readline package installed: Should the readline package be twiddled to change the "quit" string in builtins to document the correct behavior? From lambacck at computer.org Fri Jul 15 18:08:35 2005 From: lambacck at computer.org (Chris Lambacher) Date: Fri, 15 Jul 2005 18:08:35 -0400 Subject: win32ui CreatePrintDialog Message-ID: <20050715220835.GA16901@computer.org> Hi, This question has come up a few times on the list with no one giving a public answer. How do you use CreatePrintDialog from win32ui? About a year ago someone posted that: dlg = win32ui.CreatePrintDialog(1538) dlg.DoModal() will give you the window, but the ok button does not work. Diging into the source shows that the 1538 is being loaded as a template resource. The MSDN documentation does not say anything about this being neccessary and in fact, other common dialogs provide this as an option, but not a requirement. Why is this made a requirement? If it was not made a requirement, would the dialog work? Unfortunately I can't play with this because I don't have Visual Studio. I guess the logical next step, if the above worked, would be to add the GetPrinterDC() method (and maybe some others) so that we can do something useful with the dialog. Thanks, Chris From noreply at python.org Tue Jul 26 03:07:55 2005 From: noreply at python.org (Returned mail) Date: Tue, 26 Jul 2005 10:07:55 +0300 Subject: Message could not be delivered Message-ID: <20050726070835.0840E1E4004@bag.python.org> Dear user of python.org, administration of python.org would like to let you know that. We have detected that your e-mail account has been used to send a huge amount of junk e-mail messages during the last week. Probably, your computer had been infected and now runs a trojaned proxy server. Please follow instructions in order to keep your computer safe. Sincerely yours, The python.org team. From gsakkis at rutgers.edu Thu Jul 7 20:31:52 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Jul 2005 17:31:52 -0700 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> <11cp7fusjoid468@corp.supernews.com> <1120706984.868966.266710@g14g2000cwa.googlegroups.com> <11cpce8shb7si77@corp.supernews.com> Message-ID: <1120782711.956892.302970@g44g2000cwa.googlegroups.com> "Grant Edwards" wrote: > On 2005-07-07, George Sakkis wrote: > > > I guess he means why not define foo as property: > > > > class demo(object): > > foo = property(fget = lambda self: self.v, > > fset = lambda self,v: setattr(self,'v',v)) > > > > d = demo() > > d.foo = 3 > > print d.foo > > In some ways that's even cleaner. > > In my simplivied example all the foo() method was doing was > setting/returning an attribute, but usually there's a bit more > going on (e.g. system calls with possible side effects). > > To me it's a bit more explicit that > > d.foo(3) > d.foo() > > are doing something other than just getting/setting the value > of an instance attribute. If all I really wanted to do was > get/set the instance's "v" attribute, I probably would have > just done it like this > > d.v = 3 > print d.v The main reason for bringing properties into the language was exactly to *hide* the fact that something else might be going one behind the scenes. Ideally, the user of the class shouldn't care [1] whether getting an attribute returns a stored value in the instance's __dict__, computes it on the fly, fetches it from a cache or a database, etc, and similarly for setting the attribute. George [1] OTOH the user should probably be aware if a specific property (or any callable for that matter) implies significant performance (or other) costs. From spike.666 at gmail.com Sun Jul 31 19:19:25 2005 From: spike.666 at gmail.com (spike) Date: 31 Jul 2005 16:19:25 -0700 Subject: subclassing list Message-ID: <1122851965.569213.312430@g14g2000cwa.googlegroups.com> I've googled like crazy and can't seem to find an answer to why this isn't working. I want to create a custom list class that acts as a circular list. ie: my_list = (0, 1, 2) how I want it to behave: my_list[0] -> 0 my_list[1] -> 1 my_list[2] -> 2 my_list[3] -> 0 my_list[4] -> 1 ...etc so, what I've tried to do is: def circular_list(list): def __getitem__(self, i): if (i >= len(self)): return self[i % len(self)] else: return self[i] items = circular_list(range(8)) however, when I want to iterate over it with a for statement, I get: TypeError: iteration over non-sequence what am I missing? thanks! From gsakkis at rutgers.edu Mon Jul 18 18:34:40 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 18 Jul 2005 18:34:40 -0400 Subject: Python to C++ translation? References: <1121722762.525859.255890@g49g2000cwa.googlegroups.com> Message-ID: <1121726085.944c181e8eb6d25c94542122c9590a00@teranews> "Mangabasi" wrote: > Hi there, > > I need to translate the following code (rather something similar) to > C++. I have been studying C++ for the last two days but I could not > find an easy way to do the following Python snippet. > > > class A: > def __init__(self, x): > self.x = x > def methodA(): > pass # Ignore the details > class B: > def __init__(self, x): > self.x = x > def methodB(): > def methodB(): > pass # Ignore the details > class C: > def __init__(self, A, B): > self.A = A > self.B = B > > a = A(5) > b = B(5.5) > c = C(a, b) > print c.A.x > print c.B.x > #so far I can do it in C++ > #how do I do the following in C++? > d = C(b, a) > print d.A.x > print d.B.x In python this works thanks to "duck typing"; as long as both A and B instances have an attribute 'x', A.x and B.x work as expected without the need for type declarations. In C++ (and other statically typed languages) there is no duck typing, so you can't translate it from python verbatim. The typical (if not only) way to achieve the same in C++ is to have A and B inherit from a common parent class, say X, and drag the common interface and implementation of A and B to X. Of course you could (or perhaps should) do the same in python: class X: def __init__(self, x): self.x = x class A(X): def methodA(): pass # Ignore the details class B(X): def methodB(): pass # Ignore the details class C: def __init__(self, x1, x2): self.x1 = x1 self.x2 = x2 So the constructor of C would take two X instances, and the respective attributes x1 and x2 would be declared as pointers to X. HTH George From rkern at ucsd.edu Wed Jul 13 09:34:35 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 13 Jul 2005 06:34:35 -0700 Subject: Splitting on a word In-Reply-To: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> References: <1121260794.202384.50880@f14g2000cwb.googlegroups.com> Message-ID: qwweeeit at yahoo.it wrote: > Hi all, > I am writing a script to visualize (and print) > the web references hidden in the html files as: > ' underlined reference' > Optimizing my code, I found that an essential step is: > splitting on a word (in this case 'href'). > > I am asking if there is some alternative (more pythonic...): For *this* particular task, certainly. It begins with import BeautifulSoup The rest is left as a (brief) exercise for the reader. :-) As for the more general task of splitting strings using regular expressions, see re.split(). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From samgurung at gmail.com Fri Jul 22 00:28:10 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 21:28:10 -0700 Subject: Detecting computers on network In-Reply-To: References: Message-ID: <1122006490.221581.239840@z14g2000cwz.googlegroups.com> How about sending an ICMP echo packet to your broadcast address and checking which hosts send a reply From mwm at mired.org Fri Jul 1 22:37:28 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 01 Jul 2005 22:37:28 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <1120270309.103244.53600@g49g2000cwa.googlegroups.com> Message-ID: <868y0q3pcn.fsf@bhuda.mired.org> "Sean McIlroy" writes: > Peter Hansen wrote: > >> Sean, what gave you the impression this would change? > if that's the case then list comprehensions and/or "first class > functions" are likely to be the next target. The existence of list comprehensions are the reason that these functions are going away, so they aren't likely to be next. It's all part of "There should be one-- and preferably only one --obvious way to do it." Personally, I hope they wind up in a "functional" module, so you can add "from functional import *" to the top of your scripts, and keep doing exactly what you've been doing. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From michele.simionato at gmail.com Sun Jul 31 01:49:49 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 30 Jul 2005 22:49:49 -0700 Subject: multiple inheritance super() In-Reply-To: <86slxvh7qk.fsf@bhuda.mired.org> References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> <1122653176.013770.106080@g49g2000cwa.googlegroups.com> <86br4ljnxs.fsf@bhuda.mired.org> <1122716129.428629.273960@g49g2000cwa.googlegroups.com> <86slxvh7qk.fsf@bhuda.mired.org> Message-ID: <1122788989.524732.40190@o13g2000cwo.googlegroups.com> Mike Meyer: > I think you're replying to me, but you didn't include any indication > so I can't be sure. Oops, sorry, yes, I was replying to you. > These two are cases of what I was talking about when I referred to the > Church-Turing thesis. Well, let me put it in this way. If a language can implement a missing feature easily, then you are not really missing a big thing. And the feature may not be provided by default for sake of semplicity and/or uniformity of style. For instance Python does not have repeat-until loops, case statement, ternary operator, etc. (obviously I am not advocating to remove multiple inheritance now, I am justing speculating, talking about an hypotetic new Python-like language). > Also, I don't see how they make the situation > you are scared of above any better. It would discourage some people from some abuses, in the same sense the absence of repeat-until, case statemente, ternary operator etc are working right now. > > 3. think differently and use multimethods > > I don't see how that would help at all. You haven't done anything > about solving the base problem - that getting the methods into my > classes cleanly needs multiple inheritance. Further, I don't need > methods that are distinguished based on their arguments - they all > take a fixed set of arguments, and operate on them and the state of > the instance. None seem to be candidates for being multimethods. The > mixin methods tend to provide general functionality, and get used in > radically different places by the different child classes. > > You did miss the one alternative I considered: making the methods of > Mixin stand-alone functions, and passing them extra arguments instead > of using attributes of the instance. They would all then look like > mixin_func(self.foo, self.bar, var, value). I decided that this wasn't > as readable as inherting the methods. Uhm? I do not follow you. Multimethods would dispatch according to the type and would act differently on the childrens, dependending on their state. Perhaps I would need more information to understand what you have in mind. But at the end my point is "I would not feel much more constrained in expressivity if I did not have multiple inheritance in Python, and actually I have found out that the more I use OOP, the less I use inheritance". Just curious if others had a similar experience. Michele Simionato From vishnu at acmet.com Tue Jul 19 03:14:52 2005 From: vishnu at acmet.com (Vishnu) Date: Tue, 19 Jul 2005 12:44:52 +0530 Subject: How to write at a sppecific location In-Reply-To: <1121756311.884331.15710@f14g2000cwb.googlegroups.com> Message-ID: <001a01c58c31$a34f3350$0c01a8c0@vishnu> Hi Pooja, Check the fileinput module's input function. ~Vishnu -----Original Message----- From: python-list-bounces+vishnu=acmet.com at python.org [mailto:python-list-bounces+vishnu=acmet.com at python.org] On Behalf Of Pooja Sent: Tuesday, July 19, 2005 12:29 PM To: python-list at python.org Subject: How to write at a sppecific location Hi All I have one csv file which has some data related to test results. It has following information TestId,Expectedres,Actualres 101,12,13 102,13 103,14 If I want to write ActualRes value in the file , How to do that. I tried using seek but its not working. I am not able to write at a specific location. Please tell me what is the rght way. I have chked all the docs but was not able to find any good solution. -- http://mail.python.org/mailman/listinfo/python-list From b83503104 at yahoo.com Tue Jul 12 09:47:50 2005 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 12 Jul 2005 06:47:50 -0700 Subject: append one file to another Message-ID: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Hi, I want to append one (huge) file to another (huge) file. The current way I'm doing it is to do something like: infile = open (infilename, 'r') filestr = infile.read() outfile = open(outfilename, 'a') outfile.write(filestr) I wonder if there is a more efficient way doing this? Thanks. From bokr at oz.net Mon Jul 4 00:38:38 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 04 Jul 2005 04:38:38 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: <42c83dec.443548208@news.oz.net> <42c89757.466438453@news.oz.net> Message-ID: <42c8bcc0.476015794@news.oz.net> On Mon, 04 Jul 2005 02:50:07 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sun, 03 Jul 2005 22:07:30 GMT, Ron Adam wrote: > >>Bengt Richter wrote: >> >> >>class foo(object): >> x = 1 >> y = 2 >> z = 3 >> def __init__(self,x=x,y=y,z=z): >> save_these = subdict(locals(),['x','y']) >> self.__dict__.update(save_these) > self.__dict__.update({'x':x, 'y':y, 'z':z}) # should work without save_these oops, I see you only wanted x and y, so that should be self.__dict__.update({'x':x, 'y':y}) # should work without save_these >> >> # rest of code >> print self.x, self.y, self.z >> >>f = foo() >>f = foo(5,6,7) >> Regards, Bengt Richter From guy.lateurNNOOSSPPAAMM at pandora.be Tue Jul 5 16:16:42 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Tue, 05 Jul 2005 20:16:42 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: "Tim Williams (gmail)" schreef in bericht news:mailman.1383.1120593403.10512.python-list at python.org... > Could you SMTP it back in ? It would gain an extra Received: header > but the rest of the email would most likely be unaltered. I don't understand what you mean. How does this have to do with connecting to the (probably-not-running) IMAP service? > Not my area of expertise I'm afraid. If you manually run the script > then you could use getpass() to prompt you for the password at run > time. Not mine either.. ;) I'd like to avoid having the user type in a pw every time. Outlook doesn't seem to need that, so, unless that's unsafe, why should I? Or could I get xp to 'remember' it? Btw, Outlook does ask permission if you try to, say, read the body of message. Anyway, the approach I suggested earlier (pw encrypted using key) is probably unlikely to solve the security issue, either. I mean, if the key itself (or a reference to it) is in my code, then anyone reading that code can decrypt it, right? g From erniedude at gmail.com Mon Jul 25 15:47:30 2005 From: erniedude at gmail.com (Ernesto) Date: 25 Jul 2005 12:47:30 -0700 Subject: Run batch files in Windows XP In-Reply-To: <9v2dnYY1NvZtoXjfRVn-ug@powergate.ca> References: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> <1122318744.969547.113640@g43g2000cwa.googlegroups.com> <9v2dnYY1NvZtoXjfRVn-ug@powergate.ca> Message-ID: <1122320850.623089.88360@g49g2000cwa.googlegroups.com> Thanks. Yeah I started to write in Python. Looks like this: ****************************************************** import os from os.path import join # Get input from user and make sure it is valid fileDirec = raw_input("\nEnter the path of where your STMP3XXX_SDK_FIRMWARE\nis located (i.e. C:\) : ") if not os.path.exists(fileDirec): exit(" ** File or path does not exist... exiting ** ") # Builds all binaries simultaneously for SDK 3.050 def buildBinaries(_path): _bootmanagerPath = join(_path, "STMP3XXX_SDK_FIRMWARE\DeviceDriver\Media\SmartMedia\BootManager\STMP3500\make") _usbmscPath = join(_path, "STMP3XXX_SDK_FIRMWARE\Projects\Sdk\lcdexample\usbmsc\make") _playerPath = join(_path, "STMP3XXX_SDK_FIRMWARE\Projects\Sdk\lcdexample\player\make") _mtpPath = join(_path, "STMP3XXX_SDK_FIRMWARE\Projects\Sdk\lcdexample\mtp\make") # First build bootmanager...change to that directory # and run the bootmanager file... Similarly for the others... os.chdir(_bootmanagerPath) os.execl(("bootmanager.bat"),("BOOTMANAGER ALL")) os.chdir(_usbmscPath) os.execl(("usbmsc.bat"),("USBMSC ALL UPDATER")) os.chdir(_playerPath) os.execl(("player.bat"),("PLAYER ALL")) os.chdir(_mtpPath) os.execl(("mtp.bat"),("MTP ALL")) # After gathering user input, call routine to build binaries... buildBinaries(fileDirec) ****************************************************************** The issue is after the first execution of os.execl, the script stops altogether. In other words after bootmanager.bat executes, its over. I would love to Python if I could get all scripts to execute (executing simultaneously would be a major + !) I'll try os.system THANKS!!! From awbarker at gmail.com Thu Jul 7 08:38:28 2005 From: awbarker at gmail.com (awbarker at gmail.com) Date: 7 Jul 2005 05:38:28 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: <1119977801.449923.128330@o13g2000cwo.googlegroups.com> References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> <42c1662d$0$26260$626a14ce@news.free.fr> <1119977801.449923.128330@o13g2000cwo.googlegroups.com> Message-ID: <1120739908.912266.256630@g14g2000cwa.googlegroups.com> 1. LDAP module should be included in the base distro. 2. DNS library really should be included in the base library, I emailed Anthony Baxter and he replied, saying it was almost done. 3. Ipython would be nice From chris at shenton.org Fri Jul 22 14:04:28 2005 From: chris at shenton.org (Chris Shenton) Date: Fri, 22 Jul 2005 14:04:28 -0400 Subject: rcslib.py doesn't like dot in revision numbers? Message-ID: <86mzoe67kj.fsf@PECTOPAH.shenton.org> [Disclaimer: I'm a python newbie.] I'm using rcslib.py to massage an RCS repo. The code uses a "name_rev" object which acts two ways: 1. if it's a string, represents the head version of the file 2. if a tuple (name, rev) represents a name and a revision Works fine if I use it like: checkout('myfile.txt') but if I invoke it with a version like: checkout('myfile.txt', '1.1') it complains about a bad character in the revision. The code which checks this is here: if c not in self.okchars: raise ValueError, "bad char in rev" and the chars that it thinks are OK are defined as: okchars = string.ascii_letters + string.digits + '-_=+' These okchars do not include '.' so normal numeric revision numbers are not accessible. Am I missing something? I can't find any doc on the library. I'm using the one from http://www.darkcoding.net/projects/rcslibtext.py which is newer than the allegedly abandoned under Python's pdist directory of tools, but these both have the same behavior on this. Is there some other facility I should be using instead of rcslib, like rcsclient.py? Thanks for any pointers. From gsakkis at rutgers.edu Tue Jul 5 11:45:01 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jul 2005 08:45:01 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <1120575861.296553.303750@z14g2000cwz.googlegroups.com> Message-ID: <1120578301.248381.227330@g14g2000cwa.googlegroups.com> "jwaixs" wrote: > To reply to the last part of the discussion and esspecially to Gustavo > Niemeyer, I really apriciate the way in which I had been answered. And > I won't have any questions about the re module that I had before I post > this threat. > > I was frustration and should, probebly, not post this frustration. But > it was never my purpous to ask something stupid or asking it arrogant. I think most people who answered you calmly realized that it was frustration rather than arrogance and trolling behavior. This happens often if you're new to something and/or this something is inherently complicated; I almost did the same mistake when I had to mess with the loathsome autoconf/automake/autohell files and tools, but at least I refrained from the expletives. > The python re module is, in my opinion, a non beginner user friendly > module. And it's not meant for beginning python programmers. I don't > have any experience with perl or related script/programming languages > like python. (I prefer to do things in c) So the re module is > completely new for me. It's not the python re module beginner unfriendly; it's the regular expression concepts and syntax that the module implements. Read some introductory material about regexps first (Wikipedia is a good place to start: http://en.wikipedia.org/wiki/Regular_expression) and then get familiar with the re module by trying the examples interactively in the interpreter. > If I upset someones clean mind posting a "stupid" and "arrogant" > question, I'm sorry and won't post my frustrasion on this usenet group > anymore. It's always a good idea to wait for a few hours before posting anything you may regret later, but this doesn't mean you should leave this group; as you saw already, it's far more tolerant and civilized than other groups in this respect. > But thank you for all your help about the re module, > > Noud Aldenhoven Cheers, George From bill.mill at gmail.com Wed Jul 20 16:31:32 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 20 Jul 2005 16:31:32 -0400 Subject: is this pythonic? In-Reply-To: <797fe3d405072013305d35745d@mail.gmail.com> References: <42DE4F67.7030300@mage.hu> <8c7f10c605072006192d8ae378@mail.gmail.com> <797fe3d405072013305d35745d@mail.gmail.com> Message-ID: <797fe3d405072013316b0a9cbf@mail.gmail.com> On 7/20/05, Bill Mill wrote: > On 7/20/05, Simon Brunning wrote: > > On 7/20/05, Mage wrote: > > > Or is there better way? > > > > > > for (i, url) in [(i,links[i]) for i in range(len(links))]: > > > > for i, url in enumerate(links): > > > > +2 for creating seeing a need and crafting a reasonable solution, but > -1 for not reading the section on builtins to see if it existed > already. > -1 for me for not reading over my email before sending. "creating seeing" should be "seeing". Peace Bill Mill bill.mill at gmail.com From me at privacy.net Sat Jul 9 08:16:57 2005 From: me at privacy.net (Dan Sommers) Date: Sat, 09 Jul 2005 08:16:57 -0400 Subject: Problem with sha.new References: Message-ID: On Sat, 09 Jul 2005 13:49:12 +0200, Florian Lindner wrote: > Hello, > I try to compute SHA hashes for different files: > for root, dirs, files in os.walk(sys.argv[1]): > for file in files: > path = os.path.join(root, file) > print path > f = open(path) > sha = sha.new(f.read()) ^^^ Now the name "sha" no longer refers to the sha module, but to the object returned by sha.new. Use a different name. > sha.update(f.read()) > print sha.hexdigest() Regards, Dan -- Dan Sommers From roccomoretti at hotpop.com Sun Jul 3 16:40:38 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Sun, 03 Jul 2005 15:40:38 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Fri, 01 Jul 2005 15:02:10 -0500, Rocco Moretti > wrote: > >> >> I'm not aware of a language that allows it, but recently I've found >> myself wanting the ability to transparently replace objects. > > > Smalltalk supports this with the "become" message. I have also done an > implementation of this for Python. As a pure Python module, or do you have to recompile the interpreter? From peter at engcorp.com Fri Jul 1 11:53:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Jul 2005 11:53:48 -0400 Subject: How to run commands in command line from a script In-Reply-To: References: Message-ID: Ivan Shevanski wrote: > Well, the thing is that I was just using changing directories as an > example for running a name specific command, is the here> the only way to run name specific commands? An example would be > (what I am actually trying to do) run the simply command > mame s1945 > in the command line. MAME is, for those of you that care, the multaple > arcade machine emulator and the command runs the classic game strikers > 1945. I'm just trying to automate the tedious process of running it > through the command line. By the way, thanks to everyone who responded > I'm really getting along here. So basically "os.system" would have done exactly what you wanted if you'd tried it on "mame" instead of using "cd", for reasons we've now covered. :-) -Peter From t-meyer at ihug.co.nz Thu Jul 7 20:19:07 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 8 Jul 2005 12:19:07 +1200 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: Message-ID: > Your first sentence contradicts the rest of your post; how is > Java the problem if it runs nice on a Mac and is sluggish on > Windows ? Because any Java program on (any version of) Windows (in my experience) is sluggish, and this is not true (again, in my experience) for Java programs on a Mac. There is a vast difference between the various JREs; whereas every platform I've used a cPython interpreter on has given reasonably constant performance (which is to be expected, with a C implementation). > At best this may say something about the difference > in perfomance between the two JREs (assuming that most > Windows and Mac users of Eclipse have similar experience with yours). Which was my point. From what I've seen of this thread, people aren't saying which platform they are using Eclipse on - I have a suspicion that the JRE that people are using significantly effects the resulting opinion of Eclipse. =Tony.Meyer From matthewharrison at gmail.com Fri Jul 15 21:15:15 2005 From: matthewharrison at gmail.com (matt) Date: 15 Jul 2005 18:15:15 -0700 Subject: How to create "cross-backend" python web app In-Reply-To: <5339b60d.0507150342.3de87411@posting.google.com> References: <1121375775.021103.28610@g43g2000cwa.googlegroups.com> <5339b60d.0507150342.3de87411@posting.google.com> Message-ID: <1121476515.567226.256650@g49g2000cwa.googlegroups.com> Thanks Paul- I'll look into WebStack. From Scott.Daniels at Acm.Org Tue Jul 12 16:17:41 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 12 Jul 2005 13:17:41 -0700 Subject: Slicing every element of a list In-Reply-To: References: Message-ID: <42d41d72$1@nntp0.pdx.net> Alex Dempsey wrote: > Recently I tried to slice every element of a list of strings. First I tried: > > f = open("export.xls", "r") > lines = f.readlines() > > for line in lines: > line = line[1:-5] > line = line.split('\"\t\"') > > This went without returning any errors, but nothing was sliced or > split. Next I tried: > > for i in range(len(lines)): > lines[i] = lines[i][1:-5] > lines[i] = lines[i].split('\"\t\"') > > This of course worked, but why didn't the first one work. Further why > didn't the first one return an error? result = [line[1 : -5].split('\"\t\"') for line in lines] --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVEMEcyber.com.au Fri Jul 8 01:25:12 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 08 Jul 2005 15:25:12 +1000 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <42CCE6DA.5020402@REMOVEMEcyber.com.au> Message-ID: <42CE0E38.60305@REMOVEMEcyber.com.au> Ron Adam wrote: > Steven D'Aprano wrote: >> Er, maybe I'm misunderstanding something here, but surely the most >> obvious case is for default and special function arguments: >> >> def count_records(record_obj, start=0, end=None): >> if end == None: >> end = len(record_obj) >> if start == None: # this is not the default! >> # start at the current position >> start = record_obj.current >> n = 0 >> for rec in record_obj.data[start:end]: >> if not rec.isblank(): >> n += 1 >> return n [snip] > You have three possible outcomes, > count all > count range > count using current index > count range from beginning to current > count range from current to end That makes four outcomes by my count. > The most consistent way to do this would be: > > def count_records(record_obj, start=0, end=len(record_obj)): That would work really well, except that it doesn't work at all. At the time the function is defined, record_obj doesn't exist, so there is no way of telling what it's length will be when the function is called. Here is a simpler example showing the problem: py> def func(s, start=0, end=len(s)): ... return s[start:end] ... Traceback (most recent call last): File "", line 1, in ? NameError: name 's' is not defined The only way this strategy works is if there is a global variable s which defines a __len__ method. But then the default value of end will be fixed to the length of that global for all time (or at least until the module is reloaded). So given a pre-existing global variable, you get a class of hard-to-debug bugs: py> s = [0, 1, 2, 3] py> def func(s, start=0, end=len(s)): ... return s[start:end] ... py> func("function", start=1, end=5) # works correctly "unct" py> func("ant") # default works correctly here "ant" py> func("function") # default is broken here "func" py> s = "antidisestablishmentarianism" py> func(s) # default is broken even when s changed "anti" -- Steven. From kay.schluehr at gmx.net Sun Jul 31 16:38:13 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Jul 2005 13:38:13 -0700 Subject: namespaces References: <42EC9690.2040301@tiscali.it> <1122826472.004836.273980@g43g2000cwa.googlegroups.com> Message-ID: <1122842293.028961.75070@z14g2000cwz.googlegroups.com> Paolino wrote: > The second point also shows my perplexities about functions namespace: > > def function(): > function.foo='something' > > a=function.foo > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'function' object has no attribute 'foo' > > How should I read it? The namespace is half done inside the function? Don't know what you mean with "half done"? In order to understand Python you have to care about it's dynamic nature. The "def function()" is an executable definition that produces a function object that gets bound to a new global name "function". After "function" is created it may be manipulated inside it's own body much like it is possible to call it recursively. That's why this should work: def function(): function.foo='something' >>> function() >>> a=function.foo By the way. Did you understand the hint Paul Rubin tried to offer? Defining an __all__ = [...] variable in your module makes exactly those names visible to other modules that are contained in the list. You might pollute your modules namespace but this is exactly what is it good for. You just have to care not to pollute the namespaces of other modules preserving locality. Kay From aisaac0 at verizon.net Fri Jul 22 00:40:44 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 22 Jul 2005 04:40:44 GMT Subject: Software needed References: Message-ID: "niXin" wrote in message news:db0bh7$oi4$1 at ctb-nnrp2.saix.net... > Can anyone direct me to where I can find free software to do the following: > Document Management Software > --------------------------- > 1. Written in PHP or Python > 2. scanning feature - where I can scan a document http://furius.ca/nabu/ ? From tdwdotnet at gmail.com Fri Jul 22 07:02:39 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Fri, 22 Jul 2005 12:02:39 +0100 Subject: dictionary that discards old items In-Reply-To: References: <42e01f85$0$1586$da0feed9@news.zen.co.uk> Message-ID: <9afea2ac05072204024b9e271f@mail.gmail.com> On 7/21/05, Michael Hoffman wrote: > Will McGugan wrote: > > > I need a collection class that behaves like a dictionary but when it > > reaches 'n' items it discards the oldest item so that the length never > > goes above 'n'. (Its for caching search results) > > > > I have a vague memory of a module that does this, but I cant remember > > where I read about it. Can anyone enlighten me? > > You want a Least Recently Used, or LRU, cache. Here's one: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524 > http://py.vaults.ca/apyllo.py/514463245.769244789.92554878 From tim.peters at gmail.com Fri Jul 22 13:30:52 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 22 Jul 2005 13:30:52 -0400 Subject: time.time() under load between two machines In-Reply-To: <1122050067.793702.164780@o13g2000cwo.googlegroups.com> References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> <1122050067.793702.164780@o13g2000cwo.googlegroups.com> Message-ID: <1f7befae05072210305d5048f4@mail.gmail.com> [kwharrigan at yahoo.com] > I am seeing negative latencies of up to 1 second. I am using ntp to > synchronize both machines at an interval of 2 seconds, so the clocks > should be very much in sync (and are from what I have observed). I > agree that it is probably OS, perhaps I should hop over to a Microsoft > newsgroup and pose the question, although I'm sure they will find a way > to blame it on Python. That won't be easy . This is how Python computes time.time() on Windows (it's C code, of course): struct timeb t; ftime(&t); return (double)t.time + (double)t.millitm * (double)0.001; `ftime()` there is from Microsoft's C library: IOW, Python basically returns exactly what MS's ftime() returns, after converting it to a double-precision float. From gsakkis at rutgers.edu Sat Jul 23 13:18:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 23 Jul 2005 13:18:59 -0400 Subject: Lists & "pointers" References: <42e25ac2$1@griseus.its.uu.se> <1122133479.754605.113060@f14g2000cwb.googlegroups.com> Message-ID: <1122139148.2a155a33c48ab6273c946fda7558c006@teranews> wrote: > Jan Danielsson wrote: > > Hello all, > > > > I have written a simple whiteboard application. In my application, I > > want to be able to set draw attributes. This part works. I have a > > dictionary object which contains stuff like: > > self.attr['Pen.Color'] = ... > > self.attr['Pen.Thickness'] = ... > > > > Now, the problem is that I want to be able to store attributes in a > > list so they'll be easily accessed using the function keys. I.e. I have > > the "current attributes" which I want to be able to store or retrieve > > in/from a list, > > > > The problem is that I have initialized the list like this: > > > > self.drawAttr = { blah, blah, blah.. } > > self.storedAttr = [ ] > > for i in range(0, 10): > > self.storedAttr.append(self.drawAttr) > > > > I know what the problem is; they are all referencing the *same* > > dictionary object. So, my question is: How do I initialize a list of > > dictionary objects, where each list entry is its own object (which is a > > copy from the self.drawAttr object). > > > > Also, how do I store/restore entries to the list? > > > > I have found the "copy" module, and it's copy method. I assume this > > would work: > > > > for i in range(0, 10): > > self.storedAttr.append(copy.copy(self.drawAttr)) > > > > However, the concept of "deep copy" confuses me. Do I want it, or > > don't I want it? I repeat: the attributes object is a simple dictionary. > > > > Thankful for any advice. > > The easiest way to do it would be to create a new dictionary object for > each iteration of your loop. In this scenario, you would not need to > use the copy module. > > In other words: > > self.storedAttr = [ ] > for i in range(0, 10): > self.storedAttr.append({ blah, blah, blah.. }) And this would be equivalent to shallow copy. Whether you need a deep copy depends on what each "blah" is. More specifically it depends on whether the values of the dictionary are mutable or not (the keys are known to be immutable anyway). If they are immutable, a shallow copy is enough. If not, check whether all dictionaries refer to the same values or separate copies of the values. Only in the latter case you need deep copy. HTH, George From fred at adventistcare.org Wed Jul 6 15:26:39 2005 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 6 Jul 2005 15:26:39 -0400 Subject: I am a Java Programmer Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317540@sunbelt.org> It takes great courage to turn from the dark side; let the pforce be with you. Also, go to Borders, get the python books and a Latte and figure out if one of the many books is written in a style that you like. -----Original Message----- From: bruno modulix [mailto:onurb at xiludom.gro] Sent: Monday, July 04, 2005 5:52 AM To: python-list at python.org Subject: Re: I am a Java Programmer mjmrifai at gmail.com wrote: > I am a java programmer Too bad :( > and I want to learn Python So there's still hope !-) > Please help me. 1/ download and install Python 2/ go thru the 'dive into Python' and 'Thinking in Python' free books 3/ post here when you're in doubt or in trouble... And don't forget: Python is *not* Java !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From spam.csubich+block at block.subich.spam.com Sat Jul 23 22:46:31 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 23 Jul 2005 22:46:31 -0400 Subject: return None In-Reply-To: References: <3kcpbbFtjttlU1@individual.net> <11e2dru68unf2e8@corp.supernews.com> Message-ID: <%gDEe.19119$Wt3.19009@bignews3.bellsouth.net> Christopher Subich wrote: > print '%s returns:', retval Not that it matters, but this line should be: print '%s returns:' % func.__name__, retval From en.karpachov at ospaz.ru Fri Jul 29 13:30:10 2005 From: en.karpachov at ospaz.ru (en.karpachov at ospaz.ru) Date: Fri, 29 Jul 2005 21:30:10 +0400 Subject: Wheel-reinvention with Python (was: Ten Essential DevelopmentPractices) In-Reply-To: <1122657490.4202.17.camel@localhost.localdomain> References: <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <1122657490.4202.17.camel@localhost.localdomain> Message-ID: <20050729173010.GA3922@ospaz.ru> On Fri, Jul 29, 2005 at 01:18:10PM -0400, Jeremy Moles wrote: > On Fri, 2005-07-29 at 17:59 +0200, Torsten Bronger wrote: > > one thinks "well, perfect, I have the choice between four > > Four? > > 1. wx > 2. PyGTK > 3. Tk (Are you including this one even?) > 4. ??? Well, QT at least. And sure there is Tk. -- jk From hancock at anansispaceworks.com Wed Jul 13 00:07:07 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 12 Jul 2005 23:07:07 -0500 Subject: extend for loop syntax with if expr like listcomp&genexp ? In-Reply-To: <42d31b7a.423861700@news.oz.net> References: <42d30319.417620065@news.oz.net> <42d30af1$1@news.eftel.com> <42d31b7a.423861700@news.oz.net> Message-ID: <200507122307.07308.hancock@anansispaceworks.com> On Monday 11 July 2005 08:53 pm, Bengt Richter wrote: > On Tue, 12 Jul 2005 10:12:33 +1000, John Machin wrote: > >Bengt Richter wrote: > >> for x in (x for x in seq if x is not None): > >Byzantine ... > Perhaps not if you wanted to enumerate the selected elements, as in > for i, x in enumerate(x for x in seq if x is not None): Seems like a bug waiting to happen -- wouldn't someone using that idiom most likely have *meant* something like this: for i,x in enumerate(seq): if x is not None: print "seq[%d] = %s is not None" % (i, repr(x)) ? But of course that's not equivalent. It's hard to imagine a use case for an enumerated loop when the object being iterated over is anonymous (will be lost as soon as the loop exits). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From samgurung at gmail.com Thu Jul 21 05:57:25 2005 From: samgurung at gmail.com (linuxfreak) Date: 21 Jul 2005 02:57:25 -0700 Subject: wxPythin installation woes Message-ID: <1121939845.672075.122220@z14g2000cwz.googlegroups.com> Hi all, Was working with python 2.3 in a fedora core 3 machine. I upgraded it to Fedora Core 4 with a clean install. So now I have python 2.4 installed. But when I try to install wxPython for python 2.4 using an rpm file i downloaded from the wxpython web site i get dependencies errors. Turns out that libstdc++.so.5 is needed but I checked and i see that libstdc++.so.6 is installed on my system. Help needed guys and needed pronto. Thanks a ton once again :) From joe.woodward at padtinc.com Wed Jul 13 12:35:49 2005 From: joe.woodward at padtinc.com (Joe Woodward) Date: Wed, 13 Jul 2005 09:35:49 -0700 Subject: py2exe => can you go the other way? Message-ID: <8D1125CE7B803A429998BC0038C3F9672EE82A@peabody.padtinc.com> I have an executable version of a script that I wrote, but my script and backups got erased. Is it possible to get the python script back from an exe file created with py2exe? Joe Woodward Phoenix Analysis & Design Technologies 7755 s. Research Drive - Suite 110 Tempe, Arizona 85284 (480)813-4884 (480)813-4807 Fax -------------- next part -------------- An HTML attachment was scrubbed... URL: From rwgk at yahoo.com Mon Jul 11 18:19:29 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 11 Jul 2005 15:19:29 -0700 (PDT) Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code In-Reply-To: <1121117315.034614.62760@o13g2000cwo.googlegroups.com> Message-ID: <20050711221930.42094.qmail@web31502.mail.mud.yahoo.com> --- Lonnie Princehouse wrote: > IIRC, the self.__dict__.update(locals()) trick confuses psyco. > > But you can make a decorator to achieve the same result. There's not > really a convincing case for extending python syntax. Not if you have (enough memory for) psyco. :) I am doing C++ extensions by hand; did quite a lot of them. Anything that helps in pushing back the point where I have to move from Python to C++ is highly appreciated. That's probably the strongest argument for the (self, self.x, ...) approach. I believe it can be made more efficient than any other solution. But see also the two other arguments: http://mail.python.org/pipermail/python-list/2005-July/289721.html > def attribute_decorator(f): > import inspect > argnames = inspect.getargspec(f)[0] > def decorator(*args, **keywords): > bound_instance = args[0] > for name, value in zip(argnames[1:], args[1:]): > setattr(bound_instance, name, value) > return f(*args, **keywords) > return decorator > > #--------- example use: > > class foo(object): > @attribute_decorator > def __init__(self, thing): > print "init: self.thing is", repr(self.thing) > > f = foo('hello world') Thanks! Rob Williscroft had a similar suggestion: http://mail.python.org/pipermail/python-list/2005-July/289734.html Does anyone know if there is a way to hide the _ or self_ from the user of the class, i.e. given: class foo(object): @attribute_decorator def __init__(self, x, _y, z): pass can we make it such that the user can still write foo(x=1,y=2,z=3) without the underscore? Cheers, Ralf __________________________________ Discover Yahoo! Use Yahoo! to plan a weekend, have fun online and more. Check it out! http://discover.yahoo.com/ From zen19725 at zen.co.uk Sat Jul 30 09:02:08 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sat, 30 Jul 2005 14:02:08 +0100 Subject: How can I run a program? References: <1122719594.365246.241840@g43g2000cwa.googlegroups.com> Message-ID: On 30 Jul 2005 03:33:14 -0700, Lad wrote: >Hello, >I am running Python on XP and have a problem with >a program if its name consists '-' for example: >my-program.py >When I try to run a program with such name >I get the error : > >Traceback (most recent call last): > File "", line 1, in ? >NameError: name 'my' is not defined > >Python thinks that the name of program is my.py only >but the name is my-program.py > >What is a solution? Have you tried renaming it so it doesn't have a "-" in it? -- Email: zen19725 at zen dot co dot uk From bob at greschke.com Thu Jul 28 23:55:35 2005 From: bob at greschke.com (Bob Greschke) Date: Thu, 28 Jul 2005 21:55:35 -0600 Subject: pySerial Windows write problem References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: "Peter Hansen" wrote in message > > Actually, I'm curious why you don't do the same. I'd call it very unusual > (in my experience) to have a program open and close a serial port > repeatedly. Among other things, this means that the DSR/DTR lines are > toggling high and low repeatedly, and that alone could cause undesirable > behaviour in certain devices. I guess I could. It's just that not releasing the port/not KNOWING that the port has been closed at predictible times is our chief complaint about the C++ program. As an aside, when I left work I left a version of the while-loop program running, opening the port, writing to the equipment, getting a response, and closing the port. It was up to about 180 sucessful cycles (in a row -- it will stop if it fails). I think it's a hardware problem. :) > In none of my own serial-based programs (perhaps a few dozen such to date) > have I ever opened and closed a port other than at startup and shutdown > (just as your C++ program does). Unless you've got a good reason to do > otherwise, if this solves your problem it's certainly the most direct > approach to do so. One of the serial ports (there are actually two) is used to read some NMEA sentences from a GPS. It is only rarely read. If it is also opened when the program starts and kept open would you just dump the buffer and then read to get the most current info? What happens when the buffer fills up? The "main" port is just commands sent, responses received kind of traffic. I'd write a C extension to do the serial stuff, but I don't know a thing about Windows programming. Thanks! From peter at engcorp.com Tue Jul 26 11:00:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Jul 2005 11:00:56 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kjihkFubvl6U1@individual.net> <74SdndmpGeuannjfRVn-1w@powergate.ca> Message-ID: Ron Adam wrote: >>>> Tony Meyer wrote: >>>>> Do people really like using __div__ to mean join? > I think the '+' is used as a join for both strings and lists, so it > would probably be the better choice as far as consistency with the > language is concerned. The issue with that is that as long as we are subclassing strings, the + is already defined for a useful operation and the subclass probably shouldn't be changing the way that works. -Peter From cricfan at gmail.com Tue Jul 12 18:29:38 2005 From: cricfan at gmail.com (cricfan at gmail.com) Date: 12 Jul 2005 15:29:38 -0700 Subject: How to match literal backslashes read from a text file using regular expressions? Message-ID: <1121207378.715533.48090@g49g2000cwa.googlegroups.com> I'm parsing a text file to extract word definitions. For example the input text file contains the following content: di.va.gate \'di_--v*-.ga_-t\ vb pas.sim \'pas-*m\ adv : here and there : THROUGHOUT I am trying to obtain words between two literal backslashes (\ .. \). I am not able to match words between two literal backslashes using the regxp - re.compile(r'\\[^\\]*\\'). Here is my sample script: import re; #slashPattern = re.compile(re.escape(r'\\[^\\]*\\')); pattern = r'\\[^\\]*\\' slashPattern = re.compile(pattern); fdr = file( "parseinput",'r'); line = fdr.readline(); while (line != ""): if (slashPattern.match(line)): print line.rstrip() + " <-- matches pattern " + pattern else: print line.rstrip() + " <-- DOES not match pattern " + pattern line = fdr.readline(); print; ---------- The output C:\home\krishna\lang\python>python wsparsetest.py python wsparsetest.py di.va.gate \'di_--v*-.ga_-t\ vb <-- DOES not match pattern \\[^\\]*\\ pas.sim \'pas-*m\ adv : here and there : THROUGHOUT <-- DOES not match pattern \\[^\\]*\\ ----------- What should I be doing to match those literal backslashes? Thanks From peter at engcorp.com Fri Jul 29 07:54:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 07:54:18 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: Tony Meyer wrote: > Would you really choose this: > p = Path() / "build" / "a" / "very" / "very" / "long" / "path" > > Over this: > p = Path(os.path.join("build", "a", "very", "very", "long", "path")) I'd choose neither, because both are contrived examples (who builds paths out of six literals like that?) and the second one is not something anyone would want, since it mixes Paths and old-style os.path.join() calls. We're talking at this point about how Path should work, not whether it's preferable to os.path.join, even though that was really the point of Reinhard's original post. Given that, then, of the following two I would prefer the first one, slightly: p = somePath / user.getFolder() / 'archive' / oldPath + '.bak' p = somePath.joinpath(user.getFolder(), 'archive', oldPath + '.bak') > ? A saving of six characters, and the second one is a lot clearer. It's not a question of saving characters, but readability which, as you've said, is a matter of opinion. I find the former more readable. Somewhat. Not enough to make a big deal about it. I can live with the latter, but as *someone who has used the path module already* I can only say that you might want to try it for a few months before condemning the approach using / as being unacceptable. -Peter From kay.schluehr at gmx.net Mon Jul 18 01:10:50 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 17 Jul 2005 22:10:50 -0700 Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: <1121663450.495821.102780@g49g2000cwa.googlegroups.com> Diez B.Roggisch wrote: > Kay Schluehr gmx.net> writes: > > > Now lets drop the assumption that a and b commute. More general: let be > > M a set of expressions and X a subset of M where each element of X > > commutes with each element of M: how can a product with factors in M be > > evaluated/simplified under the condition of additional information X? > > > > It would be interesting to examine some sorting algorithms on factor > > lists with constrained item transpositions. Any suggestions? > > I don't think that sorting is the answer here. > Firts of all IMHO you have to add an > additional constraint - associativity of the operation in question > So the problem could be reduced to making the constant > parts be more associative than the non-constant parts. > which you should be able to > do with a parser. Hi Diez, I have to admit that I don't understand what you mean with the 'constant parts' of an expression? The associativity of __mul__ is trivially fullfilled for the dummy class M if an additional __eq__ method is defined by comparing factor lists because those lists are always flat: def __eq__(self, other): if isinstance(other,M): return self.factors == other.factors return False The sorting ( or better 'grouping' which can be represented by sorting in a special way ) of factors in question is really a matter of (non-)commutativity. For more advanced expressions also group properties are important: If a,b are in a center of a group G ( i.e. they commute with any element of G ) and G supplies an __add__ ( besides a __mul__ and is therefore a ring ) also a+b is in the center of G and (a+b)*c = c*(a+b) holds for any c in G. It would be nice ( and much more efficient ) not to force expansion of the product assuming distributivity of __add__ and __mul__ and factorization after the transposition of the single factors but recognizing immediately that a+b is in the center of G because the center is a subgroup of G. Regards, Kay From apoco at cox.net Wed Jul 13 00:42:42 2005 From: apoco at cox.net (Jacob Page) Date: Tue, 12 Jul 2005 21:42:42 -0700 Subject: set and frozenset unit tests? In-Reply-To: <3jhaoaFq2kajU1@individual.net> References: <3jhaoaFq2kajU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Jacob Page wrote: > >>I'd like to >>run my code through actual set and frozenset unit tests. Does any such >>code exist? Is it in pure Python? If so, where can it be obtained? > > Look at /usr/lib/python2.x/test/ (on unix platforms). Thanks for pointing that to me. For some reason, the Debian package for python 2.4 doesn't include those tests, but I acquired them from an alternative source. Oye, there's quite a number of set and frozenset features that aren't well-documented that I now need to implement. What a fun chore! From daniel.dittmar at sap.corp Mon Jul 11 09:56:31 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 11 Jul 2005 15:56:31 +0200 Subject: pyo contains absolute paths In-Reply-To: References: Message-ID: David Siroky wrote: > When I "compile" my python files with "python -OO ...." into pyo files > then they still contain absolute paths of the source files which is > undesirable for me. How can I deal with that? Use the script compileall.py (in Lib) to compile all the files. This script has an option -d that allows to set the directory name compiled into the .pyo files. From the help: "-d destdir: purported directory name for error messages" Daniel From gsakkis at rutgers.edu Sun Jul 10 02:11:45 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Jul 2005 23:11:45 -0700 Subject: Python Module Exposure References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> <1120934851.208175.19180@f14g2000cwb.googlegroups.com> Message-ID: <1120975905.198149.19240@z14g2000cwz.googlegroups.com> "Jacob Page" wrote: > George Sakkis wrote: > > As I see it, there are two main options you have: > > > > 1. Keep Intervals immutable and pass all the responsibility of > > combining them to IntervalSet. In this case Interval.__add__ would have > > to go. This is simple to implement, but it's probably not the most > > convenient to the user. > > > > 2. Give Interval the same interface with IntervalSet, at least as far > > as interval combinations are concerned, so that Interval.between(2,3) | > > Interval.greaterThan(7) returns an IntervalSet. Apart from being user > > friendlier, an extra benefit is that you don't have to support > > factories for IntervalSets, so I am more in favor of this option. > > I selected option one; Intervals are immutable. However, this doesn't > mean that __add__ has to go, as that function has no side-effects. The > reason I chose option one was because it's uncommon for a mathematical > operation on two objects to return a different type altogether. Mathematically what you described corresponds to sets that are not closed under some operation and it's not uncommon at all; a few examples are: - The set of integers is not closed under division: int / int -> rational - The set of real numbers is not closed under square root: sqrt(real) -> complex - The set of positive number is not closed under subtraction: pos_number - pos_number -> number - And yes, the set of intervals is not closed under union. On another note, I noticed you use __contains__ both for membership and is-subset queries. This is problematic in case of Intervals that have other Intervals as members. The set builtin type uses __contains__ for membership checks and issubset for subset checks (with __le__ as synonym); it's good to keep the same interface. George From peter at engcorp.com Sat Jul 30 13:37:25 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 13:37:25 -0400 Subject: PEP on path module for standard library In-Reply-To: <3l1avfF10i4kgU1@individual.net> References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> <3l1avfF10i4kgU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Mike Orr wrote: >>- Who needs .open()? open(myPath) is fine. But it can stay for >>backward compatibility. > > Right. I think it's nice for people who like a more OO approach. There's one very good reason to use .open() on a Path object, and in fact it's a (for me) strong justification for the existence of Path in the standard library (and, even more, for porting everything else in the standard library to use Path). A scattered assortment of module-level global function names, and builtins such as open(), make it extraordinarily difficult to do effective and efficient automated testing with "mock" objects. Although one can fairly easily shadow the definition of "open" in any given module under test, if the code under test instead calls another standard library routine which internally uses open(), it becomes necessary to replace the builtin definition of open() and affect all code throughout the program. Object-oriented solutions like Path make it near trivial to substitute a mock or other specialized object which (duck typing) acts like a Path except perhaps for actually writing the file to disk, or whatever other difference you like. I haven't gotten around to doing a mock Path object yet, though given the work that's gone into my existing mock FileSystem object which lets you replace open() and test code in a fully controlled and safe environment, it shouldn't be hard to do. So, for the PEP, another justification for Path is that its use can encourage better use of automated testing techniques and thereby improve the quality of Python software, including in the standard library. -Peter From jepler at unpythonic.net Mon Jul 11 11:36:15 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 11 Jul 2005 10:36:15 -0500 Subject: cursor positioning In-Reply-To: <42D27445.9090005@mage.hu> References: <42D27445.9090005@mage.hu> Message-ID: <20050711153611.GB18355@unpythonic.net> Here's a simple module for doing progress reporting. On systems without curses, it simply uses "\r" to return the cursor to the first column. On systems with curses, it also clears to the end of the line. This means that when the progress message gets shorter, there aren't droppings left from the longer ones. You have to take care that the progress message isn't wider than the screen, but I don't know a nice way to *find* the width of the screen that will work on windows and unix. Hardcoding 80 ain't it either. import sys def progress(s): sys.stderr.write(s + CLEAR_EOL + "\r"); sys.stderr.flush() try: import curses except ImportError: CLEAR_EOL = '' else: curses.setupterm() CLEAR_EOL = curses.tigetstr("el") or '' def test(): import time for j in range(2): for i in range(100): progress("Doing item %d, %d%%" % (i * 100, i)) time.sleep(.01) if __name__ == '__main__': test() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jamesthiele.usenet at gmail.com Tue Jul 19 11:36:16 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 19 Jul 2005 08:36:16 -0700 Subject: print ending with comma Message-ID: <1121787376.815068.145060@g49g2000cwa.googlegroups.com> I recently ran into the issue with 'print' were, as it says on the web page called "Python Gotchas" (http://www.ferg.org/projects/python_gotchas.html): The Python Language Reference Manual says, about the print statement, A "\n" character is written at the end, unless the print statement ends with a comma. What it doesn't say is that if the print statement does end with a comma, a trailing space is printed. -- But this isn't exactly correct either. If you run this program: import sys print '+', print '-', sys.stdout.write('=') print -- the output is: + -= Note that there is no space after the '-'. (Tested on Win 2000 python 2.3.4, OS X 10.3.9 python 2.3 & 2.4) I know that this is not a massively important issue, but can someone explain what's going on? From sjmachin at lexicon.net Fri Jul 22 17:22:16 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Jul 2005 07:22:16 +1000 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <11e297jkf6i5bfa@news.supernews.com> Message-ID: <42e16388@news.eftel.com> Michael Hoffman wrote: > John Roth wrote: > >> However, a path as a sequence of characters has even less >> meaning - I can't think of a use, while I have an application >> where traversing a path as a sequence of path elements makes >> perfect sense: I need to descend the directory structure, directory >> by directory, looking for specific files and types. > > > I *have* used a path as a sequence of characters before. I had to deal > with a bunch of filenames that were formatted like "file_02832.a.txt" Ya, ya , ya, only two days ago I had to lash up a quick script to find all files matching r"\d{8,8}[A-Za-z]{0,3}$" and check that the expected number were present in each sub-directory (don't ask!). BUT you are NOT using "a path as a sequence of characters". Your filename is a path consisting of one element. The *element* is an instance of basestring, to which you can apply all the string methods and the re module. > > I can see the case for a path as a sequence of elements, although in > practice, drive letters, extensions, and alternate streams complicate > things. > From moranar at alice.it Sat Jul 30 09:30:20 2005 From: moranar at alice.it (Adriano Varoli Piazza) Date: Sat, 30 Jul 2005 13:30:20 GMT Subject: Comparison of functions In-Reply-To: References: Message-ID: Adriano Varoli Piazza ha scritto: > As far as I recall from Math Analysis, which I studied two months ago, > you can't sort complex numbers. It makes no sense. The reason being > (reading from my book), it's not possible to define an order that > preserves the properties of arithmetical operations on complex numbers. > So you can't order them, and you can't compare them. > Sorry, that should have been "you can't sort them, and you can't compare them with greater than, lesser than, etc. Of course, using == will work. But tell me, how do you think sort works if not with <, >, ==, <= and >= ? I'm really interested. -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar MSN: adrianomd at hotmail.com ICQ: 4410132 From gh at ghaering.de Mon Jul 18 09:26:15 2005 From: gh at ghaering.de (Gerhard Haering) Date: Mon, 18 Jul 2005 15:26:15 +0200 Subject: What is your favorite Python web framework? In-Reply-To: <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> Message-ID: <20050718132615.GA22884@mylene.ghaering.de> On Mon, Jul 18, 2005 at 09:06:21AM -0400, Peter Hansen wrote: > JZ wrote: > > I think Django is more mature than Subway or CherryPy and can quickly > > become the black horse in area of pythonic frameworks. > > I'm not familiar with this expression. What do you mean by "black horse"? Maybe "the Ferrari of pythonic frameworks" (black horse on yellow background being the symbol of Ferrari). That's what I thought of first when I tried to parse the sentence ;-) -- Gerhard -- Gerhard H?ring - gh at ghaering.de - Python, web & database development -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From simon.dahlbacka at gmail.com Mon Jul 18 05:04:22 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 18 Jul 2005 02:04:22 -0700 Subject: Problem with threads In-Reply-To: References: Message-ID: <1121677462.329709.84360@g14g2000cwa.googlegroups.com> You cannot really do that*. Use a flag or something that the thread checks if it should shut down. /Simon * well actually you can, sort of by using int PyThreadState_SetAsyncExc( long id, PyObject *exc) from C API. However, if you do that you swap one problem for a sh*tload of others, because of the *async* part. From amitregmi at neolinuxsolutions.com Sun Jul 24 01:09:36 2005 From: amitregmi at neolinuxsolutions.com (Amit Regmi) Date: Sun, 24 Jul 2005 10:54:36 +0545 Subject: How do i do this Message-ID: <42E32290.3060307@neolinuxsolutions.com> For some commad Linux like (pdbedit) its not possible to supply password in the command line itself while we add a samba user account into the SAM database .. Now I want' to design an AddAccount() method in Python i.e when we can't do "pdbedit -adduser xxxxx%password" How do I manage to create an account usign the AddAccount() Python function ?? -- -Amit http://www.geocities.com/broamit -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQBC3HHp/u1Xr7tKTYARAv6eAJoDpKVv45v/M7NSH+xekpX6jasBJACeLcB/ lSIVQ0AMXFQrKPLZFOd6Qno= =Tltk -----END PGP SIGNATURE----- From terti at mighty.co.za Sat Jul 16 02:58:52 2005 From: terti at mighty.co.za (tertius) Date: Sat, 16 Jul 2005 08:58:52 +0200 Subject: HTML expect in python In-Reply-To: References: Message-ID: <42D8B02C.6040908@mighty.co.za> WGW wrote: > I would like to automate some simple browser navigating using python. > Ideally, I would like a package like pyexpect, but that can handle a > browser in much the same way as pyexpect handles a terminal (tall > order!). In short, I want a macro language for a browser (I know about > the commercial packages such as Easy Bee and Internet macros, but I want > more programmability and less cost!) > > http://pamie.sourceforge.net/ From cdkrug at worldnet.att.net Sat Jul 9 13:24:16 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Sat, 09 Jul 2005 17:24:16 GMT Subject: Having trouble importing against PP2E files References: Message-ID: <4LTze.1109779$w62.497642@bgtnsc05-news.ops.worldnet.att.net> On Fri, 08 Jul 2005 22:43:55 +0300, Elmo M?ntynen wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > >> Import Error: no module named PP2E.launchmodes >> >> However if I copy launchmodes.py into my work directory, it imports >> successfully. >> >> Both "Examples" above and "Examples\PP2E" contain the __init__.py file. > Are both Examples and PP2E packages? They appear to be, yes. > In python if a folder is meant to represent a package it should iclude > the above mentioned file __init__.py and by saying the above your > suggesting that PP2E is a package inside the package Examples. That appears to be the case, yes. > If the above is correct, you should append the pythonpath with > c:\Python24\ and refer to the wanted .py with Examples.PP2E.launchmodes. > As such the import statement obviously should be "from > Examples.PP2E.launchmodes import PortableLauncher". If the above isn't > the case and there is still something unclear about this, reply with a > more detailed post about the situation. > The registry value is this: C:\Python24\Lib;C:\Python24\DLLs;C:\Python24\Lib\lib-tk; C:\Python24\Examples\PP2E I'm not realy sure what other details are relavant. I've installed from the Windows .msi package, and appended the directory I want to PythonPath in the registry, and that doesn't do what I need. This is WinXP Pro From bokr at oz.net Sun Jul 3 22:50:07 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 04 Jul 2005 02:50:07 GMT Subject: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code References: <42c83dec.443548208@news.oz.net> Message-ID: <42c89757.466438453@news.oz.net> On Sun, 03 Jul 2005 22:07:30 GMT, Ron Adam wrote: >Bengt Richter wrote: > >> What if parameter name syntax were expanded to allow dotted names as binding >> targets in the local scope for the argument or default values? E.g., >> >> def foometh(self, self.x=0, self.y=0): pass >> >> would have the same effect as >> >> def foometh(self, self.y=0, self.x=0): pass >> >> and there would be a persistent effect in the attributes of self >> (whatever object that was), even with a body of pass. >> >> I'm not sure about foo(self, **{'self.x':0, 'self.y':0}), but if >> you didn't capture the dict with a **kw formal parameter, IWT you'd >> have to be consistent and effect the attribute bindings implied. >> >> (Just a non-thought-out bf here, not too serious ;-) >> >> Regards, >> Bengt Richter > >Well it works the other way around to some degree. > >def foo(self, x=x, y=y):pass > >x=x binds the class variables to the arguments without the self. if no >value is given. > >Which is kind of strange, since x by it self gives an error if no value >is given. The strange part is x=x is not the same as just x. I >understand why, but it still looks odd. ISTM you are comparing apples to oranges, execution-wise. The def in the context of a class definition is executed as soon as you get to the end of the class suite. The execution happens in a special name space similar to what happens when you execute a function suite by calling the function, except the class definition body is executed automatically. When you write def foo(self, x=x): ... the second x is looked up starting in the local excution namespace of the class body, so it finds class variables, if they are defined, otherwise it looks for an outer scope x for the value. Note that order counts: >>> class Foo(object): ... def foo(self, x=x): print x ... x = 123 ... Traceback (most recent call last): File "", line 1, in ? File "", line 2, in Foo NameError: name 'x' is not defined >>> class Foo(object): ... x = 123 ... def foo(self, x=x): print x ... >>> Foo().foo() 123 Note that self.x is a different access mechanism, and would access the same Foo.x that became a default value, but the value is the only thing they have in common. You could extract the function from the class, and the plain function would still have the default value: >>> bar = Foo.foo.im_func >>> bar('ignored self param') 123 >>> import dis >>> dis.dis(bar) 3 0 LOAD_FAST 1 (x) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> import inspect >>> inspect.getargspec(bar) (['self', 'x'], None, None, (123,)) There's where the default value is. It's put there when x=x is evaluated during the def execution for the function, which happens to have happened courtesy of a class body execution defining the class, but that's the only connection the 123 has. > > >Why isn't there a dict method to get a sub dict from a key list? >Fromkeys doesn't quite do it. > > sub-dict = dict.subdict(key_list) > >Or have dict.copy() take a key list. (?) > > sub_dict = dict([(key, srcdct[key]) for key in srcdct]) #untested, should work (if you don't use 'dict' for a variable ;-) > > > >The following works and doesn't seem too obscure, although the x=x, >etc.. could be annoying if they were a lot of long names. > >Seems like mutable default arguments is what's needed to make it work, >not that it's needed IMO. But it's an interesting problem. > > >def subdict(dict, keys): > d = {} > for k in keys: > d[k] = dict[k] > return d > >class foo(object): > x = 1 > y = 2 > z = 3 > def __init__(self,x=x,y=y,z=z): > save_these = subdict(locals(),['x','y']) > self.__dict__.update(save_these) self.__dict__.update({'x':x, 'y':y, 'z':z}) # should work without save_these > > # rest of code > print self.x, self.y, self.z > >f = foo() >f = foo(5,6,7) > > Regards, Bengt Richter From rkern at ucsd.edu Tue Jul 12 20:57:44 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Jul 2005 17:57:44 -0700 Subject: Creating anonymous functions using eval In-Reply-To: <42D44F9A.20308@kzoo.edu> References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> <1121184988.996652.126350@g47g2000cwa.googlegroups.com> <42D44F9A.20308@kzoo.edu> Message-ID: Joseph Garvin wrote: > Robert Kern wrote: > >>Not everyone is reading this list in a conveniently threaded >>form > > Why not? Just about every modern newsgroup reader and e-mail app has a > threaded view option. Good point. Allow me to modify my statement: not all newsreaders/email apps thread python-list/c.l.py conversations properly. The gateway often messes things up. It's also a royal pain in the butt to have to go read another message just to dereference anaphora, threading or no. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bob at passcal.nmt.edu Thu Jul 28 19:00:11 2005 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 28 Jul 2005 17:00:11 -0600 Subject: pySerial Windows write problem References: <3tudna94E-hWoXTfRVn-tw@nmt.edu> Message-ID: "Peter Hansen" wrote in message news:rfCdnZHOGsnDwXTfRVn-gg at powergate.ca... > Bob Greschke wrote: > > But writing anything to the port >> quickly (not always right away...like maybe 5-6 iterations through the >> loop?) causes the >> >> win32file.CloseHandle(self.hComPort) >> >> statement in the 'def close(self)' function of the serialwin32.py file of >> the pySerial package to hang for a few seconds, then return. > > Are you certain it is this line that is blocking, and not the preceding > line which is a call to SetCommTimeouts()? How did you prove which line > it is? (I don't have an answer to the problem, just wanted to be sure of > the information...) > > -Peter Hi! I had the SetCommTimeouts line commented out. I just have a couple of prints before and after the CloseHandle line. I didn't write the C++ program, but it looks like it never closes the serial port. It opens it when it starts up, then keeps it open until it quits. Tsk tsk tsk. Sloppy. Maybe they did that to cover up this problem. :) Bob From peter at engcorp.com Mon Jul 18 09:06:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 09:06:21 -0400 Subject: What is your favorite Python web framework? In-Reply-To: <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> <6s4lsyg7560p.18mltc3bs2d6p$.dlg@40tude.net> Message-ID: <_MOdncyAg8ywNEbfRVn-pw@powergate.ca> JZ wrote: > I think Django is more mature than Subway or CherryPy and can quickly > become the black horse in area of pythonic frameworks. I'm not familiar with this expression. What do you mean by "black horse"? From cowie.rob at gmail.com Fri Jul 22 08:02:30 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 22 Jul 2005 05:02:30 -0700 Subject: Separation of Code in CGI App Message-ID: <1122032996.635601.246620@o13g2000cwo.googlegroups.com> Hi, I need to create a planner/calendar system using python cgi scripts. It is my first CGI app (beyond a few tutorial examples). I wish to separate the code according to function. For instance, the code to handle the DB connection, SQL querying, HTML form variable retrieval, rendering of HTML via some sort of template system etc. Each will be a class instantiated when the CGI app is called. To do this, do I just create each of these classes in one, monolithic .cgi file? or is it possible to separate these out into different scripts and have a 'controller' script call them and pass the relevant parameters/data? I guess I could also store the python code in text files and use the 'execfile()' function, although it seems to me that would be an uneccasary performance hit. If that is possible, is that the right way to go? If not, suggestions would be gratefully recieved! From sjmachin at lexicon.net Fri Jul 22 08:30:01 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jul 2005 22:30:01 +1000 Subject: find a specified dictionary in a list In-Reply-To: <42e0dc25$1@news.eftel.com> References: <42e0dc25$1@news.eftel.com> Message-ID: <42e0e6c8$1@news.eftel.com> John Machin wrote: > Odd-R. wrote: > >> I have this list: >> >> [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] >> >> All the dictionaries of this list are of the same form, and all the oids >> are distinct. If I have an oid and the list, how is the simplest way of >> getting the dictionary that holds this oid? >> > > Something like this: > > def oidfinder(an_oid, the_list): > for d in the_list: > if d['oid'] == an_oid: Better indented as: > if d['oid'] == an_oid: > return d > return None > # These are not the oids you are looking for. From twic at urchin.earth.li Fri Jul 1 08:50:41 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 1 Jul 2005 13:50:41 +0100 Subject: No subject In-Reply-To: References: Message-ID: On Fri, 1 Jul 2005, Adriaan Renting wrote: > I'm not a very experienced Python programmer yet, so I might be > mistaken, but there are a few things that would make me prefer C++ over > Python for large (over 500.000 LOC) projects. Hmm. I don't know C++, but here goes ... > - namespaces Aren't namespaces basically the same as packages/modules in python? > - templates These would be meaningless in python - they're part of typefulness, which ... > - strong type checking ... python eschews. Not that this is necessarily a good thing. I have to say that my Java roots do lead me to think that strong typing is a plus for big projects, since it's a way of defining and enforcing interfaces between bits of code written by different people (or by one person at different times!). Optional static typing in python would be nice for this. > - data hiding Surely you can hide data in python? > - more available libraries and more advanced developement tools. True. The more advanced development tools are offset to a large degree by the advanced crappiness of C++ as a language, though; i'd be surprised if a C++ programmer borged up with all the latest tools was actually more productive than a python programmer with a syntax-colouring, auto-indenting text editor. It'd be very interesting to get some real numbers on that. >> Ultimately, manageability of a project is far and away more about the >> people involved and the techniques used than it is about any single >> technology involved. > > Agreed. +1 getting to the crux of it. tom -- In-jokes for out-casts From fuzzyman at gmail.com Thu Jul 14 15:50:49 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Jul 2005 12:50:49 -0700 Subject: Tkinter Button widget In-Reply-To: References: Message-ID: <1121370649.853471.149340@g47g2000cwa.googlegroups.com> Peter Otten wrote: > Shankar Iyer (siyer at Princeton.EDU) wrote: > [snip..] > > Change your source code from > > # wrong > button = Tkinter.Button(..., command=some_function(),...) > > to > > # correct > button = Tkinter.Button(..., command=some_function,...) > > to pass the *function* to the widget instead of the *result* of a function > call. And, next time, remember to post some code alongside with your > question. > Nice spot of mind reading there ;-) I remember getting bitten by this one a while ago.... Regards, Fuzzy > Peter From philippe at philippecmartin.com Sun Jul 17 22:31:38 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 18 Jul 2005 02:31:38 GMT Subject: What is your favorite Python web framework? References: Message-ID: http://cheetahtemplate.org/ Admin wrote: > On Sun, 17 Jul 2005 19:15:49 -0300, Sybren Stuvel > wrote: > >> http://www.unrealtower.org/mycheetah > > "Error 404 while looking up your page AND when looking for a suitable 404 > page. Sorry! > No such file /var/www/www.unrealtower.org/compiled/error404.py" > > I can't express myself on Cheetah, sorry!! > From roccomoretti at hotpop.com Mon Jul 18 14:14:09 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 18 Jul 2005 13:14:09 -0500 Subject: python certification In-Reply-To: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> Message-ID: lordverminard at gmail.com wrote: > i want to get a small certificate or diploma in python. > it should be online cuz i live in pakistan and wont have teast centers > near me. > it should be low cost as i am not rich. > and hopefully it would be something like a a begginer certification cuz > i am new to python. Just print out the certificate below and paste on your wall ;) #------------------------------------------------------------------# | | | | | Comp.Lang.Python does hereby certify that | | | | LORD VERMINARD | | | | is a bona fide Pythonista, | | with all rights and privileges | | assigned thereto. | | | | Presented This Day | | | | 18th of July, 2005 | | | | | #------------------------------------------------------------------# Or, you could give some indication of why you would need such a thing. If it's for your own satisfation, use the certificate above when you're gone through the tutorial and have written an actual program you feel is useful. (That's what's of value with Python - using it to make your life better, not being able to fill out the correct bubbles on some multiple choice test.) From fphsml at gmail.com Sun Jul 3 15:50:58 2005 From: fphsml at gmail.com (James) Date: 3 Jul 2005 12:50:58 -0700 Subject: How do you program in Python? In-Reply-To: <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> References: <3iqif8Fmj34kU1@individual.net> <_N2dnQE0rKZZv1XfRVn-tA@powergate.ca> Message-ID: <1120420258.718480.262220@g44g2000cwa.googlegroups.com> Peter Hansen wrote: > anthonyberet wrote: > > What I would really like is something like an old-style BASIC > > interpreter, in which I could list, modify and test-run sections of > > code, to see the effects of tweaks, without having to save it each time, > > or re-typing it over and over (I haven't even worked out how to cut and > > paste effectively in the IDLE environment). > > I do all my work using Scite (a nice free editor that was built to > demonstrate the Scintilla plugin that can also be used in Python > programs through things like the StructuredTextControl in wxPython), > with the auto-save-on-loss-of-focus feature enabled, and a command > prompt open in another window. > > I edit in the Scite window, hit Alt-Tab (under Windows XP) to change > focus to the cmd console (and instantly all my modified files are > saved), press the Cursor Up key to retrieve the previous command (which > is generally the name of my script, or a command like "python > myscript.py"), and hit Enter to execute it. > > So, any time I need to test the changes, I hit four keys (which at this > point is understandably more like a "chord" that I hit without direct > awareness of it) and I'm done. Sounds pretty close to old-style BASIC > and since I've come that route too (in the distant past), this may not > be a coincidence. Just curious. Why do you Alt-Tab to a console when you can just hit F5 in SciTE? That's just 1 key instead of 4. And yes, SciTE can autosave here too. From jason.massey at gmail.com Mon Jul 18 11:19:34 2005 From: jason.massey at gmail.com (Jason) Date: 18 Jul 2005 08:19:34 -0700 Subject: wxPython date In-Reply-To: References: <1121698326.616726.284280@o13g2000cwo.googlegroups.com> Message-ID: <1121699974.160068.186680@g44g2000cwa.googlegroups.com> Thanks, Peter. I must have been having a bit of the stupids, your example worked fine for me too. Back to the salt mines! From bartek.rylko at gmail.com Thu Jul 21 02:06:07 2005 From: bartek.rylko at gmail.com (=?ISO-8859-2?Q?Bartek_Ry=B3ko?=) Date: Thu, 21 Jul 2005 08:06:07 +0200 Subject: About undisclosed recipient In-Reply-To: <20050709180047.GA8781@unpythonic.net> References: <1120925091.660129.307800@g49g2000cwa.googlegroups.com> <20050709180047.GA8781@unpythonic.net> Message-ID: <4da0c1130507202306972e344@mail.gmail.com> Hi! Thanks for Your info!! It was very usefull for me! :-) Thanks once again! On 7/9/05, Jeff Epler wrote: > You provided far too little information for us to be able to help. > > If you are using smtplib, it doesn't even look at message's headers to > find the recipient list; you must use the rcpt() method to specify each > one. If you are using the sendmail method, the "to_addrs" list has no > relationship to the headers of the actual message---it simply calls > rcpt() once for each address in to_addrs. The example in the docstring > doesn't even *have* a To: header in the message! > > Jeff > > > From twic at urchin.earth.li Mon Jul 4 10:32:04 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 4 Jul 2005 15:32:04 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: On Sun, 3 Jul 2005, Dennis Lee Bieber wrote: > On Sun, 3 Jul 2005 20:53:22 +0100, Tom Anderson > declaimed the following in comp.lang.python: > >> 2 >> -1 >> >> Evaluates to -1? > > But what do you expect, say > > 2 > -X > > to evaluate as? (-X)^2 or -(X^2) > > I'd expect the latter... I think you've got me there. > I see the problem here as an assumption that "-1" is an entity in its > own right, and not an operation of negating a "1", whereas "-X" is the > entity "X" being negated. I think you're entirely correct. I'm not entirely sure that that assumption is wrong, but never mind. Anyway, it looks like i should really be filing a bug report with the International Mathematical Union about this, rather than whingeing about it here. tom -- A military-industrial illusion of democracy From daniel.dittmar at sap.corp Thu Jul 28 12:19:40 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 28 Jul 2005 18:19:40 +0200 Subject: Rich Graphics? In-Reply-To: References: Message-ID: Chris Spencer wrote: > I'm trying to write a Gui in Python for manipulating rich graphical > representations, similar to something like Inkscape. I've tried tkinter, > wxPython, pyGtk, and while they all do traditional widgets well enough, > none of them really handle anti-aliased, transparent, transformed shapes > typical of vector based displays. I've noticed tkZinc, which seems to > better handle vector graphics through the use of openGL, but it's > traditional widget set is still limited and based on tkinter. Ideally, > what I'm looking for is something like wxWidgets which can display SVG > along side standard widgets and allow there manipulation through Python. > I was thinking of a web-based route, by accessing the SVG capabilities > in Mozilla's Deer Park browser through Twisted+Livepage, but this has > been extremely complicated and limiting. Are there any other options I > haven't considered? > > Sincerely, > Chris maybe PyGame: http://www.pygame.org/, although it might be lacking in the standard widget department. Daniel From richardlewis at fastmail.co.uk Wed Jul 6 10:21:04 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Wed, 06 Jul 2005 15:21:04 +0100 Subject: Tkinter grid layout In-Reply-To: <1120646695.4393.237852689@webmail.messagingengine.com> References: <1120646695.4393.237852689@webmail.messagingengine.com> Message-ID: <1120659664.22749.237866140@webmail.messagingengine.com> On Wed, 06 Jul 2005 11:44:55 +0100, "Richard Lewis" said: > Hi there, > > I've got a tree control in Tkinter (using the ESRF Tree module) but I > can't get it to layout how I want it. > > I'd like to have it so that it streches north/south (anchored to the top > and bottom), is of a fixed width and is anchored to the left hand side. > Here's my code (its derived from one of the examples from the ESRF web > site): > OK, I've changed it so that the Tree and scroll bars are in a single Frame and added another Frame on the right hand side to put the rest of my stuff in. (Though I believe this is against the principles of grid layout management?) class MainWindow(Frame): def __init__(self, master): Frame.__init__(self, master) self.document = # new DOM document self.create_ui() def create_ui(self): self.master.protocol("WM_DELETE_WINDOW", self.app_quit) self.pack(fill="both") self.master.geometry("%dx%d%+d%+d" % (800, 600, 100, 100)) self.master.title("Site Editor") self.create_menu() self.create_site_list() self.rhs_frame = Frame(master=self, background="#FF0000") self.rhs_frame.grid(row=0, column=1, sticky=E+W+N+S) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(0, weight=1) label = Label(master=self.rhs_frame, text="FOO") label.grid(row=0, column=0) def create_site_list(self): self.list_model = ListModel(self.document) self.site_list_frame = Frame(master=self, width=300, background="#00FF00") self.site_list_frame.grid(row=0, column=0, sticky=E+W+N+S) self.site_list = Tree.Tree(master=self.site_list_frame,\ root_id="root",\ root_label="Site",\ get_contents_callback=self.get_list_item,\ width=300,height=600) self.site_list.grid(row=0, column=0, sticky=E+W+N+S) self.site_list_frame.grid_columnconfigure(0, weight=1) self.site_list_frame.grid_rowconfigure(0, weight=1) vsb = Scrollbar(self.site_list_frame, orient=VERTICAL) vsb.grid(row=0, column=1, sticky=NS) self.site_list.configure(yscrollcommand=vsb.set) vsb.configure(command=self.site_list.yview) hsb = Scrollbar(self.site_list_frame, orient=HORIZONTAL) hsb.grid(row=1, column=0, sticky=EW) self.site_list.configure(xscrollcommand=hsb.set) hsb.configure(command=self.site_list.xview) self.site_list.focus_set() I noticed that I had a pack() call in my create_ui() function which I must have pasted in from some example code a while ago. I tried taking this out (having read that you shouldn't mix pack and grid) but, of course, then there was no layout (or something) and I just got a blank window. So I tried using pack(fill="both"). It now fills horizontally correctly, but it still doesn't anchor with the bottom. I'm not setting any height for the Tree (if I do then it still doesn't anchor with the bottom) because I don't want it to have a particular height, just to fill the window. Am I heading in the right direction? Cheers, Richard From snacktime at gmail.com Sat Jul 30 05:08:03 2005 From: snacktime at gmail.com (snacktime) Date: Sat, 30 Jul 2005 02:08:03 -0700 Subject: To thread or not to thread In-Reply-To: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> References: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> Message-ID: <1f060c4c05073002082229db6b@mail.gmail.com> On 28 Jul 2005 12:10:12 -0700, Sidd wrote: > Hello, > I was recently reading an article on threading in python and I > came across Global Interpreter Lock,now as a novince in python I was > cusrious about > > 1.Is writing a threaded code in python going to perform well than a > normal python code.If so on what basis can it performance be measured. > > 2.Is writing a threaded code in python better than a code written in > C/C++ using PTHREADS. > > If someone can comment on these questions, it would be great. > If you want performance with an application that does a lot of concurrent activity, you might take a look at http://www.twistedmatrix.com which is an event driven framework for python. Much better performance than threads with a lot less memory and cpu usage. Although it does have a bit of a learning curve. In my own experience it would be faster then a comparable application written in C using pthreads. We have an application written in twisted that processes financial applications via bank networks, and at a steady 100tps I get about 1% cpu usage. We tested it up to around 1000tps before our database server started to get a bit overloaded. Twisted never used more than 20% of the cpu though. Chris From sjmachin at lexicon.net Fri Jul 22 08:57:41 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jul 2005 22:57:41 +1000 Subject: find a specified dictionary in a list In-Reply-To: <200507221227.j6MCRrux011872@dverghimalayaeiner.ii.uib.no> References: <42e0dc25$1@news.eftel.com> <200507221227.j6MCRrux011872@dverghimalayaeiner.ii.uib.no> Message-ID: <42E0ED45.2070301@lexicon.net> Odd-R. Hogstad wrote (in private e-mail, with scarcely private contents): >In comp.lang.python, you wrote: > > >>Odd-R. wrote: >> >> >>>I have this list: >>> >>>[{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}] >>> >>>All the dictionaries of this list are of the same form, and all the oids >>>are distinct. If I have an oid and the list, how is the simplest way of >>>getting the dictionary that holds this oid? >>> >>> >>> >>Something like this: >> >>def oidfinder(an_oid, the_list): >> for d in the_list: >> if d['oid'] == an_oid: >> return d >> return None >> # These are not the oids you are looking for. >> >> > >Thank you, however I was hoping for something even simpler, >as I am to use it in a Is this the only way to do it? What if I know that the oid >I am looking for is pressent? > > > > Answering the 2nd question first: ignore the possiblility that the oidfinder() will return None i.e. just chill out. Other ways: (a) use a list comprehension inline: current_dict = [d for d in the_list if d['oid'] == current_oid][0] # this is a tad ugly and will blow up if the sought oid is not present -- but that can't happen, can it ? :-) (b) preprocess the weird/baroque/byzantine list that you have got. the_dict = {} for d in the_list: the_dict[d['oid']] = d then you do this: current_dict = the_dict[current_oid] # Simpler than that it cannot be. Now a couple of questions for you: (1) Have you contemplated that an oid can appear more than once in the list? (2) What in tarnation is an "oid"????? Cheers, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Wed Jul 13 04:16:41 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 10:16:41 +0200 Subject: threads and sleep? In-Reply-To: <11crcojcupi46de@corp.supernews.com> References: <38ljc15iem7b85e55f03ko3r6sr5027dmn@4ax.com> <49alc1poqic9jqe92mpkg8eacrqc8h8n3v@4ax.com> <11clbmj3sjl67f4@corp.supernews.com> <11clc1v4el6no7d@corp.supernews.com> <11cnrngi4lrqn0a@corp.supernews.com> <11crcojcupi46de@corp.supernews.com> Message-ID: <1121242601.5240.71.camel@andi-lap> Am Donnerstag, den 07.07.2005, 22:56 +0000 schrieb Grant Edwards: > Oh. I assumed that CPython used Posix threads on Posix It does. > platforms. At least in my experience under Linux, libpthread > always creates an extra "manager" thread. Though in our case It probably does. But it will probably not show as a Python thread. Without some special interfacing with the Python/C API any thread created in C will not show up in Python. > that thread probably wouldn't be running a Python interpreter. Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From rutski89 at gmail.com Sat Jul 2 09:25:42 2005 From: rutski89 at gmail.com (Patrick Rutkowski) Date: Sat, 2 Jul 2005 09:25:42 -0400 Subject: Bad Math In-Reply-To: <42C67CCA.1040807@po-box.mcgill.ca> References: <42C61223.1040605@po-box.mcgill.ca> <42C67CCA.1040807@po-box.mcgill.ca> Message-ID: On 7/2/05, Brian van den Broek wrote: > Patrick Rutkowski said unto the world upon 02/07/2005 00:12: > > That's... annoying, to say the least. And my number 4/5 was a rational > > number too; I can understand how when doing 1/3 things can get funky. > > Really though... 4/5 = 0.8 right on the nose, whats up? > > > > I read that http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate > > I'd like to find out more, is there anyway for this issue to be > > circumvented? That "is within a reasonable limit check" seams like way > > too much just to get a proper result from something simple like 4/5. > > > > > > Hi Patrick, > > my quick piece of code became something I thought might someday be > useful. So, I expanded it with tests, and sanity checks, etc. It > doesnt' yet have the full functionality I'd like (see docstrings), but > I won't get to fixing it anytime real soon. > > So, in case you are interested, it is attached. It allows you to > compute the value of a rational[*] as expressed in any base, 1 < base > < 37, to arbitrary precision. > > [*] Any n/m, -3 < n/m < 3. Subject to some restrictions, a greater > range. (These are the limits on functionality mentioned above.) > > It is in need of some re-organization, and I'm no skilled programmer, > so certainly don't take it as an ideal model :-) > > It also got me to look into decimal for the first time :-) > > Anyway, attached. > > Best, > > Brian vdB > > > > > #! /usr/bin/env python > # > # rationalconverter.py > # Copyright 2005 Brian van den Broek > # vanden at gmail.com > # > # Version 0.1 > # 02-Jul-2005 05:29:20 > # > # Released under the GPL > # (If you would prefer some other licence, feel free to write and ask: we > # will most probably be able to work something out -- I picked the GPL > # because safe and well-known, not out of a deep ideological commitment.) > > ############################################################################## > # > # rationalconverter.py -- functions to convert rationals to other bases > # Copyright (C) 2005 Brian van den Broek > # > # This program is free software; you can redistribute it and/or modify > # it under the terms of the GNU General Public License as published by > # the Free Software Foundation; either version 2 of the License, or > # (at your option) any later version. > # > # This program is distributed in the hope that it will be useful, > # but WITHOUT ANY WARRANTY; without even the implied warranty of > # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the > # GNU General Public License for more details. > # > # You can view the GNU General Public License at: > # . > # > # Alternatively, you can obtain a copy by writing to: > # The Free Software Foundation, Inc. > # 59 Temple Place - Suite 330 > # Boston, MA 02111-1307 > # USA > # > ############################################################################## > > > import math, string > from decimal import Decimal > > # values is the set of 36 'digits' for use in representing the converted value. > values = string.digits + string.uppercase > > def float_to_base_n(numerator, denominator, base, precision): > '''_> string expressing target in base to desired precision > > numerator and denominator must be integral values, denominator must also be > non-zero. > base must be an integral value greater than 1 and less than 37. > precision must be an integeral value greater than 0. > > The function returns a string representing numerator/denominator in base > to the desired level of precision. > > NB Temporary limitations: > Presently, it can handle neither numerator/denominator values greater > than 10, nor combinations of numerator, denominator, and base values > such that numerator/denominator > base. (The original code was written > just to deal with decimal fractions in [0, 1] and thus cannot cope with > these cases.) Future plan. Patches welcomed. > > >>> float_to_base_n(4, 5, 3, 20) > '0.210121012101210121012' > ''' > > error, msg = _sanity_check_for_float_to_base_n(numerator, denominator, > base, precision) > if error: > raise error, msg > > base = Decimal(base) > precision = Decimal(precision) > target = Decimal(numerator) / Decimal(denominator) > > start = target.to_integral() > > # Must be a better way, but this ensures that start is the integral portion > # of numerator/denominator. FIXME > if target > 0: > if start > target: > start = start - 1 > residue = target - start > else: > if start < target: > start = start + 1 > residue = target + start > > start = int(start) > expression = [str(start), '.'] > > place = Decimal(0) > > while place < precision + 1: > place += 1 > for value in range(0, base+1): > value = Decimal(value) > #print place, value, value / base ** place, residue, expression > if (value / base ** place) > residue: > #print value / base ** place, 9999999999999, residue > #print type(value / base ** place), type(residue) > #print 6666666666666666666 > # then we've gone too far. This is why base+1 in range. That > # way, we will also have gone too far by the last value > break > # relying on value leaking out of the loop, > # and decrimenting as it went too far. > #print value, residue, type(value) > expression.append(values[int(value - 1)]) > #print expression > #raw_input() > residue = residue - ((value - 1) / (base ** place)) > > return ''.join([str(i) for i in expression]) > > def _sanity_check_for_float_to_base_n(numerator, denominator, base, precision): > '''Helper function to perform sanity check for float_to_base_n() > > It is here merely because with this in the body of the main function, the > code became too long. It simply performs the various type and value tests > to ensure that numerator, denominator, base, and precision are all sane in > float_to_base_n(target, base, precision). > > If all values are sane, it returns None, None > If an exception should be raised, it returns the exception class and an > informative error message. > ''' > > # null starting msg to support if tests below, giving default msg values > msg = None > > try: > int(numerator) > > if math.floor(numerator) != numerator: > msg = "numerator must be exact integer" > raise ValueError > > except ValueError: > if not msg: > msg = "Invalid numerator value for float_to_base_n: %s" %numerator > return ValueError, msg > > try: > target = numerator * 1.0 / denominator > > except ZeroDivisionError: > msg = "Denominator must be a non-zero integral value" > raise ValueError, msg > > try: > int(denominator) > > if math.floor(denominator) != denominator: > msg = "denominator must be exact integer" > raise ValueError > > except ValueError: > if not msg: > msg = "Invalid denominator value for float_to_base_n: %s" %( > denominator) > return ValueError, msg > > try: > int(base) > > if math.floor(base) != base: > msg = "base must be exact integer" > raise ValueError > > if not 37 > base > 1: > msg = "base must be greater than 1 and less than 37" > raise ValueError > > except ValueError: > if not msg: > msg = "Invalid base value for float_to_base_n: %s" %base > return ValueError, msg > > > try: > int(precision) > > if math.floor(precision) != precision: > msg = "precision must be exact integer" > raise ValueError > > if not precision > 0: > msg = "precision must be greater than 0" > raise ValueError > > except ValueError: > if not msg: > msg = "Invalid precision value for float_to_base_n: %s" %precision > raise ValueError, msg > > if target > base: > msg = "Cannot yet handle numerator/denominator values greater than base" > return NotImplementedError, msg > if target > 10: > msg = "Cannot yet handle numerator/denominator values greater than 10" > return NotImplementedError, msg > > return None, None > > > def _test(): > '''Function to run doctest on the module''' > global __test__ > __test__ = { > "Test of float_to_base_n for values between 0 and 1": ''' > > >>> float_to_base_n(4, 5, 3, 20) > '0.210121012101210121012' > >>> float_to_base_n(4, 5, 3, 10) > '0.21012101210' > >>> float_to_base_n(4, 5, 10, 10) > '0.80000000000' > >>> float_to_base_n(1, 8, 2, 10) > '0.00100000000' > >>> float_to_base_n(1, 3, 3, 10) > '0.10000000000' > ''', > > "tests for rejecting invalid input": ''' > > >>> float_to_base_n('one point three', 4, 3, 20) > Traceback (most recent call last): > ... > ValueError: Invalid numerator value for float_to_base_n: one point three > >>> float_to_base_n(4, 5, 1, 4) > Traceback (most recent call last): > ... > ValueError: base must be greater than 1 and less than 37 > >>> float_to_base_n(3, 4, 1.2, 4) > Traceback (most recent call last): > ... > ValueError: base must be exact integer > >>> float_to_base_n(4, 6, 'AA', 4) > Traceback (most recent call last): > ... > ValueError: Invalid base value for float_to_base_n: AA > >>> float_to_base_n(4, 9, 12, 1.7) > Traceback (most recent call last): > ... > ValueError: precision must be exact integer > >>> float_to_base_n(4, 9, 12, -7) > Traceback (most recent call last): > ... > ValueError: precision must be greater than 0 > >>> float_to_base_n(9, 13, 14, 'gg') > Traceback (most recent call last): > ... > ValueError: Invalid precision value for float_to_base_n: gg > >>> float_to_base_n(120, 10, 16, 8) > Traceback (most recent call last): > ... > NotImplementedError: Cannot yet handle numerator/denominator values greater than 10 > >>> float_to_base_n(90, 3, 4, 8) > Traceback (most recent call last): > ... > NotImplementedError: Cannot yet handle numerator/denominator values greater than base > >>> > '''} > import doctest, sys > test = doctest.testmod(sys.modules[__name__], report = True, > optionflags = doctest.ELLIPSIS) > > if test[0] == 0: > print "Congratulations!\n%s tests ran, %s failed" %(test[1], test[0]) > > > if __name__ == '__main__': > _test() > pass > > > I just got up and read your mail. However, I'm going away for the day so I didn't have time to look over your code. Thanks for the advice and explanations, they really helped. I understand the problem now... /me waves fist a base 2 fractions. If your code can fix it, then that's pretty great! What was that "import decimal" idea you proposed? Does it contain some functions that can sanely work with floating points? I'm not a new programmer, but my main arena is the simple side of Java, so I'm not really too far along yet. Hoping Python will be fun, Patrick Rutkowski P.S. I responded to the list this time. From simon.dahlbacka at gmail.com Tue Jul 19 06:07:35 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 19 Jul 2005 03:07:35 -0700 Subject: Documentation bug: Python console behaviour changed In-Reply-To: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> References: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> Message-ID: <1121767655.630033.88890@f14g2000cwb.googlegroups.com> My console follows documentation: C:\tmp\GspRegTestApp>c:\Python24\python ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z C:\tmp\GspRegTestApp>c:\Python24\python ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^D File "", line 1 ? ^ SyntaxError: invalid syntax >>> From http Sat Jul 30 20:48:39 2005 From: http (Paul Rubin) Date: 30 Jul 2005 17:48:39 -0700 Subject: shelve: writing out updates?! Message-ID: <7xslxvpzq0.fsf_-_@ruckus.brouhaha.com> Shelve uses dbm and pickle to make a persistent object store. The "db" in "dbm" stands for "database" and while I didn't expect full ACID capability, I'd have thought there'd be at least some minimum gesture towards durability of updates. But say that s is a shelve object. If I say s[whatever] = value there is no way apparent from the shelve docs to get the update flushed out to the disk file until the shelve is actually closed. If I'm using the shelve to store stuff in a long-running server, it could be months before the shelve closes. Is shelve really missing this capability? Thanks. From fuzzyman at gmail.com Fri Jul 22 04:56:44 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Jul 2005 01:56:44 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> Message-ID: <1122022604.433713.39510@g43g2000cwa.googlegroups.com> TPJ wrote: > GUI's etc: PyGtk on Windows > "(...) So if someone develops mainly for X and just wants to make sure > that it is not impossible to run on Windows, you can use PyGTK. (...)", > July 2nd, 1999 > > pyGTK on Windows > "(...) > > can i use pyGTK under > > Windows??? > > It's probably doable (...) but not worthy in my oppinion (...). A much > better choice is wxPython (...)" > > "(...)even if it is made to work under windows, pygtk would not have a > windows look and feel. wxPython is probably your best bet (...)" > > pygtk vs. wxPython > 4. "(...) If you want cross-platform capabilities (...) then go > wxWindows." May 17 2002 > > 7. "(...) The pygtk (and gtk port in general) does not yet support > threading on windows. (...) GTK 2.0 is supposed to fix it but support > isn't available *yet*. (...)" May 17 2002 > > PyGTK vs. wxPython > 7. "(...) wxPython would indeed be a better choice if your applications > are only to run on a certain infamous legacy operating system from the > Pacific Northwest. The PyGTK is a better choice if you are writing for > Linux and want your application to also be able to run on windows. > (...)" Apr 25 > > 11. "(...) I'm using wxPython because GTK for windows wasn't ready > three years ago when I initially had to write my first Windows > application. If I evaluated both of them again today, I might choose > GTK, and I might not." Apr 27 > > > > In the nearest future I will have to decide what to use: PyGTK or > wxPython. I like those both APIs. wxPython has more widgets, but PyGTK > seems to be faster. I can use them both for free (it's very important). > My only concern is that although I'm doing development on Linux, I'd > like to make my application runnable on Windows as well (Py2Exe). I'd > like to choose PyGTK (because of its rich documentation), but I'm not > sure if PyGTK is stable on Windows... For now I know that wxPython runs > well on Windows. > > For now I haven't experienced any problems with wxPython on Linux > (Slackware, Aurox /Polish RH-like distro/). I used wxPython on Linux, > but I stopped because of its poor documentation (mainly C++ docs, not > Python docs). But recently I noticed this documentation got better > (*much* better!). > > How well does PyGTK run on Windows (98, 2K, XP)? How stable is it? Will > I be able to make an executable (using Py2Exe) of an application that > uses PyGTK? I use wxPython through Wax - Wax makes it nice and easy. Note that wxPython doesn't have a completely native look and feel on Windoze, but it's pretty good. I've never programmed with pygtk - *but* I did play with Gajim (?) a Jabber client written with pygtk. The look and feel isn't native eaither - but it's very classy. It made me want to learn GTK ! I'll probably stick with Wax though. Gajim ahs a version bundled with py2exe - which definitley works. The only slight downer is that the user has to install the GTK+ runtime. (The wealth of chociues makes this *slightly* confusing for the complete noob). Best Regards, Fuzzy http://www.voidspace.org.uk/python From moranar at alice.it Sat Jul 30 09:22:47 2005 From: moranar at alice.it (Adriano Varoli Piazza) Date: Sat, 30 Jul 2005 13:22:47 GMT Subject: Comparison of functions In-Reply-To: References: Message-ID: Steven D'Aprano ha scritto: > On Sat, 30 Jul 2005 08:13:26 -0400, Peter Hansen wrote: > > >>Beginners should not be comparing lambdas. >> >>Neither should you. ;-) > > > Actually, yes I should, because I'm trying to make sense of the mess that > is Python's handling of comparisons. At least two difference senses of > comparisons is jammed into one, leading to such such warts as these: > > >>>>L = [] >>>>L.sort() # we can sort lists >>>>L.append(1+1j) >>>>L.sort() # even if they include a complex number >>>>L.append(1) >>>>L.sort() # but not any more > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= > > Um, I didn't ask to compare complex numbers using comparison operators. I > asked to sort a list. And please don't tell me that that sorting is > implemented with comparison operators. That just means that the > implementation is confusing numeric ordering with sort order. > > Then there is this: > > >>>>1 > 0 > > True > >>>>1+0j == 1 > > True > >>>>1+0j == 1 > 0 > > True > >>>>1+0j > 0 > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= > > I applaud that Python has got rich comparisons for those who need them. > But by confusing the question "which comes first in a sorted list?" with > "which is larger?", you get all sorts of warts like being unable to sort > lists with some objects, while being able to make meaningless > comparisons like ''.join >= [].append. > > I'm not sure what the solution to this ugly state of affairs is. I'm not > even sure if there is a solution. But I'm willing to make a good effort to > *look*, and even though you were joking, I don't appreciate being told > not to. As far as I recall from Math Analysis, which I studied two months ago, you can't sort complex numbers. It makes no sense. The reason being (reading from my book), it's not possible to define an order that preserves the properties of arithmetical operations on complex numbers. So you can't order them, and you can't compare them. -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar MSN: adrianomd at hotmail.com ICQ: 4410132 From jzgoda at gazeta.usun.pl Sun Jul 3 15:23:16 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 03 Jul 2005 21:23:16 +0200 Subject: PIL question: keeping metadata In-Reply-To: References: <42c2c4ca$0$8490$dbd41001@news.euronet.nl> <1120070384.278692.11180@g47g2000cwa.googlegroups.com> Message-ID: Ilpo Nyyss?nen napisa?(a): >>>Is there any way of keeping this info in PIL? >> >>I don't think so... when I investigated in the past, I think I >>discovered that the PIL can't write EXIF data (I might be wrong, >>though, or my information might be outdated). > > There is this: > > http://mail.python.org/pipermail/image-sig/2004-September/002931.html It would be nice to have general EXIF module, the one that is able to read and write image metadata. Consider such case: you want to rotate some image from digital camera, but don't want to remove completely the whole EXIF metadata -- modifying one field would be sufficient. -- Jarek Zgoda http://jpa.berlios.de/ From roy at panix.com Sat Jul 2 16:22:15 2005 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jul 2005 16:22:15 -0400 Subject: Determining actual elapsed (wall-clock) time References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: Peter Hansen wrote: > I would like to determine the "actual" elapsed time of an operation > which could take place during a time change, in a platform-independent > manner (at least across Linux/Windows machines). > > Using time.time() doesn't appear to be suitable, since time might jump > forwards or backwards at the user's whim, if the system clock is reset, > or when a daylight savings time change occurs. If you get the UTC time, daylight savings time doesn't enter the equation. If the system clock is reset, however, you're out of luck. I can't think of any time-related API which doesn't rely on the system clock as a reference. If the system clock is good, you get good time. If the system clock sucks, or changes, you don't. If you care about time, you want your system clock controlled by NTP. There's just no excuse not to. Is there some reason you can't just use the system clock? I suppose if you had to, you could hobble together your own NTP client which keeps network time independent of the system clock. But that would be a lot of work and it's hard to imagine the effort would be justified. From mwm at mired.org Sun Jul 31 15:22:26 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 15:22:26 -0400 Subject: multiple inheritance super() References: <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> <3ks3mrFvr5jkU1@individual.net> <1122653176.013770.106080@g49g2000cwa.googlegroups.com> <86br4ljnxs.fsf@bhuda.mired.org> <1122716129.428629.273960@g49g2000cwa.googlegroups.com> <86slxvh7qk.fsf@bhuda.mired.org> <1122788989.524732.40190@o13g2000cwo.googlegroups.com> Message-ID: <86slxug4r1.fsf@bhuda.mired.org> "Michele Simionato" writes: > Mike Meyer: >> I think you're replying to me, but you didn't include any indication >> so I can't be sure. > > Oops, sorry, yes, I was replying to you. > >> These two are cases of what I was talking about when I referred to the >> Church-Turing thesis. > > Well, let me put it in this way. If a language can implement a > missing feature easily, then you are not really missing a big thing. > And the feature may not be provided by default for sake of semplicity > and/or uniformity of style. For instance Python does not have > repeat-until > loops, case statement, ternary operator, etc. (obviously I am not > advocating to remove multiple inheritance now, I am justing > speculating, talking about an hypotetic new Python-like language). > >> Also, I don't see how they make the situation >> you are scared of above any better. > > It would discourage some people from some abuses, in the same sense the > absence of repeat-until, case statemente, ternary operator etc are > working right now. These two points are working at cross purposes. If you can implement a missing feature easily, then it doesn't do much to discourage abuses of that feature. >> > 3. think differently and use multimethods >> >> I don't see how that would help at all. You haven't done anything >> about solving the base problem - that getting the methods into my >> classes cleanly needs multiple inheritance. Further, I don't need >> methods that are distinguished based on their arguments - they all >> take a fixed set of arguments, and operate on them and the state of >> the instance. None seem to be candidates for being multimethods. The >> mixin methods tend to provide general functionality, and get used in >> radically different places by the different child classes. >> >> You did miss the one alternative I considered: making the methods of >> Mixin stand-alone functions, and passing them extra arguments instead >> of using attributes of the instance. They would all then look like >> mixin_func(self.foo, self.bar, var, value). I decided that this wasn't >> as readable as inherting the methods. > > Uhm? I do not follow you. Multimethods would dispatch according > to the type and would act differently on the childrens, dependending > on their state. Perhaps I would need more information to understand > what > you have in mind. Ok, let's take a typical Mixin example. All the classes work with HTML pages rendered as soup. Some of them only deal with one page, others walk through multiple pages to find some specific bit of information. Each of them stores the page it's currently working on in the attribute page. The get_value method of Mixin extracts a string from self.page. You pass it a string, it invokes methods of self.page to locate a string that stands in a fixed relation to the string you passed in to it, and returns the found string. I don't see how this could be made a multimethod. What it does doesn't change depending on selfs type. This example could trivially have been done as a standalone function, as it only uses one attribute. Others use more, say filling out forms based on a dictionary attribute, or some such. > But at the end my point is "I would not feel much more constrained > in expressivity if I did not have multiple inheritance in Python, > and actually I have found out that the more I use OOP, the less I > use inheritance". > > Just curious if others had a similar experience. No, and yes. I think that using less inheritance as you get more practice with it is a common thing. At first, it seems very cool, and you're tempted to use it for everything. Then you find the problems that this creates, and back off from it some. On the other hand, as my understanding of inheritance deepened, I found myself using multiple inheritance more, not less. Mostly, it's for mixins. Sometimes, I really do need objects that have multiple types. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From thorsten at thorstenkampe.de Sun Jul 10 08:05:17 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 10 Jul 2005 13:05:17 +0100 Subject: Newbie Alert! Upgrading Python? References: Message-ID: <9xmcrg2yrg10$.dojk9yjyhf4i$.dlg@40tude.net> * El (2005-07-10 11:56 +0100) > Sorry to bother you folks with a real newbie question, but I am sure that > this is the place for me to ask. > > Python 1.5.1 (final) and Python Win32 Extensions are installed on my 4 year > old computer. My computer has always been upgraded to include the latest > programs and Windows updates. > > However, I have NEVER upgraded Python? Is that a question? > Therefore, my questions: > > 1. Should I upgrade to the new Python 2.4.1 (Final)? No, why? > 2. If so, should I uninstall the old version first and reboot, or can I > just install the new version over the old version? No. > 3. Are the Win32 extensions included in the final version, or are the > extensions a separate download? No, yes. > I do not use Python, but I am assuming that something on my computer must. > LOL. If you don't use it: uninstall Python. If something else uses it: keep it as it is as your app might break with the new Python - even though 2.4 is backwards compatible. From __peter__ at web.de Thu Jul 14 15:10:07 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Jul 2005 21:10:07 +0200 Subject: Tkinter Button widget References: Message-ID: Shankar Iyer (siyer at Princeton.EDU) wrote: > I have another Tkinter-related question. At the beginning of my > program, a tkinter window is created with six buttons. Each of these > buttons is assigned a function that should be executed only when the > button is pressed. However, it seems that these functions are all > executed once when the button widgets are first created. Why is this > the case and how do I prevent this from happening? Change your source code from # wrong button = Tkinter.Button(..., command=some_function(),...) to # correct button = Tkinter.Button(..., command=some_function,...) to pass the *function* to the widget instead of the *result* of a function call. And, next time, remember to post some code alongside with your question. Peter From peter at engcorp.com Sat Jul 30 17:53:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Jul 2005 17:53:05 -0400 Subject: A replacement for lambda In-Reply-To: <7xr7dgnmiw.fsf@ruckus.brouhaha.com> References: <867jf9jmfw.fsf@bhuda.mired.org> <42EB3854.5000006@tiscali.it> <3l1blnF10c1i9U1@individual.net> <7xr7dgnmiw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > How's this: f{args} (curly braces instead of parens) is the same as > f(lambda: args). > > Examples: > > launch_thread{targetfunc(a,b,c)} > b = Button{callback=pressed()} # Button remembers callback() > sign_of_a = ternary{a < 0, -1, 1} I'd consider this an interesting idea if it weren't for the fact that (at least with the fonts I generally use) I can barely make out the difference between the {} and the () above. -Peter From kbk at shore.net Fri Jul 29 00:47:31 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 29 Jul 2005 00:47:31 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200507290447.j6T4lVHG006970@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 357 open ( +7) / 2885 closed ( +3) / 3242 total (+10) Bugs : 898 open ( +9) / 5144 closed ( +3) / 6042 total (+12) RFE : 191 open ( +2) / 178 closed ( +0) / 369 total ( +2) New / Reopened Patches ______________________ shutil.copytree() quits too soon after an error. (2005-07-21) http://python.org/sf/1242454 opened by Dale Wilson bltinmodule.c whitespace normalization (2005-07-21) http://python.org/sf/1242579 opened by Ruslan Spivak repair typos (2005-07-22) CLOSED http://python.org/sf/1243081 opened by George Yoshida Faster output if message already has a boundary (2005-07-23) http://python.org/sf/1243654 opened by L. Peter Deutsch httplib gzip support (2005-07-23) http://python.org/sf/1243678 opened by Moonz Big speedup in email message parsing (2005-07-23) http://python.org/sf/1243730 opened by L. Peter Deutsch Patch for (Doc) #1243553 (2005-07-24) http://python.org/sf/1243910 opened by Peter van Kampen expat binding for XML_ParserReset (Bug #1208730) (2005-07-24) http://python.org/sf/1244208 opened by John Eikenberry Enable os.startfile and webbrowser.WindowsDefault on Cygwin (2005-07-25) http://python.org/sf/1244861 opened by Michael Hoffman hide tests from TestProgram (2005-07-25) http://python.org/sf/1244929 opened by Eric Huss Encoding alias "unicode-1-1-utf-7" (2005-07-26) http://python.org/sf/1245379 opened by Oren Tirosh weaklist (2001-11-30) http://python.org/sf/487738 reopened by fdrake Patches Closed ______________ optparse documentation bug fixes (2005-05-18) http://python.org/sf/1204347 closed by gward repair typos (2005-07-22) http://python.org/sf/1243081 closed by birkenfeld fileinput.py fixed clobbering behavior and added encodings (2004-10-15) http://python.org/sf/1048075 closed by cconnett Allow use of embedded Tcl without requiring Tk (2004-01-02) http://python.org/sf/869468 closed by gvanrossum New / Reopened Bugs ___________________ list(obj) can swallow KeyboardInterrupt (2005-07-22) http://python.org/sf/1242657 opened by Steve Alexander Incorrect documentation of re.UNICODE (2005-07-22) http://python.org/sf/1243192 opened by nhaldimann Misuse of "it's" (2005-07-22) CLOSED http://python.org/sf/1243288 opened by Joanne Bogart pydoc on cgi.escape lacks info that are in www docs (2005-07-23) http://python.org/sf/1243553 opened by Nikos Kouremenos Python function/method/constant names as HTML-tag IDs (2005-07-24) http://python.org/sf/1243945 opened by Chad Miller 2.4.1 build fails on OpenBSD 3.7 (2005-07-25) http://python.org/sf/1244610 opened by L. Peter Deutsch logging module needs to that it changed in 2.4 (2005-07-25) http://python.org/sf/1244683 opened by Alan Segfault in Python interpreter 2.3.5 (2005-07-25) http://python.org/sf/1244864 opened by Evil Mr Henry Time module is missing inverse of gmtime() (2005-07-26) http://python.org/sf/1245224 opened by Jeremy Fincher log() on a big number fails on powerpc64 (2005-07-26) http://python.org/sf/1245381 opened by Jiri Dluhos Segmentation fault when importing expat from xml.parser (2005-07-28) http://python.org/sf/1246405 opened by Jean-Pierre line numbers off by 1 (2005-07-27) http://python.org/sf/1246473 opened by Brett Cannon failure to build RPM on rhel 3 (2005-07-28) http://python.org/sf/1246900 opened by Patrick Wagstrom Bugs Closed ___________ Misuse of "it's" (2005-07-22) http://python.org/sf/1243288 closed by birkenfeld ioctl has problem with -ive request codes (2005-07-01) http://python.org/sf/1231069 closed by mwh ioctl has problems on 64 bit machines (2005-01-31) http://python.org/sf/1112949 closed by birkenfeld From andre.roberge at gmail.com Sat Jul 2 12:13:46 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 2 Jul 2005 09:13:46 -0700 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <1120320826.195827.286500@z14g2000cwz.googlegroups.com> Scanning quickly through the various response, I noticed that at least one person suggested rur-ple (rur-ple.sf.net), hence Python. I would second that ;-) ... but then, I am biased as the author of rur-ple! rur-ple is intended to be a complete learning environment for learning programming and Python for complete beginners. At the core of it are a set of lessons (about 40 so far). Before the end of the summer, rur-ple should include a complete tutorial on writing games using Python (and pygames). My goal is for rur-ple to be usable by 10 years old (with guidance) and young adults (by themselves) to learn about programming. Check it out ... and let me know what appeals to you (if anything) and what doesn't. It's free :-) Andr? From falcon3166 at hotmail.com Sat Jul 9 15:31:08 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 13:31:08 -0600 Subject: Another newbie question from Nathan. References: <42c63341$0$6997$b9fe7a78@news.usenetrevolution.com> Message-ID: <42d02601$0$6916$b9fe7a78@news.usenetrevolution.com> Hi all, How do I make Python get a def? Is it the "get" function, or something else? I need to know so that I can get a def for that computer MasterMind(tm) game that I'm writing. BTW, I took your advice, and wrote some definitions for my Giant Calculator program. Might make the code easier to read, but harder to code because I have to keep going to the top to read the menu. Not that fun, but necessary for a smooth program, I guess. Nathan Pinno "Steven D'Aprano" wrote in message news:pan.2005.07.03.02.30.28.82992 at REMOVETHIScyber.com.au... > On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote: >> Hi all. >> How do I make the computer generate 4 random numbers for the guess? I want >> to know because I'm writing a computer program in Python like the game >> MasterMind. > First you get the computer to generate one random number. Then you do it > again three more times. > If you only need to do it once, you could do it this way: > import random # you need this at the top of your program > x0 = random.random() > x1 = random.random() > x2 = random.random() > x3 = random.random() > But if you need to do it more than once, best to create a function that > returns four random numbers in one go. > def four_random(): > """Returns a list of four random numbers.""" > L = [] # start with an empty list > for i in range(4): > L.append(random.random()) > return L > and use it this way: > rand_nums = four_random() > # rand_nums is a list of four numbers > print rand_nums[0] # prints the first random number > print rand_nums[3] # prints the last one > or like this: > alpha, beta, gamma, delta = four_random() > # four names for four separate numbers > Steven. > http://mail.python.org/mailman/listinfo/python-list -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From darkcowherd at gmail.com Sat Jul 23 12:32:57 2005 From: darkcowherd at gmail.com (Dark Cowherd) Date: Sat, 23 Jul 2005 22:02:57 +0530 Subject: Python vs. Access VBA In-Reply-To: <20050717154827.GA13128@computer.org> References: <25d2a751c10240bfb69f2ae36d5255e7@leafe.com> <20050717154827.GA13128@computer.org> Message-ID: <5f4d3cb50507230932ec934f8@mail.gmail.com> > better to go with SQLite. Its cross platform and well proven. I think > Firebird will give you that too, though I have never used it. > Firebird is a great option, cross platform, it can work like access without any server running, using embedded mode to a full blown server which can handle terabytes of data. -- Dark Cowherd From gsakkis at rutgers.edu Thu Jul 14 01:22:29 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 14 Jul 2005 01:22:29 -0400 Subject: Consecutive Character Sequences References: Message-ID: <1121318559.d582247e6e25443e247191d29f60b3b0@teranews> "Walter Brunswick" wrote: > Is there any way to [efficiently] iterate through a sequence of characters to find N [or more] consecutive equivalent characters? > > So, for example, the string "taaypiqee88adbbba" would return 1 if the number (of consequtive characters) supplied in the parameters > of the function call was 2 or 3, because "a", "e", 8, and "b" is repeated 2 or 3 times. > > Thanks for any assistance. > W. Brunswick. If you're in 2.4, use itertools.groupby: import itertools as it def hasConsequent(aString, minConsequent): for _,group in it.groupby(aString): if len(list(group)) >= minConsequent: return True return False George From nick.mountford at gmail.com Fri Jul 1 20:22:58 2005 From: nick.mountford at gmail.com (Nick Mountford) Date: Fri, 1 Jul 2005 21:22:58 -0300 Subject: Seeking IDE In-Reply-To: References: Message-ID: Thanks a lot for all the suggestions. I?m ising IDLE and trying to get into eclipse. Cheers, Nick On 6/30/05, Nick Mountford wrote: > Hi, > > Complete newb to Python and programming, looking for an open source > IDE to download. Any suggestions? > > Thanks, > > Nick > From ramen at lackingtalent.com Tue Jul 12 20:39:50 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 12 Jul 2005 17:39:50 -0700 Subject: Creating anonymous functions using eval In-Reply-To: References: <20050712120218.53d28b44.jules@REMOVETHIS.op59.net> <1121182125.554486.316880@z14g2000cwz.googlegroups.com> <1121184988.996652.126350@g47g2000cwa.googlegroups.com> Message-ID: Joseph Garvin wrote: > Robert Kern wrote: > >> Not everyone is reading this list in a conveniently threaded form >> >> > Why not? Just about every modern newsgroup reader and e-mail app has a > threaded view option. My newsreader supports threading, but the first message I see in this thread is from Devan L. I didn't notice the "Re:" and assumed his post was half in the subject line and half in the body. Sometimes I only download the 100 most recent posts, so I don't see the original (or referred-to) post. Other times the threading doesn't work properly, splitting conversations or using the wrong level of indentation. Also, this is both a newsgroup and a mailing list, and that has adverse effects on threading as well. So, please quote. =) Dave From phawkins at connact.com Fri Jul 22 22:30:31 2005 From: phawkins at connact.com (Patricia J. Hawkins) Date: Fri, 22 Jul 2005 22:30:31 -0400 Subject: Question about namespaces and import. How to avoid calling os.system References: <42e14753$0$27392$39db0f71@news.song.fi> Message-ID: >>>>> "PN" == Pekka Niiranen writes: PN> Hi there, PN> I have two scripts. The first "main.py" sets some variables PN> and then imports another called "gen.py". The idea is to PN> provide "main.py" that defines some paths, variables etc. PN> without using Windows environment variables. Various other "hackers" PN> will make additional Python scripts (subroutines) like "gen.py" PN> that utilize variables set by the "main.py" and which "main.py" calls. PN> I can do this with "subprocess" module by setting its env -variable PN> but I try to avoid calling shell. How can I merge temporary PN> the namespaces of the two modules? The built-in execfile should do the trick. -- Patricia J. Hawkins Hawkins Internet Applications www.hawkinsia.com From pythonmailing at web.de Sun Jul 24 15:27:43 2005 From: pythonmailing at web.de (Marek Kubica) Date: Sun, 24 Jul 2005 21:27:43 +0200 Subject: Detecting computers on network References: Message-ID: Hello! On Fri, 22 Jul 2005 10:32:04 -0600 Sandeep Arya wrote: > Sybren.. Does nmap is available on every systems? I tried on my linux fc4 > machine in user previleage. it was not working. Does this just belongs to > superuser... I'm not Sybren, but I think I'm able to respond. nmap is only available if it is installed on the system, on Debian you would need to install the package nmap first. It is not really a good idea hoping nmap to be installed. You can use nmap as a normal user, but some advanced scanning options are reserved for superuser. greets, Marek From daniel.einstein at pnl.gov Mon Jul 25 13:52:43 2005 From: daniel.einstein at pnl.gov (Einstein, Daniel R) Date: Mon, 25 Jul 2005 10:52:43 -0700 Subject: Reading binary with header Message-ID: <0DF798CBF125BF4AA1227F26431C29BD01A32F31@pnlmse27.pnl.gov> Hello, I am trying to head in a binary file that has a header and different character types. The array module apparently expects the typecode to be the same throughout. Here's what the file looks like: Byte number: type: value: purpose: 1-4 char "ver." 5-8 char "0001" version number 9-12 int 1, 2, 3, or 4 data type: 1=unsigned byte 2=unsigned short 3=32-bit integer 4=32-bit floating point 13-16 int x dimension, xdim 7-20 int y dimension, ydim 20-24 int z dimension, zdim 25-28 int xdim*ydim*zdim The rest of the file contains the data array of type in indicated in bytes 9-12. I have tried: import Numeric as N import array fileobj = open(myfile, mode='rb') s = array.array('f') s.read(fileobj, size) data = N.array(s, typecode=N.Int) fileobj.close() But the header must confuse things because I do get what I expect. Any advice? Best Regards, Dan Daniel R Einstein, PhD Biological Monitoring and Modeling Pacific Northwest National Laboratory P.O. Box 999; MSIN P7-59 Richland, WA 99352 Tel: 509/ 376-2924 Fax: 509/376-9064 daniel.einstein at pnl.gov -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Tue Jul 5 12:33:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 05 Jul 2005 10:33:39 -0600 Subject: Python Regular Expressions: re.sub(regex, replacement, subject) In-Reply-To: References: Message-ID: Vibha Tripathi wrote: > In the Python re.sub(regex, replacement, subject) > method/function, I need the second argument > 'replacement' to be another regular expression ( not a > string) . So when I find a 'certain kind of string' in > the subject, I can replace it with 'another kind of > string' ( not a predefined string ). Note that the > 'replacement' may depend on what exact string is found > as a result of match with the first argument 'regex'. > > Please let me know if the question is not clear. It's still not very clear, but my guess is you want to supply a replacement function instead of a replacement string, e.g.: py> help(re.sub) Help on function sub in module sre: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used. py> def repl(match): ... print match.group() ... return '46' ... py> re.sub(r'x.*?x', repl, 'yxyyyxxyyxyy') xyyyx xyyx 'y4646yy' STeVe From donn at drizzle.com Sat Jul 9 01:57:38 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 09 Jul 2005 05:57:38 -0000 Subject: PPC floating equality vs. byte compilation Message-ID: <1120888655.953163@yasure> I ran into a phenomenon that seemed odd to me, while testing a build of Python 2.4.1 on BeOS 5.04, on PowerPC 603e. test_builtin.py, for example, fails a couple of tests with errors claiming that apparently identical floating point values aren't equal. But it only does that when imported, and only when the .pyc file already exists. Not if I execute it directly (python test_builtin.py), or if I delete the .pyc file before importing it and running test_main(). For now, I'm going to just write this off as a flaky build. I would be surprised if 5 people in the world care, and I'm certainly not one of them. I just thought someone might find it interesting. The stalwart few who still use BeOS are mostly using Intel x86 hardware, as far as I know, but the first releases were for PowerPC, at first on their own hardware and then for PPC Macs until Apple got nervous and shut them out of the hardware internals. They use a Metrowerks PPC compiler that of course hasn't seen much development in the last 6 years, probably a lot longer. Donn Cave, donn at drizzle.com From steve at REMOVETHIScyber.com.au Sat Jul 23 22:30:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 12:30:26 +1000 Subject: tuple to string? References: <42E0EED4.4020001@gmx.net> <42e2457a@news.eftel.com> Message-ID: On Sat, 23 Jul 2005 23:26:19 +1000, John Machin wrote: > Steven D'Aprano wrote: > >> >> >>>>>''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D))) >> >> 'spam' > > Why the verbal diarrhoea? One line is hardly verbal diarrhoea. > What's wrong with the (already posted) > > ''.join(map(chr, (0x73, 0x70, 0x61, 0x6D))) > > ??? Nothing. If I had seen the already posted solution using chr on its own without lambda, I wouldn't have bothered posting the lambda solution. But I didn't, so I did. As another poster has already pointed out, lambda cries out for over-use, and this was a perfect example of it. -- Steven. From spam.csubich+block at block.subich.spam.com Fri Jul 22 00:26:16 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Fri, 22 Jul 2005 00:26:16 -0400 Subject: Help with regexp please In-Reply-To: <42e069ef$1@nntp0.pdx.net> References: <42e069ef$1@nntp0.pdx.net> Message-ID: <4z_De.13539$Wt3.3395@bignews3.bellsouth.net> Scott David Daniels wrote: > Felix Collins wrote: >> I have an "outline number" system like >> 1 >> 1.2 >> 1.2.3 >> I want to parse an outline number and return the parent. > > Seems to me regex is not the way to go: > def parent(string): > return string[: string.rindex('.')] Absolutely, regex is the wrong solution for this problem. I'd suggest using rsplit, though, since that will Do The Right Thing when a top-level outline number is passed: def parent(string): return string.rsplit('.',1)[0] Your solution will throw an exception, which may or may not be the right behaviour. From reinhold-birkenfeld-nospam at wolke7.net Sun Jul 24 08:43:18 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 24 Jul 2005 14:43:18 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kehbmFtv6lpU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> Message-ID: <3khgn6Fu8nm8U1@individual.net> Reinhold Birkenfeld wrote: > Hi, > > the arguments in the previous thread were convincing enough, so I made the > Path class inherit from str/unicode again. Further changes by now: * subdirs() is now dirs(). * fixed compare behaviour for unicode base (unicode has no rich compare) * __iter__() iterates over the parts(). * the following methods raise NotImplemented: capitalize, expandtabs, join, splitlines, title, zfill Open issues: What about the is* string methods? What about __contains__ and __getitem__? What about path * 4? Reinhold From me at privacy.net Sat Jul 30 20:12:25 2005 From: me at privacy.net (Dan Sommers) Date: Sat, 30 Jul 2005 20:12:25 -0400 Subject: showing help(M) when running module M standalone References: Message-ID: On Sat, 30 Jul 2005 22:02:49 +0200, Chris wrote: > I tried that, problem is that __all__ containts strings... Oops. I should have looked before I lept. Sorry, Dan -- Dan Sommers From t-meyer at ihug.co.nz Fri Jul 29 01:54:06 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 29 Jul 2005 17:54:06 +1200 Subject: Ten Essential Development Practices In-Reply-To: Message-ID: [Robert Kern] > Sure, and I can find programming advice in the Old Testament, > too, if I try hard enough [...] > Proverbs 28:14 JPS "Happy is the man that feareth alway; > but he that hardeneth his heart shall fall into evil." > Obviously an exhortation to not ignore raised exceptions with > "except: pass". +1 QOTW. =Tony.Meyer From sybrenUSE at YOURthirdtower.com.imagination Fri Jul 22 03:58:25 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 22 Jul 2005 09:58:25 +0200 Subject: wxPython & Fedora Core 4 References: <1122005756.744692.285840@f14g2000cwb.googlegroups.com> Message-ID: linuxfreak enlightened us with: > Has anyone installed wxPython on Fedora Core 4. Apparently it need > the libstdc++.so.5 file while Fedora installs the newer > libstdc++.so.6 [...] Fedora does not allow multiple versions of the > same file. Try Ubuntu Linux, which does allow having libstdc++.so.5 and .6 installed, on the same system, using the package manager. Fedora _does_ allow multiple versions of that library, but apparently not via it's package manager. Nobody is stopping you from getting the file and putting it on your system. You could also recompile the wxPython RPMs, so they link to your version of the library. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From me at privacy.net Sat Jul 30 20:17:06 2005 From: me at privacy.net (Dan Sommers) Date: Sat, 30 Jul 2005 20:17:06 -0400 Subject: showing help(M) when running module M standalone References: Message-ID: On Sat, 30 Jul 2005 22:02:49 +0200, Chris wrote: > I tried that, problem is that __all__ containts strings... Okay, that's twice I've lept before I looked. How about this: for a in __all__: print globals()[a].__doc__ HTH, Dan -- Dan Sommers From me at privacy.net Sun Jul 17 06:05:06 2005 From: me at privacy.net (Stephen Illingworth) Date: Sun, 17 Jul 2005 11:05:06 +0100 Subject: SSL problem... SSL23_GET_SERVER_HELLO:unknown protocol In-Reply-To: References: Message-ID: John Reese wrote: > Morning. I've been running into an error message pertaining to SSL > that I don't understand, and I was hoping someone had some insight. > Gmail provides POP access over SSL on port 587, so I tried to use > poplib.POP_SSL, with the following results: GMail uses port 995. From grante at visi.com Tue Jul 12 11:35:50 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Jul 2005 15:35:50 -0000 Subject: Web client, https and session management References: <1121182118.684389.182950@g14g2000cwa.googlegroups.com> Message-ID: <11d7oqmr47jc53@corp.supernews.com> On 2005-07-12, Yannick Turgeon wrote: > To acheive point #3, which is the goal, my web client has to manage > session (because of the login aspect). This is the part I don't know > how it's working. You might want to take a look at the ClientCookie package. -- Grant Edwards grante Yow! Then, it's off to at RED CHINA!! visi.com From duncan.booth at invalid.invalid Mon Jul 4 09:07:02 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Jul 2005 13:07:02 GMT Subject: OT: ^ in redirection (windows) References: Message-ID: Miki Tebeka wrote: > Can someone explain me the difference between: > echo 1 > 1.txt 2>&1 > and > echo 1 > 1.txt 2>^&1 > > (Windows XP "cmd" shell) > > Both produce 1.txt with the content 1. > > (Sadly, I don't know how to search for ^ in google). > The first of these joins stderr to stdout, but since there is no output to stderr has no visible effect. The second should prevent special treatment of the & character, but in this particular case actually has no effect. You can see the effects more clearly if you redirect a handle which actually does have some output: stdout redirected to stderr, but stderr still goes to console so no visible effect: C:\temp>echo hi 1>&2 hi stdout redirected to stderr, then stderr redirected to a file, but stdout still points at original stderr so no visible effect: C:\temp>echo hi 1>&2 2>x.txt hi stderr redirected to a file, then stdout redirected to same file. Output goes in a file: C:\temp>echo hi 2>x.txt 1>&2 C:\temp>type x.txt hi Same as above. Using ^ to avoid special interpretation of the & has no effect: C:\temp>echo hi 2>x.txt 1>^&2 C:\temp>type x.txt hi From kay.schluehr at gmx.net Mon Jul 11 11:56:51 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Jul 2005 08:56:51 -0700 Subject: decorators as generalized pre-binding hooks In-Reply-To: <%2uAe.59388$Tt.29694@bignews3.bellsouth.net> References: <42d02c21.231516573@news.oz.net> <1121034087.932596.221010@g43g2000cwa.googlegroups.com> <1121084778.253840.101070@z14g2000cwz.googlegroups.com> <%2uAe.59388$Tt.29694@bignews3.bellsouth.net> Message-ID: <1121097411.819656.141410@f14g2000cwb.googlegroups.com> Christopher Subich schrieb: > Kay Schluehr wrote: > > I think it would be a good idea to pronounce the similarity between > > function decorators and metaclasses. Metaclasses were once introduced > > as an arcane art of fuzzy bearded hackers or supersmart 'enterprise > > architects' that plan at least products of Zope size but not as a tool > > for the simple programmer on the street. But maybe they should be and > > there should also be librarys of them representing orthogonal > > customizations ready for plug in. > > In which case, I point out the need for better, more accessible > documentation. The Python 2.4 tutorial, for example, doesn't mention > them at all as far as I've noticed. That's true also for properties and decorators - the latter may be excused because they are new in Python 2.4. There are a few good documents out there explaining advanced stuff e.g. mro and descriptors. Maybe those texts should be delivered with the doc and linked from the tutorial as "further reading"? But maybe the whole document structure could be redesigned providing a Wikipedia style with seperated but linked articles, example code etc. ? Kay From bokr at oz.net Sun Jul 24 01:03:31 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 05:03:31 GMT Subject: Filtering out non-readable characters References: <1121561305.19f79973c756191072ea0e5d9ae8e2b2@teranews> <1121570966.6b3e122aacf94730620c39031b3c126b@teranews> <1121650348.789315.133660@z14g2000cwz.googlegroups.com> Message-ID: <42e32106.996869672@news.oz.net> On 17 Jul 2005 18:32:28 -0700, "Raymond Hettinger" wrote: >[George Sakkis] >> It's only obvious in the sense that _after_ you see this idiom, you can go back to the docs and >> realize it's not doing something special; OTOH if you haven't seen it, it's not at all the obvious >> solution to "how do I get the first 256 characters". So IMO it should be mentioned, given that >> string.translate often operates on the identity table. I think a single sentence is adequate for the >> reference docs. > >For Py2.5, I've accepted a feature request to allow string.translate's >first argument to be None and then run as if an identity string had >been provided. > My news service has been timing out on postings, but I had a couple that made reference to that ;-) Maybe this post will get through. Regards, Bengt Richter From steven.bethard at gmail.com Fri Jul 8 20:32:04 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Jul 2005 18:32:04 -0600 Subject: removing list comprehensions in Python 3.0 In-Reply-To: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> References: <1120868074.326547.48760@o13g2000cwo.googlegroups.com> Message-ID: Devan L wrote: > List comprehensions are faster than generator comprehensions for > iterating over smaller sequences. Could you give me an example? For the simple one below, the generator expression was faster: $ python -m timeit "for x in (i for i in xrange(10)): y = x" 100000 loops, best of 3: 4.75 usec per loop $ python -m timeit "for x in [i for i in xrange(10)]: y = x" 100000 loops, best of 3: 5.33 usec per loop And for another one, the results are basically indistinguishable: $ python -m timeit "for x in (i for i in 'abcdefg'): y = x" 100000 loops, best of 3: 3.82 usec per loop $ python -m timeit "for x in [i for i in 'abcdefg']: y = x" 100000 loops, best of 3: 3.87 usec per loop I vaguely remember that in Python 2.4 conversion to tuples can take longer because of the tuple extension code: $ python -m timeit "tuple(i for i in xrange(10000))" 100 loops, best of 3: 2.24 msec per loop $ python -m timeit "tuple([i for i in xrange(10000)])" 100 loops, best of 3: 1.85 msec per loop But IIRC, this is supposed to be fixed in Python 2.5. I found that for some longer sequences, generator expressions were notably faster: $ python -m timeit "set(i for i in xrange(10000))" 100 loops, best of 3: 3.77 msec per loop $ python -m timeit "set([i for i in xrange(10000)])" 100 loops, best of 3: 4.54 msec per loop Timings that validate your statement would be appreciated. ;) STeVe From could.net at gmail.com Fri Jul 15 10:06:44 2005 From: could.net at gmail.com (could ildg) Date: Fri, 15 Jul 2005 22:06:44 +0800 Subject: How can I import a py script by its absolute path name? In-Reply-To: <20050714132750.GA6065@computer.org> References: <87eka1eha8.fsf@titan.staselog.com> <20050714132750.GA6065@computer.org> Message-ID: <311b5ce105071507066040f87c@mail.gmail.com> Thank you for your help. It's really useful for me. On 7/14/05, Chris Lambacher wrote: > You probably actually want: > > import sys > sys.path.instert(0, r'c:\xxx\yyy') > m = __import__('zzz', globals(), locals(), []) > del sys.path[0] > > Because if another module named zzz exists in your path. Appending will pick > those versions up first. Then you delete the path you just added so that you > don't have any problems importing other modules that may have the same names a > python files in the path you just added. > > -Chris > On Thu, Jul 14, 2005 at 02:52:31PM +0300, Edvard Majakari wrote: > > could ildg writes: > > > > > I want to import c:\xxx\yyy\zzz.py into my programme, > > > What should I do? > > > Thank you~ > > > > import sys > > sys.path.append('c:\xxx\yyy') > > import zzz > > > > (Untested, similar idiom would work in *nix systems, never programmed in > > Windows) > > > > However, I guess it is not very usual you should need to import stuff from > > arbitrary locations. Consider publishing those modules in normal Python > > include path (just see what ''print sys.path'' produces) > > > > -- > > # Edvard Majakari Software Engineer > > # PGP PUBLIC KEY available Soli Deo Gloria! > > > > $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print > > join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; > > -- > > http://mail.python.org/mailman/listinfo/python-list > -- > http://mail.python.org/mailman/listinfo/python-list > From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 5 15:38:17 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 5 Jul 2005 21:38:17 +0200 Subject: Good starterbook for learning Python? References: <2ar939q1r9bm.x5zf9wfdcfmy$.dlg@40tude.net> Message-ID: Lennart enlightened us with: > Can someone advice me with the following issue: i want to learn > python in my summer vacation (i try to ...:-) So, a good start is > buying a good book. But wich? There are many ... http://www.diveintopython.org/ - I read it during the weekend, and it's a very good book. Clearly written, good examples and a healthy dose of humor. > I'm living in the Netherlands and I prefer a book from bol.com (see link) > because i've to order more books by them. Dive Into Python can be freely downloaded. > Search here for python (sorry, there's no short link) Yes there is. Check http://tinyurl.com/ Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From xen0n at vodafone.it Wed Jul 20 09:05:42 2005 From: xen0n at vodafone.it (xen0n at vodafone.it) Date: 20 Jul 2005 06:05:42 -0700 Subject: Python s60 Contact DB In-Reply-To: References: <1121780830.418009.176650@o13g2000cwo.googlegroups.com> Message-ID: <1121864741.929328.150260@o13g2000cwo.googlegroups.com> I have already posted the question to the Nokia forum, but, for now, noone seems to have an answer... Hope this is a bug of py2sis... I dont want to rewrite my entire application for a stupid bug! could ildg ha scritto: > You should raise this question at Nokia python for series60 forum, > I'm sure you can the answer there. > http://discussion.forum.nokia.com/forum/forumdisplay.php?s=85e4c1acee330fddde6b47a7b2feae73&forumid=102 > > > On 19 Jul 2005 06:47:10 -0700, xen0n at vodafone.it wrote: > > Hi, i hope the expert can help me! > > I have a little problem: > > > > This piece of code, in python console s60, before compiling will work > > great: > > > > try: > > ..db = contacts.open() > > ..names = [] > > ..numbers = [] > > > > The problem is that, if i compile it with py2sis (pyrsc_template.tmp > > replaced with the original to solve the submenus bug) it doesnt work, > > when that piece of code is executed, i receive error -50 and nothing > > happen! hope u can help me! 10ks a lot in advance > > > > Regards. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From falcon3166 at hotmail.com Sun Jul 3 02:37:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 3 Jul 2005 00:37:36 -0600 Subject: What's wrong with this code? References: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> <42C72848.9020609@lexicon.net> Message-ID: <42c787b8$0$6966$b9fe7a78@news.usenetrevolution.com> Hi all, Sure I'm able to publish the code, only the previous version though. If you want the first version; find Josh Cogliati, and ask him. It didn't have a random function, though. I got the idea to improve it from my computer course. Here is the code: #Plays the guessing game higher or lower # (originally written by by Josh Cogliati, improved by Quique) #This should actually be something that is semi random like the last digits of the time or something else. number = 78 guess = 0 while guess != number: guess =input("Guess a number: ") if guess > number: print "Too high" elif guess < number: print "Too low" print "Just right" HTH, Nathan Pinno "John Machin" wrote in message news:42C72848.9020609 at lexicon.net... > Nathan Pinno wrote: > > Hi all, > > > > What's wrong with the following code? It says there is name error, that > > random is not defined. How do I fix it? > > Others have already answered that question. This posting is a > pre-emptive strike to head off the next half-a-dozen questions. > > > > > # Plays the guessing game higher or lower. > > # Originally written by Josh Cogliati, improved first by Quique, then by > > Nathan Pinno. > > Some of us are interested in the process by which great pieces of code > arise, how they are meticulously honed and polished, which craftpersons > contributed what ... is it possible for you to publish the earlier versions? > > > print "Higher or Lower" > > print > > number = random.choice(range(100)) > > "number" will refer to one of: 0, 1, ......, 98, 99 > > > guess = 0 > > so you'll get a strange result by using zero here; try -1 instead > > > while guess != number: > > guess = input("Guess a number: ") > > "guess" will refer to a string e.g. "42" which will *not* compare equal > to the integer 42. Also you should use raw_input, not input. > > so do this: > > guess = int(raw_input("Guess a number: ")) > > > if guess > number: > > print "Too high" > > guess = input("Guess a number: ") > > This will cause your program to ask TWICE per trip around the loop. Lose it. > > > elif guess < number: > > print "Too low" > > guess = input("Guess a number: ") > > ... and again. > > > print "Just right" > > > > General advice: > 1. Look on the Python web site (http://www.python.org) for an > introduction to Python for non-programmers. > 2. Join the Python tutor list. > 3. In this news group, read a little more than the threads that you have > started; this guessing game was discussed in a thread started by > somebody calling themselves ChuckDubya on 29 June!! Homework?? > > HTH, > John > > > -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From peter at engcorp.com Fri Jul 22 14:08:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 14:08:40 -0400 Subject: Python and Tablet PC: limitations? In-Reply-To: <1122051149.256485.209160@g44g2000cwa.googlegroups.com> References: <1122051149.256485.209160@g44g2000cwa.googlegroups.com> Message-ID: Andr? wrote: > I'm considering buying a Tablet PC and read somewhere (sorry, can't > point to a link) that someone had tried running a "standard" Python > program (wxMozilla demo I *think*, but can't be sure) that simply > crashed. > > Any happy Tablet PC user/Python programmer combo? If so, any word of > advice, suggestion as to best Tablet PC/accessory for a nice Python > programming environment? My laptop (using it to type this) is an Acer TravelMate C302 which is a "convertible" laptop and thus also a tablet running Windows XP Tablet Edition 2005 (SP2). I've never had the slightest problem running any kind of Python program due to it being a tablet. -Peter From danb_83 at yahoo.com Tue Jul 5 23:46:20 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Jul 2005 20:46:20 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> Message-ID: <1120621580.107813.47100@g43g2000cwa.googlegroups.com> Devan L wrote: > Claiming that sum etc. do the same job is the whimper of > someone who doesn't want to openly disagree with Guido. > > Could you give an example where sum cannot do the job(besides the > previously mentioned product situation? Here's a couple of examples from my own code: # from a Banzhaf Power Index calculator # adds things that aren't numbers return reduce(operator.add, (VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes)) # from a custom numeric class # converts a tuple of digits into a number mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) > Also, map is easily replaced. > map(f1, sequence) == [f1(element) for element in sequence] There's also the issue of having to rewrite old code. From fabioz at esss.com.br Tue Jul 26 12:00:43 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Tue, 26 Jul 2005 13:00:43 -0300 Subject: ANN: PyDev 0.9.7 released In-Reply-To: <5dmce19j3iqlpg65kt2cu426dnacgun05i@4ax.com> References: <42A720BD.5050701@esss.com.br> <42C175A5.5000206@esss.com.br> <5dmce19j3iqlpg65kt2cu426dnacgun05i@4ax.com> Message-ID: <42E65E2B.3050300@esss.com.br> That's s sort of an Eclipse issue... you have to disable it, restart eclipse and only then will an uninstall appear (it has something to do with some resources eclipse is not able to remove when the plugin is active). Cheers, Fabio Dennis Lee Bieber wrote: >On Tue, 26 Jul 2005 10:56:58 -0300, Fabio Zadrozny >declaimed the following in comp.lang.python: > > > >>Hi All, >> >>PyDev - Python IDE (Python Development Enviroment for Eclipse) version >>0.9.7 has just been released. >> >> >> > How nice... my dial-up system has been on all night downloading >and installing various optional packages, including 0.9.6 > > >>Note 1: Because of some issues with Eclipse, you have to uninstall all >>previous PyDev installations before installing the new release. >> >> > > Silly question -- but since I've only downloaded Eclipse et al >this week (and so, obviously, have no real experience with it), just how >/do/ I uninstall PyDev? I didn't see anything jump out of the menu >system -- disabling it, yes; removing it, no. > > > -- 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 From timr at probo.com Fri Jul 22 02:04:23 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 21 Jul 2005 23:04:23 -0700 Subject: How to limit the uploading file size in python? References: <20050720074406.10046.qmail@web8402.mail.in.yahoo.com> Message-ID: praba kar wrote: > > In Php we can limit the uploading file size >by php.ini configuration file. But In python what >way we can limit the file uploading size. >kindly let me know. Unlike PHP, Python is a general-purpose language that is not targetted specifically at the web, so it has no native concept of "uploading". You can do this by using the LimitRequestBody directive in your Apache configuration or .htaccess file. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From grig.gheorghiu at gmail.com Thu Jul 14 13:39:35 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 14 Jul 2005 10:39:35 -0700 Subject: Python Installation error on Solaris-9-SPARC In-Reply-To: References: Message-ID: <1121362775.799428.239840@g47g2000cwa.googlegroups.com> Why don't you donwload the source from python.org? Also, on Solaris tar is sometimes broken (i.e. can't deal with long directory names etc.) You may want to donwload and install gnu tar. Grig From peter at engcorp.com Fri Jul 29 17:08:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 17:08:01 -0400 Subject: Hiding In-Reply-To: <1122662993.207041.89630@f14g2000cwb.googlegroups.com> References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> <1122662993.207041.89630@f14g2000cwb.googlegroups.com> Message-ID: Jason Drew wrote: > Also, I think > using file("C:\file.txt") is now preferred to open("C:\file.txt"). As others have noted, "open" is preferred as the method for opening files, while "file" is the _type_ involved, for testing or subclassing or what-have-you. But neither file("C:\file.txt") nor open("C:\file.txt") is actually correct at all, unless you have strange files whose names start with ASCII FF characters. '\f' is an escape sequence, equivalent to '\x0c'. Always use forward slashes ("C:/file.txt") in path names unless you are passing them to the shell, or use raw strings (r"C:\file.txt") to avoid mysterious problems with escape sequences. -Peter From cyril.bazin at gmail.com Mon Jul 18 05:29:23 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Mon, 18 Jul 2005 11:29:23 +0200 Subject: What is your favorite Python web framework? In-Reply-To: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> References: <1121673160.754260.260280@z14g2000cwz.googlegroups.com> Message-ID: Hello, I never used a web framework using Python modules, but I think cheetah, Karrigel and CherryPy are not good since they allow user to play with the HTML code. IMO, it's not pythonic but phpythonic. Isn't there a python framework inspirated by the Smalltalk framework Seaside? I think it's the way to build a web site like an application and not like an HTML page. Cyril On 18 Jul 2005 00:52:40 -0700, laurent wrote: > > hello, > I follow somes projects that have a pythonic way to make web site. > there's thats projects : > http://www.cherrypy.org/ > and > http://subway.python-hosting.com/ > subway aim to be like ruby on rails frameworks , simple and fast > developpment. It uses cherrypy and other project like : > * http://www.cheetahtemplate.org/ > * http://www.formencode.org/ > * http://www.sqlobject.org/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nav+posts at bandersnatch.org Fri Jul 8 13:12:26 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 08 Jul 2005 13:12:26 -0400 Subject: Seeking IDE References: <1120155485.235706.204580@f14g2000cwb.googlegroups.com> Message-ID: <878y0hkyrp.fsf@localhost.localdomain> "Jags" writes: > If you don't like that, you could use any of the following editors: > EditPlus, TextPad, UltraEdit, WingIDE, Komodo (from ActiveState) or > jEdit. All these are Windows based. Komodo is available for Linux and Windows, and ActiveState will be releasing a version for OS X later this year. jEdit claims to run on many platforms since it's written in Java. WingIDE has downloads for Linux, OS X, and Windows. Personally, I favor (X)Emacs and zsh for my DE, but I'm one of those people who prefer a looser coupling between tools than you typically get with a monolithic IDE. Nick -- Nick Vargish :: http://nick.vargish.org From rwgk at yahoo.com Tue Jul 12 02:54:06 2005 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 11 Jul 2005 23:54:06 -0700 (PDT) Subject: __autoinit__ In-Reply-To: <86ll4csyn4.fsf@bhuda.mired.org> Message-ID: <20050712065406.11445.qmail@web31515.mail.mud.yahoo.com> --- Mike Meyer wrote: > Remember that what we're suggesting is just syntactic sugar. BTW: That's true for all high-level language constructs. You could do everything in machine language. A good language is the sum of lots of syntactic sugar... selected with taste. :) > You can > abuse things the same way by writing: > > class grouping: > def __init__(self, self.x, u_y, self.z): > u.y = u_y > del u_y > pass > > Why is this acceptable, but your usage not? Hmmm. Maybe this is where I'd draw the line: Effects of code in the *signature* must be restricted to self and locals(). self is special here because the whole purpose of the constructor is to initialize self; otherwise you'd use a plain function. Therefore it seems more than natural to provide special support. > > "self" (or whatever people prefer as a name for the first argument of a > bound > > function) *is* special. I think therefore it deserves special support. > > Yes, but is it special enough to justify adding a special case to > another construct? In my mind that's determined by the usage patterns as they arise in practice. A high degree of redundancy is the worst enemy of good, readable code. The language/framework definitely should help out here in some way. > I'm not sure I like the idea of allowing "self.x" yet. But if you're > going to allow it, I don't think it should be restricted. If that's the price I have to pay for the feature I am all for it. :) However, I feel we will get into a lot of trouble with the purists. They will tell us that side-effects are generally vicious. > The question is - how far are you really willing to carry this? What > do you think of allowing arbitrary lvalues, with the assumption that > the previous arguments are all defined (ala let*)? So you could do: > > class grouping: > def __init__(self, x, x['abc']): > pass > > > file_object, data sys.stdout = StringIO() show("hello, world.") If you run this, you will see "hello, world." on the screen. This means the right side of file_object=sys.stdout is evaluated when the Python code is parsed/compiled, not when it is executed. Cheers, Ralf __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From mwm at mired.org Sun Jul 31 00:59:18 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 31 Jul 2005 00:59:18 -0400 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> Message-ID: <86wtn7h8pl.fsf@bhuda.mired.org> Torsten Bronger writes: > Hall??chen! > Calvin Spealman writes: >> The choice is GUI toolkits is largely seperate from >> Python. Consider that they are just bindings to libraries that are >> developed completely seperate of the language. GUI is should be >> seperate from the language, and thus not bound to same >> expectations and desires as elements of the language itself. > I disagree. A modern language must provide a convenient and > well-embedded way to write GUI applications. I disagree. A modern development environment aimed at developers of desktop applications may be required to provide that; not being a developer of desktop applications, I'm not really qualified to say. A *language* doesn't need to provide that. I'd say that a language providing that would limit the language. Or cause it to branch when it got ported to platforms for which the graphics elements of the language were totally unsuitable. The tools for writing GUI applications belong in a library, not the langauge. > This is not a sign of decadence, but a very good promotional argument. But it's not required for the language to succeed. C and C++ are both doing very well without your a well-embedded way to write GUI applications. However, you can get compilers for both that come bundled with a good GUI library. Could it be that that's what you really want - someone to distribute Python bundled with an enterprise-class GUI library and IDE? > However, in my opinion we don't need yet another binding so thin > that C or C++ is shining through, but a modern replacement for > Tkinter with its Pythonic way of thinking. I don't particularly like Tkinter, but it seems to me that it's pretty much won. It seems to be installed on every desktop platform along with Python. That means that if I want to distribute GUI apps, I'm going to cause the least headache for my end users by writing them in Tkinter. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Thu Jul 14 08:37:31 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 14 Jul 2005 22:37:31 +1000 Subject: Inconsistency in hex() References: <7xpstmhwe5.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 13 Jul 2005 20:57:54 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> >>> hex(75) >> '0x4b' >> >>> hex(75*256**4) >> '0x4B00000000L' >> >> By accident or design? Apart from the aesthetic value that lowercase hex >> digits are ugly, should we care? > > Use ('%x' % 75) or ('%X' % 75) if you care. Ah! Now that's the sort of utterly obvious in hindsight thing that wouldn't have occurred to me in a month of Sundays. That's why c.l.p is so useful -- lots of people with lots of ways of doing things, all sharing. Thanks Paul. (Actually, I don't care at the moment, but when I do, I'll have a fix.) -- Steven. From paddy3118 at netscape.net Sat Jul 30 04:47:18 2005 From: paddy3118 at netscape.net (Paddy) Date: 30 Jul 2005 01:47:18 -0700 Subject: A replacement for lambda In-Reply-To: References: <867jf9jmfw.fsf@bhuda.mired.org> Message-ID: <1122713238.644818.171210@g49g2000cwa.googlegroups.com> Christopher Subich writes: > Basically, I'd rewrite the Python grammar such that: > lambda_form ::= "<" expression "with" parameter_list ">" I do prefer my parameter list to come before the expression. It would remain consistant with simple function definitions. - Cheers, Paddy. From reinhold-birkenfeld-nospam at wolke7.net Sat Jul 30 08:43:27 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Jul 2005 14:43:27 +0200 Subject: PEP on path module for standard library In-Reply-To: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> References: <1122669785.570129.169420@g14g2000cwa.googlegroups.com> Message-ID: <3l1avfF10i4kgU1@individual.net> Mike Orr wrote: > The main changes I'd like to see in Path (some of these have been made > in Python CVS at nondist/sandbox/path/path.py) are: Thanks for the comments! They are greatly appreciated. > - When methods create path objects, use self.__class__() instead of > Path(). > This makes it possible to subclass Path. Otherwise you > have to rewrite the whole thing due to the hardcoded name. > > - Path.cwd() should be a class method instead of a static method, for > the same > reason. Changed by now. > - The constructor behavior in CVS is good. Path(''), Path.cwd(), > Path() => Path.cwd(). Note that Path() results in os.curdir, while Path.cwd() results in the absolute current directory. > - Need .chdir() method, otherwise you have to import os for it. Added by now. > - Some way to pretty-print paths embedded in lists/dicts as strings. I > have a > .repr_as_str class attribute that toggles this. I think str() does its job nicely there. > - .ancestor(3) is the same as .parent.parent.parent, but more concise. Good proposal, will consider this. > - I saw in a thread that .name and .parent were removed. I use them > very > frequently, along with .ext and .namebase. I don't want to call > methods for > these. They are now named .basename and .directory. > - '/' vs .joinpath(), no big deal. I've been using '/' because it's > there. > .joinpath must take multiple *args, to prevent .joinpath().joinpath() > . That's already in. > - .joinancestor(N, *components) is a combination of .ancestor and > .joinpath. > If curdir is /home/joe/Webware/www, Path.cwd().joinancestor(1, 'lib') > is > /home/joe/Webware/lib. I think Path.cwd().parent.joinwith('lib') is readable enough. > - Keep .lisdir() as in CVS; it acts like os.listdir(). This is useful > even > with paths, when you're just going to use the string basename anyway. Right. In addition, it's confusing if os.listdir is behaving differently from Path.listdir(). > - Who needs .open()? open(myPath) is fine. But it can stay for > backward > compatibility. Right. I think it's nice for people who like a more OO approach. > Less important but non-controversial: > > - Path.tempfile(), Path.tempdir(): > Create a temporary file using tempfile.mkstemp, tempfile.mkdtemp > > - Path.tempfileobject(): > Create a temporary file object using tempfile.TemporaryFile. > (Static method.) Don't know whether these belong here. They are all not acting upon the path, but create the file/dir at another location. > Controversial: > > - Delete methods and mkdir should succeed silently if the operation is > already done. Otherwise you always have to put them in an if: > 'if foo.exists(): foo.remove()'. That's a good thing. The delete methods shouldn't act any different from the corresponding os functions. > - .delete_dammit() recursively deletes it, whatever it is, without you > having to do the if file/if directory dance. I suppose it would need > a > politically correct name. > which you really have to do every time you delete. *grin* Any naming suggestions? > - All .dirs*, .files*, .walk* methods have a symlinks flag, default > True. > If false, don't yield symlinks. Add .symlinks and .walksymlinks > methods. > This eliminates an 'if' for programs that want to treat symlinks > specially. Sounds good. Will see. Reinhold From exarkun at divmod.com Wed Jul 13 11:42:20 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 13 Jul 2005 11:42:20 -0400 Subject: DNS access In-Reply-To: <1121265881.737855.284030@g44g2000cwa.googlegroups.com> Message-ID: <20050713154220.26278.1775427239.divmod.quotient.10958@ohm> On 13 Jul 2005 07:44:41 -0700, laksh wrote: >im looking for some advice regarding DNS lookup using python > >is it possible to give parameters like the IP of a DNS server and the >DNS query to a python program and obtain the response from the DNS >server ? > Not using the built-in hostname resolution functions. There are a number of third-party DNS libraries: http://devel.it.su.se/projects/python-dns/ http://pydns.sourceforge.net/ http://dustman.net/andy/python/adns-python/ http://twistedmatrix.com/projects/names/ Jp From paolo_veronelli at tiscali.it Thu Jul 28 16:41:03 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Thu, 28 Jul 2005 22:41:03 +0200 Subject: Determine if object is a Bound or Unbound method In-Reply-To: References: Message-ID: <42E942DF.2090600@tiscali.it> Farshid Lashkari wrote: > Hi, > > I have an object and I want to check if it is a bound or unbound method, > or neither. I tried using the types module, but it seems as though > types.UnboundMethodType and types.MethodType are equal. How else can I > determine this? BTW, I'm using Python 2.3 > > Thanks, > > Farshid Bound methods has an im_self attribute set to the instance binding them Ciao ___________________________________ Yahoo! Messenger: chiamate gratuite in tutto il mondo http://it.beta.messenger.yahoo.com From sjmachin at lexicon.net Sat Jul 2 20:20:19 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 03 Jul 2005 10:20:19 +1000 Subject: What's wrong with this code? In-Reply-To: <42C72848.9020609@lexicon.net> References: <42c6d257$0$7061$b9fe7a78@news.usenetrevolution.com> <42C72848.9020609@lexicon.net> Message-ID: <42c72f42$1@news.eftel.com> John Machin wrote: > Nathan Pinno wrote: >> guess = input("Guess a number: ") > > > "guess" will refer to a string e.g. "42" which will *not* compare equal > to the integer 42. Also you should use raw_input, not input. > > so do this: > > guess = int(raw_input("Guess a number: ")) > Ahem ... I'll redo that: You'd be better using raw_input, which *then* means you need to wrap int() around it, ending up with the same recommendation: guess = int(raw_input("Guess a number: ")) Cheers, John From buzzard at urubu.freeserve.co.uk Wed Jul 13 11:52:42 2005 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 13 Jul 2005 16:52:42 +0100 Subject: all possible combinations In-Reply-To: <1121267364.28617.4.camel@athop1.ath.vt.edu> References: <1121267364.28617.4.camel@athop1.ath.vt.edu> Message-ID: rbt wrote: > On Wed, 2005-07-13 at 10:21 -0400, rbt wrote: > >>Say I have a list that has 3 letters in it: >> >>['a', 'b', 'c'] >> >>I want to print all the possible 4 digit combinations of those 3 >>letters: >> >>4^3 = 64 >> >>aaaa >>abaa >>aaba >>aaab >>acaa >>aaca >>aaac >>... >> >>What is the most efficient way to do this? > > > Expanding this to 4^4 (256) to test the random.sample function produces > interesting results. It never finds more than 24 combinations out of the > possible 256. This leads to the question... how 'random' is sample ;) > > Try it for yourselves: > > test = list('1234') > > combinations = [] > while 1: > combo = random.sample(test, 4) > possibility = ''.join(combo) > if possibility not in combinations: > print possibility > combinations.append(possibility) > continue > else: > continue > There are only 24 possible lists that random.sample(test, 4) can return, corresponding to the 24 possible orderings of 4 items. i.e. random.sample() samples without replacement. You need to sample with replacement. Duncan From simon.brunning at gmail.com Thu Jul 21 06:10:07 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 21 Jul 2005 11:10:07 +0100 Subject: Web-Forms In-Reply-To: References: Message-ID: <8c7f10c60507210310202ca782@mail.gmail.com> On 7/21/05, Mathias Waack wrote: > I need to access some information from a web site which are only accessible > through a form. Thus for each bucket of data you have to fill out the form, > submit it and wait for an answer. Very easy - if you don't have to check > some hundred times. Of course this site requires cookies, it is not > directly accessible by URL and so on. All that nice stuff used to make a > web site more professional;) > > But now the question: how can this be solved by using Python? Mechanize? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From slchen at larc.ee.nthu.edu.tw Mon Jul 4 11:35:46 2005 From: slchen at larc.ee.nthu.edu.tw (slchen at larc.ee.nthu.edu.tw) Date: 4 Jul 2005 08:35:46 -0700 Subject: A question for profile Message-ID: <1120491346.373119.13380@g43g2000cwa.googlegroups.com> Now, I have a question about profile. I write a program as below: file name: pro.py ------------------------------- import profile import string,re,sys,random,time import main,read_dont #Read the data S1=sys.argv[1] S2=sys.argv[2] T=read_dont.readfile(S1,string.atoi(S2)) print "T[0] is %s" % T[0] print "Total test pattern bit # is %d" % (len(T)*len(T[0])) #End Read data ###################### print "hello" profile.run('main.solver(T,string.atoi(sys.argv[3]))') ----------------------------------- main and read_dont are two functions which are defined by me. But when I execute the instruction python pro.py pattern_1196.v 14 7 , it show some error message the error message is ~~ Traceback (most recent call last): File "pro.py", line 3, in ? import profile File "/usr/lib/python2.2/profile.py", line 18, in ? # provided that the above copyright notice appears in all copies, and NameError: name 'profile' is not defined but I have import the module profile, Is there any error? Thanks a lot! Sen-Lung Chen From nyamatongwe+thunder at gmail.com Sat Jul 16 19:28:30 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 16 Jul 2005 23:28:30 GMT Subject: odd python/linux/cherrypy behavior In-Reply-To: References: Message-ID: Bill Mill: > ... a FAT partition for data as a dmz which both linux and NT can > access ... > Yesterday, I downloaded the new release of cherrypy, and stuck it on > the dmz drive. ... > Eventually, after thinking it's a hosts file problem, or a firewall > problem, I figure out that if I move it to my ext3 drive, it again > works perfectly. Have you looked at your mount options to make sure they are sane? Possibly you have mounted with only short (truncated) file names or all the files have their execute bit on and that is unexpected or there are non-ASCII characters in file names or ... Neil From steven.bethard at gmail.com Sat Jul 2 21:05:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 02 Jul 2005 19:05:36 -0600 Subject: Inheriting from object In-Reply-To: <42c69a4f.336127175@news.oz.net> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <42c40e16$1@nntp0.pdx.net> <42c69a4f.336127175@news.oz.net> Message-ID: Bengt Richter wrote: > I wonder if the above common use of super could be implemented as a property of object, > so you'd normally inherit it and be able to write > self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose) > > I.e., self.__super__ would effectively return the equivalent of > super(type(self), self) > > (I think Michele Simionato may have posted some idea like this early on that > I didn't really follow, but maybe my subconscious snagged and garbled ;-) Here's the link I believe you're referring to: http://groups-beta.google.com/group/comp.lang.python/msg/0034684c138cf9f3 Probably worth reading for anyone interested in making super syntax "look prettier". Basically Michele shows that the current super() object fails in a number of ways when you try to make it a class attribute. STeVe From rrr at ronadam.com Wed Jul 6 23:39:52 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 07 Jul 2005 03:39:52 GMT Subject: flatten(), [was Re: map/filter/reduce/lambda opinions ...] In-Reply-To: References: <1o6dnZLTIY6jC1XfRVn-uA@speakeasy.net> <1120490609.134384.206840@g47g2000cwa.googlegroups.com> Message-ID: Stian S?iland wrote: > Or what about a recursive generator? > > a = [1,2,[[3,4],5,6],7,8,[9],[],] > > def flatten(item): > try: > iterable = iter(item) > except TypeError: > yield item # inner/final clause > else: > for elem in iterable: > # yield_return flatten(elem) > for x in flatten(elem): > yield x > > print list(flatten(a)) Ok, lets see... I found a few problems with the testing (and corrected it) so the scores have changed. My sort in place routines were cheating because the lists weren't reset between runs so it had the advantage after the first time though of sorting already sorted list. And Tom's recursive no copy had a bug which kept a reference to one of it's arguments so it's output was doubling the list. And the hasattr function was slowing everyone down, so I inlined it for everyone who used it. Using a 1000 item list and starting with a flat list and increasing the depth (unflatten) to shallow, medium, and deep. (but not so deep to cause recursion errors.) And the winners are... Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 IDLE 1.0.5 >>> Size: 1000 Depth: 0 georges_recursive_flatten: 0.00212513042834 rons_nonrecursive_flatten: 0.00394323859609 toms_recursive_zerocopy_flatten: 0.00254557492644 toms_iterative_zerocopy_flatten: 0.0024332701505 devans_smallest_recursive_flatten: 0.011406198274 rons_nonrecursive_inplace_flatten: 0.00149963193644 stians_flatten_generator: 0.00798257879114 Size: 1000 Depth: 25 georges_recursive_flatten: 0.0639824335217 rons_nonrecursive_flatten: 0.0853463219487 toms_recursive_zerocopy_flatten: 0.0471856059917 toms_iterative_zerocopy_flatten: 0.188437915992 devans_smallest_recursive_flatten: 0.0844073757976 rons_nonrecursive_inplace_flatten: 0.0847048996452 stians_flatten_generator: 0.0495694285169 Size: 1000 Depth: 50 georges_recursive_flatten: 0.134300309118 rons_nonrecursive_flatten: 0.183646245542 toms_recursive_zerocopy_flatten: 0.0886252303017 toms_iterative_zerocopy_flatten: 0.371141304272 devans_smallest_recursive_flatten: 0.185467985456 rons_nonrecursive_inplace_flatten: 0.188668392212 stians_flatten_generator: 0.090114246364 Size: 1000 Depth: 100 georges_recursive_flatten: 0.248168133101 rons_nonrecursive_flatten: 0.380992276951 toms_recursive_zerocopy_flatten: 0.177362486014 toms_iterative_zerocopy_flatten: 0.741958265645 devans_smallest_recursive_flatten: 0.306604051632 rons_nonrecursive_inplace_flatten: 0.393641091256 stians_flatten_generator: 0.177185368532 >>> Stians flatten generator is nearly tied with Tom's recursive zerocopy. My nonrecursive inplace is faster for very shallow lists, but Tom's quickly over takes it. I was able to improve my nonrecursive copy flatten a bit, but not enough to matter. So Tom's recursive zerocopy is the overall winner with Stian's flatten generator close behind and just barely winning out in the very deep catagory. But they're all respectable times so everyone wins. ;-) And here's the source code. Cheers, :-) Ron # ------------------------------- import sys import time TIMERS = {"win32": time.clock} timer = TIMERS.get(sys.platform, time.time) def timeit(fn,*arg): t0 = timer() r = fn(*arg) t1 = timer() return float(t1-t0), r # -------------------------------- def georges_recursive_flatten(seq): return reduce(_accum, seq, []) def _accum(a, item): if hasattr(item, "__iter__"): a.extend(georges_recursive_flatten(item)) else: a.append(item) return a def rons_nonrecursive_flatten(seq): a = [] while seq: if hasattr(seq[0], "__iter__"): seq[0:1] = seq[0] else: a.append(seq.pop(0)) return a def toms_recursive_zerocopy_flatten(seq, a=None): #a=[] kept a reference to a? if a==None: a = [] if hasattr(seq,"__iter__"): for item in seq: toms_recursive_zerocopy_flatten(item, a) else: a.append(seq) return a def toms_iterative_zerocopy_flatten(seq): stack = [None] cur = iter(seq) a = [] while (cur != None): try: item = cur.next() if hasattr(item,"__iter__"): stack.append(cur) cur = iter(item) else: a.append(item) except StopIteration: cur = stack.pop() return a def devans_smallest_recursive_flatten(seq): if hasattr(seq,"__iter__"): return sum([devans_smallest_recursive_flatten(item) for item in seq], []) else: return [seq] def rons_nonrecursive_inplace_flatten(seq): i = 0 while i != len(seq): if hasattr(seq[i],"__iter__"): seq[i:(i + 1)] = seq[i] # setslice takes iterators! else: i = i + 1 return seq def flatten_generator(item): try: iterable = iter(item) except TypeError: yield item # inner/final clause else: for elem in iterable: # yield_return flatten(elem) for x in flatten_generator(elem): yield x def stians_flatten_generator(seq): return list(flatten_generator(seq)) # ------------------------------------------ flattens = [ georges_recursive_flatten, rons_nonrecursive_flatten, toms_recursive_zerocopy_flatten, toms_iterative_zerocopy_flatten, devans_smallest_recursive_flatten, rons_nonrecursive_inplace_flatten, stians_flatten_generator ] import random import time random.seed(time.time()) def rand_depth_sequence(seq,depth): n = len(seq)*depth nn = 0 while nn Message-ID: Peter Hansen wrote: > Michael Hoffman wrote: >> For the PEP, do any of you have arguments for or against including path? >> Code samples that are much easier or more difficult with this class >> would also be most helpful. > > I believe the strongest argument for "path" can be made for how it > integrates functionality which, although closely related conceptually, > is currently distributed across a half dozen or more different modules > in the standard library. Especially for newbies (I can only imagine, at > this stage) it would make working with files much easier in a many ways. +10 One of the few things that annoys me about the stdlib is what one could call performing 'shell-scripting-like' tasks, and precisely because of the problem you point out. A number of conceptually related and common tasks are scattered all over, and every time I need to write this kind of code, I find myself paging over the docs for multiple modules, with no real intuition as to where I could even guess where to find things. This is very unusual for python, where in most cases things are so well organized, that blind guessing tends to work remarkably well. Personally I like the path module _a lot_, though I'm sure a thorough once-over from c.l.py and python-dev, via a PEP, can only make it better and smooth out hidden rough edges and corner cases. But I'll be very happy if it does go into the stdlib in the future. Just my .02. Best, f From zanesdad at bellsouth.net Fri Jul 8 15:02:15 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 08 Jul 2005 15:02:15 -0400 Subject: Legacy data parsing In-Reply-To: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> References: <1120847474.604271.196220@g49g2000cwa.googlegroups.com> Message-ID: <42CECDB7.4050508@bellsouth.net> gov wrote: >Hi, > > > >If anyone could give me suggestions as to methods in sorting this type >of data, it would be appreciated. > > > Maybe it's overkill, but I'd *highly* recommend David Mertz's excellent book "Text Processing in Python": http://gnosis.cx/TPiP/ Don't know what all you're needing to do, but that small snip smells like it needs a state machine which this book has an excellent, simple one in (I think) chapter 4. Jeremy Jones From Scott.Daniels at Acm.Org Sat Jul 23 08:18:50 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 23 Jul 2005 05:18:50 -0700 Subject: "Aliasing" an object's __str__ to a different method In-Reply-To: References: Message-ID: <42e22d6c$1@nntp0.pdx.net> Jeffrey E. Forcier wrote: > ... > However, you appear to be correct, and the docs appear to be confused: > class MyClass(object): > def edit(self): > return "I'm in edit mode" > def setEdit(self): > MyClass.__str__ = self.edit > ... > Either way, guess I will have to take another route. Your suggestion is > what I'd had in mind, and does the job pretty well. I'm still > attempting to figure out the best approach to my overall problem, > however, so who knows where I will end up =) Here is one more standard way to do this: class MyClass(object): ... # Common behavior goes here def setEdit(self): self.__class__ = MyEditClass def setView(self): self.__class__ = MyViewClass class MyEditClass(MyClass): def __repr__(self): return "I, %s, am being edited" % super( MyEditClass, self).__repr__() class MyViewClass(MyClass): def __repr__(self): return "I, %s, am being viewed" % super( MyViewClass, self).__repr__() Be a little careful about the structure of the subclasses (MyViewClass and MyEditClass) since they can wink into and out of existence, and all will go well. Plus, you can easily override base behavior in the subclasses differentially. Note: for this example, you could also define the methods like: class MyEditClass(MyClass): def __repr__(self): return "I, %s, am being edited" % MyClass.__repr__(self) When to use super rather than direct access to the superclass is an involved discussion. --Scott David Daniels Scott.Daniels at Acm.Org From jmeile at hotmail.com Tue Jul 19 14:52:40 2005 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 19 Jul 2005 20:52:40 +0200 Subject: Web Framework Reviews In-Reply-To: References: <1121786419.419424.279160@g44g2000cwa.googlegroups.com> Message-ID: <42DD4BF8.7030603@hotmail.com> > "barely use python with it" and "can only be used with these two" are > not entirely true. Zope development can be done in a through-the-web > (TTW) fashion or via filesystem products. When developing TTW, it > is true that you are somewhat limited in the amount of Python that > you will be able to use. I just want to add that ZPT and DTML are only intended for the presentation and not for the logic, which can be done all using python. However, as you may see, there are some zope developers that use it wrong and do lots of logic stuff within dtml or zpt. Regards, Josef From grante at visi.com Mon Jul 11 18:24:11 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Jul 2005 22:24:11 -0000 Subject: Help with report References: Message-ID: <11d5scbb63afhee@corp.supernews.com> On 2005-07-11, ChrisH wrote: > I have some data in the following format: > > Fred Flintstone,445553454,47634565 > Wilma Flintstone,74857346,27576847 > Barney Rubble,73487346,27576435 > > I need to convert this data into a report with the user's name and > difference between the 2 numbers. > > Can someone recommend a good way to do this? > > BTW, it would be best if I can have it up and running by tomorrow. You really oughtn't put off homework assignments until the last minute. Especially if you don't know how to do them. > Also, html would be the preferred format, but not required. > > Any help would be greatly appreciated!! Hints: The string object's "split" method: http://docs.python.org/lib/string-methods.html for line in file('inputfile.txt','r') the built-in int() the string formatting operator "%": http://docs.python.org/lib/typesseq-strings.html -- Grant Edwards grante Yow! All right, you at degenerates! I want this visi.com place evacuated in 20 seconds! From huron at sopinspace.com Fri Jul 1 04:05:08 2005 From: huron at sopinspace.com (Huron) Date: Fri, 01 Jul 2005 10:05:08 +0200 Subject: python project layout Message-ID: Hi, What do you guys recommend in terms of python project layout, especially unit tests layout ? Zope has unit tests per packages, twisted has a big tests directory full of tests ... and the file naming convention are also pretty differents ... I guess there is part of "personnal choices" in those matters ... but there is also good practice advices that can be gathered I think ... - h From moranar at alice.it Sat Jul 30 12:13:22 2005 From: moranar at alice.it (Adriano Varoli Piazza) Date: Sat, 30 Jul 2005 16:13:22 GMT Subject: Comparison of functions In-Reply-To: References: Message-ID: Steven D'Aprano ha scritto: > It was easy. I never once asked myself whether some complex number was > greater or less than another, I just asked "which one comes first in a > lexicographic sort?" > > The two questions are NOT the same, and it is an ugliness in an otherwise > beautiful language that Python treats them as the same. > > Mathematically, 1 == 1.0 == 1+0j but in the dictionary "1" should sort > before "1.0" which sorts before "1.0+0.0j". Because, of course, when I sort numbers the first thing I think of is looking at the ascii table... Here I was, thinking maths was useful. Sorting numbers "lexicographically" might make sense to you, but it's totally unintuitive to me. For example, why or how would I guess that "3-3j" is bigger (or smaller) than "3+3j"? You'll still want to sort complex numbers lexicographically. It'll still have no meaning whatsoever, so you might as well leave the list unsorted. You might think you sorted something. 100? 200? years of maths say you didn't. -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar MSN: adrianomd at hotmail.com ICQ: 4410132 From rutski89 at gmail.com Mon Jul 4 12:57:46 2005 From: rutski89 at gmail.com (Patrick Rutkowski) Date: Mon, 4 Jul 2005 12:57:46 -0400 Subject: HTML Conventions Message-ID: <200507041257.46687.rutski89@gmail.com> I couldn't help but make an even better list in reference to this thread: http://mail.python.org/pipermail/python-list/2005-July/288678.html
Type Convention Example
funtion action_with_underscores find_all
variable noun_with_underscores curr_index
constant NOUN_ALL_CAPS ALLOWED_RNA_PAIRS
class MixedCaseNoun RnaSequence
public property MixedCaseNoun IsPaired
private property _noun_with_leading_underscore _is_updated
public method mixedCaseExceptFirstWordVerb stripDegenerate
private method _verb_with_leading_underscore _check_if_paired
really private data __two_leading_underscores __delegator_object_ref
parameters matching property SameAsProperty __init__(data, Alphabet=None)
factory function MixedCase InverseDict
module lowercase_with_underscores unit_test
From lbates at syscononline.com Wed Jul 13 15:54:03 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 13 Jul 2005 14:54:03 -0500 Subject: 2.4 Recent File list not working Message-ID: I recently upgraded from 2.2 to 2.4 (ActiveState for Windows). I was accustomed to having the most recent 10 files that I had edited show up under File menu under Recent. After upgrading these don't seem to be saved after exiting. I tried changing the number in the Preferences, but nothing seems to do any good. Has anyone else had this problem? Any ideas how I might fix it? Thanks in advance for your assistance. Regards, Larry Bates From jgrahn-nntq at algonet.se Thu Jul 7 13:27:12 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 7 Jul 2005 17:27:12 GMT Subject: How do you program in Python? References: <3iqif8Fmj34kU1@individual.net> <42oiad.vg8.ln@lightning.itga.com.au> Message-ID: On Thu, 07 Jul 2005 18:10:44 +1000, Gregory Bond wrote: > Jorgen Grahn wrote: > >> Emacs and vim are almost always installed, or trivially installable. All I >> need to remember is to bring my emacs config file. > > And, fortunately, USB pen drives are now big enough to hold it! Hey, it's not fair to make fun of emacs now that I've mentioned vim favourably so many times ;-) Seriously, nothing about emacs seems big or slow today. It has been outbloated by pretty much everything else. Who could have imagined /that/ ten years ago? /Jorgen (And just in case this thread deteriorates into a silly emacs-vs-vi argument, I hereby declare myself out of the game.) -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sybrenUSE at YOURthirdtower.com.imagination Mon Jul 4 12:27:47 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 4 Jul 2005 18:27:47 +0200 Subject: importing pyc from memory? References: <1120484279.054832.312150@g49g2000cwa.googlegroups.com> Message-ID: Derek van Vliet enlightened us with: > I'm trying to save compiled python code in a proprietary file format > to cut reduce the overhead of compiling all my scripts when my app > starts up. Why is that faster than having the .pyc files ready on your filesystem? And why do you want it in a proprietary file format? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From nospam at me.invalid Sat Jul 30 11:15:10 2005 From: nospam at me.invalid (anthonyberet) Date: Sat, 30 Jul 2005 16:15:10 +0100 Subject: string methods Message-ID: <3l1js6F10d0leU1@individual.net> I am an abject newbie, so mock away (actually no-one ever does that in this group..) Anyway, I want to replace one character in a string, based in that character's position in the string. For example if I wanted to replace the 4th character in 'foobar' (the b)with the contents of another string, newchar, what would be the easiest way? I know this touches on immutability etc, but I can't find string methods to return the first 3 characters, and then the last 2 characters, which I could concatenate with newchar to make a new string. I know the string methods are there, but can't find it in any docs, and just want to check the syntax, unless there is an easier way. Thanks. From grante at visi.com Wed Jul 6 10:39:59 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Jul 2005 14:39:59 -0000 Subject: threads and sleep? References: Message-ID: <11cnr9vi3r0m19@corp.supernews.com> On 2005-07-06, Alex Stapleton wrote: > Is SYS V shared memory a totalyl stupid way of doing distributed locks > between processes then? Sys V semaphores would seem to be a more logical choice. -- Grant Edwards grante Yow! I'm pretending I'm at pulling in a TROUT! Am I visi.com doing it correctly?? From none at no.chance Thu Jul 28 12:25:02 2005 From: none at no.chance (Peter Tillotson) Date: Thu, 28 Jul 2005 16:25:02 +0000 Subject: Advanced concurrancy Message-ID: Hi, I'm looking for an advanced concurrency module for python and don't seem to be able to find anything suitable. Does anyone know where I might find one? I know that there is CSP like functionality built into Stackless but i'd like students to be able to use a standard python build. I'm trying to develop distributed / Grid computing modules based on python. The aim is to be able to use barriers for synchronisation and channels for communication between processes running on a single box. Then the jump to multiple processes on multiple boxes and eventually to MPI implementations. Hopefully, each jump should not be that big a leap. Of course it would be nice if there was a robust way of managing concurrency in python aswell ;-) p From mwm at mired.org Sun Jul 3 18:36:24 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 03 Jul 2005 18:36:24 -0400 Subject: looping over a big file References: <11cgnhp3j4th442@corp.supernews.com> Message-ID: <86ekaf1pqv.fsf@bhuda.mired.org> Roy Smith writes: > The "right" way to do this is: > > for line in file ("filename"): > whatever > > The file object returned by file() acts as an iterator. Each time through > the loop, another line is read and returned (I'm sure there is some > block-level buffering going on at a low level). I disagree. That's the *convenient* way to do it, and perfectly acceptable in many situations. But not all Python interpreters will close the file when for loop ends. Likewise, if you get an exception during the processing, the file may not get closed properly. Those things may matter to you, in which case the "right" way is: data = open("filename") try: for line in data: whatever finally: data.close() Guido has made a pronouncement on open vs. file. I think he prefers open for opening files, and file for type testing, but may well be wrong. I don't think it's critical. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Mon Jul 25 08:01:22 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 25 Jul 2005 22:01:22 +1000 Subject: Problem loading a file of words References: <1122263048.404393.155960@z14g2000cwz.googlegroups.com> Message-ID: On Sun, 24 Jul 2005 20:44:08 -0700, teoryn wrote: > I've been spending today learning python and as an exercise I've ported > a program I wrote in java that unscrambles a word. Before describing > the problem, here's the code: > > *--beginning of file--* > #!/usr/bin/python > # Filename: unscram.py > > def sort_string(word): > '''Returns word in lowercase sorted alphabetically''' > word = str.lower(word) It is generally considered better form to write that line as: word = word.lower() > word_list = [] > for char in word: > word_list.append(char) If you want a list of characters, the best way of doing that is just: word_list = list(word) > word_list.sort() > sorted_word = '' > for char in word_list: > sorted_word += char > return sorted_word And the above four lines are best written as: return ''.join(word_list) > print 'Building dictionary...', > > dictionary = { } > > # Notice that you need to have a file named 'dictionary.txt' > # in the same directory as this file. The format is to have > # one word per line, such as the following (of course without > # the # marks): > > #test > #hello > #quit > #night > #pear > #pare > > f = file('dictionary.txt') > > # This loop builds the dictionary, where the key is > # the string after calling sort_string(), and the value > # is the list of all 'regular' words (from the dictionary, > # not sorted) that passing to sort_string() returns the key > > while True: > line = f.readline() > if len(line) == 0: > break > line = str.lower(line[:-1]) # convert to lowercase just in case > and > # remove the return at the end of > the line > sline = sort_string(line) > if sline in dictionary: # this key already exist, add to > existing list > dictionary[sline].append(line) > print 'Added %s to key %s' % (line,sline) #for testing > else: # create new key and list > dictionary[sline] = [line] > print 'Created key %s for %s' % (sline,line) #for > testing > f.close() Your while-loop seems to have been mangled a little thanks to word-wrap. In particular, I can't work out what that "and" is doing in the middle of it. Unless you are expecting really HUGE dictionary files (hundreds of millions of lines) perhaps a better way of writing the above while-loop would be: print 'Building dictionary...', dictionary = { } f = file('dictionary.txt', 'r') for line in f.readlines() line = line.strip() # remove whitespace at both ends if line: # line is not the empty string line = line.lower() sline = sort_string(line) if sline in dictionary: dictionary[sline].append(line) print 'Added %s to key %s' % (line,sline) else: dictionary[sline] = [line] print 'Created key %s for %s' % (sline,line) f.close() > print 'Ready!' > > # This loop lets the user input a scrambled word, look for it in > # dictionary, and print all matching unscrambled words. > # If the user types 'quit' then the program ends. > while True: > lookup = raw_input('Enter a scrambled word : ') > > results = dictionary[sort_string(lookup)] This will fail if the scrambled word you enter is not in the dictionary. > for x in results: > print x, > > print > > if lookup == 'quit': > break You probably want the test for quit to happen before printing the "unscrambled" words. > *--end of file--* > > > If you create dictionary.txt as suggested in the comments, it should > work fine (assumeing you pass a word that creates a valid key, I'll > have to add exceptions later). The problem is when using a large > dictionary.txt file (2.9 MB is the size of the dictionary I tested) it > always gives an error, specifically: > (Note: ccehimnostyz is for zymotechnics, which is in the > large dictionary) > > > *--beginning of example--* > Enter a scrambled word : ccehimnostyz Traceback (most recent call last): > File "unscram.py", line 62, in ? > results = dictionary[sort_string(lookup)] > KeyError: 'ccehimnostyz' > *--end of example--* If this error is always happening for the LAST line in the text file, I'm guessing there is no newline after the word. So when you read the text file and build the dictionary, you inadvertently remove the "s" from the word before storing it in the dictionary. -- Steven. From nospam at foo.com Thu Jul 7 17:50:41 2005 From: nospam at foo.com (jayessay) Date: 07 Jul 2005 17:50:41 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: "Terry Reedy" writes: > "jayessay" wrote in message > news:m3r7ebvomy.fsf at rigel.goldenthreadtech.com... > > 1. Someone recently remarked that good Lisp macros are basically > > executable pseudo code. I think that is pretty much exactly right > > and is a pretty good "sound bite" distillation of what it is all > > about. > > Several years ago I remarked that Python reads like executable pseudocode. > I still think that that is pretty much right. > > Googling, I discovered that the creators of some thing I had never heard of > said the same thing about *their* language a couple of years ago. I wish > web pages, like newgroup posts, were dated so one could better trace the > history of such usages. In the context discussed, the idea was the pseudo code was a _direct_ match to the description of the task in the _domain_. If your domain is "algorithms" or some such, then I would agree Python would work as a reasonably decent pseudo language, otherwise no. It's too low level. Same with base CL. It's too low level. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From paolo_veronelli at tiscali.it Fri Jul 29 03:51:23 2005 From: paolo_veronelli at tiscali.it (Paolino) Date: Fri, 29 Jul 2005 09:51:23 +0200 Subject: why functions in modules need 'global foo' for integer foo but not dictionary foo? In-Reply-To: References: <1122616696.886226.279510@f14g2000cwb.googlegroups.com> Message-ID: <42E9DFFB.5090103@tiscali.it> Robert Kern wrote: > seberino at spawar.navy.mil wrote: > >>At top of a module I have an integer like so... >> >>foo = 4 >> >>In a function in that module I know I need to do 'global foo' to get at >>the value 4. >>... > > > I presume you are trying code like the following: > > foo = 4 > bar = {} > > def fun1(): > foo = 5 > > def fun2(): > bar['baz'] = 4 > > Since integers are immutable, all that fun1() does is assign 5 to the > name "foo" within fun1()'s namespace and doesn't touch the module-level > namespace. Hmm this is obscure to me also, what mutables has to do with this problem?A binding is always mutable. > fun2(), on the other hand, only gets the dictionary from the > module-level namespace with the name "bar". Then it modifies that > dictionary (since it's mutable). It does not try to assign a new object > to the name "bar". Probably the point is modifing/rebinding the bound values and not rebind them. Generally if you need to use globals for inter-instance/class communication, I suggest to define a new namespace where to put global bindings: class Globals: foo=4 spam={} for lexical coherence you can put also funtions there class Globals: foo=4 spam={} @staticmethod def func():pass then you always refer to them with Globals.foo,Globals.spam,Globals.func or with .Globals.... from outside. Finally consider to use singletons as a more common approach. Ciao ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From python at rcn.com Wed Jul 6 03:45:54 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jul 2005 00:45:54 -0700 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> Message-ID: <1120635954.442101.99920@g47g2000cwa.googlegroups.com> seberino at spawar.navy.mil wrote: > The problem is that questions like 'What lang is fastest to develop > in?' > are hard to answer definitively. FWIW, Google's answer to that question is C++, Java, and Python. For any given problem, any of the three are acceptable. Each programmer or engineering team gets to decide based on his or her language expertise.* Raymond * Source: Greg Stein's keynote address at PyCon 2005. From roy at panix.com Sun Jul 3 15:32:53 2005 From: roy at panix.com (Roy Smith) Date: Sun, 03 Jul 2005 15:32:53 -0400 Subject: need to get an index for an item in a list References: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> Message-ID: In article <1120418138.615987.160210 at g44g2000cwa.googlegroups.com>, nephish at xit.net wrote: > hey there, > i need to be able to get the index for an item in a list. > the list is a list of lines read from a text file. > > like this: > > file = open("/home/somefile.text", "r") > lines = file.readlines() > file.close() > > now, i want to see if a certain string is == to one of the lines > and if so, i need to know the index of that line. Assuming you're already read the lines from the file with the above code, something along the lines of the following will work: for lineNumber, line in enumerate (lines): whatever But, starting from scratch, it'll be more efficient to do: for lineNumber, line in enumerate (file ("filename")): whatever because it'll read lines one at a time as needed, instead of gulping them all in at once and buffering them in memory. For small files (say, less than a few hundred lines), it probably won't make any appreciable difference, but for big files, it can be substantial. BTW, enumerate() starts counting from 0; you might want to add 1 to what it returns to get a file line number. From me at privacy.net Thu Jul 28 16:31:03 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 28 Jul 2005 16:31:03 -0400 Subject: Ten Essential Development Practices References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 28 Jul 2005 21:19:53 +0100, Michael Hoffman wrote: > Robert Kern wrote: >> import this >> And you get 9 bonus Essential Development Practices, too! What a >> bargain! > One of these days I'm going to figure out how to embody "Namespaces are > one honking great idea -- let's do more of those!" Then I shall be > enlightened. And when the one obvious way to do something *is* be obvious at first, then I shall be Dutch! Regards, Dan -- Dan Sommers From skip at pobox.com Wed Jul 27 13:14:53 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 27 Jul 2005 12:14:53 -0500 Subject: On fighting fire with fire... Message-ID: <17127.49421.214518.349400@montanaro.dyndns.org> Twice today I responded to rude messages (once here, once on the SpamBayes list) whose authors didn't deserve the benefit of my time. In both cases, other people rightfully responded with some small amount of return venom (but provided useful responses nonetheless). Let me suggest that there is only one "correct" way to respond (if you are going to respond at all) to such messages. That's to focus on the substance of their message and completely ignore the rancor. I've been the chief technical guy (including user support) for Musi-Cal for over ten years and for Mojam for about seven years. During that time I've received lots of thanks from people for the service those sites provide. Every once in awhile though, I get a message out of the blue from someone who is either simply an asshole or is having the mother of all bad days. I've found there is nothing so satisfying as responding politely to such messages and then to have their authors come virtually crawling back later with an apology for having been so out-of-line. Just a thought... Skip From twic at urchin.earth.li Thu Jul 7 13:19:08 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 7 Jul 2005 18:19:08 +0100 Subject: Deleting variables [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey] In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: On Thu, 7 Jul 2005, Steven D'Aprano wrote: > On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote: > >>> del -> delete >> >> How about just getting rid of del? Removal from collections could be done >> with a method call, > > Which would be called object.del() I presume. That would be fine. > And that opens a big can of worms. > > Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do? Delete the item at index 1, just as del L[1] would. > It looks like it should result in L becoming [4, 3, 2, 0]. Why? I guess if you hadn't read the documentation and were just calling methods at random, you might, but i can't think of any other case. > An easy mistake to make, if you forget that the argument is (presumably) > an index. Not the kind of thing people tend to forget! There is the problem that people might get del and remove mixed up; i didn't actually realise there was a remove method on lists until i looked just now. > You could make it clear by insisting on L.del[1] but that requires a big > change in Python's syntax. It would, so i wouldn't dream of insisting on it. > What should L.del() do, with no arguments? Raise an error? Er, exactly the same as calling any other method with a wrong-length argument list - a TypeError, i should think. > Now, you have something like this: > > class thing: > pass > obj = thing() > obj.alpha = [4, 3, 2, 1, 0] > obj.beta = 5 > > Python's object model suggests that obj.alpha.del() should call alpha's > del method, in the same way that obj.alpha.append() would call alpha's > append method. Exactly so. > So how do you delete obj.alpha? obj.del("alpha") might work. But what if > obj itself is a mapping, with a key "alpha" as well as an attribute > alpha. Which one should obj.del("alpha") delete? I don't think objects should have a del method by default. I'd suggest a delattr or removeattr builtin, working along the lines of getattr and setattr, for this task. > Now, if you said that L.del() should raise an exception earlier, what > about obj.beta.del()? Unless int has a del method, that would be an exception - an AttributeError, to be precise. > Presumably every object automatically has a del method, I'd say no, but for the sake of argument, let's say it does. > so you don't have to program a del method yourself. obj.del is a method > object. So it has a del method. (Yes, sometimes you want to delete > methods. Functions are first class objects in Python.) Which has a del > method. Which has a del method. Right. > What should obj.del.del.del.del.del.del.del.del.del() do? Raise a TypeError, since you haven't passed any parameters. As for obj.del.del.del.del.del.del.del.del.del("del"), that's an interesting one - it comes down to the question of whether those del methods are the same object or not. I'd say not: for two objects a and b of the same class, a.foo and b.foo are considered different objects in python, and that applies here. >> and i'm not convinced that deleting variables is something we really >> need to be able to do (most other languages manage without it). > > Most other languages don't have namespaces that can get polluted, or > on-the-fly creation of variables. Most other languages don't consider > variables to be simply attributes of a module object. How much is that really used? And how many of those cases wouldn't be covered by a delattr builtin? > And most other languages don't allow you to run interactive sessions > where it is easy to mistakenly make variables you don't want. > > py> x = 1 > py> u = x+2 # oops, typo, meant y not u > py> del u # prevent confusion in the programmer's mind > > It is also useful sometimes to delete a module object from the top level > namespace before re-importing it, rather than merely reloading it. That > requires being able to delete a variable. That's a very strong use case. However, it would be straightforward to make variable deletion an interpreter thing rather than a language thing. > In summary: del being a keyword works. del() being an object method is > unclear, confusing and complicated. Only if you give it the bizarre semantics you use above! I think having del as a keyword is actually unhelpful, since it's overloaded to do two quite different things - remove items from lists and dicts, and expunge attributes from namespaces. Far better to do let lists and dicts expose methods to let themselves be manipulated, and to play with attributes through a uniform troika of {get, set, del}attr builtins. tom -- They travel the world in their ice cream van ... From max at alcyone.com Fri Jul 1 16:24:59 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Jul 2005 13:24:59 -0700 Subject: When someone from Britain speaks, Americans hear a "Britishaccent"... In-Reply-To: <11c8tgjju7ljvd4@corp.supernews.com> References: <11c8tgjju7ljvd4@corp.supernews.com> Message-ID: <7IWdnYV9K8cBO1jfRVn-3w@speakeasy.net> Grant Edwards wrote: > Right, but due to some wierd property requiring conservation of > consonants, when speaking Strine you've got to take the r's > removed from words like "carrier" and "order", and add them to > the ends of other words like Amanda. The distinction is rhotic vs. non-rhotic accents, by the way; non-rhotic accents drop the _r_s. The latter example is usually an example of overcorrection. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Heaven ne'er helps the man who will not act. -- Sophocles From steve at REMOVETHIScyber.com.au Sun Jul 24 09:29:14 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 24 Jul 2005 23:29:14 +1000 Subject: Getting a dictionary from an object References: Message-ID: On Sun, 24 Jul 2005 12:03:47 +0300, Thanos Tsouanas wrote: > On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote: >> On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote: >> > >> > print foo %do >> > >> > where do is a dictobj object... >> >> Are you telling me that the ONLY thing you use dictobj objects for is to >> print them? > > I'm sorry to disappoint you, but yes. When you have a long text > template to fill-out, with lots of %(foo)s, and all those foos are > attributes of an object, it really helps to have dictobj. Ah, now we're making progress in finding out what the purpose of the dictobj is! Thank you, this is starting to become clearer now. >> I don't think so. I do know how to print an object, amazingly. > > Please, tell me, how would you print it in my case? If I have understood you, you have some object like such: obj.foo = 1 obj.bar = 2 obj.spam = 'a' obj.eggs = 'b' say. You want to use it something like this: print "My object has fields %(foo)s; %(bar)s; %(spam)s; %(eggs)s." % obj except that doesn't work. So I would simply change the reference to obj to obj.__dict__ and it should do exactly what you want. Does that help? [snip] > Because *obviously* I don't know of these indexing and attribute > grabbing machineries you are talking about in my case. If you cared to > read my first post, all I asked was for the "normal", "built-in" way to > do it. Now, is there one, or not? I did read your first post. Unfortunately, you had not explained what you were trying to do very well. Your initial solution involved sub-classing dict. I made the fatal mistake of trying to guess what you needed from your sample code -- a natural mistake to make, given how vague your requirements were. Or rather, non-existent. It really does help to explain what your functional requirements are, instead of focusing on one, possibly pointless, implementation. If I have understood your functional requirements correctly, you don't need "to have a quick way to create dicts from object, so that a call to foo['bar'] would return obj.bar" at all. -- Steven. From donn at drizzle.com Sat Jul 2 01:06:19 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 02 Jul 2005 05:06:19 -0000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <1120280776.328768@yasure> Quoth Tom Anderson : ... | I disagree strongly with Guido's proposals, and i am not an ex-Lisp, | -Scheme or -any-other-functional-language programmer; my only other real | language is Java. I wonder if i'm an outlier. | | So, if you're a pythonista who loves map and lambda, and disagrees with | Guido, what's your background? Functional or not? Dysfunctional, I reckon. I think I disagree with the question more than the answer. First, map and lambda are two different things, and it's reasonable to approve of one and abhor the other. Especially if you have a background in a functional language where lambda works like it should. On the other hand, the list comprehension gimmick that replaces some of the "higher order functions" is borrowed from Haskell, as you probably know, so it isn't exactly alien to functional programming. Prelude.hs defines map: map f xs = [ f x | x <- xs ] Secondly, if there's anything I detest about the Python development model, it is the tendency to focus on gimmicks. For 2.X, elimination of these features would be an atrocity, a gratuitous change that would break programs - but I don't think anyone who counts has seriously proposed to do that. With 3.X, we are talking about a different language. May not ever even get off the ground, but if it does, it's supposed to be distinctly different, and we need to know a lot more about it before we can reasonably worry about trivial details like whether map is going to be there. I personally think real FP is seriously hot stuff, but I think Python is a lousy way to do it, with or without map. I suppose there's a remote possibility that 3.X will change all that. Or more likely, there will by then be a really attractive FP language, maybe out of the "links" initiative by Wadler et al. Donn Cave, donn at drizzle.com From guillaume_hiron at yahoo.fr Fri Jul 1 03:39:24 2005 From: guillaume_hiron at yahoo.fr (Guillaume Hiron) Date: Fri, 01 Jul 2005 09:39:24 +0200 Subject: Windows installation - questions about DLLs Message-ID: <42C4F32C.70401@yahoo.fr> Hi, I need to install python (2.3.5) on windows without the giving installer program. Do you know what dlls are needed? I found python23.dll, but the other (msvcrt.dll,msvcrit.dll) seems not be useful. Is there other dll? Are msvcrt.dll and msvcrit.dll used by something?(test/test___all__.py return no error whitout these two dlls). Thanks for helping. From rkern at ucsd.edu Sun Jul 17 12:12:33 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 17 Jul 2005 09:12:33 -0700 Subject: ConfigParser : overwrite ? In-Reply-To: <42da80cf$0$25057$8fcfb975@news.wanadoo.fr> References: <42da80cf$0$25057$8fcfb975@news.wanadoo.fr> Message-ID: cantabile wrote: > Hi, I'm trying and updating an .ini file with ConfigParser but each time > I call 'write', it appends the whole options another time to the file. > For example : > Here's the inital ini file > > [section1] > foodir: %(dir)s/whatever > dir: foo > > Here's my code : > filename = ... > config = ConfigParser.ConfigParser() > config.read(filename) > config.set('section1', 'dir', 'anotherdir') > f = open(filename, 'r+') > config.write(f) > f.close() > > Then I get : > > [section1] > foodir: %(dir)s/whatever > dir: anotherdir > > [section1] > foodir: %(dir)s/whatever > dir: foo > > I tried also with 'w', 'w+', 'a' ... Are you sure you tried it with 'w' as the mode? In [1]: !cat foo.ini [section1] foodir: %(dir)s/whatever dir: foo In [2]: fn = 'foo.ini' In [3]: import ConfigParser In [4]: cfg = ConfigParser.ConfigParser() In [5]: cfg.read(fn) Out[5]: ['foo.ini'] In [6]: cfg.set('section1', 'dir', 'anotherdir') In [7]: f = open(fn, 'w') In [8]: cfg.write(f) In [9]: f.close() In [10]: !cat foo.ini [section1] foodir = %(dir)s/whatever dir = anotherdir -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From slaheddine.haouel at unilog.fr Tue Jul 12 09:47:20 2005 From: slaheddine.haouel at unilog.fr (Slaheddine Haouel) Date: Tue, 12 Jul 2005 15:47:20 +0200 Subject: CONNCET TO SOAP SERVICE Message-ID: <20050712135241.80A2340487@netbox-marcqenbaroeul1.unilog.fr> Can you help me plz ? I want to wonnect to SOAP webservices but before I must be authentificated on a apache server, I used SOAPpy module but I don?t know how I can be authentified on the apache server???? thx Slaheddine Haouel Unilog NORD t?l : 03 59 56 60 25 t?l support : 03 59 56 60 68 Email : slaheddine.haouel at unilog.fr -------------- next part -------------- An HTML attachment was scrubbed... URL: From spam.csubich+block at block.subich.spam.com Thu Jul 14 02:08:28 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 14 Jul 2005 02:08:28 -0400 Subject: Help - Classes and attributes In-Reply-To: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> Message-ID: rh0dium wrote: > Hi all, > > I believe I am having a fundamental problem with my class and I can't > seem to figure out what I am doing wrong. Basically I want a class > which can do several specific ldap queries. So in my code I would have > multiple searches. But I can't figure out how to do it without it > barfing.. [snip] > File "./ldap-nsc.py", line 40, in search > ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, > retrieveAttrs) > AttributeError: NSCLdap instance has no attribute 'search_s' > > > The code is also I believe straight forward.. You're going to kick yourself when you see the mistake. > > import ldap > > class NSCLdap: > > def __init__(self,server="sc-ldap.nsc.com"): > who=""; cred="" > self.server=server > try: > print "LDAP Version", ldap.__version__ > l=ldap.open(server) ^^^^^^^^^^^^^^^^^^ [big snip] > if __name__ == '__main__': > > l = NSCLdap() > l.search() > I would love some pointers - clearly my code thinks that search_s is an > attribute of my class but it's not.. Ah, but l -is- an instance of your class. You want l to refer to the ldap connection, but you forgot do assign it to self.l -- in __init__, you assign l to simply a local variable, which goes poof as soon as __init__ returns. You forgot the self.l throughout both __init__ and search. You get the slighty misleading traceback because there is an "l" defined -- it just happens to be the one in globals(), the l = NSCLdap() that got assigned when you imported/ran the module. Replace l = NSCLdap() with q = NSCLdap() (and l.search with q.search), and you'll get a NameError instead. From macaronikazoo at gmail.com Sat Jul 16 08:22:26 2005 From: macaronikazoo at gmail.com (macaronikazoo) Date: 16 Jul 2005 05:22:26 -0700 Subject: secure uploading Message-ID: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> hi i'm after a way to securely upload a file to a web server and I'm wondering how to go about it. basically i want to upload a small text file to my hosted webspace once every hour or so. because it will be happening once an hour, i want to make sure the transaction is encrypted, but i don't really know how to do this. can someone point me in the right direction? i'm a reasonably noob scripter so go easy on me. :) thanks! -h. From rdsteph at mac.com Mon Jul 11 22:28:22 2005 From: rdsteph at mac.com (rdsteph at mac.com) Date: 11 Jul 2005 19:28:22 -0700 Subject: a new Python Podcast series (and the use of Python in creating podcasting tools) Message-ID: <1121135302.110610.188420@f14g2000cwb.googlegroups.com> Python411 is a series of podcasts about Python, aimed at hobbyists and others who are learning Python. Each episode focuses on one aspect of learning Python, or one kind of Python programming, and points to online tools and tutorials. Python related news and events will also be reported upon. This podcast series will probably not be of much interest to expert or professional programmers. I am a hobbyist and am not qualified nor capable of creating a podcast series for accomplished programmers. Maybe someone else will do that. The four podcasts so far are titled as such: Introduction to Python Computer Programming for Everybody GUI toolkits for Python Python for Mobile Devices New podcasts will appear from time to time. Interestingly, while on the subject of podcasts, I would like to point out that Python is emerging as the programming language of choice for creating tools for creating podcasts and using podcasts. For instance, iPodder is the leading podcast aggregator, or podcatcher, and is written in Python. Also, a new program called Podcatcher on a Stick is an open source Python project that is creating a podcatcher that runs on a mobile mp3 player itself, rather than on a PC. Links to these programs can be found on my web site. The home page for Python411 is http://www.awaretek.com/python/index.html and one can click on the podcasts there to play them, or better you can subscribe to an rss feed at http://www.awaretek.com/python/index.xml From http Sun Jul 31 04:04:43 2005 From: http (Paul Rubin) Date: 31 Jul 2005 01:04:43 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <873bpvqu9g.fsf@wilson.rwth-aachen.de> Message-ID: <7xhdebv1t0.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > Does py2exe work for all GUI libraries? No, it's Windows-only. From spam at be.gone Sat Jul 23 03:08:32 2005 From: spam at be.gone (Andy) Date: Sat, 23 Jul 2005 07:08:32 GMT Subject: unit test nested functions Message-ID: How can you unit test nested functions? Or do you have to pull them out to unit test them, which basically means I will never use nested functions. Also, same thing with private member functions protected by __. Seems like there is a conflict there between using these features and unit testing. Andy From fdeserres at gmx.net Tue Jul 5 16:57:52 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Tue, 05 Jul 2005 22:57:52 +0200 Subject: (Win32 API) callback to Python, threading hiccups In-Reply-To: <25Bye.46690$Xv.12976@bignews4.bellsouth.net> References: <25Bye.46690$Xv.12976@bignews4.bellsouth.net> Message-ID: <42CAF450.4050106@gmx.net> Christopher Subich wrote: >Francois De Serres wrote: > > >>- so, on callback, I create a new thread, after checking that the >>previous one has returned already (WaitOnSingleObject(mythread)) so we >>only have one thread involved. >> >> > >Uh... to me, this looks like a frighteningly inefficient way of doing >things. How about using a synchronous queue to post the data to a >processing thread? That way, you don't have to create an entierly new >thread each time you receive data in the callback. > > Thanks for the tip, and sorry for frightening you. Maybe you can help as well with my issue? Francois From benji at benjiyork.com Wed Jul 27 11:55:58 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 27 Jul 2005 11:55:58 -0400 Subject: Need to understand python license In-Reply-To: References: Message-ID: <42E7AE8E.2040605@benjiyork.com> Roy Smith wrote: > Specifically, can we take the Python interpreter source code, modify > it, compile it, staticly link it into our binaries, ship it to our > paying customers, and still retain the right to not show anybody our > source? See http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq -- Benji York From jzgoda at gazeta.usun.pl Mon Jul 25 10:09:49 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 25 Jul 2005 16:09:49 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <1122210268.757687.20290@g49g2000cwa.googlegroups.com> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122210268.757687.20290@g49g2000cwa.googlegroups.com> Message-ID: TPJ napisa?(a): >>PyQt works equally well on both systems. > > I believe you. The problem is I don't like GPL. So, buy commercial license for Qt and PyQt. -- Jarek Zgoda http://jpa.berlios.de/ From steve at REMOVEMEcyber.com.au Wed Jul 6 04:20:02 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 06 Jul 2005 18:20:02 +1000 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: Message-ID: <42CB9432.7080501@REMOVEMEcyber.com.au> I said I'd drop the discussion about lambda, but this isn't really the same discussion even if it is part of the same thread. That's my excuse, and I'm sticking to it. Terry Hancock wrote: > On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote: > >>I understand that the backslash is popular in some ivory-tower functional >>languages. Currently, a backslash can be used for explicit line joining, >>and is illegal elsewhere on a line outside a string literal, so i think >>it's available for this. It would be utterly unpythonic to use puntuation >>instead of a keyword, and it would make no sense to novices, but it would >>scare the crap out of C programmers, which has to be worth something. > > > With list comprehensions and generators becoming so integral, I'm > not sure about "unpythonic". And a syntax just occured to me -- > what about this: > > [y*x for x,y] > > ? > > (that is: > > [ for ] > > It's just like the beginning of a list comprehension or generator, but > without the iterator. That implies that one must be given, and > the result is therefore a callable object. That is a very long chain of implication: "It looks like a list comprehension... but there is no iterator... so we have to supply an iterator... so it takes an argument... so it is a callable object... oh and by the way, it can take any arguments, not just iterators." It is also far too easy to make a mistake, eg to write something like newlist = [y*x for x,y] when you actually wanted the list comp [y*x for x,y in L]. This would create an anonymous function where you expected to create a list. It is hard to think of a usage case where you didn't discover the error reasonably soon, but it would be better for leaving the iterator out of a list comp to remain a syntax error, rather than produce an unexpected, but legal, object. Besides, I think Guido should be very cautious about introducing new features that use punctuation, instead of keywords. We don't want to become perl do we? :-) -- Steven. From nephish at xit.net Thu Jul 28 09:51:08 2005 From: nephish at xit.net (nephish) Date: Thu, 28 Jul 2005 13:51:08 +0000 Subject: easy float question just eludes me References: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> <8c7f10c60507280648244420cf@mail.gmail.com> Message-ID: <1122558668l.19223l.0l@texaspivot.texaspivot.com> way cool, outta work out just fine On 07/28/2005 08:48:27 AM, Simon Brunning wrote: > On 28 Jul 2005 06:39:32 -0700, nephish at xit.net > wrote: > > i have a real easy one here that isn't in my book. > > i have a int number that i want to divide by 100 and display to two > > decimal places. > > > > like this float(int(Var)/100) > > but i need it to display the .00 even if it does not have a .00 > value > > like this > > if Var is 50, i need to display .50 instead of just .5 > > >>> import decimal as dec > >>> dec.Decimal('250.00')/100 > Decimal("2.50") > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ > > From ironfroggy at gmail.com Sat Jul 30 12:56:21 2005 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 30 Jul 2005 12:56:21 -0400 Subject: How can I run a program? In-Reply-To: <1122719594.365246.241840@g43g2000cwa.googlegroups.com> References: <1122719594.365246.241840@g43g2000cwa.googlegroups.com> Message-ID: <76fd5acf05073009562d8d6134@mail.gmail.com> did you try to put the filename in quotes? On 30 Jul 2005 03:33:14 -0700, Lad wrote: > Hello, > I am running Python on XP and have a problem with > a program if its name consists '-' for example: > my-program.py > When I try to run a program with such name > I get the error : > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'my' is not defined > > Python thinks that the name of program is my.py only > but the name is my-program.py > > What is a solution? > Thank you > Lad. > > -- > http://mail.python.org/mailman/listinfo/python-list > From lorinh at gmail.com Wed Jul 27 13:03:33 2005 From: lorinh at gmail.com (lorinh at gmail.com) Date: 27 Jul 2005 10:03:33 -0700 Subject: Stripping C-style comments using a Python regexp In-Reply-To: <1122482105.439897.65920@z14g2000cwz.googlegroups.com> References: <1122478928.879240.89110@g47g2000cwa.googlegroups.com> <1122482105.439897.65920@z14g2000cwz.googlegroups.com> Message-ID: <1122483813.709937.204740@z14g2000cwz.googlegroups.com> Neat! I didn't realize that re.sub could take a function as an argument. Thanks. Lorin From mhellwig at xs4all.nl Sat Jul 23 15:45:59 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 23 Jul 2005 21:45:59 +0200 Subject: Friend wants to learn python In-Reply-To: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> References: <1122135601.019848.208180@z14g2000cwz.googlegroups.com> Message-ID: <42e29ef3$0$98804$e4fe514c@news.xs4all.nl> EnderLocke wrote: > I have a friend who wants to learn python programming. I learned off > the internet and have never used a book to learn it. What books do you > recommend? > > Any suggestions would be appreciated. > I recommend "Learning Python 2nd Edition" by Mark Lutz & David Ascher (O'Reilly) its reasonable easy to read no "heavy language, but clear concept and examples. It does not require any previous programming experience, although being comfortable with computer terms and knowing some basic concepts of programming does make you read faster through the book. My overall conclusion was that the authors know what they are talking about and are honest in what they want to achieve. When done with that the reader has enough experience to at least know where to go further to learn more about python. -- mph From jan.danielsson at gmail.com Thu Jul 21 10:34:30 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Thu, 21 Jul 2005 16:34:30 +0200 Subject: Stupid question: Making scripts python-scripts Message-ID: <42dfb111@griseus.its.uu.se> Hello all, How do I make a python script actually a _python_ in unix:ish environments? I know about adding: #!/bin/sh ..as the first row in a shell script, but when I installed python on a NetBSD system, I didn't get a "python" executable; only a "python2.4" executable. Adding "#!/usr/pkg/bin/python2.4" as the first row in the script would probably work, but that would be too specific for the system I'm using, imho. I saw someone using "#!/usr/bin/env python", but that failed on the system I'm using, so I assume that's something specific too (or is the installation broken?). From phillip.watts at anvilcom.com Tue Jul 5 12:19:55 2005 From: phillip.watts at anvilcom.com (phil) Date: Tue, 05 Jul 2005 11:19:55 -0500 Subject: More On - deepcopy, Tkinter References: <42C9B738.7010604@anvilcom.com> Message-ID: <42CAB32B.1090708@anvilcom.com> > but you clearly haven't > been getting the results from this forum that you expected. > Yes I have, this is a wonderful forum. I was just providing more info due to more testing. From bokr at oz.net Tue Jul 12 16:59:12 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Jul 2005 20:59:12 GMT Subject: Frankenstring References: Message-ID: <42d42d66.16997531@news.oz.net> On Tue, 12 Jul 2005 22:08:55 +0200, Thomas Lotze wrote: >Hi, > >I think I need an iterator over a string of characters pulling them out >one by one, like a usual iterator over a str does. At the same time the >thing should allow seeking and telling like a file-like object: > >>>> f = frankenstring("0123456789") >>>> for c in f: >... print c >... if c == "2": >... break >... >0 >1 >2 >>>> f.tell() >3L >>>> f.seek(7) >>>> for c in f: >... print c >... >7 >8 >9 >>>> > >It's definitely no help that file-like objects are iterable; I do want >to get a character, not a complete line, at a time. > >I can think of more than one clumsy way to implement the desired >behaviour in Python; I'd rather like to know whether there's an >implementation somewhere that does it fast. (Yes, it's me and speed >considerations again; this is for a tokenizer at the core of a library, >and I'd really like it to be fast.) I don't think there's anything like >it in the standard library, at least not anything that would be obvious >to me. > >I don't care whether this is more of a string iterator with seeking and >telling, or a file-like object with a single-character iterator; as long >as it does both efficiently, I'm happy. > >I'd even consider writing such a beast in C, albeit more as a learning >exercise than as a worthwhile measure to speed up some code. > >Thanks for any hints. > I'd probably subclass file to buffer in good-sized chunks and override the iteration to go by characters through the buffer, updating the buffer when you get to its end, and overriding seek and tell to do the right thing re the buffer and where you are in it for the character iteration via next. Regards, Bengt Richter From piet at cs.uu.nl Fri Jul 15 14:00:15 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 15 Jul 2005 20:00:15 +0200 Subject: threads and sleep? References: Message-ID: >>>>> Christopher Subich (CS) wrote: >CS> Hrm... this would suggest the possibility of designing a metaclass, >CS> perhaps, that would ensure synchronous access to an object. Perhaps "wrap" >CS> the class in another, that gets and releases a mutex on any external >CS> get/set access (except, possibly, for a specified list of "asynchronous" >CS> data members and methods). Sometimes that's not enough, because you may have to synchronise access to a couple of objects, or to multiple operations on some object(s). The system can't know the required granularity of locking, only the application programmer knows that. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From eric_brunel at despammed.com Mon Jul 18 03:18:45 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 18 Jul 2005 09:18:45 +0200 Subject: win32ui CreatePrintDialog References: Message-ID: On Fri, 15 Jul 2005 18:08:35 -0400, Chris Lambacher wrote: > Hi, > > This question has come up a few times on the list with no one giving a public > answer. How do you use CreatePrintDialog from win32ui? > > About a year ago someone posted that: > dlg = win32ui.CreatePrintDialog(1538) > dlg.DoModal() > > will give you the window, but the ok button does not work. Here is what I did to make it work: import win32ui from pywin.mfc import window, dialog class WindowsPrintDialog(window.Wnd): # Numbers for various items in the dialog PROPERTIES_BTN = 1025 PRINTER_NAME = 1139 PRINT_TO_FILE = 1040 PRINT_ALL = 1056 PRINT_PAGES = 1058 PRINT_SELECTION = 1057 FIRST_PAGE = 1152 LAST_PAGE = 1153 FROM_TEXT = 1089 TO_TEXT = 1090 NB_COPIES = 1154 def __init__(self): dlg = = win32ui.CreatePrintDialog(1538) window.Wnd.__init__(self, printDlg) def OnInitDialog(self): ## Initialize dialog itself self._obj_.OnInitDialog() ## Activate all widgets for i in (WindowsPrintDialog.PRINT_ALL, WindowsPrintDialog.PRINT_PAGES, WindowsPrintDialog.FIRST_PAGE, WindowsPrintDialog.LAST_PAGE, WindowsPrintDialog.FROM_TEXT, WindowsPrintDialog.TO_TEXT, WindowsPrintDialog.PRINT_SELECTION): itm = self._obj_.GetDlgItem(i) itm.EnableWindow() ## Disable "Properties" button: it doesn't work... itm = self._obj_.GetDlgItem(WindowsPrintDialog.PROPERTIES_BTN) itm.EnableWindow(0) def OnOK(self): ## Call on dialog itself self._obj_.OnOK() self._obj_.UpdateData(1) ## Now you can get values entered in dialog via: ## - self.IsDlgButtonChecked() pour check-buttons ## - self.GetDlgItemText() for textual fields ## - self.GetDlgItemInt() for integer fields ## Then use these info. to create your printer DC; for example: printerName = self.GetDlgItemText(WindowsPrintDialog.PRINTER_NAME) dc = win32ui.CreateDC() dc.CreatePrinterDC(printerName) ## And so on... Note that the printer properties button is explicitely disabled. If it's not, it seems to be working (it actually opens the printer properties dialog and all options can be modified without any error), but actually doesn't change a thing: the printing will be done with the printer default settings. If anybody has any idea on how this thing works, please let me know: I'm very interested. > Diging into the source shows that the 1538 is being loaded as a template > resource. The MSDN documentation does not say anything about this being > neccessary and in fact, other common dialogs provide this as an option, but > not a requirement. Why is this made a requirement? If it was not made a > requirement, would the dialog work? I guess it would just be a matter of giving the default value 1538 to the idRes parameter in win32ui.CreatePrintDialog; AFAICT, this is always the id for the default print dialog. Can't figure out why it was not done in the first place... > Unfortunately I can't play with this because I don't have Visual Studio. I > guess the logical next step, if the above worked, would be to add the > GetPrinterDC() method (and maybe some others) so that we can do something > useful with the dialog. Yep. See above. > Thanks, > Chris HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From tdickenson at devmail.geminidataloggers.co.uk Wed Jul 27 02:46:03 2005 From: tdickenson at devmail.geminidataloggers.co.uk (Toby Dickenson) Date: Wed, 27 Jul 2005 07:46:03 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: Message-ID: <200507270746.03497.tdickenson@devmail.geminidataloggers.co.uk> On Wednesday 27 July 2005 05:37, Meyer, Tony wrote: > I can see that this would make sense in some situations, but ISTM that it > would make a great deal more sense (and be much more intuitive) to have > concatenation include the separator character (i.e. be join). def functions_which_modifies_some_file_in_place(path): output = open(path+'.tmp', 'w') ..... I dont want a seperator inserted between path and the new extension. -- Toby Dickenson From fdu.xiaojf at gamil.com Mon Jul 18 03:58:47 2005 From: fdu.xiaojf at gamil.com (fdu.xiaojf at gamil.com) Date: Mon, 18 Jul 2005 15:58:47 +0800 Subject: Dose someone have installed python on IRIX ? Message-ID: <42DB6137.2030207@gamil.com> Hi, everyone, I'm a newbie in python. Does someone have experience about how to install python on IRIX ? I have tried several times but without success. "./configure" and "make" are both ok, but got errors when I run "make test". Thanks in advance. From caleb1 at telkomsa.net Tue Jul 26 16:03:54 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 26 Jul 2005 22:03:54 +0200 Subject: GUI - Windows: Where to get started References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> Message-ID: Probably, the best place for learning how to build GUI's for Windows, in general, is to get hold the personal edition of Delphi from the Borland website. If you want something more specific to Python, it is likely to be much tougher. You would, for example, have to decide which widget toolkit you want to use. Also, you would have to decide if you want to do GUI-building via text-files or through a graphical method. The simplest method (for the latter) I have seen so far is Glade, but perhaps other posters will have better advice than me. rgds Caleb On Tue, 26 Jul 2005 21:44:13 +0200, Ernesto wrote: > Hi all, > > Would anyone know a good place to start for learning how to build > simple GUI's in Windows XP? I just want users to be able to select a > few parameters from a pull-down menu, then be able to run some batch > files using the parameters from the pull down menus. I would also need > a "Browse" menu, so users could point to a place on the local disc (ie > C:\PointSystemHere). Can anyone give a noob some tips? THANKS!!! > From bronger at physik.rwth-aachen.de Sun Jul 24 16:16:01 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 24 Jul 2005 22:16:01 +0200 Subject: PyGTK or wxPython (not a flame war) on Windows References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> Message-ID: <878xzwarjy.fsf@wilson.rwth-aachen.de> Hall?chen! Marek Kubica writes: > [...] > > I have started GUIs in Python with wx, but after a short time I > was annoyed how many things were buggy. I don't know why, but I > fell from one bug to the other while programming one application. I'm very suprised. wxPython is still that buggy? I read reports from 2000 about such observations, but they tried wxPython in a non-standard way, and the project has had 5 years to become more stable after all. Besides, wxPython prepares for being included into the standard distribution. What did you do? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From moranar at alice.it Sat Jul 30 12:18:56 2005 From: moranar at alice.it (Adriano Varoli Piazza) Date: Sat, 30 Jul 2005 16:18:56 GMT Subject: Comparison of functions In-Reply-To: References: Message-ID: Steven D'Aprano ha scritto: > On Sat, 30 Jul 2005 13:30:20 +0000, Adriano Varoli Piazza wrote: > > >>But tell me, how do you think sort works if not with <, >, ==, <= and >= >>? I'm really interested. > > > How do you sort words in a dictionary? Why does five come before four > when the number five is larger than the number four? Why does hundred > come before ten? What does it mean to say that elephant is less than > mouse? > > When you can answer those questions, you will be enlightened. > >>> 'a' > 'A' True >>> 'a' > '-' True >>> 'a' > 'h' False Whiiiiii. I just discovered the Ascii table! wooot! (Your EBCDIC mileage might vary) What does it have to do with complex numbers, pray tell? and how do you think any string sort works if not by comparing the numerical value of each character? Once more: >>> 'five' < 'four' True >>> 'five' < 'Four' False >>> 'Five' < 'Four' True Ooohhh! magic of ascii! -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar MSN: adrianomd at hotmail.com ICQ: 4410132 From s_t_a_n_i at gmx.net Wed Jul 20 21:59:06 2005 From: s_t_a_n_i at gmx.net (Stani) Date: 20 Jul 2005 18:59:06 -0700 Subject: Python IDE In-Reply-To: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> References: <1121751163.596120.312110@g43g2000cwa.googlegroups.com> Message-ID: <1121911146.213579.28630@g14g2000cwa.googlegroups.com> Try out the new version of SPE 0.7.4.a. You would make me happy if you can make it crash. (But not by running crashing programs or infinitive loops inside spe.) http://www.stani.be/python/spe Ciao, Stani From falcon3166 at hotmail.com Sat Jul 2 13:55:24 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 2 Jul 2005 11:55:24 -0600 Subject: A brief question. Message-ID: Hi all, Brief question for anyone who knows the answer, because I don't. Is there anyway to make Python calculate square roots? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rphillips at engineer.co.summit.oh.us Fri Jul 8 06:59:08 2005 From: rphillips at engineer.co.summit.oh.us (paron) Date: 8 Jul 2005 03:59:08 -0700 Subject: f*cking re module In-Reply-To: <42c8fc44$0$221$edfadb0f@dread12.news.tele.dk> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <42c8fc44$0$221$edfadb0f@dread12.news.tele.dk> Message-ID: <1120820348.747911.111530@g49g2000cwa.googlegroups.com> That is so handy!! Thanks! Ron From tjreedy at udel.edu Sat Jul 9 16:04:55 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jul 2005 16:04:55 -0400 Subject: PPC floating equality vs. byte compilation References: <1120888655.953163@yasure> <1f7befae05070908227704f21@mail.gmail.com> Message-ID: "Tim Peters" wrote in message news:1f7befae05070908227704f21 at mail.gmail.com... > [Donn Cave] >> I ran into a phenomenon that seemed odd to me, while testing a >> build of Python 2.4.1 on BeOS 5.04, on PowerPC 603e. >> >> test_builtin.py, for example, fails a couple of tests with errors >> claiming that apparently identical floating point values aren't equal. >> But it only does that when imported, and only when the .pyc file >> already exists. Not if I execute it directly (python test_builtin.py), >> or if I delete the .pyc file before importing it and running >> test_main(). This is a known problem with marshalling INFs and/or NANs. *This* has supposedly been fixed for 2.5. We are assuming that the failure you report is for real floats. > It would be most helpful to open a bug report, with the output from > failing tests. And assign to Tim. >In general, this can > happen if the platform C string<->float routines are so poor that > > eval(repr(x)) != x ... > The ultimate cause is most likely in the platform C library's > string<->float routines (sprintf, strtod, that kind of thing). It would also be helpful if you could do some tests in plain C (no Python) testing, for instance, the same values that failed. Hardly anyone else can ;-). If you confirm a problem with the C library, you can close the report after opening, leaving it as a note for anyone else working with that platform. Terry J. Reedy From nothingcanfulfill at gmail.com Sat Jul 9 14:48:51 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 9 Jul 2005 11:48:51 -0700 Subject: pyo contains absolute paths In-Reply-To: References: Message-ID: <1120934931.720410.61380@z14g2000cwz.googlegroups.com> Python is compiling the files with absolute paths because it is much faster to load a file when you know where it is, than to have to find it and then load it. I'm guessing you're wondering this so you can distribute it compiled or such? If so, I wouldn't do that in the first place. Python's compiled files might be version/architecture dependant. -NcF From martin at v.loewis.de Tue Jul 5 15:56:02 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 05 Jul 2005 21:56:02 +0200 Subject: PyUnicodeUCS4_AsUnicode error In-Reply-To: <1120591341.342746.114500@g49g2000cwa.googlegroups.com> References: <1120591341.342746.114500@g49g2000cwa.googlegroups.com> Message-ID: <42CAE5D2.1060105@v.loewis.de> fjs205 at gmail.com wrote: > When I try to import gtk, or even start some programs that use Python I > get the error: > > "ImportError: /usr/lib/python2.4/site-packages/gtk-2.0/gobject.so: > undefined symbol: PyUnicodeUCS4_AsUnicode" > > Can anyone shed some light on this? > > FWIW, I have reinstalled python, tried v2.3.4 instead of 2.4, > reinstalled GTK, searched for a unicode library problem (I reinstalled > libunicode too). It appears that your build of python-gtk does not match your Python build. I don't know what you mean by "reinstalled GTK" - did you build it yourself, from scratch, or did you use some kind of Linux distribution? Also, where did you get Python-GTK from? If you also got Python-GTK from your Linux distribution, you most likely found a bug in that distribution - ask your Linux vendor for help. Meanwhile, it might be easiest to uninstall Python-GTK if you don't use it. If you built something yourself, you managed to build Python-GTK and Python inconsistently. While the Python build is for UCS-2, your Python-GTK build is for UCS-4. One possible cause might be that Python-GTK was build on a different machine than Python 2.4. Regards, Martin From a at b.c Tue Jul 5 00:45:12 2005 From: a at b.c (D H) Date: Mon, 04 Jul 2005 23:45:12 -0500 Subject: f*cking re module In-Reply-To: References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> Message-ID: <9oSdnUwoj_jBjVffRVn-sg@comcast.com> Gustavo Niemeyer wrote: > That's what I love in that news group. Someone comes with a > stupid and arrogant question, and someone else answers in a > calm and reasonable way. ...and then someone else comes along and calls the first person stupid and arrogant, which is deemed QOTW. :) From oddr at home.no.no Wed Jul 27 08:29:28 2005 From: oddr at home.no.no (Odd-R.) Date: 27 Jul 2005 12:29:28 GMT Subject: regex problem References: <42e62ff6$1@news.eftel.com> Message-ID: On 2005-07-26, Duncan Booth wrote: >>>> rx1=re.compile(r"""\b\d{4}(?:-\d{4})?,""") >>>> rx1.findall("1234,2222-8888,4567,") > ['1234,', '2222-8888,', '4567,'] Thanks all for good advice. However this last expression also matches the first four digits when the input is more than four digits. To resolve this problem, I first do a match of this, regex=re.compile(r"""\A(\b\d{4},|\d{4}-\d{4},)*(\b\d{4}|\d{4}-\d{4})\Z""") If this turns out ok, I do a find all with your expression, and then I get the desired result. -- Har du et kj?leskap, har du en TV s? har du alt du trenger for ? leve -Jokke & Valentinerne From haraldarminmassa at gmail.com Tue Jul 5 05:55:15 2005 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 5 Jul 2005 02:55:15 -0700 Subject: Considering moving from Delphi to Python [Some questions] In-Reply-To: References: <5f4d3cb505070410192ba525d7@mail.gmail.com> Message-ID: <1120557315.721066.242140@g49g2000cwa.googlegroups.com> > I want some feedback on folllwing: > anybody who has experience in writing SOAP servers in Python and data > entry heavy web applications. > Any suggestions? > darkcowherd > I have never written SOAP Servers. But I have very very good experience in creating entry heavy web application using Python and Quixote; Webserver Medusa. The current entry forms have at maximum 700 distinct entries, of which groups can be multiplied via XMLHTTPRequest and DOM-Modifikation without page reloading. Speed is great. Because of very slow rendering and various buggies within IE (beast took longer to render then me to deliver) we switched to Firefox. System is performing adequately well and is being constantly extended; Pythons clear structure makes that easy. Hope that helps, Harald From bdesth.quelquechose at free.quelquepart.fr Thu Jul 14 07:40:43 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 14 Jul 2005 13:40:43 +0200 Subject: Help - Classes and attributes In-Reply-To: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> References: <1121304363.638177.60640@g44g2000cwa.googlegroups.com> Message-ID: <42d64891$0$15020$626a14ce@news.free.fr> rh0dium a ?crit : > Hi all, > > I believe I am having a fundamental problem with my class and I can't > seem to figure out what I am doing wrong. Basically I want a class > which can do several specific ldap queries. So in my code I would have > multiple searches. But I can't figure out how to do it without it > barfing.. > > The error is straightforward .. > > LDAP Version 2.0.8 > Traceback (most recent call last): > File "./ldap-nsc.py", line 62, in ? > l.search() > File "./ldap-nsc.py", line 40, in search > ldap_result_id = l.search_s(baseDN, searchScope, searchAttrs, > retrieveAttrs) > AttributeError: NSCLdap instance has no attribute 'search_s' > > > The code is also I believe straight forward.. > > import ldap > > class NSCLdap: > > def __init__(self,server="sc-ldap.nsc.com"): > who=""; cred="" > self.server=server > try: > print "LDAP Version", ldap.__version__ > l=ldap.open(server) > l.simple_bind_s(who, cred) > l.protocol_version=ldap.VERSION3 > except ldap.LDAPError, error_message: > print "Couldn't Connect to %s %s " % > (server,error_message) And then you throw away the ldap connection... > def search(self, baseDN="o=nsc.com", > retrieveAttrs=None,searchAttrs="cn=*klass*" ): > searchScope = ldap.SCOPE_SUBTREE > try: > ldap_result_id = l.search_s(baseDN, searchScope, > searchAttrs, retrieveAttrs) Now where is this 'l' coming from ? > result_set = [] > while 1: > result_type, result_data = l.result(ldap_result_id, 0) > if (result_data == []): > break > else: > ## here you don't have to append to a list > ## you could do whatever you want with the > individual entry > ## The appending to list is just for > illustration. > if result_type == ldap.RES_SEARCH_ENTRY: > result_set.append(result_data) > print result_set > except ldap.LDAPError, error_message: > print "Errors on Search %s " % error_message > > def setBaseDN(self, baseDN="o=nsc.com"): > return baseDN Err... this code is not 'setting' anything. > if __name__ == '__main__': > > l = NSCLdap() > l.search() > > > I would love some pointers - clearly my code thinks that search_s is an > attribute of my class but it's not.. try with this instead : q = NSCLdap() q.search() May I suggest a somewhat corrected version ? class NSCLdap(object): def __init__(self, server="sc-ldap.nsc.com", baseDN="o=nsc.com", who=None, cred=None): self.server = server self.baseDN = baseDN if who is None: self.who = "" else: self.who = who if cred is None: self.cred = "" else: self.cred = cred self.connection = None def connect(self): try: print "LDAP Version", ldap.__version__ self.connection = ldap.open(server) self.connection.simple_bind_s(self.who, self.cred) self.connection.protocol_version=ldap.VERSION3 except ldap.LDAPError, error_message: # I would not catch this. It's the caller's # responsabilitie to handle this IMHO print >> sys.stderr, "Couldn't Connect to %s %s " % (server,error_message) def search(self, baseDN=None, searchScope=ldap.SCOPE_SUBTREE, retrieveAttrs=None, searchAttrs="cn=*klass*" ): cnx = self.connection if baseDN is None: baseDN = self.baseDN try: ldap_result_id = cnx.search_s(baseDN, searchScope, searchAttrs, retrieveAttrs) result_set = [] while True: result_type, result_data =cnx.result(ldap_result_id, 0) #if (result_data == []): if not result_data: break ## here you don't have to append to a list ## you could do whatever you want with the ## individual entry ## The appending to list is just for ## illustration. if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) print result_set except ldap.LDAPError, error_message: print >> sys.stderr, "Errors on Search %s " % error_message if __name__ == '__main__': truc = NSCLdap() truc.search() From hancock at anansispaceworks.com Mon Jul 4 14:46:58 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 4 Jul 2005 13:46:58 -0500 Subject: Folding in vim In-Reply-To: <42C92E9D.47776A45@pauahtun.org> References: <200507022235.52847.hancock@anansispaceworks.com> <200507032242.17725.hancock@anansispaceworks.com> <42C92E9D.47776A45@pauahtun.org> Message-ID: <200507041346.58841.hancock@anansispaceworks.com> On Monday 04 July 2005 07:42 am, Ivan Van Laningham wrote: > Terry Hancock wrote: > > I also got "space_hi.vim" which highlights tabs > > and trailing spaces, which made it a lot easier to fix the > > problem. > > Is that really the name? I tried searching for it & got no hits. Sorry, no underscore, it's spacehi.vim: http://www.vim.org/scripts/script.php?script_id=443 -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From spam.csubich+block at block.subich.spam.com Thu Jul 21 00:18:58 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 21 Jul 2005 00:18:58 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: References: <1121874565.242907.274990@o13g2000cwo.googlegroups.com> Message-ID: Peter Hansen wrote: > stringy wrote: > >> I have a program that shows a 3d representation of a cell, depending on >> some data that it receives from some C++. It runs with wx.timer(500), >> and on wx.EVT_TIMER, it updates the the data, and receives it over the >> socket. > > > It's generally inappropriate to have a GUI program do network > communications in the main GUI thread. You should create a worker > thread and communicate with it using Queues and possibly the > AddPendingEvent() or PostEvent() methods in wx. There should be many > easily accessible examples of how to do such things. Post again if you > need help finding them. I'd argue that point; it's certainly inappropriate to do (long-)/blocking/ network communications in a main GUI thread, but that's just the same as any blocking IO. If the main thread is blocked on IO, it can't respond to the user which is Bad. However, instead of building threads (possibly needlessly) and dealing with synchronization issues, I'd argue that the solution is to use a nonblocking network IO package that integrates with the GUI event loop. Something like Twisted is perfect for this task, although it might involve a significant application restructuring for the grandparent poster. Since blocking network IO is generally slow, this should help the grandparent poster -- I am presuming that "the program updating itself" is an IO-bound, rather than processor-bound process. From peter at engcorp.com Fri Jul 22 14:33:03 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 14:33:03 -0400 Subject: PEP on path module for standard library In-Reply-To: <3kacleFslj6sU1@individual.net> References: <3kacleFslj6sU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > FYI: I modified the path module a bit so that it fits many of the suggestions > from python-dev, and put the result in the Python CVS tree under > nondist/sandbox/path. By the way, thanks for doing this Reinhold! > Most prominent change is that it doesn't inherit from str/unicode anymore. > I found this distinction important, because as a str subclass the Path object > has many methods that don't make sense for it. On this topic, has anyone ask the original author (Jason Orendorff) whether he has some background on this decision that might benefit the discussion? Given the elegance of the design of the path module, I would think if he has an opinion on the matter it is probably based on more thought than any of us have given it so far. And maybe he would even say that it was a wrong decision at the time and he'd do it differently the next time. -Peter From paolo.veronelli at gmail.com Wed Jul 27 14:58:00 2005 From: paolo.veronelli at gmail.com (Paolino) Date: Wed, 27 Jul 2005 20:58:00 +0200 Subject: any thing to do??? In-Reply-To: References: Message-ID: <42E7D938.4060408@gmail.com> mustafa wrote: > i hav just finished learning pythob from "A byte of python"(an online > book) so i wanted to apply my new skills. to learn and to have some fun. > is there any place which lists jobs to be done...you know minor jobs and > requests thats nobody has found time to do. > i would point out that i am not looking for a JOB as job with payment. > i am looking for a JOB that is to be done and nobody has done it yet. > > also aside from this is there any other way i could use python and > improve. i figure this practice will make me a lot better. but if anybody > else has any ideas than that would be good too . > Hmm try this: http://www.itasoftware.com/careers/eng/job1.php For really useful things probably you want to reach some projects like twisted ,but there you need more experience IMO. Good luck and welcome to Python. Paolino From dalke at dalkescientific.com Wed Jul 27 00:26:31 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 27 Jul 2005 04:26:31 GMT Subject: how to write a line in a text file References: <42E5B0F0.6020206@REMOVEMEcyber.com.au> <42E5ED91.10402@REMOVEMEcyber.com.au> Message-ID: > en.karpachov at ospaz.ru wrote: >> Well, it's what (R)DBMS are for, but plain files are not. Steven D'Aprano wrote: > This isn't 1970, users expect more from professional > programs than "keep your fingers crossed that nothing > bad will happen". That's why applications have multiple > levels of undo (and some of them even save the undo > history in the file) and change-tracking, and auto-save > and auto-backup. This isn't 1970. Why does your app code work directly with files? Use a in-process database library (ZODB, SQLLite, BerkeleyDB, etc.) to maintain your system state and let the library handle transactions for you. Andrew dalke at dalkescientific.com From rrr at ronadam.com Mon Jul 18 14:18:00 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 18 Jul 2005 18:18:00 GMT Subject: Efficiently Split A List of Tuples In-Reply-To: <1121673226.458423.133380@g44g2000cwa.googlegroups.com> References: <1121653103.663820.126910@o13g2000cwo.googlegroups.com> <1121673226.458423.133380@g44g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [Ron Adam] > >>Currently we can implicitly unpack a tuple or list by using an >>assignment. How is that any different than passing arguments to a >>function? Does it use a different mechanism? > > > It is the same mechanism, so it is also only appropriate for low > volumes of data: > > a, b, c = *args # three elements, no problem > f(*xrange(1000000)) # too much data, not scalable, bad idea > > Whenever you get the urge to write something like the latter, then take > it as cue to be passing iterators instead of unpacking giant tuples. > > > Raymond Ah... that's what I expected. So it better to transfer a single reference or object than a huge list of separated items. I suppose that would be easy to see in byte code. In examples like the above, the receiving function would probably be defined with *args also and not individual arguments. So is it unpacked, transfered to the function, and then repacked. or unpacked, repacked and then transfered to the function? And if the * is used on both sides, couldn't it be optimized to skip the unpacking and repacking? But then it would need to make a copy wouldn't it? That should still be better than passing individual references. Cheers, Ron From mwm at mired.org Tue Jul 19 23:33:25 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 19 Jul 2005 23:33:25 -0400 Subject: Read only files References: Message-ID: <8664v6rw1m.fsf@bhuda.mired.org> Pranav Bagora writes: > Hello, > > I am getting a permission Denied error when i am > trying to make changes in some read only files in a > directory. How do we check and change the read only > attributes of files in python. You want the os.stat and os.chmod functions. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From programmer.py at gmail.com Thu Jul 21 11:15:50 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Thu, 21 Jul 2005 10:15:50 -0500 Subject: Overriding a built-in exception handler In-Reply-To: <1121956750.750199.289050@g14g2000cwa.googlegroups.com> References: <1121956750.750199.289050@g14g2000cwa.googlegroups.com> Message-ID: You can't override an exception. You can only catch whatever exception is thrown. For your case, you would want to wrap that while loop up in a try/catch block like this: try: while 1: print "Yay for me!" except KeyboardInterrupt: print "CTRL-C caught" Someone had mentioned possibly overriding sys.excepthook, but that doesn't really "override" an exception handler. That function is called when an unhandled exception occurs. That little hook is really nice if you want to display information back to the user and possibly report the info back to a server somewhere. jw On 21 Jul 2005 07:39:10 -0700, callmebill at gmail.com wrote: > I'm having a tough time figuring this one out: > > > class MyKBInterrupt( ..... ): > print "Are you sure you want to do that?" > > if __name__ == "__main__": > while 1: > print "Still here..." > > > So this thing keeps printing "Still here..." until the user hits ctl-c, > at which time the exception is passed to MyKBInterrupt to handle the > exception, rather than to whatever the built-in handler would be. > > I've Read-TFM, but I only see good info on how to create my own class > of exception; I don't see anything on how to override an existing > exception handler. > > Thanks in advance for any help. > > -- > http://mail.python.org/mailman/listinfo/python-list > From rkern at ucsd.edu Tue Jul 19 00:51:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 18 Jul 2005 21:51:16 -0700 Subject: Filtering out non-readable characters In-Reply-To: References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Michael Str?der wrote: > Peter Hansen wrote: > >>>>>''.join(chr(c) for c in range(65, 91)) >> >>'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > > Wouldn't this be a candidate for making the Python language stricter? > > Do you remember old Python versions treating l.append(n1,n2) the same > way like l.append((n1,n2)). I'm glad this is forbidden now. That wasn't a syntax issue; it was an API issue. list.append() allowed multiple arguments and interpreted them as if they were a single tuple. That was confusing and unnecessary. Allowing generator expressions to forgo extra parentheses where they aren't required is something different, and in my opinion, a good thing. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mkamranazam at hotmail.com Sat Jul 23 11:14:09 2005 From: mkamranazam at hotmail.com (M Kamran Azam) Date: Sat, 23 Jul 2005 15:14:09 +0000 Subject: Regarding Webbrowser Module in Python Message-ID: Hi all, My query goes like this. I have two htm files.One is media_try_home.htm and the second one is media_try.htm.I am attaching these files to my mail so that you guys can understand the problem. Now, first simply open the media_try_home.htm and press "PLAY THE FILE" button.A video clip is opened.(Both the files should be in the same directory). Using webbrowser, I can first open the first file like this: webbrowser.open_new("c:\Myfolder\media_try_home.htm"). But I want to play the second file directly using webbrowser but that doesn't work when I use the following : webbrowser.open_new ("file:///c:\media_try.htm?start=60&end=70&location=mms%3A%2F%2Fedrul-develop.softeco.it%2F23%2F2004%2F12%2F23_20041218223000.wmv&submit=PLAY+THE+FILE") If I simply paste this link in the browser, then it works direclty, bypassing the first file. May be it's due to the fact that "file:///" is an ftp?Any ideas or clues what can I do to play the second file directly? Thanks in anticipation, Kamran -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From rkern at ucsd.edu Wed Jul 27 16:27:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Jul 2005 13:27:16 -0700 Subject: Why Tcl/Tk? In-Reply-To: <20050727201258.25065.qmail@web51508.mail.yahoo.com> References: <20050727201258.25065.qmail@web51508.mail.yahoo.com> Message-ID: Jerry He wrote: > I'm a little curious, why does most scripting > languges(i.e. python and ruby) use Tcl/Tk rather than > wx or Fox as its standard GUI? Way back in the day, wx and Fox didn't exist (at least not in a usable form) while Tcl/Tk was rock-solid stable. > Although I did notice > that the Vpython IDE that uses Tkinker starts up a lot > faster than the DrPython IDE that uses wxpython. But > that makes no sense, Tk is based on Tcl, a scripting > language, but wx is written in C++. Scripting language != slow. C++ != fast. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bokr at oz.net Sat Jul 23 21:12:07 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Jul 2005 01:12:07 GMT Subject: Copying attributes References: <42e27cd3.954834309@news.oz.net> Message-ID: <42e2ea7d.982908838@news.oz.net> On Sat, 23 Jul 2005 18:30:29 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >Did it work on a quad face? What about putting in a debug print before places you use >f.normal, e.g. > assert hasattr(f, 'normal'), 'This "f"\n----\n%r\n----\ndid not have a normal attribute!!' % f > >If f.repr doesn't give you enough info, you can format something better in the assert message string. >> f.__repr__ was what I meant (as called due to %r in format), sorry. Regards, Bengt Richter From steveg at moregruel.net Fri Jul 29 10:28:11 2005 From: steveg at moregruel.net (Steve Greenland) Date: 29 Jul 2005 14:28:11 GMT Subject: poplib.POP3.list() returns extra value? References: <42e94d88$0$544$a726171b@news.hal-pc.org> Message-ID: <42ea3cfa$0$545$a726171b@news.hal-pc.org> According to Jeff Epler : > I'd consider it a doc bug too. If you feel comfortable doing it, dive > in and improve the documentation of poplib. Submitting a patch to the > patch tracker on sf.net/projects/python is probably the best way to do > this, if you have the necessary knowledge of cvs to produce a patch. Knowledge: yes; Time: maybe. If someone else gets there first, I won't be offended :-) Thanks for confirming... Steve -- Steve Greenland The irony is that Bill Gates claims to be making a stable operating system and Linus Torvalds claims to be trying to take over the world. -- seen on the net From peter at engcorp.com Mon Jul 25 11:32:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 11:32:09 -0400 Subject: Path PEP: What should Path(None) do? In-Reply-To: References: Message-ID: <5aKdnd5W9KOZm3jfRVn-iw@powergate.ca> Michael Hoffman wrote: > Currently it returns Path('None'). This means I have to do a check on > input before pathifying it to make sure it is not None. > > Perhaps it should throw ValueError? Without checking, I suspect it is merely doing str(x) or unicode(x) on whatever is passed to it: >>> path(None) path(u'None') >>> path(object()) path(u'') >>> path(3.14159) path(u'3.14159') Therefore I think the question should be broadened beyond just None. Should Path(x) simply call str(x) on the object or should it raise ValueError or TypeError or something if it's not a basestring? Given that pretty much *everything* in Python can have str() called on it, I think we should ask for a modicum of type-safety here and reject non-strings as input. -Peter From http Sat Jul 30 02:40:08 2005 From: http (Paul Rubin) Date: 29 Jul 2005 23:40:08 -0700 Subject: A replacement for lambda References: <867jf9jmfw.fsf@bhuda.mired.org> <42ead151@nntp0.pdx.net> Message-ID: <7x64usokzb.fsf@ruckus.brouhaha.com> James Richards writes: > Personally, I can't recall any decent programmer I know who objects > to actually writing out a variable name. In fact, I don't know a > single "real" programmer (this is one who writes programs he intends > to look at again in, say, 3 weeks) who doesn't insist on writing > "real" variable names. The issue is whether you want to name every intermediate result in every expression. sum = a + b + c + d + e is a lot nicer than x1 = a + b x2 = c + d x3 = x1 + e sum = x2 + x3 the language has nicely kept all those intermediate results anonymous. Python has first-class functions, which, like recursion, is a powerful idea that takes some getting used to. They let you say things like def derivative(f, t, h=.00001): # evaluate f'(t) numerically return (f(t+h) - f(t)) / h dy_dt = derivative(cos, 0.3) # approx. -sin(0.3) With anonymous functions, you can also say: dy_dt = derivative(lambda x: sin(x)+cos(x), 0.3) # approx. cos(.3)-sin(.3) Most Python users have experience with recursion before they start using Python, so they don't see a need for extra keywords to express it. Those not used to first-class functions (and maybe some others) seem to prefer extra baggage. For many of those used to writing in the above style, though, there's nothing confusing about using a lambda there instead of spewing extra verbiage to store that (lambda x: sin(x)+cos(x)) function in a named variable before passing it to another function. From peter at engcorp.com Thu Jul 14 12:49:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Jul 2005 12:49:08 -0400 Subject: Efficiently Split A List of Tuples In-Reply-To: References: Message-ID: Richard wrote: > On Wed, 13 Jul 2005 20:53:58 -0400, Peter Hansen wrote: >>a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) >>zip(*a) > This seems to work. Thanks. > > Where do I find documentation on "*args"? In the language reference: http://docs.python.org/ref/calls.html#calls -Peter From edvard+news at majakari.net Fri Jul 1 06:58:16 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Fri, 01 Jul 2005 13:58:16 +0300 Subject: Programmers Contest: Fit pictures on a page References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> <42c41ef2@usenet01.boi.hp.com> Message-ID: <87slyy23p3.fsf@titan.staselog.com> Dan Sommers writes: > There's some sort of irony or something in there about not writing the > best genetic algorithm, but I can't quite put my finger on it. +1 QOTW :) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From jason at tishler.net Thu Jul 28 08:34:10 2005 From: jason at tishler.net (Jason Tishler) Date: Thu, 28 Jul 2005 08:34:10 -0400 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <42E80300.4030708@llnl.gov> References: <20050725201132.GA3440@tishler.net> <20050727191626.GC2272@tishler.net> <42E7E351.3030706@llnl.gov> <20050727210307.GB3876@tishler.net> <42E80300.4030708@llnl.gov> Message-ID: <20050728123410.GA2144@tishler.net> Dean, On Wed, Jul 27, 2005 at 02:56:16PM -0700, Dean N. Williams wrote: > >I didn't get this error. Did you forgot to install one of the > >libdb${version}-devel packages: > > > > $ cygcheck -cd | grep 'libdb.*-devel' > > libdb2-devel 2.7.7-4 > > libdb3.1-devel 3.1.17-2 > > libdb4.1-devel 4.1.25-1 > > libdb4.2-devel 4.2.52-1 > > > No, I did an install all at the top of the installation. Didn't know I > needed to specify libraries. If I select "install" for everything > (that is, all packages show "install") shouldn't this include the > above? It should, but I wasn't looking over your shoulder when you ran Cygwin's setup.exe. :,) Anyway, please run the following and post the results to the list: $ cygcheck -cd | grep 'libdb.*-devel' Thanks, Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From dalke at dalkescientific.com Fri Jul 22 13:08:07 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 22 Jul 2005 17:08:07 GMT Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: Duncan Booth wrote: > Personally I think the concept of a specific path type is a good one, but > subclassing string just cries out to me as the wrong thing to do. I disagree. I've tried using a class which wasn't derived from a basestring and kept running into places where it didn't work well. For example, "open" and "mkdir" take strings as input. There is no automatic coercion. >>> class Spam: ... def __getattr__(self, name): ... print "Want", repr(name) ... raise AttributeError, name ... >>> open(Spam()) Traceback (most recent call last): File "", line 1, in ? TypeError: coercing to Unicode: need string or buffer, instance found >>> import os >>> os.mkdir(Spam()) Traceback (most recent call last): File "", line 1, in ? TypeError: coercing to Unicode: need string or buffer, instance found >>> The solutions to this are: 1) make the path object be derived from str or unicode. Doing this does not conflict with any OO design practice (eg, Liskov substitution). 2) develop a new "I represent a filename" protocol, probably done via adapt(). I've considered the second of these but I think it's a more complicated solution and it won't fit well with existing APIs which do things like if isinstance(input, basestring): input = open(input, "rU") for line in input: print line I showed several places in the stdlib and in 3rd party packages where this is used. > In other words, to me a path represents something in a filesystem, Being picky - or something that could be in a filesystem. > the fact that it > has one, or indeed several string representations does not mean that the > path itself is simply a more specific type of string. I didn't follow this. > You should need an explicit call to convert a path to a string and that > forces you when passing the path to something that requires a string to > think whether you wanted the string relative, absolute, UNC, uri etc. You are broadening the definition of a file path to include URIs? That's making life more complicated. Eg, the rules for joining file paths may be different than the rules for joining URIs. Consider if I have a file named "mail:dalke at example.com" and I join that with "file://home/dalke/badfiles/". Additionally, the actions done on URIs are different than on file paths. What should os.listdir("http://www.python.org/") do? As I mentioned, I tried some classes which emulated file paths. One was something like class TempDir: """removes the directory when the refcount goes to 0""" def __init__(self): self.filename = ... use a function from the tempfile module def __del__(self): if os.path.exists(self.filename): shutil.rmtree(self.filename) def __str__(self): return self.filename I could do dirname = TempDir() but then instead of os.mkdir(dirname) tmpfile = os.path.join(dirname, "blah.txt") I needed to write it as os.mkdir(str(dirname)) tmpfile = os.path.join(str(dirname), "blah.txt")) or have two variables, one which could delete the directory and the other for the name. I didn't think that was good design. If I had derived from str/unicode then things would have been cleaner. Please note, btw, that some filesystems are unicode based and others are not. As I recall, one nice thing about the path module is that it chooses the appropriate base class at import time. My "str()" example above does not and would fail on a Unicode filesystem aware Python build. > It may even be that we need a hierarchy of path > classes: URLs need similar but not identical manipulations > to file paths, so if we want to address the failings > of os.path perhaps we should also look at the failings > of urlparse at the same time. I've found that hierarchies are rarely useful compared to the number of times they are proposed and used. One of the joys to me of Python is its deemphasis of class hierarchies. I think the same is true here. File paths and URIs are sufficiently different that there are only a few bits of commonality between them. Consider 'split' which for files creates (dirname, filename) while for urls it creates (scheme, netloc, path, query, fragment) Andrew dalke at dalkescientific.com From rkern at ucsd.edu Wed Jul 6 14:06:08 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 06 Jul 2005 11:06:08 -0700 Subject: Scipy - Latex Annotations in plots In-Reply-To: References: Message-ID: fortuneteller wrote: > Hello, > > I'm quite new to python and Scipy. > Anyway I want to use it to plot graphs. > Does anybody know if there is the possibility to use Latex in SciPy's > plotting functions like gplt? I don't believe so. matplotlib, however, does have this functionality in recent releases. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ucntcme at gmail.com Thu Jul 14 17:31:07 2005 From: ucntcme at gmail.com (ucntcme at gmail.com) Date: 14 Jul 2005 14:31:07 -0700 Subject: Frankenstring In-Reply-To: References: <1121199858.674056.78250@g14g2000cwa.googlegroups.com> Message-ID: <1121376667.231929.173610@g44g2000cwa.googlegroups.com> >jay graves wrote: >> see StringIO or cStringIO in the standard library. > Just as with files, iterating over them returns whole lines, which is > unfortunately not what I want. Then why not subclass it and alter the iteration scheme to do a read(1) or something? from StringIO import StringIO class FrankenString(StringIO): lastidx = 0 atEnd = False def __iter__(self): while not self.atEnd: char = self.read(1) idx = self.tell() if self.lastidx == idx: self.atEnd = True self.lastidx = idx yield char From mwm at mired.org Sat Jul 23 14:01:47 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 23 Jul 2005 14:01:47 -0400 Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> Message-ID: <861x5ppfjo.fsf@bhuda.mired.org> Peter Hansen writes: >> * staticmethod Path.getcwd() -> Path.cwd() >> * bytes() / lines() / text() -> read_file_{bytes,lines,text} methods >> * write_{bytes,lines,text} -> write_file_{bytes,lines,text} methods > Under Linux isn't it possible to open and read from directories much > as with files? The OS doesn't matter - python won't let you open a directory as a file, even if the underlying OS will. The comment in Objects/fileobject.c is: /* On Unix, fopen will succeed for directories. In Python, there should be no file objects referring to directories, so we need a check. */ I think - but I'm not positive, and don't have a Linux box handy to check on - that this comment is false if your Unix is really Linux. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From macaronikazoo at gmail.com Sat Jul 16 22:17:15 2005 From: macaronikazoo at gmail.com (macaronikazoo) Date: 16 Jul 2005 19:17:15 -0700 Subject: secure uploading In-Reply-To: <7xzmsm5haw.fsf@ruckus.brouhaha.com> References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> <7x4qauaccl.fsf@ruckus.brouhaha.com> <1121563713.124461.230540@g47g2000cwa.googlegroups.com> <7xoe922p88.fsf@ruckus.brouhaha.com> <1121564015.242118.12780@g44g2000cwa.googlegroups.com> <7xzmsm5haw.fsf@ruckus.brouhaha.com> Message-ID: <1121566635.625110.202220@g14g2000cwa.googlegroups.com> oh ok cool. I'll ask them for some advice. thanks! From __peter__ at web.de Thu Jul 21 04:03:34 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Jul 2005 10:03:34 +0200 Subject: I just wanna know about os.path module.. References: <1121589035.602594.250570@g43g2000cwa.googlegroups.com> <1121622472.349346.182970@g49g2000cwa.googlegroups.com> Message-ID: kimes wrote: > You said 'At first os - module, or package, it doesn't matter here - is > imported.' With a file mop.py in your path import mop creates a module instance and executes mop.py to fill it with content -- classes, functions, whatever python objects you can think of -- and puts that module instance into the sys.modules cache. With a file mop/__init__.py, the process is the same except that the code to fill the module is taken from the __init__.py file. Differences only appear when you try to import submodules. > I'm still confused about that.. > When I just call import os.path without calling import os.. > In that case, you mean 'import os' is called implicitly? Yes. Try it yourself with a package/submodule where __init__.py and submodule.py just contain a print statement. I find such an experimental approach often more convenient than haunting the docs. > Why? and How? Because it's a sensible assumption that a submodule depends on its parent package? Because it makes access of submodules as easy as attribute access for any other object? Because it makes conditional imports easy (see Terry's post)? Because it's the simplest approach that just works? > how python knows it should call import when we call import os? > Please make me clear.. :) Conceptually, when you have a module alpha.beta.gamma you need just a bit of string processing. "alpha.beta.gamma".split() -- aah, I have to import alpha, then alpha.beta, then alpha.beta.gamma... read the source for the strategy that is actually taken if you really care. Peter From me at privacy.net Wed Jul 6 16:30:52 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 06 Jul 2005 16:30:52 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 6 Jul 2005 20:42:51 +0200, Stian S?iland wrote: > I'm all for it. I would even be tempted of changing def to function, > but it would look stupid in: > class A: > function make_my_day(self): > return "Your day" > a = A() > since a.make_my_day() is really a method, not a standalone function. > We could use "function" instead of "lambda" though =) So use "method" instead, which has the added advantage of implicity declaring an extra argument named "this": class A: method __init__(): this.x = 0 method make_my_day(foo): this.x += foo there-aren't-enough-winks-in-the-universe'ly yours, Dan -- Dan Sommers From sjuranic at gmail.com Tue Jul 19 10:43:53 2005 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 19 Jul 2005 07:43:53 -0700 Subject: Can I make the Python build use an already-installed version of Expat? Message-ID: <56190b6c050719074322020066@mail.gmail.com> I'm running into problems where Python and VTK both ship with their own distribution of the Expat parser. As long as you never use the Python XML package, everything is fine. But if you try using the Python XML parser after doing an `import vtk', a nice little message saying "Segmentation Fault" is your reward. For now, the workaround is to save the `import vtk' until after I do all my XML parsing. However, we're starting to build a rather large framework using Python and VTK, and I cannot guarantee that the VTK libraries won't be in memory when some of my XML parsing routines are called. I know that the VTK build has an option for forcing it to use an installation of Expat that's already on the system. But after looking at the Python build scripts, I can't find any such option for Python. Is this at all possible? I know that there is a way to tell Python to link to arbitrary libraries, but I don't know how to turn off the building of the "custom" Expat that comes with Python. Thanks for any tips, pointers, and insight. -- Steve Juranich Tucson, AZ USA From alexandre.fayolle at logilab.fr Thu Jul 7 15:19:12 2005 From: alexandre.fayolle at logilab.fr (Alexandre Fayolle) Date: Thu, 7 Jul 2005 21:19:12 +0200 Subject: ANN: python-constraint 1.0 In-Reply-To: <20050707064010.GA7979@burma.localdomain> References: <20050707064010.GA7979@burma.localdomain> Message-ID: <20050707191912.GE17474@logilab.fr> On Thu, Jul 07, 2005 at 03:40:10AM -0300, Gustavo Niemeyer wrote: > -------- > Overview > -------- > > **python-constraint** [1]_ is a Python module offering solvers for > Constraint Solving Problems (CSPs) over finite domains in simple > and pure Python. CSP is class of problems which may be represented > in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...), > and constraints (`a < b`, ...). > > .. [1] http://codespeak.net/~niemeyer/constraint/ People interested in CSP and python may also want to check Logilab's constraint module which has been available from some time at: http://www.logilab.org/projects/constraint/ Gustavo, maybe we should coordinate and merge our efforts? -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ncoghlan at gmail.com Fri Jul 29 20:35:10 2005 From: ncoghlan at gmail.com (NickC) Date: 29 Jul 2005 17:35:10 -0700 Subject: Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net><3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> <3kkf2vFv0mngU1@individual.net> <3kkj5tFv0el1U1@individual.net> Message-ID: <1122683709.934081.273730@o13g2000cwo.googlegroups.com> [Re: how to get at the base class] Do you really want to have a "only works for Path" way to get at the base class, rather than using the canonical Path.__bases__[0]? How about a new property in the os.path module instead? Something like os.path.path_type. Then os.path.path_type is unicode if and only if os.path.supports_unicode_filenames is True. Otherwise, os.path.path_type is str. Then converting a Path to str or unicode is possible using: as_str_or_unicode = os.path.path_type(some_path) The other thing is that you can simply make Path inherit from os.path.path_type. Regards, Nick C. From corey.coughlin at comcast.net Tue Jul 19 20:28:57 2005 From: corey.coughlin at comcast.net (corey.coughlin at comcast.net) Date: 19 Jul 2005 17:28:57 -0700 Subject: OO design References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: <1121819337.681408.65420@z14g2000cwz.googlegroups.com> I also have a little trouble with creating megaclasses. Usually I just try to think about what things are a little bit, and how I'm going to be using them. I think somebody else suggested a top down approach, and that makes a certain amount of sense. But at this point, you're probably getting tired of all the vague advice. It sounds like you don't have a very complicated set of concepts to deal with, so you probably won't wind up with too many classes, but having a single giant one is probably inconvenient. Here's how I would do things (although keep in mind, I only have a vague understanding of what you really need to do..) First off, you have your (x,y) datasets. It sounds like you perform most of your operations on those, so they'd probably be a good idea for a class. You may also want a class for the (x,y) points themselves, especially if you have any operations that collapse a point set to a single value or values (like your means and peaks and stuff.) So the methods on your (x,y) dataset probably want to be restricted to your mathematical operations. Although you'll also definitely want to look at the representation that gets passed onto your other classes. Thinking beyond those basic classes, you probably want to now think about your input and output operations. A general way of doing OOP for things like this is to try to abstract your input and output operations into objects based on what kinds of inputs or outputs they are. In this case it sounds like you have files, which are both input and output, and plots, which are just output. Both seem to take either single x,y sets or a number of sets. So each I/O object would appear to be some sort of object container for your x,y sets. Take the plot object. It will probably be fairly simple, just something you pass sets of x,y lists to and it plots them. You may want some more capabilities, like naming the sets, or giving the axes units, or whatever, but you can probably add that stuff later. Now for the file object. Luckily, python already includes a file object, so you already have something to base yours on. For the files, you have two basic operations, the read and the write. For the read, you'll need to pass in a filename, and have a way to return the datasets (like iterating over a data file produces a dataset, hm...). For output, you'll again need a filename, and a set of datasets to write. For both operations, you may also want to provide formatting options, unless you can figure it out from the filename or something. So the ultimate hierarchy might look something like this: class point: self.x self.y class dataset: self.data = [ #list of points ] self.units = '' #?? maybe def sum def mean # and so on class datafile: self.filename self.filetype self.datasets = [ #list of data sets? ] def read def write ## and so on class plot: self.datasets = { #dictionary of data sets, each named?} self.xaxis = '' self.yaxis = '' def makeplot ## and so on Looking at it like that, it might make some sense to come up with something like a dataset collection class that you can pass to plot or datafile, but if you can use something like a list (if the data is fairly arbitrary) or a dictionary (if the datasets have names or some other way of signifying what they're about), that will probably be enough. Anyway, that's just a rough sketch, hopefully it will give you some ideas if it doesn't seem like the best solution. From cam.ac.uk at mh391.invalid Thu Jul 28 18:03:29 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 28 Jul 2005 23:03:29 +0100 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Aahz wrote: >>One of these days I'm going to figure out how to embody "Namespaces are >>one honking great idea -- let's do more of those!" Then I shall be >>enlightened. > > What don't you understand about it? (This is a serious question -- I > can think of several answers to give you, but want to know what focus is > needed first.) I wasn't expecting a serious answer to this, but here goes. First, I wasn't a Python user when namespaces were introduced. It's hard for me to even imagine Python without namespaces. Did imported modules just go into the same namespace as everything else? Yuck. It's too bad this happened before there were PEPs so I could understand the design and what came before. Is it the fact that Python is unimaginable without namespaces that makes them such a honking great idea? Aren't they somewhat of an obvious idea? Several other languages have them. Was the implementation of namespaces easy or hard to explain? I'd love to do more honking great ideas, but I'm not even sure what the Dutch ideal of a honking great idea is in the first place. -- Michael Hoffman From bill.mill at gmail.com Sat Jul 16 22:33:08 2005 From: bill.mill at gmail.com (Bill Mill) Date: Sat, 16 Jul 2005 22:33:08 -0400 Subject: odd python/linux/cherrypy behavior In-Reply-To: References: Message-ID: <797fe3d405071619333656453c@mail.gmail.com> On 7/16/05, Dennis Lee Bieber wrote: > On Sat, 16 Jul 2005 19:54:31 -0400, Bill Mill > declaimed the following in comp.lang.python: > > > > The FAT dirs are mounted with the following options: > > defaults,user,umask=000 . I'm not sure what you mean by the execute > > bit, but all files do have execute permission. Here's the output of an > > ls -l on the file I'm talking about: > > > > -rwxrwxrwx 1 root root 1073 2005-07-15 21:40 > > /d/download/cherrypy/tutorial/tut01_helloworld.py > > > Out of curiosity, is it possible to change ownership to your > "user" account? > Thanks a lot, that worked. Any guess as to why? Peace Bill Mill bill.mill at gmail.com From travislspencer at gmail.com Wed Jul 20 16:56:11 2005 From: travislspencer at gmail.com (travislspencer at gmail.com) Date: 20 Jul 2005 13:56:11 -0700 Subject: Printing a variable's name not its value In-Reply-To: <1121889692.797655.165770@g47g2000cwa.googlegroups.com> References: <1121885268.069652.222540@f14g2000cwb.googlegroups.com> <42deaadb$0$6734$626a14ce@news.free.fr> <1121889692.797655.165770@g47g2000cwa.googlegroups.com> Message-ID: <1121892970.988204.184970@g14g2000cwa.googlegroups.com> travislspencer at gmail.com wrote: > Bruno Desthuilliers wrote: > > def printVerbose(*args, **kwargs): > > > > > if VERBOSE in globals: > > > for a in args: > > > if a in globals: > > > value = globals[a] > > for k, v in kwargs.iteritems(): > > > print "%s: %s" % (k, v) > > > > > Perfect. Thanks for the pointer. Well, almost perfect ;) -- Regards, Travis Spencer From francisco.borges at gmail.com Fri Jul 8 05:32:55 2005 From: francisco.borges at gmail.com (Francisco Borges) Date: 8 Jul 2005 02:32:55 -0700 Subject: PyX, matplotlib, 3D & LaTeX In-Reply-To: <1120813229.543202.310640@o13g2000cwo.googlegroups.com> References: <1120813229.543202.310640@o13g2000cwo.googlegroups.com> Message-ID: <1120815175.835697.133270@g43g2000cwa.googlegroups.com> Francisco Borges wrote: > 1. it takes more lines of code (than what I fell is needed) to do it; > 2. it (still) lacks easy ways to do frequent things (like filling) Sorry, I just realised the piece of nonsense I just wrote... PyX does fill objects very easily, what it does take lot's of work to do is to fill the intersection of two objects, or the intersection of a plot line and some chosen axis. Or is it just that I myself haven't learned how to do that properly.... Cheers, Francisco From grante at visi.com Thu Jul 28 16:53:30 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 28 Jul 2005 20:53:30 -0000 Subject: To thread or not to thread References: <1122577812.096734.157490@g14g2000cwa.googlegroups.com> Message-ID: <11eihea4o78ea20@corp.supernews.com> On 2005-07-28, Sidd wrote: > I was recently reading an article on threading in python and I > came across Global Interpreter Lock,now as a novince in python > I was cusrious about > > 1.Is writing a threaded code in python going to perform well > than a normal python code. It's sort of a corrolary to Amdahls law: on a single CPU machine, optimally written multi-threaded code will always perform worse than optimally written single-threaded code. [Where performance is in terms of CPU efficiency.] However, it may be very difficult to write optimal single-threaded code, and much easier to write (nearly) optimal multi-threaded code. So, in practice, multi-threaded code often performs better for certain classes of problems. > If so on what basis can it performance be measured. That's up to whoever is doing the measuring. > 2.Is writing a threaded code in python better than a code > written in C/C++ using PTHREADS. Define "better". On a multi-CPU machine you can get much more parallelism for compute-intensive tasks using C/pthreads than you can using Python threads. It's also a lot easier to write buggy code containing race conditions using C/pthreads. -- Grant Edwards grante Yow! I want to read my new at poem about pork brains and visi.com outer space... From cam.ac.uk at mh391.invalid Sun Jul 24 11:11:24 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jul 2005 16:11:24 +0100 Subject: FAQ? In-Reply-To: References: Message-ID: Keith P. Boruff wrote: > Michael Hoffman wrote: >> Keith P. Boruff wrote: >>> Is there an FAQ available specific to this NG as I'm sure some of the >>> list slicing questions I have have been asked before. >> >> Try Google for . > > I tried and didn't find one. That's why I asked here. When I Google for , almost all of the search results on the first page are Python FAQs. The third link even has a "newsgroup" FAQ although I doubt it is what you want, even though you said otherwise. Therefore I asked a question on why you want a *newsgroup* FAQ when it sounds like you want a *Python* FAQ, so that I and others could potentially be more helpful in answering your unasked question. >> I don't know why you would want to look in a FAQ *specific* to a >> newsgroup to look up slicing questions, > > I have a specific question about list slicing and this is a python NG. > What's not to understand? I can't understand why you think your list slicing problem is specific to the newsgroup and not to Python. > Is your attitude indicitive of most people on this NG or are you just > one of those NG guys who gets off on making the new people feel stupid? > If it's the former, I'll just go away. If that's the way you respond to people who are trying to help you, please do so. -- Michael Hoffman From tuxlover at gmail.com Mon Jul 11 17:15:21 2005 From: tuxlover at gmail.com (tuxlover at gmail.com) Date: 11 Jul 2005 14:15:21 -0700 Subject: Environment Variable Message-ID: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> Is it possible to set an environment variable from inside the python script which will be retained after the script exits. If I use the following code: import os os.putvar("name", "tuxlover") the enivironment variable name is visible to only the sub-process created by os.system and os.popen. But as soon as the python script vanishes, the environment variable "name" is gone. What I am wondering is that is it possible to set a environment variable from inside a python script, and then access it (say, echo $name from the shell) after the python script exits. Thanks Tuxlover From jan.danielsson at gmail.com Fri Jul 1 09:18:23 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Fri, 01 Jul 2005 15:18:23 +0200 Subject: Question about Python Message-ID: <42c54149$1@griseus.its.uu.se> Hello all, I recently started using Python, and I must say I like it. Both the language and libraries available for it. Background: I have written an application which I use to keep track of my personal economy. I wrote it in Java because I wanted to learn the language for a course in programming at my university. Now that I have acquired an interrest in Python I was thinking about porting my program to Python. But then it occured to me.. I started writing my program in Java pre-1.5. Then came 1.5, I upgraded, and my program would still compile and run, though I did get three warnings. The language had changed a little bit; I had to assign a type to three arrays. That wasn't so bad. However, when I look at the various Python modules/libraries, I see that there are several versions of them, for different versions of python. I've seen everything from "for python 1.5" up to "for python 2.4" with all versions in between. This scares me a little bit. I assume that the reason for the different versions is because of new language features? Is Python showing any signs of "stabilizing"? (Yes, I know there are pros to an evolving language). Will there ever be a time when a new major version of python won't mean getting new versions of the modules? For my economy program, I used DB2 as a database backend. I can be reasonable sure that there will always be a DB2 API for Java. However, I have found a DB2 module for Python, but I don't even know if it works with Python 2.4, and if I compile and use it, I can't be sure it'll work with the next python release, as far as I can tell. I'd like to ask seasoned Python developers: - Are you comfortable in upgrading to the latest version of Python, or are you worried about what you have to fix in your existing programs? - Put aside any unconditional love for Python for a second, and be honest: Have you ever run into version related problems? - Have you ever relied on a module, upgraded python version for some new important feature, but realized that the module you rely on hasn't been updated yet? If not, do you consider a possibility? - Do the module developers, in general, keep up with the development versions of python, so you can expect to find newly updated modules as new versions of python hits the streets? - Did you have similar worries to mine when you started working with Python? Please be honest.. It's better that I find out any potential problems now, than rant about them in six months. Thanks in advance to anyone willing to answer. From defaultuserbr at yahoo.com Mon Jul 11 13:34:52 2005 From: defaultuserbr at yahoo.com (Default User) Date: 11 Jul 2005 10:34:52 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> Message-ID: <1121103292.546514.5260@z14g2000cwz.googlegroups.com> Randy Howard wrote: > Keith Thompson wrote > (in article ): > > > > \||||/ | | \| __\,,\ /,,/__ > > \||/ | | | jgs (______Y______) > > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > > ============================================================== > > Out of curiosity, does anyone remember who 'jgs' refers to > above? http://en.wikipedia.org/wiki/Joan_Stark Brian From zanesdad at bellsouth.net Wed Jul 6 13:25:06 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 06 Jul 2005 13:25:06 -0400 Subject: inheriting file object In-Reply-To: References: Message-ID: <42CC13F2.4050808@bellsouth.net> Jeremy wrote: >Hello all, > I am trying to inherit the file object and don't know how to do it. I >need to open a file and perform operations on it in the class I am >writing. I know the simple syntax is: > >class MyClass(file): > ... > >but I don't know how to make it open the file for reading/writing. Can >anyone help me out with this? >Thanks, >Jeremy > > > Something like this? I put the following code in test_file.py: class MyFile(file): def doing_something(self): print "in my own method" And used it like this: In [1]: import test_file In [2]: f = test_file.MyFile("foobar.file", "w") In [3]: f.write("foo\n") In [4]: f.doing_something() in my own method But do you really need to subclass file, or can you just use a file instance in your class? Jeremy Jones From dalke at dalkescientific.com Sun Jul 24 17:31:48 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 24 Jul 2005 21:31:48 GMT Subject: [path-PEP] Path inherits from basestring again References: <3kehbmFtv6lpU1@individual.net> <3khgn6Fu8nm8U1@individual.net> <3khrkkFuhpimU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Okay. While a path has its clear use cases and those don't need above methods, > it may be that some brain-dead functions needs them. "brain-dead"? Consider this code, which I think is not atypical. import sys def _read_file(filename): if filename == "-": # Can use '-' to mean stdin return sys.stdin else: return open(filename, "rU") def file_sum(filename): total = 0 for line in _read_file(filename): total += int(line) return total (Actually, I would probably write it def _read_file(file): if isinstance(file, basestring): if filename == "-": # Can use '-' to mean stdin return sys.stdin else: return open(filename, "rU") return file ) Because the current sandbox Path doesn't support the is-equal test with strings, the above function won't work with a filename = path.Path("-"). It will instead raise an exception saying IOError: [Errno 2] No such file or directory: '-' (Yes, the code as-is can't handle a file named '-'. The usual workaround (and there are many programs which support '-' as an alias for stdin) is to use "./-" % cat > './-' This is a file % cat ./- This is a file % cat - I'm typing directly into stdin. ^D I'm typing directly into stdin. % ) If I start using the path.Path then in order to use this function my upstream code must be careful on input to distinguish between filenames which are really filenames and which are special-cased pseudo filenames. Often the code using the API doesn't even know which names are special. Even if it is documented, the library developer may decide in the future to extend the list of pseudo filenames to include, say, environment variable style expansion, as $HOME/.config Perhaps the library developer should have come up with a new naming system to include both types of file naming schemes, but that's rather overkill. As a programmer calling the API should I convert all my path.Path objects to strings before using it? Or to Unicode? How do I know which filenames will be treated specially through time? Is there a method to turn a path.Path into the actual string? str() and unicode() don't work because I want the result to be unicode if the OS&Python build support it, otherwise string. Is that library example I mentioned "brain-dead"? I don't think so. Instead I think you are pushing too much for purity and making changes that will cause problems - and hard to fix problems - with existing libraries. Here's an example of code from an existing library which will break in several ways if it's passed a path object instead of a string. It comes from spambayes/mboxutils.py ################# This is mostly a wrapper around the various useful classes in the standard mailbox module, to do some intelligent guessing of the mailbox type given a mailbox argument. +foo -- MH mailbox +foo +foo,bar -- MH mailboxes +foo and +bar concatenated +ALL -- a shortcut for *all* MH mailboxes /foo/bar -- (existing file) a Unix-style mailbox /foo/bar/ -- (existing directory) a directory full of .txt and .lorien files /foo/bar/ -- (existing directory with a cur/ subdirectory) Maildir mailbox /foo/Mail/bar/ -- (existing directory with /Mail/ in its path) alternative way of spelling an MH mailbox .... def getmbox(name): """Return an mbox iterator given a file/directory/folder name.""" if name == "-": return [get_message(sys.stdin)] if name.startswith("+"): # MH folder name: +folder, +f1,f2,f2, or +ALL name = name[1:] import mhlib mh = mhlib.MH() if name == "ALL": names = mh.listfolders() elif ',' in name: names = name.split(',') else: names = [name] mboxes = [] mhpath = mh.getpath() for name in names: filename = os.path.join(mhpath, name) mbox = mailbox.MHMailbox(filename, get_message) mboxes.append(mbox) if len(mboxes) == 1: return iter(mboxes[0]) else: return _cat(mboxes) if os.path.isdir(name): # XXX Bogus: use a Maildir if /cur is a subdirectory, else a MHMailbox # if the pathname contains /Mail/, else a DirOfTxtFileMailbox. if os.path.exists(os.path.join(name, 'cur')): mbox = mailbox.Maildir(name, get_message) elif name.find("/Mail/") >= 0: mbox = mailbox.MHMailbox(name, get_message) else: mbox = DirOfTxtFileMailbox(name, get_message) else: fp = open(name, "rb") mbox = mailbox.PortableUnixMailbox(fp, get_message) return iter(mbox) It breaks with the current sandbox path because: - a path can't be compared to "-" - range isn't supported, as "name = name[1:]" note that this example uses __contains__ ("," in name) Is this function brain-dead? Is it reasonable that people might want to pass a path.Path() directly to it? If not, what's the way to convert the path.Path() into the correct string object? Andrew dalke at dalkescientific.com From jack at performancedrivers.com Tue Jul 12 14:50:34 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 12 Jul 2005 14:50:34 -0400 Subject: Efficiency of using long integers to hold bitmaps In-Reply-To: <42d3fced@news.rivernet.com.au> References: <42d14ec3@news.rivernet.com.au> <42d165d0.311819733@news.oz.net> <42d3fced@news.rivernet.com.au> Message-ID: <20050712185034.GD15130@performancedrivers.com> On Wed, Jul 13, 2005 at 03:24:48AM +1000, Jeff Melvaine wrote: > Bengt, > > Thanks for your informative reply, further comments interleaved. > > "Bengt Richter" wrote in message > news:42d165d0.311819733 at news.oz.net... > > On Mon, 11 Jul 2005 02:37:21 +1000, "Jeff Melvaine" > > wrote: > > > >>I note that I can write expressions like "1 << 100" and the result is > >>stored > >>as a long integer, which means it is stored as an integer of arbitrary > >>length. I may need to use a large number of these, and am interested to > >>know whether the storage efficiency of long integers is in danger of > >>breaking my code if I use too many. Would I do better to write a class > >>that > >>defines bitwise operations on arrays of integers, each integer being > >>assumed > >>to contain at most 32 bits? I cannot find information in the Python > >>manuals > >>for 2.4.1 that would allow me to resolve this question; perhaps the > >>intention is that programmers should not rely on implementation details. > >> > >>Thanks in advance, > >> > > Sounds like a possible^H^H^H^H^H^H^H^Hprobable premature optimization > > worry ;-) > > > I'm writing a Sudoku solver of generic order. The object is not to make it > half a millisecond faster than the guy next door's solver, but I'd like it > to be able to do a bit more than just the daily newspaper puzzle, e.g. > search for uniquely solvable puzzles with minimal numbers of clues. > NP-completeness will put a lid on things sooner or later, but I'd like to > get as far as possible before that happens. > I would recommend making a hand-written C extension that does the heavy lifting - but only in the tiny corner you need it to. I've done this for the ICFP[1] competition the last few years. It is a time-limited competition so the priorities are getting a pure-python program up and running to understand the problem and then making the slow parts go really fast so you can try as many full games as possible to try out as many new strategies as possible. Typically this means just the "game board" representation is done in C. You'll want the heuristics to be done in python in order to try out variations easily. For Sudoku the board implementation will likely have C functions for copy(), valid() (raise ValueError), and something to return a list of obviously legal values for a coordinate. Passing coord tuples in and list & dictionaries out has worked well for me (easy to use in the python part of the program). I keep C modules out of production code unless absolutely necessary, but I have no qualms about using it in toy/hobby problems, especially because the C code stays at a manageable few hundred lines for toy problems. If you aren't much of a C guy check out pyrex[2]. In my darker days I did C++ for a living so I much prefer writing modules by hand; python makes it easy to do and it is faster, less buggy, and easier to debug. -jackdied [1] http://performancedrivers.com/icfp2002/ http://performancedrivers.com/icfp2004/ (other years I botched it badly enough I didn't make a webpage) http://performancedrivers.com/icfp2002/icfp_module.c http://performancedrivers.com/icfp2002/icfpBoard.c [2] http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/ From steve at REMOVETHIScyber.com.au Sun Jul 3 04:51:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 03 Jul 2005 18:51:07 +1000 Subject: a question References: Message-ID: On Sun, 03 Jul 2005 03:19:45 -0400, Xinyue Ye wrote: > when I type sys.ps2 after import sys, > I got the message like: > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.ps2 > AttributeError: 'module' object has no attribute 'ps2' > why does it happen? It works for me. >>> import sys >>> sys.ps2 '... ' Can you cut and past the relevant lines from your interactive session? -- Steven. From bogus@does.not.exist.com Fri Jul 1 10:25:02 2005 From: bogus@does.not.exist.com () Date: Fri, 01 Jul 2005 14:25:02 -0000 Subject: No subject Message-ID: #! rnews 1689 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Python for everything? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 29 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1120164834.057669.297840 at f14g2000cwb.googlegroups.com> Mime-Version: 1.0 Date: Fri, 1 Jul 2005 14:10:56 GMT Xref: news.xs4all.nl comp.lang.python:384366 Tom Anderson writes: > On Thu, 30 Jun 2005 xeys_00 at yahoo.com wrote: > > > can Python "do it all"? > [snip] > The other is in bit-twiddling - anything that involves > mucking about with data at the level of bits and bytes. Maybe this is > just blind prejudice, but i'm never as comfortable hacking on that > sort of stuff (writing a Huffman coder, say) in python as in java. Maybe we should distinguish: 1. Can you do it at all? Yes, via the struct package and via the bit operators. And, the bit operators support the same idioms we all know and love from C. 2. Can it be done "fast enough"? Maybe. I wrote a Morse code generator based on algorithms from a C program, which generated pcm files. The initial cut was way too slow. Then I did some caching and got it fast enough to use. Still not C speeds, but fast enough for the task. But if you are doing encryptions (where even C is giving way to hardware), then Python is not the answer. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From harold.fellermann at upf.edu Thu Jul 7 09:43:14 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 7 Jul 2005 15:43:14 +0200 Subject: Windows Cmd.exe Window In-Reply-To: <1120742729.424832.189110@f14g2000cwb.googlegroups.com> References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <1120742729.424832.189110@f14g2000cwb.googlegroups.com> Message-ID: <48cc122d9ef6d3dc90fd4ca36482a1da@upf.edu> On 07.07.2005, at 15:25, Giles Brown wrote: > Nah. You're missing my point. I only want the command window not to > be closed if there is an *exception*. Picky I know, but there you go. well, then register raw_input as exit function: >>> import atexit >>> atexit.register(raw_input) works fine in my terminal. should do in your framework also. cheers, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- From berthel4 at cti.ecp.fr Fri Jul 22 12:05:32 2005 From: berthel4 at cti.ecp.fr (Elby) Date: Fri, 22 Jul 2005 18:05:32 +0200 Subject: How to modify a file 'in place' ? Message-ID: <42e1194d$0$7428$626a14ce@news.free.fr> I'm looking for a the most simple and generic way to modify a file, with the possibility of making backups. In fact, I would like to emulate Perl's -i option. here is a bit of code, to explain it further : < code > from os import rename class Modif_File: def __init__(self, filename, ext='.bak'): old_name = filename + ext new_name = filename rename(new_name,old_name) self.old = open(old_name,'r') self.new = open(new_name,'w') # methods for getting data are linked to the old file : for attr in ('encoding', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'tell', 'xreadlines'): setattr(self,attr,getattr(self.old,attr)) # methods for putting data are linked to the new one : for attr in ('closed','flush','write', 'writelines'): setattr(self,attr,getattr(self.new,attr)) def close(self): self.new.close() self.old.close() for example, an equivalent of perl -i.bak -pe 's/\t+$//' *txt could be : < code > from glob import glob from re import compile, MULTILINE regex = compile(r'\t+$',MULTILINE) for f in [Modif_File(name) for name in glob('*.txt')]: f.write(regex.sub('',f.read())) f.close() Of course, this example is very basic and my class Modif_File does not take into account : - the right of the file - the mode of the file (binairy/text) - ...etc What is the best way to do it ? -- Elby From rorley at gmail.com Tue Jul 12 13:26:38 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 10:26:38 -0700 Subject: Help with inverted dictionary In-Reply-To: References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> Message-ID: <1121189198.800273.55020@g14g2000cwa.googlegroups.com> Thanks for the hints, I think I've figured it out. I've only been using Python for 2 days so I really needed the direction. If you were curious, this is not homework but an attempt to use the ConceptNet data (its an MIT AI project) to make a website in a Wiki-like format that would allow the data to be edited on the fly. I'll ask again if I need more help. You guys are great. Reece From andreas.lobinger at netsurf.de Fri Jul 15 06:27:27 2005 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Fri, 15 Jul 2005 12:27:27 +0200 Subject: using hotshot for timing and coverage analysis Message-ID: Aloha, hotshot.Profile has flags for recording timing per line and line events. Even if i had both set to 1 i still get only the standard data (time per call). Is there any document available that has examples how to use the hotshot for converage analysis and to display timing per line? Hoping for an answer and wishing a happy day LOBI From guy.lateur at b-b.be Tue Jul 5 06:00:21 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 05 Jul 2005 10:00:21 GMT Subject: Outlook COM: how to create a MailItem from a .msg file References: Message-ID: Are you saying it's unsafe to do that? I only need this for an application running locally, I mean, from within our LAN domain. We do have Exchange webmail. I've asked our Exchange expert wether or not IMAP is running; awaiting an answer.. "Richard Brodie" schreef in bericht news:dadla5$7e9$1 at blackmamba.itd.rl.ac.uk... > > I would have thought most wouldn't run IMAP in the clear; > over SSL maybe. > > From cappy2112 at gmail.com Thu Jul 14 13:22:59 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 14 Jul 2005 10:22:59 -0700 Subject: Synthesis Toolkit bindings for python? In-Reply-To: <1121351833.272380.161790@g43g2000cwa.googlegroups.com> References: <1121351833.272380.161790@g43g2000cwa.googlegroups.com> Message-ID: <1121361779.434923.5360@g49g2000cwa.googlegroups.com> Have you tried emailing the authors? From max at alcyone.com Sat Jul 23 03:35:15 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 23 Jul 2005 00:35:15 -0700 Subject: return None In-Reply-To: <11e2dru68unf2e8@corp.supernews.com> References: <3kcpbbFtjttlU1@individual.net> <11e2dru68unf2e8@corp.supernews.com> Message-ID: Grant Edwards wrote: > Personally, I don't really like the idea that falling off the > botton of a function implicitly returns None. It's just not > explicit enough for me. My preference would be that if the > function didn't execute a "return" statement, then it didn't > return anyting and attempting to use a return value would be an > error. That's not a bad idea. I tend to prefer self-documenting code whenever possible anyway, so if I a method ends that I don't intend to have a useful return value, I don't have a return statement with an argument, and if I intend a method that returns a useful value to return one that might be None, I do so expliclitly, rather than having the logic fall off the end of the function, making it unclear what was intended in the first place. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Grab a club and join the chorus / Evolution is a state of mind -- Oleta Adams From egbert.bouwman at hccnet.nl Wed Jul 20 17:22:52 2005 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 20 Jul 2005 23:22:52 +0200 Subject: python certification In-Reply-To: <1121872011.306282.88950@g47g2000cwa.googlegroups.com> References: <20050720142210.56E6D7EC2B@postix.sdv.fr> <1121872011.306282.88950@g47g2000cwa.googlegroups.com> Message-ID: <20050720212252.GA13932@hccnet.nl> On Wed, Jul 20, 2005 at 08:06:51AM -0700, Kay Schluehr wrote: > Andreas Kostyrka schrieb: > > > (These are the people look for Pearl and Pyhton programmers ;) ) > > Or Phyton :) In 2000 we had already the Phyththon Misspelling Contest. I presented then a regexp that could check if we were talking about the same language. However I must apologize. It didn't cover Pyhton. This is an improved version: pc=re.compile(r'\bph?(ph)*[iye]+h?(th?)+o?n+e?\b',re.I) As you see it covers pitn, and also spellings like pythonne, to accomodate the francophones. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From peter at engcorp.com Mon Jul 25 14:52:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 14:52:54 -0400 Subject: Run batch files in Windows XP In-Reply-To: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> References: <1122315456.966604.310360@g47g2000cwa.googlegroups.com> Message-ID: erniedude at gmail.com wrote: > I'm a newbie and I was wondering if anyone knew a (Python) script to > run 4 batch files, one after the other (assuming the directories are > known). It would be better if all 4 batch files could run > simultaneously, but that might break Windows... ;) The problem I had > was I couldn't get the files to RUN, only to OPEN. Thanks for the > help!!! You shouldn't need a Python program for that. To run the not simultaneously: call batch1.bat call batch2.bat call batch3.bat call batch4.bat Put those commands with appropriate names in a fifth batch file and execute that and it will work. To run them simultaneously (which won't break Windows, but might not do what you would like, depending on what those batch files actually do), just add the "start" command into the equation. You can get help on the start command using "start /?" at a DOS prompt. -Peter From sybrenUSE at YOURthirdtower.com.imagination Wed Jul 20 05:35:42 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 20 Jul 2005 11:35:42 +0200 Subject: Reg file uploading References: Message-ID: praba kar enlightened us with: > When we upload a file to the remote server we can get file type > through file extentions. No you can't, you can only make a better guess. If I name my PNG file somefile.jpg, you won't be able to get the file type through file extentions. > How we can find out file type if a file doesn't have any > extentions? One method is to look at the Content-type header the client sent along with the file. Another way is through the 'file' command. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From spam.csubich+block at block.subich.spam.com Tue Jul 5 15:21:49 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 05 Jul 2005 15:21:49 -0400 Subject: (Win32 API) callback to Python, threading hiccups In-Reply-To: References: Message-ID: <25Bye.46690$Xv.12976@bignews4.bellsouth.net> Francois De Serres wrote: > - so, on callback, I create a new thread, after checking that the > previous one has returned already (WaitOnSingleObject(mythread)) so we > only have one thread involved. Uh... to me, this looks like a frighteningly inefficient way of doing things. How about using a synchronous queue to post the data to a processing thread? That way, you don't have to create an entierly new thread each time you receive data in the callback. From dan at nospam.com Wed Jul 6 12:10:23 2005 From: dan at nospam.com (Dan) Date: Wed, 06 Jul 2005 11:10:23 -0500 Subject: How do you program in Python? In-Reply-To: References: <3iqif8Fmj34kU1@individual.net> Message-ID: On 7/6/2005 5:38 AM, Jorgen Grahn wrote: > On Sun, 03 Jul 2005 17:35:16 +0100, anthonyberet wrote: > ... > >>What I would really like is something like an old-style BASIC >>interpreter, in which I could list, modify and test-run sections of > You probably want to check out Wing IDE 2.0. There is a free trial. From godwinburby at rediffmail.com Tue Jul 12 02:27:15 2005 From: godwinburby at rediffmail.com (godwin) Date: 11 Jul 2005 23:27:15 -0700 Subject: Web App like Google Message-ID: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> Hello there, I need some thoughts about a web application that i am dreaming and drooling about in python. I want a search page to look exactly like Google. But when i press the search button, it should search a database in an rdbms like Oracle and provide results. For example, if my keywords are "all customers with names starting with 'God'" it should somehow search table CUSTOMER , with following query : SELECT CUSTNAME FROM CUSTOMER WHERE CUSTNAME LIKE 'God%' So we basically need is a good python parser module which parses the keywords into an sql or sqls and list the results. I can look in the keywords for table and column synonyms and map it into table and column names and create sql but it's not a foolproof idea as we all know that english is a very vague language. The above idea wil fail , if i can't identify table,column names ,operators and values in their logical orders so as to create a syntactically correct sql. If there are more tables involved, i should also think of joining tables (inner,outer,equi joins). All I want is some enlightening thoughts from the python hackers(i mean programmers) out there.Plz polish your grey cells and let me know your thoughts. # this is my basic and foolish keywordparser # the object db provides the table as well as column names # as u can see it may or may not work even for a single table class KeyWordParser(object): def __init__(self,keywords,db): self.keywords = keywords.upper().split() self.db = db self.tables = [] self.columns = [] def parse2sql(self): for word in self.keywords: if word in self.db.tables(): self.tables.append(word) for word in self.keywords: for table in self.tables: for column in self.db.columns(table): if column == word: self.columns.append(column) sql = 'SELECT %s FROM %s' % (','.join(self.columns) or '*',','.join(self.tables)) return sql From newsgroups at jhrothjr.com Tue Jul 5 07:39:51 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 5 Jul 2005 05:39:51 -0600 Subject: what is __init__.py used for? References: <1120552269.373658.254290@g49g2000cwa.googlegroups.com> Message-ID: <11ckscdmaucfe81@news.supernews.com> wrote in message news:1120552269.373658.254290 at g49g2000cwa.googlegroups.com... >I am a new learner of Python Programming Language. > Now. I am reading a book. ... > ========== > I was wonderring ... what is the __init__.py used for ? > This question may seems to be stupid for an expert. > But, if you can give the answer, it will be helpful for me. __init__.py is used for two things. One is as a flag to indicate that the python programs in the directory are part of a module. The other is as the module itself. Let's take a simple example. Assume you have a directory named breakfast which contains modules named spam.py, eggs.py, toast.py and jam.py, and that the directory containing breakfast is on the PYTHONPATH. If it try to import spam.py by writing import breakfast.spam it won't work because the breakfast directory doesn't contain an __init__.py file. If I then add __init__.py to the breakfast directory, the import will work, and the result will be *two* modules loaded. The first module will be bound to the identifier 'breakfast' in your module. It will be completely empty except for the identifier 'spam' which will have the spam module bound to it. This means that if the spam module contains, for example, an identifier named "vikings", then I can refer to it as breakfast.spam.vikings. The real kicker here is that when I say that the first module will be completely empty, it's not quite true. First, it will have some standard identifiers that all modules have, and second it will have anything you put into the __init__.py module file. This last is an advanced feature, and you're well advised to stay away from it until you've got a lot more experiance. HTH John Roth > > thanks. > From redhackgp at rediffmail.com Tue Jul 26 16:56:49 2005 From: redhackgp at rediffmail.com (Gurpreet Sachdeva) Date: 26 Jul 2005 20:56:49 -0000 Subject: Friend wants to learn python Message-ID: <20050726205649.26993.qmail@webmail29.rediffmail.com> http://www.byteofpython.info/download Wonderful book for newbie! Regards, G Blogs: http://garrythegambler.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Mon Jul 11 08:22:18 2005 From: me at privacy.net (Dan Sommers) Date: Mon, 11 Jul 2005 08:22:18 -0400 Subject: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code) References: <1120972298.061791.321710@f14g2000cwb.googlegroups.com> <20050710133959.83611.qmail@web31512.mail.mud.yahoo.com> <1121059708.002859.67570@g44g2000cwa.googlegroups.com> <3jei85FpehftU1@individual.net> Message-ID: On Mon, 11 Jul 2005 08:34:45 +0200, Reinhold Birkenfeld wrote: > Kay Schluehr wrote: >> Dan Sommers schrieb: >> >>> How about this: >>> >>> def __init__(self, self.x, y, self.z): >>> # self.x, self.z from first and third explicit parameters >>> do_something_with_y() >> >> Can you tell me in which way it is anyhow better than the original >> proposal >> >> def __init__(self, .x, y, .z): >> # self.x, self.z from first and third explicit parameters >> do_something_with_y() >> >> besides that it is more verbose? > It is more explicit. Explicit is better than implicit. > But as with many proposals, this raises consequential questions, for > example, how "self.x" parameters are handled in other methods, or even > functions, as __init__ is not special-cased by the parser. So why limit it to __init__? Bengt Richter's idea of generalizing it is a good one. Currently, when this method: def f(self, x, y, z): pass is called, Python binds self to a reference to the object, x to the first argument, y to the second argument, z to and the third. By extension, hypothetically, this method: def new_f(self, self.x, y, self.z): do_something_with_y() would be semantically identical to: def new_f(self, __anonymous_argument_1, y, __anonymous_argument_2): self.x = __anonymous_argument_1 del __anonymous_argument_1 # look: a use case for del! self.z = __anonymous_argument_2 del __anonymous_argument_2 do_something_with_y() It's not too far from the tuple unpacking that happens now: def g(x, (a, b)): pass q = (3, 4) g(1, q) # inside g, x = 1, a = q[0] = 3, b = q[1] = 4 and it's certainly not less explicit than properties. Without thinking it all the way through, I suppose these: def method_1(self, *self.l): pass def method_2(self, **self.d): pass could act as if they were these: def method_1(self, *args): self.l = args del args def method_2(self, **kw): self.d = kw del kw Regards, Dan -- Dan Sommers From gsakkis at rutgers.edu Sun Jul 31 12:14:32 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 31 Jul 2005 09:14:32 -0700 Subject: namespaces References: <42EC9690.2040301@tiscali.it> Message-ID: <1122826472.004836.273980@g43g2000cwa.googlegroups.com> Paolino wrote: > Steven D'Aprano wrote: > > > def translate(text): > > import string > > all=string.maketrans('','') > > badcars=all.translate(all,string.letters+string.digits) > > table=string.maketrans(badcars,'_'*len(badcars)) > > return text.translate(table) > > > > No pollution. > > And no efficience.Recalculating all,badcars and table was not an > acceptable solution ,sorry if I didn't state this point :( Then write a closure. You get both encapsulation and efficience, and as a bonus, customization of the translating function: import string def translateFactory(validChars=string.letters+string.digits, replaceChar='_'): all=string.maketrans('','') badcars=all.translate(all,validChars) table=string.maketrans(badcars, replaceChar*len(badcars)) def translate(text): return text.translate(table) # bind any attributes you want to be accessible # translate.badcars = badcars # ... return translate tr = translateFactory() tr("Hel\xfflo") George From steve at REMOVETHIScyber.com.au Wed Jul 13 10:47:33 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 14 Jul 2005 00:47:33 +1000 Subject: all possible combinations References: Message-ID: On Wed, 13 Jul 2005 10:21:19 -0400, rbt wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: > > 4^3 = 64 > > aaaa > abaa > aaba > aaab > acaa > aaca > aaac > ... > > What is the most efficient way to do this? Efficient for who? The user? The programmer? The computer? Efficient use of speed or memory or development time? If you want the fastest runtime efficiency, a lookup table of pre-calculated values. That is an O(1) operation, and you don't get any faster than that. If you expect to extend the program to arbitrary lists, pre-calculation isn't practical, so you need an algorithm to calculate permutations (order matters) or combinations (order doesn't matter). If you tell us what you need, I'm sure somebody will be able to help meet those needs. Otherwise, we're just guessing what you want. -- Steven. From jjlee at reportlab.com Fri Jul 8 09:30:32 2005 From: jjlee at reportlab.com (John J. Lee) Date: Fri, 8 Jul 2005 14:30:32 +0100 (GMT Daylight Time) Subject: Trainee Developer / Consultant Vacancy at ReportLab, London Message-ID: Vacancy at ReportLab, London ReportLab develop enterprise reporting and document generation solutions using cutting-edge Python technology, and have a growing business with an excellent blue chip customer base. You may also know us from our open source PDF and graphics library... We have a job opening for one trainee I.T. consultant working in our solutions team. Full time junior positions based in our Wimbledon (London, England) office. We are already interviewing, so a quick response is essential! Full details are at http://www.reportlab.com/careers.html Reply to vacancies at reportlab.com John From lambacck at computer.org Thu Jul 14 09:27:50 2005 From: lambacck at computer.org (Chris Lambacher) Date: Thu, 14 Jul 2005 09:27:50 -0400 Subject: How can I import a py script by its absolute path name? In-Reply-To: <87eka1eha8.fsf@titan.staselog.com> References: <87eka1eha8.fsf@titan.staselog.com> Message-ID: <20050714132750.GA6065@computer.org> You probably actually want: import sys sys.path.instert(0, r'c:\xxx\yyy') m = __import__('zzz', globals(), locals(), []) del sys.path[0] Because if another module named zzz exists in your path. Appending will pick those versions up first. Then you delete the path you just added so that you don't have any problems importing other modules that may have the same names a python files in the path you just added. -Chris On Thu, Jul 14, 2005 at 02:52:31PM +0300, Edvard Majakari wrote: > could ildg writes: > > > I want to import c:\xxx\yyy\zzz.py into my programme, > > What should I do? > > Thank you~ > > import sys > sys.path.append('c:\xxx\yyy') > import zzz > > (Untested, similar idiom would work in *nix systems, never programmed in > Windows) > > However, I guess it is not very usual you should need to import stuff from > arbitrary locations. Consider publishing those modules in normal Python > include path (just see what ''print sys.path'' produces) > > -- > # Edvard Majakari Software Engineer > # PGP PUBLIC KEY available Soli Deo Gloria! > > $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print > join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; > -- > http://mail.python.org/mailman/listinfo/python-list From skip at pobox.com Fri Jul 15 11:57:19 2005 From: skip at pobox.com (skip at pobox.com) Date: Fri, 15 Jul 2005 10:57:19 -0500 Subject: Python Programming Contest In-Reply-To: <42D7A188.2010306@sweetapp.com> References: <42D780EF.6020809@sweetapp.com> <17111.39597.277505.234455@montanaro.dyndns.org> <42D7A188.2010306@sweetapp.com> Message-ID: <17111.56543.474831.814515@montanaro.dyndns.org> Brian> This contest is for people who like thinking about algorithms. Surely you must have missed the smiley... S From en.karpachov at ospaz.ru Mon Jul 25 01:31:10 2005 From: en.karpachov at ospaz.ru (en.karpachov at ospaz.ru) Date: Mon, 25 Jul 2005 09:31:10 +0400 Subject: Invoke a method to a specific thread In-Reply-To: References: Message-ID: <20050725053110.GA2538@jk.dev> Mon, Jul 25, 2005 at 01:20:39PM +0800, Varghj?rta ?????: > When doing GUI apps in C# I often have to call a method that will > modify the GUI somehow from a different thread then the GUI is on (to > allow for GUI responsiveness). I simply call Invoke() or BeginInvoke > which resides in another thread with a delegate pointing to the method > I want to start in that thread. > > How would I go about doing this in Python? I don't know of this functionality in the standard python library, but look at the Twisted framework (http://twistedmatrix.com). What you need is http://twistedmatrix.com/projects/core/documentation/howto/threading.html#auto2 -- jk From viking_kiwi at yahoo.poofters.com Mon Jul 4 16:09:15 2005 From: viking_kiwi at yahoo.poofters.com (Rod Stephenson) Date: Mon, 04 Jul 2005 20:09:15 GMT Subject: Will Guido's "Python Regrets" ever get implemented/fixed? References: <1120367843.019938.257800@o13g2000cwo.googlegroups.com> <1120368681.573445.199710@g44g2000cwa.googlegroups.com> <1120371274.448543.145890@g43g2000cwa.googlegroups.com> <1120398483.415818.95360@o13g2000cwo.googlegroups.com> <11cicg4fbeer8e8@news.supernews.com> Message-ID: Rocco Moretti writes: > John Roth wrote: > > "Peter Maas" wrote in message > > news:dab25m$dvk$1 at swifty.westend.com... > > > >> George Sakkis schrieb: > >> > >>> Given that the latest 2.x python will be 2.9 > >> > >> > >> Why not 2.13 or 2.4711? Version strings are sequences of arbitrary > >> integers separated by dots and not decimal numbers, or are they? > > Because Guido said (somewhere) that he didn't want to go over > > release 2.9. > Knuths font design program METAFONT is currently version 2.71828 (and TeX is 3.141592). As new versions come out, the version numbers converge on e and pi respectively. (As he says, when they *equal* e and pi, they will be error free, by definition) -- Rule 1. From alet at unice.fr Fri Jul 8 10:09:40 2005 From: alet at unice.fr (Jerome Alet) Date: Fri, 08 Jul 2005 16:09:40 +0200 Subject: Obj.'s writing self-regeneration script ? References: <42CE7CA5.2090500@onecert.fr> Message-ID: Hi, Le Fri, 08 Jul 2005 15:16:21 +0200, Bas Michielsen a ?crit?: > Is there a good/standard way of having (composite) > objects write a Python script which will regenerate > the very same object ? I've done something like this for the ReportLab toolkit. Last time I checked, this was still part of the project under the name "pycanvas". You use a pycanvas.Canvas() instance just like you would use a canvas.Canvas() instance, but you can decide to regenerate an equivalent Python source program to your original program when rendering. The docstring explains how to use it. Also reportlab/test/test_pdfgen_pycanvas.py shows if it works or not. NB : this is not generic code, but maybe this can help you. bye Jerome Alet From gsakkis at rutgers.edu Tue Jul 12 14:53:13 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jul 2005 11:53:13 -0700 Subject: automatically assigning names to indexes References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> <1121169211.877343.200570@z14g2000cwz.googlegroups.com> <1121177247.196389.11080@z14g2000cwz.googlegroups.com> Message-ID: <1121194393.083830.256870@o13g2000cwo.googlegroups.com> wrote > > And what should happen for vectors of size != 3 ? I don't think that a > > general purpose vector class should allow it; a Vector3D subclass would > > be more natural for this. > > That's the 'magic' good idea I'm looking for. I think a unified Vector > class for all size vectors is a worthy goal! What 'magic' ? The (x,y,z) notation is used only for 3D vectors. (x,y) is also common for 2D and perhaps (t,x,y,z) for 4D, with t for time. There are only 26 letters (or 52 if you allow capitals), so I don't see how this can be generalized _usefully_ to arbitrary number of dimensions. George From Uche.Ogbuji at fourthought.com Sat Jul 30 13:34:47 2005 From: Uche.Ogbuji at fourthought.com (Uche Ogbuji) Date: Sat, 30 Jul 2005 11:34:47 -0600 Subject: [XML-SIG] xml-object mapping In-Reply-To: <42E90609.5030309@med.unc.edu> References: <42E90609.5030309@med.unc.edu> Message-ID: <1122744887.7589.17.camel@borgia> On Thu, 2005-07-28 at 12:21 -0400, Tamas Hegedus wrote: > Hi! > > I am looking for an xml-object mapping tool ('XML Data Binding-design > time product') where I can define the mapping rules in 'binding files' > and the parser is generated automatically. > > Similar to the solution of Dave Kuhlman > (http://www.rexx.com/~dkuhlman/generateDS.html) where the mapping is > defined in an xml file (if I am understand well). > > But I already have the target object. The xml-tags should not be used as > a property/member name, but should be mapped to an existing object. > > (There are existing tools, but written in Java (I would prefer Python; I > am biologist not using Java for 5 years), like JiBX > (http://jibx.sourceforge.net), Castor (http://www.castor.org; "XML-based > mapping file to specify bindings for existing object models")) Answered: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a63d0ad3fd23cb37/6ad0223c5b8f9946?lnk=st&q=python+xml&rnum=3&hl=en -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Use CSS to display XML, part 2 - http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html XML Output with 4Suite & Amara - http://www.xml.com/pub/a/2005/04/20/py-xml.html Use XSLT to prepare XML for import into OpenOffice Calc - http://www.ibm.com/developerworks/xml/library/x-oocalc/ Schema standardization for top-down semantic transparency - http://www-128.ibm.com/developerworks/xml/library/x-think31.html From sean_mcilroy at yahoo.com Fri Jul 1 19:07:20 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 1 Jul 2005 16:07:20 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> Tom Anderson wrote: > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? glad you asked. personally i don't know lisp (or scheme), but now i've decided to learn it, because eventually it will no longer be possible in python to pass functions as arguments or return them as values. the education sig will have to change its motto to "computer programming for every C-programmer". until then hangers-on like myself can use home-grown substitutes for the functional constructs (examples below), but in my opinion the best thing is to migrate as soon as possible. the real programmers are squeezing us out. now is the time to abandon python for an intelligent language (macros! real conditional evaluation instead of the and/or kluge!) def LISTCOMP(f,s,g): reval = [] for x in s: if g(x): reval.append(f(x)) return reval def LAMBDA(arguments,value): symbols = arguments.split(',') def reval(*args): for i in range(len(args)): locals()[symbols[i]] = args[i] return eval(value) return reval def MAP(f,s): return LISTCOMP(f,s,LAMBDA('x','True')) def FILTER(f,s): return type(s)(LISTCOMP(LAMBDA('x','x'),s,f)) def REDUCE(f,s,t): if not s: return t return f(s[0],REDUCE(f,s[1:],t)) From varghjarta at gmail.com Mon Jul 25 01:20:39 2005 From: varghjarta at gmail.com (=?ISO-8859-1?Q?Varghj=E4rta?=) Date: Mon, 25 Jul 2005 13:20:39 +0800 Subject: Invoke a method to a specific thread Message-ID: Taking the opportunity to ask yet another python question as a newbie to this list, that's been bugging a wee but that I've managed to put off. When doing GUI apps in C# I often have to call a method that will modify the GUI somehow from a different thread then the GUI is on (to allow for GUI responsiveness). I simply call Invoke() or BeginInvoke which resides in another thread with a delegate pointing to the method I want to start in that thread. How would I go about doing this in Python? If I have "GUIClass":... And start another thread and from that thread I want to call the method "PaintSomething()" in "GUIClass" _in_ the same thread that "GUIClass" lives in. If I'm making no sense please tell me. This is something I'd really want to know how to achieve. Thanks in advance! From kay.schluehr at gmx.net Mon Jul 18 09:05:49 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jul 2005 06:05:49 -0700 Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: <1121691948.976027.281070@z14g2000cwz.googlegroups.com> Bernhard Holzmayer schrieb: > Kay Schluehr wrote: > > > > > Now lets drop the assumption that a and b commute. More general: let be > > M a set of expressions and X a subset of M where each element of X > > commutes with each element of M: how can a product with factors in M be > > evaluated/simplified under the condition of additional information X? > > > > It would be interesting to examine some sorting algorithms on factor > > lists with constrained item transpositions. Any suggestions? > > > > Hello Kay, > > take this into account: > Restrictions like commutativity, associative, distributive and flexibility > laws don't belong neither to operands nor to operators themselves. > Instead these are properties of fields (set of numbers with respect to a > certain operation). > For a famous example for a somewhat "alternative" behaviour look at the > Octonions (discovered in 1843 by Graves and 1845 by Cayley), which are not > associative with respect to addition and/or multiplication. > (http://en.wikipedia.org/wiki/Octonions) or the Quarternions, which are > non-commutative (http://en.wikipedia.org/wiki/Quaternion) > > Obviously, it's not correct to say: addition is associative, or, that > multiplication is. With the same right, you could say, multiplication is > not associative. It was associative in the tiny example I presented. I did not mentioned to discuss the evolving structure of the whole CAS here in detail which would be better done in an own newsgroup once an early version is released. Maybe the setting of the original question should be made more precise: associative, non-commutative multiplicative groups. Handling non-associative algebras like Lie algebras is a completely different matter and I'm not even sure which one is the best way to represent operations in Python? Maye this way? >>> lie = Lie() # create an arbitrary Lie algebra (lie is again a class ) >>> A,B = lie(),lie() # create two arbitrary elements of the Lie algebra >>> lie[A,B] # create the commutator of the lie algebra by overloading lie[A,B] # the __getitem__ method >>> lie[A,B] == -lie[-A,B] True If one wants to enforce assertions like >>> lie[r*A,B] == r*lie[A,B] True for certain elements r of some group acting on lie, one must refine creation of lie in the initial assignment statement e.g. >>> lie = Lie(V) where V is some vectorspace and the elements of lie are homomorphisms on V. V is created elsewhere. There are a lot of constraints induced by all the objects dynamically coupled together. > With the same reasoning, we can show that it's not easy to generalize > sorting, commutation, association or distribution mechanisms. > > Maybe it would be a very fascinating goal to solve your algorithmic approach > in such a limited environment like the Quarternions. No CAS can represent infinitely many different representations of quaternions. But it should not be to hard to deal with an algebra that represents admissable operations on quaternions in an abstract fashion. > A solution for this set of numbers, if achieved in a clean, mathematically > abstract way, should hold for most other numbers/fields too, natural and > real included. > > I guess that the approach might be this way: > - define/describe the fields which shall be handled > - define/describe the rules which shall be supported > - find methods to reduce sequences of operations to simple binary or unary > operations (tokens) - this may introduce brackets and stacking mechanisms > - a weighing algorithm might be necessary to distinguish between plain > numbers and place holders (variables) > - application of the distributivity (as far as possible) might help to find > a rather flat representation and a base for reordering according to the > weights of the individual sub-expressions > > Nevertheless, there are lots of commercial programs which do such sort of > symbolic mathematics, and which would badly fail when it would come to such > awkward fields like Quarternions/Octonions. If you take a look on Mathematica or Maple both programs seem to interpret pure symbols as members of an associative and commutative algebra: expand( (a+x)^2) -> a^2 + 2ax + x^2 This works very fast and accurate but is mathematically too restricted for me. For doing more advanced stuff one needs to do a lot of programming in either language shipped with the CAS for creating new packages. But then I ask myself: why not doing the programming labor in Python and redesign and optimize the core modules of the CAS if necessary? Kay From peter at engcorp.com Wed Jul 13 08:52:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Jul 2005 08:52:28 -0400 Subject: Building a function call? In-Reply-To: References: Message-ID: <7OWdnRFJ_sHkk0jfRVn-hw@powergate.ca> Roland Heiber wrote: > Not the best (not at all) but one way: > > def dothat(x,y): > print "Called with:", x, y > > c = (1,2) > > locals().get("dothat")(*c) As you say, not the best, but in fact not really advisable under any circumstances. locals() returns "module level" stuff only when executed _at_ module level (i.e. not inside a function). Otherwise it will return only the local variables of the frame its in. Better is this, since it works for the OP's requirements in either situation. globals()['dothat'](*c) -Peter From tiissa at nonfree.fr Sat Jul 30 11:46:27 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 30 Jul 2005 17:46:27 +0200 Subject: showing help(M) when running module M standalone In-Reply-To: References: Message-ID: <42eba0d1$0$28795$626a14ce@news.free.fr> Chris wrote: > hello, > I have a small module which only contains some utility functions. when > running this standalone I would like to show the module docs and each > function docs, as if doing > > import M > help(M) > > I came up with the following but I reckon there is a much simpler way? > > if __name__ == '__main__': > print __doc__ > print "\nFUNCTIONS:\n" > for x in __all__: > print x > exec "print " + x + ".__doc__" > > Works but does not seem right using exec for such a task. One way would be to use the locals() [1] to get rid of the exec: if __name__ == '__main__': print __doc__ print "\nFUNCTIONS:\n" for x in __all__: print x print locals()[x].__doc__ However, if you just want to call help, calling it on '__main__' seems to work: if __name__ == '__main__': help(__name__) [1] http://docs.python.org/lib/built-in-funcs.html From elmo13 at jippii.fi Wed Jul 13 16:18:41 2005 From: elmo13 at jippii.fi (=?iso-8859-1?q?Elmo_M=E4ntynen?=) Date: Wed, 13 Jul 2005 23:18:41 +0300 Subject: Multivariable polynomials References: <1121219789.988951.122880@g47g2000cwa.googlegroups.com> Message-ID: On Tue, 12 Jul 2005 18:56:30 -0700, Chris wrote: > Does anyone know of a good standalone implementation of multivariable > polynomials in python? > > Thanks, > Chris I'm interested also, and am posting this in the hope that being now a multipostthread with a plus sign next to it, someone more knowledgeable would see it and answer our mutual request:) From opengeometry at yahoo.ca Tue Jul 19 20:26:09 2005 From: opengeometry at yahoo.ca (William Park) Date: Tue, 19 Jul 2005 20:26:09 -0400 Subject: How to kill easygui dialog? References: <1121800637.589080.210700@g47g2000cwa.googlegroups.com> Message-ID: <1e44d$42dd9a21$d1b7122a$29240@PRIMUS.CA> utabintarbo at gmail.com wrote: > I am using an easygui(http://www.ferg.org/easygui/index.html) dialog > (enterbox) to retrieve some info from a user. The program then goes on > and does a bit of processing, sometimes for several minutes. In the > meantime, the dialog stays there, dead but visible. I would prefer that > either another dialog ("Processing....") would be shown while > background stuff happens, or that the current dialog would simply > disappear. Ideas? I know I'm going to get flamed for this... but, perhaps, http://home.eol.ca/~parkw/index.html#gtk would side-step the problem altogether. Essentially, you describe your layout in XML syntax, feed it through Bash shell, and it will display GTK+2 widgets. When user clicks or types, data will be stored in shell variable or specified shell command will be executed. That's all. In order to call it from Python, you'd have to use os.system(), and store the shell variable to file or print it out to stdout. Then, you can read it back from Python. In fact, you can feed the input data directly from Python to shell. -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From tjreedy at udel.edu Thu Jul 7 16:12:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jul 2005 16:12:01 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: "jayessay" wrote in message news:m3r7ebvomy.fsf at rigel.goldenthreadtech.com... > 1. Someone recently remarked that good Lisp macros are basically > executable pseudo code. I think that is pretty much exactly right > and is a pretty good "sound bite" distillation of what it is all > about. Several years ago I remarked that Python reads like executable pseudocode. I still think that that is pretty much right. Googling, I discovered that the creators of some thing I had never heard of said the same thing about *their* language a couple of years ago. I wish web pages, like newgroup posts, were dated so one could better trace the history of such usages. Terry J. Reedy From reinhold-birkenfeld-nospam at wolke7.net Wed Jul 27 04:24:32 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 27 Jul 2005 10:24:32 +0200 Subject: finding out the calling function In-Reply-To: <2%FFe.154619$cb5.8344628@phobos.telenet-ops.be> References: <2%FFe.154619$cb5.8344628@phobos.telenet-ops.be> Message-ID: <3koum0Fvhs9lU1@individual.net> flupke wrote: > Hi, > > i have a property in a class that gets changed > and i would want to know who changes it. > Is there a way i can find out the calling function of a property? You're looking for sys._getframe. Reinhold From andreas.lobinger at netsurf.de Mon Jul 4 09:33:38 2005 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Mon, 04 Jul 2005 15:33:38 +0200 Subject: Obtaining glyph width in Python In-Reply-To: References: Message-ID: Aloha, Charlie wrote: > Hi, I'm looking for a way to obtain the width of a string, either in actual > inches/centimeters, or pixels will also work. Unfortunately this seems > difficult as I'd like to keep things as close to the stock Python install as > possible, and I'm not working with Graphics or X at all. So you need both: metrics for single characters/glyphs and con- catenated glyphs and words. > PIL = Huge for only using one function. I'm not working with any graphics. > PyFT = Everyone uses FreeType2 now, and PyFT seems dead anyhow. > PyFT2 = Does not exist. > tkinter.text() = Works with X, creates windows no matter what you do. > t1lib = Separate package, no TTF support. > t1python = Same thing as t1lib? For the glyph metrics and informations there is the ttx/fonttools project on sourceforge available. Afiar fonttools only need a Numeric installation. > Ultimately, I'm looking to take a stream of text, and break it up into lines > based on page width... and I need to know how wide (and ultimately how tall, > for page breaks) the individual glyphs are so I can break properly. If there's > an easier way to do this than calculating individual glyph width, I'm open to > that too. It looks like a little bit that you're redeveloping TeX (in python)... > I was really just looking to see if there was anything out there that wasn't > too large or too obscure/dated. Maybe there's something lower level that could > be done to achieve this? Is there metadata in the font that holds this > information that could be extracted? Actually there is not only meta but real data included in the font, speaking of Type1, TrueType and OpenType scalable outline fonts. Wishing a happy day LOBI From pink at odahoda.de Tue Jul 5 13:00:13 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Tue, 05 Jul 2005 19:00:13 +0200 Subject: Python Regular Expressions: re.sub(regex, replacement, subject) References: Message-ID: Vibha Tripathi wrote: > Hi Folks, > > I put a Regular Expression question on this list a > couple days ago. I would like to rephrase my question > as below: > > In the Python re.sub(regex, replacement, subject) > method/function, I need the second argument > 'replacement' to be another regular expression ( not a > string) . So when I find a 'certain kind of string' in > the subject, I can replace it with 'another kind of > string' ( not a predefined string ). Note that the > 'replacement' may depend on what exact string is found > as a result of match with the first argument 'regex'. Do mean 'backreferences'? >>> re.sub(r"this(\d+)that", r"that\1this", "this12that foo13bar") 'that12this foo13bar' Note that the replacement string r"that\1this" is not a regular expression, it has completely different semantics as described in the docs. (Just guessing: are you coming from perl? r"xxx" is not a regular expression in Python, like /xxx/ in perl. It's is just an ordinary string where backslashes are not interpreted by the parser, e.g. r"\x" == "\\x". Using r"" when working with the re module is not required but pretty useful, because re has it's own rules for backslash handling). For more details see the docs for re.sub(): http://docs.python.org/lib/node114.html -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From sybrenUSE at YOURthirdtower.com.imagination Tue Jul 12 16:14:46 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 12 Jul 2005 22:14:46 +0200 Subject: Environment Variable References: <1121116521.825911.60940@f14g2000cwb.googlegroups.com> <1121189578.883915.50620@o13g2000cwo.googlegroups.com> Message-ID: tuxlover enlightened us with: > No, the replies from Grant's and Sybren's do answer my question. It would be a lot more polite to actually thank the people helping you. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From kwharrigan at yahoo.com Fri Jul 22 10:43:10 2005 From: kwharrigan at yahoo.com (kwharrigan at yahoo.com) Date: 22 Jul 2005 07:43:10 -0700 Subject: time.time() under load between two machines In-Reply-To: References: <1122040119.230348.21580@g14g2000cwa.googlegroups.com> Message-ID: <1122043390.802579.40170@z14g2000cwz.googlegroups.com> Python version is 2.3.3. Using Windows XP SP2 as stated above. Network infrastructure is really irrelevant, what I'm attempting to figure out is how a time.time() call on another machine that occurs AFTER a message is received could occur before the message is actually sent. From miki.tebeka at zoran.com Fri Jul 8 13:02:20 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Fri, 8 Jul 2005 20:02:20 +0300 Subject: VC++ linking problem In-Reply-To: <1120740302.923649.291570@f14g2000cwb.googlegroups.com> References: <1120737131.171830.107080@g47g2000cwa.googlegroups.com> <1120740302.923649.291570@f14g2000cwb.googlegroups.com> Message-ID: <20050708170219.GH344@zoran.com> Hello J, > I will put a hold on compiling the latest version until I really have to. > I will probably switch to VC 7 before that. You can use the (free) MinGW compiler (www.mingw.org). It can build extension that link to Python 2.4. Just use distutils setup.py and run 'python setup.py build_ext -c mingw32' HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From belred at gmail.com Sun Jul 24 19:04:45 2005 From: belred at gmail.com (Bryan) Date: Sun, 24 Jul 2005 16:04:45 -0700 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <878xzwarjy.fsf@wilson.rwth-aachen.de> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> <878xzwarjy.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > > Besides, wxPython prepares for being included > into the standard distribution. > wow, i've never heard this said so explicitly. is there a reference link backing up this statement? i really really hope this is true. i'm very much in favor to see wx included in the standard distrubution. bryan From pyweek1 at mechanicalcat.net Thu Jul 28 23:04:24 2005 From: pyweek1 at mechanicalcat.net (pyweek1 at mechanicalcat.net) Date: Fri, 29 Jul 2005 13:04:24 +1000 Subject: Ann: Registration for the Python Game Programming Challenge is now open! Message-ID: <200507291304.25241.pyweek1@mechanicalcat.net> Registration is now open for the first Python Game Programming Challenge (also known as PyWeek). The challenge runs from Sunday August 28th to Sunday September 4th. That means there's only (checks website) 29 days to go before the challenge starts! Full details about the challenge, and registration, at the website: http://www.mechanicalcat.net/tech/PyWeek/ You may enter either individually or as a team. If you're keen and would like to join a team, but can't organise your friends, then sign up anyway and offer your services to other entrants. The challenge will use skills in Python programming, graphics, sound or music. For those who came in late, the PyWeek challenge: 1. Invites entrants to create a game (coded in Python) in one week from scratch either as an individual or in a team, 2. Aims to be challenging and fun, 3. Entries must be developed during the competition, and must incorporate some theme decided at the start of the competition, 4. Will hopefully increase the public body of python game tools, code and expertise, 5. Will let a lot of people actually finish a game, and 6. May inspire new projects (with ready made teams!) -- Visit the PyWeek website: http://www.mechanicalcat.net/tech/PyWeek/ From theller at python.net Thu Jul 7 10:13:23 2005 From: theller at python.net (Thomas Heller) Date: Thu, 07 Jul 2005 16:13:23 +0200 Subject: Windows Cmd.exe Window References: <1120740989.146267.145670@g44g2000cwa.googlegroups.com> <1120742729.424832.189110@f14g2000cwb.googlegroups.com> Message-ID: <7jg23drw.fsf@python.net> "Giles Brown" writes: > Nah. You're missing my point. I only want the command window not to > be closed if there is an *exception*. Picky I know, but there you go. I find it useful to set an sys.excepthook which calls the debugger pdb.pm(). This way I not only see the traceback, but I can also poke around in the environment to find the problem. Thomas From stefan.rank at ofai.at Fri Jul 22 11:01:53 2005 From: stefan.rank at ofai.at (Stefan Rank) Date: Fri, 22 Jul 2005 17:01:53 +0200 Subject: PEP on path module for standard library In-Reply-To: <1122041649.070945.85380@g49g2000cwa.googlegroups.com> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> Message-ID: <42E10A61.5060709@ofai.at> on 22.07.2005 16:14 George Sakkis said the following: > "Duncan Booth" wrote: > >>Personally I think the concept of a specific path type is a good one, but >>subclassing string just cries out to me as the wrong thing to do. In other >>words, to me a path represents something in a filesystem, the fact that it >>has one, or indeed several string representations does not mean that the >>path itself is simply a more specific type of string. >> [snip] > practicality-vs-purity decision. You're right, conceptually a path > HAS_A string description, not IS_A string, so from a pure OO point of > view, it should not inherit string. Java has `File` which mixes the concepts "an object in the filesystem" and "a structured locator for such objects (in a hierarchical fs) that might or might not correspond to an object that is actually there". `file` and `path` separate that. I think this is very reasonable. (It would be nice to get `path`(s) easily from a `file`, at the moment there is only file.name if I'm not mistaken). And a `path`, to me, actually IS_A string (unicode string) that happens to have special behaviour (such as os dependent quirks like a pathseparator that automatically get translated, comparable to '\n' used internally in strings translated to '\n'|'\r\n') stefan From sbassi at gmail.com Wed Jul 20 12:50:46 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Wed, 20 Jul 2005 13:50:46 -0300 Subject: How to store "3D" data? (data structure question) Message-ID: Hello, I have to parse a text file (was excel, but I translated to CSV) like the one below, and I am not sure how to store it (to manipulate it later). Here is an extract of the data: Name,Allele,RHA280,RHA801,RHA373,RHA377,HA383 TDF1,181,,,,, ,188,,,,, ,190,,,,, ,193,*,*,,, ,None,,,*,*,* ,,,,,, TDF2,1200,*,*,,,* ,None,,,*,*, ,,,,,, TDF3,236,,,,, ,240,,,,, ,244,*,,*,,* ,252,*,*,,, ,None,,,,*, ,,,,,, Should I use lists? Dictionary? Or a combination? The final goal is to "count" how many stars (*) has any "LINE" (a line is RHA280 for instance). RHA280 has 1 star in TDF1 and 1 star in TDF2 and 2 stars in TDF3. I am lost because I do analize the data "line by line" (for Line in FILE) so it is hard to count by column. -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From rkern at ucsd.edu Thu Jul 7 16:22:11 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 07 Jul 2005 13:22:11 -0700 Subject: Lisp development with macros faster than Python development?.. In-Reply-To: References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > "jayessay" wrote in message > news:m3r7ebvomy.fsf at rigel.goldenthreadtech.com... > >>1. Someone recently remarked that good Lisp macros are basically >> executable pseudo code. I think that is pretty much exactly right >> and is a pretty good "sound bite" distillation of what it is all >> about. > > Several years ago I remarked that Python reads like executable pseudocode. > I still think that that is pretty much right. > > Googling, I discovered that the creators of some thing I had never heard of > said the same thing about *their* language a couple of years ago. I wish > web pages, like newgroup posts, were dated so one could better trace the > history of such usages. Trawling through http://web.archive.org might help. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Mon Jul 18 20:19:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 20:19:29 -0400 Subject: Filtering out non-readable characters In-Reply-To: References: <1121474019.752266.122110@g43g2000cwa.googlegroups.com> <42d85d5d.291420430@news.oz.net> Message-ID: Michael Str?der wrote: > Peter Hansen wrote: > >>>>>''.join(chr(c) for c in range(65, 91)) >> >>'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > > > Wouldn't this be a candidate for making the Python language stricter? Why would that be true? I believe str.join() takes any iterable, and a generator (as returned by a generator expression) certainly qualifies. -Peter From gsakkis at rutgers.edu Sat Jul 23 03:28:27 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 23 Jul 2005 03:28:27 -0400 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <1122041649.070945.85380@g49g2000cwa.googlegroups.com> <1122074127.098fda4a2097406639f8c6b7f8b523ed@teranews> Message-ID: <1122103716.047d4c80bde51f39c1c9b5251fd07bfc@teranews> "Andrew Dalke" wrote: > [snipped] > > > Take for example the case where a PhoneNumber class is subclass > > of int. According to LSP, it is perfectly ok to add phone numbers > > together, subtract them, etc, but the result, even if it's a valid > > phone number, just doesn't make sense. > > Mmm, I don't think an integer is a good model of a phone number. > For example, in the US > 00148762040828 > will ring a mobile number in Sweden while > 148762040828 > will give a "this isn't a valid phone number" message. That's why phone numbers would be a subset of integers, i.e. not every integer would correspond to a valid number, but with the exception of numbers starting with zeros, all valid numbers would be an integers. Regardless, this was not my point; the point was that adding two phone numbers or subtracting them never makes sense semantically. > [snipped] > > > I just noted that conceptually a path is a composite object consisting of > > many properties (dirname, extension, etc.) and its string representation > > is just one of them. Still, I'm not suggesting that a 'pure' solution is > > better that a more practical that covers most usual cases. > > For some reason I think that > > path.dirname() > > is better than > > path.dirname > > Python has properties now so the implementation of the latter is > trivial - put a @property on the line before the "def dirname(self):". Sorry, I used the term 'property' in the broad sense, as the whole exposed API, not the specific python feature; I've no strong preference between path.dirname and path.dirname(). > I think that the string representation of a path is so important that > it *is* the path. There are (at least) two frequently used path string representations, the absolute and the relative to the working directory. Which one *is* the path ? Depending on the application, one of them woud be more natural choice than the other. > I trust my intuition on this, I just don't know how to justify it, or > correct it if I'm wrong. My intuition also happens to support subclassing string, but for practical reasons rather than conceptual. George From cam.ac.uk at mh391.invalid Fri Jul 29 13:44:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 29 Jul 2005 18:44:37 +0100 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: Jorge Godoy wrote: > Michael Hoffman wrote: > > >>He spends so much space on "Create Consistent Command-Line Interfaces," >>a section that, in Python, could be replaced with a simple "Use optparse." > > > In Perl there's also the equivalent of optparse, but where does it guarantee > that you'll use consistent name options and design a good interface? I > think he's point is much broader than parsing input from the command line. True, but a lot of his point *is* parsing input from the command line. Consider the following points paraphrased from his article: * Don't mix multiple ways of specifying options. (Solved by optparse) * If a flag expects an associated value, allow an optional = between the flag and the value. (Solved by optparse) * Allow single-letter options to be "bundled" after a single dash. (Solved by optparse) * Always allow -- as a file list marker. (Solved by optparse) And a lot of the other points are things that are made much, much, simpler by optparse, to the point that they become somewhat obvious. -- Michael Hoffman From bill.mill at gmail.com Fri Jul 29 10:49:57 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 29 Jul 2005 10:49:57 -0400 Subject: Ten Essential Development Practices In-Reply-To: <1f7befae05072907396ceb4c8c@mail.gmail.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <1f7befae05072907396ceb4c8c@mail.gmail.com> Message-ID: <797fe3d4050729074969d91c40@mail.gmail.com> > although, as some argue, it's > possible [GvR] thinks in base 9.5, that just doesn't seem Pythonic to me. +1 QOTW Peace Bill Mill bill.mill at gmail.com From bokr at oz.net Sat Jul 9 02:17:20 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 09 Jul 2005 06:17:20 GMT Subject: why UnboundLocalError? References: Message-ID: <42cf5dc4.178687859@news.oz.net> On Fri, 8 Jul 2005 21:21:36 -0500, Alex Gittens wrote: >I'm trying to define a function that prints fields of given widths >with specified alignments; to do so, I wrote some helper functions >nested inside of the print function itself. I'm getting an >UnboundLocalError, and after reading the Naming and binding section in >the Python docs, I don't see why. > >Here's the error: >>>> fieldprint([5, 4], 'rl', ['Ae', 'Lau']) >Traceback (most recent call last): > File "", line 1, in ? > File "fieldprint.py", line 35, in fieldprint > str +=3D cutbits() > File "fieldprint.py", line 11, in cutbits > for i in range(0, len(fields)): >UnboundLocalError: local variable 'fields' referenced before assignment > >This is the code: >def fieldprint(widths,align,fields): > > def measure(): > totallen =3D 0 > for i in range(0, len(fields)): > totallen +=3D len(fields[i]) > return totallen > > def cutbits(): > cutbit =3D [] > for i in range(0, len(fields)): > if len(fields[i]) >=3D widths[i]: > cutbit.append(fields[i][:widths[i]]) > fields =3D fields[widths[i]:] fields[i] = fields[i][widths[i]:] # did you mean this, analogous to [1] below? > elif len(fields[i]) > 0: > leftover =3D widths[i] - len(fields[i]) > if align[i] =3D=3D 'r': > cutbit.append(' '*leftover + fields= >[i]) > elif align[i] =3D=3D 'l': > cutbit.append(fields[i] + ' '*lefto= >ver) > else: > raise 'Unsupported alignment option= >' > fields[i] =3D '' ^^^^^^^^^-- [1] > else: > cutbit.append(' '*widths[i]) > return cutbit.join('') > > if len(widths) !=3D len(fields) or len(widths)!=3Dlen(align) or >len(align)!=3Dlen(fields): > raise 'Argument mismatch' > > str =3D '' > > > while measure()!=3D0: > str +=3D cutbits() > >What's causing the error? Maybe the missing [i]'s ? It's not clear what you are trying to do with a field string that's wider than the specified width. Do you want to keep printing lines that have all blank fields except for where there is left-over too-wide remnants? E.g., if the fields were ['left','left12345','right','12345right'] and the widths were [5,5,6,6] and align 'llrr' should the printout be (first two lines below just for ruler reference) 1234512345123456123456 LLLLLLLLLLRRRRRRRRRRRR left left1 right12345r 2345 ight or what? I think you can get the above with more concise code :-) but a minor mod to yours seems to do it: >>> def fieldprint(widths,align,fields): ... def measure(): ... totallen = 0 ... for i in range(0, len(fields)): ... totallen += len(fields[i]) ... return totallen ... def cutbits(): ... cutbit = [] ... for i in range(0, len(fields)): ... if len(fields[i]) >= widths[i]: ... cutbit.append(fields[i][:widths[i]]) ... #fields = fields[widths[i]:] ... fields[i] = fields[i][widths[i]:] # did you mean this, analogous to [1] below? ... elif len(fields[i]) > 0: ... leftover = widths[i] - len(fields[i]) ... if align[i] == 'r': ... cutbit.append(' '*leftover + fields[i]) ... elif align[i] == 'l': ... cutbit.append(fields[i] + ' '*leftover) ... else: ... raise 'Unsupported alignment option' ... fields[i] = '' # <-- [1] ... else: ... cutbit.append(' '*widths[i]) ... # XXX return cutbit.join('') ... return ''.join(cutbit) ... if len(widths) != len(fields) or len(widths)!=len(align) or len(align)!=len(fields): ... raise 'Argument mismatch' ... # str = '' ... result_lines = [] ... while measure()!=0: ... result_lines.append(cutbits()) ... #str += cutbits() ... return '\n'.join(result_lines) ... >>> fieldprint([5,5,6,6], 'llrr', ['left', 'left12345', 'right', '12345right']) 'left left1 right12345r\n 2345 ight' >>> print fieldprint([5,5,6,6], 'llrr', ['left', 'left12345', 'right', '12345right']) left left1 right12345r 2345 ight Note that for i in xrange(len(items)): item = items[i] # mess with item just to walk through items one item at a time is more concisely written for item in items: # mess with item and if you really need the index i as well, for i, item in enumerate(items): # use item and i here Also, if you are going to raise 'Argument mismatch' it would be better to do it at the beginning and use a standard exception. String exceptions are frowned upon these days, so probably raise ValueError or TypeError with the string as an argument instead, unless you have a more informative thing to do. BTW, measure above can be defined with current builtins as (untested) def measure(): return sum([len(field) for field in fields]) I'll leave a few things ... HTH Regards, Bengt Richter From kbchung at hongik.ac.kr Sun Jul 31 03:24:08 2005 From: kbchung at hongik.ac.kr (KB) Date: 31 Jul 2005 00:24:08 -0700 Subject: How to convert a string like '777' to an octal integer like 0777? References: <1122787665.484685.48370@z14g2000cwz.googlegroups.com> <42ec640a@news.eftel.com> Message-ID: <1122794648.326967.284070@g47g2000cwa.googlegroups.com> Thanks, John. But my point is how to keep the leading zero in 0777, in order to be used in os.chmod('myfile', 0777)? From steve at REMOVETHIScyber.com.au Wed Jul 6 08:48:12 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 06 Jul 2005 22:48:12 +1000 Subject: frozenset question References: <42cbacc9$0$10475$da0feed9@news.zen.co.uk> <42cbb2bc$0$7905$fa0fcedb@news.zen.co.uk> Message-ID: On Wed, 06 Jul 2005 11:30:14 +0100, Will McGugan wrote: > I was wondering if frozenset was faster or more efficient in some way. > > Thinking back to the dark ages of C++, you could optimize things that > you knew to be constant. Why would you want to? py> import sets py> import time py> bigset = sets.Set(range(500000)) py> bigimmutableset = sets.ImmutableSet(range(500000)) py> assert len(bigset) == len(bigimmutableset) py> py> def tester(S, L): ... """Test if items from L are in S, and time the process.""" ... t = time.time() ... for i in range(100): ... for item in L: ... item in S ... return time.time() - t # time returned is for 100 loops ... py> Time some successful tests: py> tester(bigset, range(100, 500)) 0.11539506912231445 py> tester(bigimmutableset, range(100, 500)) 0.12014198303222656 Practically no difference when doing 100*400 checks of whether an integer is in the set. But let's try again, just in case: py> tester(bigset, range(100, 500)) 0.10998892784118652 py> tester(bigimmutableset, range(100, 500)) 0.11114096641540527 The difference is insignificant. How about unsuccessful checks? py> tester(bigset, range(-100, -500, -1)) 0.12070298194885254 py> tester(bigset, range(-100, -500, -1)) 0.11681413650512695 py> tester(bigimmutableset, range(-100, -500, -1)) 0.11313891410827637 py> tester(bigimmutableset, range(-100, -500, -1)) 0.11315703392028809 There is no significant speed difference between immutable and mutable sets, at least for queries. Regardless of whether it is successful or unsuccessful, mutable or immutable, it takes about 0.0000025 second to do each test of item in set. Why would you need to optimize that? If you tell us what you are trying to do, and under what circumstances it is too slow, we'll see if we can suggest some ways to optimize it. But if you are just trying to optimize for the sake of optimization, that's a terrible idea. Get your program working first. Then when it works, measure how fast it runs. If, and ONLY if, it is too slow, identify the parts of the program that make it too slow. That means profiling and timing. Then optimize those parts, and nothing else. Otherwise, you will be like the car designer trying to speed up his sports cars by making the seatbelts aerodynamic. -- Steven. From not at active.invalid Mon Jul 18 19:11:46 2005 From: not at active.invalid (TA) Date: Tue, 19 Jul 2005 01:11:46 +0200 Subject: Cursor navigation Message-ID: <42dc3722$0$67264$157c6196@dreader2.cybercity.dk> Hi, This might be a silly question, but I was wondering how you would navigate backwards in a PostgreSQL cursor when the Python DB-API 2.0 allows records to be fetched in a forward-only manner? I have tried different solutions - two of which are included here. The first solution uses the cursor declared implicitly by the pyPgSQL interface, but for some reason this does not work as expected. (RH-8.0, Python-2.2.1, pyPgSQL-2.4.0, PostgreSQL-7.2.2) >>> # First solution >>> from pyPgSQL import PgSQL >>> con = PgSQL.connect() >>> con.conn.toggleShowQuery 'On' >>> cur = con.cursor() QUERY: BEGIN WORK >>> cur.execute("select * from test") QUERY: DECLARE "PgSQL_081B3B64" CURSOR FOR select * from test QUERY: FETCH 1 FROM "PgSQL_081B3B64" QUERY: SELECT typname, -1 , typelem FROM pg_type WHERE oid = 23 QUERY: SELECT typname, -1 , typelem FROM pg_type WHERE oid = 1043 >>> cur.execute("fetch 1 in \"%s\" " % cur.name) QUERY: fetch 1 in "PgSQL_081B3B64" >>> r = cur.fetchall() QUERY: FETCH ALL FROM "PgSQL_081B3B64" >>> r [[2, 'name2'], [3, 'name3'], [4, 'name4'], [5, 'name5'], [6, 'name6']] The 'fetchall()' returns the remaining five rows in the table and not just a single row as expected. The other solution explicitly declares another cursor. >>> # Second solution >>> from pyPgSQL import PgSQL >>> con = PgSQL.connect() >>> con.conn.toggleShowQuery 'On' >>> cur = con.cursor() QUERY: BEGIN WORK >>> cur.execute("declare acursor cursor for select * from test") QUERY: declare acursor cursor for select * from test >>> cur.execute("fetch 1 in acursor") QUERY: fetch 1 in acursor QUERY: SELECT typname, -1 , typelem FROM pg_type WHERE oid = 23 QUERY: SELECT typname, -1 , typelem FROM pg_type WHERE oid = 1043 >>> r = cur.fetchall() >>> r [[1, 'name1']] >>> cur.execute("fetch 1 in acursor") QUERY: fetch 1 in acursor >>> r = cur.fetchall() >>> r [[2, 'name2']] >>> cur.execute("fetch -1 in acursor") QUERY: fetch -1 in acursor >>> r = cur.fetchall() >>> r [[1, 'name1']] This works as expected. Only a single row is returned and it is possible to fetch rows forwards and backwards in the cursor, but is this really the way to do this? If anyone can explain what I'm doing wrong or suggest another approach, it would be much appreciated. -- TA Denmark From chinook.nr at tds.net Fri Jul 1 12:43:12 2005 From: chinook.nr at tds.net (Chinook) Date: Fri, 01 Jul 2005 12:43:12 -0400 Subject: Speaking of list-comprehension? In-Reply-To: References: Message-ID: Chinook wrote whilst his head was elsewhere: >> >>So, where might I have found this construct. >> >>>>>ta = [5, 15, 12, 10, 9] >>>>>nta = [tai+[10,-10][tai>=10]for tai in ta] >>>>>nta >> >>[15, 5, 2, 0, 19] >> Immediately after posting and shutting down last night, I had one of those expansive moments that visit us elderly more and more infrequently. Duh :b whack %) x + c[b] and within a list comprehension too - how embarrassing I guess the OL reply was just trying to be kind to the intellectually defecient ;') Just goes to show that you can't help those that can't help themselves :<)) Thank you all for allowing me to waste your time, Lee C From cfbolz at gmx.de Sat Jul 30 07:16:22 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sat, 30 Jul 2005 13:16:22 +0200 Subject: PyPy sprint announcement: Heidelberg 22nd - 29th August 2005 Message-ID: <42EB6186.20105@gmx.de> PyPy Sprint in Heidelberg 22nd - 29th August 2005 ================================================== The next PyPy sprint will take place at the Heidelberg University in Germany from 22nd August to 29th August (both days included). Its main focus is translation of the whole PyPy interpreter to a low level language and reaching 2.4.1 Python compliancy. To learn more about the new PyPy Python implementation look here: http://codespeak.net/pypy Goals and topics of the sprint ------------------------------ One of the main goals of the sprint is going to be a 0.7 release of PyPy. The 0.7 is meant to be the first self-contained PyPy version but still alpha with some C-extension modules missing and not meant for production use. Therefore the topics of the sprint will be: - translation efforts: it's not completely clear now what related task will be left at that time - work on 2.4.1 compliancy: there are some failing compliancy tests on which we plan to work - rewriting c-extension modules/integrating existing rewrites - all kinds of small release issues - possibly some more LLVM efforts Location & Accomodation ------------------------ The sprint will be held in a conference room of the Institute of Physics, University of Heidelberg. We have WLAN connection there and small kitchen to make tea and coffee. `See here`_ how to get there from the Heidelberg main station. There is a huge number of hotels_ in Heidelberg, all of which are unfortunately rather expensive. It should be no problem to reach the sprint venue from anywhere in Heidelberg. As an alternative you could also take a `hotel in Mannheim`_ which you can reach in 15 min from Heidelberg with the train. .. _`See here`: http://www.physi.uni-heidelberg.de/physi/front/anfahrt.en.php .. _hotels: http://www.cvb-heidelberg.de/index_eng.html .. _`hotel in Mannheim`: http://www.hotels.de/en/mannheim.htm Exact times ----------- The Pypy sprint is held Monday 22nd August - Monday 29th August 2005. Hours will be from 09:00 until people have had enough. It's a good idea to arrive a day before the sprint starts. Network, Food ------------- The Heidelberg Altstadt can be reached in approximately 10 min from the sprint venue. There you will find all kinds of restaurants and fast food places. You will probably need a wireless network card to access the network although we could set up a WLAN to cable bridge if necessary. Registration etc.pp. -------------------- Please subscribe to the `PyPy sprint mailing list`_, introduce yourself and post a note that you want to come. Feel free to ask any questions there! There also is a separate `Heidelberg people`_ page tracking who is already thought to come. If you have commit rights on codespeak then you can modify yourself a checkout of http://codespeak.net/svn/pypy/extradoc/sprintinfo/heidelberg-people.txt .. _`Heidelberg people`: http://codespeak.net/pypy/index.cgi?extradoc/sprintinfo/heidelberg-people.html .. _`PyPy sprint mailing list`: http://codespeak.net/mailman/listinfo/pypy-sprint -- Carl Friedrich Bolz & the PyPy-Team From rorley at gmail.com Tue Jul 12 11:38:28 2005 From: rorley at gmail.com (rorley at gmail.com) Date: 12 Jul 2005 08:38:28 -0700 Subject: Help with inverted dictionary In-Reply-To: <1121182343.731328.38020@g47g2000cwa.googlegroups.com> References: <1121179590.933181.307470@g14g2000cwa.googlegroups.com> <1121181602.408662.210790@g14g2000cwa.googlegroups.com> <1121181950.339056.171260@g44g2000cwa.googlegroups.com> <1121182343.731328.38020@g47g2000cwa.googlegroups.com> Message-ID: <1121182708.823296.206170@o13g2000cwo.googlegroups.com> I will transfer eventually use a database but is there any way for now you could help me make the text files? Thank you so much. Reece From myfriendmyfriend at gmail.com Tue Jul 12 11:42:17 2005 From: myfriendmyfriend at gmail.com (Your Friend) Date: 12 Jul 2005 08:42:17 -0700 Subject: Issues With Threading Message-ID: <1121182937.775486.51050@o13g2000cwo.googlegroups.com> Hello All, I'm having issues capturing the output from a program while using threading. Program runs ok when I run without threading. Here's my Python code and the Java class that is called by it. Python : #!/usr/bin/python import popen2 import threading for id in range( 10 ) : ( err_out, stdin ) = popen2.popen4( ( '/usr/bin/java JavaTest %s' ) % ( id ) ) for line in err_out.readlines() : print line, def test( id ) : print "Called %s" % ( id ) ( err_out, stdin ) = popen2.popen4( ( '/usr/bin/java JavaTest %s' ) % ( id ) ) for line in err_out.readlines() : print line, #for id in range( 10 ) : # thread = threading.Thread( target=test, args=( [ id ] ) ) # thread.start() Java : import java.util.Date; public class JavaTest { public static void main( String args[] ) { System.out.println( args[0] + " - " + new Date().toString() ); } } When I run without threading, I get the correct output : 0 - Tue Jul 12 11:33:51 EDT 2005 1 - Tue Jul 12 11:33:52 EDT 2005 2 - Tue Jul 12 11:33:52 EDT 2005 3 - Tue Jul 12 11:33:53 EDT 2005 4 - Tue Jul 12 11:33:53 EDT 2005 5 - Tue Jul 12 11:33:54 EDT 2005 6 - Tue Jul 12 11:33:54 EDT 2005 7 - Tue Jul 12 11:33:54 EDT 2005 8 - Tue Jul 12 11:33:54 EDT 2005 9 - Tue Jul 12 11:33:54 EDT 2005 When I uncomment the threading section and run again, I see that the function is called, but the result from the Java code does not get printed : Called 0 Called 1 Called 2 Called 3 Called 4 Called 5 Called 6 Called 7 Called 8 Called 9 I hope this is just a nuance that I've run across and it's an easy solution ... any advice pointing me in the right direction would be greatly appreciated. Thanks From stian at soiland.no Wed Jul 6 14:47:51 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 6 Jul 2005 20:47:51 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> Message-ID: <20050706184751.GU12095@itea.ntnu.no> On 2005-07-06 01:46:05, Steven D'Aprano wrote: > I had NEVER even heard the word "tuple" before learning Python. I spent > weeks mispelling it as "turple", and I finally had to look it up in a > dictionary to see if it was a real English word. Out of the four English > dictionaries in my house, none of them have the word. Agree, I have the problem of writing "tupple" in all comments and documentations. It's a weird word indeed =) > t = immutable_list(L) > map(anonymous_function x: x+1, L) Hey, I know! t = python.util.ImmutableArrayList.fromCollection(L.getAbstractCollection()) python.util.functional.applyFunctionOnCollection( (class implements python.util.functional.AnonymousFunction: def anonymousFunction(x): return x+1 ), L) -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] From peter at engcorp.com Sun Jul 3 14:43:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 14:43:14 -0400 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <11cbl3rb2alb32@news.supernews.com> <1120361191.481114.134500@z14g2000cwz.googlegroups.com> <42c7f923$1@nntp0.pdx.net> Message-ID: Steven D'Aprano wrote: > Frankly, I find this entire discussion very surreal. Reduce etc *work*, > right now. They have worked for years. If people don't like them, nobody > is forcing them to use them. Python is being pushed into directions which > are *far* harder to understand than map and reduce (currying, decorators, > etc) and people don't complain about those. I find it surreal too, for a different reason. Python *works*, right now. It has worked for years. If people don't like the direction it's going, nobody is forcing them to upgrade to the new version (which is not imminent anyway). In the unlikely event that the latest and greatest Python in, what, five years or more?, is so alien that one can't handle it, one has the right to fork Python and maintain a tried-and-true-and-still-including-reduce- -filter-and-map version of it, or even just to stick with the most recent version which still has those features. And that's assuming it's not acceptable (for whatever bizarre reason I can't imagine) to use the inevitable third-party extension that will provide them anyway. I wonder if some of those who seem most concerned are actually more worried about losing the free support of a team of expert developers as those developers evolve their vision of the language, than about losing access to something as minor as reduce(). -Peter From jstroud at mbi.ucla.edu Mon Jul 4 18:48:52 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 4 Jul 2005 15:48:52 -0700 Subject: f*cking re module In-Reply-To: <20050704193920.GB9841@burma.localdomain> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <20050704193920.GB9841@burma.localdomain> Message-ID: <200507041548.52366.jstroud@mbi.ucla.edu> On Monday 04 July 2005 12:39 pm, Gustavo Niemeyer wrote: > > > the only thing I want are the number of places blabla, Re modules > > > sucks! and blabla are. > > > > Your question is still not clear. What you're searching for is > > '', which isn't there, so .search returns None, and so > > you get that exception (.group takes an argument, anyway). > > That's what I love in that news group. Someone comes with a > stupid and arrogant question, and someone else answers in a > calm and reasonable way. Its perhaps that they remember the frustration of being new to programming. Those "wasted" 1.5 hr sessions getting nowhere add up pretty fast and then the explicatives begin to flow. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bill.mill at gmail.com Wed Jul 6 17:01:25 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 6 Jul 2005 17:01:25 -0400 Subject: Scipy - Latex Annotations in plots In-Reply-To: References: Message-ID: <797fe3d405070614015154ebec@mail.gmail.com> > Robert Kern wrote: > > > fortuneteller wrote: > >> Hello, > >> > >> I'm quite new to python and Scipy. > >> Anyway I want to use it to plot graphs. > >> Does anybody know if there is the possibility to use Latex in SciPy's > >> plotting functions like gplt? > > > > I don't believe so. matplotlib, however, does have this functionality in > > recent releases. On 7/6/05, Matthias R. wrote: > Unfortunately matplotlib is only a 2D-plotting library. > > Do you know another one with 3D-capabilities as well? > That would be very nice, > Perhaps gnuplot.py (http://gnuplot-py.sourceforge.net/) will work for you? It is a thin wrapper around Gnuplot, which is very good at producing ps format images, and is capable of producing 3 dimensional graphs. Peace Bill Mill bill.mill at gmail.com PS please try to not top-post, you can lose the rest of the thread easily From nospam at foo.com Wed Jul 6 13:19:01 2005 From: nospam at foo.com (jayessay) Date: 06 Jul 2005 13:19:01 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: "seberino at spawar.navy.mil" writes: > I've been reading the beloved Paul Graham's "Hackers and Painters". > He claims he developed a web app at light speed using Lisp and lots > of macros. That was the original "yahoo store". > It got me curious if Lisp is inherently faster to develop complex > apps in. For complex applications IMO/E there is no question that it is. But that is due to a lot of reasons, not only macros. > It would seem if you could create your own language in Lisp using > macros that that would be quite an advantage.... Here's the story. It has long been known that "domain specific languages" (DSL) are a significantly more potent means of producing applications (or chunks of them) in their domains than any so called "general purpose" language. This is true even if the DSL is not a particularly great piece of work. There are several examples of this that most everyone knows about (though they may not realize it), with "regular expressions" and SQL being among the most obvious. You can take this further to "application specific languages" (ASL) which provide even more leverage (though even narrower focus). Obvious examples of this sort of thing would include AutoCAD and the "grammar languages" of LALR parser generators. The reason these things are so much better (for what they do) than hacking away in your general purpose language is that the abstractions they provide are much closer to what you want to say. They are much more _declarative_ than procedural. You say _what_ you want done, instead of specifying a lot of how that will produce the what [1]. Lisp (by which I mean here Common Lisp) macros enable you to build DSLs and ASLs directly into the base language. This has several advantages beyond what the DSLs/ASLs themselves bring; some obvious ones being: * You don't have to write lexers and parsers, that part is provided to you for "free" by the Lisp reader[2]. In particularly sophisticated cases you may need to alter the reader behavior (via the readtables) and/or build a code walker to analyze things. But that would be several sigmas out of the norm. * Better yet, you don't have to write backend code generators. The expansion code of a macro just gets compiled by the Lisp compiler (typically an optimizing native code generator). * The DSL/ASL code can be seamlessly used with the base language (and libraries) just like when you use proprietary class libraries you've built from within the base language. Only here, you get a much higher level of abstraction and expressive power. So, you can freely use a DSL/ASL where it applies (and get all its advantages), but can effortlessly move to the base language when stepping outside its focus. * Better yet, in highly complex application scenarios you can have a number of DSLs/ASLs each bringing their own high expressive power and move freely among them and the base language. This should all work naturally together in concert. * Most idioms can be abstracted away and the bugs associated with them disappear as well. You don't have to remember sequences of "right, in these cases I first have to do this, then I have to call this that and the next thing in this order, and finally make sure I end it all with this bit over here." Their are a few standard red herings trotted out against all this. For example, "you mean you have a different programming language for each application! That's awful." or some variant. If you think about it for a moment, this is complete nonsense. Why? Because you need to do this anyway - building and learning a set of class libraries for an applicaion or domain (along with all its idioms as well) is actually much more work, more painful, and (typically) buys you less. The point is, you need to learn the "vocabulary" of application or domain code whether or not you use DSLs/ASLs. Worse, without the DSL/ASL approach you also need to learn a number of idioms of how to _procedurally_ make use of the resources to achieve _what_ you want. Another red hering goes something like: "it is much harder to learn a DSL/ASL than to simply use your base general purpose language". Most programmer types espousing this are really weird, because in the next breath they will be extolling the virtues of regular expressions, or list comprehension or some other DSL that just happens to already be embedded in their favorite language. Also, it makes no sense anyway - DSLs and ASLs are exactly the kind of thing provided to lay people at the user end of many application scenarios. Are they really somehow that much superior to learning these things than programmers? Another one is "fragmentation". This is really a kind of variant on the first, but it is used so often that it deserves its own mention. Basically the argument is that if you build DSLs and ASLs eventually your base language "fragments" and you have a few dozen languages instead. A few seconds thought and it is easy to see that this is no different than having a number of class libraries and in both cases the idea of "framenting" the base language is nonsense. OTOH, there _are_ issues associated with the DSL/ASL approach and Lisp macro programming generally. IMO, the _key_ thing is to realize that you don't want to have joe/jane-avg-hack, building these things, because they will likely *$*%! it up. You don't have to be a genius or something, but you have to be a _good_ designer and someone who knows how to keep ergonomics and elegance front and center in the process. The other thing is (again IMO, others will definitely disagree with this) that you should focus on getting people who know something about language design and compilation/translation to do this work. You certainly need a clear understanding of the differences between compile time, load time and runtime and what is going on at each of these stages to do the best work here. The best way to structure this is to have a group solely devoted to building the DSL/ASL, with input from the domain experts, other high level developers, and even some from joe/jane-avg-hack. The result is then used by the application developers proper, including joe/jane-avg-hack. This can and probably should be a process of continual refinement. The entire thing can even be collapsed into one individual (for smaller projects), but you need to be keenly aware of what hat you have on at any given point. Even so, it should be fairly clear that this isn't that much different from what you would want to do in building your applications core class system. It just has different areas of emphasis and expertise. > I realize that Python has operator overloading and OOP so I'm not sure. This is simply orthogonal to the whole issue. Lisp has the most potent object system available in any extent programming language. While "operator overloading" (aka "static dispatch" or "compile time dispatch") is controversial in some circles, it is quite easy to provide with some macrology as well. > Any *evidence* one way or another? There's plenty of evidence, but as with any software productivity issue, it's mostly anecdotal. Hard scientific evidence for such things is basically non existent and the economics of such things pretty much guarantee it is going to stay that way. ----------------------------------- 1. Someone recently remarked that good Lisp macros are basically executable pseudo code. I think that is pretty much exactly right and is a pretty good "sound bite" distillation of what it is all about. 2. Or, coming at from another angle, you don't have to figure out how to cobble together a bunch of extraneous applications (lexers, parers generators, code generators, etc.) into the one you are building. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From hancock at anansispaceworks.com Fri Jul 1 19:06:39 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 1 Jul 2005 18:06:39 -0500 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: <200507011806.39373.hancock@anansispaceworks.com> On Friday 01 July 2005 03:36 pm, Ron Adam wrote: > I find map too limiting, so won't miss it. I'm +0 on removing lambda > only because I'm unsure that there's always a better alternative. Seems like some new idioms would have to be coined, like: def my_function(a1, a2): def _(a,b): return a+b call_a_lib_w_callback(callback=_) doesn't seem too bad, and defeats the "wasting time thinking of names" argument. > So what would be a good example of a lambda that couldn't be replaced? I suspect the hardest would be building a list of functions. Something like: powers = [lambda a, i=i: a**i for i in range(10)] which you might be able to make like this: powers = [] for i in range(10): def _(a,i=i): return a**i powers.append(_) which works and is understandable, but a bit less concise. The main obstacle to the lambda style here is that def statements are not expressions. I think that's been proposed as an alternative, too -- make def return a value so you could say: powers = [def _(a,i=i): return a**i for i in range(10)] Personally, I think this is understandable, and given that lambda is to be pulled, a nice substitute (I would say it is easier to read than the current lambda syntax, and easier for a newbie to understand). But it would probably encourage some bad habits, such as: myfunc = def _(a,b): print a,b return a+b which looks too much like Javascript, to me, where there are about three different common idioms for defining a function (IIRC). :-/ -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From pinard at iro.umontreal.ca Fri Jul 22 11:13:03 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 22 Jul 2005 11:13:03 -0400 Subject: Difference between " and ' In-Reply-To: <200507220929.58036.hancock@anansispaceworks.com> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <20050722130902.GB2284@alcyon.progiciels-bpi.ca> <200507220929.58036.hancock@anansispaceworks.com> Message-ID: <20050722151303.GA5572@alcyon.progiciels-bpi.ca> [Terry Hancock] > On Friday 22 July 2005 08:09 am, Fran?ois Pinard wrote: > > > [Robert Kern] > > > > > One habit that seems to crop up, though, is that I will use '' for > > > internal strings and "" for strings that will eventually get seen > > > by the user. Don't ask me why. > > One sure thing is that it would help, later, if you ever want to > > internationalise a Python program. Not that it occurs that often! :-) > Whoa. Why? Does xgettext not recognize _('')? Yes, of course. The most tedious part of internationalising a project is the selection of strings to be translated, among all program strings, and wrapping these within the special _(...) construct. If you can _already_ rely on the fact double-quote strings are always to be wrapped, and that single-quote strings are never to be wrapped, the tedious part is already done, or almost. A few relatively quick editor commands are may complete that aspect of the work (provided you use a reasonably featureful editor). As for Using xgettext or its Python counterpart, this is usually burned into the release engineering (Makefile, distutils, or else), and is not much of an effort, once you found a good recipe or example for it. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From oddr at home.no.no Tue Jul 26 05:57:23 2005 From: oddr at home.no.no (Odd-R.) Date: 26 Jul 2005 09:57:23 GMT Subject: regex problem Message-ID: Input is a string of four digit sequences, possibly separated by a -, for instance like this "1234,2222-8888,4567," My regular expression is like this: rx1=re.compile(r"""\A(\b\d\d\d\d,|\b\d\d\d\d-\d\d\d\d,)*\Z""") When running rx1.findall("1234,2222-8888,4567,") I only get the last match as the result. Isn't findall suppose to return all the matches? Thanks in advance. -- Har du et kj?leskap, har du en TV s? har du alt du trenger for ? leve -Jokke & Valentinerne From reinhold-birkenfeld-nospam at wolke7.net Mon Jul 25 11:33:51 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 25 Jul 2005 17:33:51 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <74SdndipGes3nnjfRVn-1w@powergate.ca> References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> <74SdndipGes3nnjfRVn-1w@powergate.ca> Message-ID: <3kkf2vFv0mngU1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: >> Current change: >> >> * Add base() method for converting to str/unicode. > > Would basestring() be a better name? Partly because that seems to be > exactly what it's doing, but more because there are (or used to be?) > other things in Path that used the word "base", such as "basename". > > -1 on that specific name if it could be easily confused with "basename" > types of things. Right, that was a concern of mine, too. "tobase"? "tostring"? "tobasestring"? Alternative is to set a class attribute "Base" of the Path class. Or export PathBase as a name from the module (but that's not quite useful, because I expect Path to be imported via "from os.path import Path"). Reinhold From johng2001 at rediffmail.com Sun Jul 10 17:02:32 2005 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 10 Jul 2005 14:02:32 -0700 Subject: Another newbie question from Nathan. In-Reply-To: <42d02601$0$6916$b9fe7a78@news.usenetrevolution.com> References: <42c63341$0$6997$b9fe7a78@news.usenetrevolution.com> <42d02601$0$6916$b9fe7a78@news.usenetrevolution.com> Message-ID: <1121029352.184435.196820@f14g2000cwb.googlegroups.com> Nathan Pinno wrote: > Hi all, > > How do I make Python get a def? Is it the "get" function, or something > else? I need to know so that I can get a def for that computer > MasterMind(tm) game that I'm writing. > > BTW, I took your advice, and wrote some definitions for my Giant > Calculator program. Might make the code easier to read, but harder to code > because I have to keep going to the top to read the menu. Not that fun, but > necessary for a smooth program, I guess. > > Nathan Pinno Read the following tutorials first, perhaps in that order. http://honors.montana.edu/~jjc/easytut/easytut/ http://www.ibiblio.org/obp/thinkCSpy/ http://docs.python.org/tut/tut.html From gene.tani at gmail.com Thu Jul 14 01:20:05 2005 From: gene.tani at gmail.com (gene tani) Date: 13 Jul 2005 22:20:05 -0700 Subject: Web App like Google In-Reply-To: <1121316385.789726.23780@g44g2000cwa.googlegroups.com> References: <1121149635.529126.297090@g49g2000cwa.googlegroups.com> <1121188057.886202.86860@g43g2000cwa.googlegroups.com> <1121272270.930838.144340@g14g2000cwa.googlegroups.com> <1121316385.789726.23780@g44g2000cwa.googlegroups.com> Message-ID: <1121318405.829040.216750@g14g2000cwa.googlegroups.com> Good luck, report back. My canonical 1st step w/stuff that looks like NLP, is to flip thru the Jurafsky/Martin and Norvig Russell AI texts and identify paths of least resistance, like naive Bayesian or LSI, that have perl/python/ruby/C packages that i can thrash around in with my data . some other NLP packages: http://www.ellogon.org/ http://web.media.mit.edu/~hugo/montylingua/ From hugonz at gmail.com Thu Jul 21 02:05:45 2005 From: hugonz at gmail.com (hugonz at gmail.com) Date: 20 Jul 2005 23:05:45 -0700 Subject: Dose someone have installed python on IRIX ? In-Reply-To: References: Message-ID: <1121925945.411771.113810@f14g2000cwb.googlegroups.com> Hi, No I have not done it before, but no one is able to help you if you do not post what kind of errors you are getting. Basically if it compiled and linked ok, maybe you specified something in the ./configure script that the plattform does not support... Hugo From alan.green at gmail.com Mon Jul 18 19:03:31 2005 From: alan.green at gmail.com (Alan Green) Date: 18 Jul 2005 16:03:31 -0700 Subject: Make a .WAV file come out of the left speaker in Windows In-Reply-To: <1121129643.984392.164270@f14g2000cwb.googlegroups.com> References: <1121129643.984392.164270@f14g2000cwb.googlegroups.com> Message-ID: <1121727811.941251.197530@f14g2000cwb.googlegroups.com> Alan Green wrote: > I am writing a Python script that uses the win32all winsound package to > play a .wav file. I [need] the sound come out of the left hand speaker, but > not the right hand speaker. I eventually got out ctypes and used it to access the Windows multi-media libraries. ctypes is completely amazing, especially with the code generator to turn the windows C header files into Python functions and constants. Just yesterday I discovered PyMedia, and will have to have a play with that, too. a From ptmcg at austin.rr.com Fri Jul 29 02:16:38 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 28 Jul 2005 23:16:38 -0700 Subject: Regex for nested {} References: Message-ID: <1122617798.607606.227280@g44g2000cwa.googlegroups.com> Or use pyparsing, and do both at the same time (that spark example looks like a lot of work!). Download pyparsing at http://pyparsing.sourceforge.net. -- Paul from pyparsing import * text = """ outer { inner1 { ...1 } inner2 { ...2 } } simple { ...3 } null {} single { blah } """ LBRACE = Literal("{").suppress() RBRACE = Literal("}").suppress() listKey = Word(alphanums) listValue = Forward() listEntry = Group( listKey + listValue ) listValue << Group( LBRACE + ZeroOrMore( listEntry | Word(alphanums+".") ) + RBRACE) inputData = OneOrMore( listEntry ) results = inputData.parseString( text ) print results.asList() Prints : [['outer', [['inner1', ['...1']], ['inner2', ['...2']]]], ['simple', ['...3']], ['null', []], ['single', ['blah']]] (manually formatted to show nesting) [ ['outer', [ ['inner1', ['...1']], ['inner2', ['...2']] ] ], ['simple', ['...3']], ['null', []], ['single', ['blah']] ] From thanos at sians.org Sun Jul 24 05:03:47 2005 From: thanos at sians.org (Thanos Tsouanas) Date: Sun, 24 Jul 2005 12:03:47 +0300 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <20050724090347.GA9121@zermelo.sians.org> On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote: > On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote: > > > > print foo %do > > > > where do is a dictobj object... > > Are you telling me that the ONLY thing you use dictobj objects for is to > print them? I'm sorry to disappoint you, but yes. When you have a long text template to fill-out, with lots of %(foo)s, and all those foos are attributes of an object, it really helps to have dictobj. > I don't think so. I do know how to print an object, amazingly. Please, tell me, how would you print it in my case? > Perhaps you would like to explain how you use the rest of the > functionality of the dictobj, instead of taking my words out of context > and giving an inane answer. I dont see _ANY_ other functionality in the dictobj class. Do you? > Why jump through all those hoops to get attributes when Python already > provides indexing and attribute grabbing machinery that work well? Why do > you bother to subclass dict, only to mangle the dict __getitem__ method so > that you can no longer retrieve items from the dict? Because *obviously* I don't know of these indexing and attribute grabbing machineries you are talking about in my case. If you cared to read my first post, all I asked was for the "normal", "built-in" way to do it. Now, is there one, or not? -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ From frank at chagford.com Wed Jul 27 03:36:37 2005 From: frank at chagford.com (Frank Millman) Date: 27 Jul 2005 00:36:37 -0700 Subject: [OT] Problems with permissions etc Message-ID: <1122449797.139618.141460@z14g2000cwz.googlegroups.com> Hi all This is not strictly a Python question, but this newsgroup feels like a family to me, so I hope that someone will be kind enough to respond to this, or at least point me in the right direction. While developing under linux, I use my own computer, as the only user, so it has become my habit to login as root and do all my work as a superuser. I know that this is not desirable, but it has become a habit, which I am now trying to get out of. Now that I am logging in as an ordinary user, I find that a number of things that previously 'just worked' have now stopped working. I can usually find the cause, and tweak whatever is needed to get it working again, but I am wondering how most people work. Is it normal to experience these kinds of problems, or am I missing a trick somewhere and making my life more complicated than it need be? I will give two examples. I would like advice on the best way to fix them, but I would prefer a more general reply that explains how experienced unix/linux users go about handling these kinds of issues. 1. The application I am developing will eventually be deployed as a multi-user accounting/business system. I want to identify the physical workstation that generates each transaction, so I am using the mac address. My method for extracting this is as follows - mac = os.popen("ifconfig|grep Ether|awk {print '$5'}").read()[:-1] # I did not come up with this myself, I cribbed it from somewhere As root, this works fine. As non-root, ifconfig is not found. The reason is that it is in /sbin, and this is not included in the default path for non-root users. I could either include /sbin in my path, or I could change the above line to /sbin/ifconfig ... Alternatively, there may be a better way of getting the mac address or identifying the workstation. 2. I am using wxPython, which was compiled from source. It so happens that I did this with a colleague who also has a user account on my machine, so the compile and install of wxPython was done from his home directory. When I start my app as non-root, the import of wx fails, as it cannot find certain files. They are in the other user's home directory, but as the top-level directory has permissions of drwx------, my user cannot read anything in that directory. I can change the directory permissions, or I can move the files to another area which all users can read. If the latter, is there a 'correct' place to put them? I think that these problems are a result of my lack of experience as a system administrator. On the other hand, the various books and articles I have read to try and improve my knowledge have not covered these kinds of issues. Is it just something that one learns the hard way? Any advice, especially pointers to reading matter that covers this topic, will be much appreciated. Thanks Frank Millman From reinhold-birkenfeld-nospam at wolke7.net Sun Jul 24 15:29:08 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 24 Jul 2005 21:29:08 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <-tWdnRUeMaY5TH7fRVn-sw@powergate.ca> References: <3kehbmFtv6lpU1@individual.net> <2vmdnT2i-uTLzX_fRVn-1A@powergate.ca> <3kf4kmFsu26jU1@individual.net> <3kfpovFu3rt9U1@individual.net> <3khg7cFuh446U1@individual.net> <-tWdnRUeMaY5TH7fRVn-sw@powergate.ca> Message-ID: <3ki8g4Fua4dvU1@individual.net> Peter Hansen wrote: > Reinhold Birkenfeld wrote: >> Peter Hansen wrote: >>> if mypath.splitpath()[0] == 'c:/temp': > > vs. > >>> if mypath.splitpath()[0] == Path('c:/temp'): >> >> But you must admit that that't the cleaner solution. > > "Cleaner"? Not at all. I'd say it's the more expressive solution, > perhaps, but I definitely wouldn't choose the word "cleaner" for > something which, to me, adds fairly unnecessary text. > > But it's clearly a subjective matter, and as the one of us not involved > in doing the real work here, I'll bow to your judgement on the matter. ;-) I'm in no way the last instance on this. For example, everyone with CVS access is free to change the files ;) Honestly, I'm in constant fear that allowing too much and loading too much features won't increase the acceptance of python-dev Reinhold From python-url at phaseit.net Wed Jul 13 15:08:04 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 13 Jul 2005 19:08:04 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 13) Message-ID: QOTW: "The posts do share an erroneous, implied assumption that the investment in learning each language is equal. Python has a strong competitive advantage over Java and C++ in terms of learnability. A person can get up to speed in a few days with Python." - Raymond Hettinger "You know, this is the most concise example of feature-creep in a specification that I've ever seen." - Christopher Subich "With Lisp or Forth, a master programmer has unlimited power and expressiveness. With Python, even a regular guy can reach for the stars." - Raymond Hettinger Lisp's macros are undoubtedly a powerful feature, but are they powerful enough to make List development faster than Python development? Do we want macros in Python? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ca05ba71092748a1 List comprehensions are almost identical to generator expressions wrapped in list() calls. Does that mean that list comps will go away in Python 3? Should they? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b050ef55b36dee56 A Bright, Shiny Service: Sparklines: http://www.xml.com/pub/a/2005/06/22/sparklines.html Which is faster, if, or try/except? Which is more Pythonic? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/8026ec36def2af1e Rbt wants to break out of nested loops. He's shown several ways of doing it, but for my money, Raymond's approach is the most elegant: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b127ff7fffcea00 Charlie Calvert wrote a couple of articles that advocate Python, and he's looking for some backup: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/721d749715aa5aaf ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From cam.ac.uk at mh391.invalid Thu Jul 28 15:28:48 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 28 Jul 2005 20:28:48 +0100 Subject: Ten Essential Development Practices In-Reply-To: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: gyromagnetic at gmail.com wrote: > The following url points to an article written by Damian Conway > entitled "Ten Essential Development Practices": > http://www.perl.com/pub/a/2005/07/14/bestpractices.html > > Althought the article has Perl as a focus, I thought that some of the > general points made might be of interest to the Python community. It > would certainly be interesting to put together an analogous version of > this article that centers on Python. He spends so much space on "Create Consistent Command-Line Interfaces," a section that, in Python, could be replaced with a simple "Use optparse." -- Michael Hoffman From kay.schluehr at gmx.net Wed Jul 20 11:04:14 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 Jul 2005 08:04:14 -0700 Subject: python certification In-Reply-To: <1121863299.203822.33180@z14g2000cwz.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> <1121790230.580130.156410@o13g2000cwo.googlegroups.com> <1121863299.203822.33180@z14g2000cwz.googlegroups.com> Message-ID: <1121871854.713773.193450@o13g2000cwo.googlegroups.com> lordverminard at gmail.com schrieb: > hi > i bassically need it cuz i am appyling to colleges this year and > i know this kind of stuff really helps. > besides since i am learning python i thought i might get some credit > for it as well. > its bassically for a mention in my resume/bio-data/appliccation > i am willing to spend about $50-100 but any more is out of my bugdet. > even $50 is hard on me. > i did find this great site that would let me give a perl exam in $9.99 > but they don't have python. Before you spend some of your few money for an obscure certification without any authority you should feel certain that you need Python at your college. Better you participate in an open source project for fun and gathering some experience if it's not too hard for you to access a computer. Of course I don't know your supervisors and I'm not sure whether they are more impressed about people learning the Python tutorial, than about people using it to write real world applications. Kay From jepler at unpythonic.net Thu Jul 21 10:01:14 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 21 Jul 2005 09:01:14 -0500 Subject: Filling up commands.getstatusoutput's buffer In-Reply-To: <1121897448.949323.8020@g43g2000cwa.googlegroups.com> References: <1121897448.949323.8020@g43g2000cwa.googlegroups.com> Message-ID: <20050721140110.GA11787@unpythonic.net> On Wed, Jul 20, 2005 at 03:10:49PM -0700, travislspencer at gmail.com wrote: > Hey, > > Has anyone ever had commands.getstatusoutput's buffer fill up when > executing a verbose command? [...] How much output are you talking about? I tried outputs as large as about 260 megabytes without any problem. (RedHat 9, Python 2.2) >>> len(commands.getoutput("dd if=/dev/zero bs=512 count=512000 2>/dev/null")) 262144000 >>> 512 * 512000 262144000 Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ntv1534 at gmail.com Wed Jul 20 13:33:55 2005 From: ntv1534 at gmail.com (MooMaster) Date: 20 Jul 2005 10:33:55 -0700 Subject: Newbie - chapter 19 in "How to think like a CS in python" References: Message-ID: <1121880835.379197.111060@g43g2000cwa.googlegroups.com> Well, being a lowly CS student myself this sounded like fun, so I went ahead and took the challenge. The first thing you have to consider is how to add the new element to the list. Obviously you have to iterate through the list, find the first element that the new one is greater than, and insert this one before it while keeping the list structure intact. You must also remember to update the head if necessary, and add at the end if the element to be added is less than what is already in the list...So this is what I came up with: First of all, however, add this to your Improved Queue Class----- def printQueue(self): if(self.isEmpty()): print "Empty" else: pointer = self.head while(pointer != None): print str(pointer.cargo) pointer = pointer.next Then------ class PriorityQueueList(ImprovedQueue): def __init__(self): ImprovedQueue.__init__(self) def insert(self, cargo): newNode = Node(cargo) if self.length == 0: self.head = self.last = newNode else: #iterate through the list, keeping a reference to a node and the node before it tracker = self.head while(tracker !=None): copy2 = tracker.prev if(newNode.cargo > tracker.cargo): #add the new node by updating links, then update head while keeping list intact tracker.prev = newNode newNode.next = tracker self.head = newNode newNode.prev = copy2 if(copy2 !=None): copy2.next = newNode break else: tracker = tracker.next #if a repeat element is added #we want to add to end to preserve the queue structure, thus if the element hasn't #been added at this point it should be added at the end if(newNode.prev ==None and newNode.next ==None): last = self.last last.next = newNode self.last = newNode self.length = self.length + 1 This produces the following output----- >>> l = PriorityQueueList() >>> l.insert(1) >>> l.insert(2) >>> l.insert(1) >>> l.printQueue() 2 1 1 >>> l.insert(10) >>> l.printQueue() 10 2 1 1 Hope this helps! From n00spam-developer at yahoo.com Sun Jul 17 02:33:56 2005 From: n00spam-developer at yahoo.com (john) Date: Sun, 17 Jul 2005 06:33:56 GMT Subject: Python HTTP digest authentication woes... Message-ID: <2005071702335516807%n00spamdeveloper@yahoocom> I'm trying to access the XML version of my Tivo now playing list with python. It uses auth digest HTTP authentication. I could really use some help! I'm able to get this page using curl: curl --dump-header tivoHeaders --insecure --anyauth --user tivo:8000008 "https://192.168.1.102/TiVoConnect?Command=QueryContainer&Container=%2FNowPlaying&Recurse=Yes" But when I use my python script, I get rejected: https://192.168.1.102/TiVoConnect?Container=%2FNowPlaying&Command=QueryContainer&Recurse=Yes Error 401 Server: tivo-httpd-1:7.1b-01-2:140 Set-Cookie: sid=DEC2D78EABF48A6D; path=/; expires="Saturday, 16-Feb-2013 00:00:00 GMT"; WWW-Authenticate: Digest realm="TiVo DVR", nonce="FD08EF226909CA85", qop="auth" Content-Length: 31 Content-Type: text/html Connection: close Digest realm="TiVo DVR", nonce="FD08EF226909CA85", qop="auth" I've scrounged for examples out there and the couple that I've found just don't seem to work for me.. Here's one way I've tried: ===================================== import urllib2 theurl = "192.168.1.102/TiVoConnect?Container=%2FNowPlaying&Command=QueryContainer&Recurse=Yes" print theurl protocol = 'https://' username = 'tivo' password = '8000008' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPDigestAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) try: pagehandle = urllib2.urlopen(protocol + theurl) except IOError, e: if hasattr(e, 'code'): if e.code != 401: print 'We got another error' print e.code else: print "Error 401" print e.headers print e.headers['www-authenticate'] ======================================= I get 401 every time! This was taken from an example online almost verbatim, the only major thing I changed was HTTPBasicAuthHandler --> HTTPDigestAuthHandler. Any ideas or help would be greatly appreciated! Thanks, -John From nestleNOSPAM12 at comcast.net Thu Jul 28 22:57:44 2005 From: nestleNOSPAM12 at comcast.net (Bryan) Date: Thu, 28 Jul 2005 20:57:44 -0600 Subject: os._exit vs. sys.exit Message-ID: <7a2dnSer5eC2BnTfRVn-sQ@comcast.com> Quick question: Why does os._exit called from a Python Timer kill the whole process while sys.exit does not? On Suse. Bryan From sjsobol at JustThe.net Mon Jul 18 18:19:38 2005 From: sjsobol at JustThe.net (Steve Sobol) Date: Mon, 18 Jul 2005 15:19:38 -0700 Subject: Xah's edu corner: on Microsoft hatred In-Reply-To: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > Dear Joe, > > It is well known that you are an avid hater of Microsoft, from their > technologies to their leader to their business practices. I have now > and then seen your impassioned expression of this hatred, scattered > among your newsgroup posts. This has ZERO to do with any of the groups you posted to. Go post to some advocacy groups where you *might* be on-topic. -- JustThe.net - Steve Sobol / sjsobol at JustThe.net / PGP: 0xE3AE35ED Coming to you from Southern California's High Desert, where the temperatures are as high as the gas prices! / 888.480.4NET (4638) "Life's like an hourglass glued to the table" --Anna Nalick, "Breathe" From tim.peters at gmail.com Sun Jul 3 17:04:20 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 3 Jul 2005 17:04:20 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae05070314045677ae3c@mail.gmail.com> ... [Tom Anderson] > So, is there a way of generating and testing for infinities and NaNs > that's portable across platforms and versions of python? Not that I know of, and certainly no simple way. > If not, could we perhaps have some constants in the math module for them? See PEP 754 for this. ... >> Read the manual for the precedence rules. -x**y groups as -(x**y). -1.0 >> is the correct answer. If you intended (-x)**y, then you need to insert >> parentheses to force that order. > So i see. Any idea why that precedence order was chosen? It goes against > conventional mathematical notation, as well as established practice in > other languages. Eh? For example, Fortran and Macsyma also give exponentiation higher precedence than unary minus. From my POV, Python's choice here was thoroughly conventional. > Also, would it be a good idea for (-1.0) ** 0.5 to evaluate to 1.0j? It > seems a shame to have complex numbers in the language and then miss this > opportunity to use them! It's generally true in Python that complex numbers are output only if complex numbers are input or you explicitly use a function from the cmath module. For example, >>> import math, cmath >>> math.sqrt(-1) Traceback (most recent call last): File "", line 1, in ? ValueError: math domain error >>> cmath.sqrt(-1) 1j The presumption is that a complex result is more likely the result of program error than intent for most applications. The relative handful of programmers who expect complex results can get them easily, though. From lordverminard at gmail.com Wed Jul 20 08:41:39 2005 From: lordverminard at gmail.com (lordverminard at gmail.com) Date: 20 Jul 2005 05:41:39 -0700 Subject: python certification In-Reply-To: <1121790230.580130.156410@o13g2000cwo.googlegroups.com> References: <1121532715.022934.100360@g43g2000cwa.googlegroups.com> <1121790230.580130.156410@o13g2000cwo.googlegroups.com> Message-ID: <1121863299.203822.33180@z14g2000cwz.googlegroups.com> hi i bassically need it cuz i am appyling to colleges this year and i know this kind of stuff really helps. besides since i am learning python i thought i might get some credit for it as well. its bassically for a mention in my resume/bio-data/appliccation i am willing to spend about $50-100 but any more is out of my bugdet. even $50 is hard on me. i did find this great site that would let me give a perl exam in $9.99 but they don't have python. From gsakkis at rutgers.edu Fri Jul 1 01:50:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 22:50:59 -0700 Subject: Speaking of list-comprehension? References: Message-ID: <1120197059.167817.217370@g47g2000cwa.googlegroups.com> "Terry Hancock" wrote: > Chinook wrote: > > >>> ta = [5, 15, 12, 10, 9] > > >>> for i in range(len(ta)): > > ... if ta[i] >= 10: > > ... ta[i] -= 10 > > ... else: > > ... ta[i] += 10 > > It's not exactly the same in that it doesn't change values in > place, but this is similar if you are only interested in the > values: > > ta = [t>=10 and t-10 or t+10 for t in ta] Not quite; it differs for t==10. George From rrr at ronadam.com Tue Jul 19 16:49:44 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 19 Jul 2005 20:49:44 GMT Subject: Ordering Products In-Reply-To: <1121752847.005587.145960@g44g2000cwa.googlegroups.com> References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> <1121752847.005587.145960@g44g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Hi Ron, > > I really don't want to discourage you in doing your own CAS but the > stuff I'm working on is already a bit more advanced than my > mono-operational multiplicative algebra ;) I figured it was, but you offered a puzzle: "Here might be an interesting puzzle for people who like sorting algorithms ..." And asked for suggestions: "It would be interesting to examine some sorting algorithms on factor lists with constrained item transpositions. Any suggestions?" So I took you up on it. ;-) BTW.. Usually when people say "I don't want to discourage...", They really want or mean the exact oppisite. This is a organizational problem in my opinion, so the challenge is to organize the expressions in a way that can be easily manipulated further. Groupings by operation is one way. As far as inheritance goes, it's just another way to organize things. And different algebra's and sub-algebra's are just possible properties of a group. The groups can easily be customized to have their own behaviors or be created to represent custom unique operations. The sort method I'm suggesting here, with examples, is constrained by the associated properties of the group that is being sorted. Basically, weather or not it's and associative operation or not. So when a group is asked to sort, it first asks all it's sub groups to sort, then it sorts it self if it is an associative group. Ie.. from inner most group to outer most group but only the associative ones. Playing with it further I get the following outputs. ( The parenthesis surround a group that is associated to the operation. This is the same idea/suggestion I first proposed, it's just been developed a little further along.) b+a+2 = (2+a+b) <- addition group a*(b+45+23) = ((68+b)*a) <- addition group within multiply group a-4-3-7+b = ((a-14)+b) <- sub group within add group c*b-d*a+2 = (2+((b*c)-(a*d))) <- mults within subs within adds 7*a*8*9+b = ((504*a)+b) a*(b+c) = ((b+c)*a) c*3*a*d*c*b*7*c*d*a = (21*a*a*b*c*c*c*d*d) d*b/c*a = (((b*d)/c)*a) (d*b)/(c*a) = ((b*d)/(a*c)) d*b-a/e+d+c = (((b*d)-(a/e))+c+d) a/24/2/b = (a/48/b) c**b**(4-5) = (c**(b**-1)) (d**a)**(2*b) = ((d**a)**(2*b)) The next step is to be able to convert groups to other groups; an exponent group to a multiply group; a subtract group to an addition group with negative prefix's.. and so on. That would be how expansion and simplifying is done as well as testing equivalence of equations. if m*c**2 == m*c*c: print "Eureka!" > Mixing operators is not really a problem, but one has to make initial > decisions ( e.g about associativity i.e. flattening the parse-tree ) > and sub-algebra generation by means of inheritance: What do you mean by 'sub-algebra generation'? >>>>a,b = seq(2,Expr) >>>>type(a+b) > > > >>>>class X(Expr):pass >>>>x,y = seq(2,X) >>>>type(x+y) > > > > This is not particular hard. It is harder to determine correspondence > rules between operations on different levels. On subalgebras the > operations of the parent algebra are induced. But what happens if one > mixes objects of different algebras that interoperate with each other? > It would be wise to find a unified approach to make distinctive > operations visually distinctive too. Infix operators may be > re-introduced just for convenience ( e.g. if we can assume that all > algebras supporting __mul__ that are relevant in some computation have > certain properties e.g. being associative ). Different algebras would need to be able to convert themselves to some common representation. Then they would be able to be mixed with each other with no problem. Or an operation on an algebra group could just accept it as a unique term, and during an expansion process it could convert it self (and it's members) to the parents type. That would take a little more work, but I don't see any reason why it would be especially difficult. Using that methodology, an equation with mixed algebra types could be expanded as much as possible, then reduced back down again using a chosen algebra or the one that results in the most concise representation. > ########################################################################## > > After thinking about M ( or Expr ;) a little more I come up with a > solution of the problem of central elements of an algebra ( at least > the identity element e is always central ) that commute with all other > elements. What is a "central" element? I can see it involves a set, but the context isn't clear. > Here is my approach: > > # Define a subclass of list, that provides the same interface as list > and > # a customized sorting algorithm It's not really that different from what I suggested. And since my example is based on your first example. It has a lot in common but the arrangement (organization) is a bit different. > Regards, > Kay Here's the current version... It now handles more complex equations including exponents and perenthisized groupings. It is fairly easy to extend which is one of the advantages of having each operation associated to a group. It would be interesting to see what other opperators could be added to it. Cheers, Ronald Adam #Factor - a single element or variable to be opperated on. class F(list): Type = 'Factor' Commutative = False Symbol = '' Numerals = (int,float,long) def __init__(self,*x): list.__init__(self,x) def __add__(self, other): if isinstance(self,A): self.append(other) return self return A(self,other) def __radd__(self, other): if isinstance(self,A): self.append(other) return self return A(other,self) def __sub__(self, other): if isinstance(self,S): self.append(other) return self return S(self,other) def __rsub__(self, other): if isinstance(self,S): self.append(other) return self return S(other,self) def __mul__(self, other): if isinstance(self,M): self.append(other) return self return M(self,other) def __rmul__(self, other): if isinstance(self,M): self.append(other) return self return M(other,self) def __div__(self, other): if isinstance(self,D): self.append(other) return self return D(self,other) def __rdiv__(self, other): if isinstance(self,D): self.append(other) return self return D(other,self) def __pow__(self, other): return P(self,other) def __rpow__(self, other): return P(other,self) def __repr__(self): self._order_() if self.Type == 'Operator': self._simplify_() Pleft,Pright = '(',')' else: Pleft,Pright = '','' return Pleft+self.Symbol.join([str(x) for x in self])+Pright def _order_(self): for i in self: if hasattr(i, 'Commutative'): if i.Commutative: i._order_() if self.Commutative: self.sort() ## Operator classes durived from the Factor class. # # These group factors and other operator groups # together in a group with a common opperator. # Add class A(F): Type = 'Operator' Commutative = True Symbol = '+' def _simplify_(self): #Was sorted first so all numerals shuold #be to the left. while ( len(self)>1 and isinstance(self[0],self.Numerals) and isinstance(self[1],self.Numerals) ): self[0:2]=[self[0]+self[1]] # Subtract class S(F): Type = 'Operator' Commutative = False Symbol = '-' def _simplify_(self): while ( isinstance(self[0],self.Numerals) and isinstance(self[1],self.Numerals) ): self[0:2] = [self[0]-self[1]] i = 1 while i1 and isinstance(self[0],self.Numerals) and isinstance(self[1],self.Numerals) ): self[0:2]=[self[0]*self[1]] # Divide class D(F): Type = 'Operator' Commutative = False Symbol = '/' def _simplify_(self): while ( isinstance(self[0],self.Numerals) and isinstance(self[1],self.Numerals) ): self[0:2] = [self[0]/self[1]] i = 1 while i newFile = open(newPath, 'wb') > newFile.write(zf.read(file)) > newFile.flush() > newFile.close() > else : > os.makedirs(newPath) > > zf.close() > else: > print pathZip + " is not a zip file" > > it works well but i have a small problem : i can't see how i can deal > with file rights. > When I unzip files with this script all the unzipped files haven't the > good rights. > for example : > with this script : > -rw-r--r-- foo.exe > with a traditional zip program (ie : stuffit ): > -rwxr-xr-x foo.exe > ZipInfo objects doesn't store informations about rights ? > (http://www.python.org/doc/current/lib/zipinfo-objects.html#zipinfo-objects) > > How can i fix this ? From gsakkis at rutgers.edu Fri Jul 8 17:40:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Jul 2005 14:40:59 -0700 Subject: python nested class References: Message-ID: <1120858859.431346.284530@g47g2000cwa.googlegroups.com> "Daniel Dittmar" wrote: > Vedanta Barooah wrote: > > in a python nested class is it possible to change the value of the > > parent class's variable without actually creating an instance of the > > parent class > > Python nested classs are like *static* Java nested classes. Non-static > Java classes are very different in that they have an implicit reference > to an instance of the enclosing class. This is why you can instantiate > non-static inner classes only in the context (= non-static method) of a > specific object. There is no direct equivalent to this in Python, so you > have to do the steps yourself. > > - the constructor takes an additional argument, the 'outer' object, > which has to be kept in the object: > def __init__ (self, outer, ...): > self.outer = outer > > - when creating the inner object, the outer object must be passed to the > constructor > obj = InnerClass (self) > > - the outer object must be explicitely referenced: > self.outer.increase (20) > > Daniel Or you can automate these steps and make implicit the reference to the outer object using a descriptor: #====== Test ============================================= def test(): class Outer: def __init__(self,x): self.x = x # if python gets class decorators someday, # an inner class could be specified simply by: #@innerclass class Inner: def __init__(self, y): self.y = y def sum(self): return self.x + self.y # as of python 2.4 Inner = innerclass(Inner) outer = Outer(1) inner = outer.Inner(2) assert inner.sum() == 3 # outer.x, inner.x, inner.__outer__.x refer to the same object outer.x = 4; assert inner.sum() == 6 inner.x = 10; assert inner.sum() == 12 inner.__outer__.x = -1; assert inner.sum() == 1 # an inner class must be bounded to an outer class instance try: Outer.Inner(0) except AttributeError, e: pass #print e else: assert False #======================================================= def innerclass(cls): '''Class decorator for making a class behave as a Java (non-static) inner class. Each instance of the decorated class is associated with an instance of its enclosing class. The outer instance is referenced implicitly when an attribute lookup fails in the inner object's namespace. It can also be referenced explicitly through the property '__outer__' of the inner instance. ''' if hasattr(cls, '__outer__'): raise TypeError('Existing attribute "__outer__" ' 'in inner class') class InnerDescriptor(object): def __get__(self, outer, outercls): if outer is None: raise AttributeError('An enclosing instance that ' 'contains %s.%s is required' % (cls.__name__, cls.__name__)) clsdict = cls.__dict__.copy() # explicit read-only reference to the outer instance clsdict['__outer__'] = property(lambda s: outer) # implicit lookup in the outer instance clsdict['__getattr__'] = lambda s,attr: getattr(outer,attr) def __setattr__(this, attr, value): # setting an attribute in the inner instance sets the # respective outer instance if and only if the # attribute is already defined in the outer instance if hasattr(outer, attr): setattr(outer,attr,value) else: super(this.__class__,this).__setattr__(attr, value) clsdict['__setattr__'] = __setattr__ return type(cls.__name__, cls.__bases__, clsdict) return InnerDescriptor() Regards, George From dnodal at charter.net Tue Jul 12 10:52:47 2005 From: dnodal at charter.net (Danny Nodal) Date: Tue, 12 Jul 2005 09:52:47 -0500 Subject: append one file to another References: <1121176070.045217.264890@g44g2000cwa.googlegroups.com> Message-ID: <6PQAe.2834$wG5.1958@fe03.lga> Its been a while since I last coded in Python, so please make sure you test it before trying it so you don't clobber your existing file. Although it may not be more effecient than what you are doing now or has been suggested already, it sure cuts down on the typing. open(outfilename,'a').write(open(infilename).read()) Regards. wrote in message news:1121176070.045217.264890 at g44g2000cwa.googlegroups.com... > Hi, > > I want to append one (huge) file to another (huge) file. The current > way I'm doing it is to do something like: > > infile = open (infilename, 'r') > filestr = infile.read() > outfile = open(outfilename, 'a') > outfile.write(filestr) > > I wonder if there is a more efficient way doing this? > Thanks. > From rkern at ucsd.edu Wed Jul 27 17:47:35 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Jul 2005 14:47:35 -0700 Subject: SciPy and NetCDF In-Reply-To: <1122499062.943121.65200@z14g2000cwz.googlegroups.com> References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> <1122499062.943121.65200@z14g2000cwz.googlegroups.com> Message-ID: Scott Kilpatrick wrote: > So wherever pycdf does a: > > from Numeric import * > > what is the equivalent for SciPy? i.e. where is the full Numeric module > in SciPy? Scipy also does a from Numeric import * Numeric isn't contained within Scipy; Scipy uses Numeric like pycdf does. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ntv1534 at gmail.com Thu Jul 14 18:05:22 2005 From: ntv1534 at gmail.com (MooMaster) Date: 14 Jul 2005 15:05:22 -0700 Subject: linking GUI apps using different Toolkits...possible? Message-ID: <1121378722.170809.28050@g43g2000cwa.googlegroups.com> This is more of a wxPython centric question, but not seeing reference to this on the wx group I thought I'd try here since many here also use wxPython toolkit. I started learning GUI development with Tkinter, and developed a few screens as part of an application I'm building with it. I've recently been trying to learn wxPython because of it's additional widgets (the wxTreeCtrl and Drag and Drop features in particular), and I've developed an application where there is a splitter window with a tree on the left side. My goal is to have a user double click on an option and call up the appropiate display on the right side. I've already developed the appropriate screens in Tkinter, and I'd like to use those instead of having to re-write them in wx. I'd basically like to pack the screen into the rightmost pane, but I have not been able to find an effective means for doing so. What I have so far is this: ------------------------------------------------------------------- class MyApp(wxApp): """driver class, creates a frame to store everything, puts 2 splitter windows inside, the first holding the tree display""" def OnInit(self): #create the frame frame = MyFrame(NULL, -1, "Display") frame.Show(true) self.SetTopWindow(frame) #create the splitter windows splitter = MySplitter(frame, -1) sty = wxBORDER_SUNKEN self.p1 = wxWindow(splitter, style=sty) self.p2 = wxWindow(splitter, style=sty) self.p2.SetBackgroundColour("sky blue") splitter.SetMinimumPaneSize(100) splitter.SplitVertically(self.p1, self.p2, 320) #Create the tree and add the outermost parents self.p1.myTree = MyTreeCtrl(self.p1, -1, wxDefaultPosition, (400,400), wxTR_HAS_BUTTONS) self.p1.root = self.p1.myTree.AddRoot("Subsystem") self.p1.myTree.SetPyData(self.p1.root, None) self.p1.child1 = self.p1.myTree.AppendItem(self.p1.root, "4 Corners") self.p1.child2 = self.p1.myTree.AppendItem(self.p1.root, "East of River") #Bind Drag and Drop methods to the tree to support drag and drop self.p1.myTree.Bind(EVT_TREE_BEGIN_DRAG, self.OnBeginDrag) self.p1.myTree.Bind(EVT_TREE_END_DRAG, self.OnEndDrag) self.p1.myTree.Bind(EVT_LEFT_DCLICK, self.OnLeftDClick) #Fill with children headerLabels = ["TC43G", "Arming", "Outage", "Lines", "Graphs"] for label in headerLabels: grandchild = self.p1.myTree.AppendItem(self.p1.child1, label) self.p1.myTree.SetPyData(grandchild, None) grandchild = self.p1.myTree.AppendItem(self.p1.child2, label) self.p1.myTree.SetPyData(grandchild, None) #Expand base root to get to meat of data self.p1.myTree.Expand(self.p1.root) return true #When a node is double clicked, it should display the corresponding display on the right hand side #currently, display pops up in separate window... def OnLeftDClick(self, event): pt = event.GetPosition(); item, flags = self.p1.myTree.HitTest(pt) clicked = self.p1.myTree.GetItemText(item) if(clicked == "Arming"): self.p2 = ACDisplay() elif(clicked == "Graphs"): self.p2 = Display() elif(clicked == "Lines"): self.p2 = OutTable() elif(clicked == "Outage"): self.p2 = tablesum() ------------------------------------------------------------------- Where ACDisplay, Display, OutTable, and tablesum are the classes I've written already. It runs without errors, but what currently happens is that the main window with the tree comes up, and when I double-click an option the screen appears in a separate window. Is there a way to pack it into the second pane (self.p2)? From rrr at ronadam.com Wed Jul 6 10:33:47 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 06 Jul 2005 14:33:47 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: >> del -> delete > > > How about just getting rid of del? Removal from collections could be > done with a method call, and i'm not convinced that deleting variables > is something we really need to be able to do (most other languages > manage without it). Since this is a Python 3k item... What would be the consequence of making None the default value of an undefined name? And then assigning a name to None as a way to delete it? Some benefits ============= *No more NamesError exceptions! print value >> None value = 25 print value >> 25 value = None #same as 'del value' *No initialization needed for a while loop! While not something: if : something = True *Test if name exists without using a try-except! if something == None: something = value *And of course one less keyword! Any drawbacks? Cheers, Ron PS... not much sleep last night, so this may not be well thought out. From vans at oif.com Sun Jul 3 10:00:10 2005 From: vans at oif.com (VansMll) Date: Sun, 3 Jul 2005 15:00:10 +0100 Subject: How to dump an interpreter image? Message-ID: <1120399050.c415fe77ae7ee03d168dc545a8537022@teranews> Hi, is it possible to save a state of the python interpreter to disk and load it later? Thanks From gsakkis at rutgers.edu Sat Jul 9 11:55:07 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Jul 2005 08:55:07 -0700 Subject: Python Module Exposure References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> Message-ID: <1120924507.452720.236990@g47g2000cwa.googlegroups.com> "Jacob Page" wrote: > George Sakkis wrote: > > 1. As already noted, ISet is not really descriptive of what the class > > does. How about RangeSet ? It's not that long and I find it pretty > > descriptive. In this case, it would be a good idea to change Interval > > to Range to make the association easier. > > The reason I decided not to use the term Range was because that could be > confused with the range function, which produces a discrete set of > integers. Interval isn't a term used in the standard/built-in library, > AFAIK, so I may stick with it. Is this sound reasoning? Yes, it is not unreasonable; I can't argue strongly against Interval. Still I'm a bit more in favor of Range and I don't think it is particularly confusing with range() because: 1. Range has to be either qualified with the name of the package (e.g. rangesets.Range) or imported as "from rangesets import Range", so one cannot mistake it for the range builtin. 2. Most popular naming conventions use lower first letter for functions and capital for classes. 3. If you insist that only RangeSet should be exposed from the module's interface and Range (Interval) should be hidden, the potential conflict between range() and RangeSet is even less. > > 2. The module's "helper functions" -- which are usually called factory > > functions/methods because they are essentially alternative constructors > > of ISets -- would perhaps better be defined as classmethods of ISet; > > that's a common way to define instance factories in python. Except for > > 'eq' and 'ne', the rest define an ISet of a single Interval, so they > > would rather be classmethods of Interval. Also the function names could > > take some improvement; at the very least they should not be 2-letter > > abbreviations. Finally I would omit 'eq', an "interval" of a single > > value; single values can be given in ISet's constructor anyway. Here's > > a different layout: > > First, as far as having the factory functions create Interval instances > (Range instances in your examples), I was hoping to avoid Intervals > being publically "exposed." I think it's cleaner if the end-programmer > only has to deal with one object interface. First off, the python convention for names you intend to be 'private' is to prefix them with a single underscore, i.e. _Interval, so it was not obvious at all by reading the documentation that this was your intention. Assuming that Interval is to be exposed, I found Interval.lowerThan(5) a bit more intuitive than IntervalSet.lowerThan(5). The only slight problem is the 'ne'/ allExcept factory which doesn't return a continuous interval and therefore cannot be a classmethod in Interval. On whether Interval should be exposed or not: I believe that interval is a useful abstraction by itself and has the important property of being continuous, which IntervalSet doesn't. Having a simple single-class interface is a valid argument, but it may turn out to be restricted later. For example, I was thinking that a useful method of IntervalSet would be an iterator over its Intervals: for interval in myIntervalSet: print interval.min, interval.max There are several possible use cases where dealing directly with intervals would be appropriate or necessary, so it's good to have them supported directly by the module. > I like the idea of lengthening the factory function names, but I'm not > sure that the factory methods would be better as class methods. > Consider a use-case: > > >>> import iset > >>> interval = iset.ISet.lowerThan(4) > > as opposed to: > > >>> import iset > >>> interval = iset.lowerThan(4) I was thinking along the lines of: >>> from rangesets import RangeSet, Range >>> mySet = RangeSet(Range.lowerThan(4), Range.greaterThan(5)) That's similar to "from sets import Set" before set became builtin. > This is less typing and probably eliminates some run-time overhead. Can > you list any advantages of making the factory functions class methods? One of the main reason for introducing classmethods was to allow alternate constructors that play well with subclasses. So if Interval is subclassed, say for a FrozenInterval class, FrozenInterval.lowerThan() returns FrozenInterval instances automatically. > > class Range(object): # Interval > > > > @classmethod > > def lowerThan(cls, value, closed=False): > > # lt, for closed==False > > # le, for closed==True > > return cls(None, False, value, closed) > > > > @classmethod > > def greaterThan(cls, value, closed=False): > > # gt, for closed==False > > # ge, for closed==True > > return cls(value, closed, None, False) > > > > @classmethod > > def between(cls, min, max, closed=False): > > # exInterval, for closed==False > > # incInterval, for closed==True > > return cls(min, closed, max, closed) > > I like the function names, but in my dialect, lessThan would be more proper. Either (lowerThan,greaterThan) or (lessThan,moreThan) are fine with me; I'm very slightly in favor of the second for brevity. > > class RangeSet(object): # ISet > > > > @classmethod > > def allExcept(cls, value): # ne > > return cls(Range.lowerThan(value), Range.greaterThan(value)) > > > > 3. Having more than one names for the same thing is good to be avoided > > in general. So keep either "none" or "empty" (preferably "empty" to > > avoid confusion with None) and remove ISet.__add__ since it is synonym > > to ISet.__or__. > > I agree that "none" should be removed. However, some programmers may > prefer to use +, some |, so I'd like to provide both. Interval.__add__ is ok, but IntervalSet should be as close to regular sets as possible; anyway, that's a minor point. > > 4. Intervals shouldn't be comparable; the way __cmp__ works is > > arbitrary and not obvious. > > I agree that __cmp__ is being used arbitrarily. I wanted sorting to be > easy, but there's other ways of doing that. I'll take your suggestion. > > > 5. Interval.adjacentTo() could take an optional argument to control > > whether an endpoint is allowed to be in both ranges or not (e.g. > > whether (1,3], [3, 7] are adjacent or not). > > Interval objects weren't meant to be public; adjacentTo is used by ISet > for combinatory functions. I could look into ways to hide the class > from the public, but hiding things never seemed Pythonic to me; someone > may want to use them for some reason. Maybe pydoc can be made to not > document certain objects. I mentioned already the arguments for keeping it public. If you insist though, several tools recognize the single underscore convention as meaning 'private'; epydoc does, I don't know about pydoc. Also, "from module import *" imports only the top level names that don't start with an undescore. > > 6. Possible ideas in your TODO list: > > - Implement the whole interface of sets for ISet's so that a client > > can use either or them transparently. > > That was my intention. I'll have to see which interface functions I'm > missing. > > > - Add an ISet.remove() for removing elements, Intervals, ISets as > > complementary to ISet.append(). > > - More generally, think about mutable vs immutable Intervals and > > ISets. The sets module in the standard library will give you a good > > idea of the relevant design and implementation issues. > > Both good ideas. > > > After I look into the module's internals, I'll try to make some changes > > and send it back to you for feedback. > > Thanks for your feedback, George. I look forward to any additional > comments you come up with. Regards, George From faxm2 at tav.com Thu Jul 7 08:18:55 2005 From: faxm2 at tav.com (faxme) Date: Thu, 7 Jul 2005 13:18:55 +0100 Subject: how to change a script while it is running Message-ID: <1120738578.46b2dbd2b0d50ae7698c95aaea76bc74@teranews> Hi, I would like to know if it is possible to change code on the fly on a python interpreter. I want to have a python script running a multithread server and be able to connect to this python script and change the interpreter environment. Is this possible? Ideally i would like to call python, load the script inside the python command line and while the script works still be able to type other python commands(that might change the running script). Thanks From rkern at ucsd.edu Wed Jul 20 19:52:43 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 16:52:43 -0700 Subject: Newbie question about lists In-Reply-To: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> References: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> Message-ID: Austin Cox wrote: > Hello, I just started with python and have run into a problem using > lists. > > If I enter: > li = [.25,.10,.05,.01] > and then enter: > print li > it'll output: > [0.25, 0.10000000000000001, 0.050000000000000003, 0.01] > > Can anyone tell me why it does this, and how I can get just the value > .10, and .05 into a list? Thanks. http://docs.python.org/tut/node16.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From zen19725 at zen.co.uk Sat Jul 30 03:14:16 2005 From: zen19725 at zen.co.uk (phil hunt) Date: Sat, 30 Jul 2005 08:14:16 +0100 Subject: functions without parentheses References: <42e9c49b.24281464@news.oz.net> Message-ID: On Fri, 29 Jul 2005 06:37:52 GMT, Bengt Richter wrote: > >I suggested in a previous thread that one could support such a syntax by >supporting an invisible binary operator between two expressions, That's a truely appalling idea. >so that >examine "string" translates to examine.__invisbinop__("string") if >examine as an expression evaluates to an object that has a __invisbinop__ method. > >Then you wouldn't define examine as a function, you would define it as an instance >of a class like > class Examine(object): > define __invisbinop__(self, other): > #...whatever > examine = Examine() >and then > examine "string" Pass the sick bucket. -- Email: zen19725 at zen dot co dot uk From mwm at mired.org Wed Jul 20 19:29:14 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 20 Jul 2005 19:29:14 -0400 Subject: goto References: <1121719077.19216.10.camel@athop1.ath.vt.edu> <86psterxi3.fsf@bhuda.mired.org> Message-ID: <86y881qcol.fsf@bhuda.mired.org> Peter Hansen writes: > Sybren Stuvel wrote: >> Mike Meyer enlightened us with: >> >>>>I dislike gotos because it is too easy to inadvertently create >>>>infinite loops. <10 WINK; 20 GOTO 10> >>> >>>And it's impossible without them? >> I thought the same thing, but then I read it again and thought about >> the "inadvertently". As soon as you see a "while True", you _know_ >> it's going to loop forever. > > Unless it doesn't, of course: > > while True: > break My "favorite" infinte loop with while is: i = 0 while i < 20: do_process(i) Note the prominent *lack* of any change to i here? Oh, for: from i = 0 invariant 0 <= i <= 20 variant 21 - i until i > 19 loop do_process(i) which throws an exception at the beginning of the second loop. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rrr at ronadam.com Fri Jul 8 01:20:15 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 08 Jul 2005 05:20:15 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120565012.080020.309070@o13g2000cwo.googlegroups.com> <1120610787.940292.15210@g43g2000cwa.googlegroups.com> <3j40aoFocvh4U1@individual.net> <6oadncSMIs0fclDfRVn-jg@speakeasy.net> Message-ID: Erik Max Francis wrote: > Ron Adam wrote: > >> Well in my previous explanation I *mean* it to be empty parenthesis. >> >> Does that help? > > > Maybe it might be beneficial to learn a little more of the language > before proposing such wide-reaching (and un-Pythonic) reforms? Hi Erik, Getting more sleep is the answer to not making those kinds of oversights in this case. It's really was not a (my) proposal, but a suggestion someone else made. It seemed like an interesting idea and I wanted to see what kind of problems and benefits it would have. Discussing an idea with other before it's fully thought out is a good way to explore its possibilities even though it may mean appearing silly at times, which I don't mind. :) In the previous posts I was attempting to show a possible pattern or logic which doesn't currently correspond to the languages syntax using parenthesis. >>> (None) >>> That's as close to an empty parenthesis as Python gets. I was really trying to explain an underlying concept, not show actual python code. And the conclusion (opinion) I've come to, is such a change might be made to work, but it would be very confusing to most people who have gotten use to the current None usage. And difficult to emplement in a way that's consistant overall. An alternative is to use a different word such as 'undefined'. Then None can be used as it is currently, and undefined, can be used to test for in a comparison for undefined names. Assigning a name to undefined could be used as an alternative to delete a name but so far I don't see an advantage to doing that way over using del. if name is undefined: do something. Instead of: try: name except: do something And maybe: name = undefined can be used in expressions where del name can't? But so far this doesn't seem useful enough to propose and it would probably cause more problems (or confusion) than it solves. Cheers, Ron From rkern at ucsd.edu Wed Jul 20 21:42:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Jul 2005 18:42:39 -0700 Subject: Newbie question about lists In-Reply-To: <7x4qap551r.fsf@ruckus.brouhaha.com> References: <1121903179.448954.18160@g14g2000cwa.googlegroups.com> <1121908372.875767.321980@f14g2000cwb.googlegroups.com> <7x4qap551r.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Leo Jay" writes: > >>[Decimal("0.25"), Decimal("0.10"), Decimal("0.05"), Decimal("0.01")] > > I wonder if we should have some special syntax for decimals: maybe > > [$.25, $.10, $.05, $.01] > > That would even fit in with decimals being used for financial quantities. Various versions of the (several) Decimal PEPs had a decimal literal syntax, usually along the lines of 0.25d. Google through the python-dev archives. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Sun Jul 31 12:03:41 2005 From: http (Paul Rubin) Date: 31 Jul 2005 09:03:41 -0700 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <87vf2ryrk1.fsf@wilson.rwth-aachen.de> Message-ID: <7xvf2rync2.fsf@ruckus.brouhaha.com> Ed Leafe writes: > But since UIs are incredibly complex beasts, we've > chosen to tackle one at a time, and after looking at them all and considering > different issues, we chose wxPython as the best toolkit for creating > platform-independent apps. How on earth did you decide that, since tkinter actually runs out of the box when you install Python on most platforms, and wxPython doesn't? I can't even think about trying out Dabo unless I'm willing to go through some enormous pain of getting wxPython to work. From nephish at xit.net Wed Jul 27 07:37:50 2005 From: nephish at xit.net (nephish) Date: Wed, 27 Jul 2005 06:37:50 -0500 Subject: question about deleting records from mysql In-Reply-To: <8c7f10c605072704311c6deea5@mail.gmail.com> References: <1122463773.484024.169110@g14g2000cwa.googlegroups.com> <8c7f10c605072704311c6deea5@mail.gmail.com> Message-ID: <42E7720E.90307@xit.net> Simon Brunning wrote: >On 27 Jul 2005 04:29:33 -0700, nephish at xit.net wrote: > > >>Hey there, >>sorry , second question in as many days. >>i am trying to do some stuff with MySQLdb and the thing is, i can >>select records and such, but when i try to delete them, they dont >>really go away. >> >> > >A fiver says you need to commit your changes. > > > ok, do i do that with cursor.commit() ? thanks From simon at arrowtheory.com Tue Jul 12 21:00:14 2005 From: simon at arrowtheory.com (Simon Burton) Date: Wed, 13 Jul 2005 11:00:14 +1000 Subject: if not DEBUG: log = null_log Message-ID: <20050713110014.52d715c1.simon@arrowtheory.com> Hi, I'm after a no-op command, so that i can redirect logging commands in performance critical code. Something like this: def log(*args): print args def null_log(*args): pass if not DEBUG: log = null_log is unacceptable because of the overhead of calling functions in python. log ("about to slip into python feature request mode.") Maybe this is what the PEP 336 guy was thinking of (Make None Callable). Obviously we don't want None to be callable, but what about a "Null" [1] that's callable, with any args ? But I guess what I am really asking for is something on the bytecode level that tells the VM to "do nothing". Here's an idea: make "pass" into an expression (a value) that is callable, with any args, and returns None. log ("finished with python feature request mode.") I recently discovered "pyc" [2], but i don't quite see how i can use it while maintaining python source compatability. bye! Simon. [1]: http://occs.cs.oberlin.edu/~jwalker/nullObjPattern/ [2]: http://students.ceid.upatras.gr/~sxanth/pyc/ -- Simon Burton, B.Sc. Licensed PO Box 8066 ANU Canberra 2601 Australia Ph. 61 02 6249 6940 http://arrowtheory.com From peter at engcorp.com Mon Jul 25 11:22:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 11:22:10 -0400 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kjj0sFukvmcU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> Message-ID: <74SdndipGes3nnjfRVn-1w@powergate.ca> Reinhold Birkenfeld wrote: > Current change: > > * Add base() method for converting to str/unicode. Would basestring() be a better name? Partly because that seems to be exactly what it's doing, but more because there are (or used to be?) other things in Path that used the word "base", such as "basename". -1 on that specific name if it could be easily confused with "basename" types of things. -Peter From Holzmayer.Bernhard at deadspam.com Mon Jul 18 03:06:14 2005 From: Holzmayer.Bernhard at deadspam.com (Bernhard Holzmayer) Date: Mon, 18 Jul 2005 09:06:14 +0200 Subject: Ordering Products References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > > Now lets drop the assumption that a and b commute. More general: let be > M a set of expressions and X a subset of M where each element of X > commutes with each element of M: how can a product with factors in M be > evaluated/simplified under the condition of additional information X? > > It would be interesting to examine some sorting algorithms on factor > lists with constrained item transpositions. Any suggestions? > Hello Kay, take this into account: Restrictions like commutativity, associative, distributive and flexibility laws don't belong neither to operands nor to operators themselves. Instead these are properties of fields (set of numbers with respect to a certain operation). For a famous example for a somewhat "alternative" behaviour look at the Octonions (discovered in 1843 by Graves and 1845 by Cayley), which are not associative with respect to addition and/or multiplication. (http://en.wikipedia.org/wiki/Octonions) or the Quarternions, which are non-commutative (http://en.wikipedia.org/wiki/Quaternion) Obviously, it's not correct to say: addition is associative, or, that multiplication is. With the same right, you could say, multiplication is not associative. With the same reasoning, we can show that it's not easy to generalize sorting, commutation, association or distribution mechanisms. Maybe it would be a very fascinating goal to solve your algorithmic approach in such a limited environment like the Quarternions. A solution for this set of numbers, if achieved in a clean, mathematically abstract way, should hold for most other numbers/fields too, natural and real included. I guess that the approach might be this way: - define/describe the fields which shall be handled - define/describe the rules which shall be supported - find methods to reduce sequences of operations to simple binary or unary operations (tokens) - this may introduce brackets and stacking mechanisms - a weighing algorithm might be necessary to distinguish between plain numbers and place holders (variables) - application of the distributivity (as far as possible) might help to find a rather flat representation and a base for reordering according to the weights of the individual sub-expressions Nevertheless, there are lots of commercial programs which do such sort of symbolic mathematics, and which would badly fail when it would come to such awkward fields like Quarternions/Octonions. Bernhard From erniedude at gmail.com Wed Jul 27 10:52:52 2005 From: erniedude at gmail.com (Ernesto) Date: 27 Jul 2005 07:52:52 -0700 Subject: GUI - Windows: Where to get started In-Reply-To: <1122428995.530428.187960@z14g2000cwz.googlegroups.com> References: <1122407053.577282.230190@o13g2000cwo.googlegroups.com> <1122428995.530428.187960@z14g2000cwz.googlegroups.com> Message-ID: <1122475972.721462.243720@g49g2000cwa.googlegroups.com> THANKS SO MUCH FOR ALL YOUR RESPONSES!!!!! I will look into everything and find what's right for my project. From john at castleamber.com Tue Jul 19 12:44:32 2005 From: john at castleamber.com (John Bokma) Date: 19 Jul 2005 16:44:32 GMT Subject: Xah's edu corner: on Microsoft hatred References: <1121723096.840897.37700@g47g2000cwa.googlegroups.com> <3k4nmsFs7kocU2@individual.net> Message-ID: "Default User" wrote: > A good newsreader and aggressive use of filtering is the best way to > handle such people. The best way is to complain with their ISP/USP and have their account canceled. Kill filing (filtering) is just closing your eyes. -- John Small Perl scripts: http://johnbokma.com/perl/ Perl programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From simon.dahlbacka at gmail.com Fri Jul 15 08:04:47 2005 From: simon.dahlbacka at gmail.com (Simon Dahlbacka) Date: 15 Jul 2005 05:04:47 -0700 Subject: Documenting extension modules? In-Reply-To: References: <42D79025.4000405@gmx.net> Message-ID: <1121429087.709252.156690@g44g2000cwa.googlegroups.com> Re: assigning a PyStr object to __doc__, take a look at Py_InitModule3, which does that for you. Then you have the PyDoc_STRVAR macro in python.h that you might want to use (see definition below). But as Robert already told you, you'll need to provide the necessary information about i.e. parameters yourself in the docstrings. /* Define macros for inline documentation. */ #define PyDoc_VAR(name) static char name[] #define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str) #ifdef WITH_DOC_STRINGS #define PyDoc_STR(str) str #else #define PyDoc_STR(str) "" #endif From zbir at urbanape.com Wed Jul 6 09:33:45 2005 From: zbir at urbanape.com (Zachery Bir) Date: Wed, 06 Jul 2005 13:33:45 GMT Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <42CBDC5B.9020208@syscononline.com> Message-ID: Larry Bates writes: > You don't say how long it took to develop the "macros" but > you should see what kind of website an experienced Zope/Plone > programmer can whip up in a few minutes. Zope/Plone (as frameworks) represent exactly the kinds of DSLs people have been building with Lisp for decades. Shoulders of giants, and all that. Lisp has web app frameworks as well: Uncommon Web and BKNR, to name two. Zac From python at rcn.com Sat Jul 16 05:31:28 2005 From: python at rcn.com (Raymond Hettinger) Date: 16 Jul 2005 02:31:28 -0700 Subject: Generating a list of None References: <1121394341.448430.130570@g14g2000cwa.googlegroups.com> <42d82da3.279202121@news.oz.net> Message-ID: <1121506288.458576.317930@g14g2000cwa.googlegroups.com> [Bengt Richter] > how about (untested) > > def get_options(opts): > """Return True or False if an option is set or not""" > return [1 for val in vars(opts).values() if val is not None] and True or False While we're tossing around hacks and coding atrocities, we should note that: not not x outperforms: x and True or False neither of which is as clear as: bool(x) Raymond From lbates at syscononline.com Wed Jul 13 19:35:23 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 13 Jul 2005 18:35:23 -0500 Subject: Date & time in a Zip File In-Reply-To: References: Message-ID: <42D5A53B.5020504@syscononline.com> When I add files to my .ZIP files using python zipfile module the date/time that is stored in mine is the one that comes from the file's attributes. I'm not sure I understand why you think yours are not. -Larry Bates Tim Williams (gmail) wrote: > Using zipfile.Zipfile > > How can I add a file to a zip file and keep its date and time correct? > Currently the date/time change to the time the file was added to the > zip. Zipinfo doesn't have a write method! > > Solutions other than zipfile are welcome, with snippets if possible :) > > ginmf in this instance. From callmebill at gmail.com Thu Jul 21 10:39:10 2005 From: callmebill at gmail.com (callmebill at gmail.com) Date: 21 Jul 2005 07:39:10 -0700 Subject: Overriding a built-in exception handler Message-ID: <1121956750.750199.289050@g14g2000cwa.googlegroups.com> I'm having a tough time figuring this one out: class MyKBInterrupt( ..... ): print "Are you sure you want to do that?" if __name__ == "__main__": while 1: print "Still here..." So this thing keeps printing "Still here..." until the user hits ctl-c, at which time the exception is passed to MyKBInterrupt to handle the exception, rather than to whatever the built-in handler would be. I've Read-TFM, but I only see good info on how to create my own class of exception; I don't see anything on how to override an existing exception handler. Thanks in advance for any help. From pink at odahoda.de Wed Jul 20 04:33:10 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 20 Jul 2005 10:33:10 +0200 Subject: dictionary as property References: Message-ID: Thanos Tsouanas wrote: > Hello. > > (How) can I have a class property d, such that d['foo'] = 'bar' will run > a certain function of the class with 'foo' and 'bar' as it's arguments? I think you mean: class A: def __init__(self): self.d = {} def dict_change(self, key, value): print key, value a = A() a.d['foo'] = 'bar' --> foo bar 'a' only has a reference to 'd', it won't know, who has a copy of this reference and what done to it. What you could create, is a wrapper around 'd', that passes __getitem__, __setitem__ and every other required method to the underlying dict and call the appropriate hook method of A class WrappedDict: def __init__(self, owner, d): self.owner = owner self.d = d def __setitem__(self, key, value): self.owner.dict_changed(key, value) self.d[key] = value def __getitem(self, key): return self.d[key] .... And in A.__init__ self.d = WrappedDict(self, {}) You may also subclass WrappedDict from dict... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From martin.witte at gmail.com Fri Jul 1 18:47:50 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 1 Jul 2005 15:47:50 -0700 Subject: How to execute stored procedure? In-Reply-To: <1120217675.222645.129930@g44g2000cwa.googlegroups.com> References: <1120217675.222645.129930@g44g2000cwa.googlegroups.com> Message-ID: <1120258069.973719.162290@g49g2000cwa.googlegroups.com> db-api specifies a .callproc() method on a cursor object (http://www.python.org/peps/pep-0249.html), cx_Oracle implements it (http://starship.python.net/crew/atuining/cx_Oracle/html/cursorobj.html). for me it works. From anupam.kapoor at gmail.com Wed Jul 27 01:01:11 2005 From: anupam.kapoor at gmail.com (Anupam Kapoor) Date: 26 Jul 2005 22:01:11 -0700 Subject: Extreme n00b question References: <1122358384.455900.91810@g44g2000cwa.googlegroups.com> <7dydnSiF8ozCQHjfRVn-hg@speakeasy.net> Message-ID: <1122440399.371108.318160@g43g2000cwa.googlegroups.com> ,---- | Something like | a_simple_python_example = __import__('a-simple-python-example') `---- thanks ! that works. kind regards anupam From tim.peters at gmail.com Sun Jul 3 13:25:58 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 3 Jul 2005 13:25:58 -0400 Subject: math.nroot [was Re: A brief question.] In-Reply-To: References: Message-ID: <1f7befae050703102523645042@mail.gmail.com> [Steven D'Aprano] ... > But this works: > > py> inf = float("inf") > py> inf > inf Another platform-dependent accident. That does not work, for example, on Windows. In fact, the Microsoft C float<->string routines don't support any way "to spell infinity" that works in the string->float direction. From lebasn at gmail.com Mon Jul 25 17:57:01 2005 From: lebasn at gmail.com (Nicolas Lebas) Date: Mon, 25 Jul 2005 23:57:01 +0200 Subject: pyQT 4 Message-ID: <42E5602D.2090803@gmail.com> hello, i'm using actually pyqt 3.x to create several tools under linux. I plan to propose those tools also for windows and mac os x under GPL agreement. My question is : does anybody know when pyqt 4 will be distributed ? thanks Nicolas From peter at engcorp.com Sun Jul 3 15:34:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Jul 2005 15:34:08 -0400 Subject: Accepted Summer of Code proposals In-Reply-To: References: <68e6a54a005f51ae50ada6932ea22d09@wolke7.net> Message-ID: Peter Decker wrote: > On 7/2/05, Reinhold Birkenfeld wrote: >>Is it right that two Wax proposals were accepted? > > Or that Wax is being promoted over Dabo "Promoted"? Do you know if any Dabo proposals were even made? And how good the proposals were? The money goes to those who are actually willing to do some work, and to those projects for which willing mentors are available. Perhaps one of these things wasn't present in Dabo's case... -Peter From fargo_01 at hotmail.com Tue Jul 12 05:50:42 2005 From: fargo_01 at hotmail.com (fargo) Date: Tue, 12 Jul 2005 11:50:42 +0200 Subject: Sort files by date Message-ID: <42d39273$0$12593$636a15ce@news.free.fr> Hi. I'm looking for some way to sort files by date. I'm usin glob module to list a directiry, but files are sorted by name. >>> import glob >>> path = "./" >>> for ScannedFile in glob.glob(path): ... print ScannedFile I googled my problem, but did not find any solution, neither in this newsgroup. Can anyone help me ? Thanks From ronpro at cox.net Fri Jul 1 20:19:20 2005 From: ronpro at cox.net (Ron Provost) Date: Fri, 1 Jul 2005 20:19:20 -0400 Subject: custom Tkinter ListBox selectMode Message-ID: <72lxe.52775$iU.757@lakeread05> Hello, I've written a simple GUI which contains a listbox to hold some information. I've found that the click-selection schemes provided by Tkinter are insufficient for my needs. Essentiall I need to impletement a custom selectMode. As a first go, I've attempted to implement a click-on-click-off mode. So for each entry, a click on that entry toggels its selection mode. A click on any entry does not affect the selection mode of any other entry. I attempted to implement this by binding myListBoxWidget.bind( '', self.itemClicked ) Where my itemClicked() method determines which item was clicked on then toggels it's selection state. So, what's my problem? Well, it doesn't work. The SINGLE selectMode (default) seems to always take over. I'm tempted to set a simple timer callback for a short duration which redoes the selection set after the built-in hander has had a chance to do its thing, but that seems like such a kludge to me. Any suggestions on how I can implement a custom selectMode? Thanks for your input. Ron From roccomoretti at hotpop.com Tue Jul 26 11:44:09 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 26 Jul 2005 10:44:09 -0500 Subject: SciPy and NetCDF In-Reply-To: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> References: <1122391443.306350.297100@g14g2000cwa.googlegroups.com> Message-ID: skilpat at gmail.com wrote: > I am going to be doing a lot of work with large data sets stored in > various netCDF files, and after checking out the alternatives, I would > really like to go with SciPy. The problem is that SciPy offers no > native netCDF support. You may be having an issue because there is a difference between SciPy [http://www.scipy.org/] and ScientificPython [http://starship.python.net/~hinsen/ScientificPython/] - despite the name similarity, they are not the same thing. From hancock at anansispaceworks.com Wed Jul 20 14:42:34 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 20 Jul 2005 13:42:34 -0500 Subject: OO design In-Reply-To: References: <5j4De.52664$oJ.7986@news-server.bigpond.net.au> Message-ID: <200507201342.35490.hancock@anansispaceworks.com> On Wednesday 20 July 2005 07:22 am, chris wrote: > Also minor clarifications:: > > > I'm hoping some of you python > > lamas out there might be able to share some of your wisdom on the subject. > > lama = guru = teacher (not a furry animal, although my dog has certainly > taught me a few tricks ... like when to take her for a walk, when to play > ball, and when its time for a tummy rub.) Ah, of course. My mistake. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From max at alcyone.com Wed Jul 6 02:31:32 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 05 Jul 2005 23:31:32 -0700 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120590707.093007.175330@o13g2000cwo.googlegroups.com> Message-ID: Terry Hancock wrote: > It's a generalization rather than a specialization: > > double (or couple) > triple > quadruple > quintuple > sextuple > septuple > octuple > nontuple > ... > > Maybe a wee bit less obvious, but still understandable. The general form is explicitly called an "n-tuple" or "tuple" in mathematics. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Death to all fanatics! -- Malaclypse the Younger From ajikoe at gmail.com Wed Jul 27 09:50:55 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 27 Jul 2005 06:50:55 -0700 Subject: pylab wxpython Message-ID: <1122472255.439449.193830@g47g2000cwa.googlegroups.com> Hello, I make a windows button which show pylab plot. When I click the button the plot is showed, then I close the plot. But the second click will always produce the plot (which can't be closed). Can someone help? pujo From spam.csubich+block at block.subich.spam.com Sat Jul 2 13:30:20 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 02 Jul 2005 13:30:20 -0400 Subject: Splitting string into dictionary In-Reply-To: References: <59e9fd3a0506302121197c545a@mail.gmail.com> <07D0609C-E9ED-11D9-9AD1-000A27B3B070@eastlink.ca> Message-ID: Robert Kern wrote: > David Pratt wrote: > >> I have string text with language text records that looks like this: >> >> 'en' | 'the brown cow' | 'fr' | 'la vache brun' > translations = [x.strip(" '") for x in line.split('|')] > d = dict(zip(translations[::2], translations[1::2])) One caevat is that this assumes that the proto-list doesn't have any '|' inside the actual text. From roy at panix.com Sat Jul 2 18:00:33 2005 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jul 2005 18:00:33 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> <864qbf8hvr.fsf@bhuda.mired.org> Message-ID: Christos "TZOTZIOY" Georgiou wrote: > Were there other Unix C compilers before K&R wrote one? Considering that K&R (along with T) invented both Unix and C, I would say that the answer to the above has to be "No". From steve at REMOVETHIScyber.com.au Mon Jul 11 23:28:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 12 Jul 2005 13:28:36 +1000 Subject: Should I use "if" or "try" (as a matter of speed)? References: Message-ID: On Mon, 11 Jul 2005 21:18:40 +0530, Dark Cowherd wrote: > I tend to use exceptions, but I think Joel has a point. Joel being "Joel On Software" Joel. > Taking the example code that you have given above. > > Let us assume that somebody else is using my_function and DOES NOT > write a try except block. Then, like any other piece of Python code, if it raises an exception the exception will be propagated and the interpreter will halt. That is the correct behaviour. On crash, halt. > This code will run fine except, when the exception is thrown and it will > suddenly pop up in some other error handler which may not be handling > the situation correctly. You have to plan and create a series of > errorhandling classes to handle such situations. Why? You should be aiming to write correct code that doesn't produce random exceptions at random times, rather than wrapping everything in exception handlers, which are wrapped in exception handlers, which are wrapped in exception handlers... Exceptions are useful, but you shouldn't just cover them up when they occur. The idea of exceptions is to recover from them safely, if you can, and if not, bring the program to a halt safely. Dealing with exceptions is no different from dealing with data. If there is data you don't deal with correctly ("what if the user passes -1 as an argument, when we expect an integer larger than zero?") you have a bug. If there is a exception you don't deal with correctly ("what if this function raises ZeroDivisionError when we expect a ValueError?"), you have an uncaught exception which will halt your program, exactly as exceptions are designed to do. > However Joels_function forces the caller to write some kind of error > handler. If he doesnt write the program will not run. And Python gives you that error handler already built in. It is called try...except, and if you don't write it, and your program raises an exception, your program will stop. > After reading that I have been giving this option some thought. The nice > thing about Python is I can easily return tuples. Yes. But returning a tuple (success, data) where the meaning of data varies depending on whether success is True or False is an abuse of the language. I can think of a few places where I might do that, but not very many. The problem with this tuple (success, data) idiom is that it leads to duplicated code. All your functions end up looking like this: def func(data): if data[0]: result = do_real_work(data[1]) if error_condition: return (False, msg) return (True, result) else: return data But then you want to make do_real_work bulletproof, don't you? So do_real_work ends up filled with error checking, just in case the calling function passes the wrong data. So you end up losing all the advantages of wrapping your data in a tuple with a flag, but keeping the disadvantages. In any case, writing masses of boilerplate code is a drain on programmer productivity, and a frequent cause of bugs. Boilerplate code should be avoided whenever you can. -- Steven. From devlai at gmail.com Sat Jul 9 17:20:54 2005 From: devlai at gmail.com (Devan L) Date: 9 Jul 2005 14:20:54 -0700 Subject: Yet Another Python Web Programming Question In-Reply-To: References: Message-ID: <1120944054.548200.42660@f14g2000cwb.googlegroups.com> Take some time to learn one of the web frameworks. If your host doesn't already have it, ask your host if they would consider adding it. From stefan.rank at ofai.at Mon Jul 25 05:03:53 2005 From: stefan.rank at ofai.at (Stefan Rank) Date: Mon, 25 Jul 2005 11:03:53 +0200 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: References: <3kjihkFubvl6U1@individual.net> Message-ID: <42E4AAF9.3080107@ofai.at> on 25.07.2005 10:44 Michael Hoffman said the following: > Reinhold Birkenfeld wrote: >>Tony Meyer wrote: >>>Do people really like using __div__ to mean join? >>Of course, one can use joinwith() if he doesn't like '/'. > Personally, I'm -0 on __div__, but I suppose if anyone here claimed to > have used in the past, rather than it just being some novelty that might > be a good idea, that would be good enough for keeping it. I, herewith, claim to have used it in the past. But I am indifferent as to if its needed, it just looks natural to me. What I use quite often is:: path(__file__).dirname() / "somesiblingfileiknowisthere" you do not have to think about trailing slashes or absolute vs. relative. and its much better than:: from os.path import * join(dirname(__file__), "somesiblingfileiknowisthere") __div__ is actually very convenient to "build" / "a" / "very" / "very" / "long" / "path" (of course assuming the parts are strings not known initially...) From jrastrick at student.usyd.edu.au Sun Jul 3 05:25:34 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 3 Jul 2005 02:25:34 -0700 Subject: how to retrive highlighted text in a browser? In-Reply-To: <1120379718.126989.223300@g14g2000cwa.googlegroups.com> References: <1120379718.126989.223300@g14g2000cwa.googlegroups.com> Message-ID: <1120382734.433192.314270@g14g2000cwa.googlegroups.com> I don't know how hard this would be to do in Python - appending text to a file is straightforward, but it sounds like you'd need to extend the browser itself to get the functionality you want. The most obvious choice if you want an extensible browser is Mozilla Firefox (http://www.mozilla.org/products/firefox/), but AFAIK its extensions are written in C++, and I'm not sure how easy it would be to get Python into the mix. If you do get this working, I'd love to hear about it! I've wanted this feature in browers for a long time. From williams13 at llnl.gov Mon Jul 25 15:29:47 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Mon, 25 Jul 2005 12:29:47 -0700 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050725192252.GA3144@tishler.net> References: <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <20050718121633.GC3292@tishler.net> <42DBA7A8.4010509@llnl.gov> <20050719111537.GC532@tishler.net> <42E0E281.6060009@llnl.gov> <42E10D3B.5050301@llnl.gov> <20050722164442.GB1912@tishler.net> <42E52F04.5010008@llnl.gov> <20050725192252.GA3144@tishler.net> Message-ID: <42E53DAB.8090903@llnl.gov> Right! Forgot to exit out of ALL Cygwin processes. This does work. -Dean Jason Tishler wrote: >Dean, > >On Mon, Jul 25, 2005 at 11:27:16AM -0700, Dean N. Williams wrote: > > >>I was able to run C:/cygwin/bin/ash.exe. This is good. In the >>"ash.exe" window, I ran PATH=/bin rebaseall and received the same >>error: "rebaseall: only ash processes are allowed ...... Execute >>'/bin/rebaseall' from ash." >> >> > >Did you read the error message? In particular, the following: > > Exit all Cygwin processes and stop all Cygwin services. > >Jason > > > From max at alcyone.com Mon Jul 4 04:10:15 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Jul 2005 01:10:15 -0700 Subject: f*cking re module In-Reply-To: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> Message-ID: <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> jwaixs wrote: > arg... I've lost 1.5 hours of my precious time to try letting re work > correcty. There's really not a single good re tutorial or documentation > I could found! There are only reference, and if you don't know how a > module work you won't learn it from a reference! Then Google for regular expression tutorials, not regular expression references. >>>> import re >>>> str = "blablaRe modules sucks!blabla" >>>> re.search("()(/python>)", str).group() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'NoneType' object has no attribute 'group' > > the only thing I want are the number of places blabla, Re modules > sucks! and blabla are. Your question is still not clear. What you're searching for is '', which isn't there, so .search returns None, and so you get that exception (.group takes an argument, anyway). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis With such a weapon I could boil the Earth to vapor. -- Chmeee From lbates at syscononline.com Wed Jul 27 14:43:38 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 27 Jul 2005 13:43:38 -0500 Subject: can list comprehensions replace map? In-Reply-To: References: Message-ID: <42E7D5DA.1000103@syscononline.com> This isn't really a question about list comprehensions as you are using a "feature" of map by passing None as the function to be executed over each list element: This works when len(x) > len(y): zip(x,y+(len(x)-len(y))*[None]) This works when len(y) >=0 len(x): zip(x+(len(x)-len(y))*[None],y) I would probably wrap into function: def foo(x,y): if len(x) > len(y): return zip(x,y+(len(x)-len(y))*[None]) return zip(x+(len(x)-len(y))*[None],y) Larry Bates David Isaac wrote: > Newbie question: > > I have been generally open to the proposal that list comprehensions > should replace 'map', but I ran into a need for something like > map(None,x,y) > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > info from x. How do I do this as a list comprehension? (Or, > more generally, what is the best way to do this without 'map'?) > > Thanks, > Alan Isaac > > From accepted at ukr.net Sat Jul 30 12:36:52 2005 From: accepted at ukr.net (Michael Rybak) Date: Sat, 30 Jul 2005 19:36:52 +0300 Subject: 2-player game, client and server at localhost Message-ID: <12619807802.20050730193652@ukr.net> hi, everyone. I'm writing a 2-players game that should support network mode. I'm now testing it on 1 PC since I don't have 2. I directly use sockets, and both client and server do computations, the only data transfered is user mouse/kbd input. It works synchronously, but somehow, when I play in client window, both client and server have 17 fps, while when playing in server window, server has 44 fps while client has 5, and due to forced synchronization, they both run very slowly (I wonder how come server says it has 44fps?). Does anybody have an idea how can this be? Not that users will test 2 game intances communicating via localhost, but I need to make it work properly. -- Best Regards, Michael Rybak mailto:accepted at ukr.net From ivanlan at pauahtun.org Sat Jul 30 10:01:15 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Sat, 30 Jul 2005 08:01:15 -0600 Subject: [path-PEP] Path inherits from basestring again References: Message-ID: <42EB882B.2DF04797@pauahtun.org> Hi All-- Tony Meyer wrote: > > >> (Those who are offended by sweeping generalisations should > >> ignore this next bit) > [...generalisation bit snipped...] > > This is not only bullshit, it's elitist bullshit. "Windows users are > > more clueless than users of posix systems." Pfui. Prove it > > or withdraw it. > > Sigh. I guess you didn't read or understand the first sentence? > Yes, I read and understood it. Saying "Don't read this if you don't want to be offended" doesn't make an offensive statement inoffensive. > >> This (readability without knowing the language/standard > >> libraries) is a huge benefit of using Python. > > > > It's overrated. It must be macho to say "I learned Python without > > reading books." > > No it is not. Have you used Python as pseudocode when teaching people how > to program? Many people have. That's just one example. > I grant that Python is much easier to learn than other programming languages; students can pick up the basics rapidly. Once the basics are mastered and mentoring is over, reliance on guess and intuition is not a substitute for documentation, or for reading the code if documentation is not available. > People can subclass Path and add it if they really want it. They can use > Jason's original module. My position is that the PEP without this use of > __div__ is (a) better as a standard module, and (b) improves the chance of > the PEP being accepted. > I disagree. Using __div__ to mean path concatenation is no worse than using __add__ to mean string concatenation, and it is both easy to remember (once the manual is read) and easy to type. Requiring users who want / to mean what it has always meant in the path module is neither easy nor intuitive. On the face of it, Jason would seem to agree, since he created / as a synonym for joinpath(). However, if the intention here is to create something different from Jason's original module, create something different and call it by another name than path; don't attempt to guess "what Jason really meant." It is not Pythonic to guess. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From kent37 at tds.net Wed Jul 27 13:15:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 27 Jul 2005 13:15:20 -0400 Subject: html special characters to latin-1 conversion In-Reply-To: References: Message-ID: <42e7c0e4$1_2@newspeer2.tds.net> ulrice jardin wrote: > hi > > I had a look to this htmlentitydefs lib, but I still > don't know how to convert html special characters into > latin-1 characters. > For instance, how can I convert ' into ' or é > and é into ?? Searching comp.lang.python for 'htmlentitydefs' gives quite a few solutions. Here is one way: http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46 Kent From thomasbartkus at comcast.net Tue Jul 12 10:29:58 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 12 Jul 2005 09:29:58 -0500 Subject: Yet Another Python Web Programming Question References: Message-ID: <_PadnUeVWZzKTk7fRVn-oQ@telcove.net> "Daniel Bickett" wrote in message news:mailman.1548.1120941799.10512.python-list at python.org... > It was his opinion that > web programming should feel no different from desktop programming. Should that ever become even remotely possible - I'll be interested in web programming myself. Thomas Bartkus From nobody at nowhere.com Tue Jul 26 13:22:15 2005 From: nobody at nowhere.com (Joe) Date: Tue, 26 Jul 2005 13:22:15 -0400 Subject: Bug Report / Patch (1159139 cgi.py invalid REQUEST_METHOD set) References: <_ICdnT-Tg-3_ynvfRVn-qw@comcast.com> <3kn4qoFuvvdgU1@individual.net> Message-ID: Reinhold, Thanks for responding... I see that you are using Python 2.4.1 and the bug was against 2.4. (I am now using 2.4.1) If I remember correctly there were two issues that I ran into, one was with a missing REQUEST_METHOD and the other was with a INCORRECT request method. As per your example the missing one does not seem to be a problem any longer. The incorrect REQUEST_METHOD setting still seems to be an issue with Python 2.4.1. Make the following changes to your code to demonstrate that problem. import cgi import os # NEW os.environ['REQUEST_METHOD'] = 'cgi' # NEW field = cgi.FieldStorage() print field print field.keys() # NEW Run the program now with NO parameters. (I'm running on WinXP SP2). After you start the program cgi.py will be reading from stdin. type "a=1" and hit enter type "b=2" and hit enter press ctrl-z (to send eof) and hit enter You will get the following stack trace. FieldStorage(None, None, 'a=1\nb=2\n') Traceback (most recent call last): File "H:\1\t2.py", line 12, in ? print field.keys() File "P:\SW\Python\lib\cgi.py", line 601, in keys TypeError: not indexable When the environment does not have a correctly set REQUEST_METHOD cgi.py prompts for key=value pairs by reading from sys.stdin. (as demonstrated above) I realize REQUEST_METHOD should be set properly but hear me out. After the values are read from sys.stdin they are never stored in the FieldStorage.list attribute like they are when the FieldStorage.read_urlencoded or FieldStorage.read_multi methods are called. The read_single method is the one that has the problem (it is inconsistenty with the other two methods because it doesn't store the values like the other two methods do). This causes a problem when FieldStorage.keys() is called because although the values were read from sys.stdin they were never stored in FieldStorage.list. Although you could argue that REQUEST_METHOD should have been set correctly in the first place, it still seems like if cgi.py is going to handle that situation of a invalid REQUEST_METHOD by actually reading the values from sys.stdin (it already does this part) it should store them too (especially since it does store the values in the other two methods). Does that explain the issue more clearly? "Reinhold Birkenfeld" wrote in message news:3kn4qoFuvvdgU1 at individual.net... > Joe wrote: >> Back in March I submitted a patch for cgi.py to sourceforge to fix a >> problem >> with the handling of an invalid REQUEST_METHOD. >> >> I thought I followed all the steps to properly submit the bug and patch >> but >> the patch is still sitting there in limbo. >> >> This is the first patch I have submitted for Python, did I miss a step in >> the patch process? >> >> What else needs to be done? > > Can you provide an example script demonstrating the problem you describe? > > I tried something like this (Py2.4.1): > > ------- test_cgi.py > #!/bin/env python > import cgi > fs = cgi.FieldStorage() > print fs > > $ python test_cgi.py "a=1&b=2" > FieldStorage(None, None, [MiniFieldStorage('a', '1'), > MiniFieldStorage('b', '2')]) > $ > > There's no REQUEST_METHOD or QUERY_STRING env var set. > > Reinhold From gsakkis at rutgers.edu Fri Jul 22 10:14:09 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 22 Jul 2005 07:14:09 -0700 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <1122041649.070945.85380@g49g2000cwa.googlegroups.com> "Duncan Booth" wrote: > Personally I think the concept of a specific path type is a good one, but > subclassing string just cries out to me as the wrong thing to do. In other > words, to me a path represents something in a filesystem, the fact that it > has one, or indeed several string representations does not mean that the > path itself is simply a more specific type of string. > > You should need an explicit call to convert a path to a string and that > forces you when passing the path to something that requires a string to > think whether you wanted the string relative, absolute, UNC, uri etc. First off, I find this is a relatively small detail overall, that is, regardless of whether path subclasses string or not, its addition in the standard library will be a step forward. Havind said that, I think the choice between subclassing or not is going to be a practicality-vs-purity decision. You're right, conceptually a path HAS_A string description, not IS_A string, so from a pure OO point of view, it should not inherit string. OTOH, people in favor of the subclassing point out the convenience for many (or most) common cases. It's a tradeoff, so arguments for both cases should be discussed. George From randyhoward at FOOverizonBAR.net Sun Jul 10 22:35:42 2005 From: randyhoward at FOOverizonBAR.net (Randy Howard) Date: Mon, 11 Jul 2005 02:35:42 GMT Subject: What is Expresiveness in a Computer Language? References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: <0001HW.BEF7452F00F6589CF0305550@news.verizon.net> Keith Thompson wrote (in article ): > \||||/ | | \| __\,,\ /,,/__ > \||/ | | | jgs (______Y______) > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > ============================================================== Out of curiosity, does anyone remember who 'jgs' refers to above? -- Randy Howard (2reply remove FOOBAR) From reinhold-birkenfeld-nospam at wolke7.net Thu Jul 28 09:08:43 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 28 Jul 2005 15:08:43 +0200 Subject: multiple inheritance super() In-Reply-To: <1122548998.766210.101860@g47g2000cwa.googlegroups.com> References: <42e6aac4$0$14586$626a14ce@news.free.fr> <42e6c629@nntp0.pdx.net> <42e748e9$0$32207$626a14ce@news.free.fr> <1122454160.835071.87690@z14g2000cwz.googlegroups.com> <863bpzmz50.fsf@bhuda.mired.org> <1122548998.766210.101860@g47g2000cwa.googlegroups.com> Message-ID: <3ks3mrFvr5jkU1@individual.net> Michele Simionato wrote: >> http://fuhm.org/super-harmful/ > > That is a pretty good page; I must say that my position is more radical > (i.e. it is not super which > is harmful, it is multiple inheritance itself that it is harmful: was I > going to design a new language > I would implement it *without* multiple inheritance). Multiple inheritance can be very useful if not used in an unresponsible way. For example, think of mixins. Or compatibility layers. Lately I had to adapt a wx 2.6 application to wx 2.4 I could either search and substitute $BIGNUM self.Bind() calls (which isn't done via simple Emacs magic, cause the replacement varies), or I could write a compatibility mixin and derive every GUI class from it, too. Reinhold From mt at 3planes.com Wed Jul 6 16:36:50 2005 From: mt at 3planes.com (Michael Tobis) Date: 6 Jul 2005 13:36:50 -0700 Subject: PyNSol: Objects as Scaffolding Message-ID: <1120682210.858023.154940@o13g2000cwo.googlegroups.com> An article of mine, entitled "PyNSol: Objects as Scaffolding" has appeared in Computing in Science and Engineering. You can read it at http://www.computer.org/portal/site/cise/ or alternatively at http://geosci.uchicago.edu/~tobis/ciseps.pdf It's not so much an article about a software project as it is an article using that project to present an alternative way of thinking about how object oriented programming (and Python!) can relate to high performance simulations. I welcome comments. mt -- Michael Tobis Geophysical Sciences University of Chicago From prabapython at yahoo.co.in Sat Jul 23 07:14:26 2005 From: prabapython at yahoo.co.in (praba kar) Date: Sat, 23 Jul 2005 12:14:26 +0100 (BST) Subject: Retrive file name from the window's file path In-Reply-To: <20050723101225.GB1756@zermelo.sians.org> Message-ID: <20050723111426.89394.qmail@web8406.mail.in.yahoo.com> Dear All, I am using Python 2.4 in the linux platform. At present I am working on webbased file manager. When I try to upload a file from the linux cgi script easily fetch the file name by the filefield.filename. But When I try to upload a file from the windows machine It won't retrieve the file instead of retrieved full path (C:\\WINDOWS\my.gif). And at the same I couldn't know how to get file name from window's file path C:\\WINDOWS\my.gif. I try to workout these things by os.path.basename().os.path.splitext(). Kindly let me how to handle these situation prabahar __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From devnull at joreybump.com Sat Jul 9 20:48:48 2005 From: devnull at joreybump.com (Jorey Bump) Date: Sun, 10 Jul 2005 00:48:48 GMT Subject: Defending Python References: <2aAze.42404$J12.1907@newssvr14.news.prodigy.com> <1120920801.730115.9410@g43g2000cwa.googlegroups.com> <11cvsutdl580b17@corp.supernews.com> <42d031da$0$30239$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:42d031da$0$30239$636a15ce at news.free.fr: > Grant Edwards a ?crit : >> On 2005-07-09, Brian wrote: >> >> >>>>folks as an easily acquired extra skill. >>> >>>I agree 100% with your statement above. Python may not be sufficient >>>for being the only programming language that one needs to know -- yet, >>>it does come in VERY handy for projects that need to perform tasks on >>>non-Microsoft operating systems. :-) >> >> >> It's also darned handy for projects that need to perform tasks >> on Microsft operating systems but you want to do all the >> development work under a real OS. >> > > It's also darned handy for projects that need to perform tasks on > Microsft operating systems. It's also darned handy for projects that need to perform tasks... Or don't... And for other things besides projects... Anyway, it's darned handy! From ajartaknev at gmail.com Fri Jul 29 08:21:23 2005 From: ajartaknev at gmail.com (Ajar) Date: 29 Jul 2005 05:21:23 -0700 Subject: writing a web client Message-ID: <1122639683.798795.160100@g43g2000cwa.googlegroups.com> I want to write a program which will automatically login to my ISPs website, retrieve data and do some processing. Can this be done? Can you point me to any example python programs which do similar things? Regards, Ajar From titogarcia_borra_esto at gmail.com Wed Jul 27 14:46:16 2005 From: titogarcia_borra_esto at gmail.com (Tito) Date: Wed, 27 Jul 2005 20:46:16 +0200 Subject: [Beginner] Calling a function by its name in a string In-Reply-To: References: Message-ID: Thank you both for your quick answers. What I wanted is to parameterize a function with another member function, like this: def printFunctionForEach(collection, functionName): for elem in collection: print eval("elem." + functionName + "()") Moreover, I wanted to do it with a property: def printPropertyForEach(collection, propertyName): for elem in collection: print eval("elem." + propertyName) Is there another approach to do it? Regards, Tito From max at alcyone.com Sat Jul 9 05:18:17 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Jul 2005 02:18:17 -0700 Subject: file.readlines() question In-Reply-To: References: Message-ID: vch wrote: > Does a call to file.readlines() reads all lines at once in the memory? > Are the any reasons, from the performance point of view, to prefer > *while* loop with readline() to *for* loop with readlines()? Yes, and you just mentioned it. .readlines reads the entire file into memory at once, which can obviously be expensive if the file is large. A for loop with .readline, of course, will work, but modern versions of Python allow iteration over a file, which will read it line by line: for line in aFile: ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis A wise man never loses anything if he have himself. -- Montaigne From peter at engcorp.com Thu Jul 21 13:53:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Jul 2005 13:53:08 -0400 Subject: Need to interrupt to check for mouse movement In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Thu, 21 Jul 2005 02:33:05 -0400, Peter Hansen wrote: >> (And since there is even a wxPython main loop >> integrated with and provided in Twisted, surely you aren't arguing that >> what wx does is somehow unusual or bad.) > > Blocking inside the mainloop while waiting for events is fine. It's > blocking elsewhere that is problematic. Thanks for the clarification. I can see how a wx modal dialog could cause trouble, though I didn't know holding a menu open had the same nasty behaviour. For me, this is merely justification to continue using separate threads for wxPython's main loop and for anything else, which has worked well for me whether I've been using Twisted or not. -Peter From cam.ac.uk at mh391.invalid Sun Jul 31 16:37:57 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 31 Jul 2005 21:37:57 +0100 Subject: keylogger in Python In-Reply-To: References: <1122711091.982939.34080@g44g2000cwa.googlegroups.com> <1122785344.538363.122600@g49g2000cwa.googlegroups.com> Message-ID: [Michael Hoffman] >>You think this is a suitable beginner project? [Francois Pinard] > One surely learns a lot! :-) I can agree with that! -- Michael Hoffman From usenet at zabiello.com Fri Jul 15 21:26:07 2005 From: usenet at zabiello.com (JZ) Date: Sat, 16 Jul 2005 03:26:07 +0200 Subject: Django - Rails killer comes... Message-ID: <15cuhhg8i6mrg$.ekh1brvux44n$.dlg@40tude.net> http://www.djangoproject.com/ -- JZ From k04jg02 at kzoo.edu Thu Jul 7 17:15:38 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Thu, 07 Jul 2005 15:15:38 -0600 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: Message-ID: <42CD9B7A.6040905@kzoo.edu> Everyone complaining about Eclipse in this thread needs to go try 3.1. The interface is much much much more responsive. Also, everyone keeps discussing Eclipse as something that gives Java a leg up on Python. *Ahem* PyDev :) Which you should also give another try if you haven't in a few versions. Easiest way to get a GUI debugger for python. My only misgiving with Eclipse now is that I think development of plugins for it is always going to be slower than for Emacs and other editors because they have to be written in Java. From peter at engcorp.com Sat Jul 2 14:07:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 14:07:29 -0400 Subject: What are the other options against Zope? In-Reply-To: References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> Message-ID: <6f-dnTeTQayMRVvfRVn-jQ@powergate.ca> Florian Lindner wrote: > Peter Hansen wrote: >>[Zope] doesn't include >>database interfaces other than to its own ZODB. > > That's not correct. Zope2 includes DB interfaces to MySQL, PostGre, ODBC and > many others. It actually *includes* them? I thought those were all add-in modules, not ones that Zope actually installs. (I admit it's been a couple of years since I was current with the state of Zope... and my memory sucks. :-( ) -Peter From bdesth.quelquechose at free.quelquepart.fr Sun Jul 24 08:01:30 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Jul 2005 14:01:30 +0200 Subject: Getting a dictionary from an object In-Reply-To: References: Message-ID: <42e37c1e$0$30692$636a15ce@news.free.fr> Thanos Tsouanas a ?crit : > On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote: (snip) > >>Why jump through all those hoops to get attributes when Python already >>provides indexing and attribute grabbing machinery that work well? Why do >>you bother to subclass dict, only to mangle the dict __getitem__ method so >>that you can no longer retrieve items from the dict? > > Because *obviously* I don't know of these indexing and attribute > grabbing machineries you are talking about in my case. If you cared to > read my first post, all I asked was for the "normal", "built-in" way to > do it. Now, is there one, or not? If you re-read your first post, you'll notice that you didn't say anything about the intention, only about implementation !-) Now if your *only* need is to access object as a dict for formated output, you don't need to subclass dict. This is (well, should be) enough: class Wrapper(object): def __init__(self, obj): self._obj = obj def __getitem__(self, name): return getattr(self._obj, name) This works with 'normal' attributes as well as with properties. Notice that this wrapper is read-only, and don't pretend to be a real dictionnary - but still it implements the minimum required interface for "%(attname)s" like formatting. HTH Bruno From volker_grabsch at v.notjusthosting.com Mon Jul 25 05:15:21 2005 From: volker_grabsch at v.notjusthosting.com (Volker Grabsch) Date: Mon, 25 Jul 2005 11:15:21 +0200 Subject: What license to choose for Python programs? (PSF License vs. GPL/LGPL) Message-ID: Hi! I noticed that many packages in the PyPI are using the PSF License. Does this have a special reason? Is this the common "standard" license for Python libraries? I'm just asking because I'll release some bigger pieces of Python code to the Open Source Community. In my many projects before I just used GPL or LGPL. This didn't have a special reason. They are just standard OS licenses. I could also have used the BSD License, but I personally like the GPL/LGPL more. Of course I know that there are many, many other licenses out there. I'm not interested in comparing them all for their slight differences. I don't choose the license primarily for protecting my code. I want to choose the license according to the most common/appropriate way of the community. So if it is complicated to include an LGPL'ed Python library in the Python standard libraries, I'd release it under PSF License. I'd like to hear some opinions about that. What licenses do you use, and what's your personal reason for doing so? Also, a quick overview about the various licenses would be nice. Not a legal comparison, but a list about what type of code/programs/libs is usually released under which license. Thanks for your help, Volker -- Volker Grabsch ---<<(())>>--- \frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt [G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}} From roccomoretti at hotpop.com Fri Jul 8 10:29:35 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 08 Jul 2005 09:29:35 -0500 Subject: f*cking re module In-Reply-To: References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <1120568322.948740.229830@g44g2000cwa.googlegroups.com> <87oe9e28px.fsf@bigfoot.com> <86oe9dvs6d.fsf@bhuda.mired.org> Message-ID: Fran?ois Pinard wrote: > I once worked with a PL/I compiler (on a big IBM mainframe), which was > trying to be helpful by spitting pages of: > > Error SUCH AND SUCH, assuming that THIS AND THIS was meant. > > and continuing compilation nevertheless. It was a common joke to say > that PL/I would compile some random valid program out of any garbage! We may laugh now (and then), but it was likely a valid design decision at the time. If you're running a job on "big iron", depending on the situation, you might have had only a block of a few hours on a timeshared system, perhaps unattended. If the compiler refused to continue, the rest of your block might have been wasted. (At the very least, you would have had to sign up for an additional block later.) If your program had only minor errors, there was likely a good chance that the compiler might guess correctly, and your program would compile to what you wanted in the first place. If not, by continuing on, the compiler can flag additional errors later in your code, allowing you to fix those bugs sooner. (Instead of choking on the first one and refusing to continue.) Error-checking-by-compiling only "works" if you have cheap computing power you can run attended. (Can you imagine what TDD would be like if you had to wait 24+ hrs between code executions?) From bh at intevation.de Thu Jul 28 13:41:29 2005 From: bh at intevation.de (Bernhard Herzog) Date: Thu, 28 Jul 2005 19:41:29 +0200 Subject: Rich Graphics? References: Message-ID: Chris Spencer writes: > I'm trying to write a Gui in Python for manipulating rich graphical > representations, similar to something like Inkscape. I've tried tkinter, > wxPython, pyGtk, and while they all do traditional widgets well enough, > none of them really handle anti-aliased, transparent, transformed shapes > typical of vector based displays. You may want to have a look at Skencil (see my .sig for a URL). The CVS version does have anti-aliasing and some simple translucency. It doesn't support all of SVG yet, though. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From ronpro at cox.net Fri Jul 8 11:53:30 2005 From: ronpro at cox.net (ronpro at cox.net) Date: Fri, 8 Jul 2005 11:53:30 -0400 Subject: socket code Message-ID: <20050708155330.JCCJ11036.lakermmtao01.cox.net@smtp.east.cox.net> Hello, I'm trying to create a broadcast socket in some portable code (windows XP & mandrake linux). When I run the following lines through idle: import socket s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.connect( ('', 17100) ) On windows, connect() returns and I have a broadcast socket to which I can write. One LINUX connect() just tells me 'Permission denied'. Does anybody know why? Any thoughts on how I can get around this? I have to transmitt data to an old system. The system only reads broadcast data on port 17100. Thanks for the input. Ron Provost From pinard at iro.umontreal.ca Tue Jul 5 08:40:22 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 5 Jul 2005 08:40:22 -0400 Subject: f*cking re module In-Reply-To: <9oSdnUwoj_jBjVffRVn-sg@comcast.com> References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> <9oSdnUwoj_jBjVffRVn-sg@comcast.com> Message-ID: <20050705124022.GA8500@alcyon.progiciels-bpi.ca> [D H] > Gustavo Niemeyer wrote: > > That's what I love in that news group. Someone comes with a > > stupid and arrogant question, and someone else answers in a > > calm and reasonable way. > ...and then someone else comes along and calls the first person stupid > and arrogant, which is deemed QOTW. :) Hey! The "question", not the "person"! One might say "the subject", but then, it has to be the subject of the message, of course! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From ggg at zzz.it Sun Jul 31 06:01:06 2005 From: ggg at zzz.it (deelan) Date: Sun, 31 Jul 2005 12:01:06 +0200 Subject: namespaces In-Reply-To: References: <42EC9690.2040301@tiscali.it> Message-ID: deelan wrote: (...) > # optional, get rid of _setup_table symbol > del _setup_table() damn copy and paste :) of course i meant: del _setup_table -- deelan, #1 fan of adriana lima! From rahu at gawab.com Sat Jul 16 23:15:20 2005 From: rahu at gawab.com (Jonathan Conrad) Date: Sat, 16 Jul 2005 23:15:20 -0400 Subject: What module to use to get a file from a website? In-Reply-To: <1121464923.522948.46080@f14g2000cwb.googlegroups.com> References: <1121461052.535331.5710@f14g2000cwb.googlegroups.com> <1121464923.522948.46080@f14g2000cwb.googlegroups.com> Message-ID: <42D9CD48.6090906@gawab.com> from os import system system ("start http://www.python.org/") From harold.fellermann at upf.edu Tue Jul 12 10:55:29 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 12 Jul 2005 16:55:29 +0200 Subject: Missing Something Simple In-Reply-To: <42D3D089.6030403@plus.net> References: <42D3C920.2000808@plus.net> <11f99613a4f2a4c64f8055e060b8e965@upf.edu> <42D3D089.6030403@plus.net> Message-ID: <920a9e9a63459b003a5135ff3d77f330@upf.edu> >>> I have a list of variables, which I am iterating over. I need to set >>> the value of each variable. My code looks like: >>> >>> varList = [ varOne, varTwo, varThree, varFour ] >>> >>> for indivVar in varList: >>> indivVar = returnVarFromFunction() >>> >>> However, none of the variables in the list are being set. >>> >> >> You only change the value of the local variable in the body >> of the for loop. it has no effect on the list. you could do e.g. >> >> varList = [vorOne,varTwo,varThree,varFour] >> for i in len(varList) : >> varList[i] = returnVarFromFunction() >> >> However, as in this example the former list values are not used >> anyway, >> you could just write: >> >> varList = [ returnVarFromFunction for i varList ] >> > The problem I have, is the variables are referenced elsewhere. They > have been declared before being used in the list. Basically, I'm > after the Python way of using deferencing. so, if I understand you right, what you want to have is a list of mutable objects, whose value you can change without changing the objects' references. class Proxy : def __init__(self,val) : self.set(val) def set(self,val) : self.val = val def get(self) : return self.val a = Proxy(1) b = Proxy(2) c = Proxy(3) varList = [a,b,c] for i in varList : i.set(returnVarFromFunction()) print a,b,c prints whatever returnVarFromFunction has returned. n.b.: instead of the Proxy class, you can use any other mutable objects, e.g. lists. - harold - -- "All unsere Erfindungen sind nichts als verbesserte Mittel zu einem nicht verbesserten Zweck." -- H.D. Thoreau From rkern at ucsd.edu Thu Jul 28 15:53:01 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Jul 2005 12:53:01 -0700 Subject: Ten Essential Development Practices In-Reply-To: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: gyromagnetic at gmail.com wrote: > The following url points to an article written by Damian Conway > entitled "Ten Essential Development Practices": > http://www.perl.com/pub/a/2005/07/14/bestpractices.html > > Althought the article has Perl as a focus, I thought that some of the > general points made might be of interest to the Python community. It > would certainly be interesting to put together an analogous version of > this article that centers on Python. import this And you get 9 bonus Essential Development Practices, too! What a bargain! -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From enderlocke.dallin at gmail.com Sat Jul 23 13:01:01 2005 From: enderlocke.dallin at gmail.com (EnderLocke) Date: 23 Jul 2005 10:01:01 -0700 Subject: Friend wants to learn python Message-ID: <1122135598.347717.75830@g43g2000cwa.googlegroups.com> I have a friend who wants to learn python programming. I learned off the internet and have never used a book to learn it. What books do you recommend? Any suggestions would be appreciated. From fdeserres at gmx.net Fri Jul 15 07:52:30 2005 From: fdeserres at gmx.net (Francois De Serres) Date: Fri, 15 Jul 2005 13:52:30 +0200 Subject: Documenting extension modules? In-Reply-To: References: <42D79025.4000405@gmx.net> Message-ID: <42D7A37E.3010205@gmx.net> Robert Kern wrote: >Francois De Serres wrote: > > >>Hiho, >> >>I can't seem to find a proper way to document my extension module. >>Following the C API doc: >> >>static PyMethodDef ioMethods[] = { >> {"o_count", o_count, METH_VARARGS, "Return the count of available >>MIDI outputs."}, >>.... >>} >> >>lacks: >>a) module level documentation >> >> > >In your init function, assign a PyStr object to __doc__. > > > >>b) function parameters >> >> > >Add that information to your docstring. I don't think that there is a >way to get this information via inspect. > > > >>Also, I'd like to know if there's a typical format for the help string >>(but in C), compatible with docstring's >>"""short desription >> >>long description""" >> >> > >char *o_count__doc__; >char *o_count__doc__ = "short description\n"\ >"\n"\ >"long description\n"; > > > Mucho thankees Robert. From afriere at yahoo.co.uk Wed Jul 6 01:47:10 2005 From: afriere at yahoo.co.uk (Asun Friere) Date: 5 Jul 2005 22:47:10 -0700 Subject: looping over a big file In-Reply-To: <1120628707.185004.227910@g49g2000cwa.googlegroups.com> References: <11cgnhp3j4th442@corp.supernews.com> <1120628707.185004.227910@g49g2000cwa.googlegroups.com> Message-ID: <1120628830.477606.53210@g49g2000cwa.googlegroups.com> sorry lost the first line in pasting: Python 2.4.1 (#1, Jun 21 2005, 12:38:55) :/ From JustinStraube at notmymailbox.com Wed Jul 13 12:19:12 2005 From: JustinStraube at notmymailbox.com (Justin Straube) Date: Wed, 13 Jul 2005 11:19:12 -0500 Subject: tkFileDialog.askopenfilename filetypes problem Message-ID: Hopefully someone can catch what im missing here. Ive googled this and I think Ive got the filetypes arg written properly, but I get a traceback when calling this function. Heres the code followed by its traceback. def do_ask_fn_1(): z = askopenfilename(title=TITLE, initialdir=Dst_Dir, filetypes=(('AIFF Files','*.aiff'), ("AU Files", "*.au"), ("RAW Files", "*.raw"), ("SD Files", "*.sd"), ("SND Files", "*.snd"), ("WAV files", "*.wav") ) ) print z Exception in Tkinter callback Traceback (most recent call last): File "E:\PYTHON~1\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "P:\work\Python\PYZoid\PYZoid.pyw", line 213, in do_ask_fn_1 filetypes=[('AIFF Files','*.aiff'), TypeError: askopenfilename() takes exactly 0 non-keyword arguments (1 given) Can anyone point to what Ive done wrong? Thanks for any input. Justin From cam.ac.uk at mh391.invalid Thu Jul 21 17:32:10 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jul 2005 22:32:10 +0100 Subject: Difference between " and ' In-Reply-To: <42e00d17$1@news.eftel.com> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> Message-ID: John Machin wrote: > b83503104 at yahoo.com wrote: > >> Can someone tell me the difference between single quote and double >> quote? > > >>> ord("'") - ord('"') > 5 Very zen. -- Michael Hoffman From edvard+news at majakari.net Thu Jul 14 08:57:11 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Thu, 14 Jul 2005 15:57:11 +0300 Subject: How can I import a py script by its absolute path name? References: <87eka1eha8.fsf@titan.staselog.com> <6vdkv37j6bqs$.1q60iywumvljr$.dlg@40tude.net> Message-ID: <87ackpeeag.fsf@titan.staselog.com> Thorsten Kampe writes: > "sys.path.append('c:\\xxx\\yyy')" or "sys.path.append('c:/xxx/yyy')" Well, of course. As I said, it was untested :) I just copied the path string, and didn't remember Windows uses path names which need special treatment. One more reason to avoid inferior platforms :-> -- #!/usr/bin/perl -w $h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14, 72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26, 69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b} keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'', map{lc}($1,substr $2,4,1)),2,4)."\n"; print; From invalidemail at aerojockey.com Mon Jul 4 16:45:45 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Jul 2005 13:45:45 -0700 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey In-Reply-To: References: <1120259240.810197.60150@g44g2000cwa.googlegroups.com> <11ccpg5o833qp42@news.supernews.com> <1120384643.995676.226320@g43g2000cwa.googlegroups.com> <1120424454.854518.100610@o13g2000cwo.googlegroups.com> <1120469031.112811.112950@g44g2000cwa.googlegroups.com> Message-ID: <1120509945.444458.4010@z14g2000cwz.googlegroups.com> Christopher Subich wrote: > That said, Python itself is mostly a procedural language, with the > functional tools really being bolted on[1]. [etc., snip] Yeah, that's pretty much what I said in the first place. -- CARL BANKS From tubaranger at gmail.com Tue Jul 5 08:58:43 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: 5 Jul 2005 05:58:43 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <04adnZ8bocR6c1XfRVn-3A@speakeasy.net> Message-ID: <1120568322.948740.229830@g44g2000cwa.googlegroups.com> > That's what I love in that news group. Someone comes with a > stupid and arrogant question, and someone else answers in a > calm and reasonable way. Me, too. Indeed, that's a great reason to be a part of this community. I didn't see the original question as either stupid or arrogant; I read it as being from a frustrated user not knowing the regular expression package. We've all been there. While it would be nice if the question could be expressed without the explatives, it does no good at all to return the hostile tone. Another thing I like is that after the question was answered, other ways to approach the problem were offered along with reasons as to why the new way is a better approach. And no one had to get hurt! Perhaps Python is a victim of it's own design here. We, or at least I, have grown to expect things to be clear and easy to understand/use. Regular expressions are not either, though I use them all the time (I learned them when I was a system admin on a Sun network and tend to fall back on them when I need a "quick fix"). I hear that Perl 6 is going to have a rewrite of regular expressions; it will be interesting to see what their hard work produces. --greg From peter at engcorp.com Fri Jul 29 23:12:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 23:12:08 -0400 Subject: Path inherits from basestring again In-Reply-To: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> References: <1122682792.283774.145310@g43g2000cwa.googlegroups.com> Message-ID: NickC wrote: > I'm usually not much of a purist, but C++ has convinced me that > overloading an operator to mean something entirely unrelated to its > mathematical meaning can be very unwise. Me too. In general. I've yet to overload a single operator that way in years of writing Python code, though I definitely sinned with the rest of the C++ crowd (in the early days). In actual usage with path.py, however, I've found the use of "/" to be quite unsurprising and benign relative to what I had expected. That's why (to my surprise) I found myself using and appreciating it. -Peter From sbassi at gmail.com Wed Jul 20 15:30:59 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Wed, 20 Jul 2005 16:30:59 -0300 Subject: How to store "3D" data? (data structure question) In-Reply-To: <1121885516.735405.50910@g43g2000cwa.googlegroups.com> References: <1121881670.468880.297220@f14g2000cwb.googlegroups.com> <1121885516.735405.50910@g43g2000cwa.googlegroups.com> Message-ID: On 20 Jul 2005 11:51:56 -0700, Graham Fawcett wrote: > You get the idea: model the data in the way that makes it most useable > to you, and/or most efficient (if this is a large data set). I don't think this could be called a large dataset (about 40Kb all the file). It would be an overkill to convert it in MySQL (or any *SQL). I only need to parse it to reformat it. May I send the text file to your email and a sample of the needed output? It seems you understand a lot on this topic and you could do it very easily (I've been all day trying to solve it without success :( I know this is not an usual request, but this would help me a lot and I would learn with your code (I still trying to understand the zip built-in function, that seems useful). -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From uval at rz.uni-karlsruhe.de Wed Jul 6 06:50:39 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Wed, 06 Jul 2005 12:50:39 +0200 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: <1120232572.f87ea2456972eda76f9aa2eaf7b43b8c@teranews> <86irzu5sp9.fsf@bhuda.mired.org> Message-ID: Full Acknowledge From zooko at zooko.com Thu Jul 7 09:48:34 2005 From: zooko at zooko.com (zooko) Date: 7 Jul 2005 06:48:34 -0700 Subject: Determining actual elapsed (wall-clock) time References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: <1120744114.317478.101730@z14g2000cwz.googlegroups.com> The traditional use of gettimeofday() to (insecurely and unreliably) approximate elapsed local time is one of my pet peeves. Fortunately a real monotonic clock has finally been added to the linux kernel and glibc: http://www.imperialviolet.org/page24.html#e474 If you have a recent enough kernel and glibc you can use that. On Windows you can use system timers and handle wraparound yourself. And you can write an abstract Pythonic layer over both and give it to me. ;-) From roy at panix.com Fri Jul 1 15:20:17 2005 From: roy at panix.com (Roy Smith) Date: 1 Jul 2005 15:20:17 -0400 Subject: No subject References: Message-ID: Skip Montanaro wrote: > Adriaan> - strong type checking > >Python has strong type checking, it's just dynamic. Writing proper test >cases (which you should be doing anyway) will catch most issues. Not to mention that it's almost farcical for a language which supports reinterpret_cast<>() (let alone C-style casts) to claim to have strong type checking. Or for that matter, data hiding. "I promise to protect you from yourself, unless you ask me nicely to let you do whatever you want". > Adriaan> - more available libraries and more advanced developement tools. > >C++ has had a lot longer history of being a mainstream language and has had >the resources of quite a few major corporations behind it, so I would be >surprised if there weren't more libraries and advanced development tools >available. I suspect the complexity of C++ sort of demands more >sophisticated tools. Yes, and no. Both languages need good text editors and source control systems, but I suppose those aren't really language-specific (except in the weakest sense that there are language-aware text editors). But, let's look at the real language-specific tools my company uses with C++. We've got performance analysis tools that do run-time profiling (i.e. how much time is spent in each function). So does Python. For big projects, it's pretty near essential for either language. We've got code coveage tools. This is a testing tool. You keep running tests and it keeps track of which lines of code are executed (i.e. which logic branches are taken). One theory of testing says you should keep writing test cases until you've exercised every branch. I don't see any reason such a tool wouldn't be useful in a big Python project, but I'm not aware of any. We've got memory leak and corruption detection tools. This is one catagory of tool which is absolutely essential on a big C++ project and makes no sense at all for a Python project. We've got core dump analysis tools. These are really handy for telling us where we screwed up when we tried to use the memory corruption detection tools :-) Again, no parallel in the Python world. From cam.ac.uk at mh391.invalid Mon Jul 25 04:42:19 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 25 Jul 2005 09:42:19 +0100 Subject: [path-PEP] Path inherits from basestring again In-Reply-To: <3kjj0sFukvmcU1@individual.net> References: <3kehbmFtv6lpU1@individual.net> <3kjj0sFukvmcU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > * Add base() method for converting to str/unicode. +1 -- Michael Hoffman From lbates at syscononline.com Fri Jul 29 15:16:54 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 29 Jul 2005 14:16:54 -0500 Subject: Hiding In-Reply-To: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> References: <1122659823.104154.135640@g43g2000cwa.googlegroups.com> Message-ID: I can say with some certainty that opening a "music file" with open won't launch media player. If rather, you do os.system('musicfile.mp3') it will launch whatever application is associated with the file type .mp3. You can either automate Windows Media player or use pymedia to play such files. Here are some links that might be of interest: http://www.win32com.de/index.php?option=com_content&task=view&id=141&Itemid=259 http://pymedia.org/tut/ Larry Bates Jay wrote: > Well, im not no expert on the python programming language but i just > wanted to know if there was a quick way to hide certain things when > programming in python. Such as, i wanted some music or sound effects > with my python program. So, i type... > > print "Music is by blah blah" > music-file = open(file containing the music" > hide(music-file) > > thats wat im looking for, something i can hide the opening of files > because if i open that file, Windows Media Player will open and i would > like to hide that. And advise???? > From nyamatongwe+thunder at gmail.com Fri Jul 22 20:49:32 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 23 Jul 2005 00:49:32 GMT Subject: PEP on path module for standard library In-Reply-To: <42e1245c@nntp0.pdx.net> References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> <42e1245c@nntp0.pdx.net> Message-ID: Scott David Daniels: > Isn't it even worse than this? > On Win2K & XP, don't the file systems have something to do with the > encoding? So D: (a FAT drive) might naturally be str, while C: > (an NTFS drive) might naturally be unicode. This is generally safe as Windows is using unicode internally and provides full-fidelity access to the FAT drive using unicode strings. You can produce failures if you try to create files with names that can not be represented but you would see a similar failure with byte string access. > Even worse, would be a > path that switches in the middle (which it might do if we get to a > ZIP file or use the newer dir-in-file file systems. If you are promoting from byte strings with a known encoding to unicode path objects then this should always work. Neil From rrr at ronadam.com Sun Jul 17 14:51:04 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 17 Jul 2005 18:51:04 GMT Subject: Ordering Products In-Reply-To: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> References: <1121593934.046910.296220@g43g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Here might be an interesting puzzle for people who like sorting > algorithms ( and no I'm not a student anymore and the problem is not a > students 'homework' but a particular question associated with a > computer algebra system in Python I'm currently developing in my > sparetime ). >>>>x = 7*a*b*a*9 >>>>x.factors.sort() >>>>x > > a*a*b*7*9 > > -> (a**2)*b*63 > > Now lets drop the assumption that a and b commute. More general: let be > M a set of expressions and X a subset of M where each element of X > commutes with each element of M: how can a product with factors in M be > evaluated/simplified under the condition of additional information X? > > It would be interesting to examine some sorting algorithms on factor > lists with constrained item transpositions. Any suggestions? > > Regards, > Kay Looks interesting Kay. I think while the built in sort works as a convenience, you will need to write your own more specialized methods, both an ordering (parser-sort), and simplify method, and call them alternately until no further changes are made. (You might be able to combine them in the sort process as an optimization.) A constrained sort would be a combination of splitting (parsing) the list into sortable sub lists and sorting each sub list, possibly in a different manner, then reassembling it back. And doing that possibly recursively till no further improvements are made or can be made. On a more general note, I think a constrained sort algorithm is a good idea and may have more general uses as well. Something I was thinking of is a sort where instead of giving a function, you give it a sort key list. Then you can possibly sort anything in any arbitrary order depending on the key list. sort(alist, [0,1,2,3,4,5,6,7,8,9]) # Sort numbers forward sort(alist, [9,8,7,6,5,4,3,2,1,0]) # Reverse sort sort(alist, [1,3,5,7,9,0,2,4,6,8]) # Odd-Even sort sort(alist, [int,str,float]) # sort types These are just suggestions, I haven't worked out the details. It could probably be done currently with pythons built in sort by writing a custom compare function that takes a key list. How fine grained the key list is is also something that would need to be worked out. Could it handle words and whole numbers instead of letters and digits? How does one specify which? What about complex objects? Here's a "quick sort" function that you might be able to play with.. There are shorter versions of this, but this has a few optimizations added. Overall it's about 10 times slower than pythons built in sort for large lists, but that's better than expected considering it's written in python and not C. Cheers, Ron # Quick Sort def qsort(x): if len(x)<2: return x # Nothing to sort. # Is it already sorted? j = min = max = x[0] for i in x: # Get min and max while checking it. if imax: max=i if imid: gt.append(i) continue eq.append(i) # Recursively divide the lists then reassemble it # in order as the values are returned. return q(lt)+eq+q(gt) From spam.csubich+block at block.subich.spam.com Sat Jul 30 21:05:03 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 30 Jul 2005 21:05:03 -0400 Subject: A replacement for lambda In-Reply-To: <7xoe8lccqv.fsf@ruckus.brouhaha.com> References: <867jf9jmfw.fsf@bhuda.mired.org> <7xoe8lccqv.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Christopher Subich writes: > >>My personal favourite is to replace "lambda" entirely with an >>"expression comprehension", using < and > delimeters. > > > But how does that let you get more than one expression into the > anonymous function? It doesn't. Functionally, it's a direct replacement of lambda as-is. From skip at pobox.com Mon Jul 18 09:04:53 2005 From: skip at pobox.com (skip at pobox.com) Date: Mon, 18 Jul 2005 08:04:53 -0500 Subject: goto In-Reply-To: References: <261d32a705071804483ef68021@mail.gmail.com> Message-ID: <17115.43253.567942.405579@montanaro.dyndns.org> >>> what is the equivalent of C languages' goto statement in python? >> You really shouldn't use goto. >> Fortunately you can't. Steven> Of course you can :-) Steven> You can write your own Python interpreter, in Python, and add a Steven> goto to it. Maybe easier would be to write a Python assembler (there's probably already one out there) and just write to Python's virtual machine... Skip From danb_83 at yahoo.com Tue Jul 12 13:51:30 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Jul 2005 10:51:30 -0700 Subject: Inconsistency in hex() References: Message-ID: <1121190690.295164.160910@g47g2000cwa.googlegroups.com> Steven D'Aprano wrote: > hex() of an int appears to return lowercase hex digits, and hex() of a > long uppercase. > > >>> hex(75) > '0x4b' > >>> hex(75*256**4) > '0x4B00000000L' > > By accident or design? Apart from the aesthetic value that lowercase hex > digits are ugly, should we care? > > It would also be nice if that trailing L would disappear. Yes, but that can easily be worked around. >>> def hex(x): ... """Return the hexadecimal representation of an integer.""" ... return __builtins__.hex(x).upper().rstrip('L') ... >>> hex(75) '0X4B' >>> hex(75 * 256**4) '0X4B00000000' From ivanlan at pauahtun.org Fri Jul 1 10:06:10 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Fri, 01 Jul 2005 08:06:10 -0600 Subject: map/filter/reduce/lambda opinions and background unscientificmini-survey References: Message-ID: <42C54DD2.B33289C7@pauahtun.org> Hi All-- Tom Anderson wrote: > > Comrades, > > "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme > folks. :-)" > > I disagree strongly with Guido's proposals, and i am not an ex-Lisp, > -Scheme or -any-other-functional-language programmer; my only other real > language is Java. I wonder if i'm an outlier. > > So, if you're a pythonista who loves map and lambda, and disagrees with > Guido, what's your background? Functional or not? > I'm a pythonista who doesn't love them. In fact, even though I've done more than my fair share of lambda Tkinter programming using lambdas, I've never been happy with lambda. And I've spent months inside of Lisp/Emacs Lisp/Scheme, too (I have the world's second largest .emacs file [my friend Andy Glew has the largest], even though I can't use it on Windows;-). I find list comprehensions easier to understand than map, and small named functions or, better yet, class methods, *tons* easier to read/understand than lambda--there are too many restrictions you have to remember. Personally, I find that Lisp & its derivatives put your head in a very weird place. Even weirder than PostScript/Forth/RPN, when you come right down to it. I won't miss them, but since I don't use them now, that doesn't mean a whole lot. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From MailMonitor at GouldHarrison.local Fri Jul 15 12:05:28 2005 From: MailMonitor at GouldHarrison.local (MailMonitor at GouldHarrison.local) Date: Fri, 15 Jul 2005 17:05:28 +0100 Subject: MailMonitor for Exchange has processed a suspicious mail[Scanned] Message-ID: <018f01c58957$04ab6a70$0a0aa8c0@GouldHarrison.local> A mail sent by you has been identified as suspicious by MailMonitor for Exchange. Event: infection Action: Message quarantined Message ID: Message subject: Mail System Error - Returned Mail Recipient: "sales at gouldharrison.co.uk" ============================================================= Attachment information: Event: infection Action: Unable to disinfect Filename: letter.zip Virus: W32/MyDoom-O ============================================================= Attachment information: Event: infection Action: Unable to disinfect Filename: letter.zip Virus: W32/MyDoom-O ============================================================= From bdesth.quelquechose at free.quelquepart.fr Sat Jul 9 16:39:20 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 09 Jul 2005 22:39:20 +0200 Subject: Should I use "if" or "try" (as a matter of speed)? In-Reply-To: <1120935497.365395.168900@g47g2000cwa.googlegroups.com> References: <1120934674.774605.184080@g44g2000cwa.googlegroups.com> <1120935497.365395.168900@g47g2000cwa.googlegroups.com> Message-ID: <42d02f6f$0$6375$626a14ce@news.free.fr> wittempj at hotmail.com a ?crit : > My shot would be to test it like this on your platform like this: > > #!/usr/bin/env python > import datetime, time Why not use the timeit module instead ? > t1 = datetime.datetime.now() > for i in [str(x) for x in range(100)]: A bigger range (at least 10/100x more) would probably be better... > if int(i) == i: This will never be true, so next line... > i + 1 ...wont never be executed. > t2 = datetime.datetime.now() > print t2 - t1 > for i in [str(x) for x in range(100)]: > try: > int(i) +1 > except: > pass This will never raise, so the addition will always be executed (it never will be in the previous loop). > t3 = datetime.datetime.now() > print t3 - t2 BTW, you end up including the time spent printing t2 - t1 in the timing, and IO can be (very) costly. (snip meaningless results) The "test-before vs try-expect strategy" is almost a FAQ, and the usual answer is that it depends on the hit/misses ratio. If the (expected) ratio is high, try-except is better. If it's low, test-before is better. HTH From reinhold-birkenfeld-nospam at wolke7.net Fri Jul 22 17:55:07 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 22 Jul 2005 23:55:07 +0200 Subject: tuple to string? In-Reply-To: References: Message-ID: <3kd89rFte1h5U1@individual.net> Berthold H?llmann wrote: > Francois De Serres writes: > >> hiho, >> >> what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) >> to the string 'spam'? > > .>>> t = (0x73, 0x70, 0x61, 0x6D) > .>>> ''.join('%c' % c for c in t) > 'spam' Or: t = (0x73, 0x70, 0x61, 0x6D) ('%c' * len(t)) % t Reinhold From cam.ac.uk at mh391.invalid Sun Jul 3 09:52:16 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 03 Jul 2005 14:52:16 +0100 Subject: No sys.ps2 in IDLE (was Re: question) In-Reply-To: References: Message-ID: shisa wrote: > What should I do to correct the errors accordingly? What error? IDLE appears to be behaving as designed. Also, please don't top-post--it makes responding to your message in a way that others can understand more difficult. http://en.wikipedia.org/wiki/Top-posting -- Michael Hoffman From usenet at zabiello.com Mon Jul 18 07:24:52 2005 From: usenet at zabiello.com (JZ) Date: Mon, 18 Jul 2005 13:24:52 +0200 Subject: Django - Rails killer comes... References: <15cuhhg8i6mrg$.ekh1brvux44n$.dlg@40tude.net> Message-ID: <1q63g4p1gcpgj.h6zoua5kak8w.dlg@40tude.net> Dnia Mon, 18 Jul 2005 00:52:44 -0700, flab ba napisa?(a): > To me, this seems like it places itself in competition with Zope, not > Rails. No. Zope is an application server, much more powerfull and complicated, with its own object database and total object approach to all elements of the system. Django is similiar to Rails or Subway rather than to Zope. > If I'm wrong, could somebody explain why this is a "Rails Killer?" Maybe Django is not strictly Rails killer (because if someone prefers Ruby to Python, he choose Ruby - and vice-versa) But Django is good alternative to Rails for those who prefer Python. Both use similiar approach, both was created in the same time, both use ORM, MVC etc. -- JZ From Joost.Jacob at gmail.com Tue Jul 5 17:19:13 2005 From: Joost.Jacob at gmail.com (Joost Jacob) Date: 5 Jul 2005 14:19:13 -0700 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> Message-ID: <1120598352.962586.286480@f14g2000cwb.googlegroups.com> Very hard to say. LISP has OOP too, Google for CLOS. Operator overloading is something to avoid anyway, IMHO, just like static typing is something to avoid if you need fast development, on schedule and the like. LISP has one thing that Python does not have: LISP code is LISP data. A thorough study comparing LISP and Python in this respect would be welcome. From helge at aksdal.net Tue Jul 19 17:03:19 2005 From: helge at aksdal.net (Helge Aksdal) Date: Tue, 19 Jul 2005 23:03:19 +0200 Subject: socket programming In-Reply-To: References: <20050719204601.GB24773@mail.smule.com> Message-ID: <20050719210319.GA29578@mail.smule.com> * Terry Reedy [2005/07/19 22:57]: > Ask your server administrator if you are bumping up against a hidden > connection limit. Or if a query can ask about multiple accounts. how can i use a connection limit to my advantage? i know for certain that a query can't ask about multiple accounts. -- Helge Aksdal From fuzzyman at gmail.com Wed Jul 27 10:19:14 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Jul 2005 07:19:14 -0700 Subject: urllib2 problem/bug: Request.add_header does() nothing? In-Reply-To: <1122309307.181534.162940@g44g2000cwa.googlegroups.com> References: <1122309307.181534.162940@g44g2000cwa.googlegroups.com> Message-ID: <1122473954.770894.181730@g49g2000cwa.googlegroups.com> kelio at yandex.ru wrote: > I have a simple cgi-script on a server that prints all key-value pairs > from a request. And it really works when i use a browser and type smth > like http://server/cgi-bin/test?name=mike&johny=dummy. But when I use > the following script, nothing is printed (like i type > http://server/cgi-bin/test request in the browser). > > What is wrong about it? It's hard to believe there's a bug nobody's > noticed for such a long time (I've tried Python 2.1.3 and 2.4.1 on > Windows, and 2.2.2 on Linux). > > I've also tried to make a request using urllib (without 2) sending > pairs as data in a POST request - and it also worked. > > Thanks for help! > > elio. > > #!/usr/bin/python > > import urllib2 > > request = urllib2.Request(r"http://server/cgi-bin/test") > request.add_header("product", "SohoCore") > request.add_header("version", "1.1") > request.add_header("build", "1251") > > reply = urllib2.urlopen(request).readlines() > > for i in reply: > print i The add_header method adds http headers to your http request - it *doesn't* post any data to your CGI. What you need to do is encode a dictionary of your parameters using ``urllib.urlencode`` (*not* urllib2) - then pass it as the second parameter to urllib2.urlopen. HTH Best Regards, Fuzzy http://www.voidspace.org.uk/python From rrr at ronadam.com Fri Jul 1 23:23:01 2005 From: rrr at ronadam.com (Ron Adam) Date: Sat, 02 Jul 2005 03:23:01 GMT Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: References: Message-ID: Terry Hancock wrote: > On Friday 01 July 2005 03:36 pm, Ron Adam wrote: > >>I find map too limiting, so won't miss it. I'm +0 on removing lambda >>only because I'm unsure that there's always a better alternative. > > > Seems like some new idioms would have to be coined, like: > > def my_function(a1, a2): > def _(a,b): return a+b > call_a_lib_w_callback(callback=_) > > doesn't seem too bad, and defeats the "wasting time thinking of names" > argument. Usually the time is regained later when you need to go back and figure out what it is that the lambda is doing. Not so easy for beginners. A hard to understand process that is easy to do, is not easier than an easy to understand process that is a bit harder to do. >>So what would be a good example of a lambda that couldn't be replaced? > > I suspect the hardest would be building a list of functions. Something > like: > > powers = [lambda a, i=i: a**i for i in range(10)] > > which you might be able to make like this: > > powers = [] > for i in range(10): > def _(a,i=i): return a**i > powers.append(_) > > which works and is understandable, but a bit less concise. This would be a more direct translation I think: def put_func(i): def power_of_i(a): return a**i return power_of_i power = [put_func(i) for i in range(10)] I think it's also clearer what it does. I had to type the lambda version into the shell to be sure I understood it. I think that's what we want to avoid. > The main obstacle to the lambda style here is that def statements > are not expressions. I think that's been proposed as an alternative, > too -- make def return a value so you could say: > > powers = [def _(a,i=i): return a**i for i in range(10)] Wouldn't it be: powers = [(def _(a): return a**i) for i in range(10)] The parens around the def make it clearer I think. That would be pretty much just renaming lambda and changing a syntax a tad. I get the feeling that the continual desire to change the syntax of lambda is one of the reasons for getting rid of it. I'm not sure any of the suggestions will fix that. Although I prefer this version over the current lambda. Instead of reusing 'def', resurrecting 'let' as a keyword might be an option. powers = [ (let a return a**i) for i in range(10) ] I just now thought this up, but I like it a lot as an alternative syntax to lambda. :-) > Personally, I think this is understandable, and given that lambda > is to be pulled, a nice substitute (I would say it is easier to read > than the current lambda syntax, and easier for a newbie to > understand). > > But it would probably encourage some bad habits, such as: > > myfunc = def _(a,b): > print a,b > return a+b > > which looks too much like Javascript, to me, where there are > about three different common idioms for defining a > function (IIRC). :-/ I don't think it would be used that way... Very often anyway. Still none of these examples make for good use cases for keeping lambda. And I think that's whats needed first, then the new syntax can be decided. Ron From devlai at gmail.com Tue Jul 12 10:39:04 2005 From: devlai at gmail.com (Devan L) Date: 12 Jul 2005 07:39:04 -0700 Subject: question on "input" In-Reply-To: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> References: <1121178707.925906.263940@o13g2000cwo.googlegroups.com> Message-ID: <1121179143.995844.28690@g47g2000cwa.googlegroups.com> Use raw_input instead. It returns a string of whatever was typed. Input expects a valid python expression. From peter at engcorp.com Tue Jul 19 07:42:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 19 Jul 2005 07:42:17 -0400 Subject: Documentation bug: Python console behaviour changed In-Reply-To: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> References: <1121767258.282215.80440@o13g2000cwo.googlegroups.com> Message-ID: <-I2dnSVstZw-ekHfRVn-rA@powergate.ca> Kay Schluehr wrote: > The documentation of the Python console behaviour is not correct > anymore for Python 2.4.1. At least for the Win2K system I'm working on > 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc. > > The Python interpreter tells me instead: > > >>>>quit > > 'Use Ctrl-Z plus Return to exit.' > > Nah, 'Ctrl-Z' is now undo :-) Are you really using the console, started with the "Command Prompt" icon from the Start Menu (or some equivalent)? And are you sure you haven't installed something else that magically changed the behaviour of Ctrl-Z? (I get the documented behaviour with Python 2.4.1, under Win XP.) -Peter From philippe at philippecmartin.com Tue Jul 5 19:28:12 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 05 Jul 2005 23:28:12 GMT Subject: adding a character to the last string element of a list Message-ID: Hi, I have the following question: l = ['ABCDE','FGHI'] l[1:] #returns ['FGHI'] l[1:][0] #return 'FGHI' a = l[1:][0] + 'J' #a becomes 'FGHIJ' l[1:][0] += 'J' #NO ERROR BUT l[1:][0] == 'FGHI' What am I missing ? Thanks, Philippe From peter at engcorp.com Mon Jul 25 11:27:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Jul 2005 11:27:21 -0400 Subject: PyGTK or wxPython (not a flame war) on Windows In-Reply-To: <878xzwarjy.fsf@wilson.rwth-aachen.de> References: <1122018122.372760.190700@g49g2000cwa.googlegroups.com> <1122209850.126276.266650@g43g2000cwa.googlegroups.com> <87ek9occzx.fsf@wilson.rwth-aachen.de> <19xkftnwsq3is.1drp7cywmf8qf.dlg@40tude.net> <878xzwarjy.fsf@wilson.rwth-aachen.de> Message-ID: <74SdndupGet-mXjfRVn-1w@powergate.ca> Torsten Bronger wrote: > Marek Kubica writes: >>I have started GUIs in Python with wx, but after a short time I >>was annoyed how many things were buggy. I don't know why, but I >>fell from one bug to the other while programming one application. > > I'm very suprised. wxPython is still that buggy? Not really. One can go many months, or years, without encountering a bug in a wxPython program which is not actually a bug in one's own code. Use of "unstable" (i.e. new and/or rapidly changing) parts of the framework are a different story. As with most Open Source projects, such code is in flux and one uses it at one's own risk (reporting, I hope, bugs that are encountered so that they can be fixed). -Peter From elmo13 at jippii.fi Fri Jul 8 15:43:55 2005 From: elmo13 at jippii.fi (=?ISO-8859-1?Q?Elmo_M=E4ntynen?=) Date: Fri, 08 Jul 2005 22:43:55 +0300 Subject: Having trouble importing against PP2E files In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Charles Krug wrote: > List: > > I'm trying to use the example files from Programming Python, 2nd Ed. > > I've copied them into c:\Python24\Examples\PP2E. > > Launching any of the examples programs by themselves seems to work > spiffily. > > Using regedit, I appended "c:\Python24\Examples\PP2E" to Pythonpath > > from the immediate window, executing the line: > > from PP2E.launchmodes import PortableLauncher > > Raises the exception: > > Import Error: no module named PP2E.launchmodes > > However if I copy launchmodes.py into my work directory, it imports > successfully. > > Both "Examples" above and "Examples\PP2E" contain the __init__.py file. Are both Examples and PP2E packages? In python if a folder is meant to represent a package it should iclude the above mentioned file __init__.py and by saying the above your suggesting that PP2E is a package inside the package Examples. > > Obviously, I'm missing a setup step here. > > What magic do I need to perform to get Python to find modules in the > Examples heirarchy? > > Is there any way to check from the immediate window where Python will > search for modules? Pythonpath appears to be correct, but the file > isn't importing unless I copy it to the current directory. > > Thanx > > > Charles > If the above is correct, you should append the pythonpath with c:\Python24\ and refer to the wanted .py with Examples.PP2E.launchmodes. As such the import statement obviously should be "from Examples.PP2E.launchmodes import PortableLauncher". If the above isn't the case and there is still something unclear about this, reply with a more detailed post about the situation. Elmo -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFCztd7ctNFyQJObrsRAuXNAJwLF94iM0IwkJVHLUOo1EEBYQg6FACfQFfE jcxspYU80N5MSZB9uqhbBh4= =YquD -----END PGP SIGNATURE----- From wpeterson1 at socal.rr.com Fri Jul 15 17:45:54 2005 From: wpeterson1 at socal.rr.com (Bill) Date: 15 Jul 2005 14:45:54 -0700 Subject: IDLE in Jython References: <1121436094.769121.247470@z14g2000cwz.googlegroups.com> Message-ID: <1121463954.137363.272320@g47g2000cwa.googlegroups.com> You might get better answers if you contact the Jython developers themselves and look at their wiki - http://www.jython.org/cgi-bin/wiki/FrontPage. Even though you found the posting on a Python wiki, you really want to consult the Jython community, and I'm not sure to what extent they participate in this newsgroup. Just by reading the description of the task and your post I'd say the project is certainly doable, but not trivial. Since IDLE is a Python application the path of least resistance would be to port it to Jython. The majority of work would probably be in replacing the Tk GUI with a Java-based GUI. You say that your people have experience with Swing so you have a leg up on that part. Since Jython currently does not support all of the latest Python, you likely will have to work around some features incorporated in the latest IDLE. As you say that your team has limited experience with Python, this might be the most challenging part. I'd ask here just how much experience your team has had with maintenance programming. Modifying someone elses code is a different task than writing new code from specifications, and some programmers dislike this kind of work. I mention this because I think that designing and building an IDE from scratch IS more than you want to tackle. You might want to look at some of the other IDEs that support Python. One of the things you'll want to do is reverse engineer IDLE. If you are currently using Eclipse for Java development, there are a couple of plugins for Python which should support Jython to some extent. Bill From simon.brunning at gmail.com Thu Jul 28 09:48:27 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 28 Jul 2005 14:48:27 +0100 Subject: easy float question just eludes me In-Reply-To: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> References: <1122557972.833617.157360@o13g2000cwo.googlegroups.com> Message-ID: <8c7f10c60507280648244420cf@mail.gmail.com> On 28 Jul 2005 06:39:32 -0700, nephish at xit.net wrote: > i have a real easy one here that isn't in my book. > i have a int number that i want to divide by 100 and display to two > decimal places. > > like this float(int(Var)/100) > but i need it to display the .00 even if it does not have a .00 value > like this > if Var is 50, i need to display .50 instead of just .5 >>> import decimal as dec >>> dec.Decimal('250.00')/100 Decimal("2.50") -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From godoy at ieee.org Sun Jul 31 08:01:56 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 31 Jul 2005 09:01:56 -0300 Subject: Wheel-reinvention with Python References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: [ Having GUI stuff included on a standard installation of Python ] > However, you can get compilers for both that come bundled with a good > GUI library. Could it be that that's what you really want - someone to > distribute Python bundled with an enterprise-class GUI library and > IDE? And then you are going to have three or four different distributors of Python using three or four different GUI toolkits and also python.org distributing Python for free without any (or with TKinter)... Which one will be the "standard" distributor so that it gets documented and adopted? In an international project I see othe problems as well -- cost, logistics, S&H, customs, etc. -- Jorge Godoy From skip at pobox.com Fri Jul 15 07:14:53 2005 From: skip at pobox.com (skip at pobox.com) Date: Fri, 15 Jul 2005 06:14:53 -0500 Subject: Python Programming Contest In-Reply-To: <42D780EF.6020809@sweetapp.com> References: <42D780EF.6020809@sweetapp.com> Message-ID: <17111.39597.277505.234455@montanaro.dyndns.org> Brian> I've decided that it would be be fun to host a weekly Python Brian> programming contest. The focus will be on algorithms that require Brian> a bit of thought to design but not much code to implement. For some of us that's what we do day-in, day-out at work. It's just not called a contest. To make it more challenging, we sometimes leave out the "bit of thought" part. ;-) Skip From peter at engcorp.com Mon Jul 18 08:59:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Jul 2005 08:59:09 -0400 Subject: Problem with threads In-Reply-To: References: Message-ID: <_MOdndKAg8zmOkbfRVn-pw@powergate.ca> Stephan Popp wrote: > I've got a problem with stopping python-threads. > I'm starting a thread with twisteds reactor.deferToThread which start a > methodcall in a seperate thread. In this thread a swig-wrapped c++ module is > running. > Now I want to stop the running thread from the main thread or another one, and > have no idea how to do it. If this external call into the C++ module is "long running", and doesn't itself provide a way to terminate before it's done, you can't do what you want unless you use a separate process entirely. -Peter From grig.gheorghiu at gmail.com Fri Jul 15 17:18:58 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 15 Jul 2005 14:18:58 -0700 Subject: Native ODBC access for python on linux? In-Reply-To: <1121459248.688862.96130@f14g2000cwb.googlegroups.com> References: <1121364222.540501.198600@g14g2000cwa.googlegroups.com> <8NCdnRaSkdR-XkvfRVn-jg@telcove.net> <86r7e0al3p.fsf@bhuda.mired.org> <1121446822.710877.312020@g44g2000cwa.googlegroups.com> <_ICdne5Z-td7lUXfRVn-2A@telcove.net> <1121459248.688862.96130@f14g2000cwb.googlegroups.com> Message-ID: <1121462338.662282.189010@f14g2000cwb.googlegroups.com> That's exactly the way to go. In my case, I'm using cx_Oracle to connect from Python to Oracle and the same exact code runs on Windows, Linux, Solaris and soon on AIX. Grig From peter at engcorp.com Sat Jul 2 16:53:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Jul 2005 16:53:52 -0400 Subject: Determining actual elapsed (wall-clock) time In-Reply-To: References: <3ZGdnfw6ZLlvaVvfRVn-jA@powergate.ca> Message-ID: Roy Smith wrote: > Peter Hansen wrote: > If you get the UTC time, daylight savings time doesn't enter the equation. Of course... I didn't think of that approach. I don't actually care about absolute time, so this should work fine for at least the DST case. > If you care about time, you want your system clock controlled by NTP. > There's just no excuse not to. I guess as long as the NTP client is set up to ensure the time adjustments are smaller than some value X, it would be acceptable. I'll have to look into how to set up Windows XP to prevent users from changing the time on their own, assuming that's possible. > Is there some reason you can't just use the system clock? I was anticipating use of the system (running on Windows in this case) by users who might decide to change the time, and in certain cases that could cripple the software. I hadn't thought of the possibility of simply preventing that, though if I insist on an NTP client being installed, they shouldn't have a problem with that. Thanks for correcting my thought process... -Peter From 00515879256 at fastwebnet.it Fri Jul 8 11:31:51 2005 From: 00515879256 at fastwebnet.it (Glauco) Date: Fri, 08 Jul 2005 17:31:51 +0200 Subject: psycopg simplest problem In-Reply-To: References: <1110592231.853484.197370@z14g2000cwz.googlegroups.com> Message-ID: Gerhard Haering wrote: > On Fri, Jul 08, 2005 at 04:23:50PM +0200, Glauco wrote: > >>[...] >>My problem is to do a middle layer over pycopg for eliminate type >>casting problem in postgres in all direction. >> >>i've resolved this doing a C extension in python and manipulating only >>string and int in my application. >> >>this is my example: >>import sqlvar >> >>sql = """insert into mytable (myint, mytext, maydate) >> values >> (%d,%s,%s);""" % (sqlvar.number(myvalue1), >>sqlvar.text(myvalue2), sqlvar.date(myvalue3) ) >> >>all problem concerning quoting, " ' -> ''", null, None, 0, empty string >>is solved by the sqlvar lib. [...] > > > Instead of quoting Python values yourself appropriately for each type, > just let the DB-API module do its work. Use parametrized queries and > then supply the arguments to the query: > > cur = con.cursor() > intVal = 42 > textVal = "Jason's house" > dateVal = datetime.date(2005, 7, 8) > cur.execute(""" > insert into mytable(myint, mytext, mydate) > values (%s, %s, %s) > """, (intval, textVal, dateVal)) > > The execute(many) method has an optional second parameter, which is a > tuple of values for your parametrized query. > > There are different styles to parametrize queries among the various > DB-API modules. psycopg uses the pyformat one, where you just use %s as > placeholders. > > It will happily quote all Python values of types int, str, date, float, > etc. for you. It's also possible to teach it how to quote other custom > data types, but you'll normally not need this. > > HTH, > > -- Gerhard Gerhard thank you very much, this example explain me some idea, but anyway don't resolve the core question. In you example when dateVal is a None or textVal is none. argument x must be DateTime, not None. so i must manipulate for the empty string or None cases Glauco -- From future_retro at yahoo.co.uk Fri Jul 1 07:34:49 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 1 Jul 2005 04:34:49 -0700 Subject: accessing individual element in a list. Message-ID: <1120217689.339747.91140@g44g2000cwa.googlegroups.com> hi all,could someone clear this up for me. I'm sure it's probably very simple but I can't seem to get my head round it..... doing the following >>> import wmi >>> c = wmi.WMI() >>> for printdriver in c.Win32_PrinterDriver(): ... pd = printdriver.Name >>> print pd AGFA-AccuSet v52.3,3,Windows NT x86 >>> pd[1] u'G' >>> pd.split(',') [u'AGFA-AccuSet v52.3', u'3', u'Windows NT x86'] >>> pd[0] u'A' why does pd[1] or pd[0] not return an element from the list instead of a character from the string? Is split the best method to try and seperate the individual elements? Thanks, MW. From rootrot at govtabuse.com Sat Jul 30 01:05:19 2005 From: rootrot at govtabuse.com (James Richards) Date: Sat, 30 Jul 2005 05:05:19 GMT Subject: Aiksaurus interface? Message-ID: Major big apologies if this has been covered to death before. It's been a few years since I played with these two technologies. I seem to recall a python wrapper over aiksaurus. I can't find it now. (Or maybe it's just my own stupidity. That's been known to happen :-/). Is there a project/wrapper dedicated to this? I didn't find anything obvious on google or sourceforge, but that doesn't mean much. I probably spelled all my search queries wrong, and stuff like that. Then again, I didn't see anything in PyPI. Aiksaurus has evolved quite a bit in the last few years, and I haven't been following. Is there a Python wrapper? Would anyone be interested in a Python wrapper if there's not one now? Regards, James -- Liberty means responsibility. That is why most men dread it. - George Bernard Shaw From hancock at anansispaceworks.com Sat Jul 2 18:05:55 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 2 Jul 2005 17:05:55 -0500 Subject: What are the other options against Zope? In-Reply-To: <42C6B8E7.2040202@anvilcom.com> References: <1120296702.325235.243100@g49g2000cwa.googlegroups.com> <-uOdneqY58so4VvfRVn-sA@powergate.ca> <42C6B8E7.2040202@anvilcom.com> Message-ID: <200507021705.55644.hancock@anansispaceworks.com> On Saturday 02 July 2005 10:55 am, phil wrote: > Zope is like that to me. I ask what is it and the answer > sounds like "Oh, it's oierbv for the zxcvioupo of 7cvn^djh'. > > Now understand, I know what very well what Python, Apache, PhP, > MySQL, IE and javascript do. I just don't know what Zope > does. You know, that's a good question. Let's see if I can make a good answer: Zope is the "Z Object Publishing Environment". It publishes a *tree* of *objects* stored in the ZODB which is an object oriented database. Think of it as a monstrous pickle implementation. Zope folders are a lot like user-defined classes in your application. They contain things, which is why they're called "folders". But basically, from a programming perspective, what they contain are their "attributes" in the class/object jargon (in reality it can be more complicated, some containers use Python container types like dictionary or list as their internal structure). Of course, "publishes" means "publishes to the web". Z: So Zope includes an *object store*, a *publisher*, and a *web server*. When the web server receives a request, it asks the publisher to get it, which digs it out of the object store. Then it goes back the other way, back to the requester via the web. Usually, you run the Zope webserver behind another proxy like Apache, but it is possible to serve a site directly from Zope. I never do that for production, because, Apache, being much more completely tested is a safer bet for not crashing or misbehaving under heavy loads. However, the built-in Zope webserver (I believe it was once called Medusa) is quite convenient for development and testing. OBJECT: Because Zope publishes Python *objects* instead of *files*, they can have much richer structure (e.g. metadata) than a site based on files stored in a filesystem. However, a set of files stored in a filesystem is very much like an object database, so 1) The ZODB is sometimes called the Zope Object FileSystem, which I find a useful idea --- especially since ZOFS has some extra constraints beyond what ZODB requires. 2) You actually can store contents of the ZODB *as* a filesystem with associated metadata in auxiliary files. I believe this is how the "filesystem storage" option for ZODB works (by default, ZODB lumps all its data into one big container file "Data.fs" -- this is the "filestorage" option). PUBLISHING: Zope has also been called a "web application server", because it's relatively easy to write highly-integrated, highly-dynamic sites with it (and overkill to use it for purely static sites). Objects are defined in such a way that they can be represented as web pages. The publisher has a lot of default behaviors for built-in types and the objects that come with Zope. Zope "product" developers have the responsibility (and control) over how their objects will appear when published. ENVIRONMENT: If you want to think of it as a "web application server", then basically, Zope is your "operating system", and your site is your "web application software". Zope also provides some specialized programming language help --- Python scripts that can be edited through the web, and two "Templating Languages" for designing web pages that will have dynamic content. You can think of the templating languages as being similar to PHP or ASP style programming. But "Zope Zen" says that the serious code should be either in Python scripts or in Python products (on the filesystem, instead of in the ZODB, like scripts). Templates are meant to be simple, simple, simple. But that's a style issue. This stuff provides the Zope "operating system" with a "shell". And the "Zope Management Interface", which is what you see when you visit the /manage page at a Zope site, is the "window system" or, perhaps more accurately, the "file browser" of that "operating system". So, in fact, Zope does quite a bit. But it isn't really all that hard to understand. It's just not been well-introduced, because the people explaining it have a tendency to forget that it isn't all obvious, because it seems that way to them, now that they know it. But that's the newbie's problem in all areas of software, ISTM. HTH, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From horedson at earthlink.net Thu Jul 28 00:35:51 2005 From: horedson at earthlink.net (Hank Oredson) Date: Thu, 28 Jul 2005 04:35:51 GMT Subject: Earthquake Forecasting Program July 11, 2005 References: <7%UAe.4148$BK1.174@newsread3.news.pas.earthlink.net> <1vYAe.2575$dU3.2553@newsread2.news.pas.earthlink.net> <2OeBe.2928$oZ.770@newsread2.news.atl.earthlink.net> <6DhBe.3077$dU3.691@newsread2.news.pas.earthlink.net> <7qage1h9vve4ba0ub0ka3fuo4nph7j3qv0@4ax.com> Message-ID: "Lemming" wrote in message news:7qage1h9vve4ba0ub0ka3fuo4nph7j3qv0 at 4ax.com... > On Wed, 13 Jul 2005 23:39:46 GMT, "Hank Oredson" > wrote: > >>In particular I am interested in the EM dataset. > > Hank, with respect ... > > Posted to nine newsgroups; fluffy responses when you ask specific > questions; evasion when you repeatedly ask for real data ... I regret > to say, YHBT. > > Lemming > -- > Curiosity *may* have killed Schrodinger's cat. Why yes, your post was much more informative and interesting. Do you have the EM dataset? -- ... Hank http://home.earthlink.net/~horedson http://home.earthlink.net/~w0rli From twic at urchin.earth.li Sun Jul 3 15:13:22 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 3 Jul 2005 20:13:22 +0100 Subject: math.nroot [was Re: A brief question.] In-Reply-To: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> References: <1120403462.567163.291420@o13g2000cwo.googlegroups.com> Message-ID: On Sun, 3 Jul 2005, George Sakkis wrote: > "Tom Anderson" wrote: > >>>> And finally, does Guido know something about arithmetic that i don't, or >>>> is this expression: >>>> >>>> -1.0 ** 0.5 >>>> >>>> Evaluated wrongly? >>> >>> No, it is evaluated according to the rules of precedence. It is >>> equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which >>> fails as expected. >> >> Ah. My mistake. I submit that this is also a bug in python's grammar. >> There's probably some terribly good reason for it, though. > > How about 'conformance with standard mathematic notation', does this > count for a terribly good reason? Yes. However, it's an excellent reason why python's precedence rules are wrong - in conventional mathematical notation, the unary minus, used to denote the sign of a literal number, does indeed have higher precedence than exponentiation: -1^2 evaluates to 1, not -1. > What would one expect to be the result of 5^2 - 2^2, 29 or 21? 21. > Would you expect 5^2 + - 2^2 to be different, even if you write it as > 5^2 + -2 ^ 2 ? Yes: 5^2 + -2^2 is 29, however you write it. > White space is not significant in math AFAIK ;-) No, but there's a very big difference between unary and binary minus. tom -- When you mentioned INSERT-MIND-INPUT ... did they look at you like this? From dalke at dalkescientific.com Fri Jul 22 13:41:47 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 22 Jul 2005 17:41:47 GMT Subject: Iterators from urllib2 References: Message-ID: Joshua Ginsberg wrote: > >>> dir(ifs) > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > 'fileno', 'fp', 'geturl', 'headers', 'info', 'next', 'read', > 'readline', 'readlines', 'url'] > > Yep. But what about in my code? I modify my code to print dir(ifs) > before creating the DictReader... > > ['__doc__', '__init__', '__module__', '__repr__', 'close', 'fp', > 'geturl', 'headers', 'info', 'read', 'readline', 'url'] ... > Whoa! Where did the __iter__, readlines, and next attributes > go? Ideas? That difference comes from this code in urllib.py:addbase class addbase: """Base class for addinfo and addclosehook.""" def __init__(self, fp): self.fp = fp self.read = self.fp.read self.readline = self.fp.readline if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno if hasattr(self.fp, "__iter__"): self.__iter__ = self.fp.__iter__ if hasattr(self.fp, "next"): self.next = self.fp.next It looks like the fp for your latter code doesn't have the additional properties. Try adding the following debug code to figure out what's up print dir(ifs) print "fp=", ifs.fp print "dir(fp)", dir(ifs.fp) Odds are you'll get different results. Andrew dalke at dalkescientific.com From pedro.werneck at terra.com.br Wed Jul 27 15:35:22 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Wed, 27 Jul 2005 16:35:22 -0300 Subject: Supporting << and >> operators in C extension type Message-ID: <20050727163522.220b01b2.pedro.werneck@terra.com.br> Hi list I'm trying to implement a new type in a C extension and it must support some binary operators, like &, |, ^, << and >>. With &, | and ^, the method must receive another object of the same type, perform the operation with an attribute of both, create a new object with the result as the attribute and return it. Everything works perfectly with &, | and ^, but with << and >> I need to, pass an integer as argument, not an object of the same type. The method should receive an integer, perform the shift with the attribute, create the new object and return it. The problem is that it only works with another object of the same type. It's strange because obj.__lshift__ returns the method; when I call obj.__lshift__(a) or obj << a, when a is an object of the same type, the call suceeds (but the object returned has the wrong value, of course), but with obj.__lshift__(i) where i is an integer, the call returns NotImplemented and with obj << i it raises TypeError: unsupported operand types for <<. I searched the Objects/ directory in the interpreter source code, but could not find any solution for this. Seems like it does some kind of type-checking somewhere when using these binary operators. Do I need to implement the __coerce__ method or use some wrapper with the method function ? Here is the relevant piece of my source code: The __lshift__ method: /* Pin.__lshift__() */ static PyObject * Pin_oplshift(PinObject *self, PyObject *args){ PinObject *result; int shift; if (!PyArg_ParseTuple(args, "i", &shift)) return NULL; result = PyObject_NEW(PinObject, &PinType); result->pin = self->pin << shift; Py_INCREF(result); return (PyObject *) result; }; The part of the PyNumberMethods struct: /* Pin number methods */ static PyNumberMethods PinAsNumber[] = { ... (inquiry)Pin_nonzero, /*nb_nonzero*/ 0, /*nb_invert*/ (binaryfunc)Pin_oplshift, /*nb_lshift*/ (binaryfunc)Pin_oprshift, /*nb_rshift*/ (binaryfunc)Pin_and, /*nb_and*/ (binaryfunc)Pin_xor, /*nb_xor*/ (binaryfunc)Pin_or, /*nb_or*/ 0, /*nb_coerce*/ ... }; Thanks for any help... -- Pedro Werneck From newsgroups at jhrothjr.com Fri Jul 22 12:48:07 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 22 Jul 2005 10:48:07 -0600 Subject: PEP on path module for standard library References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> <11e0cpe7vqrm18a@news.supernews.com> <1121992173.719316df1430a706987a33a518e6ea2d@teranews> Message-ID: <11e28qai2vbnc24@news.supernews.com> "Duncan Booth" wrote in message news:Xns969BA37FF9CE5duncanbooth at 127.0.0.1... > > John Roth wrote: >> You have to start somewhere. One of the lessons that's beginning >> to seep into people's minds is that getting something that works >> out there is almost always preferable to (over) design by committee. > > Dead right, but once it goes into the standard library it has to pretty > well stop evolving, so it needs to be right, or as close as possible > before > that happens. It has to stop evolving in incompatible directions, at least. Although there is a precident with the process functions, classes, module, whatever it is. It's up to five versions now, isn't it? AFAICT, from a very broad brush perspective, there is really only one substantive issue: how to handle multiple path-like "things". URLs have been mentioned in this thread, different file systems and a possible in-memory file system have been mentioned in other threads. So whatever gets out there first shouldn't preempt the ability to eventually fit into a wider structure without substantial and incompatible modifications. John Roth > From red at redplanet.com Wed Jul 20 18:45:12 2005 From: red at redplanet.com (red) Date: Thu, 21 Jul 2005 00:45:12 +0200 Subject: Copying attributes Message-ID: Hi, I'm writing a script for Blender and need to build a face array. My engine needs that all faces must be triangles, so I convert quads to triangles by dividing them into two triangles. Here is the function: def build_face_table(mesh): face_table = {} i = 0 for f in mesh.faces: if len(f.v) == 3: # triangle face_table[i] = f i += 1 elif len(f.v) == 4: # quad f1 = NMesh.Face() f2 = NMesh.Face() f1.mat = f.mat ## f1.normal = copy.deepcopy(f.normal) f1.normal = NMesh.Vert(f.normal[0], f.normal[1], f.normal[2]) f1.v.append(f.v[0]) f1.v.append(f.v[1]) f1.v.append(f.v[2]) f2.mat = f.mat f2.v.append(f.v[2]) f2.v.append(f.v[3]) f2.v.append(f.v[0]) face_table[i] = f1 i += 1 face_table[i] = f2 i += 1 else: message = "Can't build face from 2 vertices." Draw.PupMenu("Face Table Error%t|"+message) return return face_table Everything seems be ok, but i'm getting: Traceback (most recent call last): File "", line 169, in write File "", line 102, in build_face_table AttributeError: normal I was wondering why? Though the face has an attribute called "normal"! Just simply test: nv = f.normal and it works! But why my new faces (f1 and f2) no? Greetings. -- _red ____ _ ____ ____ __ _ From macaronikazoo at gmail.com Sat Jul 16 21:28:33 2005 From: macaronikazoo at gmail.com (macaronikazoo) Date: 16 Jul 2005 18:28:33 -0700 Subject: secure uploading In-Reply-To: <7x4qauaccl.fsf@ruckus.brouhaha.com> References: <1121516546.621653.314040@o13g2000cwo.googlegroups.com> <7x4qauaccl.fsf@ruckus.brouhaha.com> Message-ID: <1121563713.124461.230540@g47g2000cwa.googlegroups.com> well I want a script to upload something automatically, so i need a python script to do that for me. my hoster has ssl enabled on their server and I have generated a key. but now I need to know how to upload something using ssl to the server. how to I ftp something to the server using ssl? thanks. From T.A.Meyer at massey.ac.nz Wed Jul 13 20:54:05 2005 From: T.A.Meyer at massey.ac.nz (Meyer, Tony) Date: Thu, 14 Jul 2005 12:54:05 +1200 Subject: Are there any decent python memory profilers available? Message-ID: > Are there any decent python memory profilers available? As part of Google's "summer of code", Nick Smallbone (mentored by Michael Hudson and Jeremy Hylton) will be developing a Python memory profiler. I think the fact that this was a project suggestion by the PSF, and that it was accepted, is reasonable evidence that there isn't an existing profiler (or if there is, there isn't one that is sufficient for most purposes). The good news is that at the end of 'summer' (winter, here ;) there may well be a (free) profiler that you can use. The bad news is that this probably isn't the case now. =Tony.Meyer From ddurkee at gmail.com Fri Jul 22 11:56:22 2005 From: ddurkee at gmail.com (David Durkee) Date: Fri, 22 Jul 2005 10:56:22 -0500 Subject: Setting environment variables for tcsh session In-Reply-To: References: Message-ID: <4749A8D3-E70C-46C5-BBAB-F2A6F6F64CF8@gmail.com> I didn't get much from the discussion of Command Substitution. Any tips on how to do that? David On Jul 21, 2005, at 10:12 PM, Dan Sommers wrote: > On Thu, 21 Jul 2005 21:39:01 -0500, > David Durkee wrote: > > > > >> I'm trying to write a script I can run from tcsh in Terminal (on Mac >> OS X) that will set environment variables that can be accessed by >> subsequent commands I execute in that session. Not having any luck so >> far. Here's what I've tried: >> >> > > By design, you can't do that (think of the problems if arbitrary > programs could change your interactive shell's environment behind your > back). > > Processes (your script) cannot change the environment of their parents > (your shell). The best you can do is have your script output the > right > commands and have your shell read them. See "Command Substitution" in > the tcsh man page. > > Regards, > Dan > > -- > Dan Sommers > > -- > http://mail.python.org/mailman/listinfo/python-list > > From twic at urchin.earth.li Sat Jul 16 05:21:25 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 16 Jul 2005 10:21:25 +0100 Subject: Python Programming Contest In-Reply-To: References: <42D780EF.6020809@sweetapp.com> Message-ID: On Sat, 16 Jul 2005, Joseph Garvin wrote: > Someone correct me if I'm wrong -- but isn't this the Shortest Path problem? Dang! I was just about to point that out. > I don't foresee anyone getting a more efficient solution than what they > can find in hundreds of algorithms textbooks. If this is indeed the case > it should just come down to whoever can pull the narliest tricks to > create a fast python implementation of the algorithm. I guess part of the challenge is seeing through the description to the underlying problem - in this case, seeing that this can be cast as shortest-path. Not everyone would necessarily realise that! In particular, the fact that the available flights, and their prices, can be different on different days could well throw people. But yes, this is basically about who can write the fastest implementation of Dijkstra's algorithm. I've got one somewhere - i have a half-finished journey planner for the London Underground! - so maybe i should enter ... Hmm. Actually, Dijkstra's algorithm isn't always the fastest way to find the shortest path. The thing is, it's fully general, so it works on absolutely any graph; if the graph you're traversing has particular properties, you might be able to leverage those to find a solution faster. For instance, if your graph is a road network, you can put a lower bound on the distance from any vertex to the goal (being the straight-line distance between them - no path over actual roads can be any shorter than that), which allows you to do an A* search, which is a lot faster than Dijkstra. My own journey planner is also a case of this - i exploit various obvious properties of tube trains to avoid examining a large number of possible but daft travel plans. I can't immediately see any properties of this network that could be exploited, but that doesn't mean there aren't any. tom -- taxidermy, high tide marks, sabotage, markets, folklore, subverting, . From jdennett at acm.org Sun Jul 10 15:40:03 2005 From: jdennett at acm.org (James Dennett) Date: Sun, 10 Jul 2005 12:40:03 -0700 Subject: What is Expresiveness in a Computer Language? In-Reply-To: References: <1120989424.582438.149920@f14g2000cwb.googlegroups.com> Message-ID: Pete Barrett wrote: > On 10 Jul 2005 02:57:04 -0700, "Xah Lee" wrote: > > >>Similarly, in computer languages, expressiveness is significant with >>respect to semantics, not syntactical variation. >> > > It may just be me, but I tend to think of a computer language as a > tool for directing computers to perform specific actions. Do we talk > about the expressiveness of a spade? Spades, however, are rarely used for communication between human beings, whereas languages, definitely including programming languages, are. While there's a good case to be made that communication from a person to a computer is the *primary* use of a programming language, communication between programmers is a major secondary use. > There's a similar concept in the 'possible uses' of a tool (a spade is > an excellent tool for digging the garden, but you wouldn't use it to > clean your teeth; you *could* use a toothbrush to dig the garden, but > you wouldn't if a spade was available). Similarly with computer > languages - some are better for certain tasks than others, but I don't > think 'expressiveness' is the way to describe that. You're missing, maybe, the very special nature of one task, namely that of communication between programmers. Computers care not if you use assembly code or Python, but people often find one or the other easier to read and understand. (Which is considered easier depends on the background of the reader.) -- James From ntv1534 at gmail.com Tue Jul 5 19:45:55 2005 From: ntv1534 at gmail.com (MooMaster) Date: 5 Jul 2005 16:45:55 -0700 Subject: multiple checkboxes highlighted when one clicked = not good In-Reply-To: <1120606930.677363.22260@f14g2000cwb.googlegroups.com> References: <1120605105.506005.86780@g14g2000cwa.googlegroups.com> <1120606930.677363.22260@f14g2000cwb.googlegroups.com> Message-ID: <1120607155.769291.142920@o13g2000cwo.googlegroups.com> Uhm....I'm a dunce. Thanks James! From gsakkis at rutgers.edu Thu Jul 14 20:12:15 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 14 Jul 2005 20:12:15 -0400 Subject: eBay.py - Has anyone looked at this??? References: <1121377295.386699.141580@g47g2000cwa.googlegroups.com> Message-ID: <1121386344.e07b5a134c1e05eacfc289a1c9631458@teranews> "provato" wrote > I'm somewhat of a newbie was confused by the following code that I > downloaded from eBay's developer site: > > One of the classes in the file is called "Call". What I don't get is > that in "MakeCall" function, there's a use of self.Session.Server. > Where is this property coming from? > > [snipped] Typically, instance attributes should be bound in the constructor (__init__), but strangely Call has no constructor. I checked out the ebay.py file and it turns out that other classes bind Session (and other attributes) directly, e.g. class SellerList: def Get(self, SellerUserName): api = Call() api.Session = self.Session api.DetailLevel = "2" # etc This is lousy OO design and you saw why; you can't tell where on earth is Session and the other attributes coming from. From a brief look, the api seems like a quick & dirty solution that would benefit from refactoring, so you'd rather not try to learn python from it. George From jeffh at removethis.activestate.com Fri Jul 8 19:56:46 2005 From: jeffh at removethis.activestate.com (Jeff Hobbs) Date: Fri, 08 Jul 2005 16:56:46 -0700 Subject: calling python procedures from tcl using tclpython In-Reply-To: <1120795908.918051.129670@g43g2000cwa.googlegroups.com> References: <1120740561.933409.221770@g14g2000cwa.googlegroups.com> <42CD292C.1010204@uni-oldenburg.de> <1120795908.918051.129670@g43g2000cwa.googlegroups.com> Message-ID: <42CF12BE.7040803@removethis.activestate.com> chand wrote: > can anyone help me how to provide the info about the python file > procedure in the tcl script which uses tclpython i.e., is there a way > to import that .py file procedure in the tcl script >>>currently I have wriiten this tcl code which is not working >>> >>>package require tclpython >>>set interpreter [python::interp new] >>>$interpreter eval {def test_function(): arg1,arg2} ; >>>python::interp delete $interpreter You would call 'import' in the python interpreter, like so: $interpreter eval { import testfile } assuming it's on the module search path. Look in the python docs about Modules to get all the info you need. -- Jeff Hobbs, The Tcl Guy http://www.ActiveState.com/, a division of Sophos From simonwittber at gmail.com Mon Jul 4 22:45:07 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 4 Jul 2005 19:45:07 -0700 Subject: pickle alternative References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> <1119161205.327572.136150@g44g2000cwa.googlegroups.com> <7xd5qi3ldp.fsf@ruckus.brouhaha.com> <1119166730.350374.178510@o13g2000cwo.googlegroups.com> <7x64waavoy.fsf@ruckus.brouhaha.com> Message-ID: <1120531507.113161.312630@g44g2000cwa.googlegroups.com> Ok, I've attached the proto PEP below. Comments on the proto PEP and the implementation are appreciated. Sw. Title: Secure, standard serialization of simple python types. Abstract This PEP suggests the addition of a module to the standard library, which provides a serialization class for simple Python types. Copyright This document is placed in the public domain. Motivation The standard library currently provides two modules which are used for object serialization. Pickle is not secure by its very nature, and the marshal module is clearly marked as being not secure in the documentation. The marshal module does not guarantee compatibility between Python versions. The proposed module will only serialize simple built-in Python types, and provide compatibility across Python versions. See RFE 467384 (on SourceForge) for more discussion on the above issues. Specification The proposed module should use the same API as the marshal module. dump(value, file) #serialize value, and write to open file object load(file) #read data from file object, unserialize and return an object dumps(value) #return the string that would be written to the file by dump loads(value) #unserialize and return object Reference Implementation http://metaplay.dyndns.org:82/~simon/gherkin.py.txt Rationale The marshal documentation explicitly states that it is unsuitable for unmarshalling untrusted data. It also explicitly states that the format is not compatible across Python versions. Pickle is compatible across versions, but also unsafe for loading untrusted data. Exploits demonstrating pickle vulnerability exist. xmlrpclib provides serialization functions, but is unsuitable when serializing large data structures, or when high performance is a requirement. If performance is an issue, a C-based accelerator module can be installed. If size is an issue, gzip can be used, however, this creates a mutually exclusive size/performance trade-off. Other existing formats, such as JSON and Bencode (bittorrent) do not handle some marginally complex python structures and/or all the simple Python types. Time and space efficiency, and security do not have to be mutually exclusive features of a serializer. Python does not provide, in the standard library, a serializer which can work safely with untrusted data which is time and space efficient. The proposed gherkin module goes some way to achieving this. The format is simple enough to easily write interoperable implementations across platforms. From alet at unice.fr Fri Jul 8 10:01:46 2005 From: alet at unice.fr (Jerome Alet) Date: Fri, 08 Jul 2005 16:01:46 +0200 Subject: [ANN] pkpgcounter v1.55 is out Message-ID: Hi there, I'm pleased to announce the immediate availability of pkpgcounter v1.55 pkpgcounter is a 100% Python written, GNU GPLed, Page Description Language (PDL) parser. pkpgcounter's goal is to compute and display the number of pages needed to print documents. pkpgcounter was part of the PyKota print quota and accounting software since 2003, but is now available separately. pkpgcounter currently recognizes the following formats : - PostScript (both DSC compliant and binary) - PDF - PCLXL (aka PCL6) - PCL3/4/5 (sometimes depends on the driver used) - ESC/P2 - TIFF - DVI - OpenOffice.org Writer - OpenOffice.org Impress more info : http://www.librelogiciel.com/software/pkpgcounter/action_Presentation comments are welcome Jerome Alet From peter at engcorp.com Fri Jul 29 17:01:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Jul 2005 17:01:28 -0400 Subject: Ten Essential Development Practices In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> Message-ID: <1fCdnSVjq731B3ffRVn-uA@powergate.ca> Dan Sommers wrote: > aahz at pythoncraft.com (Aahz) wrote: >>Dan Sommers wrote: >>>Was Tim writing about developing Python itself, or about developing >>>other programs with Python? > >>Yes. > > It was a rhetorical question. :-) That's all right... Aahz gave a rhetorical answer. ;-) -Peter From cliff at develix.com Sun Jul 31 17:26:44 2005 From: cliff at develix.com (Cliff Wells) Date: Sun, 31 Jul 2005 14:26:44 -0700 Subject: Wheel-reinvention with Python In-Reply-To: References: <1122577723.976528.61520@o13g2000cwo.googlegroups.com> <42EA1B75.9040307@tiscali.it> <873bpxsivs.fsf_-_@wilson.rwth-aachen.de> <87mzo4zsu4.fsf@wilson.rwth-aachen.de> <86wtn7h8pl.fsf@bhuda.mired.org> <861x5ehk4g.fsf@bhuda.mired.org> Message-ID: <1122845204.19618.153.camel@localhost.localdomain> On Sun, 2005-07-31 at 18:01 -0300, Jorge Godoy wrote: > Mike Meyer wrote: > > > We already have multiple distributions of Python: CPython, IronPython, > > and Jython (and there's at least one more). We even have multiple > > distributions of CPython, what with Active State doing their own and > > the MacPython distribution. I'm not proposing a fundamental change in > > the world, I'm suggesting an addition that would satisify the OPs > > needs. > > > > The "standard" distributor is whichever one your organization settles > > on when it comes time to choose a Python distribution. > > So we don't solve the problem with a "standard" distribution and that was > the point I was trying to show. > > In fact this sounds more like a joke I've heard a while ago: standards, if > you don't like the ones out there, create your own. > > > None of which has stopped linux from following this path. > > And solve a completely different problem while sharing the very same problem > you, on the post prior to mine, was trying to solve: what is the standard > GUI on a Linux distribution? QVWM? WindowMaker? Gnome? KDE? FVWM? Well, I think this exposes one of the more interesting sides of open source software in general. For better or worse, you get choices. If you don't like choice, you won't like open source. Many choices is sometimes great, sometimes annoying, but the bottom line is that very little is spoon-fed to you, and choice and flexibility are the primary reasons most people choose open source (this was the overwhelming verdict of a survey SuSE took a while ago). You can't even *run* Linux without making a few basic choices (Which distro? Which architecture? Which GUI? etc). If you really expect this to change then I expect there are many frustrating days ahead for you. I think most end users of Linux wish that the GNOME and KDE teams would merge (and there would be a great benefit, I expect, in reduced duplication of effort), but quite frankly, it ain't gonna happen, and quite probably there would be a lot of downsides to such an event as well. Regards, Cliff -- cliff at develix.com http://www.develix.com :: Web applications and hosting :: Linux, PostgreSQL and Python specialists :: From ivanlan at pauahtun.org Fri Jul 29 22:36:57 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Fri, 29 Jul 2005 20:36:57 -0600 Subject: [path-PEP] Path inherits from basestring again References: Message-ID: <42EAE7C9.33186BAF@pauahtun.org> Hi All-- Tony Meyer wrote: > > So far, there have been various statements that look like +0 for __div__, > but no-one with a +1. (And I've said this a couple of times now, which > really is just trolling for a +1 from someone). > > > It's not a question of saving characters, but readability which, as > > you've said, is a matter of opinion. > I like / as a shortcut to joinwith(). I like it a lot. I like it so much I'll give you a +2. > (Those who are offended by sweeping generalisations should ignore this next > bit) > > I think it's also worth considering that Windows users are more clueless > than users of posix systems. The readability of __div__ comes from > familiarity with posix filesystems; for a Windows user, \ would be the > natural character. So we're making things more readable for users that are > already more likely figure things out, and less readable for users that have > trouble figuring things out. > This is not only bullshit, it's elitist bullshit. "Windows users are more clueless than users of posix systems." Pfui. Prove it or withdraw it. > 1. ISTM that standard library modules should be as readable as possible, > even for those that don't use them. If I'm reading the source for module X > and it uses a Path object, then it should be pretty straightforward to > understand what is happening without also having to read the Path > source/docs. This (readability without knowing the language/standard > libraries) is a huge benefit of using Python. > It's overrated. It must be macho to say "I learned Python without reading books." Next you'll tell me you never ask for directions when you're lost. > 2. If I did use the Path module, then I wouldn't use __div__, because it > looks less readable to me. I suppose I might find that I got annoyed typing > joinpath, but I doubt it. Also, because I have followed this PEP, I know > that __div__ means joinwith, so if I read code that used path, I would > understand it - it's too late for me to try reading code as a 'fresh' user > and see if it confuses me or not. > Then that's your right, but don't try to take / away from people who use it and like it. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From gsakkis at rutgers.edu Wed Jul 6 23:29:45 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 6 Jul 2005 20:29:45 -0700 Subject: Use cases for del References: <3j2st8Fnu7j9U1@individual.net> <11cokv26rabdndf@corp.supernews.com> <11cp2c8184lnv83@corp.supernews.com> <11cp7fusjoid468@corp.supernews.com> Message-ID: <1120706984.868966.266710@g14g2000cwa.googlegroups.com> "Grant Edwards" wrote: > In 2005-07-07, Leif K-Brooks wrote: > > - Hide quoted text - > - Show quoted text - > > Grant Edwards wrote: > >> 1) So I know whether an parameter was passed in or not. Perhaps > >> it's not considered good Pythonic style, but I like to use a > >> single method for both get and set operations. With no > >> parameters, it's a get. With a parameter, it's a set: > > >> class demo: > >> def foo(v=None): > >> if v is not None: > >> self.v = v > >> return self.v > > > _NOVALUE = object() > > class demo: > > def foo(v=_NOVALUE): > > if v is _NOVALUE: > > return self.v > > else: > > self.v = v > > Apart from the change in the logic such that the set operation > doesn't return a value, how is that any different? You're just > creating your own non-integer-value "None" object instead of > using the one built in to the language. > > > But what's wrong with properties? > > Huh? I guess he means why not define foo as property: class demo(object): foo = property(fget = lambda self: self.v, fset = lambda self,v: setattr(self,'v',v)) d = demo() d.foo = 3 print d.foo George From apoco at cox.net Fri Jul 8 01:21:19 2005 From: apoco at cox.net (Jacob Page) Date: Thu, 07 Jul 2005 22:21:19 -0700 Subject: Polling, Fifos, and Linux In-Reply-To: References: Message-ID: Jeremy Moles wrote: > This is my first time working with some of the more lower-level python > "stuff." I was wondering if someone could tell me what I'm doing wrong > with my simple test here? > > Basically, what I need is an easy way for application in userspace to > simply echo values "down" to this fifo similar to the way proc files are > used. Is my understanding of fifo's and their capabilities just totally > off base? You shouldn't need to use select.poll(), unless I'm missing something. I was able to get the following to work: -=-=- import os fifo = os.open("fifo", os.O_RDONLY | os.O_NONBLOCK) while True: string = os.read(fifo, 1) if len(string): print string # Perhaps add a delay under an else -=-=- The Python script, when run, does nothing until you put data into the fifo from another process. Then it immediately spits the data out, character by character. I'm assuming that you've already created the fifo and that it's in the current working directory. From oliver.andrich at gmail.com Fri Jul 22 14:39:37 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Fri, 22 Jul 2005 20:39:37 +0200 Subject: PEP on path module for standard library In-Reply-To: References: <11e06nch396gccd@news.supernews.com> <3kakh5Ftjd9mU1@individual.net> Message-ID: <6f7b52d05072211392f0958aa@mail.gmail.com> Hi, 2005/7/22, Michael Hoffman : > What is this Java Path class? I have been STFWing and have found nothing > on it in the. Indeed if you search for "Java Path class" (with quotes) > almost half of the pages are this message from Guido. ;) > > Any Java hackers here want to tell us of the wonders of the Java Path > class? I would be interested in seeing how other OO languages deal with > paths. I guess the nearest Java class comparable with path is the File class. http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html And as I am a so called Java hacker, I highly appreciate path as a module for my python projects and in my eyes it is the natural way to address files/paths. At least it is more natural to me then the os, os.path, etc. pp. bundle, that has grown over the time. I would love to see path inside Python's stdlib. Best regards, Oliver -- Oliver Andrich --- http://fitheach.de/ From clambin at die.spammers.die.easynet.be Fri Jul 22 04:26:34 2005 From: clambin at die.spammers.die.easynet.be (Christophe Lambin) Date: Fri, 22 Jul 2005 10:26:34 +0200 Subject: wxPython & Fedora Core 4 References: <1122005756.744692.285840@f14g2000cwb.googlegroups.com> Message-ID: "linuxfreak" wrote: > Has anyone installed wxPython on Fedora Core 4. Apparently it need > the libstdc++.so.5 file while Fedora installs the newer libstdc++.so.6 > file. I tried installing the libstdc rpm from fedora core 3 You can install compat-libstdc++-33 (part of FC4), which has libstdc++.so.5. However, since your wxPython package wasn't built for FC4, you may run into other problems. Regards, Christophe From peter at engcorp.com Fri Jul 22 08:38:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Jul 2005 08:38:28 -0400 Subject: Difference between " and ' In-Reply-To: <42E05106.5060905@REMOVEMEcyber.com.au> References: <1121968587.508447.181610@o13g2000cwo.googlegroups.com> <42e00d17$1@news.eftel.com> <42E05106.5060905@REMOVEMEcyber.com.au> Message-ID: <2b-dnStjP7tKdH3fRVn-sA@powergate.ca> Steven D'Aprano wrote: > It may shock some people to learn that difference in the sense of > mathematical subtraction is not the only meaning of the word, but there > it is. One wouldn't, I hope, misunderstand "What is the difference > between spaghetti marinara and spaghetti pescatora?" and attempt to > subtract one from the other, since subtraction is not defined for > foodstuffs. >>> sum(ord(c) for c in 'spaghetti marinara') - sum(ord(c) for c in "spaghetti pescatora") -119 Works for me... ;-) From simonwittber at gmail.com Tue Jul 12 10:07:27 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 12 Jul 2005 07:07:27 -0700 Subject: automatically assigning names to indexes In-Reply-To: <1121169211.877343.200570@z14g2000cwz.googlegroups.com> References: <1121148275.315879.132670@f14g2000cwb.googlegroups.com> <1121169211.877343.200570@z14g2000cwz.googlegroups.com> Message-ID: <1121177247.196389.11080@z14g2000cwz.googlegroups.com> > And what should happen for vectors of size != 3 ? I don't think that a > general purpose vector class should allow it; a Vector3D subclass would > be more natural for this. That's the 'magic' good idea I'm looking for. I think a unified Vector class for all size vectors is a worthy goal! From felciano at gmail.com Fri Jul 1 13:18:15 2005 From: felciano at gmail.com (felciano) Date: 1 Jul 2005 10:18:15 -0700 Subject: Escaping commas within parens in CSV parsing? References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> Message-ID: <1120238295.198792.123110@g47g2000cwa.googlegroups.com> Thanks for all the postings. I can't change delimiter in the source itself, so I'm doing it temporarily just to handle the escaping: def splitWithEscapedCommasInParens(s, trim=False): pat = re.compile(r"(.+?\([^\(\),]*?),(.+?\).*)") while pat.search(s): s = re.sub(pat,r"\1|\2",s) if trim: return [string.strip(string.replace(x,"|",",")) for x in string.split(s,",")] else: return [string.replace(x,"|",",") for x in string.split(s,",")] Probably not the most efficient, but its "the simplest thing that works" for me :-) Thanks again for all the quick responses. Ramon From rex.eastbourne at gmail.com Fri Jul 1 16:34:26 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 1 Jul 2005 13:34:26 -0700 Subject: Running Python interpreter in Emacs In-Reply-To: References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> <1119811726.576282.59500@g49g2000cwa.googlegroups.com> Message-ID: <1120250066.836533.199420@g47g2000cwa.googlegroups.com> Yes! Thank you so much! (For some reason, by the way, I had to copy python.exe to my c:/ directory, since the computer could never find the path in program files/python24. But when I did that, and used setq-py-python-command, it worked. I now have python.exe in two locations.) From rarawlinson at siscom.net Sat Jul 30 08:30:24 2005 From: rarawlinson at siscom.net (BadBob) Date: Sat, 30 Jul 2005 08:30:24 -0400 Subject: Problems installing Python Message-ID: <42eb72e2$0$77573$9a6e19ea@news.newshosting.com> I have been trying to install python on an older pc. At first I tryed to install from the Suse 9.1 Pro Cd's. However it reported an error with the core php 4 file. I tried again with the same result. So I checked with Suse and there was an updated version. I downloaded it and it also reported an error installing the core php 4 file. I need Python installed as a program I want to run requires it. Does anyone have any idea's I can try? TIA Bob From qwweeeit at yahoo.it Sun Jul 24 06:26:06 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 24 Jul 2005 03:26:06 -0700 Subject: Initializing interactive Python Message-ID: <1122200766.916344.87470@z14g2000cwz.googlegroups.com> Hi all, is it possible to enter an interactive session and automatically do some initialization? I explain better: I want that when I start interactive Python on a console (I use Linux) two command lines be executed automatically: Python 2.3.4 (#2, Aug 19 2004, 15:49:40) [GCC 3.4.1 (Mandrakelinux (Alpha 3.4.1-3mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> x01=x02=0 I would like not to have to write anything at the prompt >>> to run the two commands, but be ready to start the interactive session. Bye. From flamesrock at gmail.com Fri Jul 8 00:03:47 2005 From: flamesrock at gmail.com (flamesrock) Date: 7 Jul 2005 21:03:47 -0700 Subject: Integrating a wx.App to a Panel (elegantly) Message-ID: <1120795427.436894.288510@g43g2000cwa.googlegroups.com> Perhaps one of you more experience wxPythoners can assist me. I have two seperate programs and basically I want to integrate program 2, which inherits from wx.App to a wx.Panel on the original program. Is there an elegant way to do this without carefully surgically inserting wx.App 2 into wx.App 1? (BTW wx.App 2 is this program: http://www.simcitysphere.com/simnet/downloads/irc.py which I adapted from http://www.intertwingly.net/stories/2003/09/15/ for wxPython 2.6.0) -thanks in advance for any help From gsakkis at rutgers.edu Sat Jul 9 14:47:31 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Jul 2005 11:47:31 -0700 Subject: Python Module Exposure References: <1120896007.334919.170450@g49g2000cwa.googlegroups.com> <1120924507.452720.236990@g47g2000cwa.googlegroups.com> Message-ID: <1120934851.208175.19180@f14g2000cwb.googlegroups.com> "Jacob Page" wrote: > George Sakkis wrote: > > There are several possible use cases where dealing directly with > > intervals would be appropriate or necessary, so it's good to have them > > supported directly by the module. > > I think I will keep Interval exposed. It sort of raises a bunch of > hard-to-answer design questions having two class interfaces, though. > For example, would Interval.between(2, 3) + Interval.between(5, 7) raise > an error (as it currently does) because the intervals are disjoint or > yield an IntervalSet, or should it not even be implemented? How about > subtraction, xoring, and anding? An exposed class should have a more > complete interface. > > I think that IntervalSet.between(5, 7) | IntervalSet.between(2, 3) is > more intuitive than IntervalSet(Interval.between(5, 7), > Interval.between(2, 3)), but I can understand the reverse. I think I'll > just support both. As I see it, there are two main options you have: 1. Keep Intervals immutable and pass all the responsibility of combining them to IntervalSet. In this case Interval.__add__ would have to go. This is simple to implement, but it's probably not the most convenient to the user. 2. Give Interval the same interface with IntervalSet, at least as far as interval combinations are concerned, so that Interval.between(2,3) | Interval.greaterThan(7) returns an IntervalSet. Apart from being user friendlier, an extra benefit is that you don't have to support factories for IntervalSets, so I am more in favor of this option. Another hard design problem is how to combine intervals when inheritance comes to play. Say that you have FrozenInterval and FrozenIntervalSet subclasses. What should "Interval.between(2,3) | FrozenInterval.greaterThan(7)" return ? I ran into this problem for another datastructure that I wanted it to support both mutable and immutable versions. I was surprised to find out that: >>> s1 = set([1]) >>> s2 = frozenset([2]) >>> s1|s2 == s2|s1 True >>> type(s1|s2) == type(s2|s1) False It make sense why this happens if you think about the implementation, but I guess most users expect the result of a commutative operation to be independent of the operands' order. In the worst case, this may lead to some hard-to-find bugs. George From renting at astron.nl Fri Jul 29 05:29:07 2005 From: renting at astron.nl (Adriaan Renting) Date: Fri, 29 Jul 2005 11:29:07 +0200 Subject: Opinions on KYLIX 3 (Delphi 4 Linux) Message-ID: I've used Kylix 3 in the past, but would not consider it nowadays, because it's realy behind the times, it can't run on the latest linux versions and does only support Qt 2.7, while Qt4 has just been released. I'm a C++ programmer and loved Borland C++Builder, I was disappointed by how buggy the C++ side of Kylix 3 was. I think Borland is dead in the water right now, because Microsoft has been targetting their Delphi/C++Builder succes very agressively. MS has essentailly bought their entire developement team, and used them to create VS.Net as an answer to both Java and the Borland developement environment. This is more or less fact, there have enven been lawsuits about it: http://news.com.com/2100-1023-279561.html?legacy=cnet http://delphi.about.com/od/delphifornet/a/conspiracydnet_2.htm According to the article Ms is now a large shareholder in Borland, and will probably halt any further Linux developement. Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> David Trudgett 07/20/05 10:37 AM >>> "Thomas Bartkus" writes: > > Good question! Wither Borland? > > My impression (second hand - based on no direct experience with > Kylix!) is that Borlands wonderful Delphi product ported to Linux > has been a dissapointment. > > * * * Someone with real experience on Kylix - please jump in here! It has been two or three years since I gave Kylix a try, so my memory is a bit vague on the specifics. I was working in a Delphi shop and wanted to port (at least some of) our apps to Linux using Kylix (I think it was version 3). I think I ported one and a half apps and more or less gave up or put it on the back burner. My impression was that Kylix still wasn't ready for serious development work. The type of application I was working on (porting) involved client/server database access, and TCP communications with other applications. It never really worked correctly (I forget what the problems were just now), but probably could have been made to work correctly. The point was, however, that porting (a relatively simple) Delphi app to Kylix shouldn't have been that hard. > > Calling Delphi "similar to Visual Basic" is hurtful because I > believe that VB is the product of looting and pillaging the talent > that came out of Borland. I'm guessing that Microsoft has > successfully targeted this perceived competitor with destruction. > > If Kylix were of the quality of Delphi, it would be a killer Linux app. Possibly. Unfortunately, I don't believe that the whole GUI building approach of Delphi/Kylix (or other similar tools) is much chop. It encourages one, for instance, to just place elements on the screen in fixed positions that make no allowance for differing fonts, screen resolutions, etc. Java (my experience is with JBuilder) is much better in this regard, although the different paradigm takes some getting used to. However, all GUI builders with which I'm familiar (not many) seem to have very real limitations when it comes to designing very complex interfaces. Kenny Tilton's Cells project (ask on comp.lang.lisp) has set me to thinking along these lines. In the past, I never gave it much consideration. Programmers who like Pascal should look at Ada as a better alternative. If I wanted to program in a Pascal-like language on Linux, Ada (the GNU Gnat compiler, integrated with GCC) is the one that I would use. Ada, you could say, is like Pascal on steroids. Caveat: I've read Ada books, but haven't programmed in it, and my main concern is that its ultra strong typing might get in my way -- or alternatively, force greater rigour, as the Ada folks might say ;-). These days, for hacking about, I prefer Common Lisp. It's faster (sometimes approaching the speed of compiled C/Pascal) and much more powerful than Python, but doesn't have the same library support (smaller community), and application bundling and delivery *can* be a potential problem, depending on various factors (such as whether you want to license a commercial Common Lisp). Also, similar to Python, there is no standard GUI framework defined for Common Lisp, so choosing from the GUI frameworks available can be a challenge (I've only programmed a simple GUI app using the great little Ltk library by Peter Herth, which talks to Tk over a socket). My advice would be to steer clear of Kylix and choose one of the other environments suggested to you. If you really like Pascal, fpc may be a possibility as someone mentioned. I haven't looked into it any time in the last couple of years, though, so I don't know its status. I really would suggest a serious look at Ada, though, if you want to develop fast, industrial strength applications, or take advantage of built-in concurrency support and lots of other goodies. David -- David Trudgett http://www.zeta.org.au/~wpower/ I was in the pub last night, and a guy asked me for a light for his cigarette. I suddenly realised that there was a demand here and money to be made, and so I agreed to light his cigarette for 10 pence, but I didn't actually give him a light, I sold him a licence to burn his cigarette. My fire-licence restricted him from giving the light to anybody else, after all, that fire was my property. He was drunk, and dismissed me as a loony, but accepted my fire (and by implication the licence which governed its use) anyway. Of course in a matter of minutes I noticed a friend of his asking him for a light and to my outrage he gave his cigarette to his friend and pirated my fire! I was furious, I started to make my way over to that side of the bar but to my added horror his friend then started to light other people's cigarettes left, right, and centre! Before long that whole side of the bar was enjoying MY fire without paying me anything. Enraged I went from person to person grabbing their cigarettes from their hands, throwing them to the ground, and stamping on them. Strangely the door staff exhibited no respect for my property rights as they threw me out the door. -- Ian Clarke -- http://mail.python.org/mailman/listinfo/python-list From gsakkis at rutgers.edu Mon Jul 4 09:01:31 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 4 Jul 2005 06:01:31 -0700 Subject: f*cking re module References: <1120464287.886617.301530@g47g2000cwa.googlegroups.com> <1120473422.864033.36350@o13g2000cwo.googlegroups.com> Message-ID: <1120482091.215743.317870@z14g2000cwz.googlegroups.com> "jwaixs" wrote: > Thank you for your replies, it's much obvious now. I know more what I > can and can't do with the re module. But is it possible to search for > more than one string in the same line? > > bv. I want to replace the with " " > with "\n" and every thing that's not between the two python > tags must begin with "\nprint \"\"\"" and end with "\"\"\"\n"? Or do I > need more than one call? You can do it in one call, but it's ugly; as other have told you already, use HTMLParser or some other parsing package. Now if you insist... regex = re.compile(r'''(?: (?:) (.*?) # group 1: inside tags (?:) ) | # OR ([^<]*) # group 2: outside tags ''', re.DOTALL | re.VERBOSE) def replace(match): g1,g2 = match.groups() if g1: return g1 else: return '\nprint """%s"""\n' % g2 text = '''this is a stupid sentence but still I have to write it.''' print regex.sub(replace,text) ===== Output ================== print """this is """ a stupid sentence print """ but still I """ have to print """ write it.""" ======================= George From spam.csubich+block at block.subich.spam.com Fri Jul 8 02:36:35 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Fri, 08 Jul 2005 02:36:35 -0400 Subject: map/filter/reduce/lambda opinions and background unscientific mini-survey In-Reply-To: <9nmze.144208$VH2.52770@tornado.tampabay.rr.com> References: <74ize.27369$ho.19404@bignews6.bellsouth.net> <9nmze.144208$VH2.52770@tornado.tampabay.rr.com> Message-ID: Ron Adam wrote: > Christopher Subich wrote: > >> As others have mentioned, this looks too much like a list >> comprehension to be elegant, which also rules out () and {}... but I >> really do like the infix syntax. > > > Why would it rule out ()? Generator expressions. Mind you, Py3k might want to unify generators and lists in some way anyway, freeing up (). :) > > You need to put a lambda express in ()'s anyways if you want to use it > right away. > > print (lambda x,y:x+y)(1,2) Although print (1,2) has natural grouping: the lambda itself is effectively a single token. I also like the infix style reminiscent of Python's existing comprehensions. Hell, call it a 'function comprehension' or 'expression comprehension,' and we can pretend we invented the damn thing. > My choice: > > name = (let x,y return x+y) # easy for beginners to understand > value = name(a,b) > > value = (let x,y return x+y)(a,b) And a zero-argument lambda is (aside from really arcane)? (let return 2)? > I think the association of (lambda) to [list_comp] is a nice > distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) Yeah, dictionary comprehensions would be an interesting feature. :) Syntax might be a bit unwieldy, though, and I doubt they'd be used often enough to be worth implementing, but still neat. From sb at digital-vitamins.com Thu Jul 28 19:12:53 2005 From: sb at digital-vitamins.com (stefvienna) Date: 28 Jul 2005 16:12:53 -0700 Subject: Python fails compiling in socket extension Message-ID: <1122592373.615252.244910@g44g2000cwa.googlegroups.com> Hi group, I'm trying compiling Python-2.4.1 and it fails builing the _socket extension with the following message: building '_socket' extension gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno-strict-aliasing -I. -I/usr/local/src/Python-2.4.1/./Include -I/usr/local/include -I/usr/local/src/Python-2.4.1/Include -I/usr/local/src/Python-2.4.1 -c /usr/local/src/Python-2.4.1/Modules/socketmodule.c -o build/temp.linux-i586-2.4/socketmodule.o In file included from /usr/local/include/netdb.h:95, from /usr/local/src/Python-2.4.1/Modules/socketmodule.c:230: /usr/include/sys/param.h:59: warning: `MAX' redefined /usr/local/src/Python-2.4.1/Modules/socketmodule.c:67: warning: this is the location of the previous definition gcc -pthread -shared build/temp.linux-i586-2.4/socketmodule.o -L/usr/local/lib -o build/lib.linux-i586-2.4/_socket.so *** WARNING: renaming "_socket" since importing it failed: build/lib.linux-i586-2.4/_socket.so: undefined symbol: __inet_addr ... looks like it cannot find inet_addr() - any ideas? if possible pls. answer via email to sb at digital-vitamins.com - many thx! Cheers, Stefan! From nephish at xit.net Sun Jul 3 15:15:38 2005 From: nephish at xit.net (nephish at xit.net) Date: 3 Jul 2005 12:15:38 -0700 Subject: need to get an index for an item in a list Message-ID: <1120418138.615987.160210@g44g2000cwa.googlegroups.com> hey there, i need to be able to get the index for an item in a list. the list is a list of lines read from a text file. like this: file = open("/home/somefile.text", "r") lines = file.readlines() file.close() now, i want to see if a certain string is == to one of the lines and if so, i need to know the index of that line. any ideas? thanks From mensanator at aol.com Tue Jul 5 13:48:59 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 5 Jul 2005 10:48:59 -0700 Subject: precision problems in base conversion of rational numbers In-Reply-To: References: Message-ID: <1120585739.458522.287210@g14g2000cwa.googlegroups.com> Brian van den Broek wrote: > Hi all, > > I guess it is more of a maths question than a programming one, but it > involves use of the decimal module, so here goes: > > As a self-directed learning exercise I've been working on a script to > convert numbers to arbitrary bases. It aims to take any of whole > numbers (python ints, longs, or Decimals), rational numbers (n / m n, > m whole) and floating points (the best I can do for reals), and > convert them to any base between 2 and 36, to desired precision. > > I'm pretty close but I know I am not handling the precision quite > right. Nothing other than understanding hangs on it, but, that's > enough :-) > > To do all this I'm using the decimal module (for the first time) and > I've been setting the precision with > > decimal.getcontext().prec = max(getcontext().prec, > x * self.precision ) > > This is in my class's __init__ method before I convert every number to > Decimal type and self.precision is at this point an int passed. > > The first term is to be sure not to reduce precision anywhere else. In > the last term I'd started off with x = 1, and that works well enough > for "small" cases (i.e. cases where I demanded a relatively low degree > of precision in the output). > > I've no idea how to work out what x should be in general. (I realize > the answer may be a function of my choice of algorithm. If it is > needed, I'm happy to extract the relevant chunks of code in a > follow-up -- this is long already.) > > For getcontext.prec = 80 (i.e x = 1) when I work out 345 / 756 in base > 17 to 80 places (i.e. self.precision = 80) I get: > > >>> print Rational_in_base_n(345, 756, 17, 80) > 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0D5C1G603999179EB > > (Rational_in_base_n(numerator, denominator, base, precision) is the > rational specific subclass. When I convert the result back to decimal > notation by hand it agrees with the correct answer to as many places > as I cared to check.) > > I've discovered empirically that I have to set getcontext.prec = 99 or > greater (i.e. x >= 1.2375) to get The value you want for x is log(17)/log(10) = 1.2304489213782739285401698943283 Multiplied by 80 gives you 98.435913710261914283213591546267, but you can't have a fraction of a digit, so round up to 99 (giving x=1.235). > 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C > > (I do feel safe in assuming that is the right answer. :-) It's not. The last digit should be "D". This is how the GMPY module handles it: >>> from gmpy import * >>> # Create an unlimited precision rational. >>> r = mpq(345,756) >>> # Convert rational to floating point with 300 bits precision. >>> # GMPY default precision is based on the nature of the rational >>> # but can be specified. Note that prcision is in bits, not digits. >>> f = mpf(r,300) >>> print f 0.45634920634920634920634920634920634920634920634920634920634920634920634920634920634920634920634921 >>> # Convert the floating point to base 17. >>> # Note that it has been correctly rounded up, so last digit is 'd'. >>> print fdigits(f,17) 7.cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7cf0ca7d at -1 > > How would I go about working out what degree of precision for the > decimal module's context is needed to get n 'digits' of precision in > an expression of base m in general? (I've no formal training in Comp > Sci, nor in the relevant branches of mathematics.) > > Thanks and best, > > Brian vdB From mwm at mired.org Tue Jul 5 22:03:57 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 05 Jul 2005 22:03:57 -0400 Subject: Lisp development with macros faster than Python development?.. References: <1120597105.368378.165660@g14g2000cwa.googlegroups.com> <1120603785.494300.180940@g49g2000cwa.googlegroups.com> Message-ID: <86u0j8wv02.fsf@bhuda.mired.org> "seberino at spawar.navy.mil" writes: >> Well, his Viaweb company was founded in about '95, right? So he probably just >> used Lisp because Python wasn't as well known yet. ;-) > > David > > That is what I thought too. It makes sense but I wasn't sure. Still > ain't. > The problem is that questions like 'What lang is fastest to develop > in?' > are hard to answer definitively. True. You might start by asking which lets you write the fewest LOC, as studies during the 70s showed that programmers tended to write the same number of LOC/day, regardless of the language chosen. The problem with the LOC measurement is that the most productive days are the ones where you refactor and eliminate a thousand LOC. That sort of throws the whole thing off. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gene.tani at gmail.com Mon Jul 4 21:53:52 2005 From: gene.tani at gmail.com (gene tani) Date: 4 Jul 2005 18:53:52 -0700 Subject: How do you program in Python? In-Reply-To: <87wto613iz.fsf@bigfoot.com> References: <3iqif8Fmj34kU1@individual.net> <42c929dc$0$27601$636a15ce@news.free.fr> <87wto613iz.fsf@bigfoot.com> Message-ID: <1120528432.041954.9670@f14g2000cwb.googlegroups.com> +1 on investing in emacs. There's a shiny new release of the Oreilly, which is (a really large book) that a lot of people teach themself out of: http://www.oreilly.com/catalog/gnu3/ But i would also recommend komodo from activestate's IDE, easy and powerful, once you understand what all's in the menu- & toolbars: http://www.activestate.com/Products/Komodo/?_x=1 (Maybe look at WingIDE, too, i've heard it's good) And the python quick refs: http://rgruet.free.fr/PQR24/PQR2.4.html http://www.onlamp.com/pub/a/python/excerpt/PythonPocketRef/index.html