Re: [Tutor] Code to open a website

2013-02-10 Thread ALAN GAULD

>site.py adds the exit/quit Quitter instances to builtins (2.x
>__builtin__). When called they raise SystemExit, like sys.exit does.


So it does. You learn something new every day...
When did that first happen? It was one of my biggest frustrations 
with Python when I first started learning, that you couldn't call exit
without first importing sys (v1.3). But I never noticed that changing 
till now.


Alan G
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code to open a website

2013-02-10 Thread Albert-Jan Roskam


> On Sat, Feb 9, 2013 at 8:33 PM, Alan Gauld  

> wrote:
>> 
>>  Where does exit() come from? Usually its from sys but you
>>  don't import from sys anywhere...
> 
> site.py adds the exit/quit Quitter instances to builtins (2.x
> __builtin__). When called they raise SystemExit, like sys.exit does.
> Since you can bypass importing site.py with the -S flag, it's better
> to use sys.exit.

Maybe the OP meant to say 'quit()' ? That does not require an import.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code to open a website

2013-02-10 Thread ALAN GAULD


> Maybe the OP meant to say 'quit()' ? That does not require an import.


Ooh! another option I didn't know about!
So many ways to get rid of Python and here's me been importing sys 
or raising SystemExit all these years... :-)

Alan G.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code to open a website

2013-02-10 Thread Peter Otten
ALAN GAULD wrote:

>> Maybe the OP meant to say 'quit()' ? That does not require an import.
> 
> 
> Ooh! another option I didn't know about!
> So many ways to get rid of Python and here's me been importing sys
> or raising SystemExit all these years... :-)

I tend to use none of these and my scripts still terminate ;)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code to open a website

2013-02-10 Thread eryksun
On Sun, Feb 10, 2013 at 3:39 AM, ALAN GAULD  wrote:
> So it does. You learn something new every day...
> When did that first happen? It was one of my biggest frustrations
> with Python when I first started learning, that you couldn't call exit
> without first importing sys (v1.3). But I never noticed that changing
> till now.

Quitter was added to site.py in 2.5:

http://hg.python.org/cpython/file/c10a71cf16e4/Lib/site.py#l227

In 2.4, exit/quit were simply strings:

http://hg.python.org/cpython/file/f3f1f1462c82/Lib/site.py#l224
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Walter Prins
Hello,

I have a program where I'm overriding the retrieval of items from a list.
 As background: The data held by the lists are calculated but then read
potentially many times thereafter, so in order to prevent needless
re-calculating the same value over and over, and to remove checking/caching
code from the calculation logic code, I therefore created a subclass of
list that will automatically calculate the value in a given slot
automatically if not yet calculated. (So differently put, I'm implemented a
kind of list specific caching/memoization with the intent that it should be
transparent to the client code.)

The way I've implemented this so far was to simply override
list.__getitem__(self, key) to check if the value needs to be calculated or
not and call a calculation method if required, after which the value is
returned as normal.  On subsequent calls __getitem__ then directly returns
the value without calculating it again.

This worked mostly fine, however yesterday I ran into a slightly unexpected
problem when I found that when the list contents is iterated over and
values retrieved that way rather than via [], then __getitem__ is in fact
*not* called on the list to read the item values from the list, and
consequently I get back the "not yet calculated" entries in the list,
without the calculation routine being automatically called as is intended.

Here's a test application that demonstrates the issue:

class NotYetCalculated:
pass

class CalcList(list):
def __init__(self, calcitem):
super(CalcList, self).__init__()
self.calcitem = calcitem

def __getitem__(self, key):
"""Override __getitem__ to call self.calcitem() if needed"""
print "CalcList.__getitem__(): Enter"
value = super(CalcList, self).__getitem__(key)
if value is NotYetCalculated:
print "CalcList.__getitem__(): calculating"
value = self.calcitem(key)
self[key] = value
print "CalcList.__getitem__(): return"
return value

def calcitem(key):
# Demo: return square of index
return key*key


def main():
# Create a list that calculates its contents via a given
# method/fn onece only
l = CalcList(calcitem)
# Extend with  few entries to demonstrate issue:
l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated,
  NotYetCalculated])

print "1) Directly getting values from list works as expected:
__getitem__ is called:"
print "Retrieving value [2]:\n", l[2]
print
print "Retrieving value [3]:\n", l[3]
print
print "Retrieving value [2] again (no calculation this time):\n", l[2]
print

print "Retrieving values via an iterator doesn't work as expected:"
print "(__getitem__ is not called and the code returns "
print " NotYetCalcualted entries without calling __getitem__. How do I
fix this?)"
print "List contents:"
for x in l: print x


if __name__ == "__main__":
main()

To reiterate:

What should happen:  In test 2) above all entries should be automatically
calculated and output should be numbers only.

What actually happens: In test 2) above the first 2 list entries
corresponding to list indexes 0 and 1 are output as "NotYetCalculated" and
calcitem is not called when required.

What's the best way to fix this problem?  Do I need to maybe override
another method, perhaps provide my own iterator implementation?  For that
matter, why doesn't iterating over the list contents fall back to calling
__getitem__?

Thanks in advance,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Dave Angel

On 02/10/2013 09:32 AM, Walter Prins wrote:

Hello,

I have a program where I'm overriding the retrieval of items from a list.
  As background: The data held by the lists are calculated but then read
potentially many times thereafter, so in order to prevent needless
re-calculating the same value over and over, and to remove checking/caching
code from the calculation logic code, I therefore created a subclass of
list that will automatically calculate the value in a given slot
automatically if not yet calculated. (So differently put, I'm implemented a
kind of list specific caching/memoization with the intent that it should be
transparent to the client code.)

The way I've implemented this so far was to simply override
list.__getitem__(self, key) to check if the value needs to be calculated or
not and call a calculation method if required, after which the value is
returned as normal.  On subsequent calls __getitem__ then directly returns
the value without calculating it again.

This worked mostly fine, however yesterday I ran into a slightly unexpected
problem when I found that when the list contents is iterated over and
values retrieved that way rather than via [], then __getitem__ is in fact
*not* called on the list to read the item values from the list, and
consequently I get back the "not yet calculated" entries in the list,
without the calculation routine being automatically called as is intended.

Here's a test application that demonstrates the issue:

class NotYetCalculated:
 pass

class CalcList(list):
 def __init__(self, calcitem):
 super(CalcList, self).__init__()
 self.calcitem = calcitem

 def __getitem__(self, key):
 """Override __getitem__ to call self.calcitem() if needed"""
 print "CalcList.__getitem__(): Enter"
 value = super(CalcList, self).__getitem__(key)
 if value is NotYetCalculated:
 print "CalcList.__getitem__(): calculating"
 value = self.calcitem(key)
 self[key] = value
 print "CalcList.__getitem__(): return"
 return value

def calcitem(key):
 # Demo: return square of index
 return key*key


def main():
 # Create a list that calculates its contents via a given
 # method/fn onece only
 l = CalcList(calcitem)
 # Extend with  few entries to demonstrate issue:
 l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated,
   NotYetCalculated])

 print "1) Directly getting values from list works as expected:
__getitem__ is called:"
 print "Retrieving value [2]:\n", l[2]
 print
 print "Retrieving value [3]:\n", l[3]
 print
 print "Retrieving value [2] again (no calculation this time):\n", l[2]
 print

 print "Retrieving values via an iterator doesn't work as expected:"
 print "(__getitem__ is not called and the code returns "
 print " NotYetCalcualted entries without calling __getitem__. How do I
fix this?)"
 print "List contents:"
 for x in l: print x


if __name__ == "__main__":
 main()

To reiterate:

What should happen:  In test 2) above all entries should be automatically
calculated and output should be numbers only.

What actually happens: In test 2) above the first 2 list entries
corresponding to list indexes 0 and 1 are output as "NotYetCalculated" and
calcitem is not called when required.

What's the best way to fix this problem?  Do I need to maybe override
another method, perhaps provide my own iterator implementation?  For that
matter, why doesn't iterating over the list contents fall back to calling
__getitem__?



Implement your own __iter__() special method.

And consider whether you might need __setitem__(), __len__(), 
__setslice__(), __getslice__() and others.


Maybe you'd be better off not inheriting from list at all, and just 
having an attribute that's a list.  It doesn't sound like you're 
defining a very big subset of list, and overriding the methods you 
*don't* want seems to be more work than just implementing the ones you do.


A separate question:  is this likely to be a sparse list?  If it's very 
sparse, perhaps you'd consider using a dict, rather than a list attribute.




--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Steven D'Aprano

On 11/02/13 01:32, Walter Prins wrote:

Hello,

I have a program where I'm overriding the retrieval of items from a list.
  As background:

[...snip interesting but irrelevant background...]


Here's a test application that demonstrates the issue:

[...snip overly complicated application...]


Here is a much simpler demonstration:


py> class MyList(list):
... def __getitem__(self, i):
... print "Checking item %d" % i
... return super(MyList, self).__getitem__(i)
...
py> x = MyList([2, 4, 8, 16])
py> x[3]
Checking item 3
16
py> for i in x:
... print "got %s" % i
...
got 2
got 4
got 8
got 16




What's the best way to fix this problem?  Do I need to maybe override
another method, perhaps provide my own iterator implementation?



Pretty much. For lists, the __iter__ method returns a listiterator object
which efficiently iterates over the list items without calling __getitem__.

Try overriding your class' __iter__ method:

def __iter__(self):
for i in range(len(self)):  # use xrange in Python 2
yield self[i]


(untested).



For that
matter, why doesn't iterating over the list contents fall back to calling
__getitem__?



Probably as an optimization.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Peter Otten
Walter Prins wrote:

> Hello,
> 
> I have a program where I'm overriding the retrieval of items from a list.
>  As background: The data held by the lists are calculated but then read
> potentially many times thereafter, so in order to prevent needless
> re-calculating the same value over and over, and to remove
> checking/caching code from the calculation logic code, I therefore created
> a subclass of list that will automatically calculate the value in a given
> slot automatically if not yet calculated. (So differently put, I'm
> implemented a kind of list specific caching/memoization with the intent
> that it should be transparent to the client code.)
> 
> The way I've implemented this so far was to simply override
> list.__getitem__(self, key) to check if the value needs to be calculated
> or not and call a calculation method if required, after which the value is
> returned as normal.  On subsequent calls __getitem__ then directly returns
> the value without calculating it again.
> 
> This worked mostly fine, however yesterday I ran into a slightly
> unexpected problem when I found that when the list contents is iterated
> over and values retrieved that way rather than via [], then __getitem__ is
> in fact *not* called on the list to read the item values from the list,
> and consequently I get back the "not yet calculated" entries in the list,
> without the calculation routine being automatically called as is intended.
> 
> Here's a test application that demonstrates the issue:
> 
> class NotYetCalculated:
> pass
> 
> class CalcList(list):
> def __init__(self, calcitem):
> super(CalcList, self).__init__()
> self.calcitem = calcitem
> 
> def __getitem__(self, key):
> """Override __getitem__ to call self.calcitem() if needed"""
> print "CalcList.__getitem__(): Enter"
> value = super(CalcList, self).__getitem__(key)
> if value is NotYetCalculated:
> print "CalcList.__getitem__(): calculating"
> value = self.calcitem(key)
> self[key] = value
> print "CalcList.__getitem__(): return"
> return value
> 
> def calcitem(key):
> # Demo: return square of index
> return key*key
> 
> 
> def main():
> # Create a list that calculates its contents via a given
> # method/fn onece only
> l = CalcList(calcitem)
> # Extend with  few entries to demonstrate issue:
> l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated,
>   NotYetCalculated])
> 
> print "1) Directly getting values from list works as expected:
> __getitem__ is called:"
> print "Retrieving value [2]:\n", l[2]
> print
> print "Retrieving value [3]:\n", l[3]
> print
> print "Retrieving value [2] again (no calculation this time):\n", l[2]
> print
> 
> print "Retrieving values via an iterator doesn't work as expected:"
> print "(__getitem__ is not called and the code returns "
> print " NotYetCalcualted entries without calling __getitem__. How do I
> fix this?)"
> print "List contents:"
> for x in l: print x
> 
> 
> if __name__ == "__main__":
> main()
> 
> To reiterate:
> 
> What should happen:  In test 2) above all entries should be automatically
> calculated and output should be numbers only.
> 
> What actually happens: In test 2) above the first 2 list entries
> corresponding to list indexes 0 and 1 are output as "NotYetCalculated" and
> calcitem is not called when required.
> 
> What's the best way to fix this problem?  Do I need to maybe override
> another method, perhaps provide my own iterator implementation?  For that
> matter, why doesn't iterating over the list contents fall back to calling
> __getitem__?

Probably an optimisation for the common case where retrieval of list items 
does not involve any calculation.

You can override the __iter__() along the lines of

def __iter__(self):
for i in range(len(self)):
return self[i]

If the items are calculated from the index as in your example there's also 
the option to inherit from collections.Sequence instead of list:


from collections import Sequence

class List(Sequence):
def __init__(self, getitem, size):
self.getitem = getitem
self._cache = [None] * size
def __getitem__(self, index):
assert not isinstance(index, (slice, tuple))
value = self._cache[index]
if value is None:
value = self._cache[index] = self.getitem(index)
return value
def __len__(self):
return len(self._cache)

if __name__ == "__main__":
items = List(lambda x: x*x, 10)
print("items[4] =", items[4])
print("items =", list(items))

But first and foremost I'd seriously reinvestigate your caching scheme. Does 
it really save enough time to make it worthwhile?


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tu

Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Dave Angel

On 02/10/2013 10:10 AM, Dave Angel wrote:

On 02/10/2013 09:32 AM, Walter Prins wrote:

Hello,

I have a program where I'm overriding the retrieval of items from a list.
  As background: The data held by the lists are calculated but then read
potentially many times thereafter, so in order to prevent needless
re-calculating the same value over and over, and to remove
checking/caching
code from the calculation logic code, I therefore created a subclass of
list that will automatically calculate the value in a given slot
automatically if not yet calculated. (So differently put, I'm
implemented a
kind of list specific caching/memoization with the intent that it
should be
transparent to the client code.)

The way I've implemented this so far was to simply override
list.__getitem__(self, key) to check if the value needs to be
calculated or
not and call a calculation method if required, after which the value is
returned as normal.  On subsequent calls __getitem__ then directly
returns
the value without calculating it again.

This worked mostly fine, however yesterday I ran into a slightly
unexpected
problem when I found that when the list contents is iterated over and
values retrieved that way rather than via [], then __getitem__ is in fact
*not* called on the list to read the item values from the list, and
consequently I get back the "not yet calculated" entries in the list,
without the calculation routine being automatically called as is
intended.

Here's a test application that demonstrates the issue:

class NotYetCalculated:
 pass

class CalcList(list):
 def __init__(self, calcitem):
 super(CalcList, self).__init__()
 self.calcitem = calcitem

 def __getitem__(self, key):
 """Override __getitem__ to call self.calcitem() if needed"""
 print "CalcList.__getitem__(): Enter"
 value = super(CalcList, self).__getitem__(key)
 if value is NotYetCalculated:
 print "CalcList.__getitem__(): calculating"
 value = self.calcitem(key)
 self[key] = value
 print "CalcList.__getitem__(): return"
 return value

def calcitem(key):
 # Demo: return square of index
 return key*key


def main():
 # Create a list that calculates its contents via a given
 # method/fn onece only
 l = CalcList(calcitem)
 # Extend with  few entries to demonstrate issue:
 l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated,
   NotYetCalculated])

 print "1) Directly getting values from list works as expected:
__getitem__ is called:"
 print "Retrieving value [2]:\n", l[2]
 print
 print "Retrieving value [3]:\n", l[3]
 print
 print "Retrieving value [2] again (no calculation this time):\n",
l[2]
 print

 print "Retrieving values via an iterator doesn't work as expected:"
 print "(__getitem__ is not called and the code returns "
 print " NotYetCalcualted entries without calling __getitem__. How
do I
fix this?)"
 print "List contents:"
 for x in l: print x


if __name__ == "__main__":
 main()

To reiterate:

What should happen:  In test 2) above all entries should be automatically
calculated and output should be numbers only.

What actually happens: In test 2) above the first 2 list entries
corresponding to list indexes 0 and 1 are output as "NotYetCalculated"
and
calcitem is not called when required.

What's the best way to fix this problem?  Do I need to maybe override
another method, perhaps provide my own iterator implementation?  For that
matter, why doesn't iterating over the list contents fall back to calling
__getitem__?



Implement your own __iter__() special method.

And consider whether you might need __setitem__(), __len__(),
__setslice__(), __getslice__() and others.

Maybe you'd be better off not inheriting from list at all, and just
having an attribute that's a list.  It doesn't sound like you're
defining a very big subset of list, and overriding the methods you
*don't* want seems to be more work than just implementing the ones you do.

A separate question:  is this likely to be a sparse list?  If it's very
sparse, perhaps you'd consider using a dict, rather than a list attribute.





BTW, the answer to why iterating over the list contents doesn't call 
__getitem__, the answer is because list does define __iter__, presumably 
to do it more efficiently.


And there is your clue that perhaps you don't want to inherit from list. 
 You don't want its more-efficient version, so all you have to do is 
not to implement an __iter__ and it should just work.



--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Peter Otten
Peter Otten wrote:

> def __iter__(self):
> for i in range(len(self)):
> return self[i]

That should of course be 'yield', not 'return' 


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread Jim Byrnes

On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote:

- Original Message -


From: Jim Byrnes  To: tutor@python.org Cc:
Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip
for Ubuntu 12.04

How important is it to have the latest pip installed?

Initially I want to use it to install the latest pymongo driver for
mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1.
I see on http://www.pip-installer.org/en/latest/ the version is
1.2.1.

It certainly would be easier to install from the repositories but
will that version work to install the latest python packages?

Thanks,  Jim


You could just try it? And downloading it and then doing sudo tar
-xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is
it?


I usually install from the repositories or maybe a ppa so I don't 
believe I have ever done an install from a tar.  If necessary I will 
familiarize myself with the command you gave (yes I saw your followup 
changing -xvr to -xvf) and install that way.


However, I still wonder if using the outdated pip from the repository 
will allow me to install the latest python packages?  Will trying to use 
an outdated pip cause me problems?



But you're right, I also nnoticed that the Canonical repositories are
a little outdated sometimes. Would be nice if it's possible to add
pypi.org, so updating would be easier.

Albert-Jan



Thanks,  Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] AUTO: David J Pearson Is Attending An IBM Redbook residency (returning 19/02/2013)

2013-02-10 Thread David J Pearson

I am out of the office until 19/02/2013.

I am attending an IBM Redbook residency in Raleigh, NC, USA ... and have
limited access to my mail.

My response to your email will be delayed during this time.

Thanks

David J Pearson MBCS CITP CEng MIET
Technical Staff Member
Solution Architect [Mobile, SmartCloud & OfficeProductivity]
IBM Software Services for Collaboration CoE
IBM Collaboration Software,  IBM United Kingdom Ltd

Mailto:david_j_pear...@uk.ibm.com
Twitter: @DJPearson1




Note: This is an automated response to your message  "Tutor Digest, Vol
108, Issue 32" sent on 10/02/2013 11:00:02.

This is the only notification you will receive while this person is away.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread Timo

Op 10-02-13 17:01, Jim Byrnes schreef:

On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote:

- Original Message -


From: Jim Byrnes  To: tutor@python.org Cc:
Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip
for Ubuntu 12.04

How important is it to have the latest pip installed?

Initially I want to use it to install the latest pymongo driver for
mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1.
I see on http://www.pip-installer.org/en/latest/ the version is
1.2.1.

It certainly would be easier to install from the repositories but
will that version work to install the latest python packages?

Thanks,  Jim


You could just try it? And downloading it and then doing sudo tar
-xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is
it?


I usually install from the repositories or maybe a ppa so I don't 
believe I have ever done an install from a tar.  If necessary I will 
familiarize myself with the command you gave (yes I saw your followup 
changing -xvr to -xvf) and install that way.


However, I still wonder if using the outdated pip from the repository 
will allow me to install the latest python packages? Will trying to 
use an outdated pip cause me problems?
I doubt it will. Have a look at the pip changelog to see what has been 
changed.


Timo





But you're right, I also nnoticed that the Canonical repositories are
a little outdated sometimes. Would be nice if it's possible to add
pypi.org, so updating would be easier.

Albert-Jan



Thanks,  Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread Joel Goldstick
On Sun, Feb 10, 2013 at 1:53 PM, Timo  wrote:

> Op 10-02-13 17:01, Jim Byrnes schreef:
>
>  On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote:
>>
>>> - Original Message -
>>>
>>>  From: Jim Byrnes  To: tutor@python.org Cc:
 Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip
 for Ubuntu 12.04

 How important is it to have the latest pip installed?

 Initially I want to use it to install the latest pymongo driver for
 mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1.
 I see on 
 http://www.pip-installer.org/**en/latest/the
  version is
 1.2.1.

 It certainly would be easier to install from the repositories but
 will that version work to install the latest python packages?

 Thanks,  Jim

>>>
>>> You could just try it? And downloading it and then doing sudo tar
>>> -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is
>>> it?
>>>
>>
>> I usually install from the repositories or maybe a ppa so I don't believe
>> I have ever done an install from a tar.  If necessary I will familiarize
>> myself with the command you gave (yes I saw your followup changing -xvr to
>> -xvf) and install that way.
>>
>> However, I still wonder if using the outdated pip from the repository
>> will allow me to install the latest python packages? Will trying to use an
>> outdated pip cause me problems?
>>
> I doubt it will. Have a look at the pip changelog to see what has been
> changed.
>
> Timo
>
>
>
>
>>  But you're right, I also nnoticed that the Canonical repositories are
>>> a little outdated sometimes. Would be nice if it's possible to add
>>> pypi.org, so updating would be easier.
>>>
>>> Albert-Jan
>>>
>>
>>
>> Thanks,  Jim
>>
>> __**_
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor
>>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



You can upgrade pip with pip i believe:

jcg@jcg-desktop:~/code/python$ pip install pip
Requirement already satisfied (use --upgrade to upgrade): pip in
/usr/lib/pymodules/python2.7
Cleaning up...
jcg@jcg-desktop:~/code/python$


jcg@jcg-desktop:~/code/python$ pip install --upgrade pip


Be sure to sudo before if you don't have permissions.

-- 
Joel Goldstick
http://joelgoldstick.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Additional help

2013-02-10 Thread Ghadir Ghasemi
Hi guys, I wondered if you knew what I could add to this code so that when the 
user enters 1 from the menu and then doesn't enter a valid binary number the 
program should ask them over and over again until valid binary number is 
entered.
here is the code:

def show_menu():
 print("===")
 print("1-binary to denary")
 print("2-denary to binary")
 print("3-exit")
 print("===")


while True:
show_menu()

choice = input("please enter an option: ")

if choice == '1':
binary = input("Please enter a binary number: ")
denary = 0
place_value = 1

for i in binary [::-1]:
denary += place_value * int(i)
place_value *= 2

print("The result is",denary)


   


elif choice == '2':
denary2 = int(input("Please enter a denary number: "))
remainder = ''
while denary2 > 0:
remainder = str(denary2 % 2) + remainder
denary2 >>= 1
print("The result is",remainder)

   
 

elif choice == '3':
 break


elif choice not in '1' or '2' or '3':
print("Invalid input-try again!")


Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Additional help

2013-02-10 Thread Brian van den Broek
On 10 February 2013 15:29, Ghadir Ghasemi  wrote:
> Hi guys, I wondered if you knew what I could add to this code so that when 
> the user enters 1 from the menu and then doesn't enter a valid binary number 
> the program should ask them over and over again until valid binary number is 
> entered.
> here is the code:



> while True:
> show_menu()
>
> choice = input("please enter an option: ")
>
> if choice == '1':
> binary = input("Please enter a binary number: ")
> denary = 0
> place_value = 1
>
> for i in binary [::-1]:
> denary += place_value * int(i)
> place_value *= 2
>
> print("The result is",denary)



> elif choice == '3':
>  break


Hi Ghadir,

"over and over again until" suggests a while loop.

So, you need something like the pseudo-code:

while True:
binary = input("Please enter a binary number: ")
if isgood(binary):
pass  # do stuff then break
else:
pass #remind user of constraints before they are prompted again

(This assumes you've an isgood function that will return a boolean as
the user input is acceptable. That's not necessarily the best way, but
it makes for easy pseduo-code and doesn't do the work for you ;-)

Last, a better subject line is a good idea. Pretty much every post
asking for help from someone who's posted before could have your
subject line.

Best,

Brian vdB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Oscar Benjamin
On 10 February 2013 14:32, Walter Prins  wrote:
[snip
>
> This worked mostly fine, however yesterday I ran into a slightly unexpected
> problem when I found that when the list contents is iterated over and values
> retrieved that way rather than via [], then __getitem__ is in fact *not*
> called on the list to read the item values from the list, and consequently I
> get back the "not yet calculated" entries in the list, without the
> calculation routine being automatically called as is intended.
>
> Here's a test application that demonstrates the issue:
>
> class NotYetCalculated:
> pass
>
> class CalcList(list):
> def __init__(self, calcitem):
> super(CalcList, self).__init__()
> self.calcitem = calcitem
>
> def __getitem__(self, key):
> """Override __getitem__ to call self.calcitem() if needed"""
> print "CalcList.__getitem__(): Enter"
> value = super(CalcList, self).__getitem__(key)
> if value is NotYetCalculated:
> print "CalcList.__getitem__(): calculating"
> value = self.calcitem(key)
> self[key] = value
> print "CalcList.__getitem__(): return"
> return value
>
> def calcitem(key):
> # Demo: return square of index
> return key*key
>
> What's the best way to fix this problem?  Do I need to maybe override
> another method, perhaps provide my own iterator implementation? For that
> matter, why doesn't iterating over the list contents fall back to calling
> __getitem__?

It would use __getitem__ if __iter__ wasn't defined. e.g.:

>>> class A(object):
...   def __getitem__(self, index):
... if index > 4:
...   raise IndexError
... return index ** 2
...
>>> a = A()
>>> for x in a:
...   print(x)
...
0
1
4
9
16

The problem is that by subclassing list you inherit its __iter__
method. A for loop begins by calling iter()  on the iterable. The iter
function is roughly like:

def iterseq(seq):
  count = 0
  while True:
try:
   yield seq[count]
except IndexError:
  return
count += 1

def iter(iterable):
  if hasattr(iterable, '__iter__'):
 return iterable.__iter__()
  elif hasattr(iterable, '__getitem__'):
return iterseq(iterable)
  else:
raise TypeError


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread James Reynolds
The bigger issue with mongo is the apt versions are old. Be sure to follow
the instructions on mongos site.

If you pip install pymongo with a ubunuto or mint build your gtg
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] binary - denary converter (was Additional help)

2013-02-10 Thread bob gailer

I am changing the subject line to one that is more explicit.

On 2/10/2013 3:29 PM, Ghadir Ghasemi wrote:

 elif choice not in '1' or '2' or '3':
 print("Invalid input-try again!")

This works, but not for the reasons you had in mind.

For experiment, try:

>>> '1' or '2' or '3'
'1'

>>> '3' or'2' or '1'
'3'

>>> '1' not in '1' or '2' or '3'
'2'

It is easy to stare at this and say "huh"? or "that makes no sense". 
Instead read up on "in", "or" and "operator precedence" until you do 
understand it.


From the Language Reference:

5:9 The operators in and not in test for collection membership. x in s 
evaluates to true if x is a member of the collection s


5:10 The expression x or y first evaluates x; if x is true, its value is 
returned; otherwise, y is evaluated and the resulting value is returned.


5:15 for operator precedence

Also realize that all you need at the end is:

else:
print("Invalid input-try again!")

For checking an item against several possibilities:

elif choice not in ('1', '2', '3'):

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code to open a website

2013-02-10 Thread Steven D'Aprano

On 10/02/13 20:25, ALAN GAULD wrote:




Maybe the OP meant to say 'quit()' ? That does not require an import.



Ooh! another option I didn't know about!
So many ways to get rid of Python and here's me been importing sys
or raising SystemExit all these years... :-)



exit() and quit() (as added by the site.py module) are for interactive use.
They're mostly there for the benefit of newbies. Experienced developers (at
least in the Unix/Linux world) usually know to exit interactive terminal
apps with Ctrl-D. I believe you use Ctrl-Z  under Windows.

For programmatic use in scripts, use sys.exit(), since the site module is
not guaranteed to run.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread eryksun
On Sun, Feb 10, 2013 at 1:53 PM, Timo  wrote:
>> However, I still wonder if using the outdated pip from the repository will
>> allow me to install the latest python packages? Will trying to use an
>> outdated pip cause me problems?
>
> I doubt it will. Have a look at the pip changelog to see what has been
> changed.

Additionally, deb packages may have platform-specific patches. For
example, here's the changelog and patches for python-pip:

http://packages.debian.org/changelogs/pool/main/p/python-pip/current/changelog

http://anonscm.debian.org/viewvc/python-modules/packages/python-pip/trunk/debian/patches
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to log process handles and GDI objects in python

2013-02-10 Thread Pai, Yogesh M
Hi Alan,

Here are the additional details:
Python version: 2.7.3
OS version: Windows 7 -64 bit

I have an application that has a automation layer built in python. During every 
subsequent runs, I want to log the process threads and GDI objects ( the one 
you see in the Windows task manager) in my python code- The idea is to use this 
data to generate a plot to check if the application leaks memory in a long run. 
Although I can use a third-party app to log this, is it possible to import 
certain library in python and log these windows attributes during the execution?

Thanks,
Yogesh


-Original Message-
From: Tutor [mailto:tutor-bounces+yogesh.m.pai=tektronix@python.org] On 
Behalf Of Alan Gauld
Sent: Friday, February 08, 2013 5:02 PM
To: tutor@python.org
Subject: Re: [Tutor] How to log process handles and GDI objects in python

On 08/02/13 09:06, Pai, Yogesh M wrote:

> I would like to know how can I log system process handles and GDI 
> objects for debugging memory leak issues in python.

This isn't really a question about learning Python so probably would be better 
on the main Python mailing list.

However it will help if you specify things like the OS, the Python version. 
Also be clear about what exactly you mean by process handles and GDI objects. 
I'm guessing you are talking about Windows but I can't be sure.

> I would like to log these inside a loop (stress test) to check if my 
> application leaks handles and plot them later for my usage.

I imagine that means you are creating a test lop that creates and releases 
these handles? How do you get a handle? can you store it as a variable? can you 
print it? can you create a string and print that?

Sorry I can't be of more help but that's a fairly open question about a very 
specific problem.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] associating two objects without ORM and processing a text file

2013-02-10 Thread neubyr
I have a text file with each line in following format:

Book Name, Author Name, Genre, Publication Date

I would like to perform following queries on this file:
 * Get all books written by an author
 * Remove all books of an author
 * Get information about a book (pretty print matching line!)
 * Get books of particular genre

Also, I would like to add and delete entries in this file. I am not
planning to use any database for this purpose and would like to get better
grasp on file parsing and classes/OOP. I need some help in creating classes
and following are my initial thoughts:

# Create a class for Book object
class Book:
  atributes: name, author_name, genre, publication-date

# Create
Author:
 attribute(s): name

# Create class for reading and writing to the file
class Booksfile:
  methods: ??


* How do I associate/relate Book and Author classes so that it will help me
in getting information like 'get list of books written by an author'? Data
attribute?
* Should I create a new Booksfile object for reading, writing and deleting
entries in the file OR add corresponding methods to the book object itself?

I am not planning to use SQLite or any database and would like to use text
file only. Appreciate any help on designing such application.



thanks,
N
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-10 Thread Mitya Sirenef

On 02/11/2013 12:14 AM, neubyr wrote:



> I have a text file with each line in following format:
>
> Book Name, Author Name, Genre, Publication Date
>
> I would like to perform following queries on this file:
> * Get all books written by an author
> * Remove all books of an author
> * Get information about a book (pretty print matching line!)
> * Get books of particular genre
>
> Also, I would like to add and delete entries in this file. I am not 
planning to use any database for this purpose and would like to get 
better grasp on file parsing and classes/OOP. I need some help in 
creating classes and following are my initial thoughts:

>
> # Create a class for Book object
> class Book:
> atributes: name, author_name, genre, publication-date
>
> # Create
> Author:
> attribute(s): name
>
> # Create class for reading and writing to the file
> class Booksfile:
> methods: ??
>
>
> * How do I associate/relate Book and Author classes so that it will 
help me in getting information like 'get list of books written by an 
author'? Data attribute?
> * Should I create a new Booksfile object for reading, writing and 
deleting entries in the file OR add corresponding methods to the book 
object itself?

>
> I am not planning to use SQLite or any database and would like to use 
text file only. Appreciate any help on designing such application.

>
>


Book.author should be author instance,

Author
def books(self):
return [b for b in books if b.author==self]

Get lists by genre etc in a similar way.

To do file processing, look at the standard csv module:

http://docs.python.org/2/library/csv.html


-m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The doer alone learneth.  Friedrich Nietzsche

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-10 Thread Dave Angel

On 02/11/2013 12:14 AM, neubyr wrote:

I have a text file with each line in following format:

Book Name, Author Name, Genre, Publication Date

I would like to perform following queries on this file:
  * Get all books written by an author
  * Remove all books of an author
  * Get information about a book (pretty print matching line!)
  * Get books of particular genre

Also, I would like to add and delete entries in this file. I am not
planning to use any database for this purpose and would like to get better
grasp on file parsing and classes/OOP.


I take it from this that this is a class assignment, and that neither 
speed nor enormous data capacity nor concurrent operation is a 
requirement.  But your professor may have other requirements that you 
haven't told us about.


I need some help in creating classes

and following are my initial thoughts:

# Create a class for Book object
class Book:
   atributes: name, author_name, genre, publication-date

# Create
Author:
  attribute(s): name


Is this in order to save space, since each Book instance can then have a 
reference to an Author object, rather than a reference to a string 
containing the Author's name.


If you deem this class useful, then don't you also want one for Genre ?




# Create class for reading and writing to the file
class Booksfile:
   methods: ??


Why ?  Are you transliterating this from Java ?




* How do I associate/relate Book and Author classes so that it will help me
in getting information like 'get list of books written by an author'? Data
attribute?


If performance doesn't matter, then create one list of Book instances, 
and search it for whichever characteristics you like.




* Should I create a new Booksfile object for reading, writing and deleting
entries in the file OR add corresponding methods to the book object itself?


Neither, a pair of regular functions will do fine.  One that loads when 
you start the program, and another that saves the file when you exit. 
If you really expect to update the file incrementally, deleting entries 
in it, then think hard about your decision to roll your own database.  A 
text file isn't random access.




I am not planning to use SQLite or any database and would like to use text
file only. Appreciate any help on designing such application.




The real question is where you might proceed after meeting these first 
requirements.  For example, if you expect the list to grow to a few 
hundred million entries, then you'll need to be very careful about 
layout.  And starting and exiting the program would be very slow, since 
you can do nothing till all the data has been loaded in and converted to 
objects.


Or perhaps you'll want to have another file with additional author data, 
associated with the first by carefully spelling the author's name the 
same in all cases.  In that case, having a separate Author class makes 
great sense.  So if you expect to grow in that direction, then you 
should create the class now, even though it has only one attribute.



--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor