Re: Namespaces/introspection: collecting sql strings for validation
Martin Drautzburg wrote: def SQL(sql, checked=set()): if sql in checked: return True if not valid_sql(sql): raise ValueError checked.add(sql) return sql No this does not do the trick. I will not be able to validate an sql statement bofore I run over the piece of code that uses it. Or I would have to define all my sql = SQL stuff on module level, isn't id. I mean, the problem is: when are those sql = SQL statement really ececuted? Let's see: def SQL(sql): ... print sql ... a = SQL(module) module # that one was obvious class A: ... b = SQL(class) ... def method(self, c=SQL(default arg)): ... d = SQL(method) ... class # ha, class statements are executed, too... default arg # ...as are default arguments Peter -- http://mail.python.org/mailman/listinfo/python-list
Socket exceptions aren't in the standard exception hierarchy
Here are three network-related exceptions. These were caught by except with no exception type, because none of the more specific exceptions matched. This is what a traceback produced: 1. File D:\Python24\lib\socket.py, line 295, in read data = self._sock.recv(recv_size) timeout: timed out 2. File D:\Python24\lib\socket.py, line 295, in read data = self._sock.recv(recv_size) error: (10054, 'Connection reset by peer') 3. File D:\Python24\lib\socket.py, line 317, in readline data = recv(1) IOError: [Errno socket error] timed out For 1 and 2, those are errors that aren't in the exception hierarchy. Looking at the C code for socketmodule.c, it's clear that socket.error doesn't inherit from any standard exception class. See, in init_socket(): socket_error = PyErr_NewException(socket.error, NULL, NULL); That first NULL should be some parent exception, maybe IOError. As it is, socket.error is outside the standard exception hierarchy. That's not too good. Case #3, IOError, should have been caught by this: except IOError, message:# I/O error But it wasn't. The IOError fell through, was caught by the next outer exception block, and was logged as a generic error. I can't find where in the Python socket module an IOError could be raised. I would have expected socket.timeout. Anyway, I need to know the full set of exceptions that can be raised by sockets. Thanks. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
Ron Garret wrote: I don't understand why socketserver calling select should matter. (And BTW, there are no calls to select in SocketServer.py. I'm using Python2.5.) You don't *need* a select at all. Socketserver just blocks on accept() and dispatches a handler on the new connection. Anyway, try the following instead: That won't work for POST requests. Why not? Just add some more code to deal with the POST request body. There should be a content-length header to tell you how many bytes to read after the header section has finished. --Irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries and dot notation
Alex Martelli wrote: Martin Drautzburg [EMAIL PROTECTED] wrote: mydata = data( ) mydata.foo = 'foo' mydata.bar = 'bar' print mydata.foo print mydata.bar I am aware of all this. Okay let me rephrase my question: is there a way of using dot notation without having to create a class? Sure, all you need to create is an *INSTANCE* of a suitable type or class. For example: d = dict(foo=23, bar=45) m = new.module('for_martin') m.__dict__.update(d) m.foo 23 m.bar 45 A module may be appropriate, since it's little more than a wrapper around a dict to access items by dot notation:-). Thanks, I finally got it. Even your previous example actually does the trick. I did not notice that I can use a single class (or a module) for all my datastructures, because I can plug in new attributes into the instance without the class knowing about them. I was mistaken to believe that I had to know about attributes at the time of class creation. But your expample does not require that. Should have read this more carefully. -- http://mail.python.org/mailman/listinfo/python-list
Re: serializable object references
Gabriel Genellina wrote: En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg [EMAIL PROTECTED] escribió: I was thinking that it would be nice if a web application could talk to real objects. The client side does not need to know the internals of an object, it acts as a view for server-side models. All it has to be able to do is invoke methods on its model. So a view could just store its object-reference in an instance variable and pass it to the server, where my problem of looking it up comes in. This is more or less what several web frameworks do. You publish objects; URLs are mapped to method objects; URL parameters become method parameters. See http://wiki.python.org/moin/WebFrameworks Okay will look. I have checked out cherrypy, but it does not seem to support direct object references, i.e. the server-side objects are really stateless and all calls to an object method will see the same state unless you do something about it youself. I have also looked at the wonderful qooxdoo javascript framework and in the examples they have, the data I receive on a published object method on my cherrypy server is: dict: { '_ScriptTransport_id': '11', '_ScriptTransport_data': '{ service:qooxdoo.test, method:sleep, id:13, params:[10], server_data:null }', 'nocache': '1177256001914' } I am not sure what all of them mean, but my impression is that none of them denote an object in the sense of an INSTANCE, at least service and method definitely do not. The id is simply incremented with every call, so it is again not an instance. Now I could of course add an object reference do the params field and have qooxdoo.text dispatch the call to an INSTANCE of an object and invoke sleep() there. But first it is a shame, that I have to provide this magic myself, and second it raises again my original question: how to I pass an object reference and look up the object in qooxdoo.test. I know I can do this with a dictionary, I just thought that the __repr__() of an object could be used, as it seems the most obvious way to do it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Namespaces/introspection: collecting sql strings for validation
George Sakkis wrote: Yes, there is: use an ORM to do the SQL generation for you. Check out SQLAlchemy, it will buy you much more than what you asked for. Might look, though in general I don't like OR mappers much. Having SQL generated feels as strange as having python code generated. Too much magic, too many layers. I think it is better to simply learn SQL. And I don't really believe in OO databases much. OO databases have been around for several decades and still have not reached the maturity of relational databases. My feeling is that OO and persistence to not play together well. -- http://mail.python.org/mailman/listinfo/python-list
Re: recursion depth problem
On Apr 22, 5:51 pm, Michael Bentley [EMAIL PROTECTED] wrote: Oops! Note to self: *ALWAYS* try code before posting to a public forum :-( def binary(val, width): print '%10s = the sum of' % val for i in [2 ** x for x in range(width - 1, -1, -1)]: a = val / i print ' ' * 13 + '%s * (2 ** %s)' % (a, width) val -= i * a width -= 1 binary(233, 8) hi michael, just a quick clarification... it seems to me that the self-documenting part of the code should be more like this: print ' ' * 13 + '%s * (2 ** %s)' % (a, width-1) instead of print ' ' * 13 + '%s * (2 ** %s)' % (a, width) is this correct, or am i mixed? sincerely, proctor -- http://mail.python.org/mailman/listinfo/python-list
send pictures to mobile phones - sms767
Hi, Is there anyone interested in helping test a web service? Sending pictures to mobile phones: http://www.sms767.com Thanks, Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Support for new items in set type
En Mon, 23 Apr 2007 02:17:49 -0300, Prateek [EMAIL PROTECTED] escribió: Oh dear god, I implemented this and it overall killed performance by about 50% - 100%. The same script (entering 3000 items) takes between 88 - 109s (it was running in 55s earlier). Here is the new Set implementation: class SeaSet(set): [...] The surprising thing is that commits *ARE* running about 50% faster (according to the time column in the hotshot profiler). But, now, the longest running operations seem to be the I/O operations which are taking 10 times longer! (even if they're only reading or writing a few bytes. Could this have something to do with the set implementation being in Python as opposed to C? Hard to tell - you have posted only your SeaSet implementation, and no I/O is involved in that code. For instance, this method: def __readTableHeader(self, f): hdr = f.read(sz__TABLE_HEADER_FORMAT__) if len(hdr) sz__TABLE_HEADER_FORMAT__: raise EOFError t = THF_U(hdr) #t = unpack(__TABLE_HEADER_FORMAT__, hdr) return t is now taking 13s when it was taking less than 0.8s before! (same number of calls, nothing changed except the set implementation) I don't see where your SeaSet class is used. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
On 2007-04-20, Paul Boddie [EMAIL PROTECTED] wrote: On 20 Apr, 16:34, Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-20, Paul Boddie [EMAIL PROTECTED] wrote: You could have knowledge or accomplishment on the X axis and effort or work on the Y axis. What else is effort than the time you spent on it? What's the difference between watching a television programme called Useless Celebrity Factoids for half an hour and spending the same amount of time studying for an exam involving useful information where you might also need to show some level of understanding of the subject matter? Do you want to discus principals or the practical problem in setting up a study? If that's not comparing similar measures of information, what's the difference between studying for an exam in a subject whose prerequisites are familiar to you and studying for one in an unfamiliar field, both for the same amount of time? Same question. If you are looking at the principals there is no problem, those already familiar now, already have spent time/effort at the subject. So you should calculate that time too. In practice those setting up a study, try to pick a activity noone is very familiar with. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
In article [EMAIL PROTECTED], Irmen de Jong [EMAIL PROTECTED] wrote: Ron Garret wrote: I don't understand why socketserver calling select should matter. (And BTW, there are no calls to select in SocketServer.py. I'm using Python2.5.) You don't *need* a select at all. Yes I do, because what I'm really writing is a dispatching proxy that has to serve many simultaneous connections. Here's the full story in case you're interested: We have an application that is currently fielded as a cgi. We have a development server that needs to run multiple copies of the application at the same time. This is so that developers can push changes into their private sandboxes for evaluation before going into the main development branch. Each sandbox has its own source tree, its own database, and its own URL namespace. There are a small number of URLs in the application that are performance bottlenecks (they are used to serve AJAX updates). In order to alleviate that bottleneck without having to rewrite the whole application to run under mod_python or some such thing we've written a special dedicated server that handles only the AJAX requests. The tricky part is that each developer needs to have their own copy of this server running because each developer can have different code that needs to run to serve those requests. Assigning each developer a dedicated IP port would be a configuration nightmare, so these servers serve run on unix sockets rather than TCP sockets. I have not been able to find a proxy server that can proxy to unix sockets, so I need to write my own. Conceptually its a very simple thing: read the first line of an HTTP request, parse it with a regexp to extract the sandbox name, connect to the appropriate unix server socket, and then bidirectionally pipe bytes back and forth. But it has to do this for multiple connections simultaneously, which is why I need select. Anyway, try the following instead: That won't work for POST requests. Why not? Because POST requests can be very complicated. Just add some more code to deal with the POST request body. I was really hoping to avoid having to write a fully HTTP-aware proxy. There should be a content-length header to tell you how many bytes to read after the header section has finished. Not if the content-transfer-encoding is chunked. Or if there are multiple file attachments. Also, even GET requests can become very complicated (from a protocol point of view) in HTTP 1.1. rg -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
On 2007-04-21, Diez B. Roggisch [EMAIL PROTECTED] wrote: Antoon Pardon schrieb: On 2007-04-20, Diez B. Roggisch [EMAIL PROTECTED] wrote: So if you have the choice between a steep or a shalow income curve you will prefer the shalow curve because a steep curve makes you think about verticale clifs and such? The analogy with a walk is just silly because curves are not like walks. Nobody will say something like: I won't invest in that company because it has a steep profit curve or the reverse: I'll invest in this company because it has an easy looking downhill going profit curve. Your whole argumentation bases on the fact that the result of the learning process, and the success of it, has something to do with the reached height - or y-axis-value - of your climb. Which is nonsense. The goal is to go from A - ignorance - to B - knowledge - which both lie on the X-Axis. Well if you want to do it that way, nobody can stop you, but people in the habit of processing numbers usually put the time on the X-axis like in time spend learning or exercising and put the other value on the Y-axis. You seem to live in a very limited world, where bezier-curves (note the name...) are parametrized over t, but rendered on the x/y-axis happily going forth and back and whatnot. I'm not talking about bezier-curves or any parametric curve, because it doesn't make sense to talk about steep and shalow curves then, since there is no implication of hard/slow easy/fast associated then with steep or shalow, you might as well use polar coordinates. If using knowledge as the x-axis and effort on the y-axis, the figure of speech makes perfect sense. That is an after the fact interpretation. There certain rules/conventions in picking your variables when you want to draw a curve. The association of steep and shalow of a curve with some real world implication depends on those rules/conventions. If you don't follow those rules/conventions don't think you can get a message across by saying steep, because any data can be put on a steep curve if you are allowed to pick how to draw your axes. So your statement doesn't mean much more than: After I have played with the paper, turned it over, rotated it a bit, the curve looks steep. That is because people prefer a curve going up and down while moving to the right instead of going left and right while moving up. Which is obviously something people don't want to do in this context, because going down doesn't make too much sense here, doesn't it? Or do you want to cram the process of unlearning in the little figure of speech as well? Then those people shouldn't refer to curves. If people want to refer to curves in order to bring a message accross then the message should make sense to those familiar with curves. I can understand that some people find that doing so, makes their message feel wrong. Not a problem, use an other metaphor. Don't twist the metaphor to get a message that feels all right to you but brings nonsense to those who are familiar with the metaphor. But even a perfectly sense-making explanation can be found, I doubt that you will ever acknowledge that you did make a mistake on this one - as you always (or better never) do... As far as I can see I don't differ from most people in this respect on this news group. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Javascript equivalence
In [EMAIL PROTECTED], Prateek wrote: Try creating a dict with sequential numeric keys. If you already have a list called my_list, you can do: com_array = dict(zip(range(len(my_list)), my_list)) com_array = dict(enumerate(my_list)) That doesn't create the intermediate lists. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
On 2007-04-22, René Fleschenberg [EMAIL PROTECTED] wrote: Antoon Pardon schrieb: Who says the axes are labeled familiarity and learning period? I just assume they are labeled (y-axis) Effort and (x-axis) Knowledge (or skill or ). You can assume all you want, but no serious person processing numbers would choose axes like that. The vast majority of world population is not into processing numbers, so why should they care? They don't have to care at all. But if they don't care about how curves are usually organized, maybe they are better of not using curves to bring a message across, since it risks to bring the wrong message to those who are familiar with curves. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
En Mon, 23 Apr 2007 04:33:22 -0300, Ron Garret [EMAIL PROTECTED] escribió: I have not been able to find a proxy server that can proxy to unix sockets, so I need to write my own. Conceptually its a very simple thing: read the first line of an HTTP request, parse it with a regexp to extract the sandbox name, connect to the appropriate unix server socket, and then bidirectionally pipe bytes back and forth. But it has to do this for multiple connections simultaneously, which is why I need select. No. This is what the *server* should do, not the *handler*. The server listens on incoming requests, and creates a new handler for each one. Inside a handler, you don't have to worry about multiple connections. If you want to process simultaneous connections, inherit your server from ThreadingMixIn or ForkingMixIn (or use one of the predefined server classes). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries and dot notation
En Mon, 23 Apr 2007 03:14:32 -0300, Martin Drautzburg [EMAIL PROTECTED] escribió: I did not notice that I can use a single class (or a module) for all my datastructures, because I can plug in new attributes into the instance without the class knowing about them. I was mistaken to believe that I had to know about attributes at the time of class creation. But your expample does not require that. Should have read this more carefully. Welcome to Python and its dynamic nature! -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
On 2007-04-20, Dennis Lee Bieber [EMAIL PROTECTED] wrote: On 20 Apr 2007 12:25:40 GMT, Antoon Pardon [EMAIL PROTECTED] declaimed the following in comp.lang.python: But if a wrong idea is circulating and nobody ever tries to correct it, people will continue with the wrong idea. All I did was make a simple remark, that as I suggested anyone could ignore, but that would allow those willing to learn, to further investigate. But is it a wrong idea if 999 people interpret the phrase one way, and just 1 insists upon an interpretation that, while correct in a small technical area, results in misunderstanding when speaking with the other 999? The lay person sees productivity as movement on the x-axis (I'm here [start of job], I need to get there [end of job]). I dare you. Give some people some data: Like the productivity of each month in a year and ask them to put those numbers on a graph. I bet most will put the months on the x-axis and the productivity on the y-axis. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: python cgi problem with textarea
On Apr 23, 1:01 am, Adrian Smith [EMAIL PROTECTED] wrote: On Apr 22, 10:09 pm, placid [EMAIL PROTECTED] wrote: i just tried it and its working. here it is http://yallara.cs.rmit.edu.au/~bevcimen/form.html maybe the internal server error is because mod_python isn't installed assuming your using Apache as your web server Yeah, but it wouldn't work *at all* in that case, would it? ATM it seems to work as long as the textarea input has no spaces. it doest work because the space character isnt interpreted correctly, you need to change the space characters too nbsp; Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: python cgi problem with textarea
Adrian Smith wrote: ...and I get an internal server error if I have any spaces in the textarea, which is really going to limit its usefulness to me. Oddly, While debugging you should put #!/usr/bin/python import cgitb cgitb.enable() import cgi print Content-type: text/html\n form = cgi.FieldStorage() print form[essay].value at the beginning of your cgi -- just in case the error is in the python script. Peter -- http://mail.python.org/mailman/listinfo/python-list
Two syntax questions (newbie)
I used Mathematica for data processing a lot and I got spoiled by its functional programming possibilities. I was drawn to Python because it also allows for a similar programming style (and, more importantly, it has an interactive shell, ipython, and a lot of libraries that are useful to me, like scipy). I am still learning the language, so please be gentle :-) And here comes the first question: Mathematica allows writing result = [EMAIL PROTECTED]@[EMAIL PROTECTED] or even result = data//Sort//Reverse//processData instead of result = processData[Reverse[Sort[data]]] In Python this would be something like result = processData(list(reversed(sorted(data The first two Mma alternatives are both easier to read (especially when part of a bigger expression) and easier to type (an re-type, if working interactively) because I don't have to jump with the cursor to the beginning and end of the expression to insert the brackets when adding another function call. Is there a way to avoid typing all the parentheses in Python? Is it possible to define a different syntax for function calls or define a function composition operator for functions that take a single argument? The second question: Of course Python is not Mathematica and not as friendly with this style as Mma is. Sometimes it forces me to use some temporary variables (e.g. because lines get too long and breaking lines with a backslash is ugly). I like to get rid of these variables as soon as they aren't needed, e.g.: temp = data[:] temp.sort() temp.reverse() result = processData(temp) del temp Is it possible to avoid the explicit del temp? In C/C++ I would simply enclose the piece of code in curly brackets. Is it possible to somehow separate a block of code from the rest of the program and make variables local to it? Of course none of these two things would allow me do to something that I can not already do, but they would make work easier. And I am curious if they are possible. Thanks for your replies in advance, Szabolcs -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries and dot notation
On 2007-04-22, Martin Drautzburg [EMAIL PROTECTED] wrote: Daniel Nogradi wrote: What if I want to create a datastructure that can be used in dot notation without having to create a class, i.e. because those objects have no behavior at all? A class inheriting from dict and implementing __getattr__ and __setattr__ should do the trick... It can do the trick but one has to be careful with attributes that are used by dict such as update, keys, pop, etc. Actually it's noted in a comment at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the whole idea (attribute access of dictionaries) is a bad idea and I tend to agree. Oh thank you. So all I have to do is have my object's class implement __setattr__ and __getattr__, or derive it from a class that does so? And I could save my attributes anywhere within my instance variables. So I could even add a dictionary whose name does not conflict with what python uses and whose key/value pairs hold the attributes I want to access with dot notation and delegate all the python attributes to their native positions? Oh I see, thats tricky. I still need to be aware of the builtin stuff one way or the other. Maybe you can do the opposite and create a class that implements __getitem__ and __setitem__ in function of attribute access. The following is an example: class Rec(object): def __init__(__, **kwargs): for key,value in kwargs.items(): setattr(__, key, value) def __getitem__(self, key): return getattr(self, key) def __setitem__ (self, key, val): setattr(self, key, val) rec = Rec(a=1) print rec.a print rec[a] rec.b = 2 print rec[b] rec[c] = 3 print rec.c -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
ctypes: how to make a structure pointer to point to a buffer
first, I'm try the POINTER to convesion the pointer type. but failed. class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition',c_ubyte)] buffer = c_byte * 1024 student_p = cast(buffer, POINTER(STUDENT)) The parameter of the POINTER must be ctypes type. How could I attach the buffer pointer to the structure STUDENT ? -- http://mail.python.org/mailman/listinfo/python-list
Re: serializable object references
En Mon, 23 Apr 2007 03:35:42 -0300, Martin Drautzburg [EMAIL PROTECTED] escribió: Gabriel Genellina wrote: En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg [EMAIL PROTECTED] escribió: I was thinking that it would be nice if a web application could talk to real objects. The client side does not need to know the internals of an object, it acts as a view for server-side models. All it has to be able to do is invoke methods on its model. So a view could just store its object-reference in an instance variable and pass it to the server, where my problem of looking it up comes in. This is more or less what several web frameworks do. You publish objects; URLs are mapped to method objects; URL parameters become method parameters. See http://wiki.python.org/moin/WebFrameworks Okay will look. I have checked out cherrypy, but it does not seem to support direct object references, i.e. the server-side objects are really stateless and all calls to an object method will see the same state unless you do something about it youself. The description I wrote above aplies exactly to ZOPE: URLs map exactly to object methods and those objects can (and should) maintain state. (Zope uses an OO database, ZODB, to hold those objects). But Zope is a big framework and not easy to grasp, so I would not recomend it for a small site or web application. Using CherryPy you can keep state across requests, if you use some sort of session machinery; at least you could build a mapping SessionID-State (the state being as complex as you want). I think TurboGears has something built in for managing sessions, but I'm not sure. I have also looked at the wonderful qooxdoo javascript framework and in the examples they have, the data I receive on a published object method on my cherrypy server is: Never used qooxdoo... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Two syntax questions (newbie)
En Mon, 23 Apr 2007 05:15:26 -0300, Szabolcs [EMAIL PROTECTED] escribió: Mathematica allows writing result = [EMAIL PROTECTED]@[EMAIL PROTECTED] or even result = data//Sort//Reverse//processData instead of result = processData[Reverse[Sort[data]]] In Python this would be something like result = processData(list(reversed(sorted(data The first two Mma alternatives are both easier to read (especially when part of a bigger expression) and easier to type (an re-type, if working interactively) because I don't have to jump with the cursor to the beginning and end of the expression to insert the brackets when adding another function call. Is there a way to avoid typing all the parentheses in Python? Is it possible to define a different syntax for function calls Not a different syntax. or define a function composition operator for functions that take a single argument? You could use this: def chain(*args): Compose functions (assoc right). last argument (args[-1]): argument to last function args[0] .. args[-2]: functions taking a single argument Returns args[0](args[1](...(args[-2]))(args[-1]) args = list(args) data = args.pop(-1) while args: fn = args.pop(-1) data = fn(data) return data import random items = [random.randrange(100) for _ in range(20)] print chain(list, reversed, sorted, items) Of course Python is not Mathematica and not as friendly with this style as Mma is. Sometimes it forces me to use some temporary variables (e.g. because lines get too long and breaking lines with a backslash is ugly). I almost never use backslashes for line continuation. If you have an open (,[,{ continuation is implicit. If not, usually adding a heading ( is enough. That is, instead of x = a + b + \ c - d I'd use: x = (a + b + c - d) I like to get rid of these variables as soon as they aren't needed, e.g.: temp = data[:] temp.sort() temp.reverse() result = processData(temp) del temp Is it possible to avoid the explicit del temp? In C/C++ I would simply enclose the piece of code in curly brackets. Is it possible to somehow separate a block of code from the rest of the program and make variables local to it? Python does not have block scope; use a function instead. (It's hard to define block scopes without variable declarations). Anyway that would make any difference if you are using huge structures. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident ***
On 22 Apr 2007 17:17:40 -0700, [EMAIL PROTECTED] wrote: On Apr 22, 8:49 pm, Jim Thompson [EMAIL PROTECTED] Web-Site.com wrote: Ignorant Bastard Poster On 22 Apr 2007 11:32:34 -0700, [EMAIL PROTECTED] wrote: Dr Gideon Polya published some 130 works in a 4 decade scientific career, most recently a huge pharmacological reference text Biochemical Targets of Plant Bioactive Compounds (Taylor Francis, New York London, 2003), and is currently editing a completed book on global avoidable mortality (numerous articles on this matter can be found by a simple Google search for Gideon Polya and on his websites: Here is the BRILLIANT AND INCISIVE ANALYSIS: http://countercurrents.org/polya230407.htm-- Dr Polya, we are incredibly proud of you. God Bless you for your courage. Note that Dr. Polya comes from Tasmania - the Australian state where I was born. Meanwhile, Jim's decline continues - he has now committed top posting. Institutionalisation can't be far away. A few home truths, but when i read this kind of diatribe: The past and present US mass murder and genocide is largely un-reported by lying, racist, genocide-ignoring Mainstream media and Racist Bush-ite (RB) America (and its lackey Racist White Australia) are ruled by régimes locked into denial over the seriousness of global warming Makes me wonder about the credibility of any statement Dr Gideon Polya makes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Two syntax questions (newbie)
Thanks for the reply! On Apr 23, 10:55 am, Gabriel Genellina [EMAIL PROTECTED] wrote: or define a function composition operator for functions that take a single argument? You could use this: def chain(*args): Compose functions (assoc right). last argument (args[-1]): argument to last function args[0] .. args[-2]: functions taking a single argument Returns args[0](args[1](...(args[-2]))(args[-1]) args = list(args) data = args.pop(-1) while args: fn = args.pop(-1) data = fn(data) return data import random items = [random.randrange(100) for _ in range(20)] print chain(list, reversed, sorted, items) This is already better. Is it possible to define function composition as an operator and have something like ([EMAIL PROTECTED]@sorted)(items) or (list*reversed*sorted)(items) ? I almost never use backslashes for line continuation. If you have an open (,[,{ continuation is implicit. If not, usually adding a heading ( is enough. That is, instead of x = a + b + \ c - d I'd use: x = (a + b + c - d) Thanks! This is very useful. Szabolcs -- http://mail.python.org/mailman/listinfo/python-list
Re: Support for new items in set type
I don't see where your SeaSet class is used. Actually that is the point. According to the hotshot profile, the problem code doesn't use the SeaSet implementation. Yet that same code was running much faster earlier. I tried multiple time (2-3 times). From what I can fathom, nothing else changed - just the set implementation. It seems obvious that the read() call in the __readTableHeader method is blocking for longer periods although it isn't exactly obvious why that might be. I was hoping someone with an idea of Python-C interaction could shed some light on this. I'm on a different computer right now, I'll log back in later and post more code if that helps. Again, thanks to anyone who can help. Prateek -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
On 2007-04-20, Gabriel Genellina [EMAIL PROTECTED] wrote: En Fri, 20 Apr 2007 15:28:51 -0300, Bjoern Schliessmann [EMAIL PROTECTED] escribió: Luis M. González wrote: I don't remember exactly where I read about it, but Guido said once that tuples are being kept mainly for historical reasons. Weren't tuples added when lists already existed? Both listobject.c and tupleobject.c appear to had been checked in at the same time: Revision 2167 - (view) (download) (as text) - [select for diffs] Added Sun Oct 14 12:07:46 1990 UTC (16 years, 6 months ago) by guido File length: 4965 byte(s) Initial revision And that's before the earliest tagged release I could find on svn, Python 0.98 But this doesn't contradict the supposed comment from guido. One can add something later and come to the conclusion that it would have been better not included but that in the mean time too much depend on it to remove it. That seems a perfect description of keeping something for historical reasons. So it is possible that one keeps something for historical reasons that is more recent than something one keeps for design reasons. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes: how to make a structure pointer to point to a buffer
人言落日是天涯,望极天涯不见家 wrote: first, I'm try the POINTER to convesion the pointer type. but failed. class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition',c_ubyte)] buffer = c_byte * 1024 student_p = cast(buffer, POINTER(STUDENT)) The parameter of the POINTER must be ctypes type. How could I attach the buffer pointer to the structure STUDENT ? I think it should work like this: from ctypes import * class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition',c_ubyte)] buffer = (c_byte * 1024)() buffer_p = pointer(buffer) student_p = cast(buffer_p, POINTER(STUDENT)) print student_p Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes: how to make a structure pointer to point to a buffer
On Apr 23, 5:42 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: 人言落日是天涯,望极天涯不见家 wrote: first, I'm try the POINTER to convesion the pointer type. but failed. class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition', c_ubyte)] buffer = c_byte * 1024 student_p = cast(buffer, POINTER(STUDENT)) The parameter of the POINTER must be ctypes type. How could I attach the buffer pointer to the structure STUDENT ? I think it should work like this: from ctypes import * class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition', c_ubyte)] buffer = (c_byte * 1024)() buffer_p = pointer(buffer) student_p = cast(buffer_p, POINTER(STUDENT)) print student_p Diez yes, it should add the bracket buffer = (c_byte * 1024)() Thank you ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Two syntax questions (newbie)
This is already better. Is it possible to define function composition as an operator and have something like ([EMAIL PROTECTED]@sorted)(items) or (list*reversed*sorted)(items) ? Not on functions, but on classes/instances. So something like this might work for you (untested): class FunctionComposer(object): def __init__(self, f=None): if f is None: f = lambda x: x self._f = f def __call__(self, *args, **kwargs): return self._f(*args, **kwargs) def __mul__(self, other): def combined(*args, **kwargs): return other(self._f(*args, **kwargs)) return FunctionComposer(combined) fc = FunctionComposer Then you can write (fc() * list * reversed * sorted)(items) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: recursion depth problem
On Apr 23, 2007, at 1:57 AM, proctor wrote: On Apr 22, 5:51 pm, Michael Bentley [EMAIL PROTECTED] wrote: Oops! Note to self: *ALWAYS* try code before posting to a public forum :-( def binary(val, width): print '%10s = the sum of' % val for i in [2 ** x for x in range(width - 1, -1, -1)]: a = val / i print ' ' * 13 + '%s * (2 ** %s)' % (a, width) val -= i * a width -= 1 binary(233, 8) hi michael, just a quick clarification... it seems to me that the self-documenting part of the code should be more like this: print ' ' * 13 + '%s * (2 ** %s)' % (a, width-1) instead of print ' ' * 13 + '%s * (2 ** %s)' % (a, width) is this correct, or am i mixed? No, you're right -- actually I ended up decrementing width after the print instead of before it -- but didn't feel like posting yet another correction. Your correction works though! -- http://mail.python.org/mailman/listinfo/python-list
Offer of free dedicated servers for the Python project
Hi All Please don't interpret this as spam or as a posting of a commercial nature. I am here to point out an opportunity for the Python project to receive some free hardware support. I'm not here to sell anything :) My company, DirectScale, is offering 10 free dedicated servers to open-source projects. This can be Python, or any project related to Python, or any project at all, as long as its deliverables are licensed under an OSI-approved open-source license. The only requirement is that someone responsible for the project contact us via our website (www.directscale.com) outlining what they would use the servers for. I encourage any project who could make good use of some free servers to get in touch, as this opportunity will not last. Thanks for your time. -- Jasper Bryant-Greene [EMAIL PROTECTED] Album Limited -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
OK. In order to kill the-thread-that-would-not-die(tm), I think I know what I must do. I'll print a correction: On Apr 19, 2007, at 2:22 AM, Michael Bentley wrote: ... I switched to PyObjC. The learning curve is rather steep IMO, but worth it. One thing I think I should mention though is that if you move to PyObjC -- do some projects in Objective C first. Otherwise your brain will implode. Should be changed to: .. I switched to PyObjC. The learning-effort curve is rather steep IMO, but worth it. One thing I think I should mention though is that if you move to PyObjC -- do some projects in Objective C first. Otherwise your brain will implode. Hope this helps, Michael ;-) -- http://mail.python.org/mailman/listinfo/python-list
The Hack of bitmask used as Predicate Parameters
In this article, i explain how the use of bit masks is a hack in many imperative languages. Often, a function will need to take many True/False parameters. For example, suppose i have a function that can draw a rainbow, and each color of the rainbow can be turned on or off individually. My function specification can be of this form: “rainbow(red, orange, yellow, green, blue, violet, purple)”. Each parameter is a true or false value. So, to draw a rainbow with only red and yellow stripes on, one would code, for example “rainbow(t,f,t,f,f,f,f)”, where “t” stands for true and “f” stands for false. (or, similar values for the true/false of the language's boolean system) The problem with this simple approach is that when a function has too many parameters, “which position means what” becomes difficult to remember and manage. Alternatively, a high-level language may provide a system for named parameters. So, for example, the function may be called like this with 2 arguments “rainbow(red:t, yellow:t)”, meaning, give the true values to the parameters named “red” and “yellow”. Parameters not given may automatically assumed to have false values by default. Similarly, the language can simply have the function call look like this: “rainbow(red, yellow)”, where omitted parameter names simply means false. LSL deals with this issue by using a concept of bit-mask that came from low-level languages. From the programer's point of view, the way to call this rainbow function would look like this: “rainbow(red| yellow)”. On the surface, it seems just a syntax variation. But actually, the “red” and “yellow” here are global constants of type integer, defined by the language, and the “|” is actually a bit-wise binary operator. To explain this to a educated person (e.g. a mathematician) but who are not a professional programer, it gets a bit complex as one has to drag in binary notation, boolean operation on binary notation realized as a sequence of slots, and the compiler ease in processing numbers as binary digits, and the compiler writer and language designer's laziness in resorting to these instead of a high- level interface of named parameters. The hack of using the so-called bit-mask as a interface for functions that need named parameters, is similar to languages using “1” and “0” as the true/false symbols in its boolean system, and languages using the “or” operator “||” as a method of nested “if else” program flow constructs. The problem with these hacks, is that they jam logically disparate semantics into the same construct. Their effects is making the source code more difficult to read, and thus increased programer error. It may seem like nickpicking to say that it is a hack. However, when many such seemingly trivially improper designs appear in a language, adds up to the language's illness, and overall making the language difficult to learn, difficult to read, difficult to extend, increase programing errors, and most importantly, reduce a clear understanding of key concepts. Unix and C, are the primary perpetrator of this sin. Due to their “$free$” and “speedy” and “simplistic” nature as cigarettes given to children, have passed these designs to many imperative languages and left programers not understanding the basic issues of a function's parameters and named parameters. Examples of using bitmask as a hack: • Many functions in C. (e.g. fcntl) • Unix's function/“command line tool”'s error values. (as bits) • Perl's “sysopen”, “select”, and others. (if you know a perl example that isn't related to unix, pls let me known) • Second Life's Linden Scripting Language. (see http://xahlee.org/sl/ls-prob.html ) A example of confusion about function's parameters is exhibited in unix's bewildering, inconsist syntaxes in its command line tools's ways of taking arguments. (some parameter influence other parameters. Argument order sometimes matter, sometimes doesn't, sometimes causing unintented output and sometimes causing syntax error. Named parameters sometimes have the names optional(!). Named parameters that are predicates sometimes act by their presence along, sometimes by their value, sometimes accept both, sometimes causes syntax error. Some defaults are supplied to unnamed parameters, and some are to named parameters. Some parameters has synonyms. ...) For another example in a more modern language, is Python's “re.search()” function for text pattern matching. Its optional third parameter is a bitmask. ( see “Regular Expressions in Python” http://xahlee.org/perl-python/python_re-write/lib/node111.html ) As a example of not clearly understanding a function's parameters and the need and role of named parameters in computing languages, Python's “sorted” function as well as its “lambda” construct are both victims. (Further reading: • “Sorting in Python and Perl” http://xahlee.org/perl-python/python_doc_sort.html • “Python Doc Problem Example: sort()” http://xahlee.org/perl-python/sort_list.html • “Lambda
Re: [ANN] Pythonutils 0.3.0
Fuzzyman wrote: There is a new (and long overdue) release of the `Pythonutils module http://www.voidspace.org.uk/python/modules.shtml#pythonutils`_. This is version **0.3.0**. * `Quick Download: Pythonutils 0.3.0.zip http://www.voidspace.org.uk/ cgi-bin/voidspace/downman.py?file=pythonutils-0.3.0.zip`_ What is Pythonutils? === Pythonutils is a collection of general utility modules that simplify common programming tasks in Python. The modules included are : * `ConfigObj http://www.voidspace.org.uk/python/configobj.html`_ 4.4.0 - Easy config file reading/writing * `validate http://www.voidspace.org.uk/python/validate.html`_ 0.2.3 - Validation and type conversion system * `StandOut http://www.voidspace.org.uk/python/standout.html`_ 3.0.0 - Simple logging and output control object * `pathutils http://www.voidspace.org.uk/python/pathutils.html`_ 0.2.5 - For working with paths and files * `cgiutils http://www.voidspace.org.uk/python/cgiutils.html`_ 0.3.5 - {acro;CGI} helpers * `urlpath http://www.voidspace.org.uk/python/urlpath.html`_ 0.1.0 - Functions for handling URLs * `odict http://www.voidspace.org.uk/python/odict.html`_ 0.2.2 - Ordered Dictionary Class For more details, visit the `Pythonutils Homepage http:// www.voidspace.org.uk/python/pythonutils.html`_. What is New in 0.3.0? Several of the modules have been updated. The major changes are: * Removed the `listquote http://www.voidspace.org.uk/python/ listquote.html`_ module * ConfigObj updated to 4.4.0 * StandOut updated to 3.0.0 (*Not* backwards compatible, but much improved) Thanks, the modules are nicely documented. The odict is particularly welcome. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
On Mon, 23 Apr 2007 00:33:22 -0700, Ron Garret [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Irmen de Jong [EMAIL PROTECTED] wrote: Ron Garret wrote: I don't understand why socketserver calling select should matter. (And BTW, there are no calls to select in SocketServer.py. I'm using Python2.5.) You don't *need* a select at all. Yes I do, because what I'm really writing is a dispatching proxy that has to serve many simultaneous connections. Calling select() in a while loop doesn't give you this. [snip] I have not been able to find a proxy server that can proxy to unix sockets, so I need to write my own. Conceptually its a very simple thing: read the first line of an HTTP request, parse it with a regexp to extract the sandbox name, connect to the appropriate unix server socket, and then bidirectionally pipe bytes back and forth. But it has to do this for multiple connections simultaneously, which is why I need select. Twisted does this out of the box, for what it's worth. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: TK-grid problem, please help
Hi, Thanks for the help! Anton Vredegoor wrote: Ray wrote: hi, I have a question about how to use .grid_forget (in python/TK) I need to work on grid repeatly. everytime when a button is pressed, the rows of grid is different. such like, first time, it generate 10 rows of data. 2nd time, it maybe only 5 rows. so I need a way to RESET the grid data every time. how can I do it? by grid_forger()?, then would anyone can help on how to use grid_forget() the sample code as following: I'm not sure if it solves your problem but this modification of your code at least *looks* like it works better. The entries are completely destroyed so that the next time you call the function they can be recreated. The trick I am using is to use a list in the arguments of the function but that is a bit of a hack, the list 'remembers' its state from the last time the function was called, I think one should use classes for bookkeeping such things instead. from Tkinter import * def mygrid(text,M = []): how to use grid_forget() to clean the grid??### while M: x = M.pop() x.destroy() rows = [] count=int(text) for i in range(count): cols = [] for j in range(4): e = Entry(frame3, relief=RIDGE) M.append(e) e.grid(row=i, column=j, sticky=NSEW) e.insert(END, '%d.%d' % (i, j)) cols.append(e) rows.append(cols) root=Tk() frame1=Frame(root, width=150, height=100) frame1.pack() text=Entry(frame1) text.pack(side=LEFT) button=Button(frame1, text='generate grid', command=(lambda: mygrid(text.get( button.pack() frame2=Frame(root, width=150, height=100) frame2.pack() button2=Button(frame2, text='exit', command=root.quit) button2.pack() frame3=Frame(root, width=150, height=300) frame3.pack() root.mainloop() A. -- http://mail.python.org/mailman/listinfo/python-list
Re: TK-grid problem, please help
Hi, Thanks for the help. I was trying to find a book Python TK something on last Friday. but didn't find it :-) I know those codes are in poor design, because I wrote those sample code to show the idea about what I need. the real code is working with mysql. however, I'm really new in python. (I start learning it on last Wednesday). Thanks again for the help! Ray James Stroud wrote: Using grid_forget() is probably optimization overkill, but may be handy for slower computers where you can watch the widgets appear one by one (older than about 5 years--for example original mac ibook). Also, you should get a good book on Tkinter because your design here will pretty difficult to maintain and is not very flexible. But...if you want to know how it might be done with grid_forget using the code you already have (i.e. making widgets only if necessary): #START# from Tkinter import * from tkMessageBox import showerror def mygrid(text): how to use grid_forget() to clean the grid??### numrows = len(frame3.rows) try: count=int(text) except: showerror('Entry Error', '''Hey, %s don't make an int, Fool!''' % text, parent=frame3) return 'break' for i in range(count): if i numrows: cols = frame3.rows[i] else: cols = [Entry(frame3, relief=RIDGE) for j in range(4)] frame3.rows.append(cols) for j in range(4): e = cols[j] e.grid(row=i, column=j, sticky=NSEW) e.delete(0,END) e.insert(END, '%d.%d' % (i, j)) for i in range(i+1, numrows): for e in frame3.rows[i]: e.grid_forget() root=Tk() frame1=Frame(root, width=150, height=100) frame1.pack() text=Entry(frame1) text.pack(side=LEFT) button=Button(frame1, text='generate grid', command=(lambda: mygrid(text.get( button.pack() frame2=Frame(root, width=150, height=100) frame2.pack() button2=Button(frame2, text='exit', command=root.quit) button2.pack() frame3=Frame(root, width=150, height=300) # adding an attribute here frame3.rows = [] frame3.pack() root.mainloop() #END# Notice also the necessity for the e.delete(0, END) line to get the desired text in the entries. Also demonstrated is how to handle poor input. *Note* Remember to always call the user Fool when he does something stupid. James -- http://mail.python.org/mailman/listinfo/python-list
Re: Two syntax questions (newbie)
Szabolcs [EMAIL PROTECTED] wrote: In Python this would be something like result = processData(list(reversed(sorted(data I know that is only intended as an example, but by trying to use Mathematica idioms in Python you are perhaps blinding yourself to using Python's own idioms. A more Pythonic way to write your example in Python would be: result = processData(sorted(data, reverse=True)) sorted already returns a list, and giving it 'reverse=True' is almost always identical to sorting and then reversing (and in the rare cases where it matters the reverse parameter is probably what you want). The second question: Of course Python is not Mathematica and not as friendly with this style as Mma is. Sometimes it forces me to use some temporary variables (e.g. because lines get too long and breaking lines with a backslash is ugly). I like to get rid of these variables as soon as they aren't needed, e.g.: temp = data[:] temp.sort() temp.reverse() result = processData(temp) del temp Is it possible to avoid the explicit del temp? In C/C++ I would simply enclose the piece of code in curly brackets. Is it possible to somehow separate a block of code from the rest of the program and make variables local to it? Move the code using the temporary variable into a function and it will disappear as soon as the function returns. If you find you want to delete the temporary before the function returns then your function is too long. As always there are caveats on this: don't depend on either 'del' or a return from a function actually destroying objects immediately as any surviving references to the value will prolong its life. Also, while the current C-Python implementation deletes values immediately if they have no references other Python implementations do not. In this case the obvious fix is to use a function which copies, sorts and reverses a sequence and then you don't need the temporary. Since that function already exists you don't even need to write it. -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib basic question
Robert Kern [EMAIL PROTECTED] writes: Colin J. Williams wrote: I'm not sure that scipy has been updated to Python 2.5 ? scipy certainly works with 2.5. Are you referring to something else perhaps? Yes, the Python Enthought Edition was being discussed and it is currently based on Python 2.4.3. http://code.enthought.com/enthon/ -- Pete Forman-./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent [EMAIL PROTECTED]-./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Javascript equivalence
Sam the Cat wrote: Hey All, I am writing some COM code in Python to control photoshop. Several functions of PS require an Array argument. In the examples of VBscript or javascript the Array type is used. I have tried what would appear to be the equivalent in Python -- Lists and Tuples -- but to no avail. Anyone have any insight on what via the COM interface is equivalent to an Array in javascript ? The nest way to approach an answer to your question would be for you to post a VB snippet from one of the examples together with your attempt to do the same thing in Python plus the error traceback (or other such messages as you may see) generated when your attempts fails. Otherwise the question is just a bit too broad to give an answer. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: send pictures to mobile phones - sms767
sms767 wrote: Hi, Is there anyone interested in helping test a web service? Sending pictures to mobile phones: http://www.sms767.com Probably those list readers who are interested in having their names and cellphone numbers captured and potentially spammed to hell, as if that kind of thing doesn't already happen enough on email and newsgroups. The fact that there's no privacy policy doesn't help. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
redirect ouput
Hi, I am working on parsing an xml file using python.How can i redirect the output to 2 files,say,for some portion of code the output has to go to one file and for some part the o/p be directed to another file. -- http://mail.python.org/mailman/listinfo/python-list
Re: redirect ouput
En Mon, 23 Apr 2007 09:29:40 -0300, [EMAIL PROTECTED] escribió: I am working on parsing an xml file using python.How can i redirect the output to 2 files,say,for some portion of code the output has to go to one file and for some part the o/p be directed to another file. Using two separate files? out1 = open(output1.txt, w) out2 = open(output2.txt, w) ... if some_condition: out1.write(...) else: out2.write(...) ... out1.close() out2.close() (If that's not what you want, I may have misundertstood your question, please reformulate it) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
Antoon Pardon wrote: The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: HelpA[2:4]= lp But it give the wrong idea when using the following extended slice: HelpA[4:2:-1] = Ap So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. Clearly I understand that differently: HelpA[-2:-4:-1] 'pl' -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: =Chris Lasher wrote: = Should a Python module not intended to be executed have shebang/ = hashbang (e.g., #!/usr/bin/env python) or not? I'm used to having a = shebang in every .py file but I recently heard someone argue that = shebangs were only appropriate for Python code intended to be = executable (i.e., run from the command line). = =Personally I include it in all of them, as part of boilerplate in a =template. I'd recommend againt it. The shebang doesn't do you any good unless it's also in the presence of a file that has its executable bit set. For example, let's leave python out for a second: I have a shell script. And I also have lots of files which are not intended to be executed which are also shell scripts, but which are sucked in by the shell . or source command (which is *somewhat* analogous to python's import). Lots of these shell library scripts can't execute as standalone. The same thing is possible with pything scripts. Of course, anything that has if __name__ == __main__: in it should always have a shebang and be executable. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
On 2007-04-23, Rob Wolfe [EMAIL PROTECTED] wrote: Antoon Pardon wrote: The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: HelpA[2:4]= lp But it give the wrong idea when using the following extended slice: HelpA[4:2:-1] = Ap So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. Clearly I understand that differently: HelpA[-2:-4:-1] 'pl' This is not about what you understand. This is about what the tutorial seems to suggest here and whether or not that corresponds with how python actually works. Read the explanation and look at the picture. The -2 is to the right of l the -4 is to the left of e. So the picture IMO suggests that HelpA[-2:-4:-1] would result in le -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: TK-grid problem, please help
Hello, Ray schrieb: Hi, Thanks for the help. I was trying to find a book Python TK something on last Friday. but didn't find it :-) There is only one printed book, all the details here: http://wiki.python.org/moin/GuiBooks HTH Hertha -- http://mail.python.org/mailman/listinfo/python-list
[SQLite] Recommended wrapper?
Hello I browsed through the SQLite archives at Gname, but most threads regarding wrappers for Python date back to 2005, and for this ng, Google returns stuff from 2006 as the most relevant posts, so I figured I should ask here before diving in. There are several wrappers listed in the wiki (http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers), so I'd like some feedback about which you would recommend to use SQLite from Python (2.4, but I can upgrade to 2.5 if need be). Thank you GG. -- http://mail.python.org/mailman/listinfo/python-list
Tutorial creates confusion about slices
The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: HelpA[2:4]= lp But it give the wrong idea when using the following extended slice: HelpA[4:2:-1] = Ap So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. So I suggest to drop this. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
Michael Bentley wrote: OK. In order to kill the-thread-that-would-not-die(tm), I think I know what I must do. I'll print a correction: On Apr 19, 2007, at 2:22 AM, Michael Bentley wrote: ... I switched to PyObjC. The learning curve is rather steep IMO, but worth it. One thing I think I should mention though is that if you move to PyObjC -- do some projects in Objective C first. Otherwise your brain will implode. Should be changed to: .. I switched to PyObjC. The learning-effort curve is rather steep IMO, but worth it. One thing I think I should mention though is that if you move to PyObjC -- do some projects in Objective C first. Otherwise your brain will implode. Hope this helps, Michael ;-) I had originally thought that learning PyObjC might preclude me from having to learn Objective-C, but that seems not to be the case. I have previously found the same to be true with PyQt and wxPython--not knowing the toolkits as they are implemented in C++ is a serious handicap. I've even found this to be the case with Tkinter: understanding the Tcl implementation of Tk (which I do, because I am also a Tcl developer) is a huge advantage. Am I wrong to conclude that, if you want to do GUI programming in Python, then some level of proficiency with another language is not just recommended, but almost required? This is the case at least in my experience. When I first started learning Python a couple of years ago, I spun my wheels with it for months, because I couldn't figure out where to get started with GUI programming. Finally I set Python aside and took up Tcl/Tk for awhile--its simplicity in building GUI's is more beginner-friendly. (No there's more than one way to do it--there's only one way to do it, and that's Tk.) Now, coming back to Python with the Tk model of GUI development burned in my brain, I appreciate the breadth of functions that Python supports--but I still find myself dropping down into Tcl (!) to assemble elements of my GUI's--either to write a Python wrapper, or figure out how to implement something in pure Python. I understand the argument for Python having lots of bindings to different GUI toolkits. If you are already proficient with a GUI toolkit in a compiled language (Gtk, wxWidgets, Cocoa, Qt) then presumably switching to Python will speed up your development--learning Python is easy if you already know C++, for instance, and usually the Python bindings are just a thin wrapper over the compiled bits. But if you come to Python from the other direction--you're a relative beginner and you want to learn GUI programming without the complexities of compiled languages--then it's a lot harder to get started, ironically. Even Tkinter is a challenge for someone who doesn't know Tcl. The basics are easy enough--buttons, menus, labels, images--but doing anything sophisticated, such as trees, column views, drag-and-drop, and so on, requires extensions that may or may not be implemented in Python. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: [SQLite] Recommended wrapper?
It's all there: http://docs.python.org/lib/module-sqlite3.html Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
On Apr 23, 2007, at 7:38 AM, Antoon Pardon wrote: The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: HelpA[2:4]= lp But it give the wrong idea when using the following extended slice: HelpA[4:2:-1] = Ap So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. So I suggest to drop this. But 'drop' means to let or make (something) fall vertically... :-) At that point in the tutorial, step values had not been discussed. Just a bit lower down on the page you'll find a link to 'Sequence Types' where you'll find an explanation of stepping you'll perhaps find more satisfactory. hth, Michael --- Those who don't understand UNIX are condemned to reinvent it, poorly. --Henry Spencer -- http://mail.python.org/mailman/listinfo/python-list
Re: Can __init__ not return an object?
Steven W. Orr wrote: On Sunday, Apr 22nd 2007 at 21:01 -0400, quoth Steve Holden: [let's keep it on the list so everything gets indexed] =Steven W. Orr wrote: = When I go to create an object I want to be able to decide whether the = object is valid or not in __init__, and if not, I want the constructor to = return something other than an object, (like maybe None). I seem to be = having problems. At the end of __init__ I say (something like) = = if self.something minvalue: = del self = return None = = and it doesn't work. I first tried just the return None, then I got crafty = and tried the del self. Is what I'm trying to do possible in the = constructor or do I have to check after I return? Or would raising an = exception in the constructor be appropriate? = = Am I even being clear? = =The trouble you have is that it's too late by the time you get to =__init__. The object has been created. The reason that del self =doesn't work is that all it does is remove the local name self from =the namespace of the method - you will find that if __init__ returns =anything *except* None you get an exception. = =Don't think of __init__ as a constructor - that's __new__, which *is* =expected to return a newly-created instance. = =Raising an exception in __init__ is perfectly permissible, but adopting =the new-style classes (inheriting from object) might give you a more =efficient solution to your problem. Thanks Steve. I'm new but I do now understand that __init_ is an initializer and that new is a constructor. I don't understand your last sentence about new-style classes inheriting from an object. The object is question is mine and doesn't inherit from anything. Can you explain what you mean? Not an object but object, the root of all Python types. If you are very new you may not appreciate that Python currently implements two different class declaration mechanisms. The original classes, often now called classic classes, couldn't be used to subclass Python's built-in types because they formed an independent and parallel class hierarchy. Among other things the instances don't have an accessible __new__ method: class X: pass ... type(X) type 'classobj' At present the so-called new-style classes must specifically inherit from object (or, more correctly, must have a metaclass that is conformant with the protocol implemented by the type type, but the easiest way to do this is just to subclass object or one of the other built-in types): class X(object): pass ... type(X) type 'type' So, all I was saying is that you might prefer to implement your solution as a new-style class, since that gives you access to your class's instance creation mechanism through the __new__ method. __new__ doesn't *have* to return an instance of the class whose __new__ method is called, and this might allow you to return exactly what your application needs without having to handle exceptions at the application code level. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.co -- http://mail.python.org/mailman/listinfo/python-list
RE: Tutorial creates confusion about slices
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Antoon Pardon Sent: Monday, April 23, 2007 7:38 AM To: python-list@python.org Subject: Tutorial creates confusion about slices The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: HelpA[2:4]= lp But it give the wrong idea when using the following extended slice: HelpA[4:2:-1] = Ap So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. It makes sense if you recognize that the negative step value also flips which side the index is on. +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 -6 -5 -4 -3 -2 -1 --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: Do other Python GUI toolkits require this?
I had originally thought that learning PyObjC might preclude me from having to learn Objective-C, but that seems not to be the case. I have previously found the same to be true with PyQt and wxPython--not knowing the toolkits as they are implemented in C++ is a serious handicap. I've even found this to be the case with Tkinter: understanding the Tcl implementation of Tk (which I do, because I am also a Tcl developer) is a huge advantage. Am I wrong to conclude that, if you want to do GUI programming in Python, then some level of proficiency with another language is not just recommended, but almost required? This is the case at least in my experience. When I first started learning Python a couple of years ago, I spun my wheels with it for months, because I couldn't figure out where to get started with GUI programming. Finally I set Python aside and took up Tcl/Tk for awhile--its simplicity in building GUI's is more beginner-friendly. (No there's more than one way to do it--there's only one way to do it, and that's Tk.) Now, coming back to Python with the Tk model of GUI development burned in my brain, I appreciate the breadth of functions that Python supports--but I still find myself dropping down into Tcl (!) to assemble elements of my GUI's--either to write a Python wrapper, or figure out how to implement something in pure Python. I understand the argument for Python having lots of bindings to different GUI toolkits. If you are already proficient with a GUI toolkit in a compiled language (Gtk, wxWidgets, Cocoa, Qt) then presumably switching to Python will speed up your development--learning Python is easy if you already know C++, for instance, and usually the Python bindings are just a thin wrapper over the compiled bits. But if you come to Python from the other direction--you're a relative beginner and you want to learn GUI programming without the complexities of compiled languages--then it's a lot harder to get started, ironically. Even Tkinter is a challenge for someone who doesn't know Tcl. The basics are easy enough--buttons, menus, labels, images--but doing anything sophisticated, such as trees, column views, drag-and-drop, and so on, requires extensions that may or may not be implemented in Python. I personally can't conclude with your conclusions :) Some background: I've started with Tcl/Tk as a scripting language precisely because of Tk - I liked the easy GUI creation, the layout management, and it was available for Unix/Linux, my OS of choice. So when I discovered Python about 7 or 8 years ago, I certainly had the right mindset for Tk. So, I was able to create GUIs in Tkinter, yet it never felt very comfortable - it just has too much Tclisms in there for my taste. So for GUI-development, I moved on to Qt - and simply loved it. I do have some C++-skillz, although these are somewhat rusty. And all I needed them for was reading the excellent reference Qt-documentation. Just the class-docs, not examples! The last step then was PyObjC. I bought a mac roughly two years ago, and immediately got interested in GUI-development there. I've never done a single bit of ObjectiveC before, and even though I now have some few classes done (mainly for interfacing with parts of OS X or other libraries that weren't exposed to python, e.g. CIImage and CGImage processing), I wouldn't say that I'm an ObjectiveC-programmer. The hardships for me with PyObjc stemmed from the unawareness and unfamiliarity with the specifics of GUI-development under the mac in general. E.g. the concepts of NIBs, NIB-classes, bundles and the like. Now admittedly I'm not a totally fair comparison to you for judging the matters at hand - I had a fair amount of exposure to different languages before and while learning python. But especially for PyObjC I can say that I became productive pretty fast without having to actually do serious or even not so serious ObjectiveC-development. I'd rather say that using a gui-toolkit usually requires to adapt to whatever concepts that toolkit has implemented. And certainly there are some of these that are influenced by the language the toolkit has been developed for. But for example ObjectiveC and Python both allow for dynamic dispatch - thus lots of the design decisions would have been the same. And as ObjecC and Cocoa heavily rely on NSArray and NSDictionary, which the bridge has good marshalling code for, using python's lists dicts is natural and easy. In Qt OTOH they implemented their dynamic dispatch themselves - but using slots and signals is easy as cake as well. To me at least :) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: [re.finditer] Getting all occurences in one go?
On 22 Apr 2007 15:33:37 -0700, Paul Rubin http://[EMAIL PROTECTED] wrote: mytable[item] = ','.join(m.group(1) for m in matches) Thanks, that did it. -- http://mail.python.org/mailman/listinfo/python-list
Re: [SQLite] Recommended wrapper?
On Mon, 23 Apr 2007 16:03:05 +0200, Thomas Krüger [EMAIL PROTECTED] wrote: It's all there: http://docs.python.org/lib/module-sqlite3.html Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Learning Python - First Project
Hi, I am new to Python and am trying to write a little front end to another application in Python. What I want is to have a gui pop up listing some items with several buttons. The guts of the program I am not having any trouble with but the GUI part I am (or more accurately, the transition between GUI pieces). The first GUI that pops up lists some groups in a listbox and gives the user the choice to create a new group, open a group, rename the group, or delete the group. The new group and rename group buttons pop up a dialog gui asking for the name/new name. The Open Group is to open another GUI listing projects within that group in a list with similar options (New Project, Open Project, Rename Project, Delete Project). My question is, how should I create all these GUIs? Should each GUI be its own class with its own __init__? Then is the first GUI the root (how I have it set up now) and all other GUIs using Toplevel()? I hope this makes sense (because it only sort of makes sense in my head). THanks for any suggestions. -- http://mail.python.org/mailman/listinfo/python-list
Re: python style guide inconsistencies
Bjoern Schliessmann wrote: Darren Dale wrote: I was just searching for some guidance on how to name packages and modules, and discovered some inconsistencies on the www.python.org. http://www.python.org/doc/essays/styleguide.html says Module names can be either MixedCase or lowercase. That page also refers to PEP 8 at http://www.python.org/dev/peps/pep-0008/, which says Modules should have short, all-lowercase names. ... Python packages should also have short, all-lowercase names Which is most up to date? The priority is, IMHO, clear. The old style guide essay says, at the beginning: | This style guide has been converted to several PEPs (Python | Enhancement Proposals): PEP 8 for the main text, PEP 257 for | docstring conventions. See the PEP index. So PEP 8 is the most recent. Then perhaps http://www.python.org/doc/essays/styleguide.html should either be updated to either agree with or simply link to PEPs 8 and 257. What is the point of keeping old, out-of-date essays up on python.org? That beginning comment does not indicate that the essay is any different from the PEPs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Two syntax questions (newbie)
Diez B. Roggisch wrote: This is already better. Is it possible to define function composition as an operator and have something like ([EMAIL PROTECTED]@sorted)(items) or (list*reversed*sorted)(items) ? Not on functions, but on classes/instances. So something like this might work for you (untested): class FunctionComposer(object): def __init__(self, f=None): if f is None: f = lambda x: x self._f = f def __call__(self, *args, **kwargs): return self._f(*args, **kwargs) def __mul__(self, other): def combined(*args, **kwargs): return other(self._f(*args, **kwargs)) return FunctionComposer(combined) fc = FunctionComposer Then you can write (fc() * list * reversed * sorted)(items) A clever little hack, but please don't do this. Anyone else who will read your code will thank you. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
On 2007-04-21, Steven D'Aprano [EMAIL PROTECTED] wrote: On Fri, 20 Apr 2007 15:36:00 -0700, [EMAIL PROTECTED] wrote: The article explains that, amongst other things, tuples are faster than lists, so if you are working with constant values (inmutables) they are more indicated than lists. Thanks. I thought Python's design wasn't so concerned with optimizations. Adding a new type just for optimization reasons seems perhaps unnecessary. I could be wrong. It's times like this I want to cry... adict = {(1,2): parrot} Try replacing that tuple with a list. Just optimization my eye! So the question becomes: Why do Python dictionaries require keys to be of an immutable type? -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
On 23 Apr 2007 17:19:15 +0200, Neil Cerutti [EMAIL PROTECTED] wrote: So the question becomes: Why do Python dictionaries require keys to be of an immutable type? Dictionary keys are hashed values. If you change the key, you change the hash and lose the pointer to the referenced object. Or: Because. ;-) Chris -- A little government and a little luck are necessary in life, but only a fool trusts either of them. -- P. J. O'Rourke -- http://mail.python.org/mailman/listinfo/python-list
Re: python style guide inconsistencies
On Apr 22, 8:27 pm, Darren Dale [EMAIL PROTECTED] wrote: I was just searching for some guidance on how to name packages and modules, and discovered some inconsistencies on thewww.python.org.http://www.python.org/doc/essays/styleguide.htmlsays Module names can be either MixedCase or lowercase. That page also refers to PEP 8 athttp://www.python.org/dev/peps/pep-0008/, which says Modules should have short, all-lowercase names. ... Python packages should also have short, all-lowercase names Which is most up to date? Is this the right place to point out that one of those pages needs to be updated? Thanks, Darren In addition to the other replies on your direct question, it is also not a good idea to have modules whose names only differ by case. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
On 2007-04-23, Chris Cioffi [EMAIL PROTECTED] wrote: On 23 Apr 2007 17:19:15 +0200, Neil Cerutti [EMAIL PROTECTED] wrote: So the question becomes: Why do Python dictionaries require keys to be of an immutable type? Dictionary keys are hashed values. If you change the key, you change the hash and lose the pointer to the referenced object. Other dictionary-like implementations (C++ std::map for example) simply exhort you not to change keys (C++ makes it hard to ignore the exhortation) or suffer undefined behavior. Perhaps avoiding a cause of undefined behavior was the Python reason for the requirement. Or: Because. ;-) Heh, heh. I was wondering, if we dig deep enough, wether we'll end up back at, just an optimization, as the reason. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
numpy migration (also posted to numpy-discussion)
Hello, Since moving to numpy I've had a few problems with my existing code. It basically revolves around the numpy scalar types. e.g. import Numeric as N a = N.array([[0,1],[2,3]]) a array([[0, 1], [2, 3]]) i = a[0,0] 1/i Traceback (most recent call last): File pyshell#30, line 1, in -toplevel- 1/i ZeroDivisionError: integer division or modulo by zero b = a * 1.5 b array([[ 0. , 1.5], [ 3. , 4.5]]) N.floor(b) array([[ 0., 1.], [ 3., 4.]]) RESTART import numpy as N a = N.array([[0,1],[2,3]]) a array([[0, 1], [2, 3]]) i = a[0,0] 1/i 0 b = a * 1.5 b array([[ 0. , 1.5], [ 3. , 4.5]]) N.floor(b) array([[ 0., 1.], [ 3., 4.]]) a = N.array([[0,1],[2,3]], dtype='O') a array([[0, 1], [2, 3]], dtype=object) i = a[0,0] 1/i Traceback (most recent call last): File pyshell#45, line 1, in -toplevel- 1/i ZeroDivisionError: integer division or modulo by zero b = a * 1.5 b array([[0.0, 1.5], [3.0, 4.5]], dtype=object) N.floor(b) Traceback (most recent call last): File pyshell#48, line 1, in -toplevel- N.floor(b) AttributeError: 'float' object has no attribute 'floor' -- An additional problem involves classes that have e.g. __rmul__ methods defined and are sufficiently similar to numpy arrays that my classes' __rmul__ methods are not invoked when using numpy scalars. Using the 'O' dtype gives me Python types that raise zero division errors appropriately (for my code) and the desired calls to e.g. __rmul__ methods, but reduced functionality in other repects. I might (I hope) be missing something obvious; but it seems like, to be safe, I'm going to have to do a lot of explicit conversions to Python types (or abandon catching zero division errors, and documenting some of my classes to highlight that whether scalar * a equals a * scalar depends on whether a.__rmul__ is called, which depends on the type of scalar). I suppose I might get round both issues by subclassing existing numpy dtypes. Any ideas? Cheers. TIA. Duncan -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
En Mon, 23 Apr 2007 12:46:13 -0300, Neil Cerutti [EMAIL PROTECTED] escribió: On 2007-04-23, Chris Cioffi [EMAIL PROTECTED] wrote: On 23 Apr 2007 17:19:15 +0200, Neil Cerutti [EMAIL PROTECTED] wrote: So the question becomes: Why do Python dictionaries require keys to be of an immutable type? Or: Because. ;-) Heh, heh. I was wondering, if we dig deep enough, wether we'll end up back at, just an optimization, as the reason. Fortran guys could make programs for a long time having arrays as their ONLY structured type, so having a built in dictionary is not just an optimization, it's a luxury! :) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Apr 23)
QOTW: The users. - Ali, answering a question on what's special about Emacs. Dynamic languages look at WSDL and shrug - another example of the hoops that static typing forces humans to go through. - Gordon Weakliem http://lists.community.tummy.com/pipermail/frpythoneers/2007-April/001342.html The current issue of the rather prestigious *Computing in Science and Engineering* journal is devoted to Python (!): http://csdl2.computer.org/persagen/DLAbsToc.jsp?resourcePath=/dl/mags/cs/toc=comp/mags/cs/2007/03/c3toc.xml Python is just as capable--and more!--as JavaScript, VBScript, ... for controlling COM. Here's a little chatter on expression of Array data: http://groups.google.com/group/comp.lang.python/browse_thread/thread/af1a19a4e3541060/ Despite Python-URL!'s habitual ... reserve about regular expressions, there *are* places they fit perfectly. Steven Bethard and Peter Otten show off how good a simple RE can be: http://groups.google.com/group/comp.lang.python/browse_thread/thread/870b46f0e4bc02c6/ Python 2.5.1 is the first bugfix release of Python 2.5: http://groups.google.com/group/comp.lang.python/msg/2e58fab5387e1b77 Michael Hoffman correctly explains the so-often-misunderstood semantics of '*' (for example) in subprocess invocations. Notice use of the little-known expanduser(), expandvars(), and check_call(): http://groups.google.com/group/comp.lang.python/msg/639cc8af04a91595 Carsten Haese supplies a model for construction in Python of a VB/Delphi iterator: http://groups.google.com/group/comp.lang.python/msg/557e1358aa92c5d3 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, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ The Python Papers aims to publish the efforts of Python enthusiats. http://pythonpapers.org/ Readers have recommended the Planet sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher 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 Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. 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
Redirection problem
I am new to python. so be patient with me I am trying to redirect the output of os.popen command to a file. I want to append to that file. but instead of appending. The file only shows last command that was writtenn to it. filehandle= open(/root/yhpc-2.0/installer/yhpc-log ,a+); filehandle.write( Command executed is + cmd); try: pipe= os.popen('%s /root/yhpc-2.0/installer/yhpc-log' %cmd ); except : IOError; filehandle.close(); Any suggestion would help. filehandle.close(); -- http://mail.python.org/mailman/listinfo/python-list
Re: Can __init__ not return an object?
On Apr 22, 4:36 am, Steven W. Orr [EMAIL PROTECTED] wrote: When I go to create an object I want to be able to decide whether the object is valid or not in __init__, and if not, I want the constructor to return something other than an object, (like maybe None). I seem to be having problems. At the end of __init__ I say (something like) if self.something minvalue: del self return None and it doesn't work. I first tried just the return None, then I got crafty and tried the del self. Is what I'm trying to do possible in the constructor or do I have to check after I return? Or would raising an exception in the constructor be appropriate? You can raise an exception of course but it would just create a side effect. Another way to achieve what you request for is manipulating the class creation mechanism. class A(object): def __new__(cls, x): if x == 0: return None obj = object.__new__(cls) obj.__init__(x) return obj class B(A): def __init__(self, x): self.x = x The condition can always be checked within the static __new__ method. Kay -- http://mail.python.org/mailman/listinfo/python-list
Generate report containing pdf or ps figures?
I need to be able to generate a PDF report which consists mostly of vector images (which I can generate as encapsulated Postscript, PDF, or SVG). What I need is a way to combine these figures into a single PDF document. Right now the reports consist entire of these figures, so I just write the figures out to temp files and then use os.system() to run ghostscript with appropriate options to combine them into a single PDF file. I'd like to be able to add some text and/or place the figures in a manner other than one per page in the output document. I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? -- Grant Edwards grante Yow! Is a tattoo real, like at a curb or a battleship? visi.comOr are we suffering in Safeway? -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
Steven W. Orr wrote: On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: =Chris Lasher wrote: = Should a Python module not intended to be executed have shebang/ = hashbang (e.g., #!/usr/bin/env python) or not? I'm used to having a = shebang in every .py file but I recently heard someone argue that = shebangs were only appropriate for Python code intended to be = executable (i.e., run from the command line). = =Personally I include it in all of them, as part of boilerplate in a =template. I'd recommend againt it. The shebang doesn't do you any good unless it's also in the presence of a file that has its executable bit set. It doesn't do any bad either, so I don't understand why you would recommend against it. And the bash function I use to create new files from the template also does chmod a+x. Not to mention that I have emacs set such that things with shebangs at the top are automatically chmod a+x, so in my programming environment, having a shebang on files I create and being executable are one and the same. For example, let's leave python out for a second: I have a shell script. And I also have lots of files which are not intended to be executed which are also shell scripts, but which are sucked in by the shell . or source command (which is *somewhat* analogous to python's import). Lots of these shell library scripts can't execute as standalone. The same thing is possible with pything scripts. Of course, anything that has if __name__ == __main__: in it should always have a shebang and be executable. That's in my template as well. :) I try to write all my modules so that they can easily be adapted to run as scripts, and all my scripts so that they can easily be adapted to use as modules. This has served me well many, many times. I see no reasons to create an artificial barrier to doing this by leaving the shebang out of files where it has no ill effect. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: python style guide inconsistencies
Darren Dale wrote: Bjoern Schliessmann wrote: Darren Dale wrote: I was just searching for some guidance on how to name packages and modules, and discovered some inconsistencies on the www.python.org. http://www.python.org/doc/essays/styleguide.html says Module names can be either MixedCase or lowercase. That page also refers to PEP 8 at http://www.python.org/dev/peps/pep-0008/, which says Modules should have short, all-lowercase names. ... Python packages should also have short, all-lowercase names Which is most up to date? The priority is, IMHO, clear. The old style guide essay says, at the beginning: | This style guide has been converted to several PEPs (Python | Enhancement Proposals): PEP 8 for the main text, PEP 257 for | docstring conventions. See the PEP index. So PEP 8 is the most recent. Then perhaps http://www.python.org/doc/essays/styleguide.html should either be updated to either agree with or simply link to PEPs 8 and 257. What is the point of keeping old, out-of-date essays up on python.org? That beginning comment does not indicate that the essay is any different from the PEPs. http://wiki.python.org/moin/PythonWebsiteCreatingNewTickets -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib basic question
Pete Forman wrote: Robert Kern [EMAIL PROTECTED] writes: Colin J. Williams wrote: I'm not sure that scipy has been updated to Python 2.5 ? scipy certainly works with 2.5. Are you referring to something else perhaps? Yes, the Python Enthought Edition was being discussed and it is currently based on Python 2.4.3. http://code.enthought.com/enthon/ I'm quite familiar with Python Enthought Edition as I work at Enthought. I was confused because Colin referenced scipy specifically rather than simply saying that the current version of Python Enthought Edition was not based on 2.5. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirection problem
En Mon, 23 Apr 2007 13:10:55 -0300, CSUIDL PROGRAMMEr [EMAIL PROTECTED] escribió: I am new to python. so be patient with me I am trying to redirect the output of os.popen command to a file. I want to append to that file. but instead of appending. The file only shows last command that was writtenn to it. filehandle= open(/root/yhpc-2.0/installer/yhpc-log ,a+); filehandle.write( Command executed is + cmd); try: pipe= os.popen('%s /root/yhpc-2.0/installer/yhpc-log' %cmd ); except : IOError; filehandle.close(); There are two ways to redirect the output: - using the shell, with and - using popen You are mixing both here. Your command line uses xxx-log, thus efectively overwriting any previous content on the log file. You could do this: logfile = open(, a+) logfile.write(Command: %s\n % cmd) pipe = os.popen(cmd) for line in pipe: logfile.write(line) pipe.close() logfile.close() Or try the subprocess module. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
In article [EMAIL PROTECTED], Gabriel Genellina [EMAIL PROTECTED] wrote: En Mon, 23 Apr 2007 04:33:22 -0300, Ron Garret [EMAIL PROTECTED] escribió: I have not been able to find a proxy server that can proxy to unix sockets, so I need to write my own. Conceptually its a very simple thing: read the first line of an HTTP request, parse it with a regexp to extract the sandbox name, connect to the appropriate unix server socket, and then bidirectionally pipe bytes back and forth. But it has to do this for multiple connections simultaneously, which is why I need select. No. This is what the *server* should do, not the *handler*. The server listens on incoming requests, and creates a new handler for each one. Inside a handler, you don't have to worry about multiple connections. If you want to process simultaneous connections, inherit your server from ThreadingMixIn or ForkingMixIn (or use one of the predefined server classes). Ah, good point. But that still leaves the problem of keep-alive connections. I still need to be able to forward data in both directions without knowing ahead of time when it will arrive. (I think I can solve the problem by using send and recv directly BTW.) rg -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirection problem
On Apr 23, 9:10 am, CSUIDL PROGRAMMEr [EMAIL PROTECTED] wrote: I am new to python. so be patient with me I am trying to redirect the output of os.popen command to a file. I want to append to that file. but instead of appending. The file only shows last command that was writtenn to it. filehandle= open(/root/yhpc-2.0/installer/yhpc-log ,a+); filehandle.write( Command executed is + cmd); try: pipe= os.popen('%s /root/yhpc-2.0/installer/yhpc-log' %cmd ); except : IOError; filehandle.close(); Any suggestion would help. filehandle.close(); This works. f = open(test, 'a') stdout = os.popen(ls -l /) f.write(stdout.read()) f.close() ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
In article [EMAIL PROTECTED], Jean-Paul Calderone [EMAIL PROTECTED] wrote: Twisted does this out of the box, for what it's worth. Thanks. I will look at that. rg -- http://mail.python.org/mailman/listinfo/python-list
pyserial ... timeout on write
Hi, I notice that pyserial will hang on a write (even with timeout on) if rts/cts are one. Anyway to get around that ? Thanks hg -- http://mail.python.org/mailman/listinfo/python-list
Re: pyserial ... timeout on write
hg wrote: Hi, I notice that pyserial will hang on a write (even with timeout on) if rts/cts are one. Anyway to get around that ? Thanks hg PS: on windows -- http://mail.python.org/mailman/listinfo/python-list
Re: wx.TextCtrl.SetDefaultStyle not working?
On my platform, styling the text doesn't work for single line TextCtrl's(which seems kind of stupid), and on Windows I think you are required to specify wx.TE_RICH2 to style the text. This following code colors the entered text red for me: That's it! I didn't have the TE_RICH2 option set. It works now. The docs say it's Windows only. Does the GTK version work without this flag? -- Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: Select weirdness
In article [EMAIL PROTECTED], Ron Garret [EMAIL PROTECTED] wrote: The answer is obvious: select is looking only at the underlying socket, and not at the rfile buffers. So... is this a bug in select? Or a bug in my code? Yes. I don't see any specific followup to this point, but it is or at least should be a well known limitation of C library I/O and select. select() is an operating system function that has no way to know the state of your process I/O buffers, nor do the C stdio buffers don't come with a standard way to inspect that state. Therefore, if you mix C I/O with select(), you're more or less out of luck. This applies directly to Python, because it calls the operating system select() function and it uses C stdio buffers for its file object (and entices you to make this mistake by supporting a file object as an input to select().) This conflict can be relieved after a fashion by eliminating the buffer. The now unbuffered C fgets / Python readline won't store extra lines that select can't see, but the semantics of the operation are still a poor fit with the usual application of select. The number of system-level I/O calls is significantly greater as you transfer data one byte at a time, which may add a lot of overhead if you transfer a lot of data, and your readline() function still can't return until it gets that '\n', so a half line can block your application. It isn't a lot of work to read data with operating system functions that are compatible with select - os.read(), socket.recv() - and break it up into lines on your own, and this completely and efficiently resolves the problem. I haven't looked at your code. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket exceptions aren't in the standard exception hierarchy
Dennis Lee Bieber wrote: On Sun, 22 Apr 2007 23:20:25 -0700, John Nagle [EMAIL PROTECTED] declaimed the following in comp.lang.python: 2. File D:\Python24\lib\socket.py, line 295, in read data = self._sock.recv(recv_size) error: (10054, 'Connection reset by peer') That looks like M$ Windows version of UNIX/Linux error number 54 (pretty much all Windows socket errors are UNIX number+1) Errors coming from Windows may not be mapped to specific Python exceptions, but rather to some general error conditions. {hypothesis} As such, the Windows errors may not match what UNIX/Linux report. Actually, that's not what's happening. The socket module is explicitly raising socket.error in C code. It's not an OSError or a WindowsError, although the text makes it look like one. The problem is not that socket errors aren't entirely portable. It's that they're not even in the Python exception hierarchy. See http://docs.python.org/lib/module-exceptions.html;. They have their own hierarchy, which starts at socket.error. All built-in exceptions were supposed to be converted to the standard exception hierarchy back before Python 2.0, but these weren't. Either they should be under IOError, or there should be NetworkError under EnvironmentError, and they should be under that. NetworkError, alongside IOError in the hierarchy, would be useful. All the things that go wrong in networking belong under there. Socket-level errors, SSL/TLS-level errors, and HTTP/FTP/etc. level errors all belong under NetworkError. This has to be fixed before PEP 352, when the exception hierarchy is enforced, or the socket exceptions won't even work right. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
Neil Cerutti wrote: On 2007-04-21, Steven D'Aprano [EMAIL PROTECTED] wrote: On Fri, 20 Apr 2007 15:36:00 -0700, [EMAIL PROTECTED] wrote: The article explains that, amongst other things, tuples are faster than lists, so if you are working with constant values (inmutables) they are more indicated than lists. Thanks. I thought Python's design wasn't so concerned with optimizations. Adding a new type just for optimization reasons seems perhaps unnecessary. I could be wrong. It's times like this I want to cry... adict = {(1,2): parrot} Try replacing that tuple with a list. Just optimization my eye! So the question becomes: Why do Python dictionaries require keys to be of an immutable type? Because otherwise people would expect to be able to use a list to select a dictionary entry even after they'd modified elements of the list after creating the dictionary entry. Which they couldn't. So Python doesn't let them use lists. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's handling of unicode surrogates
Ross Ridge writes: The Unicode standard doesn't require that you support surrogates, or any other kind of character, so no you wouldn't be lying. [EMAIL PROTECTED] wrote: There is the notion of Unicode implementation levels, and each of them does include a set of characters to support. There are different levels of implemtentation for ISO 10646, but not of Unicode. It is probably an interpretation issue what supported means. The strongest claim to support Unicode that you can meaningfully make is that of conformance to the Unicode standard. The Unicode standard's conformance requirements make it explicit that you don't need to support any particular character: C8 A process shall not assume that it is required to interpret any particular coded character representation. . Processes that interpret only a subset of Unicode characters are allowed; there is no blanket requirement to interpret all Unicode characters. [...] Python clearly supports Unicode level 1 (if we leave alone the issue that it can't render all these characters out of the box, as it doesn't ship any fonts); It's not at all clear to to me that Python does support ISO 10646's implementation level 1, if only because I don't, and I assume you don't, have a copy of ISO 10646 available to verify what the requirements actually are. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] [EMAIL PROTECTED] -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
Michael Hoffman wrote: Steven W. Orr wrote: On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: =Chris Lasher wrote: = Should a Python module not intended to be executed have shebang/ = hashbang (e.g., #!/usr/bin/env python) or not? I'm used to having a = shebang in every .py file but I recently heard someone argue that = shebangs were only appropriate for Python code intended to be = executable (i.e., run from the command line). = =Personally I include it in all of them, as part of boilerplate in a =template. I'd recommend againt it. The shebang doesn't do you any good unless it's also in the presence of a file that has its executable bit set. It doesn't do any bad either, so I don't understand why you would recommend against it. And the bash function I use to create new files from the template also does chmod a+x. Not to mention that I have emacs set such that things with shebangs at the top are automatically chmod a+x, so in my programming environment, having a shebang on files I create and being executable are one and the same. For example, let's leave python out for a second: I have a shell script. And I also have lots of files which are not intended to be executed which are also shell scripts, but which are sucked in by the shell . or source command (which is *somewhat* analogous to python's import). Lots of these shell library scripts can't execute as standalone. The same thing is possible with pything scripts. Of course, anything that has if __name__ == __main__: in it should always have a shebang and be executable. That's in my template as well. :) I try to write all my modules so that they can easily be adapted to run as scripts, and all my scripts so that they can easily be adapted to use as modules. This has served me well many, many times. I see no reasons to create an artificial barrier to doing this by leaving the shebang out of files where it has no ill effect. If you ever create a module that *shouldn't be run you can always put if __name__ == __main__: print Do not run this script: it is a module for import only at the end of it. But what's the point? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
On Apr 23, 6:30 pm, Grant Edwards [EMAIL PROTECTED] wrote: I need to be able to generate a PDF report which consists mostly of vector images (which I can generate as encapsulated Postscript, PDF, or SVG). What I need is a way to combine these figures into a single PDF document. Right now the reports consist entire of these figures, so I just write the figures out to temp files and then use os.system() to run ghostscript with appropriate options to combine them into a single PDF file. I'd like to be able to add some text and/or place the figures in a manner other than one per page in the output document. I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? If you are familiar with LaTeX, an easy solution would be to automatically generate a LaTeX document that includes your images. This also allows you to add captions, scale the images and much more. You can then run the generated document through pdflatex and you have a nice looking report. Regards, Kjell Magne Fauske http://www.fauskes.net -- http://mail.python.org/mailman/listinfo/python-list
Re: python style guide inconsistencies
Darren Dale [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Then perhaps http://www.python.org/doc/essays/styleguide.html should either | be updated to either agree with or simply link to PEPs 8 and 257. What is | the point of keeping old, out-of-date essays up on python.org? Now that Guido has agreed with you (on pydev), wait a couple of days, if there is no response from one of webmasters, go to this page, click update suggestion link at bottom, and cut and paste his posting. No need for further discussion here. Thanks for following this thru. Persistence is how docs get improved. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?
On 2007-04-23, Steve Holden [EMAIL PROTECTED] wrote: Neil Cerutti wrote: So the question becomes: Why do Python dictionaries require keys to be of an immutable type? Because otherwise people would expect to be able to use a list to select a dictionary entry even after they'd modified elements of the list after creating the dictionary entry. Which they couldn't. So Python doesn't let them use lists. The interpreter explains it: A list is not a hashable object. Choosing a hash table instead of some kind of balanced tree seems to be just an optimization. ;) -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - First Project
On Apr 23, 9:52 am, KDawg44 [EMAIL PROTECTED] wrote: Hi, I am new to Python and am trying to write a little front end to another application in Python. What I want is to have a gui pop up listing some items with several buttons. The guts of the program I am not having any trouble with but the GUI part I am (or more accurately, the transition between GUI pieces). The first GUI that pops up lists some groups in a listbox and gives the user the choice to create a new group, open a group, rename the group, or delete the group. The new group and rename group buttons pop up a dialog gui asking for the name/new name. The Open Group is to open another GUI listing projects within that group in a list with similar options (New Project, Open Project, Rename Project, Delete Project). My question is, how should I create all these GUIs? Should each GUI be its own class with its own __init__? Then is the first GUI the root (how I have it set up now) and all other GUIs using Toplevel()? I hope this makes sense (because it only sort of makes sense in my head). THanks for any suggestions. Hi, You should be able to create one main window as root and use standard dialogs for the dialogs you mentioned. As for the Open Group button, you might use a tree widget instead of opening another window. You could put the tree in a splitter window or something and it might look nicer. Of course, you can do another window, but it would be a custom, hand-coded window and NOT a standard dialog. That would mean that it would indeed be another class with its own __init__. You can set both the standard dialogs and your custom one to ShowModal and then you shouldn't need to use Toplevel(). I am assuming you are using Tkinter for your front-end GUI. You might also take a gander at wxPython. It has an excellent demo you could download and it might give you some additional ideas for implementation: www.wxpython.org . Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket exceptions aren't in the standard exception hierarchy
John Nagle wrote: Dennis Lee Bieber wrote: On Sun, 22 Apr 2007 23:20:25 -0700, John Nagle [EMAIL PROTECTED] declaimed the following in comp.lang.python: 2. File D:\Python24\lib\socket.py, line 295, in read data = self._sock.recv(recv_size) error: (10054, 'Connection reset by peer') That looks like M$ Windows version of UNIX/Linux error number 54 (pretty much all Windows socket errors are UNIX number+1) Errors coming from Windows may not be mapped to specific Python exceptions, but rather to some general error conditions. {hypothesis} As such, the Windows errors may not match what UNIX/Linux report. Actually, that's not what's happening. The socket module is explicitly raising socket.error in C code. It's not an OSError or a WindowsError, although the text makes it look like one. The problem is not that socket errors aren't entirely portable. It's that they're not even in the Python exception hierarchy. See http://docs.python.org/lib/module-exceptions.html;. They have their own hierarchy, which starts at socket.error. All built-in exceptions were supposed to be converted to the standard exception hierarchy back before Python 2.0, but these weren't. Either they should be under IOError, or there should be NetworkError under EnvironmentError, and they should be under that. NetworkError, alongside IOError in the hierarchy, would be useful. All the things that go wrong in networking belong under there. Socket-level errors, SSL/TLS-level errors, and HTTP/FTP/etc. level errors all belong under NetworkError. This has to be fixed before PEP 352, when the exception hierarchy is enforced, or the socket exceptions won't even work right. John: Where did you get this information? If true it would certainly need to be logged as a bug, but under Windows on 2,4 I see issubclass(socket.gaierror, Exception) True and the same under Cygwin 2.5. I am presuming most other users will see the same thing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - First Project
On Apr 23, 9:52 am, KDawg44 [EMAIL PROTECTED] wrote: Hi, I am new to Python and am trying to write a little front end to another application in Python. What I want is to have a gui pop up listing some items with several buttons. The guts of the program I am not having any trouble with but the GUI part I am (or more accurately, the transition between GUI pieces). The first GUI that pops up lists some groups in a listbox and gives the user the choice to create a new group, open a group, rename the group, or delete the group. The new group and rename group buttons pop up a dialog gui asking for the name/new name. The Open Group is to open another GUI listing projects within that group in a list with similar options (New Project, Open Project, Rename Project, Delete Project). My question is, how should I create all these GUIs? Should each GUI be its own class with its own __init__? Then is the first GUI the root (how I have it set up now) and all other GUIs using Toplevel()? I hope this makes sense (because it only sort of makes sense in my head). THanks for any suggestions. I am assuming you are using Tkinter for your GUI front-end. You should be able to just use standard dialog boxes for your new group and rename group dialogs and a custom hand-coded dialog for the other one. All three can be called with ShowModal() instead of Toplevel(). And yes, the custom dialog would work best if you made it into a separate class. You could also put that information for the GUI that list projects into a tree widget of some sort, maybe with a splitter window. I haven't had much luck with Tkinter's tree widgets though. PMW and Tix both have rather poor docs unless you enjoy man pages. You might check out wxPython instead. It has an excellent demo that is very good at showing you not only what all it can do, but how it is done: www.wxpython.org. Good luck! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
On 2007-04-23, Kjell Magne Fauske [EMAIL PROTECTED] wrote: Is there a PDF generation library that can place EPS or PDF figures on a page? If you are familiar with LaTeX, an easy solution would be to automatically generate a LaTeX document that includes your images. Yea, I've been using TeX and LaTeX for 20+ years. :) I worked on a DoD project back in the 80's where we generated a 1000+ page requirements spec using LaTeX. It had to be broken up into a few dozen separate documents because LaTeX under VAX/VMS kept overflowing various internal counters. Doing a build of the document kept a VAX 780 busy most of the night. However, bundling a working copy of LaTeX with my Python app doesn't fall into the easy category. This app needs to be moderately cross-platform and distributable. Using either LaTeX or Ghostscript (my current solution) makes it rather painful to bundle up the app and distrubute it. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
On Apr 23, 9:30 am, Grant Edwards [EMAIL PROTECTED] wrote: I need to be able to generate a PDF report which consists mostly of vector images (which I can generate as encapsulated Postscript, PDF, or SVG). What I need is a way to combine these figures into a single PDF document. Right now the reports consist entire of these figures, so I just write the figures out to temp files and then use os.system() to run ghostscript with appropriate options to combine them into a single PDF file. I'd like to be able to add some text and/or place the figures in a manner other than one per page in the output document. I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? -- Grant Edwards grante Yow! Is a tattoo real, like at a curb or a battleship? visi.comOr are we suffering in Safeway? On a Mac... http://developer.apple.com/graphicsimaging/pythonandquartz.html ~Sean -- http://mail.python.org/mailman/listinfo/python-list
tftpy 0.41 errors
When trying to import the tftpy package, I've gotten the following error messages: Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type help, copyright, credits or license for more information. import tftpy Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/site-packages/tftpy/__init__.py, line 18, in ? from TftpServer import * File /usr/lib/python2.4/site-packages/tftpy/TftpServer.py, line 50 % (listenip if listenip else '0.0.0.0', listenport)) ^ SyntaxError: invalid syntax What am I missing? Any pointer is much appreciated. I installed the tftpy package using the standard command line: sudo python setup.py install -- http://mail.python.org/mailman/listinfo/python-list
Re: tftpy 0.41 errors
On Mon, 2007-04-23 at 12:17 -0700, [EMAIL PROTECTED] wrote: When trying to import the tftpy package, I've gotten the following error messages: Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type help, copyright, credits or license for more information. import tftpy Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/site-packages/tftpy/__init__.py, line 18, in ? from TftpServer import * File /usr/lib/python2.4/site-packages/tftpy/TftpServer.py, line 50 % (listenip if listenip else '0.0.0.0', listenport)) That if-else expression is Python 2.5 syntax. Apparently the tftpy package gave you false hope by erroneously allowing you to install it as a Python 2.4 package. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
On Apr 23, 9:30 am, Grant Edwards [EMAIL PROTECTED] wrote: I need to be able to generate a PDF report which consists mostly of vector images (which I can generate as encapsulated Postscript, PDF, or SVG). What I need is a way to combine these figures into a single PDF document. Right now the reports consist entire of these figures, so I just write the figures out to temp files and then use os.system() to run ghostscript with appropriate options to combine them into a single PDF file. I'd like to be able to add some text and/or place the figures in a manner other than one per page in the output document. I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? I've had great success using Apache's FOP utility (http:// xmlgraphics.apache.org/fop) to generate PDFs out of XSL-FO, which can contain SVG graphics (at least the 0.20.5 version can, the newer rewrite version doesn't yet). FOP is a java library but has a suitable command line interface. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
On 2007-04-23, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? On a Mac... http://developer.apple.com/graphicsimaging/pythonandquartz.html Something that's easy to do and builtin to MacOS that's painful or difficult to do under Windows? Nah, couldn't be... -- Grant Edwards grante Yow! Kids, don't gross me at off ... Adventures with visi.comMENTAL HYGIENE can be carried too FAR! -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate report containing pdf or ps figures?
On 2007-04-23, infidel [EMAIL PROTECTED] wrote: I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? I've had great success using Apache's FOP utility (http:// xmlgraphics.apache.org/fop) to generate PDFs out of XSL-FO, which can contain SVG graphics (at least the 0.20.5 version can, the newer rewrite version doesn't yet). FOP is a java library but has a suitable command line interface. Unfortunately, trying to bundle a Java installation with my app is going to be harder than bundling Ghostscript or LaTeX (the other two solutions that come to mind). I should have mentioned it in my OP, but I need something that's cross-platform (At least Linux and Windows), and not difficult to bundle using something like py2exe. -- Grant Edwards grante Yow! I'm totally DESPONDENT at over the LIBYAN situation visi.comand the price of CHICKEN ... -- http://mail.python.org/mailman/listinfo/python-list