Re: [Tutor] PYTHON NEWBIE HELP!

2012-10-14 Thread bob gailer

On 10/14/2012 9:21 PM, Salinas, Erwin d wrote:

HELP! Hi I'm a newbie in Python,

welcome

A few pointers regarding use of this email list:
- we are a few volunteers who try to help as we can
- please put your responses following the relevant text rather than at 
the top

- please reply-all so a copy goes to the list.
- please submit plain text rather than formatting or colors.
- tell us what os and python version you are using
- remove extraneous text
- provide a meaningful subject
- regarding homework

I'm having trouble organizing the FILE into the OUTPUT BELOW. I put 
the file into read, then I put it on a list, and my plan is to put the 
name and the corresponding grades into a dictionary, using the 
elements on the list, but when I print the dictionary, it's not giving 
me the result I wanted. MY CODE SO FAR IS SHOWN BELOW THE 
OUTPUT. For more details of the assignment, go to this 
link 
http://ranger.uta.edu/~kamangar/Courses/CSE_1310_FA12/Homework5(DueDate.Oct.16,2012).html#Topic18. 
Thank you so much.


FILE
HM3, 80 , HM2 ,90 , ID, 1000123456,HM4,92,Last_name,Rubble
ID, 1000100200,Last_name,Bunny,HM2,92,HM5,70,HM1,98,
ID, 1000123300,HM1,86, HM3,100,Last_name,Duck
HM4,96,Last_name,Chipmunk,HM1,86,ID,1000456456
Last_name,Simpson,HM3,70, HM1, 90 ,ID, 1000321321,Test1,90
HM1,87,Last_name,Duck,HM2, 100 ,HM4,94,ID, 1000123300
HM3,95,HM2,88,Last_name, Chipmunk ,HM1,86 , ID,1000999888
HM1, 92 ,Last_name,Simpson,ID, 1000321321,HM2,90
OUTPUT
Name | ID | HM1 | HM2 | HM3 | HM4 | Avg. |
___
Bunny | 1000100200 | 98 | 92 | 0 | 0 | 47.50 |
Chipmunk | 1000456456 | 86 | 0 | 0 | 96 | 45.50 |
Chipmunk | 1000999888 | 86 | 88 | 95 | 0 | 67.25 |
Duck | 1000123300 | 87 | 100 | 100 | 94 | 95.25 |
Rubble | 1000123456 | 0 | 90 | 80 | 92 | 65.50 |
Simpson | 1000321321 | 92 | 90 | 70 | 0 | 63.00 |
THIS IS MY CODE SO FAR
filename = open("student_grades_hm_5.txt")
infile = filename.read()
mix_list = infile.split()
print "Name | ID | HM1 | HM2 | HM3 | HM4 | Avg. |"
print "__"

Student_one = 
{"Name":mix_list[9],"ID":mix_list[5],"HM1":0,"HM2":mix_list[3],

"HM3":mix_list[1],"HM4":mix_list[7]}
print Student_one
You seem to be missing a number of basic concepts. It is hard to tell 
how much help is allowed by your instructor.


Did you successfully complete the preceding assignments? Since the 
"purpose" is to use lists, file i/o, loops and formatted print I assume 
you already know how to use split and dictionaries. True?


What elements of the "purpose" are giving you trouble? Since I see no 
loop or formatted print I assume these are giving you grief.


I suggest you start with a bit of pseudo-code to express the structure 
of the program.


Your program should not refer to the keys explicitly as you have done in 
the line starting with Student_one = nor should it refer to the list 
elements by number (that implies knowledge of the structure of a 
particular line of the file.


I also suggest you examine the results of each step by entering the 
lines at the interactive prompt, then displaying the value of the newly 
created variable. You will be surprised by what you see!


My personal guess is that you have not done the prior exercises or else 
the instructor is expecting miracles.


Do what you can to improve things then return with more questions.

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


[Tutor] PYTHON NEWBIE HELP!

2012-10-14 Thread Salinas, Erwin d
HELP! Hi I'm a newbie in Python, I'm having trouble organizing the FILE into 
the OUTPUT BELOW. I put the file into read, then I put it on a list, and my 
plan is to put the name and the corresponding grades into a dictionary, using 
the elements on the list, but when I print the dictionary, it's not giving me 
the result I wanted. MY CODE SO FAR IS SHOWN BELOW THE OUTPUT. For more details 
of the assignment, go to this link 
http://ranger.uta.edu/~kamangar/Courses/CSE_1310_FA12/Homework5(DueDate.Oct.16,2012).html#Topic18
 Thank you so much.

FILE

HM3, 80 , HM2 ,90 , ID, 1000123456,HM4,92,Last_name,Rubble
ID, 1000100200,Last_name,Bunny,HM2,92,HM5,70,HM1,98,
ID, 1000123300,HM1,86, HM3,100,Last_name,Duck
HM4,96,Last_name,Chipmunk,HM1,86,ID,1000456456
Last_name,Simpson,HM3,70, HM1, 90 ,ID, 1000321321,Test1,90
HM1,87,Last_name,Duck,HM2, 100 ,HM4,94,ID, 1000123300
HM3,95,HM2,88,Last_name, Chipmunk ,HM1,86 , ID,1000999888
HM1, 92 ,Last_name,Simpson,ID, 1000321321,HM2,90

OUTPUT

Name | ID | HM1 | HM2 | HM3 | HM4 | Avg. |
___
Bunny | 1000100200 | 98 | 92 | 0 | 0 | 47.50 |
Chipmunk | 1000456456 | 86 | 0 | 0 | 96 | 45.50 |
Chipmunk | 1000999888 | 86 | 88 | 95 | 0 | 67.25 |
Duck | 1000123300 | 87 | 100 | 100 | 94 | 95.25 |
Rubble | 1000123456 | 0 | 90 | 80 | 92 | 65.50 |
Simpson | 1000321321 | 92 | 90 | 70 | 0 | 63.00 |

THIS IS MY CODE SO FAR
filename = open("student_grades_hm_5.txt")
infile = filename.read()
mix_list = infile.split()
print "Name | ID | HM1 | HM2 | HM3 | HM4 | Avg. |"
print "__"

Student_one = {"Name":mix_list[9],"ID":mix_list[5],"HM1":0,"HM2":mix_list[3],
"HM3":mix_list[1],"HM4":mix_list[7]}
print Student_one

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


Re: [Tutor] extract uri from beautiful soup string

2012-10-14 Thread Sander Sweers
Sander Sweers schreef op ma 15-10-2012 om 02:35 [+0200]:
> > On Mon, Oct 15, 2012 at 12:12 AM, Sander Sweers  
> > wrote:
> > > Norman Khine schreef op zo 14-10-2012 om 23:10 [+0100]:
> > Norman Khine schreef op ma 15-10-2012 om 00:17 [+0100]:
> > i tried this: http://pastie.org/5059153

Btw, if I understand what you are trying to do then you can do this much
more simple. I noticed that all the a tags with onclick have an href
attribute of '#'. To get all of these do something like:

soup.findAll('a', {'href':'#'})

Then use the attrmap eg attrMap['onclick'].split('\'')[1].

Put together that may look like the below.

for i in soup.findAll('a', {'href':'#'}):
if 'toolbar=0' in i.attrMap['onclick']:
print i.attrMap['onclick'].split('\'')[1]

Greets
Sander

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


Re: [Tutor] extract uri from beautiful soup string

2012-10-14 Thread Sander Sweers
Please don't top post.

> On Mon, Oct 15, 2012 at 12:12 AM, Sander Sweers  
> wrote:
> > Norman Khine schreef op zo 14-10-2012 om 23:10 [+0100]:
> >> One thing is that when I try to write the assoc_data into a CSV file,
> >> it groaks on
> >>
> >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xc7' in 
> >> position 0:
> >
> > It looks like python is doing an implicit decode/encode on one of your
> > strings. It may be caused in codecs.open. You will have to hunt down
> > where this implicit decode/encode is done, see
> > http://nedbatchelder.com/text/unipain.html for more info.
> >
> >> here some sample data from the print:
> >
> > These strings don't cause any errors for me and fit in ascii. Add some
> > print statements before your write the string to find which string is
> > causing you grief.

> Norman Khine schreef op ma 15-10-2012 om 00:17 [+0100]:
> i tried this: http://pastie.org/5059153
> 
> but now i get a
> 
> Traceback (most recent call last):
>   File "nimes_extract.py", line 75, in 
> c.writerow([item.encode("UTF-8")])
> TypeError: 'NoneType' object is not callable


You have several str() likely to work around real bugs but now they are
biting back. In your code I don;t see any use for it..

Example how str() is hiding bugs for you.

>>> str(None).encode('UTF-8')
'None'
>>> None.encode('UTF-8')

Traceback (most recent call last):
  File "", line 1, in 
None.encode('UTF-8')
AttributeError: 'NoneType' object has no attribute 'encode'

Get rid of all the str() and make sure you have only unicode strings
*everywhere* and start fixing all the bugs that got hidden because of
it.

Do make sure to watch the video as it explains the pain you are having
with unicode.

Greets
Sander

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


Re: [Tutor] extract uri from beautiful soup string

2012-10-14 Thread Norman Khine
i tried this: http://pastie.org/5059153

but now i get a

Traceback (most recent call last):
  File "nimes_extract.py", line 75, in 
c.writerow([item.encode("UTF-8")])
TypeError: 'NoneType' object is not callable



On Mon, Oct 15, 2012 at 12:12 AM, Sander Sweers  wrote:
> Norman Khine schreef op zo 14-10-2012 om 23:10 [+0100]:
>> One thing is that when I try to write the assoc_data into a CSV file,
>> it groaks on
>>
>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xc7' in position 
>> 0:
>
> It looks like python is doing an implicit decode/encode on one of your
> strings. It may be caused in codecs.open. You will have to hunt down
> where this implicit decode/encode is done, see
> http://nedbatchelder.com/text/unipain.html for more info.
>
>> here some sample data from the print:
>
> These strings don't cause any errors for me and fit in ascii. Add some
> print statements before your write the string to find which string is
> causing you grief.
>
> Greets
> Sander
>
>> [u'Social', u'Action9', u'ash-ni...@aol.com',
>> mise en place d'ateliers, d'animations hebdomadaires et ponctuelles
>> afin de lutter contre toutes les formes d'exclusion., Mme Liberté
>> Bisbal, 04.66.27.24.84, 3002 Rte de Courbessac, 04.66.27.24.84, 3
>> NIMES, Madame BISBAL Liberté, 04.66.27.24.84,  ]
>> [u'Social', u'Adapei30', u'cont...@adapi30.org', deux lieux d'echanges
>> et d'infos des publics concernes par le probleme du handicap mental
>> representation aupres de divers organismes d'etat et du departement.,
>> 17b, RUE CHILDEBERT, 04.66.21.21.49, 30900 NIMES, Monsieur FLUTTE
>> Bernard,  ]
>> [u'Sport', u'Aero-club de nimes-courbessac', u'aeroclubni...@free.fr',
>> promouvoir , de faciliter et d'organiser la pratique de l'aviation, 65
>> Aerodrome de Nimes Courbessac, 04.66.28.16.00, 3 NIMES, Monsieur
>> VASSAL PATRICK,  ]
>>
>> How do I change to code to take note of the latin-1 encoding?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



-- 
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] extract uri from beautiful soup string

2012-10-14 Thread Sander Sweers
Norman Khine schreef op zo 14-10-2012 om 23:10 [+0100]:
> One thing is that when I try to write the assoc_data into a CSV file,
> it groaks on
> 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xc7' in position 
> 0:

It looks like python is doing an implicit decode/encode on one of your
strings. It may be caused in codecs.open. You will have to hunt down
where this implicit decode/encode is done, see
http://nedbatchelder.com/text/unipain.html for more info.

> here some sample data from the print:

These strings don't cause any errors for me and fit in ascii. Add some
print statements before your write the string to find which string is
causing you grief.

Greets
Sander

> [u'Social', u'Action9', u'ash-ni...@aol.com',
> mise en place d'ateliers, d'animations hebdomadaires et ponctuelles
> afin de lutter contre toutes les formes d'exclusion., Mme Liberté
> Bisbal, 04.66.27.24.84, 3002 Rte de Courbessac, 04.66.27.24.84, 3
> NIMES, Madame BISBAL Liberté, 04.66.27.24.84,  ]
> [u'Social', u'Adapei30', u'cont...@adapi30.org', deux lieux d'echanges
> et d'infos des publics concernes par le probleme du handicap mental
> representation aupres de divers organismes d'etat et du departement.,
> 17b, RUE CHILDEBERT, 04.66.21.21.49, 30900 NIMES, Monsieur FLUTTE
> Bernard,  ]
> [u'Sport', u'Aero-club de nimes-courbessac', u'aeroclubni...@free.fr',
> promouvoir , de faciliter et d'organiser la pratique de l'aviation, 65
> Aerodrome de Nimes Courbessac, 04.66.28.16.00, 3 NIMES, Monsieur
> VASSAL PATRICK,  ]
> 
> How do I change to code to take note of the latin-1 encoding?

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


Re: [Tutor] extract uri from beautiful soup string

2012-10-14 Thread Norman Khine
Hi thanks, i changed the code to http://pastie.org/5059153

One thing is that when I try to write the assoc_data into a CSV file,
it groaks on

UnicodeEncodeError: 'ascii' codec can't encode character u'\xc7' in position 0:

here some sample data from the print:

[u'Social', u'Action9', u'ash-ni...@aol.com',
mise en place d'ateliers, d'animations hebdomadaires et ponctuelles
afin de lutter contre toutes les formes d'exclusion., Mme Liberté
Bisbal, 04.66.27.24.84, 3002 Rte de Courbessac, 04.66.27.24.84, 3
NIMES, Madame BISBAL Liberté, 04.66.27.24.84,  ]
[u'Social', u'Adapei30', u'cont...@adapi30.org', deux lieux d'echanges
et d'infos des publics concernes par le probleme du handicap mental
representation aupres de divers organismes d'etat et du departement.,
17b, RUE CHILDEBERT, 04.66.21.21.49, 30900 NIMES, Monsieur FLUTTE
Bernard,  ]
[u'Sport', u'Aero-club de nimes-courbessac', u'aeroclubni...@free.fr',
promouvoir , de faciliter et d'organiser la pratique de l'aviation, 65
Aerodrome de Nimes Courbessac, 04.66.28.16.00, 3 NIMES, Monsieur
VASSAL PATRICK,  ]

How do I change to code to take note of the latin-1 encoding?



On Sun, Oct 14, 2012 at 8:42 PM, Steven D'Aprano  wrote:
> On 15/10/12 05:05, Norman Khine wrote:
>
>> for page_no in pages:
>
> [...]
>
>> try:
>> urllib2.urlopen(req)
>> except urllib2.URLError, e:
>> pass
>> else:
>> # do something with the page
>> doc = urllib2.urlopen(req)
>
>
> This is a bug. Just because urlopen(req) succeeded a moment ago, doesn't
> mean
> that it will necessarily succeed now.
>
> This is an example of the general class of bug known as a "race condition":
>
> http://en.wikipedia.org/wiki/Race_condition
>
>
> Better to write this as:
>
>
> try:
> doc = urllib2.urlopen(req)
>
> except urllib2.URLError, e:
> pass
> else:
> # do something with the page
> [rest of code goes here]
>
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



-- 
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] instance method call issue

2012-10-14 Thread bob gailer

On 10/14/2012 8:34 AM, Osemeka Osuagwu wrote:

 except:
 print 'Cannot display Grid'

In addition to Steve's comment I add my own gripe:

When delivering an error message tell us WHY. I have seen too many 
messages "cannot do xxx" with no information that might help me debug.

"cannot load file xxx"
"Windows cannot load the installer for xxx"

or totally confusing messages
"error 6 trying to report error 6"
"cannot do xxx to file yyy. file exists"

In reality the underlying program knows a lot more about why. Could not 
the developers have presented that information as well?


--
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] extract uri from beautiful soup string

2012-10-14 Thread Steven D'Aprano

On 15/10/12 05:05, Norman Khine wrote:


for page_no in pages:

[...]

try:
urllib2.urlopen(req)
except urllib2.URLError, e:
pass
else:
# do something with the page
doc = urllib2.urlopen(req)


This is a bug. Just because urlopen(req) succeeded a moment ago, doesn't mean
that it will necessarily succeed now.

This is an example of the general class of bug known as a "race condition":

http://en.wikipedia.org/wiki/Race_condition


Better to write this as:


try:
doc = urllib2.urlopen(req)
except urllib2.URLError, e:
pass
else:
# do something with the page
[rest of code goes here]




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


Re: [Tutor] extract uri from beautiful soup string

2012-10-14 Thread Norman Khine
ignore, i got it:

get_url = re.compile(r"""window.open\('(.*)','','toolbar=0,""",
re.DOTALL).findall


...

get_onclick = str(soup('a')[0]['onclick']) # get the 
'onclick' attribute
urls = get_url(get_onclick)
print assoc_name, urls, assoc_theme

returns

Amiral ['http://DOMAIN.TLD/extranet/associations/detail-assos.php?id=3815']
Culture


On Sun, Oct 14, 2012 at 7:05 PM, Norman Khine  wrote:
> hello, i have this code:
>
>
> #!/usr/local/bin/python
> # -*- coding: utf-8 -*-
>
> import re
> import urllib2
> import BeautifulSoup
>
> origin_site = 
> 'http://DOMAIN.TLD/index.php?id=annuaire_assos&theme=0&rech=&num_page='
>
> pages = range(1,3)
>
> for page_no in pages:
> print '== %s' % page_no
> req = ('%s%s' % (origin_site, page_no))
> user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
> headers = { 'User-Agent' : user_agent }
> items = []
> try:
> urllib2.urlopen(req)
> except urllib2.URLError, e:
> pass
> else:
> # do something with the page
> doc = urllib2.urlopen(req)
> soup = BeautifulSoup.BeautifulSoup(doc)
> infoblock = soup.findAll('tr', { "class" : "menu2" })
> for item in infoblock:
> soup = BeautifulSoup.BeautifulSoup(str(item))
> for tag in soup.recursiveChildGenerator():
> if isinstance(tag,BeautifulSoup.Tag) and 
> tag.name in ('td'):
> if tag.string is not None:
> assoc_name = (tag.string)
> if isinstance(tag,BeautifulSoup.Tag) and 
> tag.name in ('u'):
> if tag.string is not None:
> assoc_theme = (tag.string)
>
> get_onclick = soup('a')[0]['onclick'] # get the 
> 'onclick' attribute
> print assoc_name, get_onclick, assoc_theme
>
>
> this returns the following:
>
> Amiral 
> window.open('http://DOMAIN.TLD/extranet/associations/detail-assos.php?id=3815','','toolbar=0,menubar=0,location=0,scrollbars=1,top=80,left=400,width=500,height=400');return
> false Culture
>
> how do i extract from the get_onclick the
> 'http://DOMAIN.TLD/extranet/associations/detail-assos.php?id=3815'
> correctly?
>
> Any advise much appreciated.
>
>
>
> --
> %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
> chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )



-- 
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] extract uri from beautiful soup string

2012-10-14 Thread Norman Khine
hello, i have this code:


#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import re
import urllib2
import BeautifulSoup

origin_site = 
'http://DOMAIN.TLD/index.php?id=annuaire_assos&theme=0&rech=&num_page='

pages = range(1,3)

for page_no in pages:
print '== %s' % page_no
req = ('%s%s' % (origin_site, page_no))
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
items = []
try:
urllib2.urlopen(req)
except urllib2.URLError, e:
pass
else:
# do something with the page
doc = urllib2.urlopen(req)
soup = BeautifulSoup.BeautifulSoup(doc)
infoblock = soup.findAll('tr', { "class" : "menu2" })
for item in infoblock:
soup = BeautifulSoup.BeautifulSoup(str(item))
for tag in soup.recursiveChildGenerator():
if isinstance(tag,BeautifulSoup.Tag) and 
tag.name in ('td'):
if tag.string is not None:
assoc_name = (tag.string)
if isinstance(tag,BeautifulSoup.Tag) and 
tag.name in ('u'):
if tag.string is not None:
assoc_theme = (tag.string)

get_onclick = soup('a')[0]['onclick'] # get the 
'onclick' attribute
print assoc_name, get_onclick, assoc_theme


this returns the following:

Amiral 
window.open('http://DOMAIN.TLD/extranet/associations/detail-assos.php?id=3815','','toolbar=0,menubar=0,location=0,scrollbars=1,top=80,left=400,width=500,height=400');return
false Culture

how do i extract from the get_onclick the
'http://DOMAIN.TLD/extranet/associations/detail-assos.php?id=3815'
correctly?

Any advise much appreciated.



-- 
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] instance method call issue

2012-10-14 Thread Alan Gauld

On 14/10/12 13:34, Osemeka Osuagwu wrote:


I understand instance, static and class methods but I'm still
struggling with when and where they should be used.


You can pretty much ignore static methods, they were almost an
historic 'accident' superseded, in most cases, by class methods. The 
number of cases where a staticmethod is really needed is very low.


class methods you will rarely need but they are used when you want to do 
something to the entire class of objects. i.e. something that affects 
all instances both existing and future. Or they could be used where 
there are no instances (yet). Factory methods, instance selection

methods, modifying shared attributes, instance pooling, are all
examples. To give some kind of heuristic based on my personal usage, I 
use class methods in almost all my bigger projects. Such a project might 
have 20 or 30 (or more) classes. Out of that maybe 2 or 3 will have any 
class methods.


Instance methods are by far the most common. These are the things you 
want to do to a specific instance of the class. Changes to one instance 
have no effect on other instances of the same class.



In the code below, I can't seem to get around calling an instance
method (__reality_check()) from within a class method (update_grid()),


It's not a class method, you want to update a specific instance of a 
grid. update_grids() might be a class method if you wanted to, say,
change the maximum buffer size used to store the grids, or cause all 
grids to display the word 'empty' instead of a blank. Of course to do 
that you would need access to all the instances to update their existing 
values so the constructor would need to store a reference to itself in 
the class somewhere (or maybe in a separate shared database).
The class method would then iterate over all instances calling their 
instance method update_grid(). This is a common(*) class method pattern,

where a plural class method calls the singular instance methods
of all the instances.

(*) I say common, but of course class methods are not common
so its a very relative term!

HTH

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


Re: [Tutor] instance method call issue

2012-10-14 Thread Steven D'Aprano

On 14/10/12 23:34, Osemeka Osuagwu wrote:


In the code below, I can't seem to get around calling an instance
method (__reality_check()) from within a class method (update_grid()),


Of course you can't :)

Since the class method has no access to the instance, it cannot call
instance methods, since it doesn't know which instance to use!

Instead, update_grid needs to be an instance method. Of course it
does! It needs to update a specific grid, right? That will be the
instance.



I'm not even too sure that update_grid() should have been a class
method in the first place.



Probably not. Static and class methods are rarely used, since they have
no access to the instance that owns them.

Class methods are generally used for alternate constructor functions, e.g.
dict.fromkeys. Since it makes no difference whether you call fromkeys
from the class (dict) or from an instance, it is made a classmethod.

Static methods, well, 99 times out of a hundred if you think you want to
use a static method, you're probably better off making it a module level
function.

By my count, there are over 26000 instance methods in the Python standard
library, 202 class methods, and only 84 static methods. So they are rare.
I've been using Python for about 15 years, and I think I could count the
number of times I've used staticmethod on the fingers of one hand.




Please, I need help with this and any other advice on my coding style,
where I could've been more efficient etc.


class Grid:
 '''Grid(rows = 26, columns = 26) ->  Provides a world object
for the cells in Game of Life'''
 from time import sleep
 from os import system
 from sys import platform


Move the imports outside of the class. They should go at the start of
the module.

As written, your class has attributes Grid.sleep, Grid.system, etc. Since
these attributes have nothing to do with Grids, they don't belong in the
Grid class. Move them out.

Classes are not catch-all collections of unrelated methods. That's
what modules are for :)





 #class data:
 __rows, __array, os_type = [''], [], platform


A word of advise: don't waste your time with double underscore "private"
attributes. They're no more private than single underscore (private by
convention only), and the name mangling can cause difficulty when
debugging.

There are good reasons for using double underscores like this, but you
should consider them a bit more advanced.



 @staticmethod
 def display_grid(generation, os_type):
 try:
 (lambda x:Grid.system('cls') if 'win' in
os_type else Grid.system('clear'))(1)



That's wrong! Your display_grid method uses the class (Grid), so it
shouldn't be a static method.

Move the imports to the module level, and display_grid as a regular
function:

def display_grid(generation, array):
clear_screen()
print 'Now in Generation %d' % generation
for line in array:
print line

def clear_screen(platform=sys.platform()):
# The default here is set once, and defaults to your platform.
if 'win' in platform:
command = 'cls'
else:
command = 'clear'
os.system(command)


Or leave display_grid as an instance method:


class Grid:
def display_grid(self, generation):
clear_screen()
print 'Now in Generation %d' % generation
for line in self._array:
print line


Either way, clear_screen has nothing to do with grids, so it should
not be a method of Grid.




 except:
 print 'Cannot display Grid'


Never use a bare except like that. Bare except should *only* be used
at the interactive interpreter, for lazy people who want to avoid
typing. It should never be used non-interactively, it's simply poor
practice.

The problem with bare excepts is that they cover up too much. Your aim
is to write code that works. If it has a bug, you need to *see* the bug
so you can identify it and then fix it. Bare excepts make bugs
invisible.




 @staticmethod
 def extend_grid(thickness = 4, force_extend = False):
 '''extend_grid([thickness][, force_extend]) -->
Extends the edges of the grid by 4 units in
all directions if the boundary of the simulation comes close to the
edge. Extends anyway if force_extend option is True'''


Why is this a static method?

Which grid is this operating on? It should either take a grid as an
argument, or extend_grid should be an instance method that operates
on itself:

# either this top-level function
def extend_grid(grid, thickness=4, force=False):
# do stuff to the grid to extend it
# and then return it
return grid


# or make this a regular instance method
class Grid:
def extend_grid(self, thickness=4, force=False):
# do stuff to self to extend it
# no need to return anything




 @classmethod
 def update_grid(cls, generations, speed):



Why is this a class method?



   

[Tutor] instance method call issue

2012-10-14 Thread Osemeka Osuagwu
Hello people,
Firstly, thank you so much for all the assistance you provide so
selflessly through this medium.
I come from a functional programming background and have only recently
become serious with OOP.
For practice, I tried to implement John Conways 'Game of Life' without
a GUI and ran into some issues.
I understand instance, static and class methods but I'm still
struggling with when and where they should be used.
In the code below, I can't seem to get around calling an instance
method (__reality_check()) from within a class method (update_grid()),
I'm not even too sure that update_grid() should have been a class
method in the first place.
Please, I need help with this and any other advice on my coding style,
where I could've been more efficient etc.


class Grid:
'''Grid(rows = 26, columns = 26) -> Provides a world object
for the cells in Game of Life'''
from time import sleep
from os import system
from sys import platform

#class data:
__rows, __array, os_type = [''], [], platform

@staticmethod
def display_grid(generation, os_type):
try:
(lambda x:Grid.system('cls') if 'win' in
os_type else Grid.system('clear'))(1)
except:
print 'Cannot display Grid'
print 'Now in Generation %d' %(generation)
for line in Grid.__array:
print line
return

@staticmethod
def extend_grid(thickness = 4, force_extend = False):
'''extend_grid([thickness][, force_extend]) -->
Extends the edges of the grid by 4 units in
all directions if the boundary of the simulation comes close to the
edge. Extends anyway if force_extend option is True'''
pass
return

@classmethod
def update_grid(cls, generations, speed):
'''Runs the 'Life' World simulation for the specified
number of generations at the given speed'''
#control = input
#while
for times in range(generations + 1):
cls.extend_grid()
cls.__reality_check(Grid, 'all')
cls.display_grid(times, cls.os_type)
cls.sleep(speed)
return

#--

def __init__(self, rows = 26, col = 26):
'''Create a 'rows' x 'col' grid'''
Grid.__rows *= rows
Grid.__array = [Grid.__rows] * col
print 'A %d x %d cell World has been Created' %(rows, col)

def __reality_check(self, num = 'all'):
'''__reality_check([num]) -->Checks and updates the
state of the cell based on the number of 'alive' neighbors'''

#check if reality check is for single cell or entire array
if num == 'all':
for i in range(len(Grid.__array)):
for j in range(len(Grid.__array[i])):
self.__reality_check((i,j))
return

#Neighbor count check and update for single cell(num = row, col)
elif num == tuple and len(num) == 2:
col, row, neighbor_count = num[1], num[0], 0
for x in range(row-1, row+2):
for y in range(col-1, col+2):
#count only 'alive' neighbors
(includes the subject cell itself)
neighbor_count = lambda x: x+1
if Grid.__array[x][y] == '##' else x
#correct the neighbor count value if subject
cell was counted
neighbor_count = lambda x: x-1 if
Grid.__array[row][col] == '##' else x

#update cell(x,y) state
Grid.__array[row][col] = lambda x:'##' if
neighbor_count == 3 else ''

else:
print 'Wrong argument for reality check'
return

def edit_cell(self, cells, state = '##'):
'''edit_cell(cells[, state]) --> Where cells is a list
of tuples containing coordinates of the cells to edit'''
cells = cells
for eachcell in cells:
Grid.__array[eachcell[0]][eachcell[1]] = state
return

#To be moved to a different .py file after debugging.
world = Grid()
world.edit_cell([(10,10), (10, 11), (10, 12), (11, 10)], '##')
world.update_grid(5, 0.5)



p.s. I'm not yet completely through with coding some aspects like the
extend_grid() method'

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


Re: [Tutor] urllib2.urlopen()

2012-10-14 Thread eryksun
On Sun, Oct 14, 2012 at 5:44 AM, Ray Jones  wrote:
>
> I have often used help() to find my way around imported libraries. I
> didn't realize it would also help with instances. That's good to know.

help(e) shows info for the instance's class, such as methods and data
descriptors (i.e. properties, slots) broken down by inheritance.

Use dir(e) to list all attributes of an instance, or list(vars(e)) if
it has a __dict__.

This is helpful with an instance of HTTPError because the file-like
methods are set as instance data by urllib.addbase. You wouldn't know
about them based on just the help command (but the docs do say it has
a file-like interface).

>>> list(vars(e))
['fp', 'fileno', 'code', 'hdrs', 'read', 'readlines', 'next',
'headers', '__iter__', 'url', 'msg', 'readline']

For example, e.read() is a method of a socket._fileobject:

>>> e.read.__self__


This _fileobject is also at e.fp.fp. It wraps the socket interface of
the HTTPResponse, which in turn has the header data in its msg
attribute:

>>> e.fp.fp


>>> e.fp.fp._sock


>>> e.fp.fp._sock.msg


>>> e.hdrs

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


Re: [Tutor] hasattr()

2012-10-14 Thread Matthew Ngaha
Thank you xDog and Steven. The whole assignment makes a lot of sense now
after your explanations of what hasattr is doing. Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2.urlopen()

2012-10-14 Thread Ray Jones
On 10/14/2012 02:26 AM, eryksun wrote:
> e.hdrs['connection'] 'close'
> e.hdrs.getheaders('connection') ['close']

I have often used help() to find my way around imported libraries. I
didn't realize it would also help with instances. That's good to know.


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


Re: [Tutor] urllib2.urlopen()

2012-10-14 Thread eryksun
On Sun, Oct 14, 2012 at 2:15 AM, Ray Jones  wrote:
>
> I can iterate through e.info() with a 'for' loop, but all I get as a
> result is:
>
> connection
> content-type
> www-authenticate
> content-length

urllib2.HTTPError inherits from both urllib2.URLError and
urllib.addinfourl (see help(e)). An instance of the latter is what
urlopen() returns. It would be weird, but you could catch
urllib.addinfourl as the exception type (please don't).

HTTPError provides a file-like interface (read, readlines, etc), plus
the status code, headers, and URL. The info() method returns the
"headers" attribute, which is an instance of httplib.HTTPMessage (see
below). HTTPError also stores this in the attibute "hdrs". So you have
3 ways to access the headers: e.info(), e.headers, and e.hdrs.

(Actually, there are more ways since e.fp is the original addinfourl
instance, and e.fp.fp._sock.msg is the original HTTPResponse msg.)

Look at help(e.hdrs). HTTPMessage inherits a dict interface from
rfc822.Message (__getitem__, __setitem__, __delitem__,  __contains__,
__len__, __iter__, get, setdefault, has_key, items, keys, values). It
also has the method getheaders(name) that returns a list of values in
case the header appears multiple times in the message.

>>> e.hdrs['connection']
'close'
>>> e.hdrs.getheaders('connection')
['close']
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2.urlopen()

2012-10-14 Thread Ray Jones
On 10/13/2012 11:55 PM, Brian van den Broek wrote:
> On 14 October 2012 02:15, Ray Jones  wrote:
>> On 10/13/2012 07:50 PM, Steven D'Aprano wrote:
> 
>
>>> If you can do `print e.info()`, then you can also do `info = e.info()`
>>> and inspect the info programmatically.
>>>
>> One would expect that to be true. But when I do info = e.info(), info is
>> .
>>
>> When I print e.info(), I get the following:
>>
>> Content-Type: text/html
>> Connection: close
>> WWW-Authenticate: Basic realm=""
>> Content-Length: xx
>>
>> I can iterate through e.info() with a 'for' loop, but all I get as a
>> result is:
>>
>> connection
>> content-type
>> www-authenticate
>> content-length
>>
>> In other words, I get the headers but not the corresponding values.
> Ray,
>
> That smells rather like you are dealing with a dictionary. What
> happens if you try
>   e.info()["connection"]
Bingo! That's it! Thank-you very much - I will now attempt to implement it.


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