how to inherit docstrings?
Sometimes when using class inheritance, I want the overriding methods of the subclass to get the docstring of the matching method in the base class. You can do this with decorators (after the class definition), with class decorators, and with metaclasses [1]. However, I was hoping for a way to do it with just function decorators on the methods (no metaclass or class decorator). I am not sure if this is doable. I realize now that this is exactly the reason I got to thinking last week about objects being notified when they are bound [2]. So, is there a way to do this with just decorators, or am I stuck with the metaclass/class decorator route? (It's not all that bad :) Thanks! -eric p.s. Am I missing something or can you really not change the docstring of a class? I was thinking about the idea of inheriting class docstrings too. [1] http://code.activestate.com/recipes/577743-using-decorators-to-inherit-function-docstrings/ [2] http://mail.python.org/pipermail/python-ideas/2011-June/010446.html -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Eric Snow ericsnowcurren...@gmail.com writes: p.s. Am I missing something or can you really not change the docstring of a class? I was thinking about the idea of inheriting class docstrings too. The docstring of an object (whether function or class or module) is the object's ‘__doc__’ attribute. Access that attribute to get the docstring; re-bind that attribute to set a different docstring. So, it's even possible to do what you ask without decorators at all: class Foo(object): def frob(self): Frobnicate thyself. class Bar(Foo): def frob(self): pass frob.__doc__ = Foo.frob.__doc__ Not very elegant, and involving rather too much repetition; but not difficult. -- \ “We are no more free to believe whatever we want about God than | `\ we are free to adopt unjustified beliefs about science or | _o__) history […].” —Sam Harris, _The End of Faith_, 2004 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
ANN: GMPY2 or How I learned to love nan
Everyone, I'm pleased to announce a new alpha release of GMPY2. GMPY2 is a wrapper for GMP and MPFR multiple-precision arithmetic libraries. GMPY2 alpha2 introduces context manager support for MPFR arithmetic. It's now possible to trigger an exception when comparing against nan (and other for other events that normally generate nan or inf). import gmpy2 gmpy2.context().trap_erange=True gmpy2.mpfr(nan) == gmpy2.mpfr(nan) Traceback (most recent call last): File stdin, line 1, in module gmpy2.RangeError: comparison with NaN If you have an interest in multiple-precision arithmetic or want more control over the handling of exceptional events in floating point arithmetic, please check out GMPY2! GMPY2 is available for download from: http://code.google.com/p/gmpy/ Experimental release To simplify the codebase, allow for changes in the API, and support simultaneous installation, the development version has been renamed to GMPY2. The following is list of changes in GMPY2: In 2.0.0a0 -- * support for a mutable integer type xmpz * removal of random number functions * xmpz supports slices for setting/clearing bits * some methods have been renamed (scan1 - bit_scan1) * support for Python prior to 2.6 has been removed * support for all division modes has been added * ceiling - round to +Infinity * floor - round to -Infinity * truncate - round to zero * 2exp - division by a power of 2 * support is_even() and is_odd() In 2.0.0a1 -- * support for the MPFR floating point library In 2.0.0a2 -- * context manager support from controlling MPFR arithmetic * can raise Python exceptions when exceptional events occur with MPFR arithmetic; for example, comparing against nan can trigger an exception * more complete coverage for MPFR * many function names were changed to be more consistent Please report any issues! casevh -- http://mail.python.org/mailman/listinfo/python-list
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE
On 06/08/2011 01:09 PM, Cathy James wrote: I am almost there, but I need a little help: I would like to a) print my dogs in the format index. name: breed as follows: 0. Mimi:Poodle 1.Sunny: Beagle 2. Bunny: German Shepard I am getting (0, ('Mimi', 'Poodle')) . Mimi : Poodle instead-what have I done wrong? b) I would like to append to my list, but my line dogs.dogAppend() is giving a TypeError: for i in enumerate (self.dogAppend()): TypeError: 'list' object is not callable Any help? #MY CODE BELOW: import sys Not needed in the class definition, move it to the if __name__... section. Actually, it's not needed at all. That part could be rewritten to avoid the need for sys.exit() entirely. class Dog(): def __init__(self, name, breed): self.name = name self.breed = breed def dogAppend(self): self.dogAppend = [] self.dogAppend.append((self.name,self.breed)) return self.dogAppend 1: Think about what you're trying to do here... You seem to want _each_ instance of Dog to hold the whole list. Do you want Dog to be an individual Dog or do you want it to be a list of Dogs? You can't do both in a single class. 2: This won't work to append to your list anyway... each time you call dogAppend() it will clear out any existing list and result in a list of one element, a tuple of (name, breed). You can do exactly the same thing with a single line: return [(self.name, self.breed)] def display (self): for i in enumerate (self.dogAppend()): print (i,., self.name, : + self.breed) Misusing enumerate. Check the docs. http://docs.python.org/py3k/library/functions.html?highlight=enumerate#enumerate Besides that, there are easier ways to print the contents of a list. if __name__ == __main__: dogs = Dog(name=input ( Enter Dog Name: ), breed=input (Enter Dog Breed: )) while not dogs: print(Goodbye!!) sys.exit() else: else does not belong with while. #dogs.dogAppend() dogs.display() Here's one possible replacement. There are many other approaches as well. (This leaves the individual dogs as a (name, breed) tuple. It could be modified for other definitions of a dog. -- Exercise left for the reader...);-) class DogKennel: def __init__(self): self.dogs = [] # list of dogs def addDog(self): name = input(Enter dog name: ) if name == : return False breed = input(Enter dog breed: ) if breed == : return False self.dogs.append((name, breed)) # Append this dog tuple to the list return True def display(self): i = 1 for dog in self.dogs: print(%d. %s: %s % (i, dog[0], dog[1])) i += 1; if __name__ == __main__: dogs = DogKennel() while (dogs.addDog()): pass dogs.display() -=- Larry -=- -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, Jun 9, 2011 at 12:37 AM, Ben Finney ben+pyt...@benfinney.id.au wrote: Eric Snow ericsnowcurren...@gmail.com writes: p.s. Am I missing something or can you really not change the docstring of a class? I was thinking about the idea of inheriting class docstrings too. The docstring of an object (whether function or class or module) is the object's ‘__doc__’ attribute. Access that attribute to get the docstring; re-bind that attribute to set a different docstring. Sorry, I should have been more clear: class X: ... some doc ... X.__doc__ 'some doc' X.__doc__ = another doc Traceback (most recent call last): File stdin, line 1, in module AttributeError: attribute '__doc__' of 'type' objects is not writable That is on 3.3. So, it's even possible to do what you ask without decorators at all: class Foo(object): def frob(self): Frobnicate thyself. class Bar(Foo): def frob(self): pass frob.__doc__ = Foo.frob.__doc__ Not very elegant, and involving rather too much repetition; but not difficult. Yeah, definitely you can do it directly for each case. However, the inelegance, repetition, and immodularity are exactly why I am pursuing a solution. :) (I included a link in the original message to examples of how you can already do it with metaclasses and class decorators too.) I'm just looking for a way to do it with decorators in the class body without using metaclasses or class decorators. Thanks -eric -- \ “We are no more free to believe whatever we want about God than | `\ we are free to adopt unjustified beliefs about science or | _o__) history […].” —Sam Harris, _The End of Faith_, 2004 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thursday, June 9, 2011 12:13:06 AM UTC-7, Eric Snow wrote: On Thu, Jun 9, 2011 at 12:37 AM, Ben Finney ben+p...@benfinney.id.au wrote: So, it's even possible to do what you ask without decorators at all: class Foo(object): def frob(self): Frobnicate thyself. class Bar(Foo): def frob(self): pass frob.__doc__ = Foo.frob.__doc__ Not very elegant, and involving rather too much repetition; but not difficult. Yeah, definitely you can do it directly for each case. However, the inelegance, repetition, and immodularity are exactly why I am pursuing a solution. :) (I included a link in the original message to examples of how you can already do it with metaclasses and class decorators too.) I'm just looking for a way to do it with decorators in the class body without using metaclasses or class decorators. The tricky part is that, inside the class body (where decorators are being evaluated) the class object doesn't exist yet, so the method decorator has no way to infer what the base classes are at that point. A class decorator or metaclass can operate after the class object is made, but a method decorator can't. The best you could probably do with a method decorator is something like this: def inherit_docstring(base): def set_docstring(f): f.__doc__ = getattr(base,f.func_name).__doc__ return f return set_docstring where you have to repeat the base class every time: class Bar(Foo): @inherit_docstring(Foo) def somefunction(self): pass Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Eric Snow ericsnowcurren...@gmail.com writes: AttributeError: attribute '__doc__' of 'type' objects is not writable That is on 3.3. Well, that sucks :-( Where can we see the discussion of that change before it was implemented? I'm just looking for a way to do it with decorators in the class body without using metaclasses or class decorators. Yes, that'd be nice. Do you have a specification in mind for how it would work? Perhaps time to start a thread on the ‘python-ideas’ forum. -- \ “Following fashion and the status quo is easy. Thinking about | `\your users' lives and creating something practical is much | _o__)harder.” —Ryan Singer, 2008-07-09 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Any Better logic for this problem..
Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium sganapathy.subraman...@gmail.com wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 For the archives, that code is: num = 13195 #num = 600851475143L prime_numbers = [2] prime_factors = [] for i in range (2,num): for j in prime_numbers: if i % j == 0: break else: prime_numbers.append(i) print 'The Prime Numbers are : ', prime_numbers for items in prime_numbers: if num % items == 0: prime_factors.append(items) print 'The prime factors are : ' , prime_factors In the future, please avoid the unnecessary indirection of pastebins when your code is relatively short. Including the code directly in your post is also likely to increase the response rate you get. Cheers, Chris When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On 09/06/2011 09:31, Ganapathy Subramanium wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. If I was attempting this problem, I would pre-compute a file of prime numbers, in increasing order (probably use the Sieve of Erastothenes approach). You need a list of primes from 2 to the square root of the largest num you will have to process. With that, you simply work through the prime numbers, Divide num by this prime. If no remainder, replace num with num // prime (so you divide by the same prime again). else step on to next prime without changing num Stop when num becomes 1. e.g. 50 divides by 2 so factors are (2) and 25 into next iteration with 3 25 which won't divide by 3,so factors remain (2) and 25 goes into next iteration with 5 25 // 5 is 5 so factors become (2,5) and 5 into next iteration with 5 5 // 5 is 1so factors are (2,5,5) and computation complete. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On Thu, Jun 9, 2011 at 7:06 PM, Chris Rebert c...@rebertia.com wrote: On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium sganapathy.subraman...@gmail.com wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 For the archives, that code is: for items in prime_numbers: if num % items == 0: prime_factors.append(items) print 'The prime factors are : ' , prime_factors Prime factors don't quite work that way. The prime factors of 24, for instance, are 2, 2, 2, and 3. But if you're looking for _unique_ prime factors, then this will work. Rather than find all prime numbers up to num, stop at sqrt(num) - it's not possible to have any prime factors larger than that. (Be sure to include the square root itself; range(2,sqrt(num)) won't work if num is a perfect square. Use range(2,sqrt(num)+1) for safety.) That will save a fair amount of effort. Also, if you divide num by each factor found, it'll make the numbers smaller, which may be faster. Hope that helps! Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: test_popen
On 01/-10/-28163 02:59 PM, harrismh777 wrote: Looks like my 2.7 test_popen failure is an open issue7671... since Jan 2010. Looks like it really does function ok. At any rate, I was able to test Popen myself today, and it ran fine. I needed to write a script that will disable the touch pad on this HP g series, because there is no way to do that in the bios. So, in gnu/linux, you get the device id list with 'xinput list' and then to disable the touch pad for that id, enter this command: 'xinput set-prop id# Device Enabled 0' So, I'm using Popen class to talk to the system through a shell and read back the stdout through a pipe, and was able to retrieve the device ids with this (in ver 2.7.1) : from subprocess import PIPE, Popen cmd = 'xinput list' p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() print stdout (actually I parsed it with the re module) The only difference here between 2.7 and 3.2 is that 3.2 gives back a b'string' ... otherwise, same same. I'm parsing the ids listing with the re module and then using Popen to issue the command to disable the touch pad. Its a little more complicated than that, because I only allow the script to 'work' if it finds the id=# for an attached mouse or track-ball... I use the Logitech Trackman... otherwise it asks the double question for whether the touch pad should be deactivated. So, clicking the icon once disables the pad, and clicking it again re-enables it, assuming the trackman is plugged in. The trick does not work across login-logout, so the touchpad must be disabled in the startup, or else manually every time the user logs in. When I get the silly thing done I'll post it, in case anyone else is interested... there does seem to be a lot of interest on the net for disabling the synaptics touch pad... it just gets in the way most of the time and isn't very efficient the rest of the time. (but I digress) kind regards, m harris Thanks for this. It has already helped me solve a similar problem, and in my case the problem/solution is much simpler. The xinput cmd permits you to specify the device name directly, so for my Lenovo, I can just use the shell command: sudo xinput --set-prop --type=int --format=8 SynPS/2 Synaptics TouchPad Device Enabled 0 I used the information you supplied to modify what already worked on a couple of Dells I had. What I was missing was the correct string for the Lenovo. The Dells called it PS/2 Generic Mouse DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Ben Finney ben+pyt...@benfinney.id.au wrote: Eric Snow ericsnowcurren...@gmail.com writes: AttributeError: attribute '__doc__' of 'type' objects is not writable That is on 3.3. Well, that sucks :-( Where can we see the discussion of that change before it was implemented? Change? What change? C:\Python27python Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win 32 Type help, copyright, credits or license for more information. class C(object): ...Hello world ... C.__doc__ = whatever Traceback (most recent call last): File stdin, line 1, in module AttributeError: attribute '__doc__' of 'type' objects is not writable Or even: Python 2.3.5 (#1, Oct 13 2005, 09:17:23) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2 Type help, copyright, credits or license for more information. class C(object): ...Hello world ... C.__doc__ = whatever Traceback (most recent call last): File stdin, line 1, in ? TypeError: attribute '__doc__' of 'type' objects is not writable -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: smtp - python
On Wed, 2011-06-08 at 17:18 -0300, Josias L.G wrote: Hi for all, I'm very newbie in python and is very good language. I'm trying to adopt a example: import smtpd import asyncore server = smtpd.PureProxy(('127.0.0.1', 1025), ('mail', 25)) asyncore.loop() I'm trying to copy the email that is send to another email in maildir format. Here, i'm reading about the mailbox module, however, i don't know how start that (get the email that was transferred and, trought mailbox module, save all mails in one file). an someone indicate something to me read ?.. examples... texts and I don't know much about the mailbox module; the documentation looks straight-forward enough, what exactly is the question? http://docs.python.org/library/mailbox.html? If you want to put all the messages in a single file use mbox. import mailbox mybox = mailbox.mbox('my.mbox', create=True) mybox.lock() for message in messages: mybox.add(message) mybox.flush() mybox.unlock() mybox.close() To read a message into a Message object from a stream/file - from email import message_from_file message = message_from_file(stream) The best way to serialize a Message to a stream seems to be from email.generator import Generator tmp = BLOBManager.ScratchFile() # Create a stream g = Generator(tmp, mangle_from_=False, maxheaderlen=60) g.flatten(message) tmp.seek(0) -- Adam Tauno Williams awill...@whitemice.org LPIC-1, Novell CLA http://www.whitemiceconsulting.com OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba -- http://mail.python.org/mailman/listinfo/python-list
Investing in data management services could have vast benefits
If your business has huge databases of client details and other information, maintenance these records as accurate and current as possible should be a top priority, learn more http://worldupdateinformation.com/2011/06/08/investing-in-data-management-services-could-have-vast-benefits/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On 01/-10/-28163 02:59 PM, Chris Rebert wrote: On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium sganapathy.subraman...@gmail.com wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 For the archives, that code is: num =3195 #num =00851475143L prime_numbers =2] prime_factors =] for i in range (2,num): for j in prime_numbers: if i % j =0: break else: prime_numbers.append(i) print 'The Prime Numbers are : ', prime_numbers for items in prime_numbers: if num % items =0: prime_factors.append(items) print 'The prime factors are : ' , prime_factors In the future, please avoid the unnecessary indirection of pastebins when your code is relatively short. Including the code directly in your post is also likely to increase the response rate you get. Cheers, Chris When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. Others have pointed out various inefficiencies. But I wanted to start by asking what this is for. Do you really have a need to factor numbers over 2 billion? Repeatedly? In multiple runs of the program? Do you have weeks of computer time to spend or just hours? Are you really interested in the factors, or just whether or not a particular large number is prime (==has anyfactors) ? If this is a homework assignment, what's the exact assignment? Are you permitted to use other libraries, or other languages? Are you permitted to use language features you haven't encountered yet in class? Assuming you have to use pure python, no extra libraries, nothing complex, I'd just concentrate on making the current program efficient, without major surgery. First, you're generating far more primes than you can possibly need. You could stop at the square root of num. Next, you're trying every number, but you could be checking every other number (just add a step value to the range). Those two changes eliminate the range() problem, as the sqrt doesn't get over 2 billion till the num is over 10**18. But more fundamentally, you're generating a big list of numbers, using part of it once, and throwing it away. You could cache that list, store it on disk between runs, and make it tons faster. Worse you probably don't even need anywhere near the sqrt, unless num is prime. So you should probably turn the problem around. Design a function that calculates the nth prime, but that caches the work it's already done (on disk if appropriate, but in a list if not). In the loop that's finding the factors, simply call the first function each time, and each time you find a factor, divide num by that so you're dealing with a smaller number. There are faster ways to generate the primes, but now those optimizations can be applied to the nthprime() function, and they're independent of the factorization loop. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: The pythonic way equal to whoami
Christopher Head wrote: It is. Until Linux capabilities, EUID==0 used to be special-cased in the kernel Thank you all, I got a good learning *and* something to rememeber. -- goto /dev/null -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems Compiling Python 2.6.7 for Win7
On Jun 8, 6:56 pm, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Wed, 08 Jun 2011 12:28:56 -0300, Jay Osako josephos...@gmail.com escribi : I have been trying to get PyODBC to work with Python 2.6 (the latest version it is known to be compatible with) and Django, but have run into a problem which, according to the information I've got elsewhere, probably stems from a DLL incompatibility - apparently, [...] The first of these problems is, of course, tracking down a copy of VC+ + 2008 Express. While one would think that this would be the simplest solution, Microsfot themselves no longer provide the installer for this, and I'm not sure I'd trust most of the other sources claiming to provide it. Doesn'thttp://www.microsoft.com/express/Downloads/#2008-Visual-CPPwork for you? I didn't try past the initial download prompt, but it seems to be the right version. kicks self How did I overlook that? Well, OK, that seems to just what I needed, though I still seem to be having some trouble with the actual Django project. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Iterating into maildir or mbox
Hello, originally with python 2.4 ~ 2.7 (I think) iterating a maildir I was using ++Code+ try: mbox= mailbox.PortableUnixMailbox(open(mbox,'r')) except IOError: # if file not found default is None mbox= None while mbox: msg= next(mbox) if msg is None: break try: m= msg.getheader('message-id') if m: dx= m.strip('') else: continue except (IndexError, AttributeError, IOError): # message without ID, put some mark dx= str(time.time()).split('.') dx= int(dx[0])*int(dx[1]) if dx in lmbox:continue lmbox[dx]= dx return lmbox ++Code+ I'm tryng to convert into Python 3.2, but I don't get why this is not iterable anymore. -- goto /dev/null -- http://mail.python.org/mailman/listinfo/python-list
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE
Larry Hudson wrote: On 06/08/2011 01:09 PM, Cathy James wrote: Dog Breed: )) while not dogs: print(Goodbye!!) sys.exit() else: else does not belong with while. else works just fine with while; it is the path taken when the while is exhausted, but not broken out of: -- i = 5 -- while i: ... print(i) ... i -= 1 ... else: ... print(blast off!) ... 5 4 3 2 1 blast off! -- i = 5 -- while i: ... print(i) ... i -= 1 ... if i == 3: ... print('aborting') ... break ... else: ... print(blast off!) ... 5 4 aborting ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE
Ethan Furman wrote: Larry Hudson wrote: On 06/08/2011 01:09 PM, Cathy James wrote: Dog Breed: )) while not dogs: print(Goodbye!!) sys.exit() else: else does not belong with while. else works just fine with while; it is the path taken when the while is exhausted, but not broken out of: It works with 'for' as well. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: best book about Webdesign with Django
On 08.06.2011 12:29, News123 wrote: Hi, Do you have any recommendations for a good book about Web design with Django? You can do web design with HTML, CSS and Javascript. There are a lot of books about this. Django is a good web framework. It does not care much about CSS and Javascript. I guess you need buy two books :-) Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de -- http://mail.python.org/mailman/listinfo/python-list
Gnumeric scripting and license
I am looking for some information about Gnumeric scripting licensing. Here is my question: If I script for Gnumeric using Python, must I release the script code? I am unable to draw a line where Gnumeric GPL ends and where proprietary nature of macros start. Thanks in advance, -Bhushit -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, 09 Jun 2011 17:44:32 +1000, Ben Finney wrote: Eric Snow ericsnowcurren...@gmail.com writes: AttributeError: attribute '__doc__' of 'type' objects is not writable That is on 3.3. Well, that sucks :-( Where can we see the discussion of that change before it was implemented? It goes back to Python 2.2, when new style classes were first introduced. [steve@sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type help, copyright, credits or license for more information. class K(object): ... foo ... K.__doc__ = 'bar' Traceback (most recent call last): File stdin, line 1, in ? TypeError: attribute '__doc__' of 'type' objects is not writable It's an unnecessary restriction, as far as I'm concerned, but an old one. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Eric Snow wrote: p.s. Am I missing something or can you really not change the docstring of a class? I was thinking about the idea of inheriting class docstrings too. 8 module level docstring def func(): function level docstring class Test(object): class level docstring def meth(self): method level docstring if __name__ == '__main__': import sys import traceback hmmm = ( sys.modules['__main__'], func, Test(), Test().meth, Test, Test.meth, ) for obj in hmmm: try: obj.__doc__ = 'new docstring' print('successfully changed %s\n' % obj) except: traceback.print_exc() print() 8 Tested from 2.5 - 3.2. The first three always work, the last one works in 3.1+, the fourth and fifth always fail. -actual output for 2.5 successfully changed module '__main__' from 'docstring.py' successfully changed function func at 0x00A8F570 successfully changed __main__.Test object at 0x00A94230 Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'instancemethod' objects is not writable () Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'type' objects is not writable () Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'instancemethod' objects is not writable () -actual output for 3.2 successfully changed module '__main__' from 'docstring.py' successfully changed function func at 0x00BE6F60 successfully changed __main__.Test object at 0x00BFE730 Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'method' objects is not writable Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'type' objects is not writable successfully changed function meth at 0x00BE6ED0 -actual output ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: pexpect and OpenVMS
I ran into a similar problem. I found throttling self.sh.delaybeforesend works for me. I'm on ubuntu. -- http://mail.python.org/mailman/listinfo/python-list
Python 2.6 OR 3.2
Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. Please let me know the difference between them. Please give some refernce site or books to know the difference -- http://mail.python.org/mailman/listinfo/python-list
Re: Import error while running python application on Mac OS
On Jun 8, 9:20 pm, hisan santosh.s...@gmail.com wrote: HI All, I have created an application for Mac OS using py2app module, in my python script i have external modules such as MySQLdb and other , while trying to run on Mac OS i get an error saying unable to import the module MySQLdb. On Windows i convert python script to an exe using py2exe module and if i install VC++ on y machine my exe runs fine. Is there any dependency on MAC OS. Please let me know how to resolve my issue -- Regards, Santosh Can Some one reply for this Please -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
In 9037ef5f-53c5-42c6-ac5d-8f942df6c...@x38g2000pri.googlegroups.com hisan santosh.s...@gmail.com writes: Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. Please let me know the difference between them. Please give some refernce site or books to know the difference If you're starting new, use 3.2. All code will eventually move to this newer style, so you'll have to learn it eventually. The only reason to use 2.6 is if you have to maintain an existing code base that was written with 2.6 (or older). -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list
Re: Paramiko Threading Error
Il Tue, 7 Jun 2011 19:25:43 -0700 (PDT), mud ha scritto: Hi All, Does anybody know what the following error means with paramiko, and how to fix it. I don't know what is causing it and why. I have updated paramiko to version 1.7.7.1 (George) but still has the same issue. Also I can not reproduce the problem and therefore debugging is harder for me. Exception in thread Thread-4 (most likely raised during interpreter shutdown): Traceback (most recent call last): File /usr/lib64/python2.6/threading.py, line 532, in __bootstrap_inner File /usr/lib/python2.6/site-packages/paramiko/transport.py, line 1574, in run type 'exceptions.AttributeError': 'NoneType' object has no attribute 'error' if I remember rightly, I got that kind of error when I tried to use a transport without setting up the paramiko's logging subsystem. Try to put in head of your code the line: pk.util.log_to_file(log file name.txt) D. -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On Thu, Jun 9, 2011 at 4:38 AM, Dave Angel da...@ieee.org wrote: On 01/-10/-28163 02:59 PM, Chris Rebert wrote: On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium sganapathy.subraman...@gmail.com wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. Others have pointed out various inefficiencies. But I wanted to start by asking what this is for. Do you really have a need to factor numbers over 2 billion? Repeatedly? In multiple runs of the program? Do you have weeks of computer time to spend or just hours? Are you really interested in the factors, or just whether or not a particular large number is prime (==has anyfactors) ? If this is a homework assignment, what's the exact assignment? Are you permitted to use other libraries, or other languages? Are you permitted to use language features you haven't encountered yet in class? My solution: def factors(x): status, output = subprocess.getstatusoutput('factor %d' % x) if not status: return [int(i) for i in output.split()[1:]] else: print(output) Works pretty well. snip So you should probably turn the problem around. Design a function that calculates the nth prime, but that caches the work it's already done (on disk if appropriate, but in a list if not). In the loop that's finding the factors, simply call the first function each time, and each time you find a factor, divide num by that so you're dealing with a smaller number. Just use a precomputed table to do your trial division. There's a list of the first fifty million primes on prime pages- if you aren't dealing with specially constructed values (ie, RSA moduli) and haven't found a factor by the end of the first ten thousand or so you probably need to do a primality check before moving on to trying to factor it. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
urllib2 opendirector versus request object
Hi, I was wondering what the difference or advantages to using an opendirector with handlers or using a request object? I am having an issue where when I use the open director and I try to add headers it adds them after the connection-close header, but when I use the request object it does not. Here is the headers as reported by python: send: 'POST /xml-api/listaccts HTTP/1.1\r\nAccept-Encoding: identity\r\nContent-Length: 13\r\nHost: cpanel01.sea.fibercloud.com:2086\r\nContent-Type: application/x-www-form-urlencoded\r\nConnection: close\r\nUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv,1.9.2.13) Gecko/20101203 Firefox/3.6.13\r\n\r\n' send: 'domain=anjopa' reply: 'HTTP/1.1 403 Forbidden\r\n' header: Connection: close header: Server: cpsrvd/11.30.0.27 header: Content-type: text/xml Next two examples one with Request object and the next with the open director, #!/usr/bin/python import sys from xml.dom.minidom import parse, parseString import urllib import urllib2 import base64 from cookielib import CookieJar # Turn on HTTP debugging http://diveintopython.org/http_web_services/user_agent.html import httplib #With Request object: req = urllib2.Request(url, {},{'Authorization':'Basic ' + base64.b64encode( username + ':' + password ) } ) res = urllib2.urlopen(req) print res.read() With open director: # Instantiate and Initialize AuthInfo Handler for use w/ the build_opener authinfo = urllib2.HTTPBasicAuthHandler() authinfo.add_password(realm=Web Host Manager, uri=http://servername:2086/xml-api/listacct;, user=username, passwd=password) # Instantiate Cookie jar Handler for use w/ build_opener cj = CookieJar() # Create an opener object from list of handlers above opener = urllib2.build_opener(authinfo,urllib2.HTTPCookieProcessor(cj), urllib2.HTTPHandler(debuglevel=1)) urllib2.install_opener(opener) opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv,1.9.2.13) Gecko/20101203 Firefox/3.6.13')] response = opener.open(url, paramaters) Dennis O. -- http://mail.python.org/mailman/listinfo/python-list
Re: Import error while running python application on Mac OS
In article 1167f414-8901-4f9c-9d51-2723213fd...@k3g2000prl.googlegroups.com, hisan santosh.s...@gmail.com wrote: On Jun 8, 9:20 pm, hisan santosh.s...@gmail.com wrote: I have created an application for Mac OS using py2app module, in my python script i have external modules such as MySQLdb and other , while trying to run on Mac OS i get an error saying unable to import the module MySQLdb. On Windows i convert python script to an exe using py2exe module and if i install VC++ on y machine my exe runs fine. Is there any dependency on MAC OS. Can Some one reply for this Please You will want to ask questions about Python on Mac OS X on the Pythonmac list. http://dir.gmane.org/gmane.comp.python.apple But you need to supply more information. There are many reasons why you might get an import error. You should supply the exact traceback from the failing import and say which Python instance you are using, which version of MySQLdb, which set of MySQL client libraries - all of which need to be built compatibly (i.e. compatible CPU archs and deployment targets) and packaged in the app bundle or installed externally on the end user's machine. You need to specify what version of OS X you are using and what range of OS X versions your app is targeted for. And you should say whether everything works without trying to use py2app. Getting a working combination of python, MySQLdb, and MySQL client libs on OS X can be frustrating if you try to guess at it or use binaries from different suppliers. If possible, use a complete solution from a 3rd-party open source packager, like MacPorts or Homebrew. -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 06/09/2011 01:18 PM, hisan wrote: Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. Please let me know the difference between them. Please give some refernce site or books to know the difference http://wiki.python.org/moin/Python2orPython3 Pick one and learn it well. It'll be easy to switch to the other when/if you need to. Right now lots of nice libraries only support 2.x, like Twisted and lots of web frameworks (all? I think there's one or two that use 3). - -- Corey Richardson -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.17 (GNU/Linux) iQEcBAEBAgAGBQJN8SDNAAoJEAFAbo/KNFvpbewH/3IclMl/K5d35qsVesoYuICB pFt0W6gxyMSRMU2TcoYbpsSVlqjc+KCwUQ7wxv/yIw8ldXs09IV3ITbajKDR2Gnh TX5DdgRaC8vAoQHLuvjUvJST0/1INnK/sYGnzS1xuNv5uuohqZ026jx4HEXTfjUi haI/bFLELM9iKrBjuSRKYVy4RYRHAE0ziKblbXtfNTltU0Y2C56xRKkMplsEk/pV ka+6R5OkHvMap+g++TRaXqN347m60GnWKWYwTklcTSyfJmmEtaokE4gJwPodv7N4 ozQrkcNdL3tHxTLFbMfO5zrSrW+yWEpsGRYbUSJIx8zOUOhbyjZJtHBuYu+xsqI= =4AvK -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Eigensolver for Large Sparse Matrices in Python
Hi, I think you can also use scipy.sparse.linalg.eigen.arpack in addition to scipy.sparse.linalg.eigen.lobpcg Also, from my experience with this routines I can tell you that they don't like to be asked a small number of eigenvalues. Contrary to common sense I have found these routines to prefer to calculate 30 eigenvalues than 5 eigenvalues. Try to ask it for more eigenvalues. Does anybody know why the routines don't work well when they are aked for small number of eigenvalues? Andrew MacLean andrew.macl...@gmail.com wrote: Hi, I need to solve symmetric generalized eigenvalue problems with large, sparse stiffness and mass matrices, say 'A' and 'B'. The problem is of the form Av = lambdaBV. I have been using lobpcg (scipy.sparse.linalg.lobpcg), in Scipy 0.7.2, although this has been giving me incorrect values that are also about 1000 times too large. They are both Hermitian, and 'B' is positive definite, and both are of approximately of size 70 000 x 70 000. 'A' has about 5 million non- zero values and 'B' has about 1.6 million. 'A' has condition number on the order of 10^9 and 'B' has a condition number on the order of 10^6. I have stored them both as csc type sparse matrices from the scipy.sparse library. The part of my code using lobpcg is fairly simple (for the 20 smallest eigenvalues): from scipy.sparse.linalg import lobpcg from scipy import rand X = rand(A.shape[0], 20) W, V = lobpcg (A, X, B = B, largest = False, maxiter = 40) --- I tested lobpcg on a scaled down version of my problem, with 'A' and 'B' matrices of size 10 000 x 10 000, and got the correct values (using maxiter = 20), as confirmed by using the eigs function in Matlab. I used it here to find the smallest 10 eigenvalues, and here is a table of my results, showing that the eigenvalues computed from lobpcg in Python are very close to those using eigs in Matlab: https://docs.google.com/leaf?id=0Bz-X2kbPhoUFMTQ0MzM2MGMtNjgwZi00N2U0... With full sized 'A' and 'B' matrices, I could not get the correct values, and it became clear that increasing the maximum number of iterations indefinitely would not work (see graph below). I made a graph for the 20th smallest eigenvalue vs. the number of iterations. I compared 4 different guesses for X, 3 of which were just random matrices (as in the code above), and a 4th orthonormalized one. https://docs.google.com/leaf?id=0Bz-X2kbPhoUFYTM4OTIxZGQtZmE0Yi00MTMy... It appears that it will take a very large number of iterations to get the correct eigenvalues. As well, I tested lobpcg by using eigenvectors generated by eigs in Matlab as X, and lobpcg returned the correct values. I don't believe it is a bug that was solved for lobpcg in newer versions of Scipy, as I have also gotten the same problem using the most recent version (4.12) of lobpcg for Matlab. If anyone has any suggestions for how to improve the results of lobpcg, or has experience with an alternate solver (such as JDSYM from Pysparse or eigsh in newer versions of Scipy) with matrices of this size, any recommendations would be grealty appreciated. Thanks, Andrew -- http://mail.python.org/mailman/listinfo/python-list
JSONBOT 0.7.1 released
Hello kids and parents !! I just want to announce the release of JSONBOT 0.7.1. This release consists of minor bug fixes and new xmpp auth code (SASL) which support DIGEST-MD5 and PLAIN authing. JSONBOT should run well again on systems with python2.5 installed. You can fetch it at http://jsonbot.googlecode.com Have fun playing with it! Bart About JSONBOT: JSONBOT is a remote event-driven framework for building bots that talk JSON to each other over XMPP. This distribution provides bots built on this framework for console, IRC, XMPP and Convore for the shell and WWW and XMPP for the Google Application engine. JSONBOT is all of the following: * a shell console bot * a shell IRC bot * a shell XMPP bot * a shell Convore bot * a Web bot running on Google Application Engine * a XMPP bot running on Google Application Engine * a Google Wave bot running op Google Application Engine * the XMPP bots are used to communicate between bots * plugin infrastructure to write your own functionality * event driven framework by the use of callbacks -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Benjamin Kaplan wrote: 2011/6/8 Sérgio Monteiro Basto sergi...@sapo.pt: hi, cat test.py #!/usr/bin/env python #-*- coding: utf-8 -*- u = u'moçambique' print u.encode(utf-8) print u chmod +x test.py ./test.py moçambique moçambique ./test.py output.txt Traceback (most recent call last): File ./test.py, line 5, in module print u UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 2: ordinal not in range(128) in python 2.7 how I explain to python to send the same thing to stdout and the file output.txt ? Don't seems logic, when send things to a file the beaviour change. Thanks, Sérgio M. B. That's not a terminal vs file thing. It's a file that declares it's encoding vs a file that doesn't declare it's encoding thing. Your terminal declares that it is UTF-8. So when you print a Unicode string to your terminal, Python knows that it's supposed to turn it into UTF-8. When you pipe the output to a file, that file doesn't declare an encoding. So rather than guess which encoding you want, Python defaults to the lowest common denominator: ASCII. If you want something to be a particular encoding, you have to encode it yourself. Exactly the opposite , if python don't know the encoding should not try decode to ASCII. You have a couple of choices on how to make it work: 1) Play dumb and always encode as UTF-8. This would look really weird if someone tried running your program in a terminal with a CP-847 encoding (like cmd.exe on at least the US version of Windows), but it would never crash. I want python don't care about encoding terminal and send characters as they are or for a file . 2) Check sys.stdout.encoding. If it's ascii, then encode your unicode string in the string-escape encoding, which substitutes the escape sequence in for all non-ASCII characters. How I change sys.stdout.encoding always to UTF-8 ? at least have a consistent sys.stdout.encoding 3) Check to see if sys.stdout.isatty() and have different behavior for terminals vs files. If you're on a terminal that doesn't declare its encoding, encoding it as UTF-8 probably won't help. If you're writing to a file, that might be what you want to do. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Ben Finney wrote: Sérgio Monteiro Basto sergi...@sapo.pt writes: ./test.py moçambique moçambique In this case your terminal is reporting its encoding to Python, and it's capable of taking the UTF-8 data that you send to it in both cases. ./test.py output.txt Traceback (most recent call last): File ./test.py, line 5, in module print u UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 2: ordinal not in range(128) In this case your shell has no preference for the encoding (since you're redirecting output to a file). How I say to python that I want that write in utf-8 to files ? In the first print statement you specify the encoding UTF-8, which is capable of encoding the characters. In the second print statement you haven't specified any encoding, so the default ASCII encoding is used. Moral of the tale: Make sure an encoding is specified whenever data steps between bytes and characters. Don't seems logic, when send things to a file the beaviour change. They're different files, which have been opened with different encodings. If you want a different encoding, you need to specify that. -- http://mail.python.org/mailman/listinfo/python-list
[JOB] Python Programmer, Newport Beach, CA | 6-24 months - Relo OK
This is a contract/hourly 6-24 month on-site Python Programming job located in Newport Beach, CA paying $50.00 to $80.00 per hour depending on experience. Local candidates preferred, but all considered. Relocation expenses covered. Our Newport Beach, CA client is seeking a Python programmer with web- based development experience to assist with developing web based applications. The successful candidate should have excellent Python programming skills (with web development; dynamically generated charts/plots in particular) and working knowledge of Linux/UNIX Shell Scripts and SQL; Knowledge of Python integration with C/C++; - a definite plus. Selected candidate will be working with our ABS/MBS trade desk to develop and enhance applications used by Fixed Income Portfolio Management. You will assist in the design, construction and enhancement of applications used. Qualified candidates must possess a four-year college degree with a preferred major in Computer Science, Computer Engineering, or other technical/IT degree. A strong familiarity with Python on Linux; recent (2007) experience is required. Knowledge with web technologies including Apache, JavaScript/AJAX, CSS, HTML, designing, coding, and testing web based applications a plus. Programming experience in C++ is also a plus. Our selected individual must be a team player, be self-motivated, and have excellent verbal communication skills. In addition, the ability to project manage and work within a team environment will be critical to being successful in this role. Experience in the Securities industry, preferably Fixed Income is a plus. Qualifications/Requirements: * 3+ years of Python programming on Linux/Unix platform; recent (2007) required * Programming skills building forms, lay-outs, charts, and graphing required * Designing, coding, and testing web based applications preferred * Strong organizational, oral and written communications skills * High energy/self starter with the ability to work independently within the firm; demanding and highly focused environment If you are interested in this job, please submit your RESUME and HOURLY requirements to opensourcestaffing|AT|gmail.com Thank you, Beau J. Gould -- Open Source Staffing http://opensourcestaffing.wordpress.com opensourcestaffing|AT|gmail.com Follow me on Twitter: ossjobs -- http://mail.python.org/mailman/listinfo/python-list
Re: Gnumeric scripting and license
Bhushit Joshipura joship...@gmail.com writes: I am looking for some information about Gnumeric scripting licensing. You're asking in the wrong place; that's a question for the authors of the GPL, and for the copyright holders in Gnumeric. The authors of the GPL have an FAQ document you will likely find informative URL:http://www.gnu.org/copyleft/gpl-faq.html. If I script for Gnumeric using Python, must I release the script code? As far as Python is concerned, the license of Python does not require you to release your code. Consult the FSF, and the Gnumeric copyright holders, and your legal advisor, for the rest of your question. -- \ “The cost of a thing is the amount of what I call life which is | `\ required to be exchanged for it, immediately or in the long | _o__) run.” —Henry David Thoreau | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: On Thu, 09 Jun 2011 17:44:32 +1000, Ben Finney wrote: Eric Snow ericsnowcurren...@gmail.com writes: AttributeError: attribute '__doc__' of 'type' objects is not writable That is on 3.3. Well, that sucks :-( Where can we see the discussion of that change before it was implemented? It goes back to Python 2.2, when new style classes were first introduced. […] It's an unnecessary restriction, as far as I'm concerned, but an old one. Well, it's incompatible with the Python compiler I keep in my head. Have these developers no consideration for backward-thinking-compatibility? -- \ “The fact that I have no remedy for all the sorrows of the | `\ world is no reason for my accepting yours. It simply supports | _o__) the strong probability that yours is a fake.” —Henry L. Mencken | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
On Thu, 09 Jun 2011 22:14:17 +0100, Sérgio Monteiro Basto wrote: Exactly the opposite , if python don't know the encoding should not try decode to ASCII. What should it decode to, then? You can't write characters to a stream, only bytes. I want python don't care about encoding terminal and send characters as they are or for a file . You can't write characters to a stream, only bytes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Gnumeric scripting and license
On Fri, Jun 10, 2011 at 12:47 AM, Bhushit Joshipura joship...@gmail.com wrote: I am looking for some information about Gnumeric scripting licensing. Here is my question: If I script for Gnumeric using Python, must I release the script code? I am unable to draw a line where Gnumeric GPL ends and where proprietary nature of macros start. As a general rule, the GPL doesn't care what you do with your own modified copy of something; it's only a concern if you _distribute_ a modified copy (in which case you have to make available the source code, etc etc). You're fully allowed to fiddle with something and compile it for your own use, and not release your changes. See for instance the GPL FAQ which Ben Finney posted, specifically this question and answer: http://www.gnu.org/copyleft/gpl-faq.html#GPLRequireSourcePostedPublic Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
IMO, it shouldn't be necessary to explicitly copy docstrings around like this in the first place. Either it should happen automatically, or help() should be smart enough to look up the inheritance hierarchy when given a method that doesn't have a docstring of its own. Unfortunately, since unbound methods were ditched, help(Foo.blarg) no longer has an easy way to find the base classes, so help from the compiler may be needed. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
Chris Angelico wrote: Rather than find all prime numbers up to num, stop at sqrt(num) - it's not possible to have any prime factors larger than that. That's not quite true -- the prime factors of 26 are 2 and 13, and 13 is clearly greater than sqrt(26). However, once you've divided out all the primes up to sqrt(n), whatever is left, if greater than 1, must itself be prime, so you can add it to your prime factors and stop. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On Fri, Jun 10, 2011 at 8:39 AM, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Chris Angelico wrote: Rather than find all prime numbers up to num, stop at sqrt(num) - it's not possible to have any prime factors larger than that. That's not quite true -- the prime factors of 26 are 2 and 13, and 13 is clearly greater than sqrt(26). Oops! My bad. I was thinking in terms of the divide and conquer algorithm, whereby the 13 would be the residuum after dividing by 2... However, once you've divided out all the primes up to sqrt(n), whatever is left, if greater than 1, must itself be prime, so you can add it to your prime factors and stop. ... which is effectively the same as you describe here. It's a small algorithmic change but an extremely advantageous one. If you _don't_ look for the residuum, then you stop at n/2 instead of sqrt(n). Either way, though, you don't need to list the primes all the way up to n, which will improve performance significantly. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
On Fri, Jun 10, 2011 at 3:18 AM, hisan santosh.s...@gmail.com wrote: Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. As a side point, you should probably use 2.7 rather than 2.6. With regard to 2.x versus 3.x, Corey already posted a link to an excellent article. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, Jun 9, 2011 at 4:27 PM, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: IMO, it shouldn't be necessary to explicitly copy docstrings around like this in the first place. Either it should happen automatically, or help() should be smart enough to look up the inheritance hierarchy when given a method that doesn't have a docstring of its own. Auto inheriting docstrings would be nice, in some cases. WRT help(), keep in mind that docstrings are used for a bunch of other things, like doctests and some DSLs. -eric Unfortunately, since unbound methods were ditched, help(Foo.blarg) no longer has an easy way to find the base classes, so help from the compiler may be needed. -- Greg -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Sérgio Monteiro Basto sergi...@sapo.pt writes: Ben Finney wrote: In this case your shell has no preference for the encoding (since you're redirecting output to a file). How I say to python that I want that write in utf-8 to files ? You already did: In the first print statement you specify the encoding UTF-8, which is capable of encoding the characters. If you want UTF-8 on the byte stream for a file, specify it when opening the file, or when reading or writing the file. -- \ “But Marge, what if we chose the wrong religion? Each week we | `\ just make God madder and madder.” —Homer, _The Simpsons_ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Gregory Ewing greg.ew...@canterbury.ac.nz writes: IMO, it shouldn't be necessary to explicitly copy docstrings around like this in the first place. Either it should happen automatically, or help() should be smart enough to look up the inheritance hierarchy when given a method that doesn't have a docstring of its own. Since the docstrings are useful in more places than just ‘help’, I'm +1 on having docstrings be automatically inherited if not specified. Would the OP like to propose this on ‘python-ideas’? -- \“Odious ideas are not entitled to hide from criticism behind | `\ the human shield of their believers' feelings.” —Richard | _o__) Stallman | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
__doc__ immutable for classes (was: Re: how to inherit docstrings?)
On Thu, Jun 9, 2011 at 10:10 AM, Ethan Furman et...@stoneleaf.us wrote: Eric Snow wrote: p.s. Am I missing something or can you really not change the docstring of a class? I was thinking about the idea of inheriting class docstrings too. 8 module level docstring def func(): function level docstring class Test(object): class level docstring def meth(self): method level docstring if __name__ == '__main__': import sys import traceback hmmm = ( sys.modules['__main__'], func, Test(), Test().meth, Test, Test.meth, ) for obj in hmmm: try: obj.__doc__ = 'new docstring' print('successfully changed %s\n' % obj) except: traceback.print_exc() print() 8 Tested from 2.5 - 3.2. The first three always work, the last one works in 3.1+, the fourth and fifth always fail. -actual output for 2.5 successfully changed module '__main__' from 'docstring.py' successfully changed function func at 0x00A8F570 successfully changed __main__.Test object at 0x00A94230 Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'instancemethod' objects is not writable () Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'type' objects is not writable () Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'instancemethod' objects is not writable () -actual output for 3.2 successfully changed module '__main__' from 'docstring.py' successfully changed function func at 0x00BE6F60 successfully changed __main__.Test object at 0x00BFE730 Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'method' objects is not writable Traceback (most recent call last): File docstring.py, line 25, in module obj.__doc__ = 'new docstring' AttributeError: attribute '__doc__' of 'type' objects is not writable successfully changed function meth at 0x00BE6ED0 -actual output ~Ethan~ Thanks for looking up all of that, Ethan! I would love to see __doc__ writable for classes. But for method objects (really a wrapper for bound functions) would it change the __doc__ of the wrapper or of the bound function? Seems like it is analogous to the Test().__doc__ case, so the wrapper would be updated. However, I haven't really had a need to do that before, so I don't know which makes more sense. Should I take this to python-ideas? And maybe Greg's thought of auto inheriting __doc__? -eric -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, Jun 9, 2011 at 5:23 PM, Ben Finney ben+pyt...@benfinney.id.au wrote: Gregory Ewing greg.ew...@canterbury.ac.nz writes: IMO, it shouldn't be necessary to explicitly copy docstrings around like this in the first place. Either it should happen automatically, or help() should be smart enough to look up the inheritance hierarchy when given a method that doesn't have a docstring of its own. Since the docstrings are useful in more places than just ‘help’, I'm +1 on having docstrings be automatically inherited if not specified. Would the OP like to propose this on ‘python-ideas’? Yeah, I'll do that. Thanks. -eric -- \ “Odious ideas are not entitled to hide from criticism behind | `\ the human shield of their believers' feelings.” —Richard | _o__) Stallman | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
On 6/9/2011 5:46 PM, Nobody wrote: On Thu, 09 Jun 2011 22:14:17 +0100, Sérgio Monteiro Basto wrote: Exactly the opposite , if python don't know the encoding should not try decode to ASCII. What should it decode to, then? You can't write characters to a stream, only bytes. I want python don't care about encoding terminal and send characters as they are or for a file . You can't write characters to a stream, only bytes. Characters, representations are for people, byte representations are for computers. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Sérgio Monteiro Basto sergi...@sapo.pt wrote in message news:4df137a7$0$30580$a729d...@news.telepac.pt... How I change sys.stdout.encoding always to UTF-8 ? at least have a consistent sys.stdout.encoding There is an environment variable that can force Python I/O to be a specfic encoding: PYTHONIOENCODING=utf-8 -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On Thu, Jun 9, 2011 at 10:55 AM, geremy condra debat...@gmail.com wrote: On Thu, Jun 9, 2011 at 4:38 AM, Dave Angel da...@ieee.org wrote: On 01/-10/-28163 02:59 PM, Chris Rebert wrote: On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium sganapathy.subraman...@gmail.com wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. Others have pointed out various inefficiencies. But I wanted to start by asking what this is for. Do you really have a need to factor numbers over 2 billion? Repeatedly? In multiple runs of the program? Do you have weeks of computer time to spend or just hours? Are you really interested in the factors, or just whether or not a particular large number is prime (==has anyfactors) ? If this is a homework assignment, what's the exact assignment? Are you permitted to use other libraries, or other languages? Are you permitted to use language features you haven't encountered yet in class? My solution: def factors(x): status, output = subprocess.getstatusoutput('factor %d' % x) if not status: return [int(i) for i in output.split()[1:]] else: print(output) Works pretty well. snip So you should probably turn the problem around. Design a function that calculates the nth prime, but that caches the work it's already done (on disk if appropriate, but in a list if not). In the loop that's finding the factors, simply call the first function each time, and each time you find a factor, divide num by that so you're dealing with a smaller number. Just use a precomputed table to do your trial division. There's a list of the first fifty million primes on prime pages- if you aren't dealing with specially constructed values (ie, RSA moduli) and haven't found a factor by the end of the first ten thousand or so you probably need to do a primality check before moving on to trying to factor it. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list You Might be able to benefit from a primality test like Miller-Rabin, at least if your numbers can be really large. It can answer with this number is definitely composite or this number is probably prime. For quite large numbers, it might speed things up. For smaller numbers, trial division is faster. I have a Python Miller-Rabin module at: http://stromberg.dnsalias.org/svn/big-prime/trunk/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thursday, June 9, 2011 3:27:36 PM UTC-7, Gregory Ewing wrote: IMO, it shouldn't be necessary to explicitly copy docstrings around like this in the first place. Either it should happen automatically, or help() should be smart enough to look up the inheritance hierarchy when given a method that doesn't have a docstring of its own. Presumably, the reason you are overriding a method in a subclass is to change its behavior; I'd expect an inherited docstring to be inaccurate more often than not. So I'd be -1 on automatically inheriting them. However, I'd be +1 easily on a little help from the language to explicitly request to inherit the docstring. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Nobody wrote: Exactly the opposite , if python don't know the encoding should not try decode to ASCII. What should it decode to, then? UTF-8, as in tty, how I change this default ? You can't write characters to a stream, only bytes. ok got the point . Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Mark Tolonen wrote: Sérgio Monteiro Basto sergi...@sapo.pt wrote in message news:4df137a7$0$30580$a729d...@news.telepac.pt... How I change sys.stdout.encoding always to UTF-8 ? at least have a consistent sys.stdout.encoding There is an environment variable that can force Python I/O to be a specfic encoding: PYTHONIOENCODING=utf-8 Excellent thanks , double thanks. BTW: should be set by default on a utf-8 systems like Fedora, Ubuntu, Debian , Redhat, and all Linuxs. For sure I will put this on startup of my systems. -Mark -- Sérgio M. B. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
If your dependencies are satisfiable with 3.2, you're better off with 3.2. If not, use 2.7, or consider porting the dependencies yourself (assuming those dependencies have code available). Both 2.x and 3.x are good, but 3.x is clearly the way forward. 3.x has some annoyances corrected: more central unicode, incompatible types aren't silently compared in a strange way, a callable can insist on named arguments, etc. The best way to learn the difference, IMO, is to develop on both. You can do this by using 3to2, using 2to3, or using a common subset. If you write automated tests, and set them up to run with one or more 2.x's and one or more 3.x's, you'll see the differences that matter in your code pretty quickly. I've been opting for the common subset, and have been very happy with it. Lately I'm testing on cpython 2.[567], cpython 3.[012], pypy 1.[45] and Jython 2.5.2 (the jython with a fix or two patched in). 3to2 sounds like a bit nicer option than 2to3, because 3to2 can start from code that knows the difference between the two main kinds of strings. On Thu, Jun 9, 2011 at 10:18 AM, hisan santosh.s...@gmail.com wrote: Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. Please let me know the difference between them. Please give some refernce site or books to know the difference -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Carl Banks pavlovevide...@gmail.com writes: Presumably, the reason you are overriding a method in a subclass is to change its behavior; I'd expect an inherited docstring to be inaccurate more often than not. In which case the onus is on the programmer implementing different behaviour to also override the docstring. -- \ “When we pray to God we must be seeking nothing — nothing.” | `\ —Saint Francis of Assisi | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Sérgio Monteiro Basto sergi...@sapo.pt writes: Nobody wrote: Exactly the opposite , if python don't know the encoding should not try decode to ASCII. Are you advocating that Python should refuse to write characters unless the encoding is specified? I could sympathise with that, but currently that's not what Python does; instead it defaults to the ASCII codec. What should it decode to, then? UTF-8, as in tty But when you explicitly redirect to a file, it's *not* going to a TTY. It's going to a file whose encoding isn't known unless you specify it. -- \ “Reality must take precedence over public relations, for nature | `\cannot be fooled.” —Richard P. Feynman | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Ben Finney wrote: Exactly the opposite , if python don't know the encoding should not try decode to ASCII. Are you advocating that Python should refuse to write characters unless the encoding is specified? I could sympathise with that, but currently that's not what Python does; instead it defaults to the ASCII codec. could be a solution ;) or a smarter default based on LANG for example (as many GNU does). -- Sérgio M. B. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, Jun 9, 2011 at 7:12 PM, Carl Banks pavlovevide...@gmail.com wrote: On Thursday, June 9, 2011 3:27:36 PM UTC-7, Gregory Ewing wrote: IMO, it shouldn't be necessary to explicitly copy docstrings around like this in the first place. Either it should happen automatically, or help() should be smart enough to look up the inheritance hierarchy when given a method that doesn't have a docstring of its own. Presumably, the reason you are overriding a method in a subclass is to change its behavior; I'd expect an inherited docstring to be inaccurate more often than not. So I'd be -1 on automatically inheriting them. When I write ABCs to capture an interface, I usually put the documentation in the docstrings there. Then when I implement I want to inherit the docstrings. Implicit docstring inheritance for abstract base classes would meet my needs. I'm just not clear on the impact this would have for the other use cases of docstrings. However, I'd be +1 easily on a little help from the language to explicitly request to inherit the docstring. Yeah, that's more or less how I feel too. But what would fill that role? This comes back to my original question. A method at definition time does not know its class, nor would the decorator, so they won't know where from to inherit the docstring. Like I said originally, you can approach this a number of ways, but the one that appeals to me most (plain function decorators) doesn't work without some explicit help, which I would rather avoid. Implicit help would be nice, but how to do it? The most direct form, presenting the class to the execution frame of the body somehow, seems risky and strange. It's sort of like the function object being inserted into the locals when it is called. However, the class object would have to be created before the body gets exec'ed, rather than as now, where metaclass.__new__ is called after... Changing that would require changes to type.__new__ and how it's used. Perhaps a good approach would be to have a special decorator in the stdlib that type.__new__ would recognize, like this: def inherits_docstring(f): if f.__doc__ is None: f.__doc__ = NotImplemented return f # actually in typeobject.c, or something def type.__new__(meta, name, bases, namespace): # do the normal stuff here # now handle docstring inheritance for name, obj in namespace.items(): if hasattr(obj, __doc__) and obj.__doc__ is NotImplemented: # inherit the docstring... But then I look at that and wonder if it's too special-cased to be worth the trouble. I can just use a metaclass or class decorator that does that, and override builtin.__build__class__ to force its use everywhere; or use one base class for all my classes that uses the metaclass. But it would be nice to have implicit support. -eric Carl Banks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thursday, June 9, 2011 6:42:44 PM UTC-7, Ben Finney wrote: Carl Banks writes: Presumably, the reason you are overriding a method in a subclass is to change its behavior; I'd expect an inherited docstring to be inaccurate more often than not. In which case the onus is on the programmer implementing different behaviour to also override the docstring. Totally disagree. The programmer should never be under onus to correct mistakes made by the langauge. In the face of ambiguity, refuse the temptation to guess. When the language tries to guess what the programmer wants, you get monstrosities like Perl. Don't want to go there. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thursday, June 9, 2011 7:37:19 PM UTC-7, Eric Snow wrote: When I write ABCs to capture an interface, I usually put the documentation in the docstrings there. Then when I implement I want to inherit the docstrings. Implicit docstring inheritance for abstract base classes would meet my needs. Do all the subclasses do exactly the same thing? What's the use of a docstring if it doesn't document what the function does? class Shape(object): def draw(self): Draw a shape raise NotImplementedError class Triangle(Shape): def draw(self): print Triangle class Square(Shape): def draw(self): print Square x = random.choice([Triange(),Square()]) print x.draw.__doc__ # prints Draws a shape Quick, what shape is x.draw() going to draw? Shouldn't your docstring say what the method is going to do? So, I'm sorry, but I don't see this being sufficient for your use case for ABCs. I'm just not clear on the impact this would have for the other use cases of docstrings. Whenever somebody overrides a method to do something different, the inherited docstring will be insufficient (as in your ABC example) or wrong. This, I would say, is the case most of the time when overriding a base class method. When this happens, the language is committing an error. Put it this way: if Python doesn't automatically inherit docstrings, the worst that can happen is missing information. If Python does inherit docstrings, it can lead to incorrect information. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
John Gordon wrote: In 9037ef5f-53c5-42c6-ac5d-8f942df6c...@x38g2000pri.googlegroups.com hisan santosh.s...@gmail.com writes: Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. Please let me know the difference between them. Please give some refernce site or books to know the difference If you're starting new, use 3.2. All code will eventually move to this newer style, so you'll have to learn it eventually. The only reason to use 2.6 is if you have to maintain an existing code base that was written with 2.6 (or older). Library support. Cheers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
On 6/9/2011 11:41 PM, Kyle T. Jones wrote: Library support. I urge people who use 2.x only for library support to let library authors that they would have preferred a 3.x compatible library. I have library authors say Why port when none of my users have asked for a port? A couple of years ago, users were people who were already programming with 2.x. That is changing now. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On 6/9/2011 9:12 PM, Carl Banks wrote: Presumably, the reason you are overriding a method in a subclass is to change its behavior; I'd expect an inherited docstring to be inaccurate more often than not. So I'd be -1 on automatically inheriting them. However, I'd be +1 easily on a little help from the language to explicitly request to inherit the docstring. An empty docstring could be interpreted as 'ditto' ;-) It would be useless otherwise. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
On 2011.06.09 12:18 PM, hisan wrote: Hi All, Please let me know which one is GOOD whether Python 2.6 OR 3.2. Please let me know the difference between them. Please give some refernce site or books to know the difference I'm just a beginner, but AFAICT, there are three reasons to learn Python 2: - You will need to maintain or add features to a project that is written in Python 2 and is not easily converted to Python 3. - You have a project that absolutely depends on something that is written in Python 2 and is not easily converted to Python 3. - You are forced to use a 2.x version of the interpreter (e.g., your employer wants you to create Python scripts that will run on their server, which runs a 2.x version of the interpreter). In this case, you should learn the exact version of the interpreter used (some features in 2.7 aren't available in e.g., 2.3). If none of these apply to you, then 3.2 all the way. Everything is moving to 3.x - don't use 2.x as a starting point if you don't have to. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, Jun 9, 2011 at 9:59 PM, Terry Reedy tjre...@udel.edu wrote: On 6/9/2011 9:12 PM, Carl Banks wrote: Presumably, the reason you are overriding a method in a subclass is to change its behavior; I'd expect an inherited docstring to be inaccurate more often than not. So I'd be -1 on automatically inheriting them. However, I'd be +1 easily on a little help from the language to explicitly request to inherit the docstring. An empty docstring could be interpreted as 'ditto' ;-) It would be useless otherwise. I kind of like that. The only catch is for cases out there where someone used an empty string. Then it would change the behavior, maybe. But how uncommon that is, not sure. I would guess pretty uncommon. Whole implicitly inherit idea would require the empty docstring to say don't do it. With your idea you easily, clearly, and explicitly indicate that you want the inheritance activated. That would work for me. -eric -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: smtp - python
Thank you. The question is that. Get the messages that was sended and save in maildir format. One more question... testing here, has the smtpd.pureproxy support stream username and password for smtp authentication ?. I read some doc and don't find anything about. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Carl Banks pavlovevide...@gmail.com writes: On Thursday, June 9, 2011 7:37:19 PM UTC-7, Eric Snow wrote: When I write ABCs to capture an interface, I usually put the documentation in the docstrings there. Then when I implement I want to inherit the docstrings. Implicit docstring inheritance for abstract base classes would meet my needs. Do all the subclasses do exactly the same thing? What's the use of a docstring if it doesn't document what the function does? The docstring should document the object (module, class, or function) in a way useful for the user of that API. Differing implementations don't necessarily make for differing external behaviour. In those cases where the external behaviour can be adequately described by exactly the same docstring as the parent class's method, it's tedious and error-prone to repeat or duplicate the docstring. class Shape(object): def draw(self): Draw a shape raise NotImplementedError class Shape(object): Abstract class for shapes. def draw(self): Draw this shape. raise NotImplementedError class Triangle(Shape): def draw(self): print Triangle class Triangle(Shape): A three-sided polygon. def draw(self): trace_three_sided_polygon() class Square(Shape): def draw(self): print Square class Square(Shape): An equal-sided quadrilateral polygon. def draw(self): trace_quadrilateral_with_equal_sides() x = random.choice([Triange(),Square()]) print x.draw.__doc__ # prints Draws a shape x = random.choice([Triangle(), Square()]) print x.draw.__doc__# = Draw this shape. Quick, what shape is x.draw() going to draw? print x.__doc__# = An equal-sided quadrilateral polygon. Shouldn't your docstring say what the method is going to do? There's nothing wrong with the docstring for a method referring to the context within which the method is defined. Whenever somebody overrides a method to do something different, the inherited docstring will be insufficient (as in your ABC example) or wrong. I hope the above demonstrates that your assertion is untrue. Every single method on a class doesn't need to specify the full context; a docstring that requires the reader to know what class the method belongs to is fine. -- \ “In any great organization it is far, far safer to be wrong | `\ with the majority than to be right alone.” —John Kenneth | _o__)Galbraith, 1989-07-28 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Ben Finney ben+pyt...@benfinney.id.au writes: class Square(Shape): An equal-sided quadrilateral polygon. That this docstring is imprecise (it describes any rhombus, not necessarily a square) is something I hope no-one else notices or draws attention to. Oh, darn. -- \ “The sun never sets on the British Empire. But it rises every | `\morning. The sky must get awfully crowded.” —Steven Wright | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, Jun 10, 2011 at 3:25 PM, Ben Finney ben+pyt...@benfinney.id.au wrote: Ben Finney ben+pyt...@benfinney.id.au writes: class Square(Shape): An equal-sided quadrilateral polygon. That this docstring is imprecise (it describes any rhombus, not necessarily a square) is something I hope no-one else notices or draws attention to. class Square(Number): A class designed to confuse the issue arbitrarily. pass Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Le 09/06/2011 04:18, Sérgio Monteiro Basto a écrit : hi, cat test.py #!/usr/bin/env python #-*- coding: utf-8 -*- u = u'moçambique' print u.encode(utf-8) print u chmod +x test.py ../test.py moçambique moçambique The following tries to encode before to print. If you pass an already utf-8 object, it just print it; if not it encode it. All the print statements pass by MyPrint.write #!/usr/bin/env python #-*- coding: utf-8 -*- import sys class MyPrint(object): def __init__(self): self.old_stdout=sys.stdout sys.stdout=self def write(self,text): try: encoded=text.encode(utf8) except UnicodeDecodeError: encoded=text self.old_stdout.write(encoded) MyPrint() u = u'moçambique' print u.encode(utf-8) print u TEST : $ ./test.py moçambique moçambique $ ./test.py test.txt $ cat test.txt moçambique moçambique By the way, my code will not help for error message. I think that the errors are printed by sys.stderr.write. So if you want to do raise moçambique you should think about add stderr to the class MyPrint If you know French, I strongly recommend Comprendre les erreurs unicode by Victor Stinner : http://dl.afpy.org/pycon-fr-09/Comprendre_les_erreurs_unicode.pdf Have a nice day Laurent -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Le 09/06/2011 04:18, Sérgio Monteiro Basto a écrit : hi, cat test.py #!/usr/bin/env python #-*- coding: utf-8 -*- u = u'moçambique' print u.encode(utf-8) print u chmod +x test.py ../test.py moçambique moçambique The following tries to encode before to print. If you pass an already utf-8 object, it just print it; if not it encode it. All the print statements pass by MyPrint.write #!/usr/bin/env python #-*- coding: utf-8 -*- import sys class MyPrint(object): def __init__(self): self.old_stdout=sys.stdout sys.stdout=self def write(self,text): try: encoded=text.encode(utf8) except UnicodeDecodeError: encoded=text self.old_stdout.write(encoded) MyPrint() u = u'moçambique' print u.encode(utf-8) print u TEST : $ ./test.py moçambique moçambique $ ./test.py test.txt $ cat test.txt moçambique moçambique By the way, my code will not help for error message. I think that the errors are printed by sys.stderr.write. So if you want to do raise moçambique you should think about add stderr to the class MyPrint If you know French, I strongly recommend Comprendre les erreurs unicode by Victor Stinner : http://dl.afpy.org/pycon-fr-09/Comprendre_les_erreurs_unicode.pdf Have a nice day Laurent -- http://mail.python.org/mailman/listinfo/python-list
[issue7753] newgil backport
Changes by Julian Mehnle jul...@mehnle.net: -- nosy: +jmehnle ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7753 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9284] inspect.findsource() cannot find source for doctest code
Dirkjan Ochtman dirk...@ochtman.nl added the comment: Would it still be possible to get this into 2.7.2? It's a 2.6-2.7 regression, would be nice to fix, and it seems fairly low-impact. -- nosy: +benjamin.peterson ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9284 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12187] subprocess.wait() with a timeout uses polling on POSIX
Charles-François Natali neolo...@free.fr added the comment: Antoine is right: we don't have to be portable. We don't have to, but writing one POSIX-conformant solution is better than writing N OS-specific solutions, no? That's what POSIX is about. Should we block the signal? Yes. What happens when we unblock the signal? If you've read from the FD, nothing, since it consumes the pending signals. If you haven't, since signal_pthread_sigmask checks for pending signals, I guess that the handler will be called upon unblock. But signalfd is designed as an alternative to handlers, so I don't think this makes much sense, and if a SIGCHLD handler is setup, it's likely to perform a waitpid(-1, WNOHANG), which will screw up our waiting anyway... Is it possible to block a signal in all threads? Not portably. sigwait() is not impacted by the associated signal handler, but sigwait() only works if the signal is blocked (e.g. by pthread_sigmask): The point I was making is precisely that blocking the signal is not enough on some kernels: when the signal is ignored, it will sometimes not wakeup threads waiting on sigwait. sigprocmask(), sigwait() and signals in general seem to behave differently on each OS They behave correctly as long as they're used in a POSIX-conformant way. To sum up, those problems are: - since SIGCHLD is ignored by default, some kernels won't wake up threads waiting on sigwait (it works on Linux, don't know for *BSD kernels) - there's not portable way to block signals in all threads. As a consequence, there will be cases where sigtimedwait or select on a signalfd will wait until the end of the timeout. See also issue #8407 for sigtimedwait() and signalfd() in Python. You didn't commit the signalfd part? Whay do you think of sigtimedwait? Expose it as-is, or just add an optional timeout option to sigwait? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12187 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1195571] simple callback system for Py_FatalError
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: Sorry, the documentation in the patch is wrong. It should be: Cause :cfunc:`Py_FatalError` to invoke the given function before printing to standard error and aborting out of the process. I don't think it's worth making it more complex. If the application does not want the default behavior (which is already quite minimal anyway), it can always install a hook that never returns. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1195571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12291] file written using marshal in 3.2 can be read by 2.7, but not 3.2 or 3.3
New submission from Vinay Sajip vinay_sa...@yahoo.co.uk: The attached file 'data.bin' was written using Python 3.2. It can be read by Python 2.7, but in 3.2 and 3.3, after the first object is read, the file pointer is positioned at EOF, causing an error on subsequent reads. A simple test script 'marshtest.py' is below: import marshal import sys f = open('data.bin', 'rb') t = marshal.load(f) print('Python version:', sys.version) print('Object just loaded was:\n%r' % (t,)) print('File position is now at %d' % f.tell()) t = marshal.load(f) print('Object just loaded was:\n%r' % (t,)) print('File position is now at %d' % f.tell()) Results of running it under various Python versions: vinay@eta-natty:~/projects/scratch$ python marshtest.py ('Python version:', '2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) \n[GCC 4.5.2]') Object just loaded was: (u'text', u'alfa', 202, 1.0, '\x00\x00\x00\x01]q\x00K\x03a') File position is now at 52 Object just loaded was: (u'text', u'alfa', 212, 1.0, '\x00\x00\x00\x01]q\x00K\x03a') File position is now at 104 vinay@eta-natty:~/projects/scratch$ python3.2 marshtest.py Python version: 3.2 (r32:88445, Mar 25 2011, 19:28:28) [GCC 4.5.2] Object just loaded was: ('text', 'alfa', 202, 1.0, b'\x00\x00\x00\x01]q\x00K\x03a') File position is now at 53617 Traceback (most recent call last): File marshtest.py, line 9, in module t = marshal.load(f) EOFError: EOF read where object expected vinay@eta-natty:~/projects/scratch$ python3.3 marshtest.py Python version: 3.3a0 (default:8d4d87dd73ae, Apr 2 2011, 14:25:31) [GCC 4.5.2] Object just loaded was: ('text', 'alfa', 202, 1.0, b'\x00\x00\x00\x01]q\x00K\x03a') File position is now at 53617 Traceback (most recent call last): File marshtest.py, line 9, in module t = marshal.load(f) EOFError: EOF read where object expected Note the size of the file is 53617 bytes. vinay@eta-natty:~/projects/scratch$ ls -l data.bin -rw--- 1 vinay vinay 53617 2011-06-09 09:33 data.bin -- files: data.bin messages: 137943 nosy: vinay.sajip priority: normal severity: normal status: open title: file written using marshal in 3.2 can be read by 2.7, but not 3.2 or 3.3 versions: Python 3.2, Python 3.3, Python 3.4 Added file: http://bugs.python.org/file22289/data.bin ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12291 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12291] file written using marshal in 3.2 can be read by 2.7, but not 3.2 or 3.3
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: Sadly, marshal.load() looks broken: - The function starts with the comment /* XXX Quick hack -- need to do this differently */ - It starts by calling f.read() which consumes the whole file (and explains the issue reported here) - The code was probably converted too quickly: if (PyBytes_Check(data)) { ... else if (PyBytes_Check(data)) { -- nosy: +amaury.forgeotdarc ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12291 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8407] expose signalfd(2) and pthread_sigmask in the signal module
STINNER Victor victor.stin...@haypocalc.com added the comment: Oh, sigwait() doesn't accept a timeout! I would be nice to have also sigwaitinfo().. and maybe also its friend, sigwaitinfo() Oops, I mean sigtimedwait() and sigwaitinfo(). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8407 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12187] subprocess.wait() with a timeout uses polling on POSIX
STINNER Victor victor.stin...@haypocalc.com added the comment: (I should not answer in this issue, but in #8407) See also issue #8407 for sigtimedwait() and signalfd() in Python. You didn't commit the signalfd part? Not yet because I would like to provide something to decode the data written into the signalfd file descriptor (msg135438), the signalfd_siginfo structure. Whay do you think of sigtimedwait? It would like to expose it (msg137071, you should read sigtimedwait, not sigwaitinfo :-)). I started to work on a patch, but it requires a siginfo_t structure, and I didn't finish my patch. I will retry later. Expose it as-is, or just add an optional timeout option to sigwait? I prefer thin wrappers: sigwaitinfo() is more than just a timeout argument, there is also the signal info argument. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12187 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1626300] 'Installing Python Modules' does not work for Windows
Roundup Robot devnull@devnull added the comment: New changeset 2951641faed1 by Éric Araujo in branch '2.7': Add examples that work on Windows to distutils docs (#1626300) http://hg.python.org/cpython/rev/2951641faed1 -- nosy: +python-dev ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1626300 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12197] non-blocking SSL write in Windows sends large data but raises exception
David Siroky sir...@dasir.cz added the comment: I didn't meant blocking as setblocking(True). I use select/poll but I can't use returned value from send() immediately since in Windows there are often needed more send rounds to actually know how much data was sent. E.g. in Linux I know it after the first call: sslsock.write(abcd) - returns 2 poll(sslsock) sslsock.write(cd) in Windows I must do: sslsock.write(abcd) - raises SSLError poll(sslsock) sslsock.write(abcd) - returns 4 As I wrote it might be inconsistency in OpenSSL and not in Python's wrapper. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12197 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12243] getpass.getuser works on OSX
Éric Araujo mer...@netwok.org added the comment: That would be Doc/tools/sphinxext/pyspecific.py -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12243 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue11975] Fix referencing of built-in types (list, int, ...)
Éric Araujo mer...@netwok.org added the comment: I don’t like the idea of built-in functions being displayed as “builtins.int”: normal use of builtins is without explicit use of the module name. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue11975 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12246] Warn when trying to install third-party module from an uninstalled checkout
Éric Araujo mer...@netwok.org added the comment: Great! I will edit a bit the message and commit this. -- stage: - commit review type: - behavior ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12246 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue11203] gzip doc is behind
Éric Araujo mer...@netwok.org added the comment: Just one thing: I think the close call needs equal treatment to the open call. The open call is a module-level functions; the close method of GzipFile cannot be equally treated, as it is in the doc of the class, where no methods are given special treatment :) -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue11203 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8927] Handle version incompatibilities in dependencies
Éric Araujo mer...@netwok.org added the comment: [Sridhar] No, it’s register that uploads metadata. (was not sent before?) To me, not to the tracker. Ok, that's interesting. Does p7g.install support packages that do not register their new releases? Setuptools/PIP does by scraping the project home pages. p7g.pypi.simple uses the screen-scraping PyPI interface called “simple”, but I don’t know if it goes over to home pages to find links. Will p7g.install install 0.8.19? Try it in a shell? [Dave] I'm sorry, but it is simply not true that this is not a solved problem. This is a well-understood problem that's solved Well, I’m no researcher but I know that there’s still some research ongoing, in particular for upgrades: http://www.mancoosi.org/ -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8927 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12242] distutils2 environment marker for current compiler
Éric Araujo mer...@netwok.org added the comment: One issue is that multiple compiler patterns may match, Right, we can’t say “first matches” win if it’s unordered, and we won’t have OrderedDict in all versions supported by distutils2. Make it a list of tuples. First match wins, so people will have to write more specific regexes first. and break less existing code That’s not a concern; extensions in setup.cfg are a new thing, and for the Python side, we already break a lot of code. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12242 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12278] Core mentorship mention in the devguide
Éric Araujo mer...@netwok.org added the comment: You can just take the descriptions from the mail.python.org page. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12278 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10645] Remove egg-info files in stdlib
Changes by Éric Araujo mer...@netwok.org: -- dependencies: +Removing wsgiref.egg-info ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10645 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12292] bpython
New submission from Ravish ravish_nayak2...@yahoo.co.in: I was trying to install bpython v0.9.7.1(latest version) on python 2.6.5, it works fine. But If i try to install on python v3.2 it's behaviour is quite abnormal. i.e if I run(bpython) from command prompt, I could able to see the fancy window, but If I try to type something immediately it will show as Segmentation fault. Could you please provide me some suggestion for the above issue. Thanks, -- messages: 137956 nosy: ravish112 priority: normal severity: normal status: open title: bpython type: behavior versions: Python 3.2 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12292 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1626300] 'Installing Python Modules' does not work for Windows
Roundup Robot devnull@devnull added the comment: New changeset 072dbebaa83b by Éric Araujo in branch '3.2': Add examples that work on Windows to distutils docs (#1626300) http://hg.python.org/cpython/rev/072dbebaa83b -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1626300 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9312] Fix usage of :option: markup in stdlib ReST docs
Roundup Robot devnull@devnull added the comment: New changeset 59d785ea0039 by Éric Araujo in branch '3.2': Fix a few misuses of :option: I missed in r86521. http://hg.python.org/cpython/rev/59d785ea0039 -- nosy: +python-dev ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9312 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10645] Remove egg-info files in stdlib
Roundup Robot devnull@devnull added the comment: New changeset e3f6c10eb590 by Éric Araujo in branch 'default': Stop creating a Python-X.Y.Z-pyX.Y.egg-info file on install (#10645) http://hg.python.org/cpython/rev/e3f6c10eb590 New changeset af7bc95e5b1e by Éric Araujo in branch 'default': The change done for #10645 deserves a NEWS entry http://hg.python.org/cpython/rev/af7bc95e5b1e -- nosy: +python-dev ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10645 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10645] Remove egg-info files in stdlib
Changes by Éric Araujo mer...@netwok.org: -- resolution: - fixed stage: - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10645 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12293] wrong arguments passed to SMTP.sendmail in example
New submission from Fredrik Wendt fred...@wendt.se: On http://docs.python.org/library/email-examples.html#email-examples the current example (v2.7.1) at the bottom incorrectly calls SMTP.sendmail() with a single recipient e-mail address. It should be a list of addresses. -- assignee: docs@python components: Documentation messages: 137960 nosy: docs@python, wendt_se priority: normal severity: normal status: open title: wrong arguments passed to SMTP.sendmail in example versions: Python 2.7 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12293 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com