Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE

2011-06-09 Thread Larry Hudson

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?

2011-06-09 Thread Eric Snow
On Thu, Jun 9, 2011 at 12:37 AM, Ben Finney  wrote:
> Eric Snow  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 "", line 1, in 
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?

2011-06-09 Thread Carl Banks
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  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?

2011-06-09 Thread Ben Finney
Eric Snow  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..

2011-06-09 Thread Ganapathy Subramanium
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..

2011-06-09 Thread Chris Rebert
On Thu, Jun 9, 2011 at 1:31 AM, 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

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..

2011-06-09 Thread Ian

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..

2011-06-09 Thread Chris Angelico
On Thu, Jun 9, 2011 at 7:06 PM, Chris Rebert  wrote:
> On Thu, Jun 9, 2011 at 1:31 AM, 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
>
> 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

2011-06-09 Thread Dave Angel

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  "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?

2011-06-09 Thread Duncan Booth
Ben Finney  wrote:

> Eric Snow  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:\Python27>python
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 "", line 1, in 
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 "", 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

2011-06-09 Thread Adam Tauno Williams
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?
?

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  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

-- 
http://mail.python.org/mailman/listinfo/python-list


Investing in data management services could have vast benefits

2011-06-09 Thread waner
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..

2011-06-09 Thread Dave Angel

On 01/-10/-28163 02:59 PM, Chris Rebert wrote:

On Thu, Jun 9, 2011 at 1:31 AM, 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


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"

2011-06-09 Thread TheSaint
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

2011-06-09 Thread Jay Osako
On Jun 8, 6:56 pm, "Gabriel Genellina"  wrote:
> En Wed, 08 Jun 2011 12:28:56 -0300, Jay Osako   
> 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.

 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

2011-06-09 Thread TheSaint
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

2011-06-09 Thread Ethan Furman

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

2011-06-09 Thread Ethan Furman

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

2011-06-09 Thread Thomas Guettler
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

2011-06-09 Thread Bhushit Joshipura
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?

2011-06-09 Thread Steven D'Aprano
On Thu, 09 Jun 2011 17:44:32 +1000, Ben Finney wrote:

> Eric Snow  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 "", 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?

2011-06-09 Thread Ethan Furman

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 

successfully changed 

successfully changed <__main__.Test object at 0x00A94230>

Traceback (most recent call last):
  File "docstring.py", line 25, in 
obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'instancemethod' objects is not 
writable

()
Traceback (most recent call last):
  File "docstring.py", line 25, in 
obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'type' objects is not writable
()
Traceback (most recent call last):
  File "docstring.py", line 25, in 
obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'instancemethod' objects is not 
writable

()
-actual output for 3.2
successfully changed 

successfully changed 

successfully changed <__main__.Test object at 0x00BFE730>

Traceback (most recent call last):
  File "docstring.py", line 25, in 
obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'method' objects is not writable

Traceback (most recent call last):
  File "docstring.py", line 25, in 
obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'type' objects is not writable

successfully changed 
-actual output

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect and OpenVMS

2011-06-09 Thread Mark Franklin
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

2011-06-09 Thread hisan
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

2011-06-09 Thread hisan
On Jun 8, 9:20 pm, hisan  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

2011-06-09 Thread John Gordon
In <9037ef5f-53c5-42c6-ac5d-8f942df6c...@x38g2000pri.googlegroups.com> hisan 
 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

2011-06-09 Thread David
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
> : '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..

2011-06-09 Thread geremy condra
On Thu, Jun 9, 2011 at 4:38 AM, Dave Angel  wrote:
> On 01/-10/-28163 02:59 PM, Chris Rebert wrote:
>>
>> On Thu, Jun 9, 2011 at 1:31 AM, 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.
>>
>
> 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.



> 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

2011-06-09 Thread Dennis
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

2011-06-09 Thread Ned Deily
In article 
<1167f414-8901-4f9c-9d51-2723213fd...@k3g2000prl.googlegroups.com>,
 hisan  wrote:

> On Jun 8, 9:20 pm, hisan  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

2011-06-09 Thread Corey Richardson
-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

2011-06-09 Thread Javier
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  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

2011-06-09 Thread Bart Thate
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

2011-06-09 Thread Sérgio Monteiro Basto
Benjamin Kaplan wrote:

> 2011/6/8 Sérgio Monteiro Basto :
>> 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 
>> 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

2011-06-09 Thread Sérgio Monteiro Basto
Ben Finney wrote:

> Sérgio Monteiro Basto  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 
>> 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

2011-06-09 Thread PHP Recruiter
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

2011-06-09 Thread Ben Finney
Bhushit Joshipura  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 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?

2011-06-09 Thread Ben Finney
Steven D'Aprano  writes:

> On Thu, 09 Jun 2011 17:44:32 +1000, Ben Finney wrote:
>
> > Eric Snow  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

2011-06-09 Thread Nobody
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

2011-06-09 Thread Chris Angelico
On Fri, Jun 10, 2011 at 12:47 AM, Bhushit Joshipura  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?

2011-06-09 Thread Gregory Ewing

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..

2011-06-09 Thread Gregory Ewing

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..

2011-06-09 Thread Chris Angelico
On Fri, Jun 10, 2011 at 8:39 AM, Gregory Ewing
 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

2011-06-09 Thread Chris Angelico
On Fri, Jun 10, 2011 at 3:18 AM, hisan  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?

2011-06-09 Thread Eric Snow
On Thu, Jun 9, 2011 at 4:27 PM, 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.
>

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

2011-06-09 Thread Ben Finney
Sérgio Monteiro Basto  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?

2011-06-09 Thread Ben Finney
Gregory Ewing  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?)

2011-06-09 Thread Eric Snow
On Thu, Jun 9, 2011 at 10:10 AM, Ethan Furman  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 
>
> successfully changed 
>
> successfully changed <__main__.Test object at 0x00A94230>
>
> Traceback (most recent call last):
>  File "docstring.py", line 25, in 
>    obj.__doc__ = 'new docstring'
> AttributeError: attribute '__doc__' of 'instancemethod' objects is not
> writable
> ()
> Traceback (most recent call last):
>  File "docstring.py", line 25, in 
>    obj.__doc__ = 'new docstring'
> AttributeError: attribute '__doc__' of 'type' objects is not writable
> ()
> Traceback (most recent call last):
>  File "docstring.py", line 25, in 
>    obj.__doc__ = 'new docstring'
> AttributeError: attribute '__doc__' of 'instancemethod' objects is not
> writable
> ()
> -actual output for 3.2
> successfully changed 
>
> successfully changed 
>
> successfully changed <__main__.Test object at 0x00BFE730>
>
> Traceback (most recent call last):
>  File "docstring.py", line 25, in 
>    obj.__doc__ = 'new docstring'
> AttributeError: attribute '__doc__' of 'method' objects is not writable
>
> Traceback (most recent call last):
>  File "docstring.py", line 25, in 
>    obj.__doc__ = 'new docstring'
> AttributeError: attribute '__doc__' of 'type' objects is not writable
>
> successfully changed 
> -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?

2011-06-09 Thread Eric Snow
On Thu, Jun 9, 2011 at 5:23 PM, Ben Finney  wrote:
> Gregory Ewing  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

2011-06-09 Thread Terry Reedy

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

2011-06-09 Thread Mark Tolonen


"Sérgio Monteiro Basto"  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..

2011-06-09 Thread Dan Stromberg
On Thu, Jun 9, 2011 at 10:55 AM, geremy condra  wrote:

> On Thu, Jun 9, 2011 at 4:38 AM, Dave Angel  wrote:
> > On 01/-10/-28163 02:59 PM, Chris Rebert wrote:
> >>
> >> On Thu, Jun 9, 2011 at 1:31 AM, 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.
> >>
> >
> > 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.
>
> 
>
> > 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?

2011-06-09 Thread Carl Banks
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

2011-06-09 Thread Sérgio Monteiro Basto
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

2011-06-09 Thread Sérgio Monteiro Basto
Mark Tolonen wrote:

> 
> "Sérgio Monteiro Basto"  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

2011-06-09 Thread Dan Stromberg
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  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?

2011-06-09 Thread Ben Finney
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.

-- 
 \ “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

2011-06-09 Thread Ben Finney
Sérgio Monteiro Basto  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

2011-06-09 Thread Sérgio Monteiro Basto
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?

2011-06-09 Thread Eric Snow
On Thu, Jun 9, 2011 at 7:12 PM, Carl Banks  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 .__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?

2011-06-09 Thread Carl Banks
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?

2011-06-09 Thread Carl Banks
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

2011-06-09 Thread Kyle T. Jones

John Gordon wrote:

In <9037ef5f-53c5-42c6-ac5d-8f942df6c...@x38g2000pri.googlegroups.com> hisan 
 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

2011-06-09 Thread Terry Reedy

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?

2011-06-09 Thread Terry Reedy

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

2011-06-09 Thread Andrew Berg
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?

2011-06-09 Thread Eric Snow
On Thu, Jun 9, 2011 at 9:59 PM, Terry Reedy  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

2011-06-09 Thread Josias L . Gonçalves
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?

2011-06-09 Thread Ben Finney
Carl Banks  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?

2011-06-09 Thread Ben Finney
Ben Finney  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?

2011-06-09 Thread Chris Angelico
On Fri, Jun 10, 2011 at 3:25 PM, Ben Finney  wrote:
> Ben Finney  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

2011-06-09 Thread Laurent Claessens

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

2011-06-09 Thread Laurent Claessens

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

2011-06-09 Thread Laurent Claessens

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: Python 2.6 OR 3.2

2011-06-09 Thread harrismh777

Terry Reedy wrote:

A couple of years ago, users were people who were already programming
with 2.x. That is changing now.


 ... big time !


:)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 OR 3.2

2011-06-09 Thread harrismh777

Andrew Berg wrote:

AFAICT, there are three reasons to learn Python 2:


   ... there is a fourth reason.

The linux distro you are using currently was customized with python 2.x

I ran into this problem this week in fact... on my HP g6 ubuntu notebook 
running 10.04 lucid. It ships with the 2.6.5 interpreter. I installed 
2.7.1 and 3.2 (from sources) and was working along happy as a clam until 
I needed to configure a printer... and the config tools would not 
function... some of them would not even open.  Want to guess?  Yup, the 
config tools are (some of them) written in python 2.6-- and they don't 
run in 2.7.1 nor 3.2  .   :(


So, be careful.  I have had to separate *all* of my python installs on 
*every* one of my systems for this similar reason. The bottom line is if 
the distro ships with 2.6 (minus the idle) chances are that the 
interpreter is there *not* to advocate for python explicitly, but 
because the interpreter is being used by the system somewhere. If you 
install 2.7 or 3.2 you need to be careful to *not* interfere with the 
default setup.


So, you will need to be able to use both.  There is no getting around 
it... but, I would start with 3.2 (seriously). Get 3.2 under your belt 
and then when you need to, go back and deal with the 2.6 regression.


3.2 is better built, is more logically consistent (it really is, no 
kidding), and has some new features that make it very attractive. The 
down-side is that some (most) of the library support is still not there 
for many projects.   It will take some time, but it will happen.




kind regards,
m harris


--
http://mail.python.org/mailman/listinfo/python-list


Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE

2011-06-09 Thread Larry Hudson

On 06/08/2011 11:59 PM, Larry Hudson wrote:

On 06/08/2011 01:09 PM, Cathy James wrote:

I am almost there, but I need a little help:

I would like to


... 


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...) ;-)


... 

In thinking about this some more, I thought a dictionary instead of a list would be a better fit 
for this example.  For one thing, it allows accessing the dogs by name instead of an arbitrary 
index number.  But remember that a dictionary is unordered -- it won't be displayed in the same 
order that the entries were made.


Here's this approach, rewritten (and slightly expanded) using a dictionary.

class DogKennel:
def __init__(self):
"""Dog names/breeds kept in a dictionary"""
self.dogs = {}

def addDog(self):
"""Add a single dog to the dictionary"""
name = input("Enter dog's name:  ")
if name == "":  #   Abort with empty input
return False
breed = input("Enter dog's breed: ")
if breed == "": #   Abort here if needed also
return False
self.dogs[name] = breed
return True

def makeKennel(self):
"""Add multiple dogs (a pack?) to the dictionary"""
while self.addDog():
pass

def getDog(self, name=""):
"""Get the dog's breed by its name"""
if name in self.dogs:
return self.dogs[name]
else:
return None

def display(self):
"""Display all the dogs in the kennel (the dictionary)"""
i = 1
for dog in self.dogs.keys():
print("%2d.  %s: %s" % (i, dog, self.dogs[dog]))
i += 1

#   Note this is a normal function, NOT a member function of DogKennel.
#   It probably should go in the __main__ section to keep it separate from
#   the DogKennel class.  (This would be significant only if you're going
#   to import the DogKennel class into other programs.)
def yesno(prompt = ""):
"""Get a yes or no answer.  Returns True if yes, False if no"""
if prompt != "":
prompt = prompt + " (y/n)  "
while True:
ans = input(prompt).upper()
if ans != "":   #   Answer is not empty
if ans[0] == 'Y':   #   1st char is 'Y'?
return True
if ans[0] == 'N':   #   1st char is 'N'?
return False
#   Otherwise loop back for another go

if __name__ == "__main__":
dogs = DogKennel()
dogs.makeKennel()
dogs.display()
if yesno("Add more dogs?"):
dogs.makeKennel()
print("The kennel now contains")
dogs.display()
while True:
name = input("Which dog do you want?  ")
if name == "":
break
breed = dogs.getDog(name)
if breed != None:
print(name, "is a", breed)

#---
I hope studying this (and my previous) examples help you understand things 
better.
Keep at it...  It will sink in with a little effort. :-)
I also hope my rather verbose answers give you a little insight about the sort of things you 
need to consider when designing your programs.


 -=- Larry -=-
--
http://mail.python.org/mailman/listinfo/python-list