Re: Transforming a str to an operator
I would use the following approach: Abviously the OP is a python baby noob and casting your irrational fear (and many others irrational fears) of eval at him is akin to tales of Chupacabras running a muck in the jungle sucking the blood from live goats in the twilight hours. I use eval all the time and quite love it. Yes, the OP is clearly a newbie to the language and probably programming in general, but that response is nonsense. It's a perfect example of a false analogy. Chupacabras are superstition, baseless fear-mongering. eval() is a very real dangerous construct. There is absolutely nothing irrational about the unsafe nature of eval. It is a tool: it is a useful tool if one knows how to use it, but is a tool that you'll slam into your thumb and break it if you don't know how. When there are tools available which address the same problem without those dangers, newbies should be exposed to THOSE first. This is nothing more than a throw away academic exercise that will serve no useful purpose for him in the future, but serves the very useful purpose now of establishing an IO between the student and Python interpretor. I'll bet most your example (albeit a good example) flew miles above his head into la-la land. I prefer not to assume newbies are stupid; if they don't understand a part of a correct explanation that's given, they can ask for clarification and further details can be given. True, this is a very Python-specific correct example to this basic problem, with dictionary dispatch which is a very Pythonic idiom that might be a bit too much for a newbie to programming in general: if that's the case, the correct thing to show the newbie would be: if op == +: print The result is:, int(num1) + int(num2) elif op == -: print The result is:, int(num1) - int(num2) ..etc. Exposing newbies to eval() is simply irresponsible. It is not an irrational fear: eval has a purpose and it is useful and it's fine to use, IF you understand the language and implications enough to use it. If you don't, if you're a newbie to programming entirely, it is good sense and a benefit to the newbie to steer the person away from something that will get them in trouble down the road. If they're not ready to deal with input sanitization, that's fine... but exposing them to dangerous practices when there's clear and logical alternate approaches is fool-hearty. The OP has plenty of time to learn about malicious input and protecting against it, right now the fundamentals are well... fundamental :) eval is simply NOT a fundamental. It should be considered an advanced feature, for advanced usage; that it seems simple is all the more dangerous. No one should be taught from an early stage that 'this is how to address a problem', only to then teach them later, 'Oh, by the way, that thing I taught you? It's bad in most cases and you shouldn't do it again'. --S -- http://mail.python.org/mailman/listinfo/python-list
Re: Move dictionary from instance to class level
Dave Angel wrote: OK, that makes good sense. And I withdraw any suggestion to use pickling, since that could be subject to hacking. It now appears that the messages are only incidentally GUI events. And that you would be well advised to make every possible event a separate message, so that if the server state and the client state get out of synch, you can readily check and reject such operations. For example, you'd have a message for pressing the SUBMIT button on a particular form, but you'd have different message types for other buttons on the same form, or for SUBMIT on other forms. I use the same message type for all SUBMITs, but the body of the message contains a unique id for each button. When the server constructs the form, it assigns a unique id to each widget, and includes this id in the form definition it sends to the client. Therefore the server and client can unambiguously reference specific widgets, and there is no real danger of getting out of sync. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
Esam Qanadeely wrote: .NET= i meant all .NET languages What? You mean like Python? ;-) Google IronPython ya troll... Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python advanced features
Bruno Desthuilliers a écrit : jvpic a écrit : Hi, Learning Python, I understand the mechanism of : closure, __new__, descriptors, decorators and __metaclass__, but I interrogate myself on the interest of those technics ? May somebody explain me the interest ? Didn't like my answers on f.c.l.py ?-) Si, mais je voulais savoir ce qu'on en pense sur un autre forum ! Merci encore... -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
2009/8/28 John Machin sjmac...@lexicon.net: Mark, there exist parallel universes the denizens of which use strange notation e.g. 1.234,56 instead of 1,234.56 When displaying data, sure. and would you believe they use ';' instead of ',' as a list separator ... CSV is a data transfer format, not a display format. Locale specific stuff like this has no place in it. Dates, IMHO, should be in the ugly but unambiguous ISO 8601 format in a CSV. It's for import and export, not for looking pretty. Besides - CSV; the clue's in the name. ;-) Excel perfidiously gives them what they expect rather than forcing them to comply with The One True Way. When people export to a comma separated value file, they are almost certainly expecting a file containing values separated by comas. If Excel isn't giving them this by default, it's broken. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: List iterator thread safety
On Thursday 27 August 2009 16:50:16 Carl Banks wrote: On Aug 27, 7:25 am, Hendrik van Rooyen hend...@microcorp.co.za wrote: Its not too bad - if you crook a bit - the trick is that you iterate over the list backwards when you are removing stuff based on index, so that the remainder does not get jumbled up by losing their positions, as happens when you do it going forwards. That's only if you remove the current item. The OP has different threads accessing the list at the same time, so I have to assume that item being remove is not necessarily the current iteration. Sorry - I did not pick that up - The threading screws the simple scheme up. In such a situation I would have a thread to run the list - almost like a mini data base - and link the lot together using queues. It is still a bugger, though, as one thread could try to kill something that is checked out to another one. Then you have to take hard decisions, and a list is the wrong structure, because you have to remember state. Better to use a dict, so you can at least mark a thing as dead, and check for that before you update. 8 example For the record, I use a more sophisticated system that explicitly resolves cause and effect in my games. That's probably beyond the scope of this thread, though. Yes - it is hairy - and there are probably as many different solutions as there are programmers, and then some. :-) - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
On Fri, Aug 28, 2009 at 5:45 PM, hoffik be...@seznam.cz wrote: Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. As far as I know though, you will have to loop through this if you built your matrix with nested lists. i.e.: li = [[1,2],[3,4]] result = [] for row in li: result.append(row[0]) # result == [1, 3] For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. Let's say values = [[1,2][3,4]]. values[:] returns the entire values list, from beginning to end. So you end up what you started with. And, of course, values[:][0] is the same as values[0]. In fact: li[:][:][:][0] is li[0] True It's... a very interesting behaviour, to say the least. You might be able to get a proper matrix behaviour using NumPy, (which I never used, so I'm just throwing it out there as a guess) or you might have to write your own iterator for later reuse. Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
On Aug 27, 11:22 pm, r rt8...@gmail.com wrote: - Python offical docs and Tkinter - *The Python docs barely cover anything related to actual Tkinter coding. At the minimum the Tkinter doc page should have a subpage for all the widgets available --which is very small(approx 15) and each subpage should list the available methods on that wiget. I think the general idea behind the 'lack' of documentation is that it would only double tcl/tk's own documentation. I've always used Tkinter using the tcl/tk docs here: http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm and once you get used to how you transform tcl syntax to Python syntax, it works pretty well. Maintaining a documentation for Tkinter in the official Python docs would force people to run after tcl. I understand why they don't want to do that, even if I'd love to see a better Tkinter documentation too. - from Tkinter import * - *Too many noobs start out with the from Tkinter import * idiom, unknowing that they are horribly polluting their namespace. I feel that all (tkinter) code should follow the import Tkinter as tk policy and never use from Tkinter import *. To push this agenda i propose all docs be modified so that no one should see such global import blasphemy again. We should at least keep all example code in the latter non-polluting form and frown heavily upon global imports in Tkinter code or any code for that matter. Well, I just don't agree with you on this one. AFAIK, Tkinter has been made to make the 'from Tkinter import *' idiom work without too much namespace pollution. I've always used it, still use it today, and never seen any problem with it. I do agree that this might lead newbies to think it's ok for all modules, and end up doing 'from os import *' and wonder why opening a file with 'open' no more works. But this is the only problem I can see. - Tkinter Constants - *The Tkconstants module needs to be removed *yesterday* because i think it reinforces sloppy coding styles. The main problem is with subtle bugs that are created when someone rebinds one or more of the constants, for example W=20. At first i thought the constants were great but I quickly found out the shortfalls of such a Utopian approach . Since Tkinter allows strings to be passed-into widget constructors, we should remove the TkConstants immediately and force everyone to use strings instead... #-- instead of this --# w.pack(side=LEFT,fill=BOTH,anchor=W) #-- do this --# w.pack(side='left',fill='both',anchor='w') The few extra keystrokes are well worth the effort! Well, again, I don't agree. I prefer having well defined constants than having to type strings. If the values for the fill option could be anything, well, OK. But they can't: they have to be either 'x' or 'y' or 'both'. So I prefer to have them defined in constants. [snip comments on IDLE, which I don't use] - Tkinter Canvas - *The Tkinter Canvas widget should return (X,Y) pairs when calling canvas.coords(obj). The current implementation returns a flat array that is pretty much useless outside of canvas calls. Of course one could zip the coords into pairs, but it seems clumsy to call zip() on 2 LC's when Tkinter could, and should, do it for you. We agree on this one, but it's a minor flaw. *Canvas needs a canvas.rotate() method for polygons, lines -- (easy). All Canvas methods are actually forwarded to the underlying tcl interpreter. So you might want to suggest that to the tcl guys. - Tkinter ComboBox -- where's Waldo? - *As much as i hate to support anything related to M$, Tkinter needs an M$ stlye combobox. Yes, I know Tix has combobox (*puke*), however using it is like pulling teeth. I have coded up an far more elegant/ simple solution -- and yes, i know about the OptionMenu widget which serves a useful purpose but is NOT a good replacement for a REAL M$ style combobox ;). You don't seem to be aware of the new widgets in tk, which do include a combo-box (and a lot of others BTW). See the ttk:: commands in the tcl/tk documentation (link above). These widgets already have a Python wrapper (see http://pypi.python.org/pypi/pyttk/0.3). *For instance, ComboBoxes need values that the user can select from, this is as universal as humans and oxygen. But sometimes you want to give the user a detailed set of values in the dropdown listbox and then insert an abbrieation of the value once selected, such as the case with state names... New Mexico - MN California - CA Florida - FL ...instead of the
Select column from a list
Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. Thanks Hoffik -- View this message in context: http://www.nabble.com/Select-column-from-a-list-tp25185508p25185508.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
John Machin wrote: On Aug 28, 6:44 am, Mark Lawrence breamore...@yahoo.co.uk wrote: vsoler wrote: On Aug 27, 9:42 pm, Andreas Waldenburger use...@geekmail.invalid 1- the csv file was generated with Excel 2007; no prompts for what the separator should be; Excel has used ; by default, without asking anything I find this difficult to believe, Mark, there exist parallel universes the denizens of which use strange notation e.g. 1.234,56 instead of 1,234.56 and would you believe they use ';' instead of ',' as a list separator ... Excel perfidiously gives them what they expect rather than forcing them to comply with The One True Way. I suggest a new file type csvewtlsinac i.e. comma seperated value except when the list seperator is not a comma.:) Does this cover everything? p.s. is it separator or seperator, after 50+ years I still can't remember? -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: break unichr instead of fix ord?
The PEP says: * unichr(i) for 0 = i 2**16 (0x1) always returns a length-one string. * unichr(i) for 2**16 = i = TOPCHAR will return a length-one string on wide Python builds. On narrow builds it will raise ValueError. and * ord() is always the inverse of unichr() which of course we know; that is the current behavior. But there is no reason given for that behavior. Sure there is, right above the list: Most things will behave identically in the wide and narrow worlds. That's the reason: scripts should work the same as much as possible in wide and narrow builds. What you propose would break the property unichr(i) always returns a string of length one, if it returns anything at all. 1) Should surrogate pairs be disallowed on narrow builds? That appears to have been answered in the negative and is not relevant to my question. It is, as it does lead to inconsistencies between wide and narrow builds. OTOH, it also allows the same source code to work on both versions, so it also preserves the uniformity in a different way. * every Python Unicode character represents exactly one Unicode code point (i.e. Python Unicode Character = Abstract Unicode character) I'm not sure what this means (what's an abstract unicode character?). I don't think this is actually the case, but I may be confusing Unicode terminology here - abstract character is a term from the Unicode standard. Finally we read: * There is a convention in the Unicode world for encoding a 32-bit code point in terms of two 16-bit code points. These are known as surrogate pairs. Python's codecs will adopt this convention. Is a distinction made between Python and Python codecs with only the latter having any knowledge of surrogate pairs? No. In the end, the Unicode type represents code units, not code points, i.e. half surrogates are individually addressable. Codecs need to adjust to that; in particular the UTF-8 and the UTF-32 codec in narrow builds, and the UTF-16 codec in wide builds (which didn't exist when the PEP was written). Nothing else in the PEP seems remotely relevant. Except for the motivation, of course :-) In addition: your original question was why has this been changed, to which the answer is it hasn't. Then, the next question is why is it implemented that way, to which the answer is because the PEP says so. Only *then* the question is what is the rationale for the PEP specifying things the way it does. The PEP is relevant so that we can both agree that Python behaves correctly (in the sense of behaving as specified). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How do I reply to a thread by sending a message to python-list@python.org
On Thursday 27 August 2009 22:57:44 Terry Reedy wrote: Nope. I got a duplicate sent to my mailbox, which I hate. In particular, because there is no indication that it is an exact duplicate of what I will also find on the list itself. Please use reply instead of reply-all. If I do that, then the mail would go just to you, and not to the list at all, which is not what I suspect you want, in view of what you have just said. I have to do a reply all, followed by deletion of the author, and sometimes addition of the list as a to too. Its a mess, and if I muck it up, the author gets a copy in his email, if he has not fudged his reply to It would really be nice if the reply would go to the list, but for the digest versions, at least, it does not. And different mail clients do not seem to make a difference. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithms as objects?
Kreso schrieb: I am writing an application that essentially calculates set of numbers, say N1, N2, ..., where they can be calculated by several different algorithms. (One should be able to choose the algorithm at run time.) In each algorithm one starts from a set of functions, say f1, f2, ..., which are then transformed into some other functions g1(f1, f2, ..), g2(f1, f2, ...), ... , then maybe transformed once more and result is obtained by evaluating final functions. I can naturally think about this as a collection of transformation blocks, which have functions as input and output, and which can be put together to get the final results. However, I am not sure how to program this, especially since one cannot subclass function type. To be clear let me give simplified example of what is needed: f(x) has unknown shape, so one would like to try, say f1(x) = ax - b x**2 orf2(x) = a sin(b*x), where a and b are variable parameters. Then, one would like to create, with known k(x,y), function g(x) in one of two ways: g1(x) = k(x, x)*f(x) or g2(x) = integrate(k(x, y) * f(y), y=0..1), and finally evaluate N=g(1) as result. In this simple example there are 4 different algorithms for f(x) - g(x) - N, and one should be able to simply choose between them, e.g. by calling N(g1, f2, (a,b)). In practice algorithm is not necessary so linear, but is generally tree-lika: (a,b) - f1(x) ---g1(x)---+ |-- h(x) -- N (c,d) ---+-- g2(x)+ | f2(x) --+ It would be nice to have some class of function-objects, that f1(x), .., g1(x), ... could be members/instances of so that common operations on these functions could be possible (checking that they satisfy some necessary properties, plotting them, ...), and then second class of transformations/methods operating on these objects. I seem to be confused by the fact that I would like to somehow treat algorithms as objects (so that one can experiment with different algorithm systems) but I don't have clear picture how to do it. I am just brainstorming for ideas. Any advice is welcome. Sound like simple function combinators to me. Like this: import inspect def combine(f, g): if len(inspect.getargspec(g)[0]) 1: def h(*args): return g(*f(*args)) return h else: def h(*args): return g(f(*args)) return h def a(x): return 10 + x def b(x): return x ** 2 print combine(a, b)(20) def c(x): return x, x * 2 def d(x, y): return x + y print combine(c, d)(10) But to be honest - I don't think you win much with this whole thing. Spelling out the function-calls the way they are made is in the end as efficient and clear as it can get. And for *real* algorithms, you need non-strict constructs, control-structures and the like, and in the end of the day, you create a programming language on top of a programming language. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How do I reply to a thread by sending a message to python-list@python.org
On Fri, Aug 28, 2009 at 6:18 PM, Hendrik van Rooyen hend...@microcorp.co.za wrote: It would really be nice if the reply would go to the list, but for the digest versions, at least, it does not. I'm on a few other lists. The Python ones are the only ones that I have to manually change. The Nuke-user mailing list automatically changes the To: to the correct address, and I *think* they also use mail-man. The DLF list I mentioned before also doesn't have this problem. When will this be fixed? It'll take someone like 5 minutes to do a setting . . . -Just my rambling again Xav -- http://mail.python.org/mailman/listinfo/python-list
Sending email
Hello, I'm using Python version 2.6.2 and I discovered it has built-in libraries for sending email (imports smtplib and email). On the web I discovered how to send mail through smtp.gmail.com: mail_server = smtplib.SMTP() mail_server.connect('smtp.gmail.com') mail_server.ehlo() mail_server.starttls() mail_server.ehlo() mail_server.login('username', 'password') msg = MIMEText('Some message text') msg['Subject'] = 'Some subject' msg['From'] = 'Mr Underhill' msg['To'] = 'someemailaddress' me = 'myemailaddress' mail_server.sendmail(me, ['someemailaddress'], msg.as_string()) That seems to work just fine but for the messages I will be sending I don't want to use my private GMail account. We have an SMTP server at work, and I checked its settings in the Thunderbird mail client and it's using SSL over port 465, so a bit different from how GMail's SMTP server is configured in Thunderbird. I altered my code slightly to account for this: mail_server = smtplib.SMTP_SSL() mail_server.connect('mysmtpserver.at.work', 465) Everything I left untouched. However, it doesn't work: Traceback (most recent call last): File C:\Users\fencer\workspace\Send Email\src\send_email.py, line 16, in module mail_server.ehlo() File C:\Python26\lib\smtplib.py, line 382, in ehlo self.putcmd(self.ehlo_msg, name or self.local_hostname) File C:\Python26\lib\smtplib.py, line 318, in putcmd self.send(str) File C:\Python26\lib\smtplib.py, line 310, in send raise SMTPServerDisconnected('please run connect() first') smtplib.SMTPServerDisconnected: please run connect() first As you can see, I'm on Windows Vista. What do I need to change in my code to fix this problem? Thunderbird manages to do it! :) Ideally, I would like send an email that the recipient can't reply to, but if doesn't work, it's fine too. I want to use this to send automated emails to students with account information for a course. - Fencer -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
kj a écrit : In 4a967b2f$0$19301$426a7...@news.free.fr Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid writes: The only thing one is entitled to expect when learning a new language is that the language's implementation follows the language specs. In fact, the official docs, when they discuss scopes, are off to a bad start: Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use. The first paragraph implies that binding can only occur within functions, which is either incorrect, or presupposes a definition of function that is not what most programmers would recognize. Indeed, and you're right to point it. I strongly suggest you submit a ticket to the doc maintainers. In general, I found the docs very unclear on the subject of scoping. PEP 227 is much better, but I wouldn't have thought of it as the specs. Well, here again, it sure would help to make clear that peps (and release specific what's new) *are* part of the doc. But for sure, what used to be a simple and clear reference is now a bit of a mess, despite the hard work of the doc team. Side-effect of the rapid growth of the language I guess... -- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithms as objects?
Kreso a écrit : I am writing an application that essentially calculates set of numbers, say N1, N2, ..., where they can be calculated by several different algorithms. (One should be able to choose the algorithm at run time.) In each algorithm one starts from a set of functions, say f1, f2, ..., which are then transformed into some other functions g1(f1, f2, ..), g2(f1, f2, ...), ... , then maybe transformed once more and result is obtained by evaluating final functions. I can naturally think about this as a collection of transformation blocks, which have functions as input and output, and which can be put together to get the final results. However, I am not sure how to program this, especially since one cannot subclass function type. Nope, but you can write your own callable types: class functor(object): def __call__(self): print %s called % self (snip) I seem to be confused by the fact that I would like to somehow treat algorithms as objects Strategy pattern anyone ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Protecting against callbacks queuing up?
On Friday 28 August 2009 00:42:16 Esben von Buchwald wrote: OK, now things starts to make sense. You tell me to do something like this? def doCallback(self): if self.process_busy==False: self.process_busy=True self.at.after(0.01,self.data_callback) This bit is allmost right - try to make the time a millisecond or less, if you can. (however that is specified - I do not know) The spelling is probably: self.at.after(1,self.data_callback, (other_stuff)) where other stuff comes from the event and is what is needed to do the calculation. - the event should be an argument to the doCallback thinghy too, somehow, so that you can get at what you need to do the calculation. def doneCallback(self): self.process_busy=False you do not need this separate. just do this: def data_callback(self,other_stuff): calculate what must be calculated self.process_busy=False And the after command will cause python to spawn a new thread, which runs self.data_callback, which measn that the doCallback will return immediately, so the next callback from accelerometer can be processed? Yes and skipped if the calculation is not done yet. Obviously you will have to do whatever it takes to make sure the events keep coming (if anything), so it may end up a little more complex, but you basically have the idea now. The thing that happens as a result of the after is not really a new thread, it is a piece of the main loop that gets diverted for a while to do the calculation. if, in that routine, you go: while True: pass You will completely freeze up the whole bang shoot.. And when the self.data_callback() finishes, i'd make it call the doneCallback() to release my busy flag, right? see above - just clear it from the called routine. I'm gonna try this tomorrow :) Good luck! - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: variables of the class are not available as default values?
Chris Rebert a écrit : (snip) Default values are only evaluated once, when the class is defined, clarification target=newcomers s/class/function/ The function objects (defined in a class statement body...) are created before the class object itself. /clarification thus self is not defined at that point since the class is still being defined when the method definition is executed and thus there can be no instances yet anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How do I reply to a thread by sending a message to python-list@python.org
Hendrik van Rooyen hend...@microcorp.co.za writes: If I [use the “reply to author” command], then the mail would go just to you, and not to the list at all, which is not what I suspect you want, in view of what you have just said. Right. The common “reply” command in most mail clients means “reply to author”, and as you say, it requests to compose a reply addressed to the author. It would really be nice if the reply would go to the list, but for the digest versions, at least, it does not. No, it really wouldn't; because if you're asking to compose a message address to the *author*, and it instead gets addressed to the whole *list*, that's a recipe for disastrous communication errors. Instead, it would be nice if people had a “reply to list” command, and used that when they choose to send a message to the list. And different mail clients do not seem to make a difference. Fortunately, the messages that come from the list enable any mail client to know the correct address for “reply to list”. It only remains to choose a mail client that knows how to use it. -- \ “… one of the main causes of the fall of the Roman Empire was | `\that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.” —Robert Firth | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How do I reply to a thread by sending a message to python-list@python.org
On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney ben+pyt...@benfinney.id.auben%2bpyt...@benfinney.id.au wrote: Fortunately, the messages that come from the list enable any mail client to know the correct address for “reply to list”. It only remains to choose a mail client that knows how to use it. Would you be so kind and share with us for such a client that knows how to use the mailing list attribute? Thanks! -Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
hoffik a écrit : Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. Lists don't have columns. What you have is a list of lists (and FWIW, in your case, it should be a list of tuples since obviously these are fixed-size items where position is meaningfull). For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. Not exactly. In the first case, you have a reference to values[0], in the second case a _copy_ of values[0] alist = [[1, 2, 3], [4, 5, 6]] ref = alist[0] copy = alist[0][:] ref is alist[0] True copy is alist[0] False copy[0] = 999 copy [999, 2, 3] alist [[1, 2, 3], [4, 5, 6]] ref [1, 2, 3] ref[0] = 888 alist [[888, 2, 3], [4, 5, 6]] But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. alist[:] returns a copy the whole list. As I said, lists don't have columns. So yes, given your data structure, you do have to iterate over the outer list to collect items at specific positions of the inner lists (or tuples). Depending on the size of your dataset, the frequency of such operation in your code, and required perfs, you can either * just do the simplest thing, ie: first_column_items = [row[0] for row in values] * try to find a more suited datastructure * of just use the most appropriate tool for set operations, which is a relational database. FWIW, sqlite doesn't require any server setup, and can even be used with in-memory databases if you don't need persistance. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
Vlastimil Brom wrote: 2009/8/28 hoffik be...@seznam.cz: Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. ... I guess, it won't be possible without an explicit or implicit loop; you may try: from operator import itemgetter nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] map(itemgetter(1), nested_list) [2, 20, 200] vbr How about rotating the list with zip? zip (*nested_list)[1] (2, 20, 200) Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
2009/8/28 hoffik be...@seznam.cz: Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. ... I guess, it won't be possible without an explicit or implicit loop; you may try: from operator import itemgetter nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] map(itemgetter(1), nested_list) [2, 20, 200] vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How do I reply to a thread by sending a message to python-list@python.org
On Fri, 2009-08-28 at 19:04 +1000, Xavier Ho wrote: On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney ben +pyt...@benfinney.id.au wrote: Fortunately, the messages that come from the list enable any mail client to know the correct address for “reply to list”. It only remains to choose a mail client that knows how to use it. Would you be so kind and share with us for such a client that knows how to use the mailing list attribute? Evolution at least is mailing-list aware. I usually Reply to List (CTRL-L) and fugetaboutit. -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
On 28 août, 02:47, MRAB pyt...@mrabarnett.plus.com wrote: Deep_Feelings wrote: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? Fewer needed? excellent answer. LOL. Olivier -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
On Fri, 28 Aug 2009 09:03:49 +0100 Mark Lawrence breamore...@yahoo.co.uk wrote: p.s. is it separator or seperator, after 50+ years I still can't remember? The former. It's cognate to English part if that helps any. /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Protecting against callbacks queuing up?
It seems to solve the problem. What I did: def contextDataHandler(self): self.contextdata.process_busy=True self.services.findServices() self.drawDisplay() self.contextdata.process_busy=False def doCallback(self): self.at.cancel() if self.process_busy==False: self.at.after(0.01,self.data_callback) The app works awesomely stable now data_callback refers to contextDataHandler in parent class Thanks guys, good job -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
Phil a écrit : When I gave that arbitrary percentage, I was basing it off of the information I had seen with regards to launching applications built with existing frameworks using lighttpd. I do realize I was missing a lot of information by looking up something that specific. Indeed !-) I also understand that there are enough frameworks. That still won't change my mind. I do not want to write a web application, otherwise I would use an existing framework as suggested. I just wanted to experiment and see what kind of framework I could develop with some ideas I had in mind. I wrote quite a couple web and non web frameworks myself - all ending up in the trash can FWIW, but it certainly has been a very educative experience by itself. I just really like some of the new features of Python 3, and most importantly, unicode compliance is just that much straight forward in my opinion. If you're only writing your framework for learning purposes, you could as well go with Python 3, and implement everything from the ground up (not a trivial task FWIW). -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python advanced features
jvpic a écrit : Bruno Desthuilliers a écrit : jvpic a écrit : Hi, Learning Python, I understand the mechanism of : closure, __new__, descriptors, decorators and __metaclass__, but I interrogate myself on the interest of those technics ? May somebody explain me the interest ? Didn't like my answers on f.c.l.py ?-) Si, mais je voulais savoir ce qu'on en pense sur un autre forum ! Merci encore... Hum... I guess the smiley was not big enough !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python advanced features
Jonathan Gardner a écrit : On Aug 27, 5:13 am, jvpic jv...@free.fr wrote: Hi, Learning Python, I understand the mechanism of : closure, __new__, descriptors, decorators and __metaclass__, but I interrogate myself on the interest of those technics ? May somebody explain me the interest ? I assume you are asking, Why do these features exist? What makes them useful? When would I use them? For that, you should re-read the documentation and discussion surrounding them. The short answer is that the above makes your job, as a programmer easier. It's easier because you have to write less code, read less code, and your code has fewer bugs. I think the OP is mostly looking for practical use cases. FWIW, when I discovered Python's lambda (I only knew a couple low-level imperative languages by that time), I really wondered what an anonymous function could be used for !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
Esam Qanadeely wrote: who cares if a language is compiled or interpreted as long as it runs and perform the function. second thing is : even if java is faster than python , unless you are making performance critical operations : who cares? computers are getting faster all the time and languages like python or ruby are fast enough. any comment ? I like to second that, if performance is *that* important you wouldn't go with Java either, you be better of with C or even assembly. Doesn't mean you should write everything in C, just the parts that are performance critical, preferably with a 'slow' fall back if there isn't an optimized routine available yet for a specific platform. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' -- http://mail.python.org/mailman/listinfo/python-list
Re: Object's nesting scope
zaur a écrit : On 26 авг, 17:13, Diez B. Roggisch de...@nospam.web.de wrote: Whom am we to judge? Sure if you propose this, you have some usecases in mind - how about you present these Ok. Here is a use case: object initialization. For example, person = Person(): name = john age = 30 address = Address(): street = Green Street no = 12 vs. person = Person() person.name = john person.age = 30 address = person.address = Address() address.street = Green Street address.no = 12 Err... Looks like you really should read the FineManual(tm) - specifically, the parts on the __init__ method. class Person(object): def __init__(self, name, age, address): self.name = name self.age = age self.address = address class Address(object): def __init__(self, street, no): self.no = no self.street = street person = Person( name=john, age=30, address = Address( street=Green Street, no=12 ) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending email
On Aug 28, 2:37 am, Fencer no.i.d...@want.mail.from.spammers.com wrote: Hello, I'm using Python version 2.6.2 and I discovered it has built-in libraries for sending email (imports smtplib and email). On the web I discovered how to send mail through smtp.gmail.com: mail_server = smtplib.SMTP() mail_server.connect('smtp.gmail.com') mail_server.ehlo() mail_server.starttls() mail_server.ehlo() mail_server.login('username', 'password') msg = MIMEText('Some message text') msg['Subject'] = 'Some subject' msg['From'] = 'Mr Underhill' msg['To'] = 'someemailaddress' me = 'myemailaddress' mail_server.sendmail(me, ['someemailaddress'], msg.as_string()) That seems to work just fine but for the messages I will be sending I don't want to use my private GMail account. We have an SMTP server at work, and I checked its settings in the Thunderbird mail client and it's using SSL over port 465, so a bit different from how GMail's SMTP server is configured in Thunderbird. I altered my code slightly to account for this: mail_server = smtplib.SMTP_SSL() mail_server.connect('mysmtpserver.at.work', 465) Everything I left untouched. However, it doesn't work: Traceback (most recent call last): File C:\Users\fencer\workspace\Send Email\src\send_email.py, line 16, in module mail_server.ehlo() File C:\Python26\lib\smtplib.py, line 382, in ehlo self.putcmd(self.ehlo_msg, name or self.local_hostname) File C:\Python26\lib\smtplib.py, line 318, in putcmd self.send(str) File C:\Python26\lib\smtplib.py, line 310, in send raise SMTPServerDisconnected('please run connect() first') smtplib.SMTPServerDisconnected: please run connect() first As you can see, I'm on Windows Vista. What do I need to change in my code to fix this problem? Thunderbird manages to do it! :) Ideally, I would like send an email that the recipient can't reply to, but if doesn't work, it's fine too. I want to use this to send automated emails to students with account information for a course. - Fencer The docs say: --- class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]) A SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. --- So try getting ride of these two lines: mail_server.starttls() mail_server.ehlo() There's also some info on google about a bug in this regard, so check to see when you installed python 2.6.2. -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
hoffik be...@seznam.cz (h) wrote: h Hello, h I'm quite new in Python and I have one question. I have a 2D matrix of h values stored in list (3 columns, many rows). I wonder if I can select one h column without having to go through the list with 'for' command. h For example I have list called 'values'. h When I write 'values[0]' or 'values[0][:]' I'll get the first row. h But when I write 'values[:][0]' I won't get the first column, but the first h row again! I can't see why. If you work with matrices, numpy may be interesting for you. It does have the required functionality: M[:,0] will give you the first column. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Transforming a str to an operator
On Thu, 27 Aug 2009, Stephen Hansen wrote: num1 = raw_input('Enter the first number: ') num2 = raw_input('Enter the second number: ') op = raw_input('Select one of the following [+-*/]: ') print 'The answer is: ', int(num1), eval(op), int(num2) How do I convert the contents of op from a string to an actual arithmetic operator? eval() does not seem to be the answer. TIA! You could eval(num1+op+num2), but it'd be safer to do: import operator operators = {+: operator.add, -: operator.sub, *: operator.mul, /: operator.div} fn = operators[op] print The answer is:, fn(int(num1), int(num2)) Its best to avoid eval when possible :) --S In *any* language eval is dangerous, so your second example would also be my choice. Thanks for the clue. BTW, I hunted hi-n-lo for something that would address my question at http://docs.python.org. I obviously didn't have much luck. Something about those docs that is confusing -- duke -- http://mail.python.org/mailman/listinfo/python-list
ANN: M2Crypto 0.20.1
M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web session management; FTP/TLS client and server; S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME messenger for Zope. Smartcards supported with the Engine interface. This is the 0.20.1 release. Download links and bug filing instructions on the homepage at http://chandlerproject.org/Projects/MeTooCrypto. Changelog: - Fix regression in httpslib.ProxyHTTPSConnection, by Miloslav Trmac -- Heikki Toivonen - http://heikkitoivonen.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Read a content file from a P7M
On Fri, Mar 20, 2009 at 4:12 PM, Emanuele Roccae...@linux.it wrote: On 11/03/09 - 05:05, Luca wrote: There is standard or sugested way in python to read the content of a P7M file? I don't need no feature like verify sign, or sign using a certificate. I only need to extract the content file of the p7m (a doc, a pdf, ...) For PDF files you can just remove the P7M content before %PDF and after %%EOF. The following snippet converts /tmp/test.p7m into PDF, saving the resulting document into /tmp/test.pdf: import re from gzip import GzipFile contents = GzipFile('/tmp/test.p7m').read() contents_re = re.compile('%PDF-.*%%EOF', re.MULTILINE | re.DOTALL) contents = contents_re.search(contents).group() open('/tmp/test.pdf', 'w').write(contents) After all those days... only to say THANKS! The example of the PDF file is perfect, I only needed to not execute the GzipFile call (it seems that our PDF are not GZipped). Unluckily now seems that we need the same feature for non-pdf files... -- -- luca -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGTK problems after Linux update...
Looks like your pygtk package does not fit to the installed python package. from glib._glib import * ImportError: /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8 -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de -- http://mail.python.org/mailman/listinfo/python-list
Re: Annoying octal notation
On Thu, 27 Aug 2009 10:31:04 -0700, Ethan Furman wrote: Steven D'Aprano wrote: A mistake is still a mistake even if it shared with others. Treating its with a lead zero as octal was a design error when it was first thought up [snippage] I have to disagree with you on this one. The computing world was vastly different when that design decision was made. Space was at a premium, programmers were not touch-typists, every character had to count, and why in the world would somebody who had to use papertape or punch cards add a lead zero without a *real* good reason? I submit that that real good reason was to specify an octal literal, and not a decimal literal. Octal with a leading 0 comes from B, which influenced C, which influenced many languages. B was designed in 1969, the same year as Pascal, not the 1950s -- six years *after* Basic, ten years after Lisp and Cobol, eleven years after Algol, and thirteen years after Fortran. *None* of these other languages use a leading 0 for Octal, and none of them are particularly terse. Obviously I can't speak for Ken Thompson's motivation in creating this feature, but I'm pretty sure it wasn't to save typing or space on punchcards. Even in 1969, hex was more common than octal, and yet hex values are written with 0x. My guess is that he wanted all numbers to start with a digit, to simplify parsing, and beyond that, it was just his programming style -- why call the copy command `copy` when you could call it `cp`? (Thompson was the co-inventor of Unix.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. In case you want to due numerical calculations take a look at numpy it has an extended slicing notation to select columns directly. See http://www.scipy.org # create 10x10 numpy array filled with 1 data = numpy.ones((10,10)) column = data[:,0] Best wishes! Bernhard -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
On 28 Aug, 02:34, Deep_Feelings doctore...@gmail.com wrote: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? Because we are better, so fewer are needed. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to unencode a string
On Aug 27, 6:51 pm, Piet van Oostrum p...@cs.uu.nl wrote: jakecjacobson jakecjacob...@gmail.com (j) wrote: j This seems like a real simple newbie question but how can a person j unencode a string? In Perl I use something like: $part=~ s/\%([A-Fa- j f0-9]{2})/pack('C', hex($1))/seg; j If I have a string like Word1%20Word2%20Word3 I want to get Word1 j Word2 Word3. urllib.unquote(string) j Would also like to handle special characters like ',(){} j [] etc/ What would you like to do with them? Or do you mean to replace %27 by ' etc? -- Piet van Oostrum p...@cs.uu.nl URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org Yes, take '%27' and replace with ', etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Class implements Interface?
On Aug 27, 2009, at 9:16 AM, Emanuele D'Arrigo wrote: Are there resources such as tools, recipes, documents or strategies that could help me deal with these issues? I've already looked into the ABC module and the zope.interface. I'm just fishing for more things to look at. You say above that you looked at zope.interface. Did you look at zope.interface.verify? Specifically, verify.txt doctests state that: An object provides an interface if - either its class declares that it implements the interfaces, or the object declares that it directly provides the interface - the object defines all the methods required by the interface - all the methods have the correct signature - the object defines all non-method attributes required by the interface zope.interface.verify.verifyObject(I, obj) will check all of the above. Similarly, zope.interface.verify.verifyClass(I, C) will check the class. It is a good practice to call these functions in the regression tests. If this is not what you are looking for, sorry for the noise. Zvezdan -- http://mail.python.org/mailman/listinfo/python-list
Re: Annoying octal notation
Steven D'Aprano wrote: On Thu, 27 Aug 2009 10:31:04 -0700, Ethan Furman wrote: Steven D'Aprano wrote: A mistake is still a mistake even if it shared with others. Treating its with a lead zero as octal was a design error when it was first thought up [snippage] I have to disagree with you on this one. The computing world was vastly different when that design decision was made. Space was at a premium, programmers were not touch-typists, every character had to count, and why in the world would somebody who had to use papertape or punch cards add a lead zero without a *real* good reason? I submit that that real good reason was to specify an octal literal, and not a decimal literal. Octal with a leading 0 comes from B, which influenced C, which influenced many languages. B was designed in 1969, the same year as Pascal, not the 1950s -- six years *after* Basic, ten years after Lisp and Cobol, eleven years after Algol, and thirteen years after Fortran. *None* of these other languages use a leading 0 for Octal, and none of them are particularly terse. Obviously I can't speak for Ken Thompson's motivation in creating this feature, but I'm pretty sure it wasn't to save typing or space on punchcards. Even in 1969, hex was more common than octal, and yet hex values are written with 0x. My guess is that he wanted all numbers to start with a digit, to simplify parsing, and beyond that, it was just his programming style -- why call the copy command `copy` when you could call it `cp`? (Thompson was the co-inventor of Unix.) Maybe it was because they were working on minicomputers, not mainframes, so there was less processing power and storage available. -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
On Aug 28, 9:55 am, sturlamolden sturlamol...@yahoo.no wrote: On 28 Aug, 02:34, Deep_Feelings doctore...@gmail.com wrote: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? Because we are better, so fewer are needed. That makes sense!! :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
On Thu, 27 Aug 2009 17:34:17 -0700, Deep_Feelings wrote: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? Python programmers are the elite. The elite are always fewer than the masses. -- Steven who is three quarters joking -- http://mail.python.org/mailman/listinfo/python-list
Re: Transforming a str to an operator
On Thu, 27 Aug 2009, r wrote: On Aug 27, 10:52 pm, Duke Normandin dukeofp...@ml1.net wrote: How do I convert the contents of op from a string to an actual arithmetic operator? eval() does not seem to be the answer. TIA! Try this.. op = '+' one = '1' two = '2' one+op+two '1+2' eval(one+op+two) 3 you could also use string formatting. I see! Concatenate the strings within the eval() function. Of course, it's prudent not to expose eval to the outside world. But for learning purposes Thanks for the input! -- duke-- http://mail.python.org/mailman/listinfo/python-list
Re: Sending email
7stud wrote: [snip] Thanks for your reply. After consulting the sysadmins here I was able to get it to work. - Fencer -- http://mail.python.org/mailman/listinfo/python-list
Re: Transforming a str to an operator
On Fri, 28 Aug 2009, Ben Finney wrote: Duke Normandin dukeofp...@ml1.net writes: Hey I'm a Python noob So far so good! I've written the following: num1 = raw_input('Enter the first number: ') num2 = raw_input('Enter the second number: ') op = raw_input('Select one of the following [+-*/]: ') print 'The answer is: ', int(num1), eval(op), int(num2) How do I convert the contents of op from a string to an actual arithmetic operator? eval() does not seem to be the answer. TIA! In general, ‘eval’ on unsanitised input is not the answer. Agreed! If I were to expose eval to the 'net, I would have some input error checking and type checks to insure that only integers and valid operators were being input. I would use the following approach: import operator op_funcs = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div, } num_1 = int(raw_input('Enter the first number: ')) num_2 = int(raw_input('Enter the second number: ')) op_prompt = ( Select an operator + [ + .join(s for s in op_funcs.keys()) + ] + : ) op_symbol = raw_input(op_prompt) op_func = op_funcs[op_symbol] print 'The answer is: ', op_func(num_1, num_2) This has several advantages: * The input isn't evaluated directly as code. * The operator symbols are specified in one place, the ‘op_funcs’ mapping; if you want to change the set of possible operators, you just change it there. * If the input results in an operator that's not defined, it won't attempt to perform it; instead, a simple KeyError will result when trying to find the corresponding operator function. Cool! Something useful to study... Thanks for the input! -- duke-- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithms as objects?
On Thu, 27 Aug 2009 23:05:41 +, Kreso wrote: I am writing an application that essentially calculates set of numbers, say N1, N2, ..., where they can be calculated by several different algorithms. (One should be able to choose the algorithm at run time.) In each algorithm one starts from a set of functions, say f1, f2, ..., which are then transformed into some other functions g1(f1, f2, ..), g2(f1, f2, ...), ... , then maybe transformed once more and result is obtained by evaluating final functions. Sounds like you're doing functional programming. There's a rich set of functional tools in languages like Haskell, but in Python there's only a few, such as partial(). (See the functools module.) However, you can make your own, using the following general technique. Suppose you want to compose two functions, f and g. Then with a helper function: def compose(f, g): def composed_function(*args): return f(g(*args)) return composed_function you can do this: def add1(x): ... return x+1 ... def double(y): ... return 2*y ... double_plus_one = compose(add1, double) double_plus_one(3.5) 8.0 Unfortunately, about the only thing you can't do is check the return type of functions without actually calling them. I can naturally think about this as a collection of transformation blocks, which have functions as input and output, and which can be put together to get the final results. However, I am not sure how to program this, especially since one cannot subclass function type. To be clear let me give simplified example of what is needed: f(x) has unknown shape, so one would like to try, say f1(x) = ax - b x**2 orf2(x) = a sin(b*x), where a and b are variable parameters. You need factory functions! def axbx2_factory(a, b): # Return a function that returns a*x-b*x**2 def inner(x): return a*x -b*x**2 return inner And in use: f1 = axbx2_factory(1, 2) f2 = axbx2_factory(1, 0) f1(2.5) -10.0 f1(3.5) -21.0 f2(2.5) 2.5 f2(3.5) 3.5 Hope this helps. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
write Unicode to sys.out.write without access to sitecustomize.py
I would like to tell the system that it's OK to write Unicode to sys.out and sys.err. However, I'm doing this in a CGI script where I don't have access to the system directories, and as such can't use sys.setdefaultencoding in sitecustomize.py. Is there a way to make this happen? -- --Rob Knop E-mail:rk...@pobox.com Home Page: http://www.pobox.com/~rknop/ Blog: http://www.sonic.net/~rknop/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Transforming a str to an operator
En Fri, 28 Aug 2009 01:50:37 -0300, Xavier Ho cont...@xavierho.com escribió: On Fri, Aug 28, 2009 at 2:35 PM, Ben Finney ben+pyt...@benfinney.id.auben%2bpyt...@benfinney.id.au wrote: op_funcs = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div, } op_prompt = Select an operator ({}):.format(','.join(op for op in op_funcs)) op_prompt = Select an operator ({}):.format(','.join(op_funcs)) Just fixing the code a little to be more Pythonic ;). Even more ;) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Modules/packages by GvR?
Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of Pythonicity. (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How do I reply to a thread by sending a message to python-list@python.org
Xavier Ho wrote: On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney ben+pyt...@benfinney.id.auben%2bpyt...@benfinney.id.au wrote: Fortunately, the messages that come from the list enable any mail client to know the correct address for “reply to list”. It only remains to choose a mail client that knows how to use it. Would you be so kind and share with us for such a client that knows how to use the mailing list attribute? Thanks! -Xav Further to the earlier reply from Albert Hopkins, I use Thunderbird on Windows and just hit reply. The message I reply to is from Xavier Ho an email address and to python-list@python.org. I think this sums it up. -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules/packages by GvR?
How is writing code like a language maintainer going to go towards a philosophic ideal? And more principally why would this be of a benefit. In the philosophic world dressing and acting like Socrates isn't necessarily the same as following his ideals and isn't necessarily being Socratic. On Fri, Aug 28, 2009 at 8:58 AM, gb345 gb...@invalid.com wrote: Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of Pythonicity. (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: write Unicode to sys.out.write without access to sitecustomize.py
On 02:51 pm, rk...@pobox.com wrote: I would like to tell the system that it's OK to write Unicode to sys.out and sys.err. However, I'm doing this in a CGI script where I don't have access to the system directories, and as such can't use sys.setdefaultencoding in sitecustomize.py. Is there a way to make this happen? Sure, just replace the two files with versions that know how to encode the unicode using the correct encoding: import sys, codecs info = codecs.lookup('utf-8') # for example sys.stdout = info.streamwriter(sys.stdout) sys.stderr = info.streamwriter(sys.stderr) Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules/packages by GvR?
On Aug 28, 7:58 am, gb345 gb...@invalid.com wrote: Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of Pythonicity. (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe I'm sure there are. You might be able to figure that out by browsing the source repository: http://hg.python.org. But, I wouldn't necessarily say that any code written by Guido would make a good example of 'Pythonic' code. Not that he doesn't create good code, but the language and standards have evolved over time. There may be code that he wrote from the 2.0 days that may have been perfectly 'Pythonic' then but is just out-of-date now. In general though, browsing the standard modules is a good way to find examples, no matter who wrote it. Just keep in mind when it was written more than who wrote it. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: why python got less developers ?
Chris Rebert wrote: On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelingsdoctore...@gmail.com wrote: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? We lack Sun and Microsoft's massive marketing departments. :) I'm inclined to agreed. But in recent years we lost a number of developers to Ruby. I don't know but I doubt Ruby has a marketing budget. So in my mind it is difficult for me to blame just the lack of marketing dollars for the lost. I do take heart in a recent article (on Linux today). that less than 5% of open source is using C#. Which tells me that .Net in the open source world is not doing well. So in my opinion the OP is wrong when he includes .Net in his assessment of developers. As far as what the OP is suggesting I'm not to sure it matters how many total developers are using Python. Python is always in the top ten of the languages in use. And therefore is very popular. I use it daily. But it does not mean I don't use other languages too. Johnf -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
On Aug 27, 3:06 pm, vsoler vicente.so...@gmail.com wrote: I am trying to read a csv file generated by excel. Although I succeed in reading the file, the format that I get is not suitable for me. I've done: import csv spamReader = csv.reader(open('C:\\abc.csv', 'r')) print spamReader _csv.reader object at 0x01022E70 for row in spamReader: print row ['codigo;nombre;cantidad'] ['a;qwe;1'] ['b;asd;2'] ['c;zxc;3'] My questions are: 1- Why using print spamReader I cannot see the data? I expected to see a list of lists, a kind of a matrix, but I get nothing 2- Why are the rows in a single string? I expected a list of fields that, when text, would be delimited by To tell the truth, the file generated by excel does not contain the strings delimited by . Isn't it weird? 3- Is there anything I can do to have my data in a list of lists structure? would another kind of data suit better my needs? Thank you for your help Vicente Soler the csv module can handle any delimiter. change this spamReader = csv.reader(open('C:\\abc.csv', 'r')) to this spamReader = csv.reader(open('C:\\abc.csv', 'r'), delimiter=';') hope this helps, Steven Rumbalski -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
kj wrote: Miles Kaufmann mile...@umich.edu writes: ...because the suite namespace and the class namespace would get out of sync when different objects were assigned to the class namespace: class C: x = 1 def foo(self): print x print self.x o = C() o.foo() 1 1 o.x = 2 o.foo() 1 2 But this unfortunate situation is already possible, because one can already define class C: x = 1 def foo(self): print C.x print self.x which would lead to exactly the same thing. This is not the same thing, and definitely not exactly the same thing. In your example you are explicitly stating whether you want the original class variable, or the current, and possibly different, instance variable. Further, the instance variable will not be different from the class variable, even after C.x = whatever, unless the instance has had that variable set specifically for it. In [1]: class C(object): ...: x = 9 ...: def doit(self): ...: print C.x ...: print self.x ...: In [2]: test = C() In [3]: test.doit() 9 9 In [4]: C.x = 10 In [5]: test.doit() 10 10 In [6]: test.x = 7 In [7]: test.doit() 10 7 ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Distutils evil voodoo: install into a package
This is what whe world has created namespace-packages for. At least if you can live with the namespace pya being otherwise empty. That seems like a good solution. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules/packages by GvR?
[fix top posting] On Fri, Aug 28, 2009 at 8:58 AM, gb345 gb...@invalid.com wrote: Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of Pythonicity. (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe -- http://mail.python.org/mailman/listinfo/python-list John Haggerty wrote: How is writing code like a language maintainer going to go towards a philosophic ideal? And more principally why would this be of a benefit. In the philosophic world dressing and acting like Socrates isn't necessarily the same as following his ideals and isn't necessarily being Socratic. So the poor old BDFL has been reduced to the rank of language maintainer. Is it safe to assume that somebody is organising a whip round for him? Any and all currencies accepted? -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules/packages by GvR?
Matimus wrote: On Aug 28, 7:58 am, gb345 gb...@invalid.com wrote: Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of Pythonicity. (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe I'm sure there are. You might be able to figure that out by browsing the source repository: http://hg.python.org. But, I wouldn't necessarily say that any code written by Guido would make a good example of 'Pythonic' code. Not that he doesn't create good code, but the language and standards have evolved over time. There may be code that he wrote from the 2.0 days that may have been perfectly 'Pythonic' then but is just out-of-date now. I am not aware of any recent stdlib modules written by Guido. I suspect most older ones have been updated at least once by someone else. In general though, browsing the standard modules is a good way to find examples, no matter who wrote it. Just keep in mind when it was written more than who wrote it. The itertools module is relatively recent and has been recommended as one to read. -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
With regard to Tkinter documentation, and in particular the newer, more modern aspects thereof (e.g. ttk, styles, etc.) please have a look at the tutorial at http://www.tkdocs.com Would it be useful to link to this from the main Python Tkinter documentation? Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
Graham Dumpleton wrote: A few additional comments on top of what others have said. On Aug 26, 11:09 am, Phil phil...@gmail.com wrote: As I've read elsewhere, These days, FastCGI is never used directly. Actually, FCGI works quite well. Sitetruth's AdRater (http://www.sitetruth.com/downloads/adrater.html) uses FCGI and Python on the server. FCGI is basically CGI with process reusability. Each app gets its own process in its own address space with its own global interpreter lock. mod_fcgi in Apache keeps a supply of such processes around, launching additional ones if there's heavy request traffic and shutting down existing ones when there isn't. Each process handles one transaction after another, so, unlike CGI, you're not spending all your time loading Python and its modules. Here's the main loop of a real FCGI application. This uses a small WSGI library on the Python side. No framework is involved. #!/usr/local/bin/python ... from fcgi import WSGIServer import MySQLdb db = None # database connection, held open for life of FCGI # # The application # def QuickSitetruthQuery(environ, start_response): global db # static global - active database handle try: if db : # if previously attached try : db.ping() # test whether connection is still up # handle loss of database connection except MySQLdb.OperationalError, message: db = None # we lost database connection if db is None : # if no valid database handle db = miscutils.dbattach(kdbfile)# connect to database status = '200 OK' # normal status headers = [('Content-type','text/xml'), ('charset','utf-8')] reqlist = cgi.parse_qsl(environ['QUERY_STRING'])# Parse params priority = 1# priority of request sourceip = environ['REMOTE_ADDR'] # get IP address of client urls = [] # list of URLs to check for item in reqlist : # for all items (key, value) = item # extract item if key.lower() == 'url' : # want all url items urls.append(value) elif key.lower() == 'priority' :# if priority priority = int(value) # get priority value # Make request; no waiting, no details outstr = InfoDisplay.getratingXMLquick(db, kdbfile, urls, priority, sourceip) # get the rating XML, never wait start_response(status, headers) # compose result s = kprefixxml + outstr + ksuffixxml# construct output XML return [s.encode('utf8')] # encode as UTF8 except Exception, message: # if trouble, report to user # Error handling status = 500 Internal Error on Server response_headers = [(Content-type,text/html)] start_response(status, response_headers) s = h1Internal error - request not processed./h1\n\n + traceback.format_exc() s = s.replace(\n,br)# convert to HTML return [s] # # Main FCGI program # WSGIServer(QuickSitetruthQuery).run() -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules/packages by GvR?
Terry Reedy tjreedy at udel.edu writes I am not aware of any recent stdlib modules written by Guido. I suspect most older ones have been updated at least once by someone else. Guido wrote a good deal of the new Python 3 code. However, maintence has now turned over to over Python developers. For example, I now maintain 2to3 and the io library, both of which were originally written by Guido. In general though, browsing the standard modules is a good way to find examples, no matter who wrote it. Just keep in mind when it was written more than who wrote it. The itertools module is relatively recent and has been recommended as one to read. That probably don't do much good for your sense of Pythonicity, since it's written in C. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
On Aug 28, 5:43 pm, Steven Rumbalski googleacco...@rumbalski.com wrote: On Aug 27, 3:06 pm, vsoler vicente.so...@gmail.com wrote: I am trying to read a csv file generated by excel. Although I succeed in reading the file, the format that I get is not suitable for me. I've done: import csv spamReader = csv.reader(open('C:\\abc.csv', 'r')) print spamReader _csv.reader object at 0x01022E70 for row in spamReader: print row ['codigo;nombre;cantidad'] ['a;qwe;1'] ['b;asd;2'] ['c;zxc;3'] My questions are: 1- Why using print spamReader I cannot see the data? I expected to see a list of lists, a kind of a matrix, but I get nothing 2- Why are the rows in a single string? I expected a list of fields that, when text, would be delimited by To tell the truth, the file generated by excel does not contain the strings delimited by . Isn't it weird? 3- Is there anything I can do to have my data in a list of lists structure? would another kind of data suit better my needs? Thank you for your help Vicente Soler the csv module can handle any delimiter. change this spamReader = csv.reader(open('C:\\abc.csv', 'r')) to this spamReader = csv.reader(open('C:\\abc.csv', 'r'), delimiter=';') hope this helps, Steven Rumbalski Thank you very much for all your comments. After reading them I can conclude that: 1- the CSV format is not standardized; each piece of software uses it differently 2- the C in CSV does not mean comma for Microsoft Excel; the ; comes from my regional Spanish settings 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank But, perhaps, there is no standard alternative to CSV !!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Object's nesting scope
En Thu, 27 Aug 2009 12:43:55 -0300, zaur szp...@gmail.com escribió: On 27 авг, 19:19, Carl Banks pavlovevide...@gmail.com wrote: On Aug 27, 8:01 am, zaur szp...@gmail.com wrote: On 27 авг, 18:34, Carl Banks pavlovevide...@gmail.com wrote: The idea has been discussed in various forms here quite a bit over the years. I doubt there's any chance it'll be accepted into Python, because it goes against one of the main design points of Python: that attributes should always be accessed explicitly. In my opinion idea of using object's dictionary as nested scope is more about structuring code blocks rather than just saving typing and implicit attribute access. But you *are* doing implicit attribute access. Anyway, the topic was raised and rejected several times in the past; see this recent thread in the python-ideas list: http://comments.gmane.org/gmane.comp.python.ideas/5518 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
En Fri, 28 Aug 2009 13:35:19 -0300, vsoler vicente.so...@gmail.com escribió: On Aug 28, 5:43 pm, Steven Rumbalski googleacco...@rumbalski.com wrote: On Aug 27, 3:06 pm, vsoler vicente.so...@gmail.com wrote: I am trying to read a csv file generated by excel. ['a;qwe;1'] ['b;asd;2'] ['c;zxc;3'] Thank you very much for all your comments. After reading them I can conclude that: 1- the CSV format is not standardized; each piece of software uses it differently Yes! And that's part of the pain of working with 'csv' files. 2- the C in CSV does not mean comma for Microsoft Excel; the ; comes from my regional Spanish settings Yes - but not just Excel, other programs do call CSV files that are TAB-separated, by example. 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank I guess you'll get quotes around text containing ';' characters But, perhaps, there is no standard alternative to CSV !!! Of course there are! You may use SYLK, DIFF, XML, XDR... The nice thing about standards is that there are so many to choose from. (Andrew S. Tanenbaum) But look for the xlrd package, it lets you read Excel files directly from Python. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
vsoler wrote: Thank you very much for all your comments. After reading them I can conclude that: 1- the CSV format is not standardized; each piece of software uses it differently True, but there are commonalities. See http://en.wikipedia.org/wiki/Comma-separated_values 2- the C in CSV does not mean comma for Microsoft Excel; the ; comes from my regional Spanish settings The C really does stand for comma. I've never seen MS spit out semi-colon separated text on a CSV format. 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank There is no need to quote text literals with whitespace in them. There is a need when a newline exists or when the separator character is embedded in the field. --David -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw data extraction question
En Wed, 26 Aug 2009 12:18:23 -0300, Maggie la.f...@gmail.com escribió: i have event timing stretch of code i need to alter. here is code below: -- # we start each run with one full silent trial # creating a stub with the duration of a full block # less the discarded acquisitions stub = block_dur - (distax * tr) feed = sys.stdin.readlines() sess = -1 for line in feed: if re.search(line != rest): time = (line + line (-1)) + (distax * tr) print time elif (line(-1) = rest): # block onsets are determined by # block number, block duration, # and the stub; 3dDeconvolve # takes care of making these # global time = (line) + (distax * tr) print time - When you post some piece of code, copy paste it from the original source; don't retype. The code above don't even compile. my concern is that it is extracting line number and not data contained on a given line. I need it to extract data from each line (excluding lines with spaces and/or lines that contain the word pause or silence). Basically i need ONLY raw data extracted from line 1 - onward. How does a line look like? Post some sample lines. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
vsoler wrote: On Aug 28, 5:43 pm, Steven Rumbalski googleacco...@rumbalski.com wrote: On Aug 27, 3:06 pm, vsoler vicente.so...@gmail.com wrote: I am trying to read a csv file generated by excel. Although I succeed in reading the file, the format that I get is not suitable for me. I've done: import csv spamReader = csv.reader(open('C:\\abc.csv', 'r')) print spamReader _csv.reader object at 0x01022E70 for row in spamReader: print row ['codigo;nombre;cantidad'] ['a;qwe;1'] ['b;asd;2'] ['c;zxc;3'] My questions are: 1- Why using print spamReader I cannot see the data? I expected to see a list of lists, a kind of a matrix, but I get nothing 2- Why are the rows in a single string? I expected a list of fields that, when text, would be delimited by To tell the truth, the file generated by excel does not contain the strings delimited by . Isn't it weird? 3- Is there anything I can do to have my data in a list of lists structure? would another kind of data suit better my needs? Thank you for your help Vicente Soler the csv module can handle any delimiter. change this spamReader = csv.reader(open('C:\\abc.csv', 'r')) to this spamReader = csv.reader(open('C:\\abc.csv', 'r'), delimiter=';') hope this helps, Steven Rumbalski Thank you very much for all your comments. After reading them I can conclude that: 1- the CSV format is not standardized; each piece of software uses it differently 2- the C in CSV does not mean comma for Microsoft Excel; the ; comes from my regional Spanish settings 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank But, perhaps, there is no standard alternative to CSV !!! This depends on the use case of yourself or your users. If you could give more detail on what you are trying to achieve then I'm sure that more help will be forthcoming. For example, could the file be saved in Excel 97-2003 xls format and then processed with the excellent xlrd/xlwt/xlutils? They are available here:- http://pypi.python.org/pypi/xlutils/1.4.0 -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
In mailman.596.1251474438.2854.python-l...@python.org Ethan Furman et...@stoneleaf.us writes: kj wrote: Miles Kaufmann mile...@umich.edu writes: ...because the suite namespace and the class namespace would get out of sync when different objects were assigned to the class namespace: class C: x = 1 def foo(self): print x print self.x o = C() o.foo() 1 1 o.x = 2 o.foo() 1 2 But this unfortunate situation is already possible, because one can already define class C: x = 1 def foo(self): print C.x print self.x which would lead to exactly the same thing. This is not the same thing, and definitely not exactly the same thing. Thanks for the clarification! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
Bruno Desthuilliers wrote: If you're only writing your framework for learning purposes, you could as well go with Python 3, and implement everything from the ground up (not a trivial task FWIW). Python 3 isn't ready for prime time on web servers. Too many major modules, haven't been ported yet. Twisted and Django are now available up to Python 2.6; MySQLdb is available only up to Python 2.5. So the basics for web work aren't ready yet. Python 2.5 is more or less the stable version of Python for production use at the moment. 2.6 is a transition version to 3.0. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
On Aug 28, 11:12 am, Mark Roseman m...@markroseman.com wrote: Would it be useful to link to this from the main Python Tkinter documentation? Mark Thanks Mark, but i would hate to see more links to TCL code in the python docs. Whats the use of Tkinter if the docs are in TCL. Just learn TCL and skip the Python middleman. But i don;t want to code in TCL (*puke*) i much prefer Python even if i am calling wrapped TCL. Not to mention this link is not a complete coverage of all the widgets anyway. We desperately need a complete reference for tkinter written with only Python code that covers all widgets, all widget options, and all widget methods. And this would be a minimal effort if someone would just do it. Most of the information is already out there in various locations around the net. We just need to compile, compress, and edit it into one short and to the point reference material. I will happily volunteer to create on my own or contribute to the docs if i can get a guarantee from the tkinter maintainer that my work would not be in vain. -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
r wrote: On Aug 28, 11:12 am, Mark Roseman m...@markroseman.com wrote: Would it be useful to link to this from the main Python Tkinter documentation? Mark Thanks Mark, but i would hate to see more links to TCL code in the python docs. Whats the use of Tkinter if the docs are in TCL. Just learn TCL and skip the Python middleman. But i don;t want to code in TCL (*puke*) i much prefer Python even if i am calling wrapped TCL. Not to mention this link is not a complete coverage of all the widgets anyway. We desperately need a complete reference for tkinter written with only Python code that covers all widgets, all widget options, and all widget methods. And this would be a minimal effort if someone would just do it. Most of the information is already out there in various locations around the net. We just need to compile, compress, and edit it into one short and to the point reference material. I will happily volunteer to create on my own or contribute to the docs if i can get a guarantee from the tkinter maintainer that my work would not be in vain. Please go ahead and try it. Having read the Summary of Python tracker Issues on the python-dev mailing list, and followed from there to the bug tracker, it seems that all input is greatly appreciated. For the small issues the reply is often Thanks, done. Some things get rejected, and usually rightly so from what I can see. Others the issue is closed with the half way house committed/rejected. Work that out for yourself if you can.:) -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
David Smith d...@cornell.edu writes: 2- the C in CSV does not mean comma for Microsoft Excel; the ; comes from my regional Spanish settings The C really does stand for comma. I've never seen MS spit out semi-colon separated text on a CSV format. That's because you're running MS Office in a US language environment. In almost all of Europe MS products use comma as the decimal separator, and semicolon for CSV field separation. -- http://mail.python.org/mailman/listinfo/python-list
Query screen resolution?
Thought this would be easy, maybe I'm missing something :) Trying to query the x,y resolution of my screen. I've seen this available through http://python.net/crew/mhammond/win32/ : from win32api import GetSystemMetrics print width =, GetSystemMetrics (0) print height =,GetSystemMetrics (1) But I was hoping for something built-in, and something non-OS specific. Is that available? Would be nice to detect for multiple monitors as well, but I'm probably asking too much :) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Query screen resolution?
But I was hoping for something built-in, and something non-OS specific. I don't know about built-ins, but I do believe that pygame (which *is* cross-platform) will let you get at that information: http://www.pygame.org/docs/ref/display.html#pygame.display.Info On Fri, 28 Aug 2009 11:13:06 -0700, AK Eric warp...@sbcglobal.net wrote: Thought this would be easy, maybe I'm missing something :) Trying to query the x,y resolution of my screen. I've seen this available through http://python.net/crew/mhammond/win32/ : from win32api import GetSystemMetrics print width =, GetSystemMetrics (0) print height =,GetSystemMetrics (1) But I was hoping for something built-in, and something non-OS specific. Is that available? Would be nice to detect for multiple monitors as well, but I'm probably asking too much :) Thanks! -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Object's nesting scope
On 28 авг, 16:07, Bruno Desthuilliers bruno. 42.desthuilli...@websiteburo.invalid wrote: zaur a écrit : On 26 авг, 17:13, Diez B. Roggisch de...@nospam.web.de wrote: Whom am we to judge? Sure if you propose this, you have some usecases in mind - how about you present these Ok. Here is a use case: object initialization. For example, person = Person(): name = john age = 30 address = Address(): street = Green Street no = 12 vs. person = Person() person.name = john person.age = 30 address = person.address = Address() address.street = Green Street address.no = 12 Err... Looks like you really should read the FineManual(tm) - specifically, the parts on the __init__ method. class Person(object): def __init__(self, name, age, address): self.name = name self.age = age self.address = address class Address(object): def __init__(self, street, no): self.no = no self.street = street person = Person( name=john, age=30, address = Address( street=Green Street, no=12 ) ) What are you doing if 1) classes Person and Address imported from foreign module 2) __init__ method is not defined as you want? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
John Nagle a écrit : Bruno Desthuilliers wrote: If you're only writing your framework for learning purposes, you could as well go with Python 3, and implement everything from the ground up (not a trivial task FWIW). Python 3 isn't ready for prime time on web servers. Too many major modules, haven't been ported yet. Which ones (sorry, still using 2.5 at work so I didn't bother that much with 2.6 so far) ? MySQLdb is available only up to Python 2.5. So the basics for web work aren't ready yet. I wouldn't label MySQLdb as a basic for web work - I mean, something you just can't do without !-) -- http://mail.python.org/mailman/listinfo/python-list
how to edit .wsgi file extebtions with IDLE on windows
I can't figure out how to enable the .py shell and syntax highlighting for .wsgi file extensions using IDLE for windows ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
hoffik wrote: Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. Thanks Hoffik Python doesn't have 2d matrices as a native type. Others have already suggested Numpy. But I'll assume you really want to stick with what's included in base Python, because you're still learning. (Aren't we all?) The real question to me is how this data is related to each other. If it's uniform data, organized in a 3x20 rectangle, or whatever, then maybe you want to use a single list, and just use slicing to extract particular rows and columns. You were actually using slicing in your example above; that's what the colon does. But in your case, you used defaults for the 3 arguments, so you got a *copy* of the entire list. Slicing to get one row would be simplyvalues[row*3:(row+1)*3], and one column would be print values[column: -1: 3] Notice that I hardcoded the width of our matrix, since list doesn't know anything about it. And notice it's easy to add more rows, but not easy to change row size, because that's not part of the structure, but part of the code to access it. Next possibility is to make a class to describe the data structure. You can make methods that mimic the behavior you want. But I suspect that the row is 3 specific values, maybe not even the same type as each other. So they might be name, address, and phone number. Each row represents a family, and each column represents a type of data. In this case, I'd suggest making each row an instance of a new class you define, and making a list of those objects. Now, you might be representing a row by an object of your class. And representing a column by two things: your list an accessor method that knows how to extract that particular field. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to exclude imports from PyDoc
Hi Diez, Thanks for the heads up. I'll give epydoc a shot. Matt Anyone know the best way to getPyDocto ignore this (or other) imported module(s)? Don't know aboutpydoc, but epydoc (which generates much nicer docs imho) can be forced to only include certain packages. Diez -- http://mail.python.org/mailman/listinfo/python-list
copy construtor question
Hi all, I am trying to define a class with copy constructor as following: class test: def __init__(self, s=None): self=s x=[1,2] y=test(x) print y.__dict__ it gives {} The above code doesn't work. Questions are: 1. Can 'self ' be a class attribute? 2. How to make a copy constructor? Thanks for any help. Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: Query screen resolution?
On Aug 28, 11:27 am, Rami Chowdhury rami.chowdh...@gmail.com wrote: But I was hoping for something built-in, and something non-OS specific. I don't know about built-ins, but I do believe that pygame (which *is* cross-platform) will let you get at that information: http://www.pygame.org/docs/ref/display.html#pygame.display.Info Actually, I just came up with another hack using PyGame as well like so: screen = pygame.display.set_mode((0,0)) WIDTH, HEIGHT = screen.get_size() If you pass zero values into the resolution, it will pop to the current screen resolution. And since I'm making a PyGame app, this actually works out ok. However, querying the current_w current_h attrs from the Info object is a lot cleaner (I was unaware of that, thanks!) But I'd sure like to know if there is built-in way. -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
hoffik wrote: Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. rows = [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] cols = zip(*rows) To just get the second column: zip(*rows)[1] -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Colors on IDLE
Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic -- http://mail.python.org/mailman/listinfo/python-list
comparison on list yields surprising result
In [21]: x Out[21]: [1, 2, 3, 5] In [22]: x6 Out[22]: True Is this a bug? -- View this message in context: http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195170.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors on IDLE
On Aug 28, 8:58 pm, vsoler vicente.so...@gmail.com wrote: Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic Couldn't finish writing... sorry --- Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic However, everything remains black. Any help is highly appreciated Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the csv library
On Aug 29, 2:35 am, vsoler vicente.so...@gmail.com wrote: 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank Correct. Quoting is necessary only if a text field contains a delimiter (semicolon/comma), a newline, or the quote character. You can read Excel CSV output using the Python csv module by specifying delimiter=; If you need to feed a CSV file to some software that demands that text fields be quoted unconditionally, you have at least two options: (1) If you know which fields should be text fields, you can read the Excel-output file with Python csv, convert your non-text fields to float, and write it back out with quoting=csv.QUOTE_NONNUMERIC. (2) If you want precise control (and thus precise knowledge), use xlrd (http://pypi.python.org/pypi/xlrd) to read Excel 97-2003 .xls files -- it will tell you cell by cell (NOT column by column (the user has control of the type at the cell level)) whether the cell contains text (reported as a unicode object), a number (float), a Boolean (int, 1 or 0), a date (float, days since ? (read the docs)), or an error code e.g. #DIV/0! (int, read the docs) ... then you can write it out however you like. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: comparison on list yields surprising result
On Aug 29, 5:00 am, Dr. Phillip M. Feldman pfeld...@verizon.net wrote: In [21]: x Out[21]: [1, 2, 3, 5] In [22]: x6 Out[22]: True Is this a bug? No. http://docs.python.org/reference/expressions.html#notin -- http://mail.python.org/mailman/listinfo/python-list
Re: comparison on list yields surprising result
Dr. Phillip M. Feldman schrieb: In [21]: x Out[21]: [1, 2, 3, 5] In [22]: x6 Out[22]: True Is this a bug? In python2.x, it's the defined behavior - all types are somhow comparable. The comparison is stable (all lists compare larger to all ints), but of course this by no means well-defined. This debatable design-decision has been remedied in Python3: Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type help, copyright, credits or license for more information. list(range(10)) 10 Traceback (most recent call last): File stdin, line 1, in module TypeError: unorderable types: list() int() Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
r wrote: Whats the use of Tkinter if the docs are in TCL. Just learn TCL and skip the Python middleman. But Mark's tutorial at http://www.tkdocs.com/tutorial/index.html allows you to select 'Python' as one of the languages you want to see the example code in. Too bad that the 'ttk' widgets are not mainstream yet. Greetings, -- The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing. - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html -- http://mail.python.org/mailman/listinfo/python-list
Re: comparison on list yields surprising result
Dr. Phillip M. Feldman schrieb: In [21]: x Out[21]: [1, 2, 3, 5] In [22]: x6 Out[22]: True Is this a bug? In python2.x, it's the defined behavior - all types are somhow comparable. The comparison is stable (all lists compare larger to all ints), but of course this by no means well-defined. This debatable design-decision has been remedied in Python3: Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type help, copyright, credits or license for more information. list(range(10)) 10 Traceback (most recent call last): File stdin, line 1, in module TypeError: unorderable types: list() int() Diez -- http://mail.python.org/mailman/listinfo/python-list
how to send 100 continues in wsgi application ?
how do you send 100 continues in a wsgi applications ? when using curl -T file http://localhost/upload.wsgi on the wsgiref.simple_server it get stuck waiting for a 100 continue import os def application(environ, response): query=os.path.join(os.path.dirname(__file__),'teemp') range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes ','').split('/')[0].split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'ab+') as f: if environ['REQUEST_METHOD']=='PUT': f.seek(int(offset[0][0])) f.truncate() while True: chunk=environ['wsgi.input'].read(8192) if not chunk: break f.write(chunk) f.flush() l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] -- http://mail.python.org/mailman/listinfo/python-list
Re: Overriding iadd for dictionary like objects
In article 21e57363-4e92-41cb-9907-5aef96ad0...@o15g2000yqm.googlegroups.com, RunThePun ubershme...@gmail.com wrote: Anybody have any more ideas? I think python should/could havev a syntax for overriding this behaviour, i mean, obviously the complexity of supporting all operators with the getitem syntax could introduce alot of clutter. But maybe there's an elegant solution out there... Any solution you create must support this: L = [3] L[0] += 7 L [10] -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ I support family values -- Addams family values --www.nancybuttons.com -- http://mail.python.org/mailman/listinfo/python-list
Re: comparison on list yields surprising result
It looks as though what I should have done is the following: In [23]: array(x) 6 Out[23]: array([False, False, False, False], dtype=bool) -- View this message in context: http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195893.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors on IDLE
On Fri, Aug 28, 2009 at 12:00 PM, vsolervicente.so...@gmail.com wrote: On Aug 28, 8:58 pm, vsoler vicente.so...@gmail.com wrote: Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic Couldn't finish writing... sorry --- Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic However, everything remains black. Any help is highly appreciated What OS are you on? - Chris -- http://mail.python.org/mailman/listinfo/python-list