Re: Are routine objects guaranteed mutable & with dictionary?
* MRAB: Alf P. Steinbach wrote: > * Dennis Lee Bieber: >> On Sat, 05 Dec 2009 11:26:34 +0100, "Alf P. Steinbach" >> declaimed the following in >> gmane.comp.python.general: >> >>> The devolution of terminology has been so severe that now even the >>> Wikipedia article on this subject confounds the general concept of >>> "routine" with the far more specialized term "sub-routine", which >>> is just one kind of routine. It is of >> >> Well, if this were a FORTRAN IV text from the mid-70s you'd be >> talking about >> >> function subprograms >> and >> subroutine subprograms > > It's in that direction yes, but the distinction that you mention, > which is essentially the same as Pascal 'function' versus > 'procedure', or Visual Basic 'function' versus 'sub', is just a > distinction of two variants of subroutines. > > Up above there is the more general concept of a routine, where there > are more possibilites than just subroutines; Python generators are > one example. > > As I mentioned earlier, in Eiffel, which is a more modern language > than Fortran, routines are still called routines. And specialized > terms include "routine". So it's not like that language independent > terminology has been phased out in general; it's mostly only in the C > syntax family (e.g. Python operators come mostly from C) that > "function" is, misleadingly and with associated severe constraints, > used as a general term. > In C there were originally only functions; if you didn't specify a return type then it would default to 'int' ('void' was a later addition). In Python there are only functions; if you don't explicitly return a value then None is returned. The distinction between functions and procedures can be helpful in deciding whether something is Pythonic (for example, in the use of list comprehensions), but in reality they are all still functions. I'm sorry, but, first, looking at ways to emulate a syntax, thinking about whether something looks like mathematical functions, the eye-candy, is pretty irrelevant, at least IMO. To see that it is irrelevant you might consider how that works in assembly language. Or you might consider that a call of a C++ 'void' routine can be used in C++ expressions. I think that even by your mainly visual syntax criterion that must be difficult to think of as a "function". Another way of looking at it is that the information conveyed by a result restricted to N=1 possible significant values, such as Python None or C arbitrary value (all possible return values of a non-result-producing routine to be treated as the same), is log(N)/log(2) = log(1)/whatever = 0, i.e., the routine then produces zero information via its expression result. Second, what's discussed isn't the distinction between various kinds of subroutines, so that wrt. to the earlier thread it's at best a detail. Although I think that the distinction that you and Dennis raise *is* a useful discussion! :-) Cheers & hth., - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert string function to string method?
On Sun, Dec 6, 2009 at 10:47 PM, Dr. Phillip M. Feldman < pfeld...@verizon.net> wrote: > > I wrote a handy-dandy function (see below) called "strip_pairs" for > stripping > matching pairs of characters from the beginning and end of a string. This > function works, but I would like to be able to invoke it as a string method > rather than as a function. Is this possible? > No. String objects are immutable and you can not set new attributes/methods on the type itself. Really the best thing to do in this case is to just have this in an easy to access library, and call it as a function and not a string method. The only alternative is to create a string subtype which has a new method-- but that would require all the strings you're using to be this subclass. E.g. you'd have to do MyString(regular_String) for each. This is really IMHO unwieldy and not really worth the effort -- just put strip_pairs into a library and call it as a function. --S -- http://mail.python.org/mailman/listinfo/python-list
how to convert string function to string method?
I wrote a handy-dandy function (see below) called "strip_pairs" for stripping matching pairs of characters from the beginning and end of a string. This function works, but I would like to be able to invoke it as a string method rather than as a function. Is this possible? def strip_pairs(s=None, open='([{\'"', close=')]}\'"'): """This function strips matching pairs of characters from the beginning and end of the input string `s`. `open` and `close` specify corresponding pairs of characters, and must be equal-length strings. If `s` begins with a character in `open` and ends with the corresponding character in `close`, both are removed from the string. This process continues until no further matching pairs can be removed.""" if len(open) != len(close): raise Exception, \ '\'open\' and \'close\' arguments must be strings of equal length.' # If input is missing or is not of type `str` (or `unicode`), return None: if s is None or not isinstance(s,(str,unicode)): return None while len(s) >= 2: # Check whether first character of `s` is in `open`: i= open.find(s[0]) # If `s` does not begin with a character from `open`, there are no more # pairs to be stripped: if i == -1: break # If `s` does not begin and end with matching characters, there are no # more pairs to be stripped: if s[-1] != close[i]: break # Strip the first and last character from `s`: s= s[1:-1] return s -- View this message in context: http://old.nabble.com/how-to-convert-string-function-to-string-method--tp26673209p26673209.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the significance of after() in this code?
zeph wrote: > True, though by *context* the after method looks like it takes a time > (probably in milliseconds, given its size), and a method, and calls > the method after that amount of time, and returning some process/ > thread id to self.after_id. Though if that's right, we still don't > know if its synchronous or not, if its calling it in a new thread or a > new process, etc etc. "Please tell me what this function does based solely on its name and signature" is _still_ a ridiculous question, though, even given the context you can extrapolate from it. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the significance of after() in this code?
On Dec 6, 8:46 pm, Benjamin Kaplan wrote: > On Sun, Dec 6, 2009 at 10:29 PM, W. eWatson wrote: > > See Subject. > > def StackImages(self): > > self.Upload("P") > > self.after_id = self.master.after(1,self.GetFrameOne) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think this is close to winning an award for "least information > provided". How are we supposed to know with the information you gave > us? We don't know what package you're using, what type anything is, or > even the purpose of that method. Try putting this line in there > somewhere > print type(self.master) > > and then open up the interactive interpreter, import whatever you need and do > help(.after) True, though by *context* the after method looks like it takes a time (probably in milliseconds, given its size), and a method, and calls the method after that amount of time, and returning some process/ thread id to self.after_id. Though if that's right, we still don't know if its synchronous or not, if its calling it in a new thread or a new process, etc etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are routine objects guaranteed mutable & with dictionary?
Alf P. Steinbach wrote: > * Dennis Lee Bieber: >> On Sat, 05 Dec 2009 11:26:34 +0100, "Alf P. Steinbach" >> declaimed the following in >> gmane.comp.python.general: >> >>> The devolution of terminology has been so severe that now even the >>> Wikipedia article on this subject confounds the general concept of >>> "routine" with the far more specialized term "sub-routine", which >>> is just one kind of routine. It is of >> >> Well, if this were a FORTRAN IV text from the mid-70s you'd be >> talking about >> >> function subprograms >> and >> subroutine subprograms > > It's in that direction yes, but the distinction that you mention, > which is essentially the same as Pascal 'function' versus > 'procedure', or Visual Basic 'function' versus 'sub', is just a > distinction of two variants of subroutines. > > Up above there is the more general concept of a routine, where there > are more possibilites than just subroutines; Python generators are > one example. > > As I mentioned earlier, in Eiffel, which is a more modern language > than Fortran, routines are still called routines. And specialized > terms include "routine". So it's not like that language independent > terminology has been phased out in general; it's mostly only in the C > syntax family (e.g. Python operators come mostly from C) that > "function" is, misleadingly and with associated severe constraints, > used as a general term. > In C there were originally only functions; if you didn't specify a return type then it would default to 'int' ('void' was a later addition). In Python there are only functions; if you don't explicitly return a value then None is returned. The distinction between functions and procedures can be helpful in deciding whether something is Pythonic (for example, in the use of list comprehensions), but in reality they are all still functions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 6, 1:48 pm, sturlamolden wrote: > On 6 Des, 21:52, r0g wrote: > > > > .> Right. Using abs(x-y) < eps is the way to go. > > > .> > > > .> Raymond > > > > This only works when abs(x) and abs(y) are larger that eps, but not > > > too much larger. > > > Okay, I'm confused now... I thought them being larger was entirely the > > point. > > Yes. dbd got it wrong. If both a smaller than eps, the absolute > difference is smaller than eps, so they are considered equal. Small x,y failure case: eps and even eps squared are representable as floats. If you have samples of a sine wave with peak amplitude of one half eps, the "abs(x- y) < eps" test would report all values on the sine wave as equal to zero. This would not be correct. Large x,y failure case: If you have two calculation paths that symbolically should produce the same value of size one over eps, valid floating point implementations may differ by an lsb or more. An single lsb error would be 1, much greater than the test allows as 'nearly equal' for floating point comparison. 1.0 + eps is the smallest value greater than 1.0, distinguishable from 1.0. Long chains of floating point calculations that would symbolically be expected to produce a value of 1.0 many be expected to produce errors of an eps or more due to the inexactness of floating point representation. These errors should be allowed in floating point equality comparison. The value of the minimum representable error will scale as the floating point number varies. A constant comparison value is not appropriate. Mark was right, DaveA's discussion explains a strategy to use. Dale B. Dalrymple -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators.
On 12/7/2009 7:22 AM, Jorge Cardona wrote: Hi, I was trying to create a function that receive a generator and return a list but that each elements were computed in a diferent core of my machine. I start using islice function in order to split the job in a way that if there is "n" cores each "i" core will compute the elements i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: it's nothing weird, python just do what you're telling it to: transform all x in X with f(x) g = (f(x) for x in X) then slice the result of that print(list(x for x in islice(g,0,None,2))) what you want to do is to slice before you transform: >>> g = (x for x in islice(X, 0, None, 2)) >>> print(list(f(x) for x in g)) eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] islice execute the function at the generator and drop the elements that aren't in the slice. I found that pretty weird, the way that i see generators is like an association between and indexing set (an iterator or another generator) and a computation that is made indexed by the indexing set, and islice is like a "transformation" on the indexing set,it doesn't matter the result of the function, the slice should act only on the indexing set, some other "transformation" like takewhile act on the result so, the execution it has to be made, but in the islice, or other "transformation" that act only in the indexing set, the function shouldn't be executed at each element, but only on that new set that result of the application of the "transformation" on the original set. that seems like an extremely lazy evaluation, I don't know if even a true lazy language do that. Python is a strict language, with a few laziness provided by generators, in the end it's still a strict language. Well, it works for what i need, but is not very neat, and i think that there it should be a formal way to act on the base indexing iterator, such way exists? Is there a better approach to get what i need? Reverse your operation. -- http://mail.python.org/mailman/listinfo/python-list
python proxy checker ,change to threaded version
Hello ALL, i have some python proxy checker . and to speed up check, i was decided change to mutlthreaded version, and thread module is first for me, i was tried several times to convert to thread version and look for many info, but it not so much easy for novice python programmar . if anyone can help me really much appreciate!! thanks in advance! import urllib2, socket socket.setdefaulttimeout(180) # read the list of proxy IPs in proxyList proxyList = open('listproxy.txt').read() def is_bad_proxy(pip): try: proxy_handler = urllib2.ProxyHandler({'http': pip}) opener = urllib2.build_opener(proxy_handler) opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib2.install_opener(opener) req=urllib2.Request('http://www.yahoo.com') # <---check whether proxy alive sock=urllib2.urlopen(req) except urllib2.HTTPError, e: print 'Error code: ', e.code return e.code except Exception, detail: print "ERROR:", detail return 1 return 0 for item in proxyList: if is_bad_proxy(item): print "Bad Proxy", item else: print item, "is working" -- View this message in context: http://old.nabble.com/python-proxy-checker-%2Cchange-to-threaded-version-tp26672548p26672548.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the significance of after() in this code?
On Sun, Dec 6, 2009 at 10:29 PM, W. eWatson wrote: > See Subject. > def StackImages(self): > self.Upload("P") > self.after_id = self.master.after(1,self.GetFrameOne) > -- > http://mail.python.org/mailman/listinfo/python-list > I think this is close to winning an award for "least information provided". How are we supposed to know with the information you gave us? We don't know what package you're using, what type anything is, or even the purpose of that method. Try putting this line in there somewhere print type(self.master) and then open up the interactive interpreter, import whatever you need and do help(.after) -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the significance of after() in this code?
On Dec 6, 7:29 pm, "W. eWatson" wrote: > See Subject. > def StackImages(self): > self.Upload("P") > self.after_id = self.master.after(1,self.GetFrameOne) It's a "method" of the object that is bound to "self.master". It's return value is then bound to the attribute "after_id" of the object "self". Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
What is the significance of after() in this code?
See Subject. def StackImages(self): self.Upload("P") self.after_id = self.master.after(1,self.GetFrameOne) -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
Carl Banks wrote: On Dec 6, 11:34 am, Anton81 wrote: I do some linear algebra and whenever the prefactor of a vector turns out to be zero, I want to remove it. I'd like to keep the system comfortable. So basically I should write a new class for numbers that has it's own __eq__ operator? Is there an existing module for that? I highly recommend against it; among other things it invalidates the transitive property of equality: "If a =b and b == c, then a == c." It will also make the number non-hashable, and have several other negative consequences. Plus, it's not something that's never foolproof. What numbers are close enought to be condidered "equal" depends on the calculations. (I remember once struggling in a homework assignment over seemingly large discrepancies in a calculation I was doing, until i realized that the actual numbers were on the scale of 10**11, and the difference was around 10**1, so it really didn't matter.) Carl Banks A few decades ago I implemented the math package (microcode) under the machine language for a proprietary processor (this is when a processor took 5 boards of circuitry to implement). I started with floating point add and subtract, and continued all the way through the trig, log, and even random functions. Anyway, a customer called asking whether a particular problem he had was caused by his logic, or by errors in our math. He was calculating the difference in height between an always-level table and a perfectly flat table (between an arc of a great circle around the earth, and a flat table that doesn't follow the curvature.) In a couple of hundred feet of table, the difference was measured in millionths of an inch, as I recall. Anyway it turned out his calculation was effectively subtracting (8000 miles plus a little bit) - (8000 miles) and if he calculated it three different ways, he got three different results, one was off in about the 3rd place, while the other was only half the value. I was able to show him another way (through geometrical transformations) to solve the problem that got the exact answer, or at least to more digits than he could possibly measure. I think I recall that the new solution also cancelled out the need for trig. Sometimes the math package shouldn't hide the problem, but give it to you straight. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
"Phillip M. Feldman" wrote: > It does seem as though IPython could be a bit more clever about this. I disagree. I _like_ that IPython is only reporting on the current state of the interpreter and not trying to second guess what I meant. > If the user asks for documentation on xyz via "?xyz" and xyz is not > defined, then I'd like to see IPython check for a module named "xyz" and > if it exists, extract and display the docstring. How would you recommend IPython distinguish between which "xyz" you meant: the one in site-packages, the one in some package on the python path, or the one in the folder you're running IPython from? -- http://mail.python.org/mailman/listinfo/python-list
Re: High-performance Python websites
The key to scaling a web site is to make sure you can load-balance to as many front ends as needed and then use a common database backend that is fast enough or possibly a common file system that is fast enough. I can't speak to Django specifically but you can certainly get essentially unlimited scalability on the front-end side of the equation using a Python based web app. The google app engine will set such a configuration up for you automatically, but they are still working some bugs out with regard to performance, I think, based on my experience here http://whiffdoc.appspot.com/ and here http://listtree.appspot.com/ I hope that helps. -- Aaron Watters === an apple every 8 hours will keep 3 doctors away. -kliban -- http://mail.python.org/mailman/listinfo/python-list
Re: Are routine objects guaranteed mutable & with dictionary?
* Dennis Lee Bieber: On Sat, 05 Dec 2009 11:26:34 +0100, "Alf P. Steinbach" declaimed the following in gmane.comp.python.general: The devolution of terminology has been so severe that now even the Wikipedia article on this subject confounds the general concept of "routine" with the far more specialized term "sub-routine", which is just one kind of routine. It is of Well, if this were a FORTRAN IV text from the mid-70s you'd be talking about function subprograms and subroutine subprograms It's in that direction yes, but the distinction that you mention, which is essentially the same as Pascal 'function' versus 'procedure', or Visual Basic 'function' versus 'sub', is just a distinction of two variants of subroutines. Up above there is the more general concept of a routine, where there are more possibilites than just subroutines; Python generators are one example. As I mentioned earlier, in Eiffel, which is a more modern language than Fortran, routines are still called routines. And specialized terms include "routine". So it's not like that language independent terminology has been phased out in general; it's mostly only in the C syntax family (e.g. Python operators come mostly from C) that "function" is, misleadingly and with associated severe constraints, used as a general term. Cheers, - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
Chris Rebert wrote: On Sun, Dec 6, 2009 at 12:34 PM, Dr. Phillip M. Feldman wrote: OK. I was able to reproduce the problem. My difficulty was that the command that I issued initially was "from xyz import *" rather than just "import xyz". If I say "import xyz", then the docstring is defined; if I say "from xyz import *", it isn't. I'm not sure whether this is a bug or expected behavior. Expected behavior. If you `from foo import bar`, the name `foo` won't be bound, so needless to say you won't be able to access its docstring foo.__doc__. $ ipython Python 2.6.2 (r262:71600, Nov 5 2009, 15:03:16) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: ?pickle Object `pickle` not found. In [2]: from pickle import * In [3]: ?pickle Object `pickle` not found. In [4]: pickle.__doc__ --- NameError Traceback (most recent call last) /Users/chris/ in () NameError: name 'pickle' is not defined In [5]: import pickle In [6]: ?pickle In [7]: pickle.__doc__ Out[7]: 'Create portable serialized representations of Python objects.\n\nSee module cPickle for a (much) faster implementation.\nSee module copy_reg for a mechanism for registering custom picklers.\nSee module pickletools source for extensive comments.\n\nClasses:\n\nPickler\nUnpickler\n\nFunctions:\n\n dump(object, file)\ndumps(object) -> string\nload(file) -> object\nloads(string) -> object\n\nMisc variables:\n\n __version__\nformat_version\ncompatible_formats\n\n' Cheers, Chris -- http://blog.rebertia.com Hello Chris- It does seem as though IPython could be a bit more clever about this. If the user asks for documentation on xyz via "?xyz" and xyz is not defined, then I'd like to see IPython check for a module named "xyz" and if it exists, extract and display the docstring. Phillip -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Sun, Dec 6, 2009 at 1:46 AM, Mark Dickinson wrote: > On Dec 5, 3:37 pm, Anton81 wrote: >> I'd like to do calculations with floats and at some point equality of >> two number will be checked. >> What is the best way to make sure that equality of floats will be >> detected, where I assume that mismatches beyond a certain point are >> due to truncation errors? > > Well, it depends a lot on the details of the application, but > a good general scheme is to allow both a fixed relative error > and an absolute error, and to assert that your two values are > 'nearly equal' if they're within *either* the relative error *or* > the absolute error. Something like, for example: > > def almostEqual(expected, actual, rel_err=1e-7, abs_err = 1e-20): > absolute_error = abs(actual-expected) > return absolute_error <= max(abs_err, rel_err * abs(expected)) If you can depend on IEEE 754 semantics, one relatively robust method is to use the number of representable floats between two numbers. The main advantage compared to the proposed methods is that it somewhat automatically takes into account the amplitude of input numbers: abs(x - y) <= N * spacing(max(abs(x), abs(y))) Where spacing(a) is the smallest number such as a + spacing(a) != a. Whether a and b are small or big, the same value of N can be used, and it tells you how close two numbers are in terms of internal representation. Upcoming numpy 1.4.0 has an implementation for spacing - implementing your own for double is not difficult, though, cheers, David -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 6, 4:54 pm, Carl Banks wrote: > On Dec 6, 11:34 am, Anton81 wrote: > > > I do some linear algebra and whenever the prefactor of a vector turns > > out to be zero, I want to remove it. > > > I'd like to keep the system comfortable. So basically I should write a > > new class for numbers that has it's own __eq__ operator? > > Is there an existing module for that? > > I highly recommend against it; among other things it invalidates the > transitive property of equality: > > "If a == b and b == c, then a == c." > > It will also make the number non-hashable, and have several other > negative consequences. What numbers are close enought to be condidered > "equal" > depends on the calculations. > > (I remember once struggling in a homework assignment over seemingly > large discrepancies in a calculation I was doing, until i realized > that the actual numbers were on the scale of 10**11, and the > difference was around 10**1, so it really didn't matter.) > > Carl Banks Maybe it's the gin, but "Plus, it's not something that's never foolproof.' +1 QOTW Cheers, TheSeeker -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 6, 11:34 am, Anton81 wrote: > I do some linear algebra and whenever the prefactor of a vector turns > out to be zero, I want to remove it. > > I'd like to keep the system comfortable. So basically I should write a > new class for numbers that has it's own __eq__ operator? > Is there an existing module for that? I highly recommend against it; among other things it invalidates the transitive property of equality: "If a == b and b == c, then a == c." It will also make the number non-hashable, and have several other negative consequences. Plus, it's not something that's never foolproof. What numbers are close enought to be condidered "equal" depends on the calculations. (I remember once struggling in a homework assignment over seemingly large discrepancies in a calculation I was doing, until i realized that the actual numbers were on the scale of 10**11, and the difference was around 10**1, so it really didn't matter.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
Edward A. Falk wrote: For development purposes, you should stick with the oldest version that will actually run your code. Every time you move to a more modern version, you're leaving potential users/customers out in the cold. If the fear of customers disatification prevents you from using a certain version of X, you should consider a deployment strategy that cuts out dependencies as much as possible. Although this will result in a larger end package and possible high amount of duplication, it is still preferable to just stop supporting popular platforms or be swamped away with bugs due to version mismatches. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
On 06-Dec-09 13:25 PM, Luis M. González wrote: On Dec 6, 3:21 pm, vsoler wrote: I recently read that many libraries, including Numpy have not been ported to Python 3. When do you think that Python 3 will be fully deployed? Should I stick, so far, to Python 2.6? Regards Vicente Soler You'll have some answers here: http://jessenoller.com/2009/12/04/pythons-moratorium-lets-think-about-this/ 2.7 is now available. Work is going on numpy with Python 3.0 Colin W. -- http://mail.python.org/mailman/listinfo/python-list
CMNDBOT 0.1 BETA2 released
Hello world ! a week after BETA1 i'm releasing BETA2, changes go fast ;] what changed in this version: * RSS plugin can now push to xmpp clients .. add cmnd...@appspot.com to your jabber client and do 1) rss-add to add a feed 2) use rss-start to make the bot start sending you feed updates. * a gadget plugin that enables you to load gadgets with one command (well two if you need to add the gadgets url) * a iframe gadget was made that loads the bots web interface into wave and other gadget containers * focus of the command box is now off when loading the gadget * a plugin dedicated to wave functionality was made. currently it has commands to get the id of the wave, getting the url redirecting to the wave and one to get a list of the wave's participants * lots of other bug fixes .. running from one to the other ;] Bart About CMNDBOT: CMNDBOT is an IRC like command bot for wave, web and xmpp, and has a plugin structure to allow users to program there own plugins. CMNDBOT is free code (BSD) so you can clone it and run a CMNDBOT yourself. Source is available at http://cmndbot.googlecode.com/ For a live example of CMNDBOT see cmnd...@appspot.com for jabber and wave and http://cmndbot.appspot.com for web. You can also try the new iframe gadget at http://cmndbot.appspot.com/iframe.xml or ... invite the bot to your wave and run !load cmndbot ;] feedback is very much appriciated, i made a wave where we can meet: https://wave.google.com/wave/#restored:wave:googlewave.com!w%252BV9a2mVSOC -- http://mail.python.org/mailman/listinfo/python-list
hola
hola soy un pequeño programador y quiesiera pedirles ayuda para programar en python, no se si me podrian mandar ejemplos para poder empezar, y como terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias -- ..FrankiSoft... -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
Anton81 wrote: I do some linear algebra and whenever the prefactor of a vector turns out to be zero, I want to remove it. I'd like to keep the system comfortable. So basically I should write a new class for numbers that has it's own __eq__ operator? Is there an existing module for that? You have to define your own "comfortable." But if it's zero you're checking for, then I most certainly wouldn't try to hide it inside a "number class." Most such formulas go ballistic when you get near zero. The definition of 'close enough" is very context dependent, and shouldn't be hidden at too low a level. But your mileage may vary. For example, in your case, you might want to check that the prefactor is much smaller than the average (of the abs values) of the vector elements. Enough orders of magnitude smaller, and you call it equal to zero. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
In article , vsoler wrote: >I recently read that many libraries, including Numpy have not been >ported to Python 3. > >When do you think that Python 3 will be fully deployed? It will never be fully deployed. There will always be people out there who haven't felt it necessary to upgrade their systems. The question you should be asking is "when will the percentage of systems without Python 3 be so small that I don't care about the customers I'll lose if I switch?" I can say personally that I still haven't seen any needs pressing enough to upgrade my perfectly-function Ubuntu 8 system. That means I can't even run Python 2.6 code. I'm still using 2.5. >Should I stick, so far, to Python 2.6? For development purposes, you should stick with the oldest version that will actually run your code. Every time you move to a more modern version, you're leaving potential users/customers out in the cold. -- -Ed Falk, f...@despams.r.us.com http://thespamdiaries.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Can't I Delete a File I Created with Win XP?
Hans Mulder wrote: J wrote: But that being said, this brings to mind a question about this... in *nix, when I can't do something like delete a file or directory, or unmount a filesystem and cant find the cause, I can do an lsof and grep for references to the file/directory in question, then work from there to close anything that still has a lock. It's been a while since a last had this problem. I found a program named "handle.exe" somewhere on microsoft.com. It spits out a listing showing which process has which files open. You can kill the offending processes, and then you can delete your file. I suppose Google can help you find this program. Hope this helps, -- HansM Handle.exe and "Process Explorer" (mentioned by J) are both from Sysinternals, which was acquired by Microsoft, and to be found on their site. http://technet.microsoft.com/en-us/sysinternals/default.aspx http://technet.microsoft.com/en-us/sysinternals/bb896655.aspxfor handle.exe http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx for process explorer But as long as I'm in the thread, I'll state that I suspect the problem to be simply that the OP is running his script inside some IDE, and it hasn't really ended. So the first thing I'd try is to exit the IDE, and see whether the file is then released. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On 6 Des, 21:52, r0g wrote: > > .> Right. Using abs(x-y) < eps is the way to go. > > .> > > .> Raymond > > > This only works when abs(x) and abs(y) are larger that eps, but not > > too much larger. > > Okay, I'm confused now... I thought them being larger was entirely the > point. Yes. dbd got it wrong. If both a smaller than eps, the absolute difference is smaller than eps, so they are considered equal. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
Dr. Phillip M. Feldman, 06.12.2009 21:34: > OK. I was able to reproduce the problem. My difficulty was that the command > that I issued initially was "from xyz import *" rather than just "import > xyz". If I say "import xyz", then the docstring is defined; if I say "from > xyz import *", it isn't. I'm not sure whether this is a bug or expected > behavior. Definitely expected behaviour. The problem isn't the docstring but what you import. "from xyz import a,b,c" does not import "xyz" into the current namespace. Only the names a,b,c are imported. If you do "import xyz", then "xyz" becomes a defined name in your current namespace. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
On Sun, Dec 6, 2009 at 12:34 PM, Dr. Phillip M. Feldman wrote: > OK. I was able to reproduce the problem. My difficulty was that the command > that I issued initially was "from xyz import *" rather than just "import > xyz". If I say "import xyz", then the docstring is defined; if I say "from > xyz import *", it isn't. I'm not sure whether this is a bug or expected > behavior. Expected behavior. If you `from foo import bar`, the name `foo` won't be bound, so needless to say you won't be able to access its docstring foo.__doc__. $ ipython Python 2.6.2 (r262:71600, Nov 5 2009, 15:03:16) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: ?pickle Object `pickle` not found. In [2]: from pickle import * In [3]: ?pickle Object `pickle` not found. In [4]: pickle.__doc__ --- NameError Traceback (most recent call last) /Users/chris/ in () NameError: name 'pickle' is not defined In [5]: import pickle In [6]: ?pickle In [7]: pickle.__doc__ Out[7]: 'Create portable serialized representations of Python objects.\n\nSee module cPickle for a (much) faster implementation.\nSee module copy_reg for a mechanism for registering custom picklers.\nSee module pickletools source for extensive comments.\n\nClasses:\n\nPickler\nUnpickler\n\nFunctions:\n\n dump(object, file)\ndumps(object) -> string\nload(file) -> object\nloads(string) -> object\n\nMisc variables:\n\n __version__\nformat_version\ncompatible_formats\n\n' Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3: Sane way to deal with broken encodings
Johannes Bauer a écrit : > Dear all, > > I've some applciations which fetch HTML docuemnts off the web, parse > their content and do stuff with it. Every once in a while it happens > that the web site administrators put up files which are encoded in a > wrong manner. > > Thus my Python script dies a horrible death: > > File "./update_db", line 67, in > for line in open(tempfile, "r"): > File "/usr/local/lib/python3.1/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position > 3286: unexpected code byte > > This is well and ok usually, but I'd like to be able to tell Python: > "Don't worry, some idiot encoded that file, just skip over such > parts/replace them by some character sequence". > > Is that possible? If so, how? This might get you started: """ >>> help(str.decode) decode(...) S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
dbd wrote: > On Dec 6, 1:12 am, Raymond Hettinger wrote: >> On Dec 5, 11:42 pm, Tim Roberts wrote: >> >>> Raymond Hettinger wrote: if not round(x - y, 6): ... >>> That's a dangerous suggestion. It only works if x and y happen to be >>> roughly in the range of integers. > .> > .> Right. Using abs(x-y) < eps is the way to go. > .> > .> Raymond > > This only works when abs(x) and abs(y) are larger that eps, but not > too much larger. Okay, I'm confused now... I thought them being larger was entirely the point. At what point can they become too large? Isn't eps entirely arbitrary anyway? > > Mark's suggestion is longer, but it works. The downside is it requires > you to think about the scale and accuracy of your application. > Shouldn't one be doing that in any case?? Roger. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
OK. I was able to reproduce the problem. My difficulty was that the command that I issued initially was "from xyz import *" rather than just "import xyz". If I say "import xyz", then the docstring is defined; if I say "from xyz import *", it isn't. I'm not sure whether this is a bug or expected behavior. -- View this message in context: http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26668758.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
Steven D'Aprano-7 wrote: > > On Sun, 06 Dec 2009 10:55:50 +0100, Andreas Waldenburger wrote: > >> On Sat, 5 Dec 2009 23:04:42 -0800 (PST) "Dr. Phillip M. Feldman" >> wrote: >> >> >>> If I create a module xyz.py with a docstring """xyz does everything you >>> could possibly want.""" at the top, the command ?xyz issued at the >>> IPython prompt does not display this docstring. What am I doing wrong? >> >> Stab in the dark: You have imported the module first, right? >> >> Also: Never, EVER, ask a question like this on any technical forum >> without posting your code (or rather: a minimal version of it that still >> exhibits the problem). That way, people can help you directly instead of >> taking wild guesses at what your problem might be. > > In fairness, Phillip's description of the problem is pretty straight- > forward: he has a module xyz.py with a docstring. The minimal version of > the code is no code at all, just a docstring: > > """xyz does everything you could possibly want.""" > > His problem isn't an error when running the code, but an error with > IPython's command ?xyz. > > What he didn't say is what IPython prints instead of the expected > docstring. Over to you Phillip, don't just tell us what IPython doesn't > do, tell us what it does do. > > My guesses are: > > * He hasn't imported the module, so he gets an error of some sort. > > * He hasn't actually defined a docstring. Docstrings have to be string > literals, you can't do this: > > """%s does everything you could possibly want.""" % "xyz" > > Nor can you have anything except comments and whitespace between the top > of the module and the string. > > * He has another module called xyz which is shadowing the module he > expects, and so he sees that module's docstring instead. > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > > My bad. This is working for me now. I could swear that I imported the module previously, but perhaps I didn't . My apologies, and thanks for the help! -- View this message in context: http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26668719.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Python3: Sane way to deal with broken encodings
Dear all, I've some applciations which fetch HTML docuemnts off the web, parse their content and do stuff with it. Every once in a while it happens that the web site administrators put up files which are encoded in a wrong manner. Thus my Python script dies a horrible death: File "./update_db", line 67, in for line in open(tempfile, "r"): File "/usr/local/lib/python3.1/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 3286: unexpected code byte This is well and ok usually, but I'd like to be able to tell Python: "Don't worry, some idiot encoded that file, just skip over such parts/replace them by some character sequence". Is that possible? If so, how? Kind regards, Johannes -- "Aus starken Potentialen können starke Erdbeben resultieren; es können aber auch kleine entstehen - und "du" wirst es nicht für möglich halten (!), doch sieh': Es können dabei auch gar keine Erdbeben resultieren." -- "Rüdiger Thomas" alias Thomas Schulz in dsa über seine "Vorhersagen" <1a30da36-68a2-4977-9eed-154265b17...@q14g2000vbi.googlegroups.com> -- http://mail.python.org/mailman/listinfo/python-list
Generators.
Hi, I was trying to create a function that receive a generator and return a list but that each elements were computed in a diferent core of my machine. I start using islice function in order to split the job in a way that if there is "n" cores each "i" core will compute the elements i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: from itertools import islice def f(x): print("eval: %d"%x) return x X = range(10) g = (f(x) for x in X) print(list(x for x in islice(g,0,None,2))) $ python2.5 test.py eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 2, 4, 6, 8] $ python2.7 test.py eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 2, 4, 6, 8] $ python3.0 test.py eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 2, 4, 6, 8] islice execute the function at the generator and drop the elements that aren't in the slice. I found that pretty weird, the way that i see generators is like an association between and indexing set (an iterator or another generator) and a computation that is made indexed by the indexing set, and islice is like a "transformation" on the indexing set,it doesn't matter the result of the function, the slice should act only on the indexing set, some other "transformation" like takewhile act on the result so, the execution it has to be made, but in the islice, or other "transformation" that act only in the indexing set, the function shouldn't be executed at each element, but only on that new set that result of the application of the "transformation" on the original set. I search a little bit and found that gi_frame.f_locals['.0'] holds the inner indexing element of a generator, so i decide to define my own islice like this: from itertools import islice import sys if sys.version_info[0] != 3: def next(it): return it.next() def f(x): print("eval: %d"%x) return x def islice(iterable, *args): s = slice(*args) # search the deepest iter (Base indexing set) it = iterable while hasattr(it, 'gi_frame'): it = it.gi_frame.f_locals['.0'] # Consume the base indexing set until the first element for i in range(s.start): it.next() for e in iterable: yield e # Consume the base indexing set until the next element for i in range(s.step-1): next(it) X = range(10) g = (f(x) for x in X) print(list(x for x in islice(g,0,None,2))) jcard...@terminus:/tmp$ python2.5 test.py eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] jcard...@terminus:/tmp$ python2.7 test.py eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] jcard...@terminus:/tmp$ python3.0 test.py eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] Well, it works for what i need, but is not very neat, and i think that there it should be a formal way to act on the base indexing iterator, such way exists? Is there a better approach to get what i need? Thanks. -- Jorge Eduardo Cardona jorgeecard...@gmail.com jorgeecardona.blogspot.com Linux registered user #391186 Registered machine#291871 -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
I do some linear algebra and whenever the prefactor of a vector turns out to be zero, I want to remove it. I'd like to keep the system comfortable. So basically I should write a new class for numbers that has it's own __eq__ operator? Is there an existing module for that? -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 6, 1:12 am, Raymond Hettinger wrote: > On Dec 5, 11:42 pm, Tim Roberts wrote: > > > Raymond Hettinger wrote: > > > > if not round(x - y, 6): ... > > > That's a dangerous suggestion. It only works if x and y happen to be > > roughly in the range of integers. .> .> Right. Using abs(x-y) < eps is the way to go. .> .> Raymond This only works when abs(x) and abs(y) are larger that eps, but not too much larger. Mark's suggestion is longer, but it works. The downside is it requires you to think about the scale and accuracy of your application. Dale B. Dalrymple -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Can't I Delete a File I Created with Win XP?
J wrote: But that being said, this brings to mind a question about this... in *nix, when I can't do something like delete a file or directory, or unmount a filesystem and cant find the cause, I can do an lsof and grep for references to the file/directory in question, then work from there to close anything that still has a lock. It's been a while since a last had this problem. I found a program named "handle.exe" somewhere on microsoft.com. It spits out a listing showing which process has which files open. You can kill the offending processes, and then you can delete your file. I suppose Google can help you find this program. Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
On Dec 6, 7:43 am, Steven D'Aprano wrote: > On Sun, 06 Dec 2009 06:34:17 -0600, Tim Chase wrote: > > I've occasionally wanted something like this, and have found that it can > > be done by manually assigning to __doc__ (either at the module-level or > > classes) which can make some documentation bits a little easier: > > Unfortunately, and surprisingly, assigning to __doc__ doesn't work with > new-style classes. > > -- > Steven Fortunately, in the OP's case, he isn't trying to do this with a class, but with a module. For me, assigning to __doc__ at the module works in defining a docstring for pyparsing, at least for Py2.5. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: NumPy installation won't import correctly
On Dec 1, 7:04 pm, Ethos wrote: > On Dec 1, 6:37 pm, David Cournapeau wrote: > > > On Wed, Dec 2, 2009 at 11:03 AM, Ethos wrote: > > > > I reinstallednumpy, from sourceforge, even though I had already > > > installed the latest version. Same business. 2.5 imports fine, 2.6 > > > doesn't. > > > > Here's the output of the commands you gave me. > > > Which exact version of mac os x are you using ? (the output of sw_vers > > -productVersion > > would be fine). > > > David > > ProductName: Mac OS X > ProductVersion: 10.5.8 > BuildVersion: 9L30 > > Kevin I am also trying to install numpy 1.4 and observing exactly the same symptoms as Kevin (unsurprisingly, since it's a very similar installation: BuildVersion of 10.5.8 is 9L31a, otherwise identical). I can also reproduce the problem with the 2.5 version of the 1.4 rc1 numpy DMG (with macpython 2.5.4 from python.org -- it refuses to install using Apple's own 2.5.1). Is there any known-to-work way to install numpy 1.4 on Mac OS X 10.5.8, and Python either 2.5 or 2.6? Guess next I'll try building from sources... Alex -- http://mail.python.org/mailman/listinfo/python-list
wxEasyGUI: Easy and Interactive GUI Function Dialogs for Python newbie
Python newbie, like me, need a simple, easy to understand and use, simple interactive GUI functions abd dialogs for starting using the language quickly. I wrote the wxEasyGUI simple library with this idea in my mind and started a new project on the SourceForge.net << wxEasyGUI - Easy to Use Interactive GUI Functions Dialogs based on "wxPython" and deep inspired by "EasyGui". >> Files are availables at http://sourceforge.net/projects/wxeasygui/files/ and on the Google Group http://groups.google.com/group/wxeasygui we can discuss this new small project. I very appreciate if the Python community can comments the idea, suggest improvements and review the wxEasyGUI code. Thanks. Valter Foresto. http://electronicbricks.blogspot.com/2009/11/wxeasygui.html -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
On Dec 6, 3:21 pm, vsoler wrote: > I recently read that many libraries, including Numpy have not been > ported to Python 3. > > When do you think that Python 3 will be fully deployed? > > Should I stick, so far, to Python 2.6? > > Regards > > Vicente Soler You'll have some answers here: http://jessenoller.com/2009/12/04/pythons-moratorium-lets-think-about-this/ -- http://mail.python.org/mailman/listinfo/python-list
Re: logging module, SMTPHandler and gmail in python 2.6
On Dec 4, 12:31 pm, mynthon wrote: Thank you for this suggestion. Ideally, you would have created an issue for this on bugs.python.org, because then it would be more likely to be acted upon. I've implemented this feature in r76691 (in Python trunk and py3k) in a more general way. It works by specifying an optional secure argument to SMTPHandler.__init__. This defaults to None, which implements the current behaviour - no TLS support. If TLS support is required, pass in a tuple for secure, with one of the following values: 1. An empty tuple 2. A 1-tuple with the name of the PEM-formatted keyfile with a private key. 3. A 2-tuple with the name of the PEM-formatted keyfile and a PEM- formatted certificate chain file. This tuple, if specified, is passed to the SMTP object's starttls method (and via that to socket.ssl). Check the starttls/ssl methods for more information. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
On Sun, 06 Dec 2009 06:34:17 -0600, Tim Chase wrote: >> * He hasn't actually defined a docstring. Docstrings have to be string >> literals, you can't do this: >> >> """%s does everything you could possibly want.""" % "xyz" > > I've occasionally wanted something like this, and have found that it can > be done by manually assigning to __doc__ (either at the module-level or > classes) which can make some documentation bits a little easier: Unfortunately, and surprisingly, assigning to __doc__ doesn't work with new-style classes. >>> class K(object): ... pass ... >>> K.__doc__ is None True >>> K.__doc__ = "docstring" Traceback (most recent call last): File "", line 1, in AttributeError: attribute '__doc__' of 'type' objects is not writable -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
* He hasn't actually defined a docstring. Docstrings have to be string literals, you can't do this: """%s does everything you could possibly want.""" % "xyz" I've occasionally wanted something like this, and have found that it can be done by manually assigning to __doc__ (either at the module-level or classes) which can make some documentation bits a little easier: # ds.py ## "original docstring" OPTIONS = { 'FOO': 'bar', 'BAZ': 'boing', } __doc__ = """ This is %(FOO)s and it does %(BAZ)s """ % OPTIONS more_code_that_uses(OPTIONS) ## you can then >>> import ds >>> help(ds) ... and see the formatted help that makes use of the options in the file. Being lazy, I'm all for self-updating documentation ;-) Even weirder is assigning a repr()/str()'able class-instance as the __doc__ for even crazier behaviors (though it looks like the internal help() function ignores them, perhaps requiring isinstance(__doc__, basestring) to pass) # ds2.py ### class DynamicHelp: def __init__(self, name, count=0): self.name = name self.count = count def __str__(self): self.count += 1 if self.count = 3: return "Are you REALLY that forgetful?!" return "%s:%i" % (self.name, self.count) def __repr__(self): return "<%s>" % self class C: "Raw C" def __init__(self, name): self.__doc__ = DynamicHelp(name) where you can then do weird things like >>> import ds2 >>> c = ds2.C("Hello") >>> c.__doc__ >>> c.__doc__ >>> c.__doc__ Are you REALLY that forgetful?! >>> c.__doc__ -tkc -- http://mail.python.org/mailman/listinfo/python-list
Exception classes don't follow pickle protocol, problems unpickling
Hi, I am puzzled why Python's exception classes don't seem to follow the pickle protocol. To be more specific: an instance of a user defined exception, subclassed from Exception, cannot be pickled/unpickled correctly in the expected way. The pickle protocol says that: __getinitargs__ is used if you want __init__ to be called for old-style classes __getnewargs__ is used if you want to pass params to __new__ for new-style classes __getstate__ is used to determine what to pickle instead of the objects __dict__ None of these are used when pickling Exception objects! I've pasted some test code at the end of this message that creates a normal object and an object derived from Exception, and pickles them both. Then it unpickles them. The output is: creating MyObj myobj init: bla creating MyEx myex init: foutje pickle myobj myobj getnewargs # <-- great, newargs is used because of new style class myobj getstate # getstate as well pickle myex unpickling MyObj # <-- huh?? where are getnewargs/getinitargs/getstate? unpickled MyObj: [MyObj 'bla'] unpickling MyEx Traceback (most recent call last): File "ex.py", line 49, in o=pickle.loads(p_myex) TypeError: ('__init__() takes exactly 2 arguments (1 given)', , ()) So there are 2 problems: the pickle protocol isn't used when exception objects (or instances of classes derived from Exception) are pickled, and during unpickling, it then crashes because it calls __init__ with the wrong amount of parameters. (why is it bothering with __init__ anyway? Aren't exceptions new style classes?) This started happening in Python 2.5, Python 2.4 works without error. What is causing this? How can I best solve this error? (using pickle instead of cPickle and changing the protocol number doesn't help). --irmen code follows import cPickle as pickle class MyObj(object): def __init__(self, mymessage): print "myobj init:",mymessage self.mymessage=mymessage def __str__(self): return "[MyObj '%s']" % self.mymessage def __getinitargs__(self): print "myobj getinitargs" return (self.mymessage,) def __getnewargs__(self): print "myobj getnewargs" return (self.mymessage,) def __getstate__(self): print "myobj getstate" return {"mymessage":self.mymessage} class MyEx(Exception): def __init__(self, mymessage): print "myex init:",mymessage self.mymessage=mymessage def __str__(self): return "[MyEx '%s']" % self.mymessage def __getinitargs__(self): print "myex getinitargs" return (self.mymessage,) def __getnewargs__(self): print "myex getnewargs" return (self.mymessage,) def __getstate__(self): print "myex getstate" return {"mymessage":self.mymessage} print "creating MyObj" myobj=MyObj("bla") print "creating MyEx" myex=MyEx("foutje") print "pickle myobj" p_myobj=pickle.dumps(myobj,protocol=pickle.HIGHEST_PROTOCOL) print "pickle myex" p_myex=pickle.dumps(myex,protocol=pickle.HIGHEST_PROTOCOL) print "unpickling MyObj" o=pickle.loads(p_myobj) print "unpickled MyObj:",o print "unpickling MyEx" o=pickle.loads(p_myex) print "unpickled MyEx:",o -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
On Sun, 06 Dec 2009 10:55:50 +0100, Andreas Waldenburger wrote: > On Sat, 5 Dec 2009 23:04:42 -0800 (PST) "Dr. Phillip M. Feldman" > wrote: > > >> If I create a module xyz.py with a docstring """xyz does everything you >> could possibly want.""" at the top, the command ?xyz issued at the >> IPython prompt does not display this docstring. What am I doing wrong? > > Stab in the dark: You have imported the module first, right? > > Also: Never, EVER, ask a question like this on any technical forum > without posting your code (or rather: a minimal version of it that still > exhibits the problem). That way, people can help you directly instead of > taking wild guesses at what your problem might be. In fairness, Phillip's description of the problem is pretty straight- forward: he has a module xyz.py with a docstring. The minimal version of the code is no code at all, just a docstring: """xyz does everything you could possibly want.""" His problem isn't an error when running the code, but an error with IPython's command ?xyz. What he didn't say is what IPython prints instead of the expected docstring. Over to you Phillip, don't just tell us what IPython doesn't do, tell us what it does do. My guesses are: * He hasn't imported the module, so he gets an error of some sort. * He hasn't actually defined a docstring. Docstrings have to be string literals, you can't do this: """%s does everything you could possibly want.""" % "xyz" Nor can you have anything except comments and whitespace between the top of the module and the string. * He has another module called xyz which is shadowing the module he expects, and so he sees that module's docstring instead. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't print Chinese to HTTP
Gnarlodious wrote: On Dec 5, 3:54 am, Lie Ryan wrote: Because of the switch to unicode str, a simple print('晉') should've worked flawlessly if your terminal can accept the character, but the problem is your terminal does not. There is nothing wrong with Terminal, Mac OSX supports Unicode from one end to the other. The problem is that your code works normally in Terminal but not in a browser. #!/usr/bin/python import sys, io print("Content-type:text/plain;charset=f-8\n\n") sys.stdout =o.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") print("晉") The browser shows "Server error", Apache 2 reports error: [error] [client 127.0.0.1] malformed header from script. Bad header\xe6\x99\x89: test.py So far every way to print Unicode to a browser looks very un-Pythonic. I am just wondering if I have a bug or am missing the right way entirely. -- Gnarlie You change the meaning of sys.stdout without flushing the previous instance. So of course buffering can mess you up. If you want to change the encoding, do it at the beginning of the script. #!/usr/bin/python import sys, io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") print("Content-type:text/plain;charset=f-8\n\n") print("晉") (You probably could use sys.stdout.flush() before reassigning, but doing it at the beginning is better for several reasons.) DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a docstring for a module?
On Sat, 5 Dec 2009 23:04:42 -0800 (PST) "Dr. Phillip M. Feldman" wrote: > > If I create a module xyz.py with a docstring """xyz does everything > you could possibly want.""" at the top, the command ?xyz issued at > the IPython prompt does not display this docstring. What am I doing > wrong? Stab in the dark: You have imported the module first, right? Also: Never, EVER, ask a question like this on any technical forum without posting your code (or rather: a minimal version of it that still exhibits the problem). That way, people can help you directly instead of taking wild guesses at what your problem might be. /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 5, 11:42 pm, Tim Roberts wrote: > Raymond Hettinger wrote: > > > if not round(x - y, 6): ... > > That's a dangerous suggestion. It only works if x and y happen to be > roughly in the range of integers. Right. Using abs(x-y) < eps is the way to go. Raymond -- http://mail.python.org/mailman/listinfo/python-list