From rgarcia at fas.harvard.edu  Sun Apr  1 00:00:47 2007
From: rgarcia at fas.harvard.edu (Rafael Garcia)
Date: Sat, 31 Mar 2007 18:00:47 -0400
Subject: [Tutor] tokenizing a simple string with split()
In-Reply-To: <3576e740703311443q7a25a476iba10c15fbe4345a0@mail.gmail.com>
References: <3576e740703311443q7a25a476iba10c15fbe4345a0@mail.gmail.com>
Message-ID: <460EDA0F.7030801@fas.harvard.edu>

I think by "multiple characters" they mean more than one character for 
ONE separator. I don't know how to specify multiple separators. You 
could try something like this:

s = "spam;egg mail"
list = []
for t in s.split(";"):
    for u in t.split(" "):
        list.append(u)

which yields:
list = ['spam', 'egg', 'mail']


Rafael

On 3/31/07 5:43 PM, Andrei Petre wrote:
> I want to split a string like "C:\My\Doc\;D:\backup\" with two 
> separators: \ and ;
> I found that \ is handled with /raw string/ notation r"". But the 
> problem i encountered is with split() function.
> In the 2.5 reference is said that "The sep argument of the split() 
> function may consist of multiple characters". But I cannot figured out 
> why this simple example not working:
>
> s = "spam;egg mail"
> s.split("; ")
>
> output: ['spam;egg mail']
>
> instead of ['spam', 'egg', 'mail']
>
> any suggestion is welcome,
> andrei
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070331/8e1bedb4/attachment.htm 

From gregcorradini at gmail.com  Sun Apr  1 00:20:02 2007
From: gregcorradini at gmail.com (Greg Corradini)
Date: Sat, 31 Mar 2007 17:20:02 -0500
Subject: [Tutor] Create an Access table w/ mxODBC module
Message-ID: <429320790703311520w1ab9f56agd20914acb567bc77@mail.gmail.com>

Hello all,
I'm brand new to the mxODBC module from egenix (like yesterday). I currently
use the module for data laundering. I connect to a Microsoft Access .mdb and
perform some SQL queries on tables. Almost everything is going fine.
However, I can't find out how to create a new table. Even other examples
that I've found on the web that use the "create table" SQL command aren't
working for me. When I run mycursor.execute('create table TEST (nr Integer,
val Integer)'), i only get a return value of -1.  I was hoping somebody with
more mxODBC experience could give me a hand with this minor problem.

Thanks
Greg
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070331/cfd322a8/attachment.html 

From pythontut at pusspaws.net  Sun Apr  1 00:20:21 2007
From: pythontut at pusspaws.net (Dave S)
Date: Sat, 31 Mar 2007 23:20:21 +0100
Subject: [Tutor] My Python project - an update
In-Reply-To: <200703281212.46363.ms@cerenity.org>
References: <200703232231.26662.pythontut@pusspaws.net>
	<e5a6f5430703280250m4d17518bpcd38306dba891c99@mail.gmail.com>
	<200703281212.46363.ms@cerenity.org>
Message-ID: <200703312320.21457.pythontut@pusspaws.net>

Very valid points, I was not aware that MD5 had been cracked :)

Dave

From alan.gauld at btinternet.com  Sun Apr  1 01:01:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 1 Apr 2007 00:01:49 +0100
Subject: [Tutor] Detect errors when using os.popen.readlines()
References: <460E8C78.80803@marscode.net>
Message-ID: <eump92$ka9$1@sea.gmane.org>


"Peter" <lists1 at marscode.net> wrote

> Is there a way to detect errors when running shell commands using
> os.popen?

You have to parse the programs output.
Usually errors will appear on stderr so you need to read that as
well as stdout.

This may be slightly easier using the new subprocess module
and the Popen class.

> if an interface doesn't exist I get an error from the shell command.
> I tried using try and except, but that did seem to work.

Even if the program returns an error popen is still working just
fine so no exception gets raised. You must parse the output
(or check the status value, but thats not reliable in all programs)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From jmutter at uakron.edu  Sun Apr  1 02:45:21 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sat, 31 Mar 2007 20:45:21 -0400
Subject: [Tutor] Another parsing question
In-Reply-To: <460EA809.5040108@tds.net>
References: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>
	<460EA809.5040108@tds.net>
Message-ID: <7BD9F003-BE85-47BF-A83C-6A8926EB31C0@uakron.edu>

Kent;
Again thanks for the help.
i am not sure if this is what you menat but i put

for line in s:
     jay = patno.findall(line)
     jay2 = "".join(jay[0])
     print jay2

and it prints fine up until line 111 which is a line that had  
previously returned [ ] since a number didn't exist on that line and   
then exits with

Traceback (most recent call last):
   File "patentno2.py", line 12, in ?
     jay2 = "".join(jay[0])
IndexError: list index out of range


And as long as i am writing, how can I delete a return at the end of  
a line if the line ends in a certain pattern?

For instance, if line ends with the abbreviation  No.
I want to join the current line with next line.
Are lists immutable or can they be changed?

Thanks again

jay

On Mar 31, 2007, at 2:27 PM, Kent Johnson wrote:

> Jay Mutter III wrote:
>> I have the following that I am using to extract "numbers' from a file
>> ...
>> which yields the following
>> [('1', '337', '912')]
> > ...
>> So what do i have above ? A list of tuples?
>
> Yes, each line is a list containing one tuple containing three  
> string values.
>
>> How do I  send the output to a file?
>
> When you print, the values are automatically converted to strings  
> by calling str() on them. When you use p2.write(), this conversion  
> is not automatic, you have to do it yourself via
>   p2.write(str(jay))
>
> You can also tell the print statement to output to a file like this:
>   print >>p2, jay
>
>> Is there a way to get the output as
>> 1337912  instead of   [('1', '337', '912')]  ?
>
> In [4]: jay=[('1', '337', '912')]
>
> jay[0] is the tuple alone:
> In [6]: jay[0]
> Out[6]: ('1', '337', '912')
>
> Join the elements together using an empty string as the separator:
> In [5]: ''.join(jay[0])
> Out[5]: '1337912'
> In [7]:
>
> Kent


From kent37 at tds.net  Sun Apr  1 05:42:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 31 Mar 2007 23:42:14 -0400
Subject: [Tutor] tokenizing a simple string with split()
In-Reply-To: <3576e740703311443q7a25a476iba10c15fbe4345a0@mail.gmail.com>
References: <3576e740703311443q7a25a476iba10c15fbe4345a0@mail.gmail.com>
Message-ID: <460F2A16.4050206@tds.net>

Andrei Petre wrote:
> I want to split a string like "C:\My\Doc\;D:\backup\" with two 
> separators: \ and ;
> I found that \ is handled with /raw string/ notation r"". But the 
> problem i encountered is with split() function.
> In the 2.5 reference is said that "The sep argument of the split() 
> function may consist of multiple characters". 

The argument to split() is the literal string to split on, not a list of 
potential splitting characters. So to split on '; ' your string would 
have to be 'spam; egg; mail'.

To split on one of a list of characters you have to use a regular 
expression and re.split().

In [1]: import re
In [3]: re.split('[; ]', "spam;egg mail")
Out[3]: ['spam', 'egg', 'mail']

[; ] is a regular expression that means, "match either of ; or space".

Kent

From David.Heiser at intelliden.com  Sun Apr  1 08:43:34 2007
From: David.Heiser at intelliden.com (David Heiser)
Date: Sun, 1 Apr 2007 00:43:34 -0600
Subject: [Tutor] tokenizing a simple string with split()
In-Reply-To: <460F2A16.4050206@tds.net>
Message-ID: <DB30DA681DB9544886EA69FE9082737CCAF316@csoexc02.intelliden.net>


Or you can try something like:

x = r"C:\My\Doc\;D:\backup"
x = x.replace("\\", ";")
x = x.split(";")


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Kent Johnson
Sent: Saturday, March 31, 2007 9:42 PM
To: Andrei Petre
Cc: tutor at python.org
Subject: Re: [Tutor] tokenizing a simple string with split()


Andrei Petre wrote:
> I want to split a string like "C:\My\Doc\;D:\backup\" with two
> separators: \ and ;
> I found that \ is handled with /raw string/ notation r"". But the 
> problem i encountered is with split() function.
> In the 2.5 reference is said that "The sep argument of the split() 
> function may consist of multiple characters". 

The argument to split() is the literal string to split on, not a list of

potential splitting characters. So to split on '; ' your string would 
have to be 'spam; egg; mail'.

To split on one of a list of characters you have to use a regular 
expression and re.split().

In [1]: import re
In [3]: re.split('[; ]', "spam;egg mail")
Out[3]: ['spam', 'egg', 'mail']

[; ] is a regular expression that means, "match either of ; or space".

Kent
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Sun Apr  1 09:54:02 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 1 Apr 2007 08:54:02 +0100
Subject: [Tutor] Another parsing question
References: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu><460EA809.5040108@tds.net>
	<7BD9F003-BE85-47BF-A83C-6A8926EB31C0@uakron.edu>
Message-ID: <eunoeu$prr$1@sea.gmane.org>


"Jay Mutter III" <jmutter at uakron.edu> wrote

> for line in s:
>     jay = patno.findall(line)
>     jay2 = "".join(jay[0])
>     print jay2
>
> and it prints fine up until line 111 which is a line that had
> previously returned [ ] since a number didn't exist on that line and
> then exits with

> IndexError: list index out of range

Either try/catch the exception or add an
if not line: continue  # or return a default string

> And as long as i am writing, how can I delete a return at the end of
> a line if the line ends in a certain pattern?
>
> For instance, if line ends with the abbreviation  No.

if line.endswith(string): line = line.rstrip()

> I want to join the current line with next line.
> Are lists immutable or can they be changed?

lists can be changed, tuples cannot.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From jmutter at uakron.edu  Sun Apr  1 13:40:36 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sun, 1 Apr 2007 07:40:36 -0400
Subject: [Tutor] Tutor Digest, Vol 38, Issue 1
In-Reply-To: <mailman.33.1175421611.31003.tutor@python.org>
References: <mailman.33.1175421611.31003.tutor@python.org>
Message-ID: <C097C2CA-CB5B-4AAA-A629-3F68FAE36890@uakron.edu>

Alan thanks for the response;


> Message: 8
> Date: Sun, 1 Apr 2007 08:54:02 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Another parsing question
> To: tutor at python.org
> Message-ID: <eunoeu$prr$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
>
> "Jay Mutter III" <jmutter at uakron.edu> wrote
>
>> for line in s:
>>     jay = patno.findall(line)
>>     jay2 = "".join(jay[0])
>>     print jay2
>>
>> and it prints fine up until line 111 which is a line that had
>> previously returned [ ] since a number didn't exist on that line and
>> then exits with
>
>> IndexError: list index out of range
>
> Either try/catch the exception or add an
> if not line: continue  # or return a default string
>
>> And as long as i am writing, how can I delete a return at the end of
>> a line if the line ends in a certain pattern?
>>
>> For instance, if line ends with the abbreviation  No.
>
> if line.endswith(string): line = line.rstrip()
>

For some reason this never works for me;
i am using an intel imac with OS X 10.4.9 which has python 2.3.5

inp = open('test.txt','r')
s = inp.readlines()
for line in s:
     if line.endswith('No.'):
         line = line.rstrip()
     print line
and it never ever removes the line feed.  (These are unix \r  
according to Text wrangler)
I am beginning to think that it is a problem with readlines.

But then i thought well why not

inp = open('test.txt','r')
s = inp.readlines()
for line in s:
     if line.endswith('No.'):
         line += s.next()
     print line,

however that doesn't work either which leads me to believe that it is  
me and my interpretation of the above.

Thanks

Jay



>> I want to join the current line with next line.
>> Are lists immutable or can they be changed?
>
> lists can be changed, tuples cannot.
>
> HTH,
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 38, Issue 1
> ************************************


From rikard.bosnjakovic at gmail.com  Sun Apr  1 14:28:36 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sun, 1 Apr 2007 14:28:36 +0200
Subject: [Tutor] Tutor Digest, Vol 38, Issue 1
In-Reply-To: <C097C2CA-CB5B-4AAA-A629-3F68FAE36890@uakron.edu>
References: <mailman.33.1175421611.31003.tutor@python.org>
	<C097C2CA-CB5B-4AAA-A629-3F68FAE36890@uakron.edu>
Message-ID: <d9e88eaf0704010528m2700fe7by53b17e366140bedd@mail.gmail.com>

On 4/1/07, Jay Mutter III <jmutter at uakron.edu> wrote:

> For some reason this never works for me;

That's because you are ignoring the linefeed character:

[...]
>      if line.endswith('No.'):

>>> s1 = "some line\n"
>>> s2 = "some line"
>>> s1.endswith("line"), s2.endswith("line")
(False, True)

Just skip the if and simply rstrip the string.


-- 
- Rikard - http://bos.hack.org/cv/

From alan.gauld at btinternet.com  Sun Apr  1 17:42:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 1 Apr 2007 16:42:56 +0100
Subject: [Tutor] Tutor Digest, Vol 38, Issue 1
References: <mailman.33.1175421611.31003.tutor@python.org><C097C2CA-CB5B-4AAA-A629-3F68FAE36890@uakron.edu>
	<d9e88eaf0704010528m2700fe7by53b17e366140bedd@mail.gmail.com>
Message-ID: <euoju5$a7c$1@sea.gmane.org>


"Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote 

>>>> s1 = "some line\n"
>>>> s2 = "some line"
>>>> s1.endswith("line"), s2.endswith("line")
> (False, True)
> 
> Just skip the if and simply rstrip the string.

Or add \n to the endswith() test string if you really only 
want to strip the newline in those cases....

Alan G.


From alan.gauld at btinternet.com  Sun Apr  1 17:46:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 1 Apr 2007 16:46:05 +0100
Subject: [Tutor] Tutor Digest, Vol 38, Issue 1
References: <mailman.33.1175421611.31003.tutor@python.org>
	<C097C2CA-CB5B-4AAA-A629-3F68FAE36890@uakron.edu>
Message-ID: <euok41$are$1@sea.gmane.org>

"Jay Mutter III" <jmutter at uakron.edu> wrote 

> inp = open('test.txt','r')
> s = inp.readlines()
> for line in s:
>     if line.endswith('No.'):
>         line = line.rstrip()
>     print line

BTW,
You do know that you can shorten that considerably? 
With:

for line in open('test.txt'):
   if line.endswith('No.\n'):
      line = line.rstrip()
   print line

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From gregp at liveammo.com  Sun Apr  1 18:17:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 01 Apr 2007 12:17:00 -0400
Subject: [Tutor] Communication between classes
Message-ID: <20070401161218.5D9C117051@smtp2.hushmail.com>

Hi again,

I am still in the process of learning OOP concepts and reasons why classes should be used instead of functions etc.

One thing that is not apparent to me is the best way for classes to communicate with each other.  For example, I have created an Args class that sets a variety of internal variables (__filename, __outputdir etc) by parsing the argv array from th command line.  What would be the preferred mechanism for returning or passing along those variables to another class?  Maybe by a function method that returns all of those variables?




From project5 at redrival.net  Sun Apr  1 20:46:21 2007
From: project5 at redrival.net (Andrei)
Date: Sun, 01 Apr 2007 20:46:21 +0200
Subject: [Tutor] Communication between classes
In-Reply-To: <20070401161218.5D9C117051@smtp2.hushmail.com>
References: <20070401161218.5D9C117051@smtp2.hushmail.com>
Message-ID: <euould$au7$1@sea.gmane.org>

Hi Greg,

Greg Perry wrote:
> I am still in the process of learning OOP concepts and 
 > reasons why classes should be used instead of functions etc.
> 
> One thing that is not apparent to me is the best way for 
 > classes to communicate with each other.  For example,

Good question. Unfortunately there's no general rule that you can apply 
and end up with an undisputably perfect solution.

Classes should communicate on a need-to-know basis. Take for example a 
RSS feed reader application. You may have a class representing a feed 
and a class representing a post. The feed will know what posts it 
contains, but the post probably won't know what feed it comes from. The 
interface would display a list of feeds (without knowing their 
contents), a list of posts within a feed (this needs to know both feed 
and feed contents) and the contents of a single post (knows only about 
an individual post).

 > I have created an Args class that sets a variety of internal
 > variables (__filename, __outputdir etc) by parsing the argv

Be careful with classes that simply act as a container for what are in 
fact global variables. A class should do one thing only (of course what 
you accept as 'one thing' is open for debate) and encapsulate all that's 
necessary for that particular thing. Make sure you're not 
overcomplicating your solution by making classes where they're not 
really necessary.

 > array from th command line.  What would be the preferred
 > mechanism for returning or passing along those variables

In some cases only some parts of the information contained in class A 
are relevant to class B - you should pass only that particular 
information, e.g. in the constructor or by setting a property of B. In 
your example, if you have a Reader class that is interested in the 
filename, you would not pass the whole Args object to it - only the 
filename, like this:

     myreader = Reader(Args.FileName)

 > to another class?  Maybe by a function method that returns
 > all of those variables?

Use properties if you need getter/setter methods or simple attributes 
otherwise. In your case, I would not make __filename etc. 'private' 
(that's what the double underscore suggests), then write a getter method 
for it - just call it FileName and be done with it. Python idiom here is 
more flexible than other languages.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From ebrosh at nana.co.il  Sun Apr  1 23:25:39 2007
From: ebrosh at nana.co.il (Eli Brosh)
Date: Mon, 2 Apr 2007 00:25:39 +0300
Subject: [Tutor] A bug or a feature - complex arguments in special functions
Message-ID: <957526FB6E347743AAB42B212AB54FDA7A5AEB@NANAMAILBACK1.nanamail.co.il>

Hello
I am trying to convert from MATLAB to Python.
I am using Python 2.4.3 for Windows (Enthought Edition)
In one of the first programs, I tried to use the special functions from the SciPy  "special" module.
However, when I tryed:
 
>> from scipy import *
>> special.jv(0,1+1j)
 
I got an error message and python restarted.
 
The problem did not go away after I installed the latest version of SciPy.
 
Is there a significant bug in the bessel functions when handling complex arguments ?
Or, is it some feature that I do not understand ?
 
 
Thanks
Eli Brosh
 
 
 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070402/41c2d81a/attachment.html 

From gregp at liveammo.com  Mon Apr  2 01:24:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 01 Apr 2007 19:24:00 -0400
Subject: [Tutor] Communication between classes
Message-ID: <20070401231953.2698917069@smtp2.hushmail.com>

That makes sense, thank you for the detailed explanation Andrei.  For this simple project I am working on, it looks like the most direct route would be to use functions and only develop classes for the portions of the program that can be reused.

Is it safe to say that classes are only useful for instances where reuse is a key consideration?  From my very limited perspective, it seems that classes are in most cases overkill for simple tasks (such as reading the command line then calculating a hash/checksum to verify integrity).

Thanks again for your very descriptive answer.

-----Original Message-----
From: Andrei

Hi Greg,
>
>Greg Perry wrote:
> I am still in the process of learning OOP concepts and 
> > reasons why classes should be used instead of functions etc.
> 
> One thing that is not apparent to me is the best way for 
> > classes to communicate with each other.  For example,
>
>Good question. Unfortunately there's no general rule that you can apply 
>and end up with an undisputably perfect solution.
>
>Classes should communicate on a need-to-know basis. Take for example a 
>RSS feed reader application. You may have a class representing a feed 
>and a class representing a post. The feed will know what posts it 
>contains, but the post probably won't know what feed it comes from. The 
>interface would display a list of feeds (without knowing their 
>contents), a list of posts within a feed (this needs to know both feed 
>and feed contents) and the contents of a single post (knows only about 
>an individual post).
>
> > I have created an Args class that sets a variety of internal
> > variables (__filename, __outputdir etc) by parsing the argv
>
>Be careful with classes that simply act as a container for what are in 
>fact global variables. A class should do one thing only (of course what 
>you accept as 'one thing' is open for debate) and encapsulate all that's 
>necessary for that particular thing. Make sure you're not 
>overcomplicating your solution by making classes where they're not 
>really necessary.
>
> > array from th command line.  What would be the preferred
> > mechanism for returning or passing along those variables
>
>In some cases only some parts of the information contained in class A 
>are relevant to class B - you should pass only that particular 
>information, e.g. in the constructor or by setting a property of B. In 
>your example, if you have a Reader class that is interested in the 
>filename, you would not pass the whole Args object to it - only the 
>filename, like this:
>
>     myreader = Reader(Args.FileName)
>
> > to another class?  Maybe by a function method that returns
> > all of those variables?
>
>Use properties if you need getter/setter methods or simple attributes 
>otherwise. In your case, I would not make __filename etc. 'private' 
>(that's what the double underscore suggests), then write a getter method 
>for it - just call it FileName and be done with it. Python idiom here is 
>more flexible than other languages.
>
>-- 
>Yours,
>
>Andrei
>
>=====
>Mail address in header catches spam. Real contact info:
>''.join([''.join(s) for s in zip(
>"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
>"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>



From allison.william at comcast.net  Mon Apr  2 01:48:04 2007
From: allison.william at comcast.net (William Allison)
Date: Sun, 01 Apr 2007 19:48:04 -0400
Subject: [Tutor] datetime.timedelta Output Format
Message-ID: <461044B4.8080900@comcast.net>

Is there a way to have the output of "print tis" in the same format as 
"print now" and "print tafmsd" in the code below?
Thanks,
Will


savage:~ wallison$ python
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> import datetime
 >>> now = datetime.date.today()
 >>> print now
2007-04-01
 >>> tafmsd = datetime.date(1994, 2, 23)
 >>> print tafmsd
1994-02-23
 >>> tis = now - tafmsd
 >>> print tis
4785 days, 0:00:00
 >>>


From alan.gauld at btinternet.com  Mon Apr  2 02:13:37 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 2 Apr 2007 01:13:37 +0100
Subject: [Tutor] Communication between classes
References: <20070401161218.5D9C117051@smtp2.hushmail.com>
Message-ID: <euphrm$f8f$1@sea.gmane.org>

"Greg Perry" <gregp at liveammo.com> wrote 

> I am still in the process of learning OOP concepts and 
> reasons why classes should be used instead of 
> functions etc.

That's OK, many folks find the transition hard at first.
It is a new way of looking at problems.

> One thing that is not apparent to me is the best way 
> for classes to communicate with each other.  

Classes don't.
Its *object* oriented programming and its objects 
which communicate. Objects pass messages 
between each other and the parameters are other 
objects. Classes are just the mechanisms for defining 
and creating objects. And thats a very important distinction.

> For example, I have created an Args class that sets 
> a variety of internal variables (__filename, __outputdir etc) 
> by parsing the argv array from th command line.  

OK, What is the responsibility of an Args object?
What kind of things would you do with/to an Args 
instance? You might want to get the vatrious values 
from it - treating it somewhat like a dictionary maybe?
You might want to store it so the same set of args 
can be used over and over. What else do you want 
the args to do? Focus on the responsibility of the object 
as a whole.

> What would be the preferred mechanism for returning 
> or passing along those variables to another class?  

You pass an instance of the args class as an object to 
another object via a message.

> Maybe by a function method that returns all of those variables?

You might have a method of the Args class that can get 
the values for a given instance but you wouldn't want to 
extract the values from the object and manage them elsewhere. 
That would be to defeat the point of the object, which is to 
encapsulate both the data and the operations on the data 
in one entity, the object, which can be passed around in 
its entirety.

For example when you drive your car(an object) you don't 
dismantle it and then reassemble just the bits you need.
Let's see its only me so only one seat and its a warm day 
so I don't need the heater... You just jump into the complete 
car and drive it. Same with your args class(*). You create 
an instance and use it whichever way you need. If somebody 
else needs your args to do something you give them the args
(just like if somebody borrows your car you don't give them 
bits of it you lend them the whole car)


(*)And same with the car, you don't lend someone the factory 
blueprint (the class) and tell them to build their own car, you 
lend them your specific instance of the car.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Mon Apr  2 02:20:28 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 2 Apr 2007 01:20:28 +0100
Subject: [Tutor] Communication between classes
References: <20070401231953.2698917069@smtp2.hushmail.com>
Message-ID: <eupi8h$g5d$1@sea.gmane.org>

"Greg Perry" <gregp at liveammo.com> wrote 

> That makes sense, thank you for the detailed explanation 
> Andrei.  For this simple project I am working on, it looks 
> like the most direct route would be to use functions 

Thats often the case. Often when people start with OOP 
they try to do everything with objects. Its possible but often 
not very efficient.

> and only develop classes for the portions of the program 
> that can be reused.
> Is it safe to say that classes are only useful for instances 
> where reuse is a key consideration?  

Its not only for reuse. Classes and objects are often a 
more natural model of the real world. One of the best 
examples is a GUI program where each window or control 
can be treated as an object. Thats intuitively obvious because 
to our eyews it looks and acts somewhat like a real world 
object. But you rarely reuse the specific controls or windows 
developeed for a particular project. (Widgets are another 
matter, they are designed for reuse)

> seems that classes are in most cases overkill for simple 
> tasks 

Yes thats true. OOP was invented as a way to control 
complexity in large programs. It can be used in smaller 
programs but if you only have a dozen or so linres of 
executable code then classes may well be overkill.

> such as reading the command line then calculating a 
> hash/checksum to verify integrity

If you had a lot of different data types each with their own 
checksum algorithm then classes and objects might be 
appropriate but a single case would usually be easier 
using functions.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Mon Apr  2 02:24:06 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 2 Apr 2007 01:24:06 +0100
Subject: [Tutor] A bug or a feature - complex arguments in special
	functions
References: <957526FB6E347743AAB42B212AB54FDA7A5AEB@NANAMAILBACK1.nanamail.co.il>
Message-ID: <eupifa$gj0$1@sea.gmane.org>


"Eli Brosh" <ebrosh at nana.co.il> wrote 

>> from scipy import *
>> special.jv(0,1+1j)
> 
> I got an error message and python restarted.

It would be good if you could include the error text.

However, did you try putting the complex number in parens?
or assigning to a variable and then pass the variable into the call?
It may simply be that Python is interpreting it as

special.jv((0,1)+1j)

 or somesuch strangeness.

But I don't use SciPy so I can't check. An error text may help.

Alan G


From amonroe at columbus.rr.com  Mon Apr  2 02:52:07 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sun, 1 Apr 2007 20:52:07 -0400
Subject: [Tutor] datetime.timedelta Output Format
In-Reply-To: <461044B4.8080900@comcast.net>
References: <461044B4.8080900@comcast.net>
Message-ID: <711210149.20070401205207@columbus.rr.com>

> Is there a way to have the output of "print tis" in the same format as 
> "print now" and "print tafmsd" in the code below?
> Thanks,
> Will


> savage:~ wallison$ python
> Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import datetime
>  >>> now = datetime.date.today()
>  >>> print now
> 2007-04-01
>  >>> tafmsd = datetime.date(1994, 2, 23)
>  >>> print tafmsd
> 1994-02-23
>  >>> tis = now - tafmsd
>  >>> print tis
> 4785 days, 0:00:00
>  >>>

That seems like a weird idea. Are you really sure you want the number
of days between start and end dates displayed itself as a date? What
date would that be?

That's kind of like asking how to say "128 shopping days left until
Christmas" in the format of "2007-04-01 shopping days left until
Christmas". It doesn't work, somehow.

Alan


From project5 at redrival.net  Mon Apr  2 09:30:04 2007
From: project5 at redrival.net (Andrei)
Date: Mon, 2 Apr 2007 07:30:04 +0000 (UTC)
Subject: [Tutor] Communication between classes
References: <20070401231953.2698917069@smtp2.hushmail.com>
Message-ID: <loom.20070402T090150-214@post.gmane.org>

Greg Perry <gregp <at> liveammo.com> writes:

> Is it safe to say that classes are only useful for instances where reuse is a
key consideration?  From my very
> limited perspective, it seems that classes are in most cases overkill for
simple tasks (such as reading
> the command line then calculating a hash/checksum to verify integrity).

Alan has already adressed your questions, I just have one addition on this
point. If this is *all* your application does, a class is indeed overkill.
However, if this functionality is part of a larger application, it could become
a small class. 

Imagine an application that would offer some file operations, like:
- calculate hash
- split into chunks of 1.44 MB
- compress
- encrypt

You could have a generic ancestor class, say FileOperation and inherit from it
different classes implementing specific operations.

  class FileOperation(object):
      def __init__(self, filename):
          self._filename = filename
      def Perform(self):
          pass # should be implemented in children
      def ShowHelp(self):
          pass # should be implemented in children

  class HashFileOperation(FileOperation):
      def Perform(self):
          # calculate hash of self._filename
      def ShowHelp(self):
          print "Calculates MD5 hash of the file"

  <etc>

Depending on a command line option, the application could instantiate one of the
operation classes and work with it. Assuming the command line would be 'app.py
<operation> <filename>' (e.g. 'app.py hash myfile.txt'), the application code
could look something like this:

  # register all known operation classes and bind them
  # to specific command line options
  operations = {'hash': HashFileOperation,
                'split': SplitFileOperation, <etc>}

  opname = sys.argv[1]

  # determine what operation class is necessary
  opclass = operations[opname]

  # instantiate that operation (make a file operation object)
  fileop = opclass(sys.argv[2])

  # check if it should display help or run the operation
  if sys.argv[2] == '?': 
      fileop.ShowHelp()
  else:    
      fileop.Perform()

Adding new operations would be a matter of implementing an appropriate class and
adding it to the operations dictionary. With a bit of Python magic you could
even get the operation classes to auto-register, so just writing an operation
class would automatically make it available in the application.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet <at> aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])



From alan.gauld at btinternet.com  Mon Apr  2 09:39:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 2 Apr 2007 08:39:36 +0100
Subject: [Tutor] datetime.timedelta Output Format
References: <461044B4.8080900@comcast.net>
	<711210149.20070401205207@columbus.rr.com>
Message-ID: <euqbvt$fe4$1@sea.gmane.org>


"R. Alan Monroe" <amonroe at columbus.rr.com> wrote

>> Is there a way to have the output of "print tis" in the same format 
>> as
>> "print now" and "print tafmsd" in the code below?

>>  >>> now = datetime.date.today()
>>  >>> print now
>> 2007-04-01
>>  >>> tis = now - tafmsd
>>  >>> print tis
>> 4785 days, 0:00:00

> That's kind of like asking how to say "128 shopping days left until
> Christmas" in the format of "2007-04-01 shopping days left until
> Christmas". It doesn't work, somehow.

I assume that what Will really means is how does he
get the number of days expressed as a number of
years/months and days.

As in: There are 4 months, 8 days to Xmas.

I don't use datetime so don't know whether/how that would be done
but it seems like a reasonable request.

And if that's not what Will wants can someone tell me
because I'm now curious! Its a non trivial conversion and
would require knowledge of the context - ie start or end date.

Alan G. 



From allison.william at comcast.net  Mon Apr  2 11:24:00 2007
From: allison.william at comcast.net (William Allison)
Date: Mon, 02 Apr 2007 05:24:00 -0400
Subject: [Tutor] datetime.timedelta Output Format
In-Reply-To: <euqbvt$fe4$1@sea.gmane.org>
References: <461044B4.8080900@comcast.net>	<711210149.20070401205207@columbus.rr.com>
	<euqbvt$fe4$1@sea.gmane.org>
Message-ID: <4610CBB0.1010900@comcast.net>

Alan Gauld wrote:
> "R. Alan Monroe" <amonroe at columbus.rr.com> wrote
>
>   
>>> Is there a way to have the output of "print tis" in the same format 
>>> as
>>> "print now" and "print tafmsd" in the code below?
>>>       
>
>   
>>>  >>> now = datetime.date.today()
>>>  >>> print now
>>> 2007-04-01
>>>  >>> tis = now - tafmsd
>>>  >>> print tis
>>> 4785 days, 0:00:00
>>>       
>
>   
>> That's kind of like asking how to say "128 shopping days left until
>> Christmas" in the format of "2007-04-01 shopping days left until
>> Christmas". It doesn't work, somehow.
>>     
>
> I assume that what Will really means is how does he
> get the number of days expressed as a number of
> years/months and days.
>
> As in: There are 4 months, 8 days to Xmas.
>   
Yes, that's correct.  Sorry I didn't express myself clearly.
Thanks again,
Will


From ebrosh at nana.co.il  Mon Apr  2 11:33:54 2007
From: ebrosh at nana.co.il (Eli Brosh)
Date: Mon, 2 Apr 2007 12:33:54 +0300
Subject: [Tutor]  A bug or a feature - complex arguments in special
Message-ID: <957526FB6E347743AAB42B212AB54FDA7A5AEC@NANAMAILBACK1.nanamail.co.il>

Alan G wrote:
>It would be good if you could include the error text.

>However, did you try putting the complex number in parens?
>or assigning to a variable and then pass the variable into the call?

Well, the error message is not from Pytho but from the operating system (windows XP).
It says "pythonw.exe has encountered a problem and needs to close. We are sorry for the inconvenience."
 
The IDLE does not close but it is restarted:
There appears a line: >>> ================================ RESTART ================================
 
 
 
I tried to assign the argument to a variable:
>>>from scipy import *
>>> x=.5
>>> special.jv(0,x)
0.938469807241
>>> y=.5+1.j
>>> y
(0.5+1j)
>>> special.jv(0,y)
>>> ================================ RESTART ================================
>>> 

The results are still the same: when the variable is real, the result is correct.
When the variable is comlex, the program crashes.
Is it a bug ?
 
 
 
Thanks
Eli

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070402/ca5abc1a/attachment.html 

From kent37 at tds.net  Mon Apr  2 12:34:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 02 Apr 2007 06:34:01 -0400
Subject: [Tutor] datetime.timedelta Output Format
In-Reply-To: <461044B4.8080900@comcast.net>
References: <461044B4.8080900@comcast.net>
Message-ID: <4610DC19.6020807@tds.net>

William Allison wrote:
> Is there a way to have the output of "print tis" in the same format as 
> "print now" and "print tafmsd" in the code below?
> Thanks,
> Will
> 
> 
> savage:~ wallison$ python
> Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import datetime
>  >>> now = datetime.date.today()
>  >>> print now
> 2007-04-01
>  >>> tafmsd = datetime.date(1994, 2, 23)
>  >>> print tafmsd
> 1994-02-23
>  >>> tis = now - tafmsd
>  >>> print tis
> 4785 days, 0:00:00

It looks like Gustavo Niemeyer's dateutil module will at least do the 
year/month/day calculation if not the formatting:

In [1]: from datetime import date
In [2]: from dateutil import relativedelta
In [3]: now = date.today()
In [9]: rd = relativedelta.relativedelta(now, tafmsd)
In [10]: rd
Out[10]: relativedelta(years=+13, months=+1, days=+10)

http://labix.org/python-dateutil

Kent

From gawron at rohan.sdsu.edu  Sun Apr  1 19:47:14 2007
From: gawron at rohan.sdsu.edu (Jean Mark Gawron)
Date: Sun, 1 Apr 2007 10:47:14 -0700
Subject: [Tutor] Tokenizing a imple string with split()
In-Reply-To: <mailman.33.1175421611.31003.tutor@python.org>
References: <mailman.33.1175421611.31003.tutor@python.org>
Message-ID: <BC3F4388-BD80-4229-A417-FEFF30C9B537@rohan.sdsu.edu>

The  split method in the "re" module does what you want here.
This is a method on compiled re_patterns, so first you construct
a regular expression that matches any of the desired separators:

     >>> s = "spam;egg mail"
     >>> x_re = re.compile(r'[; ]')
     >>> s.split("; ")
     ['spam;egg mail']
     >>> x_re.split(s)
     ['spam', 'egg', 'mail']
 >>>

>
> Message: 1
> Date: Sat, 31 Mar 2007 18:00:47 -0400
> From: Rafael Garcia <rgarcia at fas.harvard.edu>
> Subject: Re: [Tutor] tokenizing a simple string with split()
> To: tutor at python.org
> Message-ID: <460EDA0F.7030801 at fas.harvard.edu>
> Content-Type: text/plain; charset="iso-8859-1"
>
> I think by "multiple characters" they mean more than one character for
> ONE separator. I don't know how to specify multiple separators. You
> could try something like this:
>
> s = "spam;egg mail"
> list = []
> for t in s.split(";"):
>     for u in t.split(" "):
>         list.append(u)
>
> which yields:
> list = ['spam', 'egg', 'mail']
>
>
> Rafael
>
> On 3/31/07 5:43 PM, Andrei Petre wrote:
>> I want to split a string like "C:\My\Doc\;D:\backup\" with two
>> separators: \ and ;
>> I found that \ is handled with /raw string/ notation r"". But the
>> problem i encountered is with split() function.
>> In the 2.5 reference is said that "The sep argument of the split()
>> function may consist of multiple characters". But I cannot figured  
>> out
>> why this simple example not working:
>>
>> s = "spam;egg mail"
>> s.split("; ")
>>
>> output: ['spam;egg mail']
>>
>> instead of ['spam', 'egg', 'mail']
>>
>> any suggestion is welcome,
>> andrei
>>
>> --------------------------------------------------------------------- 
>> ---
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: http://mail.python.org/pipermail/tutor/attachments/ 
> 20070331/8e1bedb4/attachment.html
>
> ------------------------------
>
> Message: 2
> Date: Sat, 31 Mar 2007 17:20:02 -0500
> From: "Greg Corradini" <gregcorradini at gmail.com>
> Subject: [Tutor] Create an Access table w/ mxODBC module
> To: tutor at python.org
> Message-ID:
> 	<429320790703311520w1ab9f56agd20914acb567bc77 at mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> Hello all,
> I'm brand new to the mxODBC module from egenix (like yesterday). I  
> currently
> use the module for data laundering. I connect to a Microsoft  
> Access .mdb and
> perform some SQL queries on tables. Almost everything is going fine.
> However, I can't find out how to create a new table. Even other  
> examples
> that I've found on the web that use the "create table" SQL command  
> aren't
> working for me. When I run mycursor.execute('create table TEST (nr  
> Integer,
> val Integer)'), i only get a return value of -1.  I was hoping  
> somebody with
> more mxODBC experience could give me a hand with this minor problem.
>
> Thanks
> Greg
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: http://mail.python.org/pipermail/tutor/attachments/20070331/ 
> cfd322a8/attachment.htm
>
> ------------------------------
>
> Message: 3
> Date: Sat, 31 Mar 2007 23:20:21 +0100
> From: Dave S <pythontut at pusspaws.net>
> Subject: Re: [Tutor] My Python project - an update
> To: tutor at python.org
> Message-ID: <200703312320.21457.pythontut at pusspaws.net>
> Content-Type: text/plain;  charset="iso-8859-15"
>
> Very valid points, I was not aware that MD5 had been cracked :)
>
> Dave
>
>
> ------------------------------
>
> Message: 4
> Date: Sun, 1 Apr 2007 00:01:49 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Detect errors when using os.popen.readlines()
> To: tutor at python.org
> Message-ID: <eump92$ka9$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
>
> "Peter" <lists1 at marscode.net> wrote
>
>> Is there a way to detect errors when running shell commands using
>> os.popen?
>
> You have to parse the programs output.
> Usually errors will appear on stderr so you need to read that as
> well as stdout.
>
> This may be slightly easier using the new subprocess module
> and the Popen class.
>
>> if an interface doesn't exist I get an error from the shell command.
>> I tried using try and except, but that did seem to work.
>
> Even if the program returns an error popen is still working just
> fine so no exception gets raised. You must parse the output
> (or check the status value, but thats not reliable in all programs)
>
> HTH,
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ------------------------------
>
> Message: 5
> Date: Sat, 31 Mar 2007 20:45:21 -0400
> From: Jay Mutter III <jmutter at uakron.edu>
> Subject: Re: [Tutor] Another parsing question
> To: Kent Johnson <kent37 at tds.net>
> Cc: tutor at python.org
> Message-ID: <7BD9F003-BE85-47BF-A83C-6A8926EB31C0 at uakron.edu>
> Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed
>
> Kent;
> Again thanks for the help.
> i am not sure if this is what you menat but i put
>
> for line in s:
>      jay = patno.findall(line)
>      jay2 = "".join(jay[0])
>      print jay2
>
> and it prints fine up until line 111 which is a line that had
> previously returned [ ] since a number didn't exist on that line and
> then exits with
>
> Traceback (most recent call last):
>    File "patentno2.py", line 12, in ?
>      jay2 = "".join(jay[0])
> IndexError: list index out of range
>
>
> And as long as i am writing, how can I delete a return at the end of
> a line if the line ends in a certain pattern?
>
> For instance, if line ends with the abbreviation  No.
> I want to join the current line with next line.
> Are lists immutable or can they be changed?
>
> Thanks again
>
> jay
>
> On Mar 31, 2007, at 2:27 PM, Kent Johnson wrote:
>
>> Jay Mutter III wrote:
>>> I have the following that I am using to extract "numbers' from a  
>>> file
>>> ...
>>> which yields the following
>>> [('1', '337', '912')]
>>> ...
>>> So what do i have above ? A list of tuples?
>>
>> Yes, each line is a list containing one tuple containing three
>> string values.
>>
>>> How do I  send the output to a file?
>>
>> When you print, the values are automatically converted to strings
>> by calling str() on them. When you use p2.write(), this conversion
>> is not automatic, you have to do it yourself via
>>   p2.write(str(jay))
>>
>> You can also tell the print statement to output to a file like this:
>>   print >>p2, jay
>>
>>> Is there a way to get the output as
>>> 1337912  instead of   [('1', '337', '912')]  ?
>>
>> In [4]: jay=[('1', '337', '912')]
>>
>> jay[0] is the tuple alone:
>> In [6]: jay[0]
>> Out[6]: ('1', '337', '912')
>>
>> Join the elements together using an empty string as the separator:
>> In [5]: ''.join(jay[0])
>> Out[5]: '1337912'
>> In [7]:
>>
>> Kent
>
>
>
> ------------------------------
>
> Message: 6
> Date: Sat, 31 Mar 2007 23:42:14 -0400
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] tokenizing a simple string with split()
> To: Andrei Petre <andrei.petre at gmail.com>
> Cc: tutor at python.org
> Message-ID: <460F2A16.4050206 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Andrei Petre wrote:
>> I want to split a string like "C:\My\Doc\;D:\backup\" with two
>> separators: \ and ;
>> I found that \ is handled with /raw string/ notation r"". But the
>> problem i encountered is with split() function.
>> In the 2.5 reference is said that "The sep argument of the split()
>> function may consist of multiple characters".
>
> The argument to split() is the literal string to split on, not a  
> list of
> potential splitting characters. So to split on '; ' your string would
> have to be 'spam; egg; mail'.
>
> To split on one of a list of characters you have to use a regular
> expression and re.split().
>
> In [1]: import re
> In [3]: re.split('[; ]', "spam;egg mail")
> Out[3]: ['spam', 'egg', 'mail']
>
> [; ] is a regular expression that means, "match either of ; or space".
>
> Kent
>
>
> ------------------------------
>
> Message: 7
> Date: Sun, 1 Apr 2007 00:43:34 -0600
> From: "David Heiser" <David.Heiser at intelliden.com>
> Subject: Re: [Tutor] tokenizing a simple string with split()
> To: <tutor at python.org>
> Message-ID:
> 	<DB30DA681DB9544886EA69FE9082737CCAF316 at csoexc02.intelliden.net>
> Content-Type: text/plain;	charset="us-ascii"
>
>
> Or you can try something like:
>
> x = r"C:\My\Doc\;D:\backup"
> x = x.replace("\\", ";")
> x = x.split(";")
>
>
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
> Behalf Of Kent Johnson
> Sent: Saturday, March 31, 2007 9:42 PM
> To: Andrei Petre
> Cc: tutor at python.org
> Subject: Re: [Tutor] tokenizing a simple string with split()
>
>
> Andrei Petre wrote:
>> I want to split a string like "C:\My\Doc\;D:\backup\" with two
>> separators: \ and ;
>> I found that \ is handled with /raw string/ notation r"". But the
>> problem i encountered is with split() function.
>> In the 2.5 reference is said that "The sep argument of the split()
>> function may consist of multiple characters".
>
> The argument to split() is the literal string to split on, not a  
> list of
>
> potential splitting characters. So to split on '; ' your string would
> have to be 'spam; egg; mail'.
>
> To split on one of a list of characters you have to use a regular
> expression and re.split().
>
> In [1]: import re
> In [3]: re.split('[; ]', "spam;egg mail")
> Out[3]: ['spam', 'egg', 'mail']
>
> [; ] is a regular expression that means, "match either of ; or space".
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> ------------------------------
>
> Message: 8
> Date: Sun, 1 Apr 2007 08:54:02 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Another parsing question
> To: tutor at python.org
> Message-ID: <eunoeu$prr$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
>
> "Jay Mutter III" <jmutter at uakron.edu> wrote
>
>> for line in s:
>>     jay = patno.findall(line)
>>     jay2 = "".join(jay[0])
>>     print jay2
>>
>> and it prints fine up until line 111 which is a line that had
>> previously returned [ ] since a number didn't exist on that line and
>> then exits with
>
>> IndexError: list index out of range
>
> Either try/catch the exception or add an
> if not line: continue  # or return a default string
>
>> And as long as i am writing, how can I delete a return at the end of
>> a line if the line ends in a certain pattern?
>>
>> For instance, if line ends with the abbreviation  No.
>
> if line.endswith(string): line = line.rstrip()
>
>> I want to join the current line with next line.
>> Are lists immutable or can they be changed?
>
> lists can be changed, tuples cannot.
>
> HTH,
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 38, Issue 1
> ************************************


From andreas at kostyrka.org  Mon Apr  2 11:44:04 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Mon, 2 Apr 2007 11:44:04 +0200
Subject: [Tutor] Tokenizing a imple string with split()
In-Reply-To: <BC3F4388-BD80-4229-A417-FEFF30C9B537@rohan.sdsu.edu>
References: <mailman.33.1175421611.31003.tutor@python.org>
	<BC3F4388-BD80-4229-A417-FEFF30C9B537@rohan.sdsu.edu>
Message-ID: <20070402094404.GG1382@andi-lap.la.revver.com>

Alternativly, one might consider the standard shlex module.
Depending what one ones to achieve this might be the better or worse
choice.

Andreas

From eike.welk at gmx.net  Mon Apr  2 14:49:42 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Mon, 02 Apr 2007 14:49:42 +0200
Subject: [Tutor] A bug or a feature - complex arguments in special
In-Reply-To: <957526FB6E347743AAB42B212AB54FDA7A5AEC@NANAMAILBACK1.nanamail.co.il>
References: <957526FB6E347743AAB42B212AB54FDA7A5AEC@NANAMAILBACK1.nanamail.co.il>
Message-ID: <200704021449.43294.eike.welk@gmx.net>

On Monday 02 April 2007 11:33, Eli Brosh wrote:
> >>>>from scipy import *
> >>>
> >>> x=.5
> >>> special.jv(0,x)
>
> 0.938469807241
>
> >>> y=.5+1.j
> >>> y
>
> (0.5+1j)
>
> >>> special.jv(0,y)
> >>> ================================ RESTART
> >>> ================================
>
> The results are still the same: when the variable is real, the
> result is correct. When the variable is comlex, the program
> crashes.
> Is it a bug ?

I think it is a bug, the function should definitely not crash the 
python session. You should go to the SciPy mailing list:
http://projects.scipy.org/mailman/listinfo/scipy-user
Maybe there someone knows a workaround for you. 

On my computer it does not crash:

In [1]:import scipy

In [2]:from scipy import *

In [3]:y=.5+1.j

In [4]:special.jv(0,y)
Out[4]:(1.1798566304-0.273726785591j)

In [5]:scipy.__version__
Out[5]:'0.5.2'


Regards, Eike.



From HouseScript at comcast.net  Mon Apr  2 17:19:45 2007
From: HouseScript at comcast.net (HouseScript at comcast.net)
Date: Mon, 02 Apr 2007 15:19:45 +0000
Subject: [Tutor] A string-manipulation question
Message-ID: <040220071519.29887.46111F1100003596000074BF22007623029C9A01070C9C019D0DA19C@comcast.net>

>>The only "hitch" I see is how one tells that an initial 
>>consonant is a vowel sound or not. (honor vs home)?

The above is exactly what I was thinking about, theres no way I could think of besides creating a dict for the few thousand English words that have this trait.  Then run a search against the dict (the one for words like honor), then something like if the words on this list then just add ay to the end of the word and jump to the next word in the sequence.  And if the word's not on that list then just following the regular pig latin rules.

I apologize if what I'm saying doesn't make too much sense.  I've been teaching myself python for all of 3 weeks.  Its been long days and even longer nights of pure confusion at some times...but only because I NEED to know everything I can.  Imaginary numbers blew my mind lol.

-------------- Original message -------------- 
From: Bob Gailer <bgailer at alum.rpi.edu> 

> HouseScript at comcast.net wrote: 
> > Alan Gilfoy wrote: 
> > 
> > > Is there a way in Python to separate a string into its component words. 
> > you could do something like this: 
> > >>> x = Is there a way in Python to seperate a string into its 
> > compontent words. 
> > >>> x.split() 
> > that would yield: 
> > ['Is', 'there', 'a', 'way', 'in', 'Python', 'to', 'separate', 'a', 
> > 'string', 'into', 'its', 'component', 'words.'] 
> > As far as teh translating to pig latin.....well I honestly don't know. 
> From Wikipedia, the rules are: 
> 
> 1. For words that begin with consonant 
> sounds, move the initial 
> consonant or consonant cluster 
> to the end of the 
> word and add "ay." Examples: 
> * fatso ??? atso-fay 
> * button ??? /utton-bay/ 
> * star ??? /ar-stay/ 
> * three ??? /ee-thray/ 
> * question ??? /estion-quay/ 
> 2. For words that begin with vowel 
> sounds (including silent 
> consonants ), simply 
> add the syllable "ay" to the end of the word. 
> * eagle ??? /eagle-ay/ 
> * America ??? /America-ay/ 
> * honor ??? /honor-ay/ 
> 
> Seems pretty straightforward to translate to Python (or any other 
> language). The only "hitch" I see is how one tells that an initial 
> consonant is a vowel sound or not. (honor vs home)? 
> 
> opehay isthay elphay 
> 
> -- 
> Bob Gailer 
> 510-978-4454 
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070402/a7e30277/attachment.htm 

From chad.hughes at pnl.gov  Mon Apr  2 17:31:11 2007
From: chad.hughes at pnl.gov (Hughes, Chad O)
Date: Mon, 2 Apr 2007 08:31:11 -0700
Subject: [Tutor] C coded extinsion question
Message-ID: <B9E8CAB897D169409548B45B8AB86490099493@EMAIL02.pnl.gov>


I am writing a c type extension for Python deriving from the list class (using PyList_Type.tp_init).  I have the need to overload the ?+? operator (To add two numbers stored as binary lists ? instead of concatenation).  I have tried the following: 

static PyMethodDef BinaryList_methods[] = {
	...
	{"__add__", (PyCFunction)BinaryList___add__, METH_VARARGS,
		PyDoc_STR("__add__(self,other) -> BinaryList")},
	...
	{NULL,	NULL},
};

This the BinaryList___add__ function is called if I use the __add__ explicitly but the list base class __add__ is called for the ?+? operator, for example:

a = BinaryList([1,0,0,0])
b = BinaryList([0,0,0,1])
print a.__add__(b)  #prints [1,0,0,1]
print a + b               #prints [1,0,0,0,0,0,0,1]


I read this:
object.h -- Added tp_call member to the typeobject struct
This along with a minor change to the ceval.c allows overloading
of the function call operator for any class.

Can anyone either tell me what I am doing wrong and or give me an example of how to properly overload an operator in a c coded extension?

From carroll at tjc.com  Mon Apr  2 19:21:58 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 2 Apr 2007 10:21:58 -0700 (PDT)
Subject: [Tutor] Fw: 2) 'WHICH MULTI'
In-Reply-To: <20070330231751.95294.qmail@web86114.mail.ird.yahoo.com>
Message-ID: <Pine.LNX.4.44.0704021012560.25797-100000@violet.rahul.net>

On Fri, 30 Mar 2007, ALAN GAULD wrote:

> One of my tutorial users has come upon a really weird bug.
> 
> He has sent a transcript oif his session. Notice that wx 
> is not defined yet doing help(wx) produces a strange message.

Very weird.  Here's what I get, weird in a different way...

___________________________________________________________
ActivePython 2.5.0.0 (ActiveState Software Inc.) based on
Python 2.5 (r25:51908, Mar  9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print wx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wx' is not defined
>>> dir(wx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wx' is not defined
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Welcome to Python 2.5!  This is the online help utility.
[etc.]

help> wx
[pause of about 6 seconds]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python25\lib\site.py", line 355, in __call__
    return pydoc.help(*args, **kwds)
  File "C:\Python25\Lib\pydoc.py", line 1649, in __call__
    self.interact()
  File "C:\Python25\Lib\pydoc.py", line 1667, in interact
    self.help(request)
  File "C:\Python25\Lib\pydoc.py", line 1688, in help
    elif request: doc(request, 'Help on %s:')
  File "C:\Python25\Lib\pydoc.py", line 1481, in doc
    pager(title % desc + '\n\n' + text.document(object, name))
  File "C:\Python25\Lib\pydoc.py", line 324, in document
    if inspect.ismodule(object): return self.docmodule(*args)
  File "C:\Python25\Lib\pydoc.py", line 1084, in docmodule
    contents.append(self.docother(value, key, name, maxlen=70))
  File "C:\Python25\Lib\pydoc.py", line 1283, in docother
    repr = self.repr(object)
  File "C:\Python25\Lib\repr.py", line 24, in repr
    return self.repr1(x, self.maxlevel)
  File "C:\Python25\Lib\pydoc.py", line 951, in repr1
    return cram(stripid(repr(x)), self.maxother)
  File "C:\Python25\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__
    def __repr__(self):                 return 'wx.Colour' + str(self.Get(True))

  File "C:\Python25\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get
    return _gdi_.Colour_Get(*args, **kwargs)
TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *'
>>>



From carroll at tjc.com  Mon Apr  2 19:45:38 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 2 Apr 2007 10:45:38 -0700 (PDT)
Subject: [Tutor] hashlib weirdness
In-Reply-To: <20070331001223.C53C71706B@smtp2.hushmail.com>
Message-ID: <Pine.LNX.4.44.0704021041130.25797-100000@violet.rahul.net>

On 30 Mar 2007, Greg Perry wrote:

> Here's one that has me stumped.
> 
> I am writing a forensic analysis tool that takes either a file or a
> directory as input, then calculates a hash digest based on the contents
> of each file.
> 
> I have created an instance of the hashlib class:
> 
> m = hashlib.md5()
> 
> I then load in a file in binary mode:
> 
> f = open("c:\python25\python.exe", "rb")
> 
> According to the docs, the hashlib update function will update the hash
> object with the string arg.  So:
> 
> m.update(f.read())
> m.hexdigest()
> 
> The md5 hash is not correct for the file.

Odd.  It's correct for me:

In Python:

>>> import hashlib
>>> m = hashlib.md5()
>>> f = open("c:\python25\python.exe", "rb")
>>> m.update(f.read())
>>> m.hexdigest()
'7e7c8ae25d268636a3794f16c0c21d7c'

Now, check against the md5 as calculated by the md5sum utility:

>md5sum c:\Python25\python.exe
\7e7c8ae25d268636a3794f16c0c21d7c *c:\\Python25\\python.exe


> f.seek(0)
> hashlib.md5(f.read()).hexdigest()

No difference here:

>>> f.close()
>>> f = open("c:\python25\python.exe", "rb")
>>> hashlib.md5(f.read()).hexdigest()
'7e7c8ae25d268636a3794f16c0c21d7c'


From gregp at liveammo.com  Mon Apr  2 20:34:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 02 Apr 2007 14:34:00 -0400
Subject: [Tutor] hashlib weirdness
Message-ID: <20070402182948.C35D61704E@smtp2.hushmail.com>

Thanks Terry, others have pointed out the same thing.  The stock Python 2.5 interpreter functions properly; my issue seems to be with the IDE I am using, that is where I've been able to nail down the problem so far.

-----Original Message-----
From: Terry Carroll

On 30 Mar 2007, Greg Perry wrote:
>
>> Here's one that has me stumped.
> 
> I am writing a forensic analysis tool that takes either a file or a
> directory as input, then calculates a hash digest based on the contents
> of each file.
> 
> I have created an instance of the hashlib class:
> 
> m = hashlib.md5()
> 
> I then load in a file in binary mode:
> 
> f = open("c:\python25\python.exe", "rb")
> 
> According to the docs, the hashlib update function will update the hash
> object with the string arg.  So:
> 
> m.update(f.read())
> m.hexdigest()
> 
> The md5 hash is not correct for the file.
>
>Odd.  It's correct for me:
>
>In Python:
>
>>>> import hashlib
>>> m = hashlib.md5()
>>> f = open("c:\python25\python.exe", "rb")
>>> m.update(f.read())
>>> m.hexdigest()
>'7e7c8ae25d268636a3794f16c0c21d7c'
>
>Now, check against the md5 as calculated by the md5sum utility:
>
>>md5sum c:\Python25\python.exe
>\7e7c8ae25d268636a3794f16c0c21d7c *c:\\Python25\\python.exe
>
>
>> f.seek(0)
> hashlib.md5(f.read()).hexdigest()
>
>No difference here:
>
>>>> f.close()
>>> f = open("c:\python25\python.exe", "rb")
>>> hashlib.md5(f.read()).hexdigest()
>'7e7c8ae25d268636a3794f16c0c21d7c'
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>



From allison.william at comcast.net  Mon Apr  2 20:53:22 2007
From: allison.william at comcast.net (William Allison)
Date: Mon, 02 Apr 2007 14:53:22 -0400
Subject: [Tutor] datetime.timedelta Output Format
In-Reply-To: <4610DC19.6020807@tds.net>
References: <461044B4.8080900@comcast.net> <4610DC19.6020807@tds.net>
Message-ID: <46115122.90603@comcast.net>

Kent Johnson wrote:
>
> It looks like Gustavo Niemeyer's dateutil module will at least do the 
> year/month/day calculation if not the formatting:
>
> In [1]: from datetime import date
> In [2]: from dateutil import relativedelta
> In [3]: now = date.today()
> In [9]: rd = relativedelta.relativedelta(now, tafmsd)
> In [10]: rd
> Out[10]: relativedelta(years=+13, months=+1, days=+10)
>
> http://labix.org/python-dateutil
>
> Kent
>
Thank you, seems to be just what I was looking for!
Will

From carroll at tjc.com  Mon Apr  2 21:26:58 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 2 Apr 2007 12:26:58 -0700 (PDT)
Subject: [Tutor] hashlib weirdness
In-Reply-To: <20070402182948.C35D61704E@smtp2.hushmail.com>
Message-ID: <Pine.LNX.4.44.0704021226430.27116-100000@violet.rahul.net>

On 2 Apr 2007, Greg Perry wrote:

> Thanks Terry, others have pointed out the same thing.  The stock Python
> 2.5 interpreter functions properly; my issue seems to be with the IDE I
> am using, that is where I've been able to nail down the problem so far.

Just curious, what's the IDE?



From brian_macanna at hotmail.com  Tue Apr  3 02:08:10 2007
From: brian_macanna at hotmail.com (Brian McDermott)
Date: Tue, 03 Apr 2007 01:08:10 +0100
Subject: [Tutor] apihelper module for python
Message-ID: <BAY21-F18DA364B38CE287BE55A2389670@phx.gbl>

i have looked and been unable to find this module anywhere, can somebody 
please direct me to where i can download it, thanks

_________________________________________________________________
Message offline contacts without any fire risk! 
http://www.communicationevolved.com/en-ie/


From kent37 at tds.net  Tue Apr  3 03:46:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 02 Apr 2007 21:46:28 -0400
Subject: [Tutor] apihelper module for python
In-Reply-To: <BAY21-F18DA364B38CE287BE55A2389670@phx.gbl>
References: <BAY21-F18DA364B38CE287BE55A2389670@phx.gbl>
Message-ID: <4611B1F4.1010107@tds.net>

Brian McDermott wrote:
> i have looked and been unable to find this module anywhere, can somebody 
> please direct me to where i can download it, thanks

A little context might help here, but I guess you are looking for the 
apihelper referenced in Chapter 4 of Dive Into Python. This module is 
included in the download for the book:
http://diveintopython.org/download/diveintopython-examples-5.4.zip

Kent

From willshattuck at gmail.com  Wed Apr  4 00:05:16 2007
From: willshattuck at gmail.com (Will Shattuck)
Date: Tue, 3 Apr 2007 15:05:16 -0700
Subject: [Tutor] Building Project Management Software
Message-ID: <ba2bc7f40704031505t2cc60ec9u4c5e6cc4d254eeab@mail.gmail.com>

Hi all,

I'm a beginning Python programmer and a beginning programmer in
general.  I have a need to fill, but I can't seem to find any software
out there that currently meets my needs.  So, I'm wanting to try to
build it using Python, however I am very new to everything.

So I want this Project Management software to be able to hold multiple
projects, with tasks and sub tasks.  In those tasks are placed for
notes, and notes about progress, etc.

What I don't know how to do is where to start.  I know this is
probably a very open ended question, but where would the best place to
start be?

Thanks,
Will

-- 
Will Shattuck
http://www.willshattuck.com
http://www.willthecomputerguy.com

"When you get to your wit's end,
you'll find God lives there."

From andreas at kostyrka.org  Wed Apr  4 00:18:49 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Wed, 4 Apr 2007 00:18:49 +0200
Subject: [Tutor] Building Project Management Software
In-Reply-To: <ba2bc7f40704031505t2cc60ec9u4c5e6cc4d254eeab@mail.gmail.com>
References: <ba2bc7f40704031505t2cc60ec9u4c5e6cc4d254eeab@mail.gmail.com>
Message-ID: <20070403221849.GD17286@andi-lap.la.revver.com>

* Will Shattuck <willshattuck at gmail.com> [070404 00:08]:
> Hi all,
> 
> I'm a beginning Python programmer and a beginning programmer in
> general.  I have a need to fill, but I can't seem to find any software
> out there that currently meets my needs.  So, I'm wanting to try to
> build it using Python, however I am very new to everything.

Have you considered Trac?

Andreas

From alan.gauld at btinternet.com  Wed Apr  4 01:15:31 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 4 Apr 2007 00:15:31 +0100
Subject: [Tutor] Building Project Management Software
References: <ba2bc7f40704031505t2cc60ec9u4c5e6cc4d254eeab@mail.gmail.com>
Message-ID: <euun6p$63g$1@sea.gmane.org>


"Will Shattuck" <willshattuck at gmail.com> wrote

> I'm a beginning Python programmer and a beginning programmer in
> general.  I have a need to fill, but I can't seem to find any 
> software
> out there that currently meets my needs.  So, I'm wanting to try to
> build it using Python, however I am very new to everything.
>
> So I want this Project Management software to be able to hold 
> multiple
> projects, with tasks and sub tasks.  In those tasks are placed for
> notes, and notes about progress, etc.

Given there is a plethora of project management software available at
any price ranging from free to thousands of dollars can you give us
some idea of why you can't use a standard package? Are there any
special features you need?

> What I don't know how to do is where to start.  I know this is
> probably a very open ended question, but where would the
> best place to start be?

If you really want to build your own - and its quite an ambitious
project for a newbie - The first thing will be to learn to program
in Python. Write small applications first. They may be related
to your big project - just manually maintaining a list of tasks
sorted by due date would be a good start. Only after you feel
comfortable using Python for basic tools should you start to
think about a major project. And even then break it down into
its most minimal form, use it as a tool to record the base data
and automate a few baic tasks initially then add more automation
over time. Don't worry too much about GUI interfaces or Web
front ends they can be added later.

Finally consider starting with an existing tool and tweaking it.
WhatWhat status is an example of a free package that
takes very different approach to project management from
apps like MS Project etc. and is written in Python

http://cleverdevil.org/whatwhat

For a more traditional option look at GanntProject

http://ganttproject.biz/

Its in Java rather than Python.

And now for something completely different:

http://faces.homeip.net/

also in Python....

Do any of these come close to what you want? If so you may
be better starting there.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




From wescpy at gmail.com  Wed Apr  4 01:38:19 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 3 Apr 2007 16:38:19 -0700
Subject: [Tutor] Building Project Management Software
In-Reply-To: <ba2bc7f40704031505t2cc60ec9u4c5e6cc4d254eeab@mail.gmail.com>
References: <ba2bc7f40704031505t2cc60ec9u4c5e6cc4d254eeab@mail.gmail.com>
Message-ID: <78b3a9580704031638j6e5f70c4w8eebef00811df621@mail.gmail.com>

> So I want this Project Management software to be able to hold multiple
> projects, with tasks and sub tasks.  In those tasks are placed for
> notes, and notes about progress, etc.


trac is good.  if you want barebones issue mgmt, there's RoundUp (
http://roundup.sf.net ).  for something on the other end, a full
blown, yet simple and quick CRM and ERP system is TinyERP (
http://www.tinyerp.com ).

good luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From pine508 at hotmail.com  Wed Apr  4 07:14:39 2007
From: pine508 at hotmail.com (Che M)
Date: Wed, 04 Apr 2007 01:14:39 -0400
Subject: [Tutor] passing arguments via an instance of a class
Message-ID: <BAY18-F198EF94783B4013402D32FE0660@phx.gbl>

Hi.  Alan G helped me a week or two back with how to pass a list of points 
to a class which could use it to draw a graph..  Now I am doing it again, 
but with different code (based on an example of embedding a matplotlib plot 
in wxPython) and having trouble.

That same basic issue is:  I need to create an instance of a class and in so 
doing pass the class two lists of numbers to serve as points in the graph.  
However, I can't get it to work because in the various ways I've tried it, 
the class is either not expecting to be passed a list as an argument, or it 
is not providing the list to its draw() method so nothing is plotted.

My problem is I don't understand how to create the class such that it a) 
expects to be passed two lists, and b) hands those lists off to its draw() 
method to use in drawing the graph.  Relevant code and some errors I got 
provided below.

-------------------------------------------------------
class PlotPanel(wx.Panel):

    def __init__(self,parent, xpoints=[], ypoints=[], id = -1, color = 
None,\
        dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
        wx.Panel.__init__(self, parent, id = id, style = style, **kwargs)
        self.figure = Figure(None, dpi)
        self.xpoints = xpoints
        self.ypoints = ypoints
       #the NoRepaintCanvas class code snipped out
        self.canvas = NoRepaintCanvas(self, -1, self.figure)
        self.SetColor(color)
        self.Bind(wx.EVT_IDLE, self._onIdle)
        self.Bind(wx.EVT_SIZE, self._onSize)
        self._resizeflag = True
        self._SetSize()

# ... various code snipped which determines plot, size, color, etc...

#This draw method is what does the work of drawing the points.

    def draw(self):
        if not hasattr(self, 'subplot'):
            self.subplot = self.figure.add_subplot(111)

#if the following two lines were not commented out, the graph works fine
#but the point is to have these passed in by a user choice, not just
#always these same points.

        #x = [1,2,3]
        #y = [5,10,15]

#this next just plots a red line using whatever x,y points given

        self.subplot.plot(x,y, '-r')

#This is now the button which is supposed to feed the PlotPanel
#the points it needs.  It is a method of the wxFrame (code not shown)

def OnButton1Button(self, event):
#these are the points I want to be plotted when I push this button
        xpoints=[2,4,6]
        ypoints=[10,20,30]
        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)
        self.notebook1.AddPage(imageId=-1, page=self.weightplot,
                select=True, text='Test Plot')

--------------------------------------------------------------------------------------------

As is, when I press that button I get this error:

Name Error:  global name xpoints is not defined.

Suggesting the draw() method never got passed the xpoints (or the ypoints) 
via the button press.
I think I'm not setting up either the PlotPanel's __init__ or the draw() 
method or something to be able to receive these x and y lists, but I've 
tried it a number of different ways and can't figure it out.

Any advice is appreciated.
-Che

_________________________________________________________________
MSN is giving away a trip to Vegas to see Elton John.? Enter to win today. 
http://msnconcertcontest.com?icid-nceltontagline


From john at fouhy.net  Wed Apr  4 07:23:38 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 4 Apr 2007 17:23:38 +1200
Subject: [Tutor] passing arguments via an instance of a class
In-Reply-To: <BAY18-F198EF94783B4013402D32FE0660@phx.gbl>
References: <BAY18-F198EF94783B4013402D32FE0660@phx.gbl>
Message-ID: <5e58f2e40704032223n556414f6y99017b8a8d6c5ffb@mail.gmail.com>

On 04/04/07, Che M <pine508 at hotmail.com> wrote:
> As is, when I press that button I get this error:
>
> Name Error:  global name xpoints is not defined.

Can you post the full error message (including stack trace and line
numbers) and the code for the last function in the stack trace?
(i.e. the code where the NameError occurs)

-- 
John.

From alan.gauld at btinternet.com  Wed Apr  4 10:02:02 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 4 Apr 2007 09:02:02 +0100
Subject: [Tutor] passing arguments via an instance of a class
References: <BAY18-F198EF94783B4013402D32FE0660@phx.gbl>
Message-ID: <euvm20$qic$1@sea.gmane.org>


"Che M" <pine508 at hotmail.com> wrote

> My problem is I don't understand how to create
> the class such that it a) expects to be passed two lists,

You've done that correctly by creating an init that takes xpoints
and ypoints and storing those as members of self.

> b) hands those lists off to its draw() method to use in
> drawing the graph.

You don't need to 'hand them off' to draw because draw
is part of self, therefore it can access self.xpoints and
self.ypoints directly.

>    def __init__(self,parent, xpoints=[], ypoints=[], id = -1,
>                     color = None, dpi = None,
>                     style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
>          wx.Panel.__init__(self, parent, id = id, style = style, 
> **kwargs)

I don't think you need to specify id and style since kwargs will
do that for you. But it shouldn't do any harm, its just extra work.

>        self.figure = Figure(None, dpi)
>        self.xpoints = xpoints
>        self.ypoints = ypoints

This is where you store the lists of points.

>    def draw(self):
>#if the following two lines were not commented out, the graph works 
>fine
>        #x = [1,2,3]
>        #y = [5,10,15]

you could do:

x = self.xpoints
y = self.ypoints

Or just wait and use seld.xpoints etc at the point of use.

>#this next just plots a red line using whatever x,y points given
>        self.subplot.plot(x,y, '-r')

So this could just be

self.subplot.plot(self.xpoints,self.ypoints,'-r')


#This is now the button which is supposed to feed the PlotPanel
#the points it needs.  It is a method of the wxFrame (code not shown)
>
>def OnButton1Button(self, event):
>#these are the points I want to be plotted when I push this button
>        xpoints=[2,4,6]
>        ypoints=[10,20,30]
>        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)

But this needs to use self to access the member values:

        self.weightplot = 
PlotPanel(self.notebook1,self.xpoints,self.ypoints)

> As is, when I press that button I get this error:
>
> Name Error:  global name xpoints is not defined.

Are you sure you get that error with the code you've posted?
It looks like the error I'd expect before yopu created the 2
hard coded lists above?

> Suggesting the draw() method never got passed the
> xpoints (or the ypoints) via the button press.

It doesn't, it should access them directly via self.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From kent37 at tds.net  Wed Apr  4 12:24:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 04 Apr 2007 06:24:15 -0400
Subject: [Tutor] passing arguments via an instance of a class
In-Reply-To: <euvm20$qic$1@sea.gmane.org>
References: <BAY18-F198EF94783B4013402D32FE0660@phx.gbl>
	<euvm20$qic$1@sea.gmane.org>
Message-ID: <46137CCF.2080604@tds.net>

Alan Gauld wrote:
> #This is now the button which is supposed to feed the PlotPanel
> #the points it needs.  It is a method of the wxFrame (code not shown)
>> def OnButton1Button(self, event):
>> #these are the points I want to be plotted when I push this button
>>        xpoints=[2,4,6]
>>        ypoints=[10,20,30]
>>        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)
> 
> But this needs to use self to access the member values:
> 
>         self.weightplot = 
> PlotPanel(self.notebook1,self.xpoints,self.ypoints)

A minor correction to an otherwise excellent explanation - xpoints and 
ypoints are not member variables here - they are ordinary local 
variables - so 'self' is not needed.

Kent

From alan.gauld at btinternet.com  Wed Apr  4 14:07:24 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 4 Apr 2007 13:07:24 +0100
Subject: [Tutor] passing arguments via an instance of a class
References: <BAY18-F198EF94783B4013402D32FE0660@phx.gbl><euvm20$qic$1@sea.gmane.org>
	<46137CCF.2080604@tds.net>
Message-ID: <ev04e2$k47$1@sea.gmane.org>


"Kent Johnson" <kent37 at tds.net> wrote

>>> #these are the points I want to be plotted when I push this button
>>>        xpoints=[2,4,6]
>>>        ypoints=[10,20,30]
>>>        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)
>>
>> But this needs to use self to access the member values:
>>
>>         self.weightplot =
>> PlotPanel(self.notebook1,self.xpoints,self.ypoints)
>
> A minor correction to an otherwise excellent explanation - xpoints 
> and
> ypoints are not member variables here - they are ordinary local
> variables - so 'self' is not needed.

I was assuming that the two locals were temporary stop gaps and
that the actual requirement was for the original xpoints to be used.
If the locals are intentional then yes indeed, the self is not needed
in this case.

Thanks Kent,

Alan G. 



From kent37 at tds.net  Wed Apr  4 14:34:10 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 4 Apr 2007 07:34:10 -0500
Subject: [Tutor] passing arguments via an instance of a class
Message-ID: <20070404073410.ETJYF.1573.root@webfep12>

Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
> 
>>>> #these are the points I want to be plotted when I push this button
>>>>        xpoints=[2,4,6]
>>>>        ypoints=[10,20,30]
>>>>        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)
>>> But this needs to use self to access the member values:
>>>
>>>         self.weightplot =
>>> PlotPanel(self.notebook1,self.xpoints,self.ypoints)
>> A minor correction to an otherwise excellent explanation - xpoints 
>> and
>> ypoints are not member variables here - they are ordinary local
>> variables - so 'self' is not needed.
> 
> I was assuming that the two locals were temporary stop gaps and
> that the actual requirement was for the original xpoints to be used.
> If the locals are intentional then yes indeed, the self is not needed
> in this case.

Ah. I was assuming that in the real code this function would pull the desired points from the GUI somewhere, since the function is an event handler and not part of the PlotPanel class. 

Kent

From pine508 at hotmail.com  Wed Apr  4 18:09:56 2007
From: pine508 at hotmail.com (Che M)
Date: Wed, 04 Apr 2007 12:09:56 -0400
Subject: [Tutor] passing arguments via an instance of a class
Message-ID: <BAY18-F158CFB6F775AB672C30CDCE0660@phx.gbl>


John Fouhy said:
>Can you post the full error message (including stack trace and line
>numbers) and the code for the last function in the stack trace?
>(i.e. the code where the NameError occurs)

It is now working (so I won't post the code/errors unless you think it is 
useful for people to see), and the corrected code is shown below.

Alan Gauld said:

>you could do:
>
>x = self.xpoints
>y = self.ypoints
>
>Or just wait and use self.xpoints etc at the point of use.

Thank you, Alan.  My whole problem is not fully understanding the self (to 
paraphrase Socrates...) and making sure to specify it.  I did change this in 
this way.  Also...

>#This is now the button which is supposed to feed the PlotPanel
>#the points it needs.  It is a method of the wxFrame (code not shown)
> >
> >def OnButton1Button(self, event):
> >#these are the points I want to be plotted when I push this button
> >        xpoints=[2,4,6]
> >        ypoints=[10,20,30]
> >        self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)
>
>But this needs to use self to access the member values:
>
>         self.weightplot = 
>PlotPanel(self.notebook1,self.xpoints,self.ypoints)

Doing it this way didn't work--it gave the error:

AttributeError: 'Frame1' object has no attribute 'xpoints'

because, I think, self in this case refers to the whole frame, and not 
PlotPanel (i.e. notebook1 is an attribute of the Frame but xpoints and 
ypoints are meant to be attributes of PlotPanel).  The button was an object 
under the whole wxFrame (not sure I mentioned that), so self referred to the 
frame, not the PlotPanel, I think.  But writing it this way:

          self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)

did work.  Which is the same situation as what you helped me with last week. 
  The difference in this case is that I was, wrongly, not telling draw() to 
plot self.xpoints (I was giving just xpoints) and the draw() method could 
not know which instance this is from.  Is that right?

To summarize (just to have this clear for myself and other beginners), these 
are the lines which mattered:

1. The init had to have the xpoints and ypoints lists included so it could 
"accept" the lists when needed:

    def __init__(self, parent, xpoints=[], ypoints=[], id = -1, color = 
None,\
        dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):

2. The x and y lists had to refer to self.xpoints and self.ypoints (or I 
could have done it the other
way Alan mentioned):

    x = self.xpoints
    y = self.ypoints

3. I had to have an instance of the PlotPanel which was passed the parent 
notebook and the lists:

    self.weightplot = PlotPanel(self.notebook1,xpoints,ypoints)

4. And then I just added this self.weightplot PlotPanel instance as a page 
to my notebook:

    self.notebook1.AddPage(imageId=-1, page=self.weightplot,
                select=True, text='Test Plot)

Thanks Alan for your help! and John for your offer to debug!--it's great to 
understand this better and to have this simple plot actually display, very 
encouraging.  I guess I really have to work on my "self" control.  :)

-Che

_________________________________________________________________
MSN is giving away a trip to Vegas to see Elton John.? Enter to win today. 
http://msnconcertcontest.com?icid-nceltontagline


From clajo04 at mac.com  Wed Apr  4 21:45:34 2007
From: clajo04 at mac.com (John Clark)
Date: Wed, 4 Apr 2007 15:45:34 -0400
Subject: [Tutor] New York City Python Users Group Meeting
Message-ID: <00c301c776f1$d175e970$fefea8c0@haengma>

Greetings!

The next New York City Python Users Group meeting is this Tuesday, April
10th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd
St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who
are interested in Python to attend. However, we need a list of first and
last names to give to building security to make sure you can gain access to
the building. RSVP to clajo04 at mac.com to add your name to the list. 

More information can be found on the yahoo group page:

 <http://tech.groups.yahoo.com/group/nycpython/>
http://tech.groups.yahoo.com/group/nycpython/

Hope to see you there!

-John

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070404/088fc639/attachment.html 

From alan.gauld at btinternet.com  Thu Apr  5 01:25:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 5 Apr 2007 00:25:29 +0100
Subject: [Tutor] passing arguments via an instance of a class
References: <BAY18-F158CFB6F775AB672C30CDCE0660@phx.gbl>
Message-ID: <ev1c5g$n3q$1@sea.gmane.org>

"Che M" <pine508 at hotmail.com> wrote

> > >def OnButton1Button(self, event):
> > >        self.weightplot = 
> > > PlotPanel(self.notebook1,xpoints,ypoints)
> >
> >But this needs to use self to access the member values:
>
> Doing it this way didn't work--it gave the error:
> because, I think, self in this case refers to the whole frame,

Exactly right, this is what Kent pointed out. I had not noticed
the fact that this was a method of the GUI Frame rather than
of the PlotPanel.

> To summarize

You got it exactly right.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From deliberatus at verizon.net  Thu Apr  5 03:28:21 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 04 Apr 2007 22:28:21 -0300
Subject: [Tutor] windows and python and shebangs, oh my!
Message-ID: <461450B5.9040409@verizon.net>

OK, in a script, we include a special statement telling the shell where 
to go find the interpeter. This is the first line of the script, and is 
a dpecial sort of comment, called informally the shebang. it looks like 
this:
#!C:\path\interpeterprogramname

In windows, this is for the current edition C:\python25\pythonw.exe
so the shebang is
#!C:\python\pythonw.exe

Well, gues what? looking at a little used program, inherited from an 
earlier edition, which pops up the manual for the wiki I am developing, 
the shebang was:
c:\python22\pythonw.exe

Notice it is 22. My installed version is 2.5... hmmm... the path 
indicated does not exist in this computer, and should trigger a error.

OK, I took out the path. It still worked. Hmmm...

OK, I renamed the interpreter file declared in the shebang to a non 
existent file name. it still worked. WHAT THE MERRY HELL?!?

At a loss, it then occurred to me that the program is a .py name 
extension. When the auto installer installed python it may have created 
an association between that name extension and the correct interpreter 
automatically, so a interpreter declaration line is not required in 
windows, unlike my beloved FreeBSD that critter my server on the web 
speaks with only a slightly obsolete accent. Hmmm...

So work with me, windows Pythonistas. CAN I rely on windows definitely 
and reliably having .py files associated with the windows python 
interpreter, so the script does not need a shebang declaration? Can I 
skip this part of the configure/install process of the application and 
count on it working reliably?

If so, my task of designing the autoinstaller script just got a LOT simpler.



-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From john at fouhy.net  Thu Apr  5 04:35:20 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 5 Apr 2007 14:35:20 +1200
Subject: [Tutor] windows and python and shebangs, oh my!
In-Reply-To: <461450B5.9040409@verizon.net>
References: <461450B5.9040409@verizon.net>
Message-ID: <5e58f2e40704041935x306e616r431771ce01e2f418@mail.gmail.com>

On 05/04/07, Kirk Bailey <deliberatus at verizon.net> wrote:
> So work with me, windows Pythonistas. CAN I rely on windows definitely
> and reliably having .py files associated with the windows python
> interpreter, so the script does not need a shebang declaration? Can I
> skip this part of the configure/install process of the application and
> count on it working reliably?

As far as I'm aware, Microsoft Windows doesn't follow the shebang
custom at all.  IOW, that line doesn't do anything.  You should be
able to rely on the file extensions if python was installed normally
(i.e. with the installer).

-- 
John.

From listsdl04 at yahoo.de  Thu Apr  5 05:34:53 2007
From: listsdl04 at yahoo.de (Guba Castro)
Date: Thu, 05 Apr 2007 11:34:53 +0800
Subject: [Tutor] Newbie question concerning text covering multiple lines
Message-ID: <1175744093.2314.8.camel@ubox>

Hello,

I recently started teaching myself Python with Michael Dawson's 'Python
Programming for the Absolute Beginner'.

My problem is that I am running Python 2.5 under Linux while the book is
based on Python 2.2.3. Apparently this means that I cannot just follow
the programming examples the author gives.

While I like the book and intent to continue using it, I was wondering
which online resources I should consult in order to bridge the gap. So
far I am stuck with the Python Tutorial at http://docs.python.org/tut/
which, however, doesn't care too precisely to my needs.

Would you happen to have any suggestions for me?

Many thanks,

Guba






	
		
___________________________________________________________ 
Der fr?he Vogel f?ngt den Wurm. Hier gelangen Sie zum neuen Yahoo! Mail: http://mail.yahoo.de

From kent37 at tds.net  Thu Apr  5 04:56:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 04 Apr 2007 22:56:31 -0400
Subject: [Tutor] Newbie question concerning text covering multiple lines
In-Reply-To: <1175744093.2314.8.camel@ubox>
References: <1175744093.2314.8.camel@ubox>
Message-ID: <4614655F.7020409@tds.net>

Guba Castro wrote:
> Hello,
> 
> I recently started teaching myself Python with Michael Dawson's 'Python
> Programming for the Absolute Beginner'.
> 
> My problem is that I am running Python 2.5 under Linux while the book is
> based on Python 2.2.3. Apparently this means that I cannot just follow
> the programming examples the author gives.

You should be able to use the book with Python 2.5. Python releases 
rarely break old code, rather they add new capabilities. What kinds of 
trouble are you having? If you tell us the specific problems you are 
running into we can help.

> While I like the book and intent to continue using it, I was wondering
> which online resources I should consult in order to bridge the gap. So
> far I am stuck with the Python Tutorial at http://docs.python.org/tut/
> which, however, doesn't care too precisely to my needs.
> 
> Would you happen to have any suggestions for me?

Each Python release includes a What's New document that describes the 
changes in that release. You can find them by clicking on each version 
number here:
http://www.python.org/doc/versions/

Several good beginners tutorials are listed here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Kent

Kent

From rabidpoobear at gmail.com  Thu Apr  5 08:52:11 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 05 Apr 2007 01:52:11 -0500
Subject: [Tutor] windows and python and shebangs, oh my!
In-Reply-To: <461450B5.9040409@verizon.net>
References: <461450B5.9040409@verizon.net>
Message-ID: <46149C9B.2030901@gmail.com>

Kirk Bailey wrote:
> OK, in a script, we include a special statement telling the shell where 
> to go find the interpeter. This is the first line of the script, and is 
> a dpecial sort of comment, called informally the shebang. it looks like 
> this:
> #!C:\path\interpeterprogramname
>
> In windows, this is for the current edition C:\python25\pythonw.exe
> so the shebang is
> #!C:\python\pythonw.exe
>
> Well, gues what? looking at a little used program, inherited from an 
> earlier edition, which pops up the manual for the wiki I am developing, 
> the shebang was:
> c:\python22\pythonw.exe
>
> Notice it is 22. My installed version is 2.5... hmmm... the path 
> indicated does not exist in this computer, and should trigger a error.
>
> OK, I took out the path. It still worked. Hmmm...
>
> OK, I renamed the interpreter file declared in the shebang to a non 
> existent file name. it still worked. WHAT THE MERRY HELL?!?
>
> At a loss, it then occurred to me that the program is a .py name 
> extension. When the auto installer installed python it may have created 
> an association between that name extension and the correct interpreter 
> automatically, so a interpreter declaration line is not required in 
> windows, unlike my beloved FreeBSD that critter my server on the web 
> speaks with only a slightly obsolete accent. Hmmm...
>
> So work with me, windows Pythonistas. CAN I rely on windows definitely 
> and reliably having .py files associated with the windows python 
> interpreter, so the script does not need a shebang declaration? Can I 
> skip this part of the configure/install process of the application and 
> count on it working reliably?

Kirk:
I addressed this issue in reply to your readlines question earlier:

""""""""""""""""""""""""""""""
Kirk Bailey wrote:
> #!C:\Python25\pythonw.exe
#! is only for Unix, it's pointless here.
""""""""""""""""""""""""""""""

Please don't skip over sections of  my replies, I occasionally do say 
useful things. ;)
-Luke

From alan.gauld at btinternet.com  Thu Apr  5 10:27:38 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 5 Apr 2007 09:27:38 +0100
Subject: [Tutor] windows and python and shebangs, oh my!
References: <461450B5.9040409@verizon.net>
Message-ID: <ev2bu0$dbr$1@sea.gmane.org>

"Kirk Bailey" <deliberatus at verizon.net> wrote

> OK, in a script, we include a special statement telling the shell 
> where
> to go find the interpeter. This is the first line of the script, and 
> is
> a dpecial sort of comment, called informally the shebang.

Yes, but it is not a Python feature it is a Unix thing.
When you execute a script (of any kind) in Unix the Unix
shell(*) reads the first line and if its a shebang transfers
control to the appropriate interpreter.

(*) And not all Unix shells adhere to the convention,
but thankfully the vast majority do. The SVR4 Bourne
shell didn't as I recall.

> In windows, this is for the current edition C:\python25\pythonw.exe
> so the shebang is
> #!C:\python\pythonw.exe

This is often done purely as a convention that shows what
version of Python the script was created for.
Python does nothing with it, it is only a comment.

> At a loss, it then occurred to me that the program is a .py name
> extension. When the auto installer installed python it may have 
> created
> an association between that name extension and the correct 
> interpreter
> automatically,

Correct, or you can do it manually. tHat is the only way that Windows
associates files with commands.

> So work with me, windows Pythonistas. CAN I rely on windows 
> definitely
> and reliably having .py files associated with the windows python
> interpreter,

No, the association can be changed by any user or install script.

But in practice it rarely is changed so you can habe a good chance of 
success.
If you really want to be sure the associations are stored in the 
registry.
You can look them up and change them (or add a missing one) as you 
need.

> If so, my task of designing the autoinstaller script just got a LOT 
> simpler.

On Windows the answer is usually in the registry somewhere, you
just need to figure out where to look!

Alan G. 



From alan.gauld at btinternet.com  Thu Apr  5 10:32:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 5 Apr 2007 09:32:29 +0100
Subject: [Tutor] Newbie question concerning text covering multiple lines
References: <1175744093.2314.8.camel@ubox> <4614655F.7020409@tds.net>
Message-ID: <ev2c74$ei4$1@sea.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote

> Several good beginners tutorials are listed here:
> http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

But very few of them will have been updated to reflect 
changes in 2.5. My own tutor is accurate for 2.3.
This is precisely because, as Kent said, the changes 
in Python are nearly always backwards compatible, so 
you can use old code in a new version.

If you came across something broken between 2.2 
and 2.5 you are very unlucky. What was it?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From jmutter at uakron.edu  Thu Apr  5 15:35:57 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Thu, 5 Apr 2007 09:35:57 -0400
Subject: [Tutor] Tutor Digest, Vol 38, Issue 2
In-Reply-To: <mailman.19483.1175471544.32030.tutor@python.org>
References: <mailman.19483.1175471544.32030.tutor@python.org>
Message-ID: <DA90B14F-0449-4E9F-BA3D-A40D6C017FB5@uakron.edu>

>
>
> Message: 3
> Date: Sun, 1 Apr 2007 16:42:56 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Tutor Digest, Vol 38, Issue 1
> To: tutor at python.org
> Message-ID: <euoju5$a7c$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
>
> "Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote
>
>>>>> s1 = "some line\n"
>>>>> s2 = "some line"
>>>>> s1.endswith("line"), s2.endswith("line")
>> (False, True)
>>
>> Just skip the if and simply rstrip the string.
>

see below

> Or add \n to the endswith() test string if you really only
> want to strip the newline in those cases....
>
> Alan G.
>
>
>
> ------------------------------
>
> Message: 4
> Date: Sun, 1 Apr 2007 16:46:05 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Tutor Digest, Vol 38, Issue 1
> To: tutor at python.org
> Message-ID: <euok41$are$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
> "Jay Mutter III" <jmutter at uakron.edu> wrote
>
>> inp = open('test.txt','r')
>> s = inp.readlines()
>> for line in s:
>>     if line.endswith('No.'):
>>         line = line.rstrip()
>>     print line
>
> BTW,
> You do know that you can shorten that considerably?
> With:
>
> for line in open('test.txt'):
>    if line.endswith('No.\n'):
>       line = line.rstrip()
>    print line
>

Whether I attempt to just strip the string or attempt to

if line.endswith('No.\r'):
     line = line.rstrip()

It doesn't work.
Note - I tried \n, \r and \n\r although text wrangler claims that it  
does have unix line endings
When I used tr to do a few things \n or \r worked fine
I tried sed and it didn't work but from the command line in sed using  
ctrl-v and ctrl-j to insert the  line feed it worked
although i then could not figure out how to do the same in a script.
It is as if the python interpreter doesn't recognize the escaped n  
(or r) as a line feed.
This is an imac running python 2.3.5 under OS-X 10.4.9

Thanks again

> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
> ------------------------------
>
> Message: 5
> Date: 01 Apr 2007 12:17:00 -0400
> From: "Greg Perry" <gregp at liveammo.com>
> Subject: [Tutor] Communication between classes
> To: <tutor at python.org>
> Message-ID: <20070401161218.5D9C117051 at smtp2.hushmail.com>
>
> Hi again,
>
> I am still in the process of learning OOP concepts and reasons why  
> classes should be used instead of functions etc.
>
> One thing that is not apparent to me is the best way for classes to  
> communicate with each other.  For example, I have created an Args  
> class that sets a variety of internal variables (__filename,  
> __outputdir etc) by parsing the argv array from th command line.   
> What would be the preferred mechanism for returning or passing  
> along those variables to another class?  Maybe by a function method  
> that returns all of those variables?
>
>
>
>
>
> ------------------------------
>
> Message: 6
> Date: Sun, 01 Apr 2007 20:46:21 +0200
> From: Andrei <project5 at redrival.net>
> Subject: Re: [Tutor] Communication between classes
> To: tutor at python.org
> Message-ID: <euould$au7$1 at sea.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Hi Greg,
>
> Greg Perry wrote:
>> I am still in the process of learning OOP concepts and
>> reasons why classes should be used instead of functions etc.
>>
>> One thing that is not apparent to me is the best way for
>> classes to communicate with each other.  For example,
>
> Good question. Unfortunately there's no general rule that you can  
> apply
> and end up with an undisputably perfect solution.
>
> Classes should communicate on a need-to-know basis. Take for example a
> RSS feed reader application. You may have a class representing a feed
> and a class representing a post. The feed will know what posts it
> contains, but the post probably won't know what feed it comes from.  
> The
> interface would display a list of feeds (without knowing their
> contents), a list of posts within a feed (this needs to know both feed
> and feed contents) and the contents of a single post (knows only about
> an individual post).
>
>> I have created an Args class that sets a variety of internal
>> variables (__filename, __outputdir etc) by parsing the argv
>
> Be careful with classes that simply act as a container for what are in
> fact global variables. A class should do one thing only (of course  
> what
> you accept as 'one thing' is open for debate) and encapsulate all  
> that's
> necessary for that particular thing. Make sure you're not
> overcomplicating your solution by making classes where they're not
> really necessary.
>
>> array from th command line.  What would be the preferred
>> mechanism for returning or passing along those variables
>
> In some cases only some parts of the information contained in class A
> are relevant to class B - you should pass only that particular
> information, e.g. in the constructor or by setting a property of B. In
> your example, if you have a Reader class that is interested in the
> filename, you would not pass the whole Args object to it - only the
> filename, like this:
>
>      myreader = Reader(Args.FileName)
>
>> to another class?  Maybe by a function method that returns
>> all of those variables?
>
> Use properties if you need getter/setter methods or simple attributes
> otherwise. In your case, I would not make __filename etc. 'private'
> (that's what the double underscore suggests), then write a getter  
> method
> for it - just call it FileName and be done with it. Python idiom  
> here is
> more flexible than other languages.
>
> -- 
> Yours,
>
> Andrei
>
> =====
> Mail address in header catches spam. Real contact info:
> ''.join([''.join(s) for s in zip(
> "poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
> "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
>
>
>
> ------------------------------
>
> Message: 7
> Date: Mon, 2 Apr 2007 00:25:39 +0300
> From: "Eli Brosh" <ebrosh at nana.co.il>
> Subject: [Tutor] A bug or a feature - complex arguments in special
> 	functions
> To: <tutor at python.org>
> Message-ID:
> 	<957526FB6E347743AAB42B212AB54FDA7A5AEB at NANAMAILBACK1.nanamail.co.il>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hello
> I am trying to convert from MATLAB to Python.
> I am using Python 2.4.3 for Windows (Enthought Edition)
> In one of the first programs, I tried to use the special functions  
> from the SciPy  "special" module.
> However, when I tryed:
>
>>> from scipy import *
>>> special.jv(0,1+1j)
>
> I got an error message and python restarted.
>
> The problem did not go away after I installed the latest version of  
> SciPy.
>
> Is there a significant bug in the bessel functions when handling  
> complex arguments ?
> Or, is it some feature that I do not understand ?
>
>
> Thanks
> Eli Brosh
>
>
>
>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: http://mail.python.org/pipermail/tutor/attachments/ 
> 20070402/41c2d81a/attachment.htm
>
> ------------------------------
>
> Message: 8
> Date: 01 Apr 2007 19:24:00 -0400
> From: "Greg Perry" <gregp at liveammo.com>
> Subject: Re: [Tutor] Communication between classes
> To: <project5 at redrival.net>
> Cc: tutor at python.org
> Message-ID: <20070401231953.2698917069 at smtp2.hushmail.com>
>
> That makes sense, thank you for the detailed explanation Andrei.   
> For this simple project I am working on, it looks like the most  
> direct route would be to use functions and only develop classes for  
> the portions of the program that can be reused.
>
> Is it safe to say that classes are only useful for instances where  
> reuse is a key consideration?  From my very limited perspective, it  
> seems that classes are in most cases overkill for simple tasks  
> (such as reading the command line then calculating a hash/checksum  
> to verify integrity).
>
> Thanks again for your very descriptive answer.
>
> -----Original Message-----
> From: Andrei
>
> Hi Greg,
>>
>> Greg Perry wrote:
>> I am still in the process of learning OOP concepts and
>>> reasons why classes should be used instead of functions etc.
>>
>> One thing that is not apparent to me is the best way for
>>> classes to communicate with each other.  For example,
>>
>> Good question. Unfortunately there's no general rule that you can  
>> apply
>> and end up with an undisputably perfect solution.
>>
>> Classes should communicate on a need-to-know basis. Take for  
>> example a
>> RSS feed reader application. You may have a class representing a feed
>> and a class representing a post. The feed will know what posts it
>> contains, but the post probably won't know what feed it comes  
>> from. The
>> interface would display a list of feeds (without knowing their
>> contents), a list of posts within a feed (this needs to know both  
>> feed
>> and feed contents) and the contents of a single post (knows only  
>> about
>> an individual post).
>>
>>> I have created an Args class that sets a variety of internal
>>> variables (__filename, __outputdir etc) by parsing the argv
>>
>> Be careful with classes that simply act as a container for what  
>> are in
>> fact global variables. A class should do one thing only (of course  
>> what
>> you accept as 'one thing' is open for debate) and encapsulate all  
>> that's
>> necessary for that particular thing. Make sure you're not
>> overcomplicating your solution by making classes where they're not
>> really necessary.
>>
>>> array from th command line.  What would be the preferred
>>> mechanism for returning or passing along those variables
>>
>> In some cases only some parts of the information contained in class A
>> are relevant to class B - you should pass only that particular
>> information, e.g. in the constructor or by setting a property of  
>> B. In
>> your example, if you have a Reader class that is interested in the
>> filename, you would not pass the whole Args object to it - only the
>> filename, like this:
>>
>>     myreader = Reader(Args.FileName)
>>
>>> to another class?  Maybe by a function method that returns
>>> all of those variables?
>>
>> Use properties if you need getter/setter methods or simple attributes
>> otherwise. In your case, I would not make __filename etc. 'private'
>> (that's what the double underscore suggests), then write a getter  
>> method
>> for it - just call it FileName and be done with it. Python idiom  
>> here is
>> more flexible than other languages.
>>
>> -- 
>> Yours,
>>
>> Andrei
>>
>> =====
>> Mail address in header catches spam. Real contact info:
>> ''.join([''.join(s) for s in zip(
>> "poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
>> "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
>
>
> ------------------------------
>
> Message: 9
> Date: Sun, 01 Apr 2007 19:48:04 -0400
> From: William Allison <allison.william at comcast.net>
> Subject: [Tutor] datetime.timedelta Output Format
> To: tutor at python.org
> Message-ID: <461044B4.8080900 at comcast.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Is there a way to have the output of "print tis" in the same format as
> "print now" and "print tafmsd" in the code below?
> Thanks,
> Will
>
>
> savage:~ wallison$ python
> Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import datetime
>>>> now = datetime.date.today()
>>>> print now
> 2007-04-01
>>>> tafmsd = datetime.date(1994, 2, 23)
>>>> print tafmsd
> 1994-02-23
>>>> tis = now - tafmsd
>>>> print tis
> 4785 days, 0:00:00
>>>>
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 38, Issue 2
> ************************************


From clajo04 at mac.com  Thu Apr  5 15:57:28 2007
From: clajo04 at mac.com (John Clark)
Date: Thu, 5 Apr 2007 09:57:28 -0400
Subject: [Tutor] windows and python and shebangs, oh my!
In-Reply-To: <ev2bu0$dbr$1@sea.gmane.org>
References: <461450B5.9040409@verizon.net> <ev2bu0$dbr$1@sea.gmane.org>
Message-ID: <008901c7778a$59f418b0$fefea8c0@haengma>


Be aware that by default the Apache web server _WILL_ use the shebang line
even when running on Windows to try to find the Python interpreter when
python is run as a CGI script.  

There is a setting in the configuration file that controls whether to use
the shebang line or to reference the windows registry.  The setting is 
	ScriptInterpreterSource registry

-jdc

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Alan Gauld
Sent: Thursday, April 05, 2007 4:28 AM
To: tutor at python.org
Subject: Re: [Tutor] windows and python and shebangs, oh my!

"Kirk Bailey" <deliberatus at verizon.net> wrote

> OK, in a script, we include a special statement telling the shell 
> where to go find the interpeter. This is the first line of the script, 
> and is a dpecial sort of comment, called informally the shebang.

Yes, but it is not a Python feature it is a Unix thing.
When you execute a script (of any kind) in Unix the Unix
shell(*) reads the first line and if its a shebang transfers control to the
appropriate interpreter.

(*) And not all Unix shells adhere to the convention, but thankfully the
vast majority do. The SVR4 Bourne shell didn't as I recall.

> In windows, this is for the current edition C:\python25\pythonw.exe so 
> the shebang is #!C:\python\pythonw.exe

This is often done purely as a convention that shows what version of Python
the script was created for.
Python does nothing with it, it is only a comment.

> At a loss, it then occurred to me that the program is a .py name 
> extension. When the auto installer installed python it may have 
> created an association between that name extension and the correct 
> interpreter automatically,

Correct, or you can do it manually. tHat is the only way that Windows
associates files with commands.

> So work with me, windows Pythonistas. CAN I rely on windows definitely 
> and reliably having .py files associated with the windows python 
> interpreter,

No, the association can be changed by any user or install script.

But in practice it rarely is changed so you can habe a good chance of
success.
If you really want to be sure the associations are stored in the registry.
You can look them up and change them (or add a missing one) as you need.

> If so, my task of designing the autoinstaller script just got a LOT 
> simpler.

On Windows the answer is usually in the registry somewhere, you just need to
figure out where to look!

Alan G. 


_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


From jeffpeery at yahoo.com  Thu Apr  5 17:56:57 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Thu, 5 Apr 2007 08:56:57 -0700 (PDT)
Subject: [Tutor] where to look for help with modbus TCP/IP
In-Reply-To: <008901c7778a$59f418b0$fefea8c0@haengma>
Message-ID: <709957.71259.qm@web43145.mail.sp1.yahoo.com>

hello, I want to use python to communicate (pluck data out of registers) with a controller (walchem, http://www.walchem.com/nav/CMImage.aspx?CMID=0&Name=180277_Modbus_C.pdf). I found great documentation using python sockets and TCP/IP; however I am very unfamiliar with modbus and how modbus TCP/IP is related to TCP/IP. Does anyone know where I might find sample code or a good book describing how to do this? thanks.

Jeff

 
---------------------------------
Sucker-punch spam with award-winning protection.
 Try the free Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070405/d8fbe68d/attachment.htm 

From kent37 at tds.net  Thu Apr  5 14:39:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 05 Apr 2007 08:39:13 -0400
Subject: [Tutor] Newbie question concerning text covering multiple lines
In-Reply-To: <1175754075.2314.15.camel@ubox>
References: <1175744093.2314.8.camel@ubox> <4614655F.7020409@tds.net>
	<1175754075.2314.15.camel@ubox>
Message-ID: <4614EDF1.3000400@tds.net>

Guba Castro wrote:

> The links you sent me are helpful, many thanks for that. Maybe there is
> another site you might be able to recommend to me: what I want to do
> with Python in primarily (Linux) scripting. Any ideas?

What do you mean by "Linux scripting"? If you want to work with files 
and directories, look at the os and shutil modules. If you want to run 
other programs, look at the subprocess module (though you may find that 
Python has built-in capabilities that you can use instead of calling 
external programs).

If you want better recommendations you will have to be more specific 
about your needs.

Kent

PS Please use Reply All to reply to the list.



From alan.gauld at btinternet.com  Thu Apr  5 18:50:09 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 5 Apr 2007 17:50:09 +0100
Subject: [Tutor] where to look for help with modbus TCP/IP
References: <008901c7778a$59f418b0$fefea8c0@haengma>
	<709957.71259.qm@web43145.mail.sp1.yahoo.com>
Message-ID: <ev39c8$7ak$1@sea.gmane.org>


"Jeff Peery" <jeffpeery at yahoo.com> wrote 

> sockets and TCP/IP; however I am very unfamiliar with 
> modbus and how modbus TCP/IP is related to TCP/IP. 

I've learned never to say never on this list but this isn't really a 
novice type thing so you might get better results asking on the 
main comp.lang.python newsgroup.

Which means that even as I type somebody is probably 
posting a reply all about modbus! :-)

Alan G.


From rikard.bosnjakovic at gmail.com  Thu Apr  5 18:55:44 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 5 Apr 2007 18:55:44 +0200
Subject: [Tutor] Tutor Digest, Vol 38, Issue 2
In-Reply-To: <DA90B14F-0449-4E9F-BA3D-A40D6C017FB5@uakron.edu>
References: <mailman.19483.1175471544.32030.tutor@python.org>
	<DA90B14F-0449-4E9F-BA3D-A40D6C017FB5@uakron.edu>
Message-ID: <d9e88eaf0704050955u6a93fa77ia286d18a171473aa@mail.gmail.com>

Jay, PLEASE shorten your posts by removing all unnecessary quoting.


On 4/5/07, Jay Mutter III <jmutter at uakron.edu> wrote:

> Whether I attempt to just strip the string or attempt to
>
> if line.endswith('No.\r'):
>      line = line.rstrip()
>
> It doesn't work.

That's because you assume the linefeeds to be \r only. If you really
want to strip endings on strings ending with "No.", then do this
workaround:

foo = line.rstrip()
if foo.endswith("No."):
  line = foo

Never assume line breaks to be of any type, because there are four of
them: \n, \r, \n\r, \r\n. It would be a waste of code to check for all
four, kind of reimplementing the wheel again.


-- 
- Rikard - http://bos.hack.org/cv/

From alan.gauld at btinternet.com  Thu Apr  5 18:57:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 5 Apr 2007 17:57:27 +0100
Subject: [Tutor] Tutor Digest, Vol 38, Issue 2
References: <mailman.19483.1175471544.32030.tutor@python.org>
	<DA90B14F-0449-4E9F-BA3D-A40D6C017FB5@uakron.edu>
Message-ID: <ev39pu$eie$1@sea.gmane.org>


"Jay Mutter III" <jmutter at uakron.edu> wrote 


> Whether I attempt to just strip the string or attempt to
> 
> if line.endswith('No.\r'):
>     line = line.rstrip()
> 
> It doesn't work.

Can you try printing the string repr just before the test. 
Or even the last 6 characters:

print repr(line[-6:])
if line.endswith('No: \n')
   line = line.strip()

See if that helps narrow down the cause...

> This is an imac running python 2.3.5 under OS-X 10.4.9

Shouldn't make any odds.

Weird,

Alan G.



From kent37 at tds.net  Thu Apr  5 19:00:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 05 Apr 2007 13:00:25 -0400
Subject: [Tutor] where to look for help with modbus TCP/IP
In-Reply-To: <709957.71259.qm@web43145.mail.sp1.yahoo.com>
References: <709957.71259.qm@web43145.mail.sp1.yahoo.com>
Message-ID: <46152B29.7050201@tds.net>

Jeff Peery wrote:
> hello, I want to use python to communicate (pluck data out of registers) 
> with a controller (walchem, 
> http://www.walchem.com/nav/CMImage.aspx?CMID=0&Name=180277_Modbus_C.pdf). 
> I found great documentation using python sockets and TCP/IP; however I 
> am very unfamiliar with modbus and how modbus TCP/IP is related to 
> TCP/IP. Does anyone know where I might find sample code or a good book 
> describing how to do this? thanks.

 From a quick look at the docs you reference, my guess is you just open 
a socket to the device and start exchanging data. Figuring out the 
command formats might take some time to get right.

Kent

From pythontut at pusspaws.net  Thu Apr  5 19:27:50 2007
From: pythontut at pusspaws.net (Dave S)
Date: Thu, 5 Apr 2007 18:27:50 +0100
Subject: [Tutor] Talking between C++ & Python ?
Message-ID: <200704051827.50278.pythontut@pusspaws.net>

Hi all,

I have written a Python app, a company who don't use Python want to integrate 
its back end with their C++ coded GUI.

At the moment they are proposing using CSV files to communicate between the 
Python & C++, ie C++ GUI generates a CSV, calls Python back end, back end 
does the work and generates return CSV, Python exits back to C++.

This would work but seems a bit messy. Any comments of suggestions on a better 
solution ? 

The data to & from the C++, Python code consists of fairly large tables of up 
to 80,000 items.

Many thanks for your help in advance

Dave

From alan.gauld at btinternet.com  Thu Apr  5 19:54:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 5 Apr 2007 18:54:14 +0100
Subject: [Tutor] Talking between C++ & Python ?
References: <200704051827.50278.pythontut@pusspaws.net>
Message-ID: <ev3d4d$ib9$1@sea.gmane.org>


"Dave S" <pythontut at pusspaws.net> wrote

> At the moment they are proposing using CSV files to communicate 
> between the
> Python & C++, ie C++ GUI generates a CSV, calls Python back end, 
> back end
> does the work and generates return CSV, Python exits back to C++.
>
> This would work but seems a bit messy. Any comments of suggestions 
> on a better
> solution ?


Sounds like a job for SOAP or XML/RPC.
I'd probably opt for SOAP in this case.
Have a look at the various python SOAP modules.
pySOAP is one example.


Alan G. 



From pythontut at pusspaws.net  Thu Apr  5 20:37:14 2007
From: pythontut at pusspaws.net (Dave S)
Date: Thu, 5 Apr 2007 19:37:14 +0100
Subject: [Tutor] Talking between C++ & Python ?
In-Reply-To: <ev3d4d$ib9$1@sea.gmane.org>
References: <200704051827.50278.pythontut@pusspaws.net>
	<ev3d4d$ib9$1@sea.gmane.org>
Message-ID: <200704051937.14920.pythontut@pusspaws.net>

On Thursday 05 April 2007 18:54, Alan Gauld wrote:
> "Dave S" <pythontut at pusspaws.net> wrote
>
> > At the moment they are proposing using CSV files to communicate
> > between the
> > Python & C++, ie C++ GUI generates a CSV, calls Python back end,
> > back end
> > does the work and generates return CSV, Python exits back to C++.
> >
> > This would work but seems a bit messy. Any comments of suggestions
> > on a better
> > solution ?
>
> Sounds like a job for SOAP or XML/RPC.
> I'd probably opt for SOAP in this case.
> Have a look at the various python SOAP modules.
> pySOAP is one example.
>
>
> Alan G.
>

Thanks for that - I will go investigate - Once the back end is integrated - 
its pay day ? :)

Cheers

Dave



>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From nephish at gmail.com  Thu Apr  5 21:11:09 2007
From: nephish at gmail.com (shawn bright)
Date: Thu, 5 Apr 2007 14:11:09 -0500
Subject: [Tutor] question about gui tool-kits
Message-ID: <384c93600704051211t15d3345fkd52680f917b01617@mail.gmail.com>

lo there all,

i have been working with pygtk2 for a while now, and, though i do like
the look and feel of a GTK2 app, i would like to do some stuff with
wx. I know, it doesn't look as cool, but , i may have need to work on
something that i can port to a windows box, and i think that wx would
be a lot easier to do. Also, i think it might prove a tad easier.

So my question is to any out there who have developed on both. What is
the comparison of how easy one is compared to another ?

thanks,
sk

From Mike.Hansen at atmel.com  Thu Apr  5 21:48:15 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 5 Apr 2007 13:48:15 -0600
Subject: [Tutor] Question about exception
Message-ID: <57B026980605A64F9B23484C5659E32E6C3C4D@poccso.US.ad.atmel.com>

When doing a try/except block, is it possible to return a list as part
of the exception?

try:
    check_someting()
except CheckSomethingError, e:
    for each_error in e:
       # do something

Can 'e' be a list of errors? If so, how do you construct your exception
class?


Is it better to do it like this?

(errors) = check_something()
if errors:
   # do something 
 

Mike "head zoned out due to allergies"   

From bill at celestial.net  Thu Apr  5 21:57:32 2007
From: bill at celestial.net (Bill Campbell)
Date: Thu, 5 Apr 2007 12:57:32 -0700
Subject: [Tutor] Question about exception
In-Reply-To: <57B026980605A64F9B23484C5659E32E6C3C4D@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E6C3C4D@poccso.US.ad.atmel.com>
Message-ID: <20070405195732.GA25753@ayn.mi.celestial.com>

On Thu, Apr 05, 2007, Mike Hansen wrote:
>When doing a try/except block, is it possible to return a list as part
>of the exception?
>
>try:
>    check_someting()
>except CheckSomethingError, e:
>    for each_error in e:
>       # do something
>
>Can 'e' be a list of errors? If so, how do you construct your exception
>class?

If the Exception is defined as a class, e will be an instance of
that class so you can have pretty much anything available:

class MyException(Exception):
    def __init__(self, msg, mylist)
        self.msg = msg
        self.mylist = mylist
        Exception.__init__(self, msg)

try:
    check_something()
except MyException, e:
    for entry in e.mylist: ...

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``I don't make jokes, I just watch the Government and report the facts...''
    Will Rogers

From Mike.Hansen at atmel.com  Thu Apr  5 22:23:59 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 5 Apr 2007 14:23:59 -0600
Subject: [Tutor] Question about exception
In-Reply-To: <20070405195732.GA25753@ayn.mi.celestial.com>
References: <57B026980605A64F9B23484C5659E32E6C3C4D@poccso.US.ad.atmel.com>
	<20070405195732.GA25753@ayn.mi.celestial.com>
Message-ID: <57B026980605A64F9B23484C5659E32E6C3C57@poccso.US.ad.atmel.com>

> If the Exception is defined as a class, e will be an instance of
> that class so you can have pretty much anything available:
> 
> class MyException(Exception):
>     def __init__(self, msg, mylist)
>         self.msg = msg
>         self.mylist = mylist
>         Exception.__init__(self, msg)
> 
> try:
>     check_something()
> except MyException, e:
>     for entry in e.mylist: ...
> 
> Bill
> --
> INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
> URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
> FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; 
> (206) 236-1676
> 
> ``I don't make jokes, I just watch the Government and report 
> the facts...''
>     Will Rogers

Doh! It was right in front of me, but I wasn't connecting the dots. 

Thanks,

Mike

From jjcrump at myuw.net  Thu Apr  5 22:02:56 2007
From: jjcrump at myuw.net (Jon Crump)
Date: Thu, 5 Apr 2007 13:02:56 -0700 (PDT)
Subject: [Tutor] beautifulSoup and .next iteration
Message-ID: <Pine.LNX.4.64.0704051258270.1111@cicero11.myuw.net>

As a complete tyro, I've broken my teeth on this web-page scraping 
problem. I've several times wanted to scrape pages in which the only 
identifying elements are positional rather than syntactical, that is, 
pages in which everything's a sibling and there's no way to predict how 
many sibs there are in each section headed by an empty named anchor. I've 
been trying to use beautifulSoup to scrape these. It's not clear to me 
which is worse: my grasp of python in general or beautifulSoup in 
particular. Here's a stripped down example of the sort of thing I mean:

<html>
<body>
<a name="A1"></a>
<p>paragraph 1</p>
<p>paragraph 1.A</p>
<ul>
   <li>some line</li>
   <li>another line</li>
</ul>
<p>paragraph 1.B</p>

<a name="A2"></a>
<p>paragraph 2</p>
<p>paragraph 2.B</p>

<a name="A3"></a>
<p>paragraph 3</p>
<table>
   <tr><td>some</td><td>data</td></tr>
</table>
</body>
</html>

I want to end up with some container, say a list, containing something 
like this:
[
   [A1, paragraph 1, paragraph 1.A, some line, another line, paragraph 1.B]
   [A2, paragraph 2, paragraph 2.B]
   [A3, paragraph 3, some, data]
]
I've tried things like this: (just using print for now, I think I'll be 
able to build the lists or whatever once I get the basic idea.)

anchors = soup.findAll('a', { 'name' : re.compile('^A.*$')})
for x in anchors:
   print x
   x = x.next
   while getattr(x, 'name') != 'a':
     print x

And get into endless loops. I can't help thinking there are simple and 
obvious ways to do this, probably many, but as a rank beginner, they are 
escaping me.

Can someone wise in the ways of screen scraping give me a clue?

thanks,
Jon

From andy.koch at pc-doctor.com  Thu Apr  5 23:39:48 2007
From: andy.koch at pc-doctor.com (Andy Koch)
Date: Thu, 05 Apr 2007 14:39:48 -0700
Subject: [Tutor] UnicodeDecodeError in kinterbasdb
Message-ID: <ev3qbf$n1b$1@sea.gmane.org>

Hello,

I've installed Python 25 on an XP machine, installed kinterbasdb (and 
eginix-mx-base).  Python works fine.

However, when I try to load the firebird module in IDLE I get ...


Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
 >>> import kinterbasdb
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "C:\Python25\Lib\site-packages\kinterbasdb\__init__.py", line 
98, in <module>
     _instPath, 'bin'
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 
237: ordinal not in range(128)


..........

 From searching the web I'm led to think this is related to the default 
encodings on the machine.  But I'm not sure what to do about this.

For what it's worth, I have another machine and this same library works 
just fine.

Thank You,

Andy Koch


From amonroe at columbus.rr.com  Fri Apr  6 01:13:08 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 5 Apr 2007 19:13:08 -0400
Subject: [Tutor] Talking between C++ & Python ?
In-Reply-To: <200704051827.50278.pythontut@pusspaws.net>
References: <200704051827.50278.pythontut@pusspaws.net>
Message-ID: <9350870935.20070405191308@columbus.rr.com>


> I have written a Python app, a company who don't use Python want to integrate 
> its back end with their C++ coded GUI.

> At the moment they are proposing using CSV files to communicate between the 
> Python & C++, ie C++ GUI generates a CSV, calls Python back end, back end 
> does the work and generates return CSV, Python exits back to C++.

> This would work but seems a bit messy. Any comments of suggestions on a better 
> solution ? 

> The data to & from the C++, Python code consists of fairly large tables of up 
> to 80,000 items.

SQLite?

Alan


From alan.gauld at btinternet.com  Fri Apr  6 09:29:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 6 Apr 2007 08:29:45 +0100
Subject: [Tutor] Talking between C++ & Python ?
References: <200704051827.50278.pythontut@pusspaws.net>
	<9350870935.20070405191308@columbus.rr.com>
Message-ID: <ev4stg$c4u$1@sea.gmane.org>


"R. Alan Monroe" <amonroe at columbus.rr.com> wrote

>> I have written a Python app, a company who don't use Python want to 
>> integrate
>> its back end with their C++ coded GUI.
>
>> The data to & from the C++, Python code consists of fairly large 
>> tables of up
>> to 80,000 items.
>
> SQLite?

That's a good idea if the apps are co-located.
I had, for some reason, assumed they must be remote
from each other when I suggested SOAP, but if they
are co-located then a database is a good solution for
those volumes. It probably requires that each end
implements a poller to check for updates and a
table or column to be added to indicate the status.

Alan G. 



From pythontut at pusspaws.net  Fri Apr  6 09:51:29 2007
From: pythontut at pusspaws.net (Dave S)
Date: Fri, 6 Apr 2007 08:51:29 +0100
Subject: [Tutor] Talking between C++ & Python ?
In-Reply-To: <ev4stg$c4u$1@sea.gmane.org>
References: <200704051827.50278.pythontut@pusspaws.net>
	<9350870935.20070405191308@columbus.rr.com>
	<ev4stg$c4u$1@sea.gmane.org>
Message-ID: <200704060851.29280.pythontut@pusspaws.net>

On Friday 06 April 2007 08:29, Alan Gauld wrote:
> "R. Alan Monroe" <amonroe at columbus.rr.com> wrote
>
> >> I have written a Python app, a company who don't use Python want to
> >> integrate
> >> its back end with their C++ coded GUI.
> >>
> >> The data to & from the C++, Python code consists of fairly large
> >> tables of up
> >> to 80,000 items.
> >
> > SQLite?
>
> That's a good idea if the apps are co-located.
> I had, for some reason, assumed they must be remote
> from each other when I suggested SOAP, but if they
> are co-located then a database is a good solution for
> those volumes. It probably requires that each end
> implements a poller to check for updates and a
> table or column to be added to indicate the status.
>
> Alan G.
>
>

Yep both apps are on the same machine, the company just wants to put a 
corporate GUI on my Python code to claim it as their own because they cant 
work out how to convert some of the Python to C++ - I leverage the Python 
interpreter parsing to evaluate some fairly complex and user changeable 
logical expressions + I have written a class that sits on top of Reportlab to 
generate the PDF manuals. They don't want to re-write that either :) 

I am now learning C++, its interesting - takes a lot of code to do what in 
Python takes a line or two ....
 
I had never heard of SOAP - there is just so much out there but it does seem 
to be for remote apps.

SQLite ? - just Googled it and it looks interesting. Licence seems OK too - 
these guys are allergic to the GPL - reportlab is BSD. That's another reason 
that they want their own GUI - QT4 on windows ....

Thanks once again

Dave








> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From jmutter at uakron.edu  Fri Apr  6 10:46:24 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Fri, 6 Apr 2007 04:46:24 -0400
Subject: [Tutor] Tutor Digest, Vol 38, Issue 10
In-Reply-To: <mailman.20020.1175809218.32030.tutor@python.org>
References: <mailman.20020.1175809218.32030.tutor@python.org>
Message-ID: <62E6051E-CA65-435E-A326-59BA751FEF6F@uakron.edu>

>
>
> "Jay Mutter III" <jmutter at uakron.edu> wrote
>
>
>> Whether I attempt to just strip the string or attempt to
>>
>> if line.endswith('No.\r'):
>>     line = line.rstrip()
>>
>> It doesn't work.
>
> Can you try printing the string repr just before the test.
> Or even the last 6 characters:
>
> print repr(line[-6:])
> if line.endswith('No: \n')
>    line = line.strip()
>

Alan using your suggestion with the code aove here is the print out:

jay-mutter-iiis-computer:~/documents/ToBePrinted jlm1$ python test.py
'andal\r'
'  No.\r'
' Dor-\r'
'  14;\r'
'315 ;\r'
'  No.\r'
'utton\r'
'H'

Which appears to me to have 2 lines ending with No. where

  the LF should be removed and the next line would be on the same line

Again thanks for the help/suggestions

> See if that helps narrow down the cause...
>
>> This is an imac running python 2.3.5 under OS-X 10.4.9
>
> Shouldn't make any odds.
>
> Weird,
>
> Alan G.


From kjabra at jps.net  Thu Apr  5 08:11:03 2007
From: kjabra at jps.net (Keegan Johnson)
Date: Wed, 4 Apr 2007 23:11:03 -0700
Subject: [Tutor] Need a Clean Start
Message-ID: <2C348849-490D-4CD9-B7C5-6129FB7971E4@jps.net>

Hi everyone,
I'm taking a computer science class. We haven't gotten to Python yet  
but I've started dabbling and become rather enamored. Anyway, I've  
been using different versions and have installed different things and  
am going crazy. I need to get the pygames, py2app, etc on my computer  
(I have a Macintosh). Is there any way to clean up all these files  
that I've accrued trying to get things to work? I've been able to do  
a little bit but nothing more than that. Also, what should I use?  
There's lots of different versions different sites recommend. Anyone  
willing to authoritatively decide?
Thanks a million for any help at all,
Keegan

From kent37 at tds.net  Fri Apr  6 12:36:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 06 Apr 2007 06:36:35 -0400
Subject: [Tutor] Talking between C++ & Python ?
In-Reply-To: <200704060851.29280.pythontut@pusspaws.net>
References: <200704051827.50278.pythontut@pusspaws.net>	<9350870935.20070405191308@columbus.rr.com>	<ev4stg$c4u$1@sea.gmane.org>
	<200704060851.29280.pythontut@pusspaws.net>
Message-ID: <461622B3.6030705@tds.net>

Dave S wrote:

> Yep both apps are on the same machine, the company just wants to put a 
> corporate GUI on my Python code to claim it as their own because they cant 
> work out how to convert some of the Python to C++ - I leverage the Python 
> interpreter parsing to evaluate some fairly complex and user changeable 
> logical expressions + I have written a class that sits on top of Reportlab to 
> generate the PDF manuals. They don't want to re-write that either :) 

Why not write the GUI in Python too?

Another option is to embed the Python interpreter in the C++ program, 
rather than making it a separate program. This might be a good fit for 
your requirements.

> SQLite ? - just Googled it and it looks interesting. Licence seems OK too - 
> these guys are allergic to the GPL - reportlab is BSD. That's another reason 
> that they want their own GUI - QT4 on windows ....

Why is QT4 a problem? If they want QT4, presumably they already have a 
commercial license. If they don't want QT4, use Tkinter or wxPython.

Kent

From rikard.bosnjakovic at gmail.com  Fri Apr  6 13:09:04 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 6 Apr 2007 13:09:04 +0200
Subject: [Tutor] Need a Clean Start
In-Reply-To: <2C348849-490D-4CD9-B7C5-6129FB7971E4@jps.net>
References: <2C348849-490D-4CD9-B7C5-6129FB7971E4@jps.net>
Message-ID: <d9e88eaf0704060409k57cdbae2qee724eeb3bb1e58d@mail.gmail.com>

On 4/5/07, Keegan Johnson <kjabra at jps.net> wrote:

> Is there any way to clean up all these files
> that I've accrued trying to get things to work? I've been able to do
> a little bit but nothing more than that. Also, what should I use?
> There's lots of different versions different sites recommend.

Your post is confusing.

Exactly what are you asking?


-- 
- Rikard - http://bos.hack.org/cv/

From allison.william at comcast.net  Fri Apr  6 14:01:53 2007
From: allison.william at comcast.net (William Allison)
Date: Fri, 06 Apr 2007 08:01:53 -0400
Subject: [Tutor] Need a Clean Start
In-Reply-To: <2C348849-490D-4CD9-B7C5-6129FB7971E4@jps.net>
References: <2C348849-490D-4CD9-B7C5-6129FB7971E4@jps.net>
Message-ID: <461636B1.9020406@comcast.net>

Keegan Johnson wrote:
>  I need to get the pygames, py2app, etc on my computer  
> (I have a Macintosh). Is there any way to clean up all these files  
> that I've accrued trying to get things to work? I've been able to do  
> a little bit but nothing more than that. Also, what should I use?  
> There's lots of different versions different sites recommend. Anyone  
> willing to authoritatively decide?
> Thanks a million for any help at all,
> Keegan
>   
Not sure what you've accrued trying to get things to work so can't tell 
you how to clean them all up.  But sounds like you might want to check 
out easy_install, it lets you install, upgrade, and uninstall Python 
packages.  You can even have a "custom installation location" such as in 
your
home directory. 

http://peak.telecommunity.com/DevCenter/EasyInstall

As far as which version to use,  I think I read somewhere that the 
latest version of Python is typically the best version of Python.
Will

From dotancohen at gmail.com  Fri Apr  6 16:21:39 2007
From: dotancohen at gmail.com (Dotan Cohen)
Date: Fri, 6 Apr 2007 17:21:39 +0300
Subject: [Tutor] Writing KDE apps in Python.
Message-ID: <880dece00704060721h6cbcdbf5m65d335842c2a8240@mail.gmail.com>

Hi all, I'm new to python but I've some limited experience with C and
PHP. I'm having a rather hard time piecing together a simple GUI
Hello, world! app. All the documentation online seems to be outdated,
and I've little access to the dead-tree variety of record keeping.

Could someone please RTFM me with a link to the Python Qt bindings. I
use KDE in Fedora and I've a few self-made console apps that I'd like
to run in the KDE system tray to make life a little cleaner. Thanks.

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/

From alan.gauld at btinternet.com  Fri Apr  6 16:35:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 6 Apr 2007 15:35:01 +0100
Subject: [Tutor] Need a Clean Start
References: <2C348849-490D-4CD9-B7C5-6129FB7971E4@jps.net>
Message-ID: <ev5lqs$mh$1@sea.gmane.org>

"Keegan Johnson" <kjabra at jps.net> wrote

> been using different versions and have installed different things 
> and
> am going crazy. I need to get the pygames, py2app, etc on my 
> computer
> (I have a Macintosh). Is there any way to clean up all these files

Just delete them. At least the main packages you installed.
One of the beauties of a Mac is that uninstalling is as easy
as deleting the application bundle. Don't try to tidy up all
the libraries by hand however because MacOS comes with
its own version of Python and you might break something
that relies on it!

Of course if you don;t remembder what you installed or where
then theres not too much tyou can do except do a trawl with
find (or maybe with finder/sherlock) to locate the most recently
installed files and if they look likely delete those...

> There's lots of different versions different sites recommend. Anyone
> willing to authoritatively decide?

On a Mac install the latest MacPython package.
Then install the pyGamer versions that correspond.
Don;t install too many things at once, make sure it
all works first!

HTH,

Alan G. 



From dotancohen at gmail.com  Fri Apr  6 16:42:07 2007
From: dotancohen at gmail.com (Dotan Cohen)
Date: Fri, 6 Apr 2007 17:42:07 +0300
Subject: [Tutor] Writing KDE apps in Python.
In-Reply-To: <880dece00704060721h6cbcdbf5m65d335842c2a8240@mail.gmail.com>
References: <880dece00704060721h6cbcdbf5m65d335842c2a8240@mail.gmail.com>
Message-ID: <880dece00704060742j11814b8fsa93e51d0a62a5974@mail.gmail.com>

On 06/04/07, Dotan Cohen <dotancohen at gmail.com> wrote:
> Hi all, I'm new to python but I've some limited experience with C and
> PHP. I'm having a rather hard time piecing together a simple GUI
> Hello, world! app. All the documentation online seems to be outdated,
> and I've little access to the dead-tree variety of record keeping.
>
> Could someone please RTFM me with a link to the Python Qt bindings. I
> use KDE in Fedora and I've a few self-made console apps that I'd like
> to run in the KDE system tray to make life a little cleaner. Thanks.
>
> Dotan Cohen
>
> http://lyricslist.com/
> http://what-is-what.com/
>

Sorry for the noise, folks. The parrot sent me an automated email of
FAQs (apparently all new list members get the mail), and although I
thought that I was thorough in my skim of python.org I did miss the
link to riverbankcomputing. I should be able to continue now. Thank
you.

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/

From alan.gauld at btinternet.com  Fri Apr  6 16:43:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 6 Apr 2007 15:43:27 +0100
Subject: [Tutor] Talking between C++ & Python ?
References: <200704051827.50278.pythontut@pusspaws.net><9350870935.20070405191308@columbus.rr.com><ev4stg$c4u$1@sea.gmane.org>
	<200704060851.29280.pythontut@pusspaws.net>
Message-ID: <ev5man$32j$1@sea.gmane.org>

"Dave S" <pythontut at pusspaws.net> wrote

>> are co-located then a database is a good solution for
>> those volumes. It probably requires that each end
>> implements a poller to check for updates and a
>
> Yep both apps are on the same machine, the company just wants to put 
> a
> corporate GUI on my Python code to claim it as their own

OK, If you go doewn the GUI route a more efficient solution to
polling at each end would be a lightweight socket interface from
the client to server. I'm not sure which end originates the big
data volumes, but I'll assume the server.
Client makes request to server via socket
Server writes data to database
Server sends response to client to say data is available
Client reads data from database.

Should be more flexible than a csv file although it would work
in the same way.


> I had never heard of SOAP - there is just so much out there but it 
> does seem
> to be for remote apps.

SOAP is rapoidly becoming the standartd for remote message
passing between different architectures/lamnguages. Its only
downsides are that it is expensive on both CPU (parsing XML)
and bandwidth (XML v Binary encoding). There are a few security
issues too, but you can get encrypting libraries etc now too.

> SQLite ? - just Googled it and it looks interesting.

It could be any database that you can access from both C++
and Python. So if you already use SQL Server or Oracle or
DB2 then just use that and the appropriate adapters.

Just some more thoughts,

Alan G. 



From alan.gauld at btinternet.com  Fri Apr  6 16:47:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 6 Apr 2007 15:47:56 +0100
Subject: [Tutor] Tutor Digest, Vol 38, Issue 10
References: <mailman.20020.1175809218.32030.tutor@python.org>
	<62E6051E-CA65-435E-A326-59BA751FEF6F@uakron.edu>
Message-ID: <ev5mj3$4c7$1@sea.gmane.org>


"Jay Mutter III" <jmutter at uakron.edu> wrote

>> Can you try printing the string repr just before the test.
>> Or even the last 6 characters:
>>
>> print repr(line[-6:])
>> if line.endswith('No: \n')
>>    line = line.strip()

> Alan using your suggestion with the code aove here is the print out:
>
> jay-mutter-iiis-computer:~/documents/ToBePrinted jlm1$ python 
> test.py
> 'andal\r'
> '  No.\r'

Just to be picky, the code I posted used a colon and a space
whereas the repr shows a period and no space. And it's using \r
so what happens if you run  it again with:

print repr(line[-6:])
if line.endswith('No.\r'):
    line = line.strip()

Clutching at straws,

Alan G. 



From deliberatus at verizon.net  Fri Apr  6 15:53:04 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 06 Apr 2007 10:53:04 -0300
Subject: [Tutor] windows and python and shebangs, oh my!
In-Reply-To: <008901c7778a$59f418b0$fefea8c0@haengma>
References: <461450B5.9040409@verizon.net> <ev2bu0$dbr$1@sea.gmane.org>
	<008901c7778a$59f418b0$fefea8c0@haengma>
Message-ID: <461650C0.1070501@verizon.net>

No problem, windoweswiki is shipped with a very simple server which is 
pretty dullwitted, but handles cgi and http, and nothing else. a little 
thing called tinyweb, it's efficent, small, and it is bulletproof- and 
so stupid it's actually easy to use. You can read about it here:

	http://www.ritlabs.com/tinyweb/

John Clark wrote:
> Be aware that by default the Apache web server _WILL_ use the shebang line
> even when running on Windows to try to find the Python interpreter when
> python is run as a CGI script.  
> 
> There is a setting in the configuration file that controls whether to use
> the shebang line or to reference the windows registry.  The setting is 
> 	ScriptInterpreterSource registry
> 
> -jdc
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
> Of Alan Gauld
> Sent: Thursday, April 05, 2007 4:28 AM
> To: tutor at python.org
> Subject: Re: [Tutor] windows and python and shebangs, oh my!
> 
> "Kirk Bailey" <deliberatus at verizon.net> wrote
> 
>> OK, in a script, we include a special statement telling the shell 
>> where to go find the interpeter. This is the first line of the script, 
>> and is a dpecial sort of comment, called informally the shebang.
> 
> Yes, but it is not a Python feature it is a Unix thing.
> When you execute a script (of any kind) in Unix the Unix
> shell(*) reads the first line and if its a shebang transfers control to the
> appropriate interpreter.
> 
> (*) And not all Unix shells adhere to the convention, but thankfully the
> vast majority do. The SVR4 Bourne shell didn't as I recall.
> 
>> In windows, this is for the current edition C:\python25\pythonw.exe so 
>> the shebang is #!C:\python\pythonw.exe
> 
> This is often done purely as a convention that shows what version of Python
> the script was created for.
> Python does nothing with it, it is only a comment.
> 
>> At a loss, it then occurred to me that the program is a .py name 
>> extension. When the auto installer installed python it may have 
>> created an association between that name extension and the correct 
>> interpreter automatically,
> 
> Correct, or you can do it manually. tHat is the only way that Windows
> associates files with commands.
> 
>> So work with me, windows Pythonistas. CAN I rely on windows definitely 
>> and reliably having .py files associated with the windows python 
>> interpreter,
> 
> No, the association can be changed by any user or install script.
> 
> But in practice it rarely is changed so you can habe a good chance of
> success.
> If you really want to be sure the associations are stored in the registry.
> You can look them up and change them (or add a missing one) as you need.
> 
>> If so, my task of designing the autoinstaller script just got a LOT 
>> simpler.
> 
> On Windows the answer is usually in the registry somewhere, you just need to
> figure out where to look!
> 
> Alan G. 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From maseriyer at yahoo.com  Fri Apr  6 22:28:45 2007
From: maseriyer at yahoo.com (Iyer)
Date: Fri, 6 Apr 2007 13:28:45 -0700 (PDT)
Subject: [Tutor] ConfigParser and multiple option names
Message-ID: <20070406202845.97828.qmail@web37708.mail.mud.yahoo.com>

The problem I have is very similar to this:

http://www.thescripts.com/forum/threadnav486400-1-10.html

But, I cannot change the config file layout -- it is a
read only file, so if I have the contents of the
config file (take it as config_file.lay) as 

[dir_options]
dir="/home/florian"
dir="/home/john"
dir="/home/whoever"

what method would you suggest to read each "dir" value
above from the config_file.lay?

Thanx,
iyer


 
____________________________________________________________________________________
Sucker-punch spam with award-winning protection. 
Try the free Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/mailbeta/features_spam.html

From janos.juhasz at VELUX.com  Sat Apr  7 08:49:02 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sat, 7 Apr 2007 08:49:02 +0200
Subject: [Tutor] Movies from jpg files
Message-ID: <OFEEFE32C3.F98B7DD9-ONC12572B6.0023E199-C12572B6.0025724B@velux.com>

Dear All,

I have found a fine Axis 2100 webcamera on my shelf, that was out of 
usage,
It uploads jpg images every minutes to an ftp server now.
I would like to build up a movie from the pictures for easier review.
I don't know which movie format can be built up easier,
.jpeg, quicktime .mov, .wmv, .avi or anything else.
It would be fine to use a format that has compression advantage compared 
the raw
volume of jpg files. It could be possible as the camera placed statically 
so the images
are very similar. 

May you recommend me which format could be used ?
May you recommend anything to build them easy ?


Yours sincerely,
______________________________
J?nos Juh?sz


From alan.gauld at btinternet.com  Sat Apr  7 09:52:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 7 Apr 2007 08:52:00 +0100
Subject: [Tutor] Movies from jpg files
References: <OFEEFE32C3.F98B7DD9-ONC12572B6.0023E199-C12572B6.0025724B@velux.com>
Message-ID: <ev7ij8$77e$1@sea.gmane.org>


"J?nos Juh?sz" <janos.juhasz at VELUX.com> wrote
> It uploads jpg images every minutes to an ftp server now.
> I would like to build up a movie from the pictures for easier 
> review.

If you are usoing XP this is very easily done using MovieMaker.
Just drag n drop the jpg files into MM and adjust the durations.

If you are on a Mac you can do the same iusing iMovie.

There is a free DV editor for Linux too but I can't recall its name.

Any of those programs will give you a choice of formats in
which to save the final movie.

This is almost certainly easier than trying to write a
program to do it. In addiotion you can add titles, music,
narration or anything else you fancy.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From project5 at redrival.net  Sat Apr  7 10:22:07 2007
From: project5 at redrival.net (Andrei)
Date: Sat, 07 Apr 2007 10:22:07 +0200
Subject: [Tutor] ConfigParser and multiple option names
In-Reply-To: <20070406202845.97828.qmail@web37708.mail.mud.yahoo.com>
References: <20070406202845.97828.qmail@web37708.mail.mud.yahoo.com>
Message-ID: <ev7kaf$da1$1@sea.gmane.org>

Iyer wrote:
<snop>
> 
> I cannot change the config file layout -- it is a
<snip>
> [dir_options]
> dir="/home/florian"
> dir="/home/john"
<snip>
> what method would you suggest to read each "dir" value
> above from the config_file.lay?

Internally, the ConfigParser implementation uses dictionaries to store 
sections and section contents making it impossible to have duplicate 
sections or option names - this file is against the philosophy of the 
parser.
If these dir values are all you're interested in, you could write a very 
simple parser only for them in a few lines.
Alternatively I think you'll have to trick the parser into thinking 
these are different options by overriding optionxform, to mangle the 
option name and make it unique:

 >>> from random import random
 >>> class DuplicateOptionParser(ConfigParser):
...     def optionxform(self, option):
...         return option.lower() + '____' + str(random()) + str(random())
...
 >>> parser = DuplicateOptionParser()
 >>> parser.read('xyz.ini')
 >>> parser.items('dir_options')
[('dir____0.2893357144260.69151552211', '"/home/whoever"'),
('dir____0.8258732656650.272559810163', '"/home/florian"'),
('dir____0.6565224032210.703769464586', '"/home/john"')]

Note that it will do this for *all* options in your file, even those 
that have no duplicates. You'll have to trim the part starting with 
'____' before using them.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From janos.juhasz at VELUX.com  Sat Apr  7 12:20:51 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sat, 7 Apr 2007 12:20:51 +0200
Subject: [Tutor] Movies from jpg files
In-Reply-To: <mailman.39.1175940011.28072.tutor@python.org>
Message-ID: <OF22E1F382.C6C56EEB-ONC12572B6.003737BC-C12572B6.0038D669@velux.com>

Dear Alan,


Alan Gauld wrote:
>If you are usoing XP this is very easily done using MovieMaker.
>Just drag n drop the jpg files into MM and adjust the durations.
>
>Any of those programs will give you a choice of formats in
>which to save the final movie.

Thanks your response.
It should works well with some images, but I would do it with a scheduled 
way
with some 1000 files.

So, I have to extend my prev. post.

-------
I have found a fine Axis 2100 webcamera on my shelf, that was out of 
usage,
It uploads jpg images every minutes to an ftp server now.
I would like to build up a movie from the pictures for easier review.
I don't know which movie format can be built up easier,
.jpeg, quicktime .mov, .wmv, .avi or anything else.
It would be fine to use a format that has compression advantage compared 
the raw volume of jpg files. It could be possible as the camera placed 
statically
so the images are very similar.

May you recommend me which format could be used ?
May you recommend anything to build them easy ?
-------

I have some thousand images, so I would use some kind of script to do it.
May you recommend any python library to build any kind of movies from a 
folder of
jpg files?
It could be any commandline tool anyway, that I can call with os.system(),
but I wouldn't use GUI for it.


Yours sincerely,
______________________________
J?nos Juh?sz


From gregp at liveammo.com  Sat Apr  7 18:56:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 07 Apr 2007 12:56:00 -0400
Subject: [Tutor] Movies from jpg files
Message-ID: <20070407165119.5160817051@smtp2.hushmail.com>

Maybe PyMedia is what you are looking for:  http://www.pymedia.org

It's a Python library based on FFmpeg, which is a program that can encode and decode many different video streams.  FFmpeg can also create an mpeg from a collection of jpeg images, read section 1.2 of the FFmpeg FAQ which demonstrates making a mpeg from a sequence of jpeg images:

http://ffmpeg.mplayerhq.hu/faq.html

Subject: [Tutor] Movies from jpg files
To: tutor at python.org

Dear All,
>
>I have found a fine Axis 2100 webcamera on my shelf, that was out of 
>usage,
>It uploads jpg images every minutes to an ftp server now.
>I would like to build up a movie from the pictures for easier review.
>I don't know which movie format can be built up easier,
>.jpeg, quicktime .mov, .wmv, .avi or anything else.
>It would be fine to use a format that has compression advantage compared 
>the raw
>volume of jpg files. It could be possible as the camera placed statically 
>so the images
>are very similar. 
>
>May you recommend me which format could be used ?
>May you recommend anything to build them easy ?
>
>
>Yours sincerely,
>______________________________
>J?nos Juh?sz
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>



From tms43 at clearwire.net  Sat Apr  7 18:07:33 2007
From: tms43 at clearwire.net (Teresa Stanton)
Date: Sat, 7 Apr 2007 09:07:33 -0700
Subject: [Tutor] Command line args
Message-ID: <000001c7792e$dbf4d2a0$2dbbe942@samiam>

If one argument to a script is provided I am to take the input from it.  I
figure that is presented like this:

filename = sys.argv[1]
data = open(filename).read()

But, if none are provided, input should come from standard input.  How do I
write that code?

TY
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070407/06412991/attachment.htm 

From alan.gauld at btinternet.com  Sat Apr  7 19:47:30 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 7 Apr 2007 18:47:30 +0100
Subject: [Tutor] Command line args
References: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
Message-ID: <ev8lfq$7sb$1@sea.gmane.org>


"Teresa Stanton" <tms43 at clearwire.net> wrote

> If one argument to a script is provided I am to take the input from 
> it.

OK This sounds like a homework so I can't give you a direct
answer but only some things to consider.

> I figure that is presented like this:
>
> filename = sys.argv[1]
> data = open(filename).read()

So far so good but how will you know whether there is
anyting in sys.argv to read?

> But, if none are provided, input should come from standard input.

Standard input is where you normally get input in interactive 
programs.
How do you normally get a user to giove you information?

You'll find more about receiving input from users in the
"Talking to the User" topic of my tutorial.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From andreas at kostyrka.org  Sat Apr  7 20:49:26 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 7 Apr 2007 20:49:26 +0200
Subject: [Tutor] Command line args
In-Reply-To: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
References: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
Message-ID: <20070407184926.GJ24498@andi-lap.la.revver.com>

* Teresa Stanton <tms43 at clearwire.net> [070407 18:52]:
>    If one argument to a script is provided I am to take the input from it.  I
>    figure that is presented like this:
> 
>    filename = sys.argv[1]
>    data = open(filename).read()
> 
>    But, if none are provided, input should come from standard input.  How do
>    I write that code?

if len(sys.argv) > 1:
     fp = file(sys.argv[1])
else:
     fp = sys.stdin
data = fp.read()
if fp is not sys.stdin:
     fp.close()

Andreas

From samrobertsmith at gmail.com  Sun Apr  8 11:38:26 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Sun, 8 Apr 2007 02:38:26 -0700
Subject: [Tutor] reassign
Message-ID: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>

Hi,
I have a list: [2,5,8,0,1,7]
how i can randomly reassign the values to different location in the list?
for example:
Time 1: [5,2,8,0,1,7]
Time 2: [8,0,7,1,5,2]
Thanks!
Linda

From mail at timgolden.me.uk  Sun Apr  8 11:54:43 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Sun, 08 Apr 2007 10:54:43 +0100
Subject: [Tutor] reassign
In-Reply-To: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
References: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
Message-ID: <4618BBE3.10205@timgolden.me.uk>

linda.s wrote:
> Hi,
> I have a list: [2,5,8,0,1,7]
> how i can randomly reassign the values to different location in the list?
> for example:
> Time 1: [5,2,8,0,1,7]
> Time 2: [8,0,7,1,5,2]
>   
Have a look at the .shuffle function in the random module.

TJG

From janos.juhasz at VELUX.com  Sun Apr  8 14:57:31 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sun, 8 Apr 2007 14:57:31 +0200
Subject: [Tutor] Movies from jpg files
In-Reply-To: <mailman.37.1176026410.22588.tutor@python.org>
Message-ID: <OF779A577D.0BB5EBDA-ONC12572B7.004661B0-C12572B7.00472E41@velux.com>

Dear Greg,

thanks the link to pymedia.

> Maybe PyMedia is what you are looking for:  http://www.pymedia.org

I looked for it for a while. It is very cool.
I made the next short script from one of the samples that make exactly 
what I wanted.

###########

import sys, os, glob, Image, time
import pymedia.video.vcodec as vcodec

def files2Video(files, outFile='out.mpg', outCodec='mpeg1video'):
  s= Image.open(files[0])
  if outCodec== 'mpeg1video': bitrate= 2700000
  else:                       bitrate= 9800000
  params= { 'type': 0, 'gop_size': 12, 'frame_rate_base': 125, 
'max_b_frames': 0,
            'width': s.size[0], 'height': s.size[1], 'frame_rate': 2997,
            'deinterlace': 0,'bitrate': bitrate, 'id': 
vcodec.getCodecID(outCodec)
          }
  e= vcodec.Encoder(params)

  fw= open(outFile, 'wb')
  for ActPic in files:
    s= Image.open(ActPic)
    ss= s.tostring()
    bmpFrame= vcodec.VFrame(vcodec.formats.PIX_FMT_RGB24, s.size, 
(ss,None,None))
    yuvFrame= bmpFrame.convert(vcodec.formats.PIX_FMT_YUV420P)
    d= e.encode(yuvFrame)
    fw.write(d.data)
  fw.close()

if __name__== '__main__':
    files = glob.glob(r'.\test\*.jpg')
    files.sort(key=lambda f:(os.stat(f).st_mtime, f))
    files2Video(files, time.strftime('Cam1_%Y%m%d%H%M.mpg', 
time.localtime()))
    [os.remove(f) for f in files]

###########

Python is Cool :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070408/ac88ca12/attachment.htm 

From gregp at liveammo.com  Sun Apr  8 18:05:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 08 Apr 2007 12:05:00 -0400
Subject: [Tutor] Movies from jpg files
Message-ID: <20070408160020.7B7D31704E@smtp2.hushmail.com>

Indeed ;)

>Python is Cool :)




From spelzdinkelclonk at web.de  Sun Apr  8 18:27:23 2007
From: spelzdinkelclonk at web.de (Andreas Pfrengle)
Date: Sun, 08 Apr 2007 18:27:23 +0200
Subject: [Tutor] Addressing a variable whose name is the value of a string
Message-ID: <461917EB.4010501@web.de>

Hello,

I want to change the value of a variable whose name I don't know, but
this name is stored as a string in another variable, like:

x = 1
var = 'x'

Now I want to change the value of x, but address it via var. I'm quite
sure I've already seen a solution for this, but right now I don't get it :-(
Some help would be appreciated :-)

Thanks in advance,
Andreas



From noufal at airtelbroadband.in  Sun Apr  8 19:06:23 2007
From: noufal at airtelbroadband.in (Noufal Ibrahim)
Date: Sun, 08 Apr 2007 22:36:23 +0530
Subject: [Tutor] TCLtutor like python program
Message-ID: <4619210F.3010205@airtelbroadband.in>

Hello everyone,
   A couple of months ago, I had posted on this list asking about the
usefulness of such a program. Something similar to TclTutor
(http://www.msen.com/~clif/TclTutor.html) for python.
   I've spent some time on this and have come up with a crude first
version. I'd appreciate if some of the more experienced members of this
list could take a quick look at the program and comment on the code and
the content of the lessons.
   I've written 7 lessons till now. The order is roughly based on the
standard python tutorial on python.org.
   I've used Tkinter for the GUI because it's widely available. I've
tried to keep all the GUI functionality in a separate module so that I
can add (maybe) GTK support later on.

   The whole thing is available as a tarball from
http://nibrahim.net.in/downloads/pydagogue-0.1.tgz
   I'd really appreciate some comments and feedback on what everyone
thinks about the project.

Thanks much.

-- 
~noufal

From bgailer at alum.rpi.edu  Sun Apr  8 19:32:22 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 08 Apr 2007 10:32:22 -0700
Subject: [Tutor] Addressing a variable whose name is the value of a
	string
In-Reply-To: <461917EB.4010501@web.de>
References: <461917EB.4010501@web.de>
Message-ID: <46192726.6090500@alum.rpi.edu>

Andreas Pfrengle wrote:
> Hello,
>
> I want to change the value of a variable whose name I don't know, but
> this name is stored as a string in another variable, like:
>
> x = 1
> var = 'x'
>
> Now I want to change the value of x, but address it via var. 
exec is the statement for doing this, but the need to do this can always 
be met better by using a dictionary instead of global variables.

-- 
Bob Gailer
510-978-4454


From clajo04 at mac.com  Sun Apr  8 19:51:38 2007
From: clajo04 at mac.com (John Clark)
Date: Sun, 8 Apr 2007 13:51:38 -0400
Subject: [Tutor] Addressing a variable whose name is the value of
	a	string
In-Reply-To: <46192726.6090500@alum.rpi.edu>
References: <461917EB.4010501@web.de> <46192726.6090500@alum.rpi.edu>
Message-ID: <006401c77a06$8f6bfd40$fefea8c0@haengma>

Bob Gailer wrote:
>Andreas Pfrengle wrote:
>> Hello,
>>
>> I want to change the value of a variable whose name I don't know, but 
>> this name is stored as a string in another variable, like:
>>
>> x = 1
>> var = 'x'
>>
>> Now I want to change the value of x, but address it via var. 
>
>exec is the statement for doing this, but the need to do this can always be
met better by using a dictionary instead of global variables.
>

I think you can also do this with

globals()[var] 

-or- 

locals()[var]

But I am not sure what the pros/cons for doing something like this would
be...

-jdc 



From spelzdinkelclonk at web.de  Sun Apr  8 20:29:48 2007
From: spelzdinkelclonk at web.de (Andreas Pfrengle)
Date: Sun, 08 Apr 2007 20:29:48 +0200
Subject: [Tutor] Addressing a variable whose name is the value of a
	string
In-Reply-To: <46192726.6090500@alum.rpi.edu>
References: <461917EB.4010501@web.de> <46192726.6090500@alum.rpi.edu>
Message-ID: <4619349C.4010802@web.de>

Bob Gailer wrote:

> Andreas Pfrengle wrote:
>
>> Hello,
>>
>> I want to change the value of a variable whose name I don't know, but
>> this name is stored as a string in another variable, like:
>>
>> x = 1
>> var = 'x'
>>
>> Now I want to change the value of x, but address it via var. 
>
> exec is the statement for doing this, but the need to do this can 
> always be met better by using a dictionary instead of global variables.
>
Thanks Bob, the 'exec' saved me. But I'm not sure how I could solve my 
specific problem with a dict, since my 'var' variable is a string I'm 
getting from a database-field, that refers to the name of another field, 
which should be changed. So I see no other way than resolving the string 
in some instance - or is there?

From spelzdinkelclonk at web.de  Sun Apr  8 23:47:36 2007
From: spelzdinkelclonk at web.de (Andreas Pfrengle)
Date: Sun, 08 Apr 2007 23:47:36 +0200
Subject: [Tutor] Addressing a variable whose name is the value of
	a	string
In-Reply-To: <46195808.5040101@gmail.com>
References: <461917EB.4010501@web.de> <46192726.6090500@alum.rpi.edu>
	<4619349C.4010802@web.de> <46195808.5040101@gmail.com>
Message-ID: <461962F8.8040108@web.de>

Jordan Greenberg wrote:

>Andreas Pfrengle wrote:
>  
>
>>Bob Gailer wrote:
>>
>>    
>>
>>>Andreas Pfrengle wrote:
>>>
>>>      
>>>
>>>>Hello,
>>>>
>>>>I want to change the value of a variable whose name I don't know, but
>>>>this name is stored as a string in another variable, like:
>>>>
>>>>x = 1
>>>>var = 'x'
>>>>
>>>>Now I want to change the value of x, but address it via var. 
>>>>        
>>>>
>>>exec is the statement for doing this, but the need to do this can 
>>>always be met better by using a dictionary instead of global variables.
>>>
>>>      
>>>
>>Thanks Bob, the 'exec' saved me. But I'm not sure how I could solve my 
>>specific problem with a dict, since my 'var' variable is a string I'm 
>>getting from a database-field, that refers to the name of another field, 
>>which should be changed. So I see no other way than resolving the string 
>>in some instance - or is there?
>>    
>>
>
>Sure, you do something like:
>mydict={'x':1, 'y':2}
>var='x'
>mydict[var]=5
>and then you just access it like mydict['x'] instead of just x.
>Jordan
>
>  
>
Hi Jordan,
looks good if I'm happy with my values inside mydict and don't want to 
have sth. like x=5 in the end. But since 'x' is the name of a database 
field (I simplified it here for an example), I still see no way around 
the exec, so I can change the content of the x-field (consider the 
content of the var-field as a vector to the corresponding field that 
needs a change, x in the example).
If this is still possible with a dict, I still don't see it (sorry), but 
it would surely be more elegant than an exec-solution, since I don't 
need security checks for the string that is saved, before executing it.
Andreas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070408/64cc6fde/attachment.html 

From deliberatus at verizon.net  Sun Apr  8 23:29:40 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sun, 08 Apr 2007 18:29:40 -0300
Subject: [Tutor] HTML IN PYTHON AND OTHER DELIGHTS
Message-ID: <46195EC4.5070609@verizon.net>

OK, riddle me this.

Using css, I supressed the bullet in unordered lists. The Print line 
prints an '*' before the item in the listing. so you will see displayed:

* abba
* abbb
* abbc
* abbd

so the listing can be copied and pasted into a listing in a wiki page.
It works. but when you mouse copy and paste, you get this:


# * abba
# * abbb
# * abbc
# * abbd

which did not display. Intresting. why, and how to overcome this design 
misfeature?



-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rikard.bosnjakovic at gmail.com  Mon Apr  9 00:57:12 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 9 Apr 2007 00:57:12 +0200
Subject: [Tutor] HTML IN PYTHON AND OTHER DELIGHTS
In-Reply-To: <46195EC4.5070609@verizon.net>
References: <46195EC4.5070609@verizon.net>
Message-ID: <d9e88eaf0704081557p2a7337f0j87a72b08a985338a@mail.gmail.com>

On 4/8/07, Kirk Bailey <deliberatus at verizon.net> wrote:

> It works. but when you mouse copy and paste, you get this:
[...]

This has what to do with Python?


-- 
- Rikard - http://bos.hack.org/cv/

From bgailer at alum.rpi.edu  Mon Apr  9 01:11:12 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 08 Apr 2007 16:11:12 -0700
Subject: [Tutor] Addressing a variable whose name is the value
	of	a	string
In-Reply-To: <461962F8.8040108@web.de>
References: <461917EB.4010501@web.de>
	<46192726.6090500@alum.rpi.edu>	<4619349C.4010802@web.de>
	<46195808.5040101@gmail.com> <461962F8.8040108@web.de>
Message-ID: <46197690.7050103@alum.rpi.edu>

Andreas Pfrengle wrote:
> [snip]

> looks good if I'm happy with my values inside mydict and don't want to 
> have sth. like x=5 in the end. But since 'x' is the name of a database 
> field (I simplified it here for an example), I still see no way around 
> the exec, so I can change the content of the x-field (consider the 
> content of the var-field as a vector to the corresponding field that 
> needs a change, x in the example).
> If this is still possible with a dict, I still don't see it (sorry), 
> but it would surely be more elegant than an exec-solution, since I 
> don't need security checks for the string that is saved, before 
> executing it.
I'd love to help, but am confused. If your code (at least the relevant 
part) is of reasonable size, would you post it?

Or at least some pseudo-code so I can follow your algorithm?

-- 
Bob Gailer
510-978-4454


From kent37 at tds.net  Mon Apr  9 01:55:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 08 Apr 2007 19:55:40 -0400
Subject: [Tutor] Addressing a variable whose name is the value of
	a	string
In-Reply-To: <4619349C.4010802@web.de>
References: <461917EB.4010501@web.de> <46192726.6090500@alum.rpi.edu>
	<4619349C.4010802@web.de>
Message-ID: <461980FC.8030702@tds.net>

Andreas Pfrengle wrote:
> Bob Gailer wrote:

>>> Now I want to change the value of x, but address it via var. 
>> exec is the statement for doing this, but the need to do this can 
>> always be met better by using a dictionary instead of global variables.
>>
> Thanks Bob, the 'exec' saved me. But I'm not sure how I could solve my 
> specific problem with a dict, since my 'var' variable is a string I'm 
> getting from a database-field, that refers to the name of another field, 
> which should be changed. So I see no other way than resolving the string 
> in some instance - or is there?

It sounds like your database value is the one that should be stored in a 
dictionary, or as an attribute of a class instance (which can be changed 
with setattr()).

Kent

From kent37 at tds.net  Mon Apr  9 01:58:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 08 Apr 2007 19:58:33 -0400
Subject: [Tutor] Addressing a variable whose name is the value
	of	a	string
In-Reply-To: <006401c77a06$8f6bfd40$fefea8c0@haengma>
References: <461917EB.4010501@web.de> <46192726.6090500@alum.rpi.edu>
	<006401c77a06$8f6bfd40$fefea8c0@haengma>
Message-ID: <461981A9.90207@tds.net>

John Clark wrote:

> locals()[var]
> 
> But I am not sure what the pros/cons for doing something like this would
> be...

locals() should be considered read-only. From the docs:

locals(  	)
     Update and return a dictionary representing the current local 
symbol table. Warning: The contents of this dictionary should not be 
modified; changes may not affect the values of local variables used by 
the interpreter.

At global scope, locals() == globals() and modifying locals() will work. 
Within a function, modifying locals() will not do what you want.

Kent

From alan.gauld at btinternet.com  Mon Apr  9 01:59:06 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 9 Apr 2007 00:59:06 +0100
Subject: [Tutor] Fw: 2) 'WHICH MULTI'
References: <20070330231751.95294.qmail@web86114.mail.ird.yahoo.com>
	<Pine.LNX.4.44.0704021012560.25797-100000@violet.rahul.net>
Message-ID: <evbvkj$ih5$1@sea.gmane.org>


"Terry Carroll" <carroll at tjc.com> wrote 
>> One of my tutorial users has come upon a really weird bug.
>> 
>> He has sent a transcript oif his session. Notice that wx 
>> is not defined yet doing help(wx) produces a strange message.
> 
> Very weird.  Here's what I get, weird in a different way...

Just for completeness...

I don't know what caused Terry's problem but the guy who wrote 
to me solved his problem. He had a rogue file new.pyc without 
a corresponding new.py. I still don't understand how that got 
picked up by help() but deleting the rogue file made the problem 
go away...

Alan G.



From deliberatus at verizon.net  Mon Apr  9 05:53:26 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Mon, 09 Apr 2007 00:53:26 -0300
Subject: [Tutor] Command line args
In-Reply-To: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
References: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
Message-ID: <4619B8B6.8010104@verizon.net>



Teresa Stanton wrote:
> If one argument to a script is provided I am to take the input from it.  
> I figure that is presented like this:
> 
> filename = sys.argv[1]
Try:
	filename=sys.arg[1]
except exception, E:
	filename='FooBar'

> data = open(filename).read()
> 
> But, if none are provided, input should come from standard input.  How 
> do I write that code?
> 
> TY
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> ------------------------------------------------------------------------
> 
> No virus found in this incoming message.
> Checked by AVG Free Edition.
> Version: 7.5.446 / Virus Database: 269.0.0/750 - Release Date: 4/6/2007 9:30 PM

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.


From hugonz-lists at h-lab.net  Mon Apr  9 08:04:38 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Mon, 09 Apr 2007 01:04:38 -0500
Subject: [Tutor] how to run a text file in an interpreter?
In-Reply-To: <460D41D9.60007@umn.edu>
References: <460D41D9.60007@umn.edu>
Message-ID: <4619D776.6010705@h-lab.net>

Hi Tonu,

Tonu Mikk wrote:
> I do not know what the author means by running a text file with the 
> interpreter. I noticed that I came across an obstacle early on in trying 
> out the code.

What plattform are you in? Linux, Windows, Mac?

Check out the faqs at:

http://www.python.org/doc/faq/windows/#how-do-i-run-a-python-program-under-windows


From rdm at rcblue.com  Mon Apr  9 11:29:21 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 09 Apr 2007 02:29:21 -0700
Subject: [Tutor] Creating new files w/o overwriting existing ones
Message-ID: <20070409093008.54E841E4016@bag.python.org>

Sorry if my Subject line isn't clear about what my question is.

I have a script that uses the turtle and random modules to create SVG 
files, one after another, in a directory just for the SVGs. The 
script assigns filenames in the form, "n.svg", where n is an integer. 
E.g. 1.svg, 2.svg. 3.svg, ... 44.svg, 45.svg. As it is now, I have to 
reset the starting integer when restarting the script, so as to not 
overwrite the files already created. Thus if the highest number 
filename is 45.svg, I have to configure the script so that it begins 
to create SVGs with filenames of 46.svg on up.

I'm hoping to add a function that will find find that highest number 
filename in the directory. Is this possible?

I should add that the numbers of the existing files will not 
necessarily be consecutive. There could be gaps. E.g., 4.svg., 
5.svg., 8.svg, 9.svg.

Thanks,

Dick Moores
Win XP
Python 2.5


From jordangreenberg at gmail.com  Sun Apr  8 23:00:56 2007
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Sun, 08 Apr 2007 17:00:56 -0400
Subject: [Tutor] Addressing a variable whose name is the value of
	a	string
In-Reply-To: <4619349C.4010802@web.de>
References: <461917EB.4010501@web.de> <46192726.6090500@alum.rpi.edu>
	<4619349C.4010802@web.de>
Message-ID: <46195808.5040101@gmail.com>

Andreas Pfrengle wrote:
> Bob Gailer wrote:
> 
>> Andreas Pfrengle wrote:
>>
>>> Hello,
>>>
>>> I want to change the value of a variable whose name I don't know, but
>>> this name is stored as a string in another variable, like:
>>>
>>> x = 1
>>> var = 'x'
>>>
>>> Now I want to change the value of x, but address it via var. 
>> exec is the statement for doing this, but the need to do this can 
>> always be met better by using a dictionary instead of global variables.
>>
> Thanks Bob, the 'exec' saved me. But I'm not sure how I could solve my 
> specific problem with a dict, since my 'var' variable is a string I'm 
> getting from a database-field, that refers to the name of another field, 
> which should be changed. So I see no other way than resolving the string 
> in some instance - or is there?

Sure, you do something like:
mydict={'x':1, 'y':2}
var='x'
mydict[var]=5
and then you just access it like mydict['x'] instead of just x.
Jordan

-- 
I prefer encrypted mail. My key is available at:
http://myweb.wit.edu/greenbergj/publickey.txt

From kent37 at tds.net  Mon Apr  9 12:39:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 09 Apr 2007 06:39:46 -0400
Subject: [Tutor] Creating new files w/o overwriting existing ones
In-Reply-To: <20070409093008.54E841E4016@bag.python.org>
References: <20070409093008.54E841E4016@bag.python.org>
Message-ID: <461A17F2.6060602@tds.net>

Dick Moores wrote:
> Sorry if my Subject line isn't clear about what my question is.
> 
> I have a script that uses the turtle and random modules to create SVG 
> files, one after another, in a directory just for the SVGs. The 
> script assigns filenames in the form, "n.svg", where n is an integer. 
> E.g. 1.svg, 2.svg. 3.svg, ... 44.svg, 45.svg. As it is now, I have to 
> reset the starting integer when restarting the script, so as to not 
> overwrite the files already created. Thus if the highest number 
> filename is 45.svg, I have to configure the script so that it begins 
> to create SVGs with filenames of 46.svg on up.
> 
> I'm hoping to add a function that will find find that highest number 
> filename in the directory. Is this possible?
> 
> I should add that the numbers of the existing files will not 
> necessarily be consecutive. There could be gaps. E.g., 4.svg., 

Just look at the existing files and figure out the max. This is pretty 
straightforward with os.listdir(), simple string manipulations - 
endswith() and split() or os.path.splitext() - and the int() function to 
convert the prefix to an integer.

I wasn't going to show you the code but I can't resist putting it into a 
one-liner (which will break if you have other files in the same dir) -
max(int(os.path.splitext(f)[0]) for f in os.listdir(...) if 
f.endswith('.svg'))

Setting a bad example for tutors everywhere :-)
Kent

From rikard.bosnjakovic at gmail.com  Mon Apr  9 13:46:51 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 9 Apr 2007 13:46:51 +0200
Subject: [Tutor] Movies from jpg files
In-Reply-To: <OF22E1F382.C6C56EEB-ONC12572B6.003737BC-C12572B6.0038D669@velux.com>
References: <mailman.39.1175940011.28072.tutor@python.org>
	<OF22E1F382.C6C56EEB-ONC12572B6.003737BC-C12572B6.0038D669@velux.com>
Message-ID: <d9e88eaf0704090446y3488e4f3n62e18e6a9f87983c@mail.gmail.com>

On 4/7/07, J?nos Juh?sz <janos.juhasz at velux.com> wrote:

> May you recommend anything to build them easy ?

I use this C-shell script for the same purpose. Even if it doesn't add
up to the features you want, you can always use it as reference for
re-hacking.


-- 
- Rikard - http://bos.hack.org/cv/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: makempeg.csh
Type: application/x-csh
Size: 4993 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070409/f2b6cee5/attachment.csh 

From rikard.bosnjakovic at gmail.com  Mon Apr  9 13:48:42 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 9 Apr 2007 13:48:42 +0200
Subject: [Tutor] reassign
In-Reply-To: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
References: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
Message-ID: <d9e88eaf0704090448v3c9c4501rde6434c49e400501@mail.gmail.com>

On 4/8/07, linda.s <samrobertsmith at gmail.com> wrote:

> how i can randomly reassign the values to different location in the list?

>>> import random
>>> mylist = [1,2,3,4,5,6,7,8,9]
>>> mylist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(mylist)
>>> mylist
[3, 6, 9, 4, 7, 1, 2, 8, 5]


-- 
- Rikard - http://bos.hack.org/cv/

From rdm at rcblue.com  Mon Apr  9 15:47:22 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 09 Apr 2007 06:47:22 -0700
Subject: [Tutor] Creating new files w/o overwriting existing ones
In-Reply-To: <461A17F2.6060602@tds.net>
References: <20070409093008.54E841E4016@bag.python.org>
	<461A17F2.6060602@tds.net>
Message-ID: <20070409134731.736BF1E400B@bag.python.org>

At 03:39 AM 4/9/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>Sorry if my Subject line isn't clear about what my question is.
>>I have a script that uses the turtle and random modules to create 
>>SVG files, one after another, in a directory just for the SVGs. The 
>>script assigns filenames in the form, "n.svg", where n is an 
>>integer. E.g. 1.svg, 2.svg. 3.svg, ... 44.svg, 45.svg. As it is 
>>now, I have to reset the starting integer when restarting the 
>>script, so as to not overwrite the files already created. Thus if 
>>the highest number filename is 45.svg, I have to configure the 
>>script so that it begins to create SVGs with filenames of 46.svg on up.
>>I'm hoping to add a function that will find find that highest 
>>number filename in the directory. Is this possible?
>>I should add that the numbers of the existing files will not 
>>necessarily be consecutive. There could be gaps. E.g., 4.svg.,
>
>Just look at the existing files and figure out the max. This is 
>pretty straightforward with os.listdir(), simple string 
>manipulations - endswith() and split() or os.path.splitext() - and 
>the int() function to convert the prefix to an integer.
>
>I wasn't going to show you the code but I can't resist putting it 
>into a one-liner (which will break if you have other files in the same dir) -
>max(int(os.path.splitext(f)[0]) for f in os.listdir(...) if 
>f.endswith('.svg'))
>
>Setting a bad example for tutors everywhere :-)

Thanks, Kent. All I really needed to know was that there was an 
os.listdir(). I thought I'd try writing the function without looking 
at how you got the max, and here's what I came up with:

def nextSVGnum():
     lstSvg = listdir("E:\Python25\dev\Turtle\SVG")
     lstNums = []
     for x in lstSvg:
         num = int(x.split('.')[0])
         lstNums.append(num)
     nextSVGnum = max(lstNums) + 1
     return nextSVGnum

This fits with the function that creates the SVG:
def createSVG(nextSVGnum):
     fldrPth = "E:\Python25\dev\Turtle\SVG\\"
     svgName = str(nextSVGnum) + ".svg"
     SVG_path = fldrPth + svgName
     canvasvg.saveall(SVG_path, T._canvas)
     return nextSVGnum + 1

BTW for anyone interested, I got the canvasvg module from 
<http://wmula.republika.pl/proj/canvas2svg/>.

Dick 


From alan.gauld at btinternet.com  Mon Apr  9 17:19:47 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 9 Apr 2007 16:19:47 +0100
Subject: [Tutor] Creating new files w/o overwriting existing ones
References: <20070409093008.54E841E4016@bag.python.org><461A17F2.6060602@tds.net>
	<20070409134731.736BF1E400B@bag.python.org>
Message-ID: <evdlis$5ou$1@sea.gmane.org>

"Dick Moores" <rdm at rcblue.com> wrote 

>     lstNums = []
>     for x in lstSvg:
>         num = int(x.split('.')[0])
>         lstNums.append(num)

This is exactly what a list comp does so you could rewrite it as:

lstNums = [int(x.split('.')[0]) for x in lstSvg]

One of the cases where I actually think a list comprehension 
is more readable than the expanded code.

>     nextSVGnum = max(lstNums) + 1
>     return nextSVGnum


HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From spelzdinkelclonk at web.de  Mon Apr  9 17:53:38 2007
From: spelzdinkelclonk at web.de (Andreas Pfrengle)
Date: Mon, 09 Apr 2007 17:53:38 +0200
Subject: [Tutor] Addressing a variable whose name is the value of a
	string
In-Reply-To: <46197690.7050103@alum.rpi.edu>
References: <461917EB.4010501@web.de>
	<46192726.6090500@alum.rpi.edu>	<4619349C.4010802@web.de>
	<46195808.5040101@gmail.com> <461962F8.8040108@web.de>
	<46197690.7050103@alum.rpi.edu>
Message-ID: <461A6182.3070504@web.de>

Bob Gailer wrote:

> Andreas Pfrengle wrote:
>
>> [snip]
>
>> looks good if I'm happy with my values inside mydict and don't want 
>> to have sth. like x=5 in the end. But since 'x' is the name of a 
>> database field (I simplified it here for an example), I still see no 
>> way around the exec, so I can change the content of the x-field 
>> (consider the content of the var-field as a vector to the 
>> corresponding field that needs a change, x in the example).
>> If this is still possible with a dict, I still don't see it (sorry), 
>> but it would surely be more elegant than an exec-solution, since I 
>> don't need security checks for the string that is saved, before 
>> executing it.
>
> I'd love to help, but am confused. If your code (at least the relevant 
> part) is of reasonable size, would you post it?
>
> Or at least some pseudo-code so I can follow your algorithm?
>
Since I'm still considering the way my db has to look, the mentioned 
problem was already thought in advance to what I will have to solve, so 
real db-interaction code doesn't exist yet. I'm using the django 
framework for this, so the essential parts might later look sth. like:

# Accessing db (see http://www.djangoproject.com/documentation/db-api/):
myobj = MyModel.objects.get(<some filter>)
var = myobj.vector
# vector is a Textfield, so var now contains a string, naming another 
db-field of myobj

execstr = "attr = myobj." + var
exec execstr
# attr now contains the content of the field named in var (an int in my 
case)
attr += 42    #some calculation with attr

execstr = "myobj." + var + " = attr"
exec execstr
myobj.save()
#the newly calculated value is now saved back to the desired field

(This is still simplified, since the vector can also reach other models, 
so there has to be more programming logic in the end)

From emilia12 at mail.bg  Mon Apr  9 17:57:26 2007
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Mon, 09 Apr 2007 18:57:26 +0300
Subject: [Tutor]  how to split a stream of chars
In-Reply-To: <mailman.43.1176112811.18536.tutor@python.org>
References: <mailman.43.1176112811.18536.tutor@python.org>
Message-ID: <1176134246.eaa416bb1af59@mail.bg>

hi list,

i have a long stream of data, represented in hexadecimal
form. I need to split it in bytes (by 2 chars each). eg
'00010203040506'... -> ['00', '01, '02' ...].
So my question is: is there an inverse function of zip, or
an easy way to split this long string in pairs (without
indexing in cycle, nor regexpr.)?

Emily

-----------------------------

SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? ??????????.
http://www.bgscena.com/


From kent37 at tds.net  Mon Apr  9 18:04:08 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 09 Apr 2007 12:04:08 -0400
Subject: [Tutor] Addressing a variable whose name is the value of
	a	string
In-Reply-To: <461A6182.3070504@web.de>
References: <461917EB.4010501@web.de>	<46192726.6090500@alum.rpi.edu>	<4619349C.4010802@web.de>	<46195808.5040101@gmail.com>
	<461962F8.8040108@web.de>	<46197690.7050103@alum.rpi.edu>
	<461A6182.3070504@web.de>
Message-ID: <461A63F8.4000603@tds.net>

Andreas Pfrengle wrote:
> # Accessing db (see http://www.djangoproject.com/documentation/db-api/):
> myobj = MyModel.objects.get(<some filter>)
> var = myobj.vector
> # vector is a Textfield, so var now contains a string, naming another 
> db-field of myobj
> 
> execstr = "attr = myobj." + var
> exec execstr
> # attr now contains the content of the field named in var (an int in my 
> case)

Use
attr = getattr(myobj, var)

> attr += 42    #some calculation with attr
> 
> execstr = "myobj." + var + " = attr"
> exec execstr

setattr(myobj, var, attr)

Kent

From spelzdinkelclonk at web.de  Mon Apr  9 18:18:29 2007
From: spelzdinkelclonk at web.de (Andreas Pfrengle)
Date: Mon, 09 Apr 2007 18:18:29 +0200
Subject: [Tutor] Addressing a variable whose name is the value of
	a	string
In-Reply-To: <461A63F8.4000603@tds.net>
References: <461917EB.4010501@web.de>	<46192726.6090500@alum.rpi.edu>	<4619349C.4010802@web.de>	<46195808.5040101@gmail.com>
	<461962F8.8040108@web.de>	<46197690.7050103@alum.rpi.edu>
	<461A6182.3070504@web.de> <461A63F8.4000603@tds.net>
Message-ID: <461A6755.6090901@web.de>

Kent Johnson wrote:

> Andreas Pfrengle wrote:
>
>> # Accessing db (see http://www.djangoproject.com/documentation/db-api/):
>> myobj = MyModel.objects.get(<some filter>)
>> var = myobj.vector
>> # vector is a Textfield, so var now contains a string, naming another 
>> db-field of myobj
>>
>> execstr = "attr = myobj." + var
>> exec execstr
>> # attr now contains the content of the field named in var (an int in 
>> my case)
>
>
> Use
> attr = getattr(myobj, var)
>
>> attr += 42    #some calculation with attr
>>
>> execstr = "myobj." + var + " = attr"
>> exec execstr
>
>
> setattr(myobj, var, attr)
>
> Kent
>
Thanks Kent, I've just looked up getattr and setattr, and since they 
take strings for the addressed attributes, this really seems to be the 
optimal solution! :)

From alan.gauld at btinternet.com  Mon Apr  9 19:03:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 9 Apr 2007 18:03:01 +0100
Subject: [Tutor] how to split a stream of chars
References: <mailman.43.1176112811.18536.tutor@python.org>
	<1176134246.eaa416bb1af59@mail.bg>
Message-ID: <evdrke$pa5$1@sea.gmane.org>


<emilia12 at mail.bg> wrote 
> i have a long stream of data, represented in hexadecimal
> form. I need to split it in bytes (by 2 chars each). eg
> '00010203040506'... -> ['00', '01, '02' ...].

> So my question is: is there an inverse function of zip, or
> an easy way to split this long string in pairs (without
> indexing in cycle, nor regexpr.)?

I'm not quite sure what you mean by 'indexing in cycle' 
but you will need some kind of loop to extract this data
whether explicit or hidden inside a library function.

My guess is the simplest solution is to use list slicing 
and a list comprehension with a step size of 2. 
Something like:

bytes = [stream[start :start+2] for start in range(0,len(stream),2)]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
     


From humbolt at comcast.net  Mon Apr  9 19:44:48 2007
From: humbolt at comcast.net (Robert H. Haener IV)
Date: Mon, 09 Apr 2007 13:44:48 -0400
Subject: [Tutor] copy2 arguments?
Message-ID: <461A7B90.8060803@comcast.net>

Hey folks, I just need to know if shutil.copy2() will accept a directory as the destination or if I have to supply a full path including the name of the file (e.g. "C:\foo\bar.txt" as opposed to "C:\foo\").  The target is 32-bit Windows XP with Python 2.5.


-Robert

From humbolt at comcast.net  Mon Apr  9 19:49:19 2007
From: humbolt at comcast.net (Robert H. Haener IV)
Date: Mon, 09 Apr 2007 13:49:19 -0400
Subject: [Tutor] copy2 arguments?
In-Reply-To: <461A7B90.8060803@comcast.net>
References: <461A7B90.8060803@comcast.net>
Message-ID: <461A7C9F.4000105@comcast.net>

Never mind, SPE answered my question for me.  Heh, I may have to stop coding Python in vim  8?}


-Robert

From rdm at rcblue.com  Mon Apr  9 20:19:26 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 09 Apr 2007 11:19:26 -0700
Subject: [Tutor] Creating new files w/o overwriting existing ones
In-Reply-To: <evdlis$5ou$1@sea.gmane.org>
References: <20070409093008.54E841E4016@bag.python.org>
	<461A17F2.6060602@tds.net>
	<20070409134731.736BF1E400B@bag.python.org>
	<evdlis$5ou$1@sea.gmane.org>
Message-ID: <20070409181936.4805B1E400A@bag.python.org>

At 08:19 AM 4/9/2007, Alan Gauld wrote:
>"Dick Moores" <rdm at rcblue.com> wrote
>
> >     lstNums = []
> >     for x in lstSvg:
> >         num = int(x.split('.')[0])
> >         lstNums.append(num)
>
>This is exactly what a list comp does so you could rewrite it as:
>
>lstNums = [int(x.split('.')[0]) for x in lstSvg]
>
>One of the cases where I actually think a list comprehension
>is more readable than the expanded code.

Thanks, Alan. I'll use it.

> >     nextSVGnum = max(lstNums) + 1
> >     return nextSVGnum

Dick



From kent37 at tds.net  Mon Apr  9 20:27:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 09 Apr 2007 14:27:40 -0400
Subject: [Tutor] Creating new files w/o overwriting existing ones
In-Reply-To: <evdlis$5ou$1@sea.gmane.org>
References: <20070409093008.54E841E4016@bag.python.org><461A17F2.6060602@tds.net>	<20070409134731.736BF1E400B@bag.python.org>
	<evdlis$5ou$1@sea.gmane.org>
Message-ID: <461A859C.7030404@tds.net>

Alan Gauld wrote:
> "Dick Moores" <rdm at rcblue.com> wrote 
> 
>>     lstNums = []
>>     for x in lstSvg:
>>         num = int(x.split('.')[0])
>>         lstNums.append(num)
> 
> This is exactly what a list comp does so you could rewrite it as:
> 
> lstNums = [int(x.split('.')[0]) for x in lstSvg]
> 
> One of the cases where I actually think a list comprehension 
> is more readable than the expanded code.

And from there it is just one more step to skip the list completely:

nextSVGnum = max(int(x.split('.')[0]) for x in lstSvg) + 1

Kent

From bgailer at alum.rpi.edu  Mon Apr  9 20:43:27 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 09 Apr 2007 11:43:27 -0700
Subject: [Tutor] how to split a stream of chars
In-Reply-To: <evdrke$pa5$1@sea.gmane.org>
References: <mailman.43.1176112811.18536.tutor@python.org>	<1176134246.eaa416bb1af59@mail.bg>
	<evdrke$pa5$1@sea.gmane.org>
Message-ID: <461A894F.90005@alum.rpi.edu>

<emilia12 at mail.bg> wrote
>> i have a long stream of data, represented in hexadecimal
>> form. I need to split it in bytes (by 2 chars each). eg
>> '00010203040506'... -> ['00', '01, '02' ...].
>>     
>> So my question is: is there an inverse function of zip, or
>> an easy way to split this long string in pairs (without
>> indexing in cycle, nor regexpr.)?
>>     
I'm developing a Python version of IBM's CMS Pipelines (see 
http://en.wikipedia.org/wiki/Hartmann_pipeline).

You'd apply it to your problem thus:

import pipeline
result = pipeline.pipe('deblock 2', '00010203040506...')

Does this interest you? (The capabilities of Pipelines is MUCH bigger 
than this example!)
Would you like to be an alpha tester of this tool?

-- 
Bob Gailer
510-978-4454


From rabidpoobear at gmail.com  Mon Apr  9 23:42:49 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 09 Apr 2007 16:42:49 -0500
Subject: [Tutor] Command line args
In-Reply-To: <4619B8B6.8010104@verizon.net>
References: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
	<4619B8B6.8010104@verizon.net>
Message-ID: <461AB359.2060607@gmail.com>

Kirk Bailey wrote:
> Teresa Stanton wrote:
>   
>> If one argument to a script is provided I am to take the input from it.  
>> I figure that is presented like this:
>>
>> filename = sys.argv[1]
>>     
> Try:
>   
the 'try' keyword is not capitalized in Python.
> 	filename=sys.arg[1]
> except exception, E:
>   
you should only catch the exception you expect, so you don't 
accidentally silence an unrelated error.
so
except IndexError:
because you're trying to index into a list that might not have 2 or more 
elements.
> 	filename='FooBar'
>   
You said you wanted the input from standard input, so just put a 
raw_input here.

so the new code is:

try: filename = sys.argv[1]
except IndexError: filename = raw_input("Prompt: ")

HTH,
-Luke

From alan.gauld at btinternet.com  Tue Apr 10 00:27:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 9 Apr 2007 23:27:35 +0100
Subject: [Tutor] copy2 arguments?
References: <461A7B90.8060803@comcast.net> <461A7C9F.4000105@comcast.net>
Message-ID: <eveel0$nv5$1@sea.gmane.org>


"Robert H. Haener IV" <humbolt at comcast.net> wrote 

>...., I may have to stop coding Python in vim  8?}

vim 8?!!
I didn't hardly notice that vim 7 was out!

Time for an upgrade I guess...

Alan G


From humbolt at comcast.net  Tue Apr 10 02:54:13 2007
From: humbolt at comcast.net (Robert H. Haener IV)
Date: Mon, 09 Apr 2007 20:54:13 -0400
Subject: [Tutor] vim confusion (was copy2 arguments?)
In-Reply-To: <eveel0$nv5$1@sea.gmane.org>
References: <461A7B90.8060803@comcast.net> <461A7C9F.4000105@comcast.net>
	<eveel0$nv5$1@sea.gmane.org>
Message-ID: <461AE035.4070603@comcast.net>

Alan,

What you mistook for "vim 8" (with some garbage afterward) was in fact a smiley I use frequently.


-Robert

From deliberatus at verizon.net  Tue Apr 10 04:28:59 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Mon, 09 Apr 2007 23:28:59 -0300
Subject: [Tutor] Command line args
In-Reply-To: <461AB359.2060607@gmail.com>
References: <000001c7792e$dbf4d2a0$2dbbe942@samiam>
	<4619B8B6.8010104@verizon.net> <461AB359.2060607@gmail.com>
Message-ID: <461AF66B.5020804@verizon.net>

ok, try this:

Try:
	filename=sys.arv[1]
except Exception, e:
	if filename='':
		filename='foo'		# define a default value
	else:
		if foo:			# detect one likely error
			foobarcode
	else:
		if bar:			# detect another one
			morefoobarcode
	else:				# final catchall for things you
					# did not anticipate
		Print 'how the heck did you accomplish this?!? I QUIT~!
		sys.exit(13)

i has something vauely like this in the wiki on the slab right now, 
except it was addressing the query string. other than that, same problem.

another idea is simply detect that there IS a argument;

if sys.argv[1];
	filename=sys.argv[1]
	if condition:
		do something
	else:
		do this instead
else:
	filename="foo"

which avoids try altogether. Somehow I kinda like this way more.



Luke Paireepinart wrote:
> Kirk Bailey wrote:
>> Teresa Stanton wrote:
>>  
>>> If one argument to a script is provided I am to take the input from 
>>> it.  I figure that is presented like this:
>>>
>>> filename = sys.argv[1]
>>>     
>> Try:
>>   
> the 'try' keyword is not capitalized in Python.
>>     filename=sys.arg[1]
>> except exception, E:
>>   
> you should only catch the exception you expect, so you don't 
> accidentally silence an unrelated error.
> so
> except IndexError:
> because you're trying to index into a list that might not have 2 or more 
> elements.
>>     filename='FooBar'
>>   
> You said you wanted the input from standard input, so just put a 
> raw_input here.
> 
> so the new code is:
> 
> try: filename = sys.argv[1]
> except IndexError: filename = raw_input("Prompt: ")
> 
> HTH,
> -Luke
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rabidpoobear at gmail.com  Tue Apr 10 08:51:37 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 10 Apr 2007 01:51:37 -0500
Subject: [Tutor] [Fwd: Re:  Command line args]
Message-ID: <461B33F9.2000206@gmail.com>

Sorry, guys.  Accidentally replied off-list.
-------------- next part --------------
An embedded message was scrubbed...
From: Luke Paireepinart <rabidpoobear at gmail.com>
Subject: Re: [Tutor] Command line args
Date: Tue, 10 Apr 2007 01:50:48 -0500
Size: 3564
Url: http://mail.python.org/pipermail/tutor/attachments/20070410/cafa798b/attachment.mht 

From maseriyer at yahoo.com  Tue Apr 10 09:10:59 2007
From: maseriyer at yahoo.com (Iyer)
Date: Tue, 10 Apr 2007 00:10:59 -0700 (PDT)
Subject: [Tutor] ConfigParser and multiple option names
In-Reply-To: <ev7kaf$da1$1@sea.gmane.org>
Message-ID: <439175.16403.qm@web37710.mail.mud.yahoo.com>

wow, Andrei, that is a really very neat solution ! It
worked. 

So it seems configparser is dict based.

Thanks a lot for your help. 

-iyer

--- Andrei <project5 at redrival.net> wrote:

> Iyer wrote:
> <snop>
> > 
> > I cannot change the config file layout -- it is a
> <snip>
> > [dir_options]
> > dir="/home/florian"
> > dir="/home/john"
> <snip>
> > what method would you suggest to read each "dir"
> value
> > above from the config_file.lay?
> 
> Internally, the ConfigParser implementation uses
> dictionaries to store 
> sections and section contents making it impossible
> to have duplicate 
> sections or option names - this file is against the
> philosophy of the 
> parser.
> If these dir values are all you're interested in,
> you could write a very 
> simple parser only for them in a few lines.
> Alternatively I think you'll have to trick the
> parser into thinking 
> these are different options by overriding
> optionxform, to mangle the 
> option name and make it unique:
> 
>  >>> from random import random
>  >>> class DuplicateOptionParser(ConfigParser):
> ...     def optionxform(self, option):
> ...         return option.lower() + '____' +
> str(random()) + str(random())
> ...
>  >>> parser = DuplicateOptionParser()
>  >>> parser.read('xyz.ini')
>  >>> parser.items('dir_options')
> [('dir____0.2893357144260.69151552211',
> '"/home/whoever"'),
> ('dir____0.8258732656650.272559810163',
> '"/home/florian"'),
> ('dir____0.6565224032210.703769464586',
> '"/home/john"')]
> 
> Note that it will do this for *all* options in your
> file, even those 
> that have no duplicates. You'll have to trim the
> part starting with 
> '____' before using them.
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact
> info:
> ''.join([''.join(s) for s in zip(
> "poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one
> oC.",
> "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn
> edt C")])
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



 
____________________________________________________________________________________
We won't tell. Get more on shows you hate to love 
(and love to hate): Yahoo! TV's Guilty Pleasures list.
http://tv.yahoo.com/collections/265 

From zebra05 at gmail.com  Tue Apr 10 09:26:03 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Tue, 10 Apr 2007 09:26:03 +0200
Subject: [Tutor] File storage vs DB storage.
Message-ID: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com>

Hello all,

Im a newbie and am currently going through the Python Tutorial for the
second time. At work, i use C#, but what a delight Python is!

Ok, to get to the point: when building a web app that should store an
retrieve photos, what would be more efficient between the app storing the
files on a local hard disk, or saving blobs/ binary data to a database?
Someone toldme that database storage should be avoided as it would cause a
botleneck, whereas i dont want to imagine the nightmare of managing tons of
files sitting in a folder. I use Windows XP.


Cheers,

-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070410/c0692870/attachment.htm 

From alan.gauld at btinternet.com  Tue Apr 10 09:38:23 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 10 Apr 2007 08:38:23 +0100
Subject: [Tutor] Command line args
References: <000001c7792e$dbf4d2a0$2dbbe942@samiam><4619B8B6.8010104@verizon.net>
	<461AB359.2060607@gmail.com> <461AF66B.5020804@verizon.net>
Message-ID: <evfeto$gkv$1@sea.gmane.org>

"Kirk Bailey" <deliberatus at verizon.net> wrote 

> Try:
>     filename=sys.arv[1]
> except Exception, e:

This still doesn't help for the problem where a 
different exception is raised.It really does need to be

try: filename = sys.argv[1]:
except IndexError:


>     if filename='':
>         filename='foo' # define a default value
>     else:
>         if foo: # detect one likely error
>             foobarcode
>     else:

This is invalid syntax it would need to be a chain of if/elif/else

> another idea is simply detect that there IS a argument;
> 
> if sys.argv[1];
> filename=sys.argv[1]
> ...
> which avoids try altogether. Somehow I kinda like this way more.

This would still throw an exception if argv[1] doesn't exist 
because the code still tries to access non existent data. 
You cannot get away without using the try/except here 
unless you check the length of argv:

if len(sys.argv) > 1:
    filename = sys.argv[1]

Now you can check whether filename is valid or not.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From hugonz-lists at h-lab.net  Tue Apr 10 09:43:21 2007
From: hugonz-lists at h-lab.net (=?UTF-8?B?SHVnbyBHb256w6FsZXogTW9udGV2ZXJkZQ==?=)
Date: Tue, 10 Apr 2007 02:43:21 -0500
Subject: [Tutor] File storage vs DB storage.
In-Reply-To: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com>
References: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com>
Message-ID: <461B4019.3000404@h-lab.net>

Hi,

Managaing a lot of files is not a nightmare if you use/build the right 
tools.

Why not saving filenames in the DB and then just using the ordinary web 
server to deliver them? Getting the blob out of the DB and then serving 
it through the web app is going to be a lot slower than letting, say, 
Apache do it.

I wrote a system that kept 15000 files in a directory tree. You just let 
your software deal with them....

Hugo

From alan.gauld at btinternet.com  Tue Apr 10 09:40:26 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 10 Apr 2007 08:40:26 +0100
Subject: [Tutor] vim confusion (was copy2 arguments?)
References: <461A7B90.8060803@comcast.net>
	<461A7C9F.4000105@comcast.net><eveel0$nv5$1@sea.gmane.org>
	<461AE035.4070603@comcast.net>
Message-ID: <evff1k$h09$1@sea.gmane.org>


"Robert H. Haener IV" <humbolt at comcast.net> wrote 

> What you mistook for "vim 8" (with some garbage afterward) 
> was in fact a smiley I use frequently.

ROTFL!

:-)

Alan G


From hugonz-lists at h-lab.net  Tue Apr 10 09:48:57 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-2?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Tue, 10 Apr 2007 02:48:57 -0500
Subject: [Tutor] Movies from jpg files
In-Reply-To: <OF22E1F382.C6C56EEB-ONC12572B6.003737BC-C12572B6.0038D669@velux.com>
References: <OF22E1F382.C6C56EEB-ONC12572B6.003737BC-C12572B6.0038D669@velux.com>
Message-ID: <461B4169.2060102@h-lab.net>

J?nos Juh?sz wrote:

> 
> Thanks your response.
> It should works well with some images, but I would do it with a scheduled 
> way
> with some 1000 files.

Hi,

I previously have used python to control mencoder. Mencoder does the 
combining and putting together into a video.

You script the arguments and the command line switches to mencoder. 
Maybe use the subprocess module? or the "commands" module for very 
simple tasks?

http://www.mplayerhq.hu/
http://en.wikipedia.org/wiki/MEncoder

Hugo

From rikard.bosnjakovic at gmail.com  Tue Apr 10 09:50:30 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 10 Apr 2007 09:50:30 +0200
Subject: [Tutor] copy2 arguments?
In-Reply-To: <eveel0$nv5$1@sea.gmane.org>
References: <461A7B90.8060803@comcast.net> <461A7C9F.4000105@comcast.net>
	<eveel0$nv5$1@sea.gmane.org>
Message-ID: <d9e88eaf0704100050w25ebd42m9216285e35dd9b45@mail.gmail.com>

On 4/10/07, Alan Gauld <alan.gauld at btinternet.com> wrote:

> vim 8?!!
> I didn't hardly notice that vim 7 was out!

alias vim='/usr/bin/env emacs'


-- 
- Rikard.

From alan.gauld at btinternet.com  Tue Apr 10 10:00:15 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 10 Apr 2007 08:00:15 +0000 (GMT)
Subject: [Tutor] copy2 arguments?
Message-ID: <989765.99247.qm@web86105.mail.ird.yahoo.com>


> > I didn't hardly notice that vim 7 was out!
> alias vim='/usr/bin/env emacs'

No editor wars please! :-)

But actually I use Xemacs when wortking in Unix but for some 
reason it never felt right on Windows. So I use both depending 
on the OS. (Actually I use vim on Unix too for short edits, but 
I prefer emacs for writing fresh code or long sessions)

Alan G





      ___________________________________________________________ 
Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for
your free account today http://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winter07.html

From alan.gauld at btinternet.com  Tue Apr 10 12:10:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 10 Apr 2007 11:10:05 +0100
Subject: [Tutor] File storage vs DB storage.
References: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com>
Message-ID: <evfnq6$e83$1@sea.gmane.org>

"OkaMthembo" <zebra05 at gmail.com> wrote

> Ok, to get to the point: when building a web app that should store 
> an
> retrieve photos, what would be more efficient between the app 
> storing the
> files on a local hard disk, or saving blobs/ binary data to a 
> database?
> Someone toldme that database storage should be avoided as it
> would cause a botleneck,

I wouldn't say a bottleneck but it can cause problems by
making the database itself very big. That can cause
problems for some operations, including admin tasks.
Some databases work better with blobs than others.

> whereas i dont want to imagine the nightmare of managing
> tons of files sitting in a folder. I use Windows XP.

Naming issues are usually the biggest problem.
It will work best if you use a numrerical naming convention
and manage all of the meta data in the database, along
with the filename.

The advantage of using the file system is that you can
use different folders to help organise the files - folders for
month created or submitter or whatever. Also you can
use the facilities of the OS to create encrypted folders,
secure folders, compressed folders, move the folders
onto other drives as the capacity expands, do incremental
backups etc etc.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Tue Apr 10 20:04:18 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 10 Apr 2007 18:04:18 +0000 (GMT)
Subject: [Tutor] Fw:  Command line args
Message-ID: <435721.40277.qm@web86110.mail.ird.yahoo.com>

Please use REPLY ALL to include the rest of the group.

The code looks OK although the error that you raise should probably 
be a RuntimeError rather than a SyntaxError since its not really a 
syntax problem.

You can get a list of the built in exceptions by doing:

>>> import exceptions
>>> dir(exceptions)

HTH,

Alan G.

----- Original Message ----
From: Teresa Stanton <tms43 at clearwire.net>
To: Alan Gauld <alan.gauld at btinternet.com>
Sent: Tuesday, 10 April, 2007 5:52:44 PM
Subject: RE: [Tutor] Command line args

This is how I actually did it after reading a number of your posts:

numLst = []   #an empty list

if len(sys.argv) == 2: #only one filename, please
    infile = open(sys.argv[1], 'r')
elif len(sys.argv) < 2:  #handles the case where no file is provided on
command line
    infilename = raw_input("Name of file: ")
elif len(sys.argv) > 2:  #raises error if more than one filename is provided
    raise SyntaxError, "Too many arguments"
data = open(infilename, 'r')

for x  in data:
    numLst.append(x.strip('\n').split(" "))

Thank you so much for the discussion.  It has been very helpful!






      ___________________________________________________________ 
Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for
your free account today http://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winter07.html 





      ___________________________________________________________ 
Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for
your free account today http://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winter07.html 

From astroultraman at gmail.com  Tue Apr 10 23:24:01 2007
From: astroultraman at gmail.com (Robert William Hanks)
Date: Tue, 10 Apr 2007 18:24:01 -0300
Subject: [Tutor] iscube function
Message-ID: <6be1291e0704101424s3ccf20b7w7db9e20b858c9f52@mail.gmail.com>

how is the best way to find out if a number is a perfect cube in python?
  i am working if integer numbers only. i am asking because
 pow(1728, 1.0/3.0) --> 11.999999999999998
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070410/e5c9d26b/attachment.html 

From carroll at tjc.com  Wed Apr 11 02:11:03 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 10 Apr 2007 17:11:03 -0700 (PDT)
Subject: [Tutor] iscube function
In-Reply-To: <6be1291e0704101424s3ccf20b7w7db9e20b858c9f52@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0704101709470.20379-100000@violet.rahul.net>

On Tue, 10 Apr 2007, Robert William Hanks wrote:

> how is the best way to find out if a number is a perfect cube in python?
>   i am working if integer numbers only. i am asking because
>  pow(1728, 1.0/3.0) --> 11.999999999999998


def iscube(n):
    cubed_root = n**(1/3.0)
    if round(cubed_root)**3 == n:
        return True
    else:
        return False

if __name__ == "__main__":
    rootlim = 20
    calculated_cubes = [n**3 for n in range(1,rootlim+1)]
    found_cubes = [n for n in range(1, rootlim**3+1) if iscube(n)]
    if found_cubes == calculated_cubes:
        print "Hey, it worked!"
    else:
        print "Oops."
        missed_cubes = [n for n in calculated_cubes if n not in found_cubes]
        wrong_cubes = [n for n in found_cubes if n not in calculated_cubes]
        print "missed cubes:", missed_cubes
        print "wrong cubes:", wrong_cubes

 


From atpridgen at mail.utexas.edu  Wed Apr 11 06:59:27 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Tue, 10 Apr 2007 23:59:27 -0500
Subject: [Tutor] kwds
Message-ID: <f989e6210704102159o194a053co23edb5ebf9e5df4e@mail.gmail.com>

Hello,

I am having a difficult time understanding the whole "def
function(*args, **kwds):" business, and I have not really found a
clear or concise explanation via Google.

My question is pretty much this, is **kwds a dictionary and can I use
it like a dictionary, and what is the deal with the * or **?


Sometime ago I found something explaining the basics of these
parameters, but I lost the link and I lost that warm and fuzzy feeling
I had about them ;).

Thanks in advance,

Adam

From john at fouhy.net  Wed Apr 11 07:41:37 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 11 Apr 2007 17:41:37 +1200
Subject: [Tutor] kwds
In-Reply-To: <f989e6210704102159o194a053co23edb5ebf9e5df4e@mail.gmail.com>
References: <f989e6210704102159o194a053co23edb5ebf9e5df4e@mail.gmail.com>
Message-ID: <5e58f2e40704102241r3011482doc4cb87137d7d7e13@mail.gmail.com>

On 11/04/07, Adam Pridgen <atpridgen at mail.utexas.edu> wrote:
> Hello,
>
> I am having a difficult time understanding the whole "def
> function(*args, **kwds):" business, and I have not really found a
> clear or concise explanation via Google.
>
> My question is pretty much this, is **kwds a dictionary and can I use
> it like a dictionary, and what is the deal with the * or **?

Short answer: kwds is a dictionary.

Longer answer:

You can use *args and **kwargs to collect "extra" positional and
keyword parameters.  This is easier to demonstrate than explain, so I
will try to illustrate with examples.

Here's a function that takes two arguments:

>>> def f(x, y):
...  print x, y
...

I can call it:

>>> f(1, 3)
1 3

But if I try to call it with more than two arguments, python complains:

>>> f(1, 3, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f() takes exactly 2 arguments (3 given)

Here's another function.  This one takes _at least_ two arguments:

>>> def f(x, y, *extra):
...  print x, y, extra
...

I can call it as before.  Notice that 'extra' is a 0-tuple:

>>> f(1, 2)
1 2 ()

I can also give it some extra positional arguments.  Python will take
the first two positional arguments and assign them the local names 'x'
and 'y', and it will put the remaining positional arguments into a
tuple, and call that 'extra'.

>>> f(1, 2, 3, 4, 5)
1 2 (3, 4, 5)

But f has two named parameters, so I need to give it _at least_ two arguments.

>>> f(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f() takes at least 2 arguments (1 given)

Finally, f doesn't handle keyword arguments.

>>> f(1, 2, foo=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f() got an unexpected keyword argument 'foo'

Here's a function that takes two keyword arguments:

>>> def f(x=1, y=2):
...  print x, y
...

I can use it as normal:

>>> f(y=5)
1 5

But if I give it a keyword argument it doesn't expect, python complains:

>>> f(y=5, z=9)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f() got an unexpected keyword argument 'z'

Here's another function.  This function will collect undeclared
keyword arguments into a dictionary.

>>> def f(x=1, y=2, **kwargs):
...  print x, y, kwargs
...

If I don't give any extra keyword arguments, the dictionary is empty.

>>> f()
1 2 {}

If I do, the dictionary will be populated.  I hope you can see the
connection between the keyword arguments and the dictionary structure.

>>> f(z=9, foo='bar')
1 2 {'z': 9, 'foo': 'bar'}

**kwargs will only collect keyword arguments.  So if I provide extra
positional arguments, python will still complain.

>>> f(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f() takes at most 2 arguments (3 given)

You can combine explicit positional and keyword arguments and the
*args / **kwargs forms.  I hope it should be obvious how things work;
if it's not, experiment :-)

You can also use the syntax in the opposite direction (as it were).
If 'args' is a list and you use '*args' in a function call, python
will expand args into positional parameters.

eg, here is a function:

>>> def f(x, y, *args):
...  print 'x:%s, y:%s, args:%s' % (x, y, args)
...

I can call it with four positional parameters:

>>> f(1, 2, 3,4)
x:1, y:2, args:(3, 4)

Or I can build a list of four elements, and convert the list into
positional parameters:

>>> lst = [1, 2, 3, 4]
>>> f(*lst)
x:1, y:2, args:(3, 4)

You can do the same thing with keyword arguments and dictionaries:

>>> def f(x=1, y=2, **kw):
...  print 'x:%s, y:%s, kw:%s' % (x, y, kw)
...
>>> args = {'y':9, 'z':13, 'k':42}
>>> f(**args)
x:1, y:9, kw:{'k': 42, 'z': 13}

And, obviously, you can combine both of these.

You might commonly see this when dealing with inheritance -- a
subclass will define some of its own parameters, and use *args/**kw to
collect any other arguments and pass them on to the base class.  eg:

class MySubClass(BaseClass):
    def __init__(self, x, y, foo='foo', *args, **kw):
        BaseClass.__init__(*args, **kw)
        # Do stuff with x, y, foo

> and I have not really found a clear or concise explanation via Google.

I don't think this counts as "concise", but I hope it is clear :-)

-- 
John.

From zebra05 at gmail.com  Wed Apr 11 09:39:06 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Wed, 11 Apr 2007 09:39:06 +0200
Subject: [Tutor] File storage vs DB storage.
In-Reply-To: <evfnq6$e83$1@sea.gmane.org>
References: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com>
	<evfnq6$e83$1@sea.gmane.org>
Message-ID: <c7c6f3bc0704110039h68a60d0awd8f988f18570ae29@mail.gmail.com>

Thanks, gentlemen.

Indeed, using directories may be a better bet when there are many files
involved. At least, this has been my feeling, and i gather the same from
your replies.

I'll be using Lighttpd + FastCGI + Python + MySQL (maybe PostGRE here) on
Win. XP SP2. Any known caveats of this combo before i plunge?

Thanks again

Lloyd

On 4/10/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "OkaMthembo" <zebra05 at gmail.com> wrote
>
> > Ok, to get to the point: when building a web app that should store
> > an
> > retrieve photos, what would be more efficient between the app
> > storing the
> > files on a local hard disk, or saving blobs/ binary data to a
> > database?
> > Someone toldme that database storage should be avoided as it
> > would cause a botleneck,
>
> I wouldn't say a bottleneck but it can cause problems by
> making the database itself very big. That can cause
> problems for some operations, including admin tasks.
> Some databases work better with blobs than others.
>
> > whereas i dont want to imagine the nightmare of managing
> > tons of files sitting in a folder. I use Windows XP.
>
> Naming issues are usually the biggest problem.
> It will work best if you use a numrerical naming convention
> and manage all of the meta data in the database, along
> with the filename.
>
> The advantage of using the file system is that you can
> use different folders to help organise the files - folders for
> month created or submitter or whatever. Also you can
> use the facilities of the OS to create encrypted folders,
> secure folders, compressed folders, move the folders
> onto other drives as the capacity expands, do incremental
> backups etc etc.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070411/2358c6c4/attachment.htm 

From govindgoyal at gmail.com  Wed Apr 11 13:00:17 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Wed, 11 Apr 2007 16:30:17 +0530
Subject: [Tutor] urllib2_realm??
Message-ID: <f96f96bc0704110400u63e6bdb9s4b9b42e8415e4e72@mail.gmail.com>

Hi,

Use of Basic HTTP Authentication:

import urllib2
auth_handler.add_password(*'realm'*, 'host', 'username', 'password')

What is realm and its use in above line of code?

If I want to access a web page and I don't know what the realm is,then
what should I write in place of realm?

Can anybody help?

Best Regards,

Govind Goyal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070411/e50e3422/attachment.htm 

From clajo04 at mac.com  Wed Apr 11 13:36:24 2007
From: clajo04 at mac.com (John Clark)
Date: Wed, 11 Apr 2007 07:36:24 -0400
Subject: [Tutor] ANN: Next NYC Python User Group meeting, Tues May 8th, 2007,
	6:30 pm
In-Reply-To: <00c301c776f1$d175e970$fefea8c0@haengma>
References: <00c301c776f1$d175e970$fefea8c0@haengma>
Message-ID: <003701c77c2d$a396a580$fefea8c0@haengma>

My apologies for the comical timing of the below announcement - I actually
sent the announcement on April 4th, but it obviously didn't clear the
moderator's desk in time for the meeting mentioned below.  In an attempt to
avoid this same problem, let me announce next month's meeting now.
 
The next New York City Python Users Group meeting is Tuesday, May 8th from
6:30-8:30pm at the Millenium Partners office at 666 Fifth Avenue (53rd St.
and 5th Ave.) on the 8th Floor.  We welcome all those in the NYC area who
are interested in Python to attend.  However, we need a list of first and
last names to give to building security to make sure you can gain access to
the building.  RSVP to clajo04 at mac.com to add your name to the list.
 
More information can be found on the yahoo group page:
 
http://tech.groups.yahoo.com/group/nycpython
 
Hope to see you there!
 
-John


  _____  

From: python-list-bounces+clajo04=mac.com at python.org
[mailto:python-list-bounces+clajo04=mac.com at python.org] On Behalf Of John
Clark
Sent: Wednesday, April 04, 2007 3:46 PM
To: python-list at python.org; python-announce at python.org; tutor at python.org
Subject: New York City Python Users Group Meeting



Greetings!

The next New York City Python Users Group meeting is this Tuesday, April
10th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd
St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who
are interested in Python to attend. However, we need a list of first and
last names to give to building security to make sure you can gain access to
the building. RSVP to clajo04 at mac.com to add your name to the list. 

More information can be found on the yahoo group page:

 <http://tech.groups.yahoo.com/group/nycpython/>
http://tech.groups.yahoo.com/group/nycpython/

Hope to see you there!

-John

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070411/cc33b919/attachment.htm 

From kent37 at tds.net  Wed Apr 11 13:42:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 11 Apr 2007 07:42:58 -0400
Subject: [Tutor] urllib2_realm??
In-Reply-To: <f96f96bc0704110400u63e6bdb9s4b9b42e8415e4e72@mail.gmail.com>
References: <f96f96bc0704110400u63e6bdb9s4b9b42e8415e4e72@mail.gmail.com>
Message-ID: <461CC9C2.2010909@tds.net>

govind goyal wrote:
>  
> Hi,
>  
> Use of Basic HTTP Authentication:
> 
> import urllib2
> auth_handler.add_password(*'realm'*, 'host', 'username', 'password')
> 
> What is realm and its use in above line of code?

Realm is set by the host. It is usually displayed in the login dialog in 
a browser, it will look like a site name.

The realm is in the headers received back from the server. For example:
$ curl -I http://xxx.com/
HTTP/1.1 401 Authorization Required
Date: Wed, 11 Apr 2007 01:39:47 GMT
Server: Apache/2.0.52 (Red Hat) mod_python/3.2.8 Python/2.4.4
WWW-Authenticate: Basic realm="xxxx"
Content-Type: text/html; charset=iso-8859-1
Vary: Accept-Encoding,User-Agent

> 
> If I want to access a web page and I don't know what the realm is,then what should I write in place of realm?

I think you can instantiate the HTTPBasicAuthHandler with an instance of 
HTTPPasswordMgrWithDefaultRealm. Then pass None as the realm and it will 
be used as the default.

Kent

From alan.gauld at btinternet.com  Wed Apr 11 15:10:32 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 11 Apr 2007 14:10:32 +0100
Subject: [Tutor] File storage vs DB storage.
References: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com><evfnq6$e83$1@sea.gmane.org>
	<c7c6f3bc0704110039h68a60d0awd8f988f18570ae29@mail.gmail.com>
Message-ID: <evimoi$g25$1@sea.gmane.org>


"OkaMthembo" <zebra05 at gmail.com> wrote

> I'll be using Lighttpd + FastCGI + Python + MySQL on
> Win. XP SP2. Any known caveats of this combo 
> before i plunge?

That should be fine I think.

Alan G.


From chris.arndt at web.de  Wed Apr 11 16:21:26 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Wed, 11 Apr 2007 16:21:26 +0200
Subject: [Tutor] File storage vs DB storage.
In-Reply-To: <c7c6f3bc0704110039h68a60d0awd8f988f18570ae29@mail.gmail.com>
References: <c7c6f3bc0704100026l14ca6768r783f0777790357f3@mail.gmail.com>	<evfnq6$e83$1@sea.gmane.org>
	<c7c6f3bc0704110039h68a60d0awd8f988f18570ae29@mail.gmail.com>
Message-ID: <461CEEE6.4090107@web.de>

OkaMthembo schrieb:
> Indeed, using directories may be a better bet when there are many files
> involved. At least, this has been my feeling, and i gather the same from
> your replies.

I suggest that you take a look at a database abstraction layer or ORM like
SQLAlchemy [1], that makes handling the data layer much easier and also allows
you to map different data sources (e.g. file system/database) onto the same
data object very easily.

For example, there is a recipe in the SQLObject docs [2] on how to store images
in the filesystem but access them transparently via object properties (aka
dynamic attributes). This recipe could be easily applied to SQLAlchemy mapper
objects as well.


Chris

[1] http://sqlalchemy.org
[2] http://sqlobject.org/SQLObject.html#adding-magic-attributes-properties

From kent37 at tds.net  Wed Apr 11 17:19:08 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 11 Apr 2007 11:19:08 -0400
Subject: [Tutor] Python books on sale
Message-ID: <461CFC6C.5030205@tds.net>

For anyone interested in a copy of Wesley Chun's recently updated book 
Core Python Programming, it is 50% off at bookpool.com at the moment:
http://www.bookpool.com/sm/0132269937

Also the TurboGears book is 51% off:
http://www.bookpool.com/sm/0132433885

Kent

From rabidpoobear at gmail.com  Wed Apr 11 19:05:48 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 11 Apr 2007 12:05:48 -0500
Subject: [Tutor] ANN: Next NYC Python User Group meeting, Tues May 8th,
 2007, 6:30 pm
In-Reply-To: <003701c77c2d$a396a580$fefea8c0@haengma>
References: <00c301c776f1$d175e970$fefea8c0@haengma>
	<003701c77c2d$a396a580$fefea8c0@haengma>
Message-ID: <461D156C.7010607@gmail.com>

John Clark wrote:
> My apologies for the comical timing of the below announcement - I 
> actually sent the announcement on April 4th, but it obviously didn't 
> clear the moderator's desk in time for the meeting mentioned below.  
> In an attempt to avoid this same problem, let me announce next month's 
> meeting now.
Is this list moderated?
I seem to be able to send replies and such at pretty much any time, and 
the other people get them right away.
At least occasionally they do, because I sometimes get replies to my 
reply shortly thereafter.

From kent37 at tds.net  Wed Apr 11 19:35:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 11 Apr 2007 13:35:15 -0400
Subject: [Tutor] ANN: Next NYC Python User Group meeting, Tues May 8th,
 2007, 6:30 pm
In-Reply-To: <461D156C.7010607@gmail.com>
References: <00c301c776f1$d175e970$fefea8c0@haengma>	<003701c77c2d$a396a580$fefea8c0@haengma>
	<461D156C.7010607@gmail.com>
Message-ID: <461D1C53.3050502@tds.net>

Luke Paireepinart wrote:
> John Clark wrote:
>> My apologies for the comical timing of the below announcement - I 
>> actually sent the announcement on April 4th, but it obviously didn't 
>> clear the moderator's desk in time for the meeting mentioned below.  
>> In an attempt to avoid this same problem, let me announce next month's 
>> meeting now.
> Is this list moderated?
> I seem to be able to send replies and such at pretty much any time, and 
> the other people get them right away.

Posts by non-members are moderated. I usually take care of them the same 
day they are posted. Once you join your posts are not moderated. I don't 
recall seeing any posts about the NYC user group in the moderator's 
queue, maybe something else was responsible for the delay.

Kent

From alan.gauld at btinternet.com  Wed Apr 11 19:53:25 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 11 Apr 2007 18:53:25 +0100
Subject: [Tutor] Python books on sale
References: <461CFC6C.5030205@tds.net>
Message-ID: <evj7av$81s$1@sea.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote

> Also the TurboGears book is 51% off:
> http://www.bookpool.com/sm/0132433885

FWIW I've just finished this one and its pretty good but full of 
bad typos and inconsistencies(*). If you bear with it and type 
in the examples it starts to become obvious where the 
errors are. It's a lot better than trying to figure out TurboGears 
from the online docs though.

(*) Hopefully a second printing should improve things 
significantly.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From Mike.Hansen at atmel.com  Wed Apr 11 20:51:07 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 11 Apr 2007 12:51:07 -0600
Subject: [Tutor] Python books on sale
In-Reply-To: <evj7av$81s$1@sea.gmane.org>
References: <461CFC6C.5030205@tds.net> <evj7av$81s$1@sea.gmane.org>
Message-ID: <57B026980605A64F9B23484C5659E32E6C4018@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> 
> "Kent Johnson" <kent37 at tds.net> wrote
> 
> > Also the TurboGears book is 51% off:
> > http://www.bookpool.com/sm/0132433885
> 

Safari(http://safari.oreilly.com) has both the TurboGears book and Core
Python book, so you can check them out before deciding if you want the
dead tree version.

Mike 

From bensherman at gmail.com  Wed Apr 11 21:58:00 2007
From: bensherman at gmail.com (Ben Sherman)
Date: Wed, 11 Apr 2007 15:58:00 -0400
Subject: [Tutor] List slicing and joining
Message-ID: <5a56471e0704111258h18974eefw69b3f01a64cf76a5@mail.gmail.com>

I've got a list that contain a bunch of information, including the
FQDN of a host.

host_data=['foo.example.com', 'other unimportant data']

I need to seperate the hostname from the domain name.

This is how I'm doing it, and it work, but it seems *really* hacky.
Is there a better (or more pythony) way?

hostname=host_data[0].split(".")[0]
domain=".".join(host_data[0].split(".")[1:])

Thanks,
Ben

From andreas at kostyrka.org  Wed Apr 11 22:11:50 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Wed, 11 Apr 2007 22:11:50 +0200
Subject: [Tutor] List slicing and joining
In-Reply-To: <5a56471e0704111258h18974eefw69b3f01a64cf76a5@mail.gmail.com>
References: <5a56471e0704111258h18974eefw69b3f01a64cf76a5@mail.gmail.com>
Message-ID: <20070411201150.GK19371@andi-lap.la.revver.com>

* Ben Sherman <bensherman at gmail.com> [070411 22:02]:
> I've got a list that contain a bunch of information, including the
> FQDN of a host.
> 
> host_data=['foo.example.com', 'other unimportant data']
> 
> I need to seperate the hostname from the domain name.
> 
> This is how I'm doing it, and it work, but it seems *really* hacky.
> Is there a better (or more pythony) way?
> 
> hostname=host_data[0].split(".")[0]
> domain=".".join(host_data[0].split(".")[1:])

Well, it's basically ok, but I'd probably do something like this:
fqdn_parts = host_data[0].split(".")
host = fqdn_parts[0]
domain = ".".join(fqdn_parts[1:])

Alternativly, if you are sure that you've got a '.' in the host_part,
you can do:

host, domain = host_data[0].split(".", 1)

Andreas

From jorgen.maillist at gmail.com  Thu Apr 12 10:46:53 2007
From: jorgen.maillist at gmail.com (Jorgen Bodde)
Date: Thu, 12 Apr 2007 10:46:53 +0200
Subject: [Tutor] Calling private base class methods
Message-ID: <11e49df10704120146nb65e001vefa5d11054274258@mail.gmail.com>

Hi All,

Now that I am really diving into Python, I encounter a lot of things
that us newbies find difficult to get right. I thought I understood
how super() worked, but with 'private' members it does not seem to
work. For example;

>>> class A(object):
... 	def __baseMethod(self):
... 		print 'Test'

Deriving from A, and doing;

>>> class D(A):
... 	def someMethod(self):
... 		super(A, self).__baseMethod()
... 		print 'test3'

Will not work;

>>> p = D()
>>> p.someMethod()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "<interactive input>", line 3, in someMethod
AttributeError: 'super' object has no attribute '_D__baseMethod'

Is it possible to call a private base method? I come from a C++
background, and I liked this construction as my base class has helper
methods so that I do not have to  duplicate code.

When I do;

>>> class E(object):
... 	def someMethod(self):
... 		print 'Hello'
... 		
>>> class F(E):
... 	def otherMethod(self):
... 		super(F, self).someMethod()
... 		print 'There'
... 		
>>> p = F()
>>> p.otherMethod()
Hello
There
>>>

This seems to work.

Thanks in advance,
- Jorgen

From andreas at kostyrka.org  Thu Apr 12 11:04:44 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 12 Apr 2007 11:04:44 +0200
Subject: [Tutor] Calling private base class methods
In-Reply-To: <11e49df10704120146nb65e001vefa5d11054274258@mail.gmail.com>
References: <11e49df10704120146nb65e001vefa5d11054274258@mail.gmail.com>
Message-ID: <20070412090442.GP19371@andi-lap.la.revver.com>

* Jorgen Bodde <jorgen.maillist at gmail.com> [070412 10:57]:
> Hi All,
> 
> Now that I am really diving into Python, I encounter a lot of things
> that us newbies find difficult to get right. I thought I understood
> how super() worked, but with 'private' members it does not seem to
> work. For example;
Rename your __baseMethod to _baseMethod.
Or call it as _A__baseMethod.

Basically __ just provokes name mangling.

Andreas

From alan.gauld at btinternet.com  Thu Apr 12 12:35:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 12 Apr 2007 11:35:40 +0100
Subject: [Tutor] Calling private base class methods
References: <11e49df10704120146nb65e001vefa5d11054274258@mail.gmail.com>
Message-ID: <evl227$fm2$1@sea.gmane.org>


"Jorgen Bodde" <jorgen.maillist at gmail.com> wrote

>>>> class A(object):
> ... def __baseMethod(self):
> ... print 'Test'
>
> Deriving from A, and doing;
>
>>>> class D(A):
> ... def someMethod(self):
> ... super(A, self).__baseMethod()
> ... print 'test3'
>
> Will not work;

> Is it possible to call a private base method? I come from a C++
> background, and I liked this construction as my base class has 
> helper
> methods so that I do not have to  duplicate code.

But if you declared a method private in C++ a sub class could
not call it either, it is only if it is protected that subclasses can
call base methods. But Python has no protected mode, only
the single underscore naming convention.

So either you need to rename your method with a single underscore
or don't make it private at all. Do you really, really need it to be 
private?
There are very few real cases where private methods are required and
the norm in Python is for public methods, it makes for much more
flexible classes.

Personally I don't like the super() implementation in Python and
tend to use the the more explicit style of call to the superclass.
As in:

A.__baseMethod(self)

But I don't think that would make any difference here.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From python at uni-code.com  Fri Apr 13 00:20:20 2007
From: python at uni-code.com (python at uni-code.com)
Date: Thu, 12 Apr 2007 18:20:20 -0400 (EDT)
Subject: [Tutor] Some questions.
Message-ID: <2947.70.237.200.212.1176416420.squirrel@uni-code.com>

Hello my name is lamonte and I'm interesting in getting better @ python so
I guess this is the correct place then :).

One question is whats the best GUI library to build from?

Anyone recommend any good tutorials that helped them get good @ learning
python?

I know some decent basics and soon to try and develope my own game engine.
 I feel this will be a good project to learn new and different things. 
Thanks in advanced.

Regards,
Lamonte Harris.

From alan.gauld at btinternet.com  Fri Apr 13 01:30:58 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 13 Apr 2007 00:30:58 +0100
Subject: [Tutor] Some questions.
References: <2947.70.237.200.212.1176416420.squirrel@uni-code.com>
Message-ID: <evmfft$f6n$1@sea.gmane.org>

> Hello my name is lamonte and I'm interesting in getting 
> better @ python so I guess this is the correct place 

Welcome, and you are right, this is the place for learning! :-)

> One question is whats the best GUI library to build from?

That depends a lot on what you want to do and what your 
previous experience is.

Tkinter is multi platform and comes as part of Pythpons 
standard Library. Its what IDLE is built from.

Many people prefer wxPython which is a downloadable 
extra because it has more widgets and looks more like 
the native toolkit

Native windows programmers can use MFC via Marki Hammonds 
winall add-on package (standard in ActiveState Python)

Jython lets you access the Java libraries including the 
GUI toolkits such as Swing.

And there are also bindings for GTk and Qt if you know them 
from Linux/X windows

Personally I like Tkinter because its simple, standard and does 
all that I need. Many others prefer wxPython. Unless you have 
previous experience with some of the others I'd look at both 
and make a choice between them.

> Anyone recommend any good tutorials that helped them 
> get good @ learning python?

Tutorials are very personal. Some folks prefer to get the 
theory explained before wading in, others prefer to work 
by example and pick up the theory by osmosis. The great 
thing in Python is you can try them all till you find one that 
suits because theyb are all on the Web... There is a web 
page on the Python web site that links to the most 
common/popular ones. Pick one, follow it and ask 
questions here if you get stuck or puzzled. (If you pick 
mine you can also use the web link to send me mail 
directly)

> I know some decent basics and soon to try and develope 
> my own game engine.

I assume you know that there is already a game enine 
for Python: pyGame. Its pretty low level so you may want 
to start from that as a foundation. There is a tutorial for 
pyGame too.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From suryogondol at gmail.com  Fri Apr 13 03:57:41 2007
From: suryogondol at gmail.com (suryo agung)
Date: Thu, 12 Apr 2007 18:57:41 -0700
Subject: [Tutor] please help me!
Message-ID: <ce2f3c920704121857t2c4db09fpa610aff2d0c8ca5f@mail.gmail.com>

pleate tell me how to make

input number=4
result

1
22
333
4444

in python
please give me your answer.

From kent37 at tds.net  Fri Apr 13 05:29:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 12 Apr 2007 23:29:13 -0400
Subject: [Tutor] please help me!
In-Reply-To: <ce2f3c920704121857t2c4db09fpa610aff2d0c8ca5f@mail.gmail.com>
References: <ce2f3c920704121857t2c4db09fpa610aff2d0c8ca5f@mail.gmail.com>
Message-ID: <461EF909.9040800@tds.net>

suryo agung wrote:
> pleate tell me how to make
> 
> input number=4
> result
> 
> 1
> 22
> 333
> 4444
> 
> in python
> please give me your answer.

This looks a lot like homework to me. What have you tried? What have you 
learned?

Kent

From bensherman at gmail.com  Fri Apr 13 05:43:59 2007
From: bensherman at gmail.com (Ben Sherman)
Date: Thu, 12 Apr 2007 23:43:59 -0400
Subject: [Tutor] please help me!
In-Reply-To: <ce2f3c920704121857t2c4db09fpa610aff2d0c8ca5f@mail.gmail.com>
References: <ce2f3c920704121857t2c4db09fpa610aff2d0c8ca5f@mail.gmail.com>
Message-ID: <5a56471e0704122043n3a371459kd3ead5214b5cb67b@mail.gmail.com>

You

On 4/12/07, suryo agung <suryogondol at gmail.com> wrote:
> pleate tell me how to make
>
> input number=4
> result
>
> 1
> 22
> 333
> 4444
>
> in python
> please give me your answer.

input_number = 4

for i in range(1,input_number + 1):
  print str(i) * i

If this is homework, please tell your teacher I helped - I need the
extra credit.

From oeyvind at sporck.net  Fri Apr 13 13:50:01 2007
From: oeyvind at sporck.net (=?iso-8859-1?Q?=D8yvind_Dale_Sp=F8rck?=)
Date: Fri, 13 Apr 2007 13:50:01 +0200 (CEST)
Subject: [Tutor] Microsoft Exchange
Message-ID: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>

Hello.

I need to get the mailbox size out from Exchange. I have been googling and
all I have found is how to get the size from my personal mailbox. But,
that is not what I need. I need to find the sizes of the mailboxes for all
users.

Does anyone know of any modules that works towards the central
Exchange-server or any example scripts that can give me any hints?

Thanks in advance


-- 
This email has been scanned for viruses & spam by Domenebutikken - www.domenebutikken.no
Denne e-posten er sjekket for virus & spam av Domenebutikken - www.domenebutikken.no


From rikard.bosnjakovic at gmail.com  Fri Apr 13 14:34:26 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 13 Apr 2007 14:34:26 +0200
Subject: [Tutor] Microsoft Exchange
In-Reply-To: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>
References: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>
Message-ID: <d9e88eaf0704130534m399a1c57v61882bd16d58aef8@mail.gmail.com>

On 4/13/07, ?yvind Dale Sp?rck <oeyvind at sporck.net> wrote:

> Does anyone know of any modules that works towards the central
> Exchange-server or any example scripts that can give me any hints?

Try this list instead: http://mail.python.org/mailman/listinfo/python-win32


-- 
- Rikard - http://bos.hack.org/cv/

From python at kapitalisten.no  Fri Apr 13 14:35:42 2007
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Fri, 13 Apr 2007 14:35:42 +0200 (CEST)
Subject: [Tutor]  Some questions.
Message-ID: <43778.193.71.38.142.1176467742.squirrel@mail.sporck.net>

>One question is whats the best GUI library to build from?

WxPython is a very good one. However, you should look into Pythoncard
(http://pythoncard.sourceforge.net/) which lets you build WxPython even
easier.


-- 
This email has been scanned for viruses & spam by Domenebutikken - www.domenebutikken.no
Denne e-posten er sjekket for virus & spam av Domenebutikken - www.domenebutikken.no


From mail at timgolden.me.uk  Fri Apr 13 15:08:19 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 13 Apr 2007 14:08:19 +0100
Subject: [Tutor] Microsoft Exchange
In-Reply-To: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>
References: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>
Message-ID: <461F80C3.5000102@timgolden.me.uk>

?yvind Dale Sp?rck wrote:
> Hello.
> 
> I need to get the mailbox size out from Exchange. I have been googling and
> all I have found is how to get the size from my personal mailbox. But,
> that is not what I need. I need to find the sizes of the mailboxes for all
> users.
> 
> Does anyone know of any modules that works towards the central
> Exchange-server or any example scripts that can give me any hints?

Haven't tried it, but the pywin32 stuff comes with
an exchange module. You'd have to mull about a bit
for the docs, though.

TJG

From andreas at kostyrka.org  Sat Apr 14 00:22:10 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 14 Apr 2007 00:22:10 +0200
Subject: [Tutor] Microsoft Exchange
In-Reply-To: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>
References: <14218.193.71.38.142.1176465001.squirrel@mail.sporck.net>
Message-ID: <20070413222210.GL19371@andi-lap.la.revver.com>

* ?yvind Dale Sp?rck <oeyvind at sporck.net> [070414 00:15]:
> Hello.
> 
> I need to get the mailbox size out from Exchange. I have been googling and
> all I have found is how to get the size from my personal mailbox. But,
> that is not what I need. I need to find the sizes of the mailboxes for all
> users.
> 
> Does anyone know of any modules that works towards the central
> Exchange-server or any example scripts that can give me any hints?

Basically, you've got two ways here:

*) make Exchange talk some standard protocol like imap.
*) use some nonportable Win32 solution. I'd google around for a
solution to your problem no matter what language. You can easily
afterwards recode that solution in Python.

Andreas

From dyoo at cs.wpi.edu  Sat Apr 14 02:24:12 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Fri, 13 Apr 2007 20:24:12 -0400 (EDT)
Subject: [Tutor] please help me
Message-ID: <Pine.LNX.4.63.0704132020280.5041@cs.wpi.edu>

> If this is homework, please tell your teacher I helped - I need the 
> extra credit.

Please avoid giving homework answers like this.  Rather than actually help 
the person, it can do harm, because it encourages a lazy attitude toward 
solving problems.

From dyoo at cs.wpi.edu  Sat Apr 14 02:51:04 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Fri, 13 Apr 2007 20:51:04 -0400 (EDT)
Subject: [Tutor] Command line args
Message-ID: <Pine.LNX.4.63.0704132047210.5041@cs.wpi.edu>

Hi Teresa,

Has anyone on this thread already suggested the 'fileinput' module?  From 
what I understand, what 'fileinput' does is exactly what you're asking 
from:

     http://mail.python.org/pipermail/tutor/2007-April/053669.html

Here's documentation on 'fileinput':

     http://www.python.org/doc/lib/module-fileinput.html


Good luck!

From gregp at liveammo.com  Sat Apr 14 02:47:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 13 Apr 2007 20:47:00 -0400
Subject: [Tutor] please help me
Message-ID: <20070414005232.B3B621704F@smtp2.hushmail.com>

Let no good deed go unpunished!

-----Original Message-----
From: Daniel Yoo
Date: Friday, Apr 13, 2007 8:24 pm
Subject: Re: [Tutor] please help me

> If this is homework, please tell your teacher I helped - I need the 
> extra credit.
>
>Please avoid giving homework answers like this.  Rather than actually help 
>the person, it can do harm, because it encourages a lazy attitude toward 
>solving problems.




From dyoo at cs.wpi.edu  Sat Apr 14 03:29:27 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Fri, 13 Apr 2007 21:29:27 -0400 (EDT)
Subject: [Tutor] beautifulSoup and .next iteration
Message-ID: <Pine.LNX.4.63.0704132055570.5041@cs.wpi.edu>

> anchors = soup.findAll('a', { 'name' : re.compile('^A.*$')})
> for x in anchors:
>    print x
>    x = x.next
>    while getattr(x, 'name') != 'a':
>      print x

> And get into endless loops. I can't help thinking there are simple and 
> obvious ways to do this, probably many, but as a rank beginner, they are 
> escaping me.


Hi Jon,

Whenever I hear "infinite loop", I look for "while" loops.  There's 
something funky with the while loop in the above code.

     while getattr(x, 'name') != 'a':
         print x

If we assume that the test of while loop ever succeeds, then there's a 
problem: when does the test ever fail?  Nothing in the body of the for 
loop does anything to change the situation.  So that part doesn't quite 
work.  So, for the moment, strip out the while loop.  Let's simplify the 
behavior so that it only shows the anchors:

############################################################
anchors = soup.findAll('a', { 'name' : re.compile('^A.*$')})
for anchor in anchors:
     print anchor
############################################################

This shouldn't raise any infinite loops.



>From your question, it sounds like you want to get a list of the sibling 
elements after each particular anchor.  The documentation at:

http://www.crummy.com/software/BeautifulSoup/documentation.html#nextSibling%20and%20previousSibling

doesn't make this as clear as I'd like, but what you want is probably not 
the 'next' attribute of an object, but a 'nextSibling' attribute.


You might find the following definitions helpful:

#############################################################
def get_siblings_to_next_anchor(anchor):
     """Anchor Tag -> element list

     Given an anchor element, returns all the nextSiblings elements up to
     (but not including) the next anchor as a list of either Tags or
     NavigatableStrings."""

     elt = anchor.nextSibling
     results = []
     while (elt != None) and (not is_anchor(elt)):
         results.append(elt)
         elt = elt.nextSibling
     return results


def is_anchor(elt):
     """element -> boolean
     Returns true if the element is an anchor Tag."""

     if isinstance(elt, NavigableString):
         return False
     else:
         return elt.name == 'a'
#############################################################

They should help you get the results you want.


Good luck!

From tms43 at clearwire.net  Sat Apr 14 05:39:40 2007
From: tms43 at clearwire.net (Teresa Stanton)
Date: Fri, 13 Apr 2007 20:39:40 -0700
Subject: [Tutor] Command line args
In-Reply-To: <Pine.LNX.4.63.0704132047210.5041@cs.wpi.edu>
References: <Pine.LNX.4.63.0704132047210.5041@cs.wpi.edu>
Message-ID: <000301c77e46$8a2f88d0$2dbbe942@samiam>

No one suggested this.  That's great! Wish I had seen it sooner.  Thanks,
I'll put that in my notebook for further use later.

 

-----Original Message-----
From: Daniel Yoo [mailto:dyoo at cs.wpi.edu] 
Sent: Friday, April 13, 2007 5:51 PM
To: tms43 at clearwire.net
Cc: tutor at python.org
Subject: RE: Command line args

Hi Teresa,

Has anyone on this thread already suggested the 'fileinput' module?  From
what I understand, what 'fileinput' does is exactly what you're asking
from:

     http://mail.python.org/pipermail/tutor/2007-April/053669.html

Here's documentation on 'fileinput':

     http://www.python.org/doc/lib/module-fileinput.html


Good luck!



From arunkumarpg at gmail.com  Sat Apr 14 08:13:02 2007
From: arunkumarpg at gmail.com (Arun Kumar PG)
Date: Sat, 14 Apr 2007 11:43:02 +0530
Subject: [Tutor] threading.currentThread() always same across request ?
Message-ID: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>

Guys,

I have a web application and I want to store an object per request so thta
that is available across all classes till end of request.

I am planning  to write the below code in my entry program which is executed
as soon as a request comes:

entry.py
  import threading

  th = threading.currentThread()
  th.service = somemod.Service()

then in other parts of program whereever I want to use service:

  th = threading.currentThread()
  if hasattr(th, 'service'):
    th.service.call_whatever()

I am wondering if I will ever face a problem in this case ? I want to make
sure that since the request till the end the same "service" object is
available and it should not collide with any other request. Since it's a web
application multilple request may come simutaneously.

Is this approach correct ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070414/c5900456/attachment-0001.html 

From ceasar102 at yahoo.com  Sat Apr 14 09:04:45 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Sat, 14 Apr 2007 00:04:45 -0700 (PDT)
Subject: [Tutor] help on raw_input()
Message-ID: <943730.56602.qm@web56105.mail.re3.yahoo.com>

Hi,

i wanted to get a string from raw_input like this

raw_input('>')
> \n\nsomestring

but the problem is raw input will return the string
'\\n\\nsomestring'

My question is
Are there any function to convert back those string to  '\n\nsomestring' ?

Thanks


       
---------------------------------
Ahhh...imagining that irresistible "new car" smell?
 Check outnew cars at Yahoo! Autos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070414/05cf4e2f/attachment.htm 

From samrobertsmith at gmail.com  Sat Apr 14 09:19:18 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Sat, 14 Apr 2007 00:19:18 -0700
Subject: [Tutor] reassign
In-Reply-To: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
References: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
Message-ID: <1d987df30704140019o3131dc10o3b3afe4632435184@mail.gmail.com>

I wonder how to use colors from gray to black to represent a group of
values from small to large?
Thanks,
Linda

From alan.gauld at btinternet.com  Sat Apr 14 09:28:41 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 14 Apr 2007 08:28:41 +0100
Subject: [Tutor] Command line args
References: <Pine.LNX.4.63.0704132047210.5041@cs.wpi.edu>
	<000301c77e46$8a2f88d0$2dbbe942@samiam>
Message-ID: <evpvrl$qiv$1@sea.gmane.org>


"Teresa Stanton" <tms43 at clearwire.net> wrote

> No one suggested this.  That's great! Wish I had seen it sooner. 
> Thanks,
> I'll put that in my notebook for further use later.

Note that Fileinput is used to iterate over a (set of) file line by 
line,
it doesn't read the entire file into a string as in your original
question. You can get round that by using join() to join the
lines togvether after reading.

Also there are no prompts to stdin if that matters.

HTH,

Alan G.



From alan.gauld at btinternet.com  Sat Apr 14 09:36:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 14 Apr 2007 08:36:00 +0100
Subject: [Tutor] help on raw_input()
References: <943730.56602.qm@web56105.mail.re3.yahoo.com>
Message-ID: <evq09c$rio$1@sea.gmane.org>

"ammar azif" <ceasar102 at yahoo.com> wrote

> i wanted to get a string from raw_input like this
> 
> raw_input('>')
>> \n\nsomestring

OK, Can you explain precisely what you want the string to contain.
\n is the string representation of a newline. Do you want to enter 
something that starts with two newlines? Or do you literally want
the sequence \,n,\,n?

If its the latter thats what Python has stored. The double slash 
is only there when python displays the result (Try using len and 
comparing if you aren't convinced)

If you want to actually capture newline characters from raw_input, 
thats more tricky. But before we get to that can you clarify what 
you actually want?

Alan G.


From ceasar102 at yahoo.com  Sat Apr 14 09:46:43 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Sat, 14 Apr 2007 00:46:43 -0700 (PDT)
Subject: [Tutor] help on raw_input()
In-Reply-To: <evq09c$rio$1@sea.gmane.org>
Message-ID: <971615.46909.qm@web56107.mail.re3.yahoo.com>

Actually i wanted to write a http client using just he low level socket module.
The program will prompt the user asking for input and the use will type http commands like 'GET /index.html HTTP/1.0\r\nHost: somehost\r\n\r\n'
when i use the raw_input function , the string that i get is 
'GET /index.html HTTP/1.0\\r\\nHost: somehost\\r\\n\\r\\n'

is there any easy way other than modify this string ? Perhaps regular expression?



Alan Gauld <alan.gauld at btinternet.com> wrote: "ammar azif"  wrote

> i wanted to get a string from raw_input like this
> 
> raw_input('>')
>> \n\nsomestring

OK, Can you explain precisely what you want the string to contain.
\n is the string representation of a newline. Do you want to enter 
something that starts with two newlines? Or do you literally want
the sequence \,n,\,n?

If its the latter thats what Python has stored. The double slash 
is only there when python displays the result (Try using len and 
comparing if you aren't convinced)

If you want to actually capture newline characters from raw_input, 
thats more tricky. But before we get to that can you clarify what 
you actually want?

Alan G.

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


       
---------------------------------
Ahhh...imagining that irresistible "new car" smell?
 Check outnew cars at Yahoo! Autos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070414/0884abef/attachment.html 

From kent37 at tds.net  Sat Apr 14 13:26:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 14 Apr 2007 07:26:41 -0400
Subject: [Tutor] threading.currentThread() always same across request ?
In-Reply-To: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
References: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
Message-ID: <4620BA71.1090609@tds.net>

Arun Kumar PG wrote:
> Guys,
> 
> I have a web application and I want to store an object per request so 
> thta that is available across all classes till end of request.
> 
> I am planning  to write the below code in my entry program which is 
> executed as soon as a request comes:
> 
> entry.py
>   import threading
>  
>   th = threading.currentThread()
>   th.service = somemod.Service()
> 
> then in other parts of program whereever I want to use service:
> 
>   th = threading.currentThread ()
>   if hasattr(th, 'service'):
>     th.service.call_whatever()

Rather than store your attributes directly in the thread, it would 
probably be better to use a threading.local() object as the container.
http://docs.python.org/lib/module-threading.html#l2h-3416

I don't really know if it makes any difference but this is the supported 
mechanism for thread-local storage.

> I am wondering if I will ever face a problem in this case ? I want to 
> make sure that since the request till the end the same "service" object 
> is available and it should not collide with any other request. Since 
> it's a web application multilple request may come simutaneously.

You have to be careful that you don't get stale data, as threads are 
often reused in web servers. At the end of the request processing you 
should clear out your local data.

If you are using an existing web framework it probably has some kind of 
support for sessions. Using session objects might be another way to do this.

Kent

From kent37 at tds.net  Sat Apr 14 13:36:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 14 Apr 2007 07:36:04 -0400
Subject: [Tutor] help on raw_input()
In-Reply-To: <943730.56602.qm@web56105.mail.re3.yahoo.com>
References: <943730.56602.qm@web56105.mail.re3.yahoo.com>
Message-ID: <4620BCA4.70203@tds.net>

ammar azif wrote:
> Hi,
> 
> i wanted to get a string from raw_input like this
> 
> raw_input('>')
>  > \n\nsomestring
> 
> but the problem is raw input will return the string
> '\\n\\nsomestring'

This is a bit confusing to talk about because the actual contents of the 
string differ from what is printed. I don't know if you realize that or 
not so I'll start at the beginning.

In [3]: s= raw_input('> ')
 > one\r\ntwo
In [4]: s
Out[4]: 'one\\r\\ntwo'

When the interpreter outputs a string, it outputs it in the form of a 
string constant. Any actual \ in the string is escaped with an extra \. 
The string s contains single \ characters. You can verify this by 
getting the length:
In [5]: len(s)
Out[5]: 10

or by outputting it with print, which just outputs the actual characters:
In [6]: print s
one\r\ntwo

So s does contain the same characters as typed.

 > My question is
 > Are there any function to convert back those string to '\n\nsomestring' ?

You don't want the four literal characters \, r, \, n, you want a 
carriage return / newline combination. raw_input() doesn't interpret 
escape characters but there is a way to convert them:
In [7]: t=s.decode('string_escape')

Now t contains a carriage return / newline instead of the escape characters:
In [8]: t
Out[8]: 'one\r\ntwo'
In [9]: len(t)
Out[9]: 8
In [10]: print t
one
two

Kent

From alan.gauld at btinternet.com  Sat Apr 14 14:40:17 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 14 Apr 2007 13:40:17 +0100
Subject: [Tutor] reassign
References: <1d987df30704080238u1071bd08xff487e6787cd817b@mail.gmail.com>
	<1d987df30704140019o3131dc10o3b3afe4632435184@mail.gmail.com>
Message-ID: <evqi3u$afi$1@sea.gmane.org>

"linda.s" <samrobertsmith at gmail.com> wrote

>I wonder how to use colors from gray to black to represent a group of
> values from small to large?

Can you explain what you mean? Normally colours are represented
in code as a tuple of three numbers for the RGB values. If its shades
of grey then all three numbers are the same so you only need a
single number.

But you don't store colours in a program (except maybe as
string representations, eg 'cyan', 'blue', 'azure'). I'm not sure what
you mean by using colours to represent values. Usually its the other
way around?

If you do mean turning a range of values into shades of grey then
thats faitrly easy, just scale your values between 0 and 255,
where black is (0,0,0) and white is (255,255,255). If you have
N values then the scaling factor is 255/N. Then simply multiply
the value by the factor...

Alan G. 



From alan.gauld at btinternet.com  Sat Apr 14 14:49:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 14 Apr 2007 13:49:05 +0100
Subject: [Tutor] help on raw_input()
References: <evq09c$rio$1@sea.gmane.org>
	<971615.46909.qm@web56107.mail.re3.yahoo.com>
Message-ID: <evqikd$c0p$1@sea.gmane.org>

"ammar azif" <ceasar102 at yahoo.com> wrote

> Actually i wanted to write a http client using just he low level 
> socket module.

I won;t ask why! But the httplib module probably does what you want
just in case you dodn't realize it existed...

> The program will prompt the user asking for input and the
> use will type http commands like
> 'GET /index.html HTTP/1.0\r\nHost: somehost\r\n\r\n'

OK, So you want the user to acrtually type \,n,\,n and you
will then send that string to be interpreted as newlines?

> when i use the raw_input function , the string that i get is
> 'GET /index.html HTTP/1.0\\r\\nHost: somehost\\r\\n\\r\\n'

The double \\ doesn''t actually exist its just Python telling you
that it is a literal \ character not an escaped sequence.
As I said earlier if you check the len() of the string it will
only have one character per backslash.

I think it's already doing what you want!
You just need to turn the \n's that the user entered into
newline characters, Kent has shown you how to do that
with the decode() method...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From ceasar102 at yahoo.com  Sat Apr 14 14:59:10 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Sat, 14 Apr 2007 05:59:10 -0700 (PDT)
Subject: [Tutor] help on raw_input()
In-Reply-To: <evqikd$c0p$1@sea.gmane.org>
Message-ID: <892499.76746.qm@web56105.mail.re3.yahoo.com>

Thanks the encode method really helps.

Alan Gauld <alan.gauld at btinternet.com> wrote: "ammar azif"  wrote

> Actually i wanted to write a http client using just he low level 
> socket module.

I won;t ask why! But the httplib module probably does what you want
just in case you dodn't realize it existed...

> The program will prompt the user asking for input and the
> use will type http commands like
> 'GET /index.html HTTP/1.0\r\nHost: somehost\r\n\r\n'

OK, So you want the user to acrtually type \,n,\,n and you
will then send that string to be interpreted as newlines?

> when i use the raw_input function , the string that i get is
> 'GET /index.html HTTP/1.0\\r\\nHost: somehost\\r\\n\\r\\n'

The double \\ doesn''t actually exist its just Python telling you
that it is a literal \ character not an escaped sequence.
As I said earlier if you check the len() of the string it will
only have one character per backslash.

I think it's already doing what you want!
You just need to turn the \n's that the user entered into
newline characters, Kent has shown you how to do that
with the decode() method...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


       
---------------------------------
Ahhh...imagining that irresistible "new car" smell?
 Check outnew cars at Yahoo! Autos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070414/51fb17f2/attachment.html 

From andreas at kostyrka.org  Sat Apr 14 19:34:13 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 14 Apr 2007 19:34:13 +0200
Subject: [Tutor] threading.currentThread() always same across request ?
In-Reply-To: <4620BA71.1090609@tds.net>
References: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
	<4620BA71.1090609@tds.net>
Message-ID: <20070414173410.GN19371@andi-lap.la.revver.com>

* Kent Johnson <kent37 at tds.net> [070414 19:30]:
> Arun Kumar PG wrote:
> > Guys,
> > 
> > I have a web application and I want to store an object per request so 
> > thta that is available across all classes till end of request.
> > 
> > I am planning  to write the below code in my entry program which is 
> > executed as soon as a request comes:
> > 
> > entry.py
> >   import threading
> >  
> >   th = threading.currentThread()
> >   th.service = somemod.Service()
> > 
> > then in other parts of program whereever I want to use service:
> > 
> >   th = threading.currentThread ()
> >   if hasattr(th, 'service'):
> >     th.service.call_whatever()
> 
> Rather than store your attributes directly in the thread, it would 
> probably be better to use a threading.local() object as the container.
> http://docs.python.org/lib/module-threading.html#l2h-3416
> 
> I don't really know if it makes any difference but this is the supported 
> mechanism for thread-local storage.

Well, the other mechanism is also supported, because subclassing
threads is allowed, and subclasses need to keep their attributes, even
if accessed via threading.currentThread().

But as Kent has stated, stick with the Session mechanism of your
framework.

> If you are using an existing web framework it probably has some kind of 
> support for sessions. Using session objects might be another way to do this.

Andreas

From kent37 at tds.net  Sat Apr 14 19:39:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 14 Apr 2007 13:39:13 -0400
Subject: [Tutor] threading.currentThread() always same across request ?
In-Reply-To: <20070414173410.GN19371@andi-lap.la.revver.com>
References: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
	<4620BA71.1090609@tds.net>
	<20070414173410.GN19371@andi-lap.la.revver.com>
Message-ID: <462111C1.5040308@tds.net>

Andreas Kostyrka wrote:
> * Kent Johnson <kent37 at tds.net> [070414 19:30]:
>> Rather than store your attributes directly in the thread, it would 
>> probably be better to use a threading.local() object as the container.
>> http://docs.python.org/lib/module-threading.html#l2h-3416
>>
>> I don't really know if it makes any difference but this is the supported 
>> mechanism for thread-local storage.
> 
> Well, the other mechanism is also supported, because subclassing
> threads is allowed, and subclasses need to keep their attributes, even
> if accessed via threading.currentThread().

That's a good point. Does anyone know when to prefer threading.local() 
vs thread attributes?

Kent

From andreas at kostyrka.org  Sat Apr 14 20:11:53 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 14 Apr 2007 20:11:53 +0200
Subject: [Tutor] threading.currentThread() always same across request ?
In-Reply-To: <462111C1.5040308@tds.net>
References: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
	<4620BA71.1090609@tds.net>
	<20070414173410.GN19371@andi-lap.la.revver.com>
	<462111C1.5040308@tds.net>
Message-ID: <20070414181151.GO19371@andi-lap.la.revver.com>

* Kent Johnson <kent37 at tds.net> [070414 19:53]:
> Andreas Kostyrka wrote:
> > * Kent Johnson <kent37 at tds.net> [070414 19:30]:
> >> Rather than store your attributes directly in the thread, it would 
> >> probably be better to use a threading.local() object as the container.
> >> http://docs.python.org/lib/module-threading.html#l2h-3416
> >>
> >> I don't really know if it makes any difference but this is the supported 
> >> mechanism for thread-local storage.
> > 
> > Well, the other mechanism is also supported, because subclassing
> > threads is allowed, and subclasses need to keep their attributes, even
> > if accessed via threading.currentThread().
> 
> That's a good point. Does anyone know when to prefer threading.local() 
> vs thread attributes?
It's design question, I guess:

*) if you have thread subclasses, then use thread attributes.
*) if you have standard threads, then use thread.local().

The idea is, that it's "rude" to stick attributes on an object that is
not owned by you.

Rationale:
*) Somebody might decide to make threading.Thread be a new style
object with __slots__ => your code breaks.

I know, it's unprobably, but if you derive a subclass, you can be at
least sure that the object will have a __dict__ ;)

Andreas

From kent37 at tds.net  Sun Apr 15 01:50:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 14 Apr 2007 19:50:50 -0400
Subject: [Tutor] threading.currentThread() always same across request ?
In-Reply-To: <20070414181151.GO19371@andi-lap.la.revver.com>
References: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
	<4620BA71.1090609@tds.net>
	<20070414173410.GN19371@andi-lap.la.revver.com>
	<462111C1.5040308@tds.net>
	<20070414181151.GO19371@andi-lap.la.revver.com>
Message-ID: <462168DA.9070806@tds.net>

Andreas Kostyrka wrote:
> * Kent Johnson <kent37 at tds.net> [070414 19:53]:
>> That's a good point. Does anyone know when to prefer threading.local() 
>> vs thread attributes?
> It's design question, I guess:
> 
> *) if you have thread subclasses, then use thread attributes.
> *) if you have standard threads, then use thread.local().
> 
> The idea is, that it's "rude" to stick attributes on an object that is
> not owned by you.
> 
> Rationale:
> *) Somebody might decide to make threading.Thread be a new style
> object with __slots__ => your code breaks.
> 
> I know, it's unprobably, but if you derive a subclass, you can be at
> least sure that the object will have a __dict__ ;)

If you use threading.local() you can be sure the names you use don't 
conflict with any attributes of the thread.

Kent

From kadri.asrar at googlemail.com  Sat Apr 14 23:40:34 2007
From: kadri.asrar at googlemail.com (Asrar Kadri)
Date: Sat, 14 Apr 2007 22:40:34 +0100
Subject: [Tutor] Seeking python projects
Message-ID: <88dc53b0704141440h530a7d33w14a83229b4afeee7@mail.gmail.com>

Hi folks,

I want to practice Python programming by developing complete applications.

Where can I get such problems, which can improve my Python programming
skills.

Thanks in anticipation.

Regards,

Asrar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070414/552f554d/attachment.html 

From washakie at juno.com  Sun Apr 15 00:57:32 2007
From: washakie at juno.com (Washakie Wyoming)
Date: Sat, 14 Apr 2007 22:57:32 GMT
Subject: [Tutor] read text file in zip archive, process, plot
Message-ID: <20070414.155827.774.337103@webmail21.lax.untd.com>

An embedded and charset-unspecified text was scrubbed...
Name: not available
Url: http://mail.python.org/pipermail/tutor/attachments/20070414/049ea718/attachment.pot 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: flight_data.zip
Type: application/zip
Size: 11001 bytes
Desc: flight_data.zip
Url : http://mail.python.org/pipermail/tutor/attachments/20070414/049ea718/attachment.zip 

From arunkumarpg at gmail.com  Sun Apr 15 07:06:54 2007
From: arunkumarpg at gmail.com (Arun Kumar PG)
Date: Sun, 15 Apr 2007 10:36:54 +0530
Subject: [Tutor] threading.currentThread() always same across request ?
In-Reply-To: <462168DA.9070806@tds.net>
References: <3cffff920704132313g4d22cc35u6c80ec7c388ea2ba@mail.gmail.com>
	<4620BA71.1090609@tds.net>
	<20070414173410.GN19371@andi-lap.la.revver.com>
	<462111C1.5040308@tds.net>
	<20070414181151.GO19371@andi-lap.la.revver.com>
	<462168DA.9070806@tds.net>
Message-ID: <3cffff920704142206l45f6f9e8j5c94fc682a30ae31@mail.gmail.com>

Thx guys.

now quick question on the usage of thread local storage.

In my case I have the below object model:

class Base(object):'
  def __init__(self):
    self.__service = None
  def _GetService():
    if not hasattr(threading.currentThread(), 'service'):
      threading.currentThread().service = Service()
      self.__service =  threading.currentThread().service

    return self.__service

class Child1(Base):'
  def DoSomething():
    service = self._GetService()
    # use service

class Child2(Base):'
  def DoSomething():
    service = self._GetService()
    # use service

The above Child classes are used by a controller:

class Controller(object):
  def process(self):
    c1 = Child1()
    c1.DoSomething()
    ....
    ...
    c2 = Child2()
    c2.DoSomething()

Using the above technique the "service" is instantiated only one time i.e.
as soon as I create the first instance of the Child class abd associated
with the current thread for future instantiation of any Child class.

Now in this scenario how can I use thread local ? Where do I keep the thread
local object as in my case I am instantiating the Child classes ? Using
currentThread() always gives me the same thread instance for a given request
and I can bypass instantiating the Service class by simply returning the
"service" attribute already attached to the current thread.

Any suggestion appreciated!

- A






On 4/15/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Andreas Kostyrka wrote:
> > * Kent Johnson <kent37 at tds.net> [070414 19:53]:
> >> That's a good point. Does anyone know when to prefer threading.local()
> >> vs thread attributes?
> > It's design question, I guess:
> >
> > *) if you have thread subclasses, then use thread attributes.
> > *) if you have standard threads, then use thread.local().
> >
> > The idea is, that it's "rude" to stick attributes on an object that is
> > not owned by you.
> >
> > Rationale:
> > *) Somebody might decide to make threading.Thread be a new style
> > object with __slots__ => your code breaks.
> >
> > I know, it's unprobably, but if you derive a subclass, you can be at
> > least sure that the object will have a __dict__ ;)
>
> If you use threading.local() you can be sure the names you use don't
> conflict with any attributes of the thread.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070415/9dc697bb/attachment-0001.html 

From alan.gauld at btinternet.com  Sun Apr 15 09:18:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 15 Apr 2007 08:18:05 +0100
Subject: [Tutor] Seeking python projects
References: <88dc53b0704141440h530a7d33w14a83229b4afeee7@mail.gmail.com>
Message-ID: <evsjjq$etj$1@sea.gmane.org>


"Asrar Kadri" <kadri.asrar at googlemail.com> wrote 

> I want to practice Python programming by developing 
> complete applications.

The best way is to think of an application you want tro 
use yourself and build it. But if you can't think of one 
you can try searching SourceForge for projects 
using Python and join a team of developers working 
on something there.

> Where can I get such problems, which can improve 
> my Python programming skills.

There are several otherways to improve your knowledge.
The appendix topic of my tutorial has several suggestions.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld at btinternet.com  Sun Apr 15 09:35:11 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 15 Apr 2007 08:35:11 +0100
Subject: [Tutor] read text file in zip archive, process, plot
References: <20070414.155827.774.337103@webmail21.lax.untd.com>
Message-ID: <evskjs$gqs$1@sea.gmane.org>


"Washakie Wyoming" <washakie at juno.com> wrote

> I'm writing to ask for ways to improve it. I feel like the
> writing and reading from 'jnk' files is definitely a hack!

Yup!
I'm not sure why you do it, at least the first time.
You read the file into memory, why not just process it there?
You can split the file into lines using split('\n') and you get
the same list that readlines generates from the jnk file.


So you can replace all of this:

        f = open('jnk','w')
        f.write(contents)
        f.close()
        print "file closed, now reading"
        #now open files to process
        f = open('jnk','r')
        fn = open('newjnk','w')
        data = f.readlines()

with

       data = contents.split('\n')
       fn = open('newjnk','w')

I'm not familiar with pyLab so I don;t know if you can
bypass the newjnk file.... Also you seem to overwrite
the newjnk file before you use it. open('w') will overwrite
the existing file. Is that what you want? Or should you
be appending the data? Or maybe you want to create
a new file for each file in the zipfile? So you create a
new filename like:

       fn = open(filename + '.jnk', 'w')

Othewise your pylab section only ever processes the
last file in the zipfile.

> Any suggestions?

The other thing is that I'd introduce a couple of functions,
one to process each file from the archive, the second to
do the pylab stuff. So your outer loop will shrink to
something like:

for filename in z.namelist():
     prepareFile(filename)
     display(filename)

It helps to keep the logic separated which makes
maintenance easier in the future.

HTH,

Alan G.

Here's my program (a zip is attached - if that's allowed???):

import zipfile
import os
import pylab as P

z = zipfile.ZipFile("flight_data.zip", "r")
for filename in z.namelist():
        print filename
        contents = z.read(filename)
        f = open('jnk','w')
        f.write(contents)
        f.close()
        print "file closed, now reading"
        #now open files to process
        f = open('jnk','r')
        fn = open('newjnk','w')
        data = f.readlines()
        firstline = data[0].strip().split(' ')
        stind = int(firstline[0])
        hdrline = stind - 1
        #print data[stind:len(data)]
        for l in data[stind:len(data)]:
                #l = l.replace('  ',',')
                fn.writelines(l)
        f.close()
        fn.close()
        #print 'file closed now'

jnk2 = P.load('newjnk')
t = jnk2[:,0]
x = jnk2[:,24]

P.scatter(t,x)
P.xlabel('time (s) after 00 UTC')
P.ylabel('Altitude (hPa)')
P.title('Flight elevation vs. Time')
P.grid(True)
if os.path.exists("flight_track.png"):
     os.remove("flight_track.png")
P.savefig('flight_track')
P.close()
os.remove("jnk")
os.remove("newjnk")






________________________________________________________________________
Interested in getting caught up on today's news?
Click here to checkout USA TODAY Headlines.
http://track.juno.com/s/lc?s=198954&u=http://www.usatoday.com/news/front.htm?csp=24




--------------------------------------------------------------------------------


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From kent37 at tds.net  Sun Apr 15 13:23:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 15 Apr 2007 07:23:19 -0400
Subject: [Tutor] read text file in zip archive, process, plot
In-Reply-To: <20070414.155827.774.337103@webmail21.lax.untd.com>
References: <20070414.155827.774.337103@webmail21.lax.untd.com>
Message-ID: <46220B27.1060109@tds.net>

Washakie Wyoming wrote:
> Greetings all!
> 
> I'm including here a first python program! Very nice. It's written to
> read in a text file which resides in a .zip archive, extract two fields
> and plot them. It uses some bits from pylab for the plotting.
> 
> I'm writing to ask for ways to improve it. I feel like the writing and
> reading from 'jnk' files is definitely a hack! Any suggestions? I would
> be greatly appreciative of anyone provided comments on how to more
> efficiently tackle this problem. (NOTE: this is not a school
> assignment... just some side learning out of interest in what seems to
> be a great language!).
> 
> Thanks!
> 
> Here's my program (a zip is attached - if that's allowed???):
> 
> import zipfile
> import os
> import pylab as P
> 
> z = zipfile.ZipFile("flight_data.zip", "r")
> for filename in z.namelist():
>         print filename
>         contents = z.read(filename)
>         f = open('jnk','w')
>         f.write(contents)
>         f.close()
>         print "file closed, now reading"
>         #now open files to process
>         f = open('jnk','r')
>         fn = open('newjnk','w') 
>         data = f.readlines()

Alan has shown you a better way to do this.

>         firstline = data[0].strip().split(' ')
>         stind = int(firstline[0])      
>         hdrline = stind - 1
>         #print data[stind:len(data)]
>         for l in data[stind:len(data)]:

You don't need the end index when it is the length of the data:
   for l in data[stind:]:

>                 #l = l.replace('  ',',')
>                 fn.writelines(l)
>         f.close()
>         fn.close()
>         #print 'file closed now'
>         
> jnk2 = P.load('newjnk')
> t = jnk2[:,0]
> x = jnk2[:,24]

It looks like you are using newjnk just as a way to get P.load() to 
parse the data for you. You can do this yourself with something like
   x = []
   t = []
   for l in data[stind:]:
     l = l.split()  # Split on whitespace
     tval = float(l[0])
     t.append(tval)
     xval = float(l[24])
     x.append(xval)

Kent

From washakie at juno.com  Sun Apr 15 13:52:09 2007
From: washakie at juno.com (Washakie Wyoming)
Date: Sun, 15 Apr 2007 11:52:09 GMT
Subject: [Tutor] read text file in zip archive, process, plot
Message-ID: <20070415.045259.8794.2796030@webmail03.lax.untd.com>

An embedded and charset-unspecified text was scrubbed...
Name: not available
Url: http://mail.python.org/pipermail/tutor/attachments/20070415/e32c0981/attachment.pot 

From washakie at gmail.com  Sun Apr 15 14:32:44 2007
From: washakie at gmail.com (John W)
Date: Sun, 15 Apr 2007 14:32:44 +0200
Subject: [Tutor]  read text file in zip archive, process, plot
Message-ID: <aaf235960704150532tfde3123kbe6de8fd358b45f7@mail.gmail.com>

Kent and Alan: better?
.j

import zipfile
import os
import pylab as P
iFile = raw_input("Which file to process?")

def openarchive(filename):
    """ open the cmet archive and read contents of file into memory """
    z = zipfile.ZipFile(filename, "r")
    for filename in z.namelist():
        print filename
        contents = z.read(filename)
        data = contents.split('\n')
        return data

def plotflight(data):
    """ Plot flight data t vs. hPa with Pylab """
    firstline = data[0].strip().split(' ')
    stind = int(firstline[0])
    hdrline = stind - 1
    x = []
    t = []
    for l in data[stind:-1]:
            l = l.split()  # Split on whitespace
            tval = float(l[0])
            t.append(tval)
            xval = float(l[24])
            x.append(xval)
    #Create scatter plot using pylab function
    P.scatter(t,x)
    P.xlabel('time (s) after 00 UTC')
    P.ylabel('Altitude (hPa)')
    P.title('Flight elevation vs. Time')
    P.grid(True)
    #print out figure
    if os.path.exists("flight_track.png"):
     os.remove("flight_track.png")
    P.savefig('flight_track')
    P.close()

flightdata = openarchive(iFile)
plotflight(flightdata)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070415/b4f3c53b/attachment.htm 

From andreas at kostyrka.org  Sun Apr 15 14:39:29 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sun, 15 Apr 2007 14:39:29 +0200
Subject: [Tutor] read text file in zip archive, process, plot
In-Reply-To: <20070415.045259.8794.2796030@webmail03.lax.untd.com>
References: <20070415.045259.8794.2796030@webmail03.lax.untd.com>
Message-ID: <20070415123929.GQ19371@andi-lap.la.revver.com>

* Washakie Wyoming <washakie at juno.com> [070415 14:25]:
> Thank you both! That seems to make my code much more clear... I thought
> it was foolish writing files, but I just couldn't determine how to
> parse the data!
> 
> Kent, one thing, regarding:
>         x = []
>         t = []
>         for l in data[stind:-1]:
>                 l = l.split()  # Split on whitespace
>                 tval = float(l[0])
>                 t.append(tval)
>                 xval = float(l[24])
>                 x.append(xval)
> 
> note that I had to change to [stind:-1] I believe I must have a blank
> line at the end of the file...
That depends upon the platform. Under Unix, files are meant to be
ending in a \n, so you get an empty line at the end. But nobody
enforces that.

So personally, I'd probably add something like this to the loop:
       l = l.split()
       if not l:
           continue

This way the loop ignores empty lines.

Andreas

From kent37 at tds.net  Sun Apr 15 15:43:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 15 Apr 2007 09:43:53 -0400
Subject: [Tutor] read text file in zip archive, process, plot
In-Reply-To: <aaf235960704150532tfde3123kbe6de8fd358b45f7@mail.gmail.com>
References: <aaf235960704150532tfde3123kbe6de8fd358b45f7@mail.gmail.com>
Message-ID: <46222C19.7030304@tds.net>

John W wrote:
> Kent and Alan: better?
> .j
> 
> import zipfile
> import os
> import pylab as P
> iFile = raw_input("Which file to process?")
> 
> def openarchive(filename):
>     """ open the cmet archive and read contents of file into memory """
>     z = zipfile.ZipFile(filename, "r")
>     for filename in z.namelist():
>         print filename
>         contents = z.read(filename)
>         data = contents.split('\n')
>         return data

This will just return the data of the first file in the zip, is that 
what you want? The return statement will exit from the loop. If there 
can be more than one file in the zip, you should call plotflight(data) 
within the loop instead of returning the data.

If you only want the first file, you could omit the loop and write
   filename = z.namelist()[0]

> def plotflight(data):
>     """ Plot flight data t vs. hPa with Pylab """
>     firstline = data[0].strip().split(' ')
>     stind = int(firstline[0])     
>     hdrline = stind - 1

You don't use hdrline

>     x = []
>     t = []
>     for l in data[stind:-1]:
>             l = l.split()  # Split on whitespace
>             tval = float(l[0])
>             t.append(tval)
>             xval = float(l[24])
>             x.append(xval)

I split out tval and xval for clarity but I would actually write this as
   t.append(float(l[0]))
and skip the temp variables.

>     #Create scatter plot using pylab function
>     P.scatter(t,x)
>     P.xlabel('time (s) after 00 UTC')
>     P.ylabel('Altitude (hPa)')
>     P.title('Flight elevation vs. Time')
>     P.grid(True)
>     #print out figure
>     if os.path.exists("flight_track.png"):
>      os.remove("flight_track.png")
>     P.savefig('flight_track')
>     P.close()
> 
> flightdata = openarchive(iFile)
> plotflight(flightdata)
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From ebbaalm at uiuc.edu  Sun Apr 15 17:49:10 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 15 Apr 2007 10:49:10 -0500
Subject: [Tutor] imported module/global
Message-ID: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>

If a module "x" imports module "y" with a global variable "z", then
this global can be referred or assigned to in "x" with the syntax
"y.z" (no "global" keyword preceding) and changes are accessible to
class methods in "y" referring to "global z".

I assume this is related to namespace/scope?

Thanks!

From washakie at gmail.com  Sun Apr 15 18:38:35 2007
From: washakie at gmail.com (Washakie)
Date: Sun, 15 Apr 2007 18:38:35 +0200
Subject: [Tutor] read text file in zip archive, process, plot
In-Reply-To: <46222C19.7030304@tds.net>
References: <aaf235960704150532tfde3123kbe6de8fd358b45f7@mail.gmail.com>
	<46222C19.7030304@tds.net>
Message-ID: <aaf235960704150938u4fc2c18dldc4ba04533ac3ab6@mail.gmail.com>

Thanks so much! Now another task, associated with this one... what I
actually ultimately want is to just pull out several fields from the text
file in the zip archive (there is actually only one file).. so, my goal is
the to create a file that looks like:

t[0], x[0], y[0]
t[1], x[1], y[1]
t[2], x[2], y[2]
t[3], x[3], y[3]
...
t[:], x[:], y[:]

Note, these would actually be strings representing the values... and I'm not
trying to do the header yet... :s

I've tried OUT = [t,x,y ]
but when I write it out, it seems to go through all of t first, then x, then
y...
i'm having a really hard time switching my thinking away from matlab array
processing which I think is part of my problem!! I read a discussion last
night that I thought was interesting:
http://mail.python.org/pipermail/python-list/2002-December/174954.html

It was this point that made me start to think I need to 'rethink' how I'm
going about things... but argh!! ... how to teach an old dog new tricks!

-j



>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070415/a43f0d15/attachment.html 

From kent37 at tds.net  Sun Apr 15 19:08:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 15 Apr 2007 13:08:27 -0400
Subject: [Tutor] read text file in zip archive, process, plot
In-Reply-To: <aaf235960704150938u4fc2c18dldc4ba04533ac3ab6@mail.gmail.com>
References: <aaf235960704150532tfde3123kbe6de8fd358b45f7@mail.gmail.com>	
	<46222C19.7030304@tds.net>
	<aaf235960704150938u4fc2c18dldc4ba04533ac3ab6@mail.gmail.com>
Message-ID: <46225C0B.3070306@tds.net>

Washakie wrote:
> Thanks so much! Now another task, associated with this one... what I 
> actually ultimately want is to just pull out several fields from the 
> text file in the zip archive (there is actually only one file).. so, my 
> goal is the to create a file that looks like:
> 
> t[0], x[0], y[0]
> t[1], x[1], y[1]
> t[2], x[2], y[2]
> t[3], x[3], y[3]
> ...
> t[:], x[:], y[:]
> 
> Note, these would actually be strings representing the values... and I'm 
> not trying to do the header yet... :s

You could just write them out as you process them. The same loop that 
reads the input lines can write the output lines.
> 
> I've tried OUT = [t,x,y ]
> but when I write it out, it seems to go through all of t first, then x, 
> then y...
> i'm having a really hard time switching my thinking away from matlab 
> array processing which I think is part of my problem!!

Have you looked at NumPy? It has a native array type.
http://numpy.scipy.org/
http://www.scipy.org/NumPy_for_Matlab_Users

Kent


From ermastley at charter.net  Sun Apr 15 19:10:43 2007
From: ermastley at charter.net (Gene Astley)
Date: Sun, 15 Apr 2007 10:10:43 -0700
Subject: [Tutor] DOTNETNUKE 4.5
Message-ID: <002a01c77f81$00549380$6501a8c0@D3K8PT61>

I am an administrator in charge of creating and maintaining our web site. I use Dreamweaver/Front Page composition tools. I am being urged to convert to DOTNETNUKE 4.5. This is a open source Framework for Creating Enterprise Web Applications. They say it is built on Microsoft ASP.net (VB,Net) platform.
Do you have an opinion of whether it is better than Dreamworks and will it be compatible with python?

Gene Astley
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070415/183918c6/attachment.htm 

From kent37 at tds.net  Sun Apr 15 19:12:49 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 15 Apr 2007 13:12:49 -0400
Subject: [Tutor] imported module/global
In-Reply-To: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
Message-ID: <46225D11.5090104@tds.net>

Cecilia Alm wrote:
> If a module "x" imports module "y" with a global variable "z", then
> this global can be referred or assigned to in "x" with the syntax
> "y.z" (no "global" keyword preceding) and changes are accessible to
> class methods in "y" referring to "global z".

Yes.

> I assume this is related to namespace/scope?

I suppose. Python doesn't really have a global scope other than the 
builtin scope. What is called global scope is really module scope. 
Global variables, functions and classes defined in a module are 
attributes of the module object. When you import the module in another 
module, you gain access to the imported module's attributes using the 
normal dot notation for attribute access.

Kent

From andreas at kostyrka.org  Sun Apr 15 20:29:37 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sun, 15 Apr 2007 20:29:37 +0200
Subject: [Tutor] imported module/global
In-Reply-To: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
Message-ID: <20070415182937.GR19371@andi-lap.la.revver.com>

* Cecilia Alm <ebbaalm at uiuc.edu> [070415 18:21]:
> If a module "x" imports module "y" with a global variable "z", then
> this global can be referred or assigned to in "x" with the syntax
> "y.z" (no "global" keyword preceding) and changes are accessible to
> class methods in "y" referring to "global z".

Well, you don't need the global statement for accessing z. You need it
for modifying it, or Python will assume that you are working with a
local variable z.

Andreas

From andreas at kostyrka.org  Sun Apr 15 20:37:18 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sun, 15 Apr 2007 20:37:18 +0200
Subject: [Tutor] read text file in zip archive, process, plot
In-Reply-To: <46225C0B.3070306@tds.net>
References: <aaf235960704150532tfde3123kbe6de8fd358b45f7@mail.gmail.com>
	<46222C19.7030304@tds.net>
	<aaf235960704150938u4fc2c18dldc4ba04533ac3ab6@mail.gmail.com>
	<46225C0B.3070306@tds.net>
Message-ID: <20070415183715.GT19371@andi-lap.la.revver.com>

* Kent Johnson <kent37 at tds.net> [070415 20:30]:
> Washakie wrote:
> > Thanks so much! Now another task, associated with this one... what I 
> > actually ultimately want is to just pull out several fields from the 
> > text file in the zip archive (there is actually only one file).. so, my 
> > goal is the to create a file that looks like:
> > 
> > t[0], x[0], y[0]
> > t[1], x[1], y[1]
> > t[2], x[2], y[2]
> > t[3], x[3], y[3]
> > ...
> > t[:], x[:], y[:]
> > 
> > Note, these would actually be strings representing the values... and I'm 
> > not trying to do the header yet... :s
> 
> You could just write them out as you process them. The same loop that 
> reads the input lines can write the output lines.

Consider using the csv module.

out = file("output", "w")
cout = csv.writer(out)
cout.writerow((1,2,3,"abc", "def"))

> > 
> > I've tried OUT = [t,x,y ]
> > but when I write it out, it seems to go through all of t first, then x, 
> > then y...
> > i'm having a really hard time switching my thinking away from matlab 
> > array processing which I think is part of my problem!!

out = file("output", "w")
cout = csv.writer(out)
cout.writerows(zip(t, x, y))
out.close()

Andreas

From alan.gauld at btinternet.com  Sun Apr 15 21:05:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 15 Apr 2007 20:05:05 +0100
Subject: [Tutor] DOTNETNUKE 4.5
References: <002a01c77f81$00549380$6501a8c0@D3K8PT61>
Message-ID: <evtt1e$u9o$1@sea.gmane.org>

"Gene Astley" <ermastley at charter.net> wrote 

> I am an administrator in charge of creating and maintaining 
> our web site. I use Dreamweaver/Front Page composition tools. 

Fairly conventional, good tools.

> I am being urged to convert to DOTNETNUKE 4.5. 

By whom and why?
Is there a rational reason for the change or simply
a religious fervour for something new?

There is a strong case for "if it aint broke don;t fix it...."

> This is a open source Framework for Creating Enterprise 
> Web Applications. They say it is built on Microsoft ASP.net 
> (VB,Net) platform.

Not in itself an argument for change unless the rest of your 
organisation are heavily into .NET

> Do you have an opinion of whether it is better than 
> Dreamworks and will it be compatible with python?

There is a .NET version of Python so I suppose that would 
work. Beyond that I'd need to find out more about it. But you 
can use the Dreamweaver stuff to develop ASP and .NET web 
apps too - although unless you have a specific reason there's 
no need to.

It all sounds slightly odd to me! If that's your biggest worry 
then you don't have too much to be concerned about 
IMHO. :-)


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From jjcrump at myuw.net  Sun Apr 15 20:41:15 2007
From: jjcrump at myuw.net (Jon Crump)
Date: Sun, 15 Apr 2007 11:41:15 -0700 (PDT)
Subject: [Tutor] beautifulSoup and .next iteration
In-Reply-To: <Pine.LNX.4.63.0704132055570.5041@cs.wpi.edu>
References: <Pine.LNX.4.63.0704132055570.5041@cs.wpi.edu>
Message-ID: <Pine.LNX.4.64.0704151131410.18498@cicero11.myuw.net>

Daniel,

It was kind of you to respond, and your response was a model of clarity. 
You correctly surmised from my awkward framing of the question, that what 
I wanted was a list of sibling elements between one named anchor and the 
next. My problem was, in part, that I still don't think in terms of 
functional programming, thus, the function defs you proposed are very 
helpful models for me. I do, however, still need to work out how to make 
is_anchor() return true only if the anchor name attribute satisfies a 
given regex. Starting with your model, I'm sure I'll be able to figure 
this out.

Thanks so much for your time!

Jon

>
> You might find the following definitions helpful:
>
> #############################################################
> def get_siblings_to_next_anchor(anchor):
>    """Anchor Tag -> element list
>
>    Given an anchor element, returns all the nextSiblings elements up to
>    (but not including) the next anchor as a list of either Tags or
>    NavigatableStrings."""
>
>    elt = anchor.nextSibling
>    results = []
>    while (elt != None) and (not is_anchor(elt)):
>        results.append(elt)
>        elt = elt.nextSibling
>    return results
>
>
> def is_anchor(elt):
>    """element -> boolean
>    Returns true if the element is an anchor Tag."""
>
>    if isinstance(elt, NavigableString):
>        return False
>    else:
>        return elt.name == 'a'
> #############################################################

From ebbaalm at uiuc.edu  Sun Apr 15 22:51:20 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 15 Apr 2007 15:51:20 -0500
Subject: [Tutor] imported module/global
In-Reply-To: <20070415182937.GR19371@andi-lap.la.revver.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<20070415182937.GR19371@andi-lap.la.revver.com>
Message-ID: <7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>

2007/4/15, Andreas Kostyrka <andreas at kostyrka.org>:
> * Cecilia Alm <ebbaalm at uiuc.edu> [070415 18:21]:
> > If a module "x" imports module "y" with a global variable "z", then
> > this global can be referred or assigned to in "x" with the syntax
> > "y.z" (no "global" keyword preceding) and changes are accessible to
> > class methods in "y" referring to "global z".
>
> Well, you don't need the global statement for accessing z. You need it
> for modifying it, or Python will assume that you are working with a
> local variable z.
>

Hm, I'm confused by your post. Within the global's module, the "global
z" syntax works for bothh modifying and accessing, and makes the code
clearer to read in my opinion. (Although, it may not be needed when
accessing or when modifying mutable types.)

But, when importing the module ("y") of the global in another module,
the syntax "y.z" seems adequate both for accessing and modifying, as
confirmed by Keith's post (prepending 'global' results in NameError).

From ebbaalm at uiuc.edu  Sun Apr 15 23:08:49 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 15 Apr 2007 16:08:49 -0500
Subject: [Tutor] imported module/global
In-Reply-To: <46225D11.5090104@tds.net>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<46225D11.5090104@tds.net>
Message-ID: <7a4620dc0704151408n3aa31c26wfc5ed06f65ad25ca@mail.gmail.com>

> attributes of the module object. When you import the module in another
> module, you gain access to the imported module's attributes using the
> normal dot notation for attribute access.

By " attribute access", you also mean modifying/assigning to, right?

From andreas at kostyrka.org  Sun Apr 15 23:25:13 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sun, 15 Apr 2007 23:25:13 +0200
Subject: [Tutor] imported module/global
In-Reply-To: <7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<20070415182937.GR19371@andi-lap.la.revver.com>
	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
Message-ID: <20070415212513.GU19371@andi-lap.la.revver.com>

* Cecilia Alm <ebbaalm at uiuc.edu> [070415 23:19]:
> 2007/4/15, Andreas Kostyrka <andreas at kostyrka.org>:
> >* Cecilia Alm <ebbaalm at uiuc.edu> [070415 18:21]:
> >> If a module "x" imports module "y" with a global variable "z", then
> >> this global can be referred or assigned to in "x" with the syntax
> >> "y.z" (no "global" keyword preceding) and changes are accessible to
> >> class methods in "y" referring to "global z".
> >
> >Well, you don't need the global statement for accessing z. You need it
> >for modifying it, or Python will assume that you are working with a
> >local variable z.
> >
> 
> Hm, I'm confused by your post. Within the global's module, the "global
> z" syntax works for bothh modifying and accessing, and makes the code
> clearer to read in my opinion. (Although, it may not be needed when
> accessing or when modifying mutable types.)
Well, the global is not needed for accessing the name.

And the assume it's a local variable is meant serious:

>>> def x():
...     z += 1
... 
>>> x()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in x
UnboundLocalError: local variable 'z' referenced before assignment

It's one of the more baffling errors for newbies.

The real reason is important to understand, it explains things like
self. and global:

*) when accessing a name, it's easy to try out multiple namespaces
till you find the correct one.
*) when reassigning a name, it's way harder, because you cannot
automatically guess which namespace should be used.

That's the reason why you need global statement, which makes
assignments to a name go to the module namespace. And that's one of
the reasons, why instance variables are accessed explicitly as self.name.

Andreas

From kent37 at tds.net  Sun Apr 15 23:38:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 15 Apr 2007 17:38:01 -0400
Subject: [Tutor] imported module/global
In-Reply-To: <7a4620dc0704151408n3aa31c26wfc5ed06f65ad25ca@mail.gmail.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>	
	<46225D11.5090104@tds.net>
	<7a4620dc0704151408n3aa31c26wfc5ed06f65ad25ca@mail.gmail.com>
Message-ID: <46229B39.6090605@tds.net>

Cecilia Alm wrote:
>> attributes of the module object. When you import the module in another
>> module, you gain access to the imported module's attributes using the
>> normal dot notation for attribute access.
> 
> By " attribute access", you also mean modifying/assigning to, right?

Yes, you can create and assign attributes in an imported module. In 
general I wouldn't recommend this, it could lead to code that is 
difficult to understand, but sometimes it is useful. For example you 
might have a shared configuration module, or a module might have 
configuration parameters that can be changed.

Kent

From ebbaalm at uiuc.edu  Sun Apr 15 23:46:16 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 15 Apr 2007 16:46:16 -0500
Subject: [Tutor] imported module/global
In-Reply-To: <20070415212513.GU19371@andi-lap.la.revver.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<20070415182937.GR19371@andi-lap.la.revver.com>
	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
	<20070415212513.GU19371@andi-lap.la.revver.com>
Message-ID: <7a4620dc0704151446y412300dbpc59c2b3acd918228@mail.gmail.com>

Well, your example still seems to be about accessing or modifying a
global variable *within* its own module. Then it can't hurt to prepend
'global' even when just accessing, right? (even if not *necessary*,
one could argue make the code clearer).

But, my question related specifically to another case:  when another
module import a second module and the importing module tries to access
and modify the second module's "global" variable, which Kent's post
explained is really a module attribute. Then, the dot notation seems
needed.

(Maybe its my use of 'global' in this context which causes misunderstanding?)



2007/4/15, Andreas Kostyrka <andreas at kostyrka.org>:
> * Cecilia Alm <ebbaalm at uiuc.edu> [070415 23:19]:
> > 2007/4/15, Andreas Kostyrka <andreas at kostyrka.org>:
> > >* Cecilia Alm <ebbaalm at uiuc.edu> [070415 18:21]:
> > >> If a module "x" imports module "y" with a global variable "z", then
> > >> this global can be referred or assigned to in "x" with the syntax
> > >> "y.z" (no "global" keyword preceding) and changes are accessible to
> > >> class methods in "y" referring to "global z".
> > >
> > >Well, you don't need the global statement for accessing z. You need it
> > >for modifying it, or Python will assume that you are working with a
> > >local variable z.
> > >
> >
> > Hm, I'm confused by your post. Within the global's module, the "global
> > z" syntax works for bothh modifying and accessing, and makes the code
> > clearer to read in my opinion. (Although, it may not be needed when
> > accessing or when modifying mutable types.)
> Well, the global is not needed for accessing the name.
>
> And the assume it's a local variable is meant serious:
>
> >>> def x():
> ...     z += 1
> ...
> >>> x()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in x
> UnboundLocalError: local variable 'z' referenced before assignment
>
> It's one of the more baffling errors for newbies.
>
> The real reason is important to understand, it explains things like
> self. and global:
>
> *) when accessing a name, it's easy to try out multiple namespaces
> till you find the correct one.
> *) when reassigning a name, it's way harder, because you cannot
> automatically guess which namespace should be used.
>
> That's the reason why you need global statement, which makes
> assignments to a name go to the module namespace. And that's one of
> the reasons, why instance variables are accessed explicitly as self.name.
>
> Andreas
>


-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

From ebbaalm at uiuc.edu  Sun Apr 15 23:47:34 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 15 Apr 2007 16:47:34 -0500
Subject: [Tutor] imported module/global
In-Reply-To: <46229B39.6090605@tds.net>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<46225D11.5090104@tds.net>
	<7a4620dc0704151408n3aa31c26wfc5ed06f65ad25ca@mail.gmail.com>
	<46229B39.6090605@tds.net>
Message-ID: <7a4620dc0704151447n7d2c0410p74fdf43bbc6e9a76@mail.gmail.com>

> difficult to understand, but sometimes it is useful. For example you
> might have a shared configuration module, or a module might have
> configuration parameters that can be changed.

Yes, this is exactly the case I got. (Otherwise, I'd rather avoid
"globals" all together.)

Thanks for your responses.

From alan.gauld at btinternet.com  Mon Apr 16 00:22:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 15 Apr 2007 23:22:45 +0100
Subject: [Tutor] imported module/global
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com><20070415182937.GR19371@andi-lap.la.revver.com>
	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
Message-ID: <evu8k2$11j$1@sea.gmane.org>

"Cecilia Alm" <ebbaalm at uiuc.edu> wrote

> Hm, I'm confused by your post. Within the global's module, the 
> "global
> z" syntax works for bothh modifying and accessing, and makes the 
> code
> clearer to read in my opinion.

You seem to be confused about the role of the global keyword.

It is purely used to define a name within a local namespace
(ie inside a function) as being proper to the module's namespace.

It has no role whatsoever in assignment or in access, it
purely controls the namespace. In practice of course
this means that assignments in the local namespace to
a name defined to be global do not create a local version, it
has no affect whatsoever on access.

global in Python is completely different to the type definition
usage found in other languages (eg static in C)

Does using it when access only in required do any harm?
No.
Does using it make the code more readable?
Only very marginally to those familiar with Puython,
but possibly more so to those from other languages.

But using it for access only is non Pythonic and therefore
out of idiom to experienced Python profgrammers which
might lead to confusion rather than clarity. Personally I'd
always argue for using the local languages idioms rather
than changing the idiom to suit new users temporary
disorientation. And it could cause such users to take
away the erroneous idea that global somwhow affected
access, which could cause cognitive issues when dealing
with more convemntional usage..

> (Although, it may not be needed when
> accessing or when modifying mutable types.)

Again it has nothing whatsoever to do with types whether
mutable or not. It is purely about defining where a name
is located.

> But, when importing the module ("y") of the global in another 
> module,
> the syntax "y.z" seems adequate both for accessing and modifying, as
> confirmed by Keith's post (prepending 'global' results in 
> NameError).

Because global only applies in the local module.
As Kent suggested global is an unfortunate choice of a name and it
should really be "module", since that is as far as the scope extends.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From ebbaalm at uiuc.edu  Mon Apr 16 01:36:16 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 15 Apr 2007 18:36:16 -0500
Subject: [Tutor] imported module/global
In-Reply-To: <evu8k2$11j$1@sea.gmane.org>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<20070415182937.GR19371@andi-lap.la.revver.com>
	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
	<evu8k2$11j$1@sea.gmane.org>
Message-ID: <7a4620dc0704151636g76787137qb1114ab4d3f8408@mail.gmail.com>

OK, apologies if my terminology and wording was unfortunate and unclear.

(Setting aside for now if this is preferred practice or not) In
regards to modifying a global mutable list/dictionary (for example
appending to a global list), the name does not need defined within the
local namespace, right? However, for example for a global integer
counter, the name would need to be defined in the local name space, as
shown by Andreas' previous example.

2007/4/15, Alan Gauld <alan.gauld at btinternet.com>:
> "Cecilia Alm" <ebbaalm at uiuc.edu> wrote
>
> > Hm, I'm confused by your post. Within the global's module, the
> > "global
> > z" syntax works for bothh modifying and accessing, and makes the
> > code
> > clearer to read in my opinion.
>
> You seem to be confused about the role of the global keyword.
>
> It is purely used to define a name within a local namespace
> (ie inside a function) as being proper to the module's namespace.
>
> It has no role whatsoever in assignment or in access, it
> purely controls the namespace. In practice of course
> this means that assignments in the local namespace to
> a name defined to be global do not create a local version, it
> has no affect whatsoever on access.
>
> global in Python is completely different to the type definition
> usage found in other languages (eg static in C)
>
> Does using it when access only in required do any harm?
> No.
> Does using it make the code more readable?
> Only very marginally to those familiar with Puython,
> but possibly more so to those from other languages.
>
> But using it for access only is non Pythonic and therefore
> out of idiom to experienced Python profgrammers which
> might lead to confusion rather than clarity. Personally I'd
> always argue for using the local languages idioms rather
> than changing the idiom to suit new users temporary
> disorientation. And it could cause such users to take
> away the erroneous idea that global somwhow affected
> access, which could cause cognitive issues when dealing
> with more convemntional usage..
>
> > (Although, it may not be needed when
> > accessing or when modifying mutable types.)
>
> Again it has nothing whatsoever to do with types whether
> mutable or not. It is purely about defining where a name
> is located.
>
> > But, when importing the module ("y") of the global in another
> > module,
> > the syntax "y.z" seems adequate both for accessing and modifying, as
> > confirmed by Keith's post (prepending 'global' results in
> > NameError).
>
> Because global only applies in the local module.
> As Kent suggested global is an unfortunate choice of a name and it
> should really be "module", since that is as far as the scope extends.
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

From nalrawahi at gmail.com  Mon Apr 16 04:32:47 2007
From: nalrawahi at gmail.com (Nader Alrawahi)
Date: Sun, 15 Apr 2007 22:32:47 -0400
Subject: [Tutor] Protected in Python
Message-ID: <aa2bc4840704151932g515f3be4y1d95aeabff050472@mail.gmail.com>

Hello everyone,
I have been working on an object-oriented project using Python and I was
browsing through the manual looking for some information about data-hiding
in Python. We know that methods can be private or public , but is there a
way we can make them protected in Python, something similar to Java? maybe?
and if that so how does that work? I have been googling around and I found
this post:
http://mail.python.org/pipermail/python-list/2006-April/377721.html ,
"protected
= used internally by base and derived classes" , can someone please explain
further or point me to the right direction to search or read?


Appreciate it!

-- 
Nader
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070415/b7f4fc0b/attachment.html 

From alan.gauld at btinternet.com  Mon Apr 16 07:43:02 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 16 Apr 2007 06:43:02 +0100
Subject: [Tutor] Protected in Python
References: <aa2bc4840704151932g515f3be4y1d95aeabff050472@mail.gmail.com>
Message-ID: <evv2dk$pbs$1@sea.gmane.org>


"Nader Alrawahi" <nalrawahi at gmail.com> wrote

> in Python. We know that methods can be private or public , but is 
> there a
> way we can make them protected in Python, something similar to Java?

No, Python does not support protected.
However a common conventionis to use a single underscore
before the name to *suggest* that the name should not be directly
accessed, rather like protected attributes.

However IMHO you are far better off working without the type of
data hiding you use in static languages like C++/Java etc.
Embrace the Python idioms and stop worrying about such things
unless you have a very real reason. (Even then I suggest that
using properties is a better solution in most cases). The Python
way is to believe that we are all intelligent programmers and trust
us.

C++ introduced the private/protected/public paranoia into OOP
and unfortunately every language since seems to have followed it.
But such tricks are rarely needed if the class is designed properly
such that the operations do all that is needed. And if they don't
then no amount of "protection" will impriove the situation, it just
makes the class harder to use/reuse. Even C++ didn't introduce
protected till version 2.0...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From andreas at kostyrka.org  Mon Apr 16 08:00:27 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Mon, 16 Apr 2007 08:00:27 +0200
Subject: [Tutor] imported module/global
In-Reply-To: <7a4620dc0704151636g76787137qb1114ab4d3f8408@mail.gmail.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<20070415182937.GR19371@andi-lap.la.revver.com>
	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
	<evu8k2$11j$1@sea.gmane.org>
	<7a4620dc0704151636g76787137qb1114ab4d3f8408@mail.gmail.com>
Message-ID: <20070416060027.GV19371@andi-lap.la.revver.com>

* Cecilia Alm <ebbaalm at uiuc.edu> [070416 07:45]:
> OK, apologies if my terminology and wording was unfortunate and unclear.
> 
> (Setting aside for now if this is preferred practice or not) In
> regards to modifying a global mutable list/dictionary (for example
> appending to a global list), the name does not need defined within the
> local namespace, right? However, for example for a global integer
> counter, the name would need to be defined in the local name space, as
> shown by Andreas' previous example.
Naturally. But you should not confuse these two operations. Rebinding
(assigning) a name is a different beast than modifying an existing
object.

t1.py:
from t2 import x, test
test()
print x # prints [123]

t2.py:
x = []

def test():
    x.append(123)

Compare with this:

t1.py:
from t2 import x, test
test()
print x # prints 0

t2.py:
x = 0

def test():
    global x
    x = 123

And concerning your claim that adding a global is more readable for
access, I'd like to point out, that if I need to see who uses
"VarName", I usually just search for the string. If I need to see who
rebinds "VarName", I search for "global VarName" => thus
systematically adding global will make your code harder to understand
for the typical developer.

OTOH, module globals are seldom used, and usually frowned on. E.g. the
python2.5 standard lib (>200K lines, 584 py files), uses exactly 104
distinct global statements.

andreas at andi-lap:/usr/lib/python2.5> grep -r "^[ \t]*global " . | sed 's/[ \t][ \t]*/ /' | sort -u | wc -l
105
andreas at andi-lap:/usr/lib/python2.5> find . -name \*.py | xargs wc -l | tail -1
 202106 insgesamt
andreas at andi-lap:/usr/lib/python2.5> find . -name \*.py | wc -l
584

In practice I have seldom to use globals.

Andreas

From atpridgen at mail.utexas.edu  Mon Apr 16 10:27:35 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Mon, 16 Apr 2007 03:27:35 -0500
Subject: [Tutor] python instances and type
Message-ID: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>

Hello,

Sorry for the long email, but thanks in advance.

I am not quite sure what is happening, so I have not been able to
adequately seek a solution via Google, so if this answer is fairly
easy to find on Google, let me know.  I am not sure how to produce an
example of my problem without using the python code and classes that I
have, so I will try to compose an effective  theoretical example
below.  If there are any clarifications to be made please let me know.

Basically the problem I am having is obtaining the proper type
identification from a Python object.  So going through the motions,
lets say I have 2 types:

class foo_1:
   data = ""
class foo_2:
  foo_1s={}

Time goes by and some assignments are performed and foo_2 is populated
with some foo_1 objects.  Now, I am using the the function below,
get_class_resolution to get the type of foo_1 and foo_2, and it works
well when I don't perform any black magic voodoo and simply use after
the object is created.

It would return the string "foo_1" for the example below:

x = foo_1()
x.data = "boring"
print type(x), type(x).mro()
<class 'foo_1'> [<class 'foo_1'>]
print get_class_resolution(x)
foo_1


But I need to do black magic voodoo, and when I perform an operation
similar to below
on a foo_2 object the get_class_resolution returns "instance".  In
fact I am expecting it to return foo_1.

foo_2o = foo_2()
foo_2o.foo_1s["boring"] = x
bar = foo_2o.foo_1s.values()[0]
print type(bar), type(bar).mro()
<type 'instance'> [<type 'instance'>, <type 'object'>]
print get_class_resolution(bar)
instance

I am not sure what the difference between the instance vs.  a class,
but I never thought the type of the object was allowed to change. Any
help would be appreciated.


Thanks, Adam

def get_class_resolution(obj):
    '''
        get the first class resolution string for a particular object

        @type obj: Mixed/ Any
        @param obj: this is the object to get the name of.  Good
                    for aiding in the comparison of two objects
                    by name and heirarchy

        @rtype: string
        @return: class name resolution of the object
    '''
    # typical output is "[<class 'class.resolution'> <type 'object'>]"
    print str(type(obj).mro())
    print str(type(obj))
    name = str(type(obj).mro()).split("'")[1]
    if len(name.split(".")) > 1:
        return ".".join(name.split(".")[:-1])
    return name

From andreas at kostyrka.org  Mon Apr 16 10:50:54 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Mon, 16 Apr 2007 10:50:54 +0200
Subject: [Tutor] python instances and type
In-Reply-To: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>
References: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>
Message-ID: <20070416085052.GA22885@andi-lap.lan>

Sorry, I cannot replicate your described behaviour:

andreas at andi-lap:~> cat /tmp/t.py
def get_class_resolution(obj):
    '''
        get the first class resolution string for a particular object

        @type obj: Mixed/ Any
        @param obj: this is the object to get the name of.  Good
                    for aiding in the comparison of two objects
                    by name and heirarchy

        @rtype: string
        @return: class name resolution of the object
    '''
    # typical output is "[<class 'class.resolution'> <type 'object'>]"
    print str(type(obj).mro())
    print str(type(obj))
    name = str(type(obj).mro()).split("'")[1]
    if len(name.split(".")) > 1:
        return ".".join(name.split(".")[:-1])
    return name

class foo_1:
   data = ""
class foo_2:
  foo_1s={}
 
x = foo_1()
x.data = "boring"
print type(x), type(x).mro()
print get_class_resolution(x)
foo_1
foo_2o = foo_2()
foo_2o.foo_1s["boring"] = x
bar = foo_2o.foo_1s.values()[0]
print type(bar), type(bar).mro()
print get_class_resolution(bar)

andreas at andi-lap:~> python2.4 /tmp/t.py
<type 'instance'> [<type 'instance'>, <type 'object'>]
[<type 'instance'>, <type 'object'>]
<type 'instance'>
instance
<type 'instance'> [<type 'instance'>, <type 'object'>]
[<type 'instance'>, <type 'object'>]
<type 'instance'>
instance
andreas at andi-lap:~> exit

Amdreas

From andreengels at gmail.com  Mon Apr 16 10:58:49 2007
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 16 Apr 2007 10:58:49 +0200
Subject: [Tutor] python instances and type
In-Reply-To: <6faf39c90704160157p6df339bfh3590da05768e1a1f@mail.gmail.com>
References: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>
	<6faf39c90704160157p6df339bfh3590da05768e1a1f@mail.gmail.com>
Message-ID: <6faf39c90704160158y5ae8c1abh418ca070cfdf3903@mail.gmail.com>

2007/4/16, Adam Pridgen <atpridgen at mail.utexas.edu>:
> Hello,
>
> Sorry for the long email, but thanks in advance.
>
> I am not quite sure what is happening, so I have not been able to
> adequately seek a solution via Google, so if this answer is fairly
> easy to find on Google, let me know.  I am not sure how to produce an
> example of my problem without using the python code and classes that I
> have, so I will try to compose an effective  theoretical example
> below.  If there are any clarifications to be made please let me know.
>
> Basically the problem I am having is obtaining the proper type
> identification from a Python object.  So going through the motions,
> lets say I have 2 types:
> class foo_1:
>    data = ""
> class foo_2:
>   foo_1s={}
>
> Time goes by and some assignments are performed and foo_2 is populated
> with some foo_1 objects.  Now, I am using the the function below,
> get_class_resolution to get the type of foo_1 and foo_2, and it works
> well when I don't perform any black magic voodoo and simply use after
> the object is created.
>
> It would return the string "foo_1" for the example below:
>
> x = foo_1()
> x.data = "boring"
> print type(x), type(x).mro()
> <class 'foo_1'> [<class 'foo_1'>]
> print get_class_resolution(x)
> foo_1

Would it? When I try it out, I get:

>>> class foo_1:
  data = ""

>>> x = foo_1()
>>> x.data = "boring"
>>> print type(x), type(x).mro()
<type 'instance'> [<type 'instance'>, <type 'object'>]
>>> get_class_resolution(x)
[<type 'instance'>, <type 'object'>]
<type 'instance'>
'instance'


To get your desired behaviour, you need something like:

>>> class foo_1(object):
        data = ""


>>> x = foo_1()
>>> x.data = "boring"
>>> print type(x), type(x).mro()
<class '__main__.foo_1'> [<class '__main__.foo_1'>, <type 'object'>]
>>> get_class_resolution(x)
[<class '__main__.foo_1'>, <type 'object'>]
<class '__main__.foo_1'>
'__main__'
>>>
--
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels

From kent37 at tds.net  Mon Apr 16 12:27:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 16 Apr 2007 06:27:33 -0400
Subject: [Tutor] python instances and type
In-Reply-To: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>
References: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>
Message-ID: <46234F95.7010600@tds.net>

Adam Pridgen wrote:

> x = foo_1()
> x.data = "boring"
> print type(x), type(x).mro()
> <class 'foo_1'> [<class 'foo_1'>]

> print type(bar), type(bar).mro()
> <type 'instance'> [<type 'instance'>, <type 'object'>]

As Andre has pointed out, this is a difference between new- and 
old-style classes, not an artifact of the way you are using the classes.

The type and the class of an instance of an old-style class are not the 
same. To find out the class of an old-style class instance, you should 
use the __class__ attribute:
In [1]: class foo_1: pass   # old-style class
    ...:
In [2]: class foo_2(object): pass   # new-style class
    ...:
In [3]: f1 = foo_1()
In [4]: type(f1)
Out[4]: <type 'instance'>
In [5]: f1.__class__
Out[5]: <class __main__.foo_1 at 0x1201090>

For instances of new-style classes, it's class and type are the same and 
__class__ and type() give the same result:
In [14]: f2=foo_2()
In [15]: f2.__class__
Out[15]: <class '__main__.foo_2'>
In [16]: type(f2)
Out[16]: <class '__main__.foo_2'>

If you want to know the base classes that will be searched for attribute 
access of an old-style class, use inspect.getmro(). This will work for 
new-style classes also.

In [19]: import inspect
In [22]: class foo_3(foo_1): pass
    ....:
In [23]: f3=foo_3()
In [24]: type(f3).mro()
Out[24]: [<type 'instance'>, <type 'object'>]
In [25]: inspect.getmro(f3.__class__)
Out[25]: (<class __main__.foo_3 at 0x1272c90>, <class __main__.foo_1 at 
0x1201090>)

Kent


From kent37 at tds.net  Mon Apr 16 12:31:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 16 Apr 2007 06:31:07 -0400
Subject: [Tutor] python instances and type
In-Reply-To: <46234F95.7010600@tds.net>
References: <f989e6210704160127u2370e0ady785f85e8a1f71f60@mail.gmail.com>
	<46234F95.7010600@tds.net>
Message-ID: <4623506B.9020205@tds.net>

Kent Johnson wrote:
> The type and the class of an instance of an old-style class are not the 
> same. 

For a little more explanation, see
http://docs.python.org/ref/node33.html

For a lot more explanation, see
http://www.python.org/doc/newstyle.html

Kent

From rabidpoobear at gmail.com  Mon Apr 16 17:45:35 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 16 Apr 2007 10:45:35 -0500
Subject: [Tutor] imported module/global
In-Reply-To: <20070416060027.GV19371@andi-lap.la.revver.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>	<20070415182937.GR19371@andi-lap.la.revver.com>	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>	<evu8k2$11j$1@sea.gmane.org>	<7a4620dc0704151636g76787137qb1114ab4d3f8408@mail.gmail.com>
	<20070416060027.GV19371@andi-lap.la.revver.com>
Message-ID: <46239A1F.3030708@gmail.com>

Andreas Kostyrka wrote:
> OTOH, module globals are seldom used, and usually frowned on. E.g. the
> python2.5 standard lib (>200K lines, 584 py files), uses exactly 104
> distinct global statements.
>
> andreas at andi-lap:/usr/lib/python2.5> grep -r "^[ \t]*global " . | sed 's/[ \t][ \t]*/ /' | sort -u | wc -l
>   
I don't understand this grep exactly, but it looks to me like it only 
counts globals after tabs...
what about globals after spaces?

From alexf4 at iastate.edu  Mon Apr 16 17:47:04 2007
From: alexf4 at iastate.edu (Kharbush, Alex [ITCSV])
Date: Mon, 16 Apr 2007 10:47:04 -0500
Subject: [Tutor] Multiple lines with the command line
Message-ID: <C8A091151D3C0449BA9A31F3FAC94AFA0AC57B6B@exchs015.ats.iastate.edu>


I want to use the UNIX Mail program with python

I need multiple entries with the os.system(cmd)line

I will need something like this

#output to unix

Mail Alexf4 at iastate.edu -f alexf4 at gmail.com
Subject : hello alex

#message part
how is it going

#the end of mail
. 

When I write os.system("Mail Alexf4 at gmail.com") my program will send email to where i want it to go

MY PROBLEM is that i need to enter multiple lines of input into unix. os.system() takes only one argument

thanks for the time
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070416/99f55a21/attachment.html 

From andreas at kostyrka.org  Mon Apr 16 20:34:19 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Mon, 16 Apr 2007 20:34:19 +0200
Subject: [Tutor] imported module/global
In-Reply-To: <46239A1F.3030708@gmail.com>
References: <7a4620dc0704150849y2303c299vc691abf15b572f02@mail.gmail.com>
	<20070415182937.GR19371@andi-lap.la.revver.com>
	<7a4620dc0704151351l5e5536ffm4bda626068890498@mail.gmail.com>
	<evu8k2$11j$1@sea.gmane.org>
	<7a4620dc0704151636g76787137qb1114ab4d3f8408@mail.gmail.com>
	<20070416060027.GV19371@andi-lap.la.revver.com>
	<46239A1F.3030708@gmail.com>
Message-ID: <20070416183418.GB22885@andi-lap.lan>

* Luke Paireepinart <rabidpoobear at gmail.com> [070416 20:27]:
> Andreas Kostyrka wrote:
> >OTOH, module globals are seldom used, and usually frowned on. E.g. the
> >python2.5 standard lib (>200K lines, 584 py files), uses exactly 104
> >distinct global statements.
> >
> >andreas at andi-lap:/usr/lib/python2.5> grep -r "^[ \t]*global " . | sed 's/[ \t][ \t]*/ /' | sort -u | wc -l
> >  
> I don't understand this grep exactly, but it looks to me like it only counts globals after tabs...
> what about globals after spaces?
Notice the space before \t :)

Andreas

From tktucker at gmail.com  Mon Apr 16 23:19:34 2007
From: tktucker at gmail.com (Tom Tucker)
Date: Mon, 16 Apr 2007 17:19:34 -0400
Subject: [Tutor] Multiple lines with the command line
In-Reply-To: <C8A091151D3C0449BA9A31F3FAC94AFA0AC57B6B@exchs015.ats.iastate.edu>
References: <C8A091151D3C0449BA9A31F3FAC94AFA0AC57B6B@exchs015.ats.iastate.edu>
Message-ID: <2a278ffe0704161419y25bf636ke48afcea334dabf6@mail.gmail.com>

Have you tried the "email" module?

http://docs.python.org/lib/module-email.html



On 4/16/07, Kharbush, Alex [ITCSV] <alexf4 at iastate.edu> wrote:
>
>
> I want to use the UNIX Mail program with python
>
> I need multiple entries with the os.system(cmd)line
>
> I will need something like this
>
> #output to unix
>
> Mail Alexf4 at iastate.edu -f alexf4 at gmail.com
> Subject : hello alex
>
> #message part
> how is it going
>
> #the end of mail
> .
>
> When I write os.system("Mail Alexf4 at gmail.com") my program will send email
> to where i want it to go
>
> MY PROBLEM is that i need to enter multiple lines of input into unix.
> os.system() takes only one argument
>
> thanks for the time
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070416/de417e0e/attachment.html 

From tktucker at gmail.com  Tue Apr 17 00:03:12 2007
From: tktucker at gmail.com (Tom Tucker)
Date: Mon, 16 Apr 2007 18:03:12 -0400
Subject: [Tutor] Multiple lines with the command line
In-Reply-To: <2a278ffe0704161419y25bf636ke48afcea334dabf6@mail.gmail.com>
References: <C8A091151D3C0449BA9A31F3FAC94AFA0AC57B6B@exchs015.ats.iastate.edu>
	<2a278ffe0704161419y25bf636ke48afcea334dabf6@mail.gmail.com>
Message-ID: <2a278ffe0704161503k4a6c26bcm3fb2152fc0828dc9@mail.gmail.com>

Sorry, you mentioned you wanted to use the Unix mail program.

Is your information static? If yes, how bout this.
cmd = "mail -s 'my subject' user at domain.com <user at domain.com> <
/path/to/static_message"
os.system(cmd)

Similar approach could be to capture the users message body as command line
arguments, save them to a file, and then include them in the execution. Not
very sexy, but it will work.


example
##############
~>/tmp/mail_wrapper.py  this is the body of my message
['this', 'is', 'the', 'body', 'of', 'my', 'message']


#!/usr/bin/env python
import sys
message = sys.argv[1:]

# save message variable to a file
# execute mail command < file




On 4/16/07, Tom Tucker < tktucker at gmail.com> wrote:
>
> Have you tried the "email" module?
>
> http://docs.python.org/lib/module-email.html
>
>
>
> On 4/16/07, Kharbush, Alex [ITCSV] <alexf4 at iastate.edu> wrote:
>
> >
> > I want to use the UNIX Mail program with python
> >
> > I need multiple entries with the os.system(cmd)line
> >
> > I will need something like this
> >
> > #output to unix
> >
> > Mail Alexf4 at iastate.edu -f alexf4 at gmail.com
> > Subject : hello alex
> >
> > #message part
> > how is it going
> >
> > #the end of mail
> > .
> >
> > When I write os.system("Mail Alexf4 at gmail.com") my program will send
> > email to where i want it to go
> >
> > MY PROBLEM is that i need to enter multiple lines of input into unix.
> > os.system() takes only one argument
> >
> > thanks for the time
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070416/840b884b/attachment.htm 

From bgailer at alum.rpi.edu  Tue Apr 17 00:31:05 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 16 Apr 2007 15:31:05 -0700
Subject: [Tutor] [OT] ETL Tools
In-Reply-To: <b6131fdc0703300027l408f941dj7f32e745e1192aa2@mail.gmail.com>
References: <b6131fdc0703300027l408f941dj7f32e745e1192aa2@mail.gmail.com>
Message-ID: <4623F929.7080808@alum.rpi.edu>

I responded on 3/30, but did not hear back from you, so I thought I'd 
try again:

Stephen Nelson-Smith wrote:
> Hello all,
>
> Does anyone know of any ETL (Extraction, Transformation, Loading)
> tools in Python (or at any rate, !Java)?
>   
I have under development a Python tool that is based on IBM's CMS
Pipelines. I think it would be suitable for ETL. It would help me to see
a sample of the raw data and a more detailed description of "process,
aggregate, group-by". Perhaps your application is the nudge I need to
bring this tool to life.

Let me know what you think of this positive, neutral, negative. I'm 
trying to gather momentum and interest. Your response will help.

-- 
Bob Gailer
510-978-4454



From Namratha.Pavar at coair.com  Tue Apr 17 00:48:28 2007
From: Namratha.Pavar at coair.com (Pavar, Namratha)
Date: Mon, 16 Apr 2007 17:48:28 -0500
Subject: [Tutor] Help with pysvn
Message-ID: <CF40FDD838BC56459FE1C29AADFA95EA02B71185@nhqsexc22.nam.coair.com>

Hi,

 

I am getting the error "pysvn._pysvn.ClientError: callback_get_login
required" when I try to do a simple exercise using pysvn. I have made
sure the subversion config file doesn't have the "store-auth-creds = no"
.

I would appreciate any help. 

 

Following is the code and error message. 

 

>>> import pysvn

>>> client = pysvn.Client()

>>>
client.checkout('http://arcsource.nam.coair.com/arc/svn/devref/trunk/mak
o/',

'D:\cpy')

Traceback (most recent call last):

  File "<stdin>", line 1, in ?

pysvn._pysvn.ClientError: callback_get_login required

 

Thanks,

 

Nam

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070416/f99a1a2c/attachment.htm 

From kent37 at tds.net  Mon Apr 16 15:27:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 16 Apr 2007 09:27:43 -0400
Subject: [Tutor] Beautiful Soup update
Message-ID: <462379CF.1010200@tds.net>

There was a thread here a few months ago about problems with running the 
unit tests for Beautiful Soup under Python 2.5. These  problems have 
apparently been fixed with a new release of Beautiful Soup.
http://www.crummy.com/software/BeautifulSoup/

Kent

From mwalsh at groktech.org  Tue Apr 17 04:23:55 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Mon, 16 Apr 2007 21:23:55 -0500
Subject: [Tutor] Help with pysvn
In-Reply-To: <CF40FDD838BC56459FE1C29AADFA95EA02B71185@nhqsexc22.nam.coair.com>
References: <CF40FDD838BC56459FE1C29AADFA95EA02B71185@nhqsexc22.nam.coair.com>
Message-ID: <46242FBB.5060206@groktech.org>

Hi Nam,

Pavar, Namratha wrote:
> Hi,
> 
>  
> 
> I am getting the error "pysvn._pysvn.ClientError: callback_get_login
> required" when I try to do a simple exercise using pysvn. I have made
> sure the subversion config file doesn't have the "store-auth-creds = no"
> .
> 
> I would appreciate any help. 
> 
> Following is the code and error message. 
> 
>>>> import pysvn
> 
>>>> client = pysvn.Client()
> 
> client.checkout('http://arcsource.nam.coair.com/arc/svn/devref/trunk/mak
> o/',
> 
> 'D:\cpy')
> 
> Traceback (most recent call last):
> 
>   File "<stdin>", line 1, in ?
> 
> pysvn._pysvn.ClientError: callback_get_login required
> 
>  

In this case, the truth is in the traceback.

Here is the relevant part of the pysvn documentation:
http://pysvn.tigris.org/docs/pysvn_prog_ref.html#pysvn_client_callback_get_login

pysvn.Client seems to require that you declare a callback function to
provide login credentials when needed to access a repository/project, if
not previously cached (or if caching is disabled). A simple example
providing a callback function might look like this:

def login(*args):
    return True, 'myuser', 'mypass', False

import pysvn
client = pysvn.Client()
client.callback_get_login = login
client.checkout('http://subversion.example.com/someproject/trunk')

But, the above might not be acceptable -- depending on security
concerns, as your repository password is presented in plain text.

HTH,
Marty

> Thanks,
> 
>  
> 
> Nam
> 

From python at uni-code.com  Tue Apr 17 13:26:59 2007
From: python at uni-code.com (python at uni-code.com)
Date: Tue, 17 Apr 2007 07:26:59 -0400 (EDT)
Subject: [Tutor] sys.argv?
Message-ID: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>

I've been reading the python tutorial trying to get used to the style
tryna understand it.  So I come across this: "sys.argv[0]" in the tutorial
on python.org.  What is "sys.argv"?  How does it work? Can someone give me
a simple example on how to use it?

From python at uni-code.com  Tue Apr 17 13:42:50 2007
From: python at uni-code.com (python at uni-code.com)
Date: Tue, 17 Apr 2007 07:42:50 -0400 (EDT)
Subject: [Tutor] range() help
Message-ID: <2021.70.230.187.68.1176810170.squirrel@uni-code.com>

Alright I'm a bit confused when looking at how range works.  I'm reading
lesson 4.3 in the python tutorial. http://docs.python.org/tut/node6.html

I came across this:

>>> range(-10, -100, -30)
[-10, -40, -70]

How come it prints on -40 or -70.

Does -70 come from -70 -> -100?

This is really confusing me.

From necmettin.begiter at gmail.com  Tue Apr 17 13:55:30 2007
From: necmettin.begiter at gmail.com (Necmettin Begiter)
Date: Tue, 17 Apr 2007 14:55:30 +0300
Subject: [Tutor] range() help
In-Reply-To: <2021.70.230.187.68.1176810170.squirrel@uni-code.com>
References: <2021.70.230.187.68.1176810170.squirrel@uni-code.com>
Message-ID: <200704171455.30619.nbegiter@gmx.com.tr>

On Tuesday 17 April 2007 14:42:50 python at uni-code.com wrote:
> >>> range(-10, -100, -30)
>
> [-10, -40, -70]
>
> How come it prints on -40 or -70.
>
> Does -70 come from -70 -> -100?
>
from -10 to -100 (excluding -100)
-10-30 = -40
-40-30= -70

From lists at mostrom.pp.se  Tue Apr 17 13:52:43 2007
From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=)
Date: Tue, 17 Apr 2007 13:52:43 +0200
Subject: [Tutor] sys.argv?
In-Reply-To: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
Message-ID: <r02020000-207-1049-ppc-22390ACEDE8840589E83C4F744777F31@Infinitum.local>

Reply to python at uni-code.com 07-04-17 07:26:

>I've been reading the python tutorial trying to get used to the style
>tryna understand it.  So I come across this: "sys.argv[0]" in the tutorial
>on python.org.  What is "sys.argv"?  How does it work? Can someone give me
>a simple example on how to use it?

It's how you read the argument from the command line


Example, a simple script

import sys

for x in sys.argv:
     print "Argument: ", x

and then how you can us it

>python ex.py
Argument:  ex.py
>python ex.py hello
Argument:  ex.py
Argument:  hello
>python ex.py hello world
Argument:  ex.py
Argument:  hello
Argument:  world
>

From lists at mostrom.pp.se  Tue Apr 17 13:57:18 2007
From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=)
Date: Tue, 17 Apr 2007 13:57:18 +0200
Subject: [Tutor] range() help
In-Reply-To: <2021.70.230.187.68.1176810170.squirrel@uni-code.com>
Message-ID: <r02020000-207-1049-ppc-1560A53D1E574290ADDB30C865DE1152@Infinitum.local>

Reply to python at uni-code.com 07-04-17 07:42:

>How come it prints on -40 or -70.
>
>Does -70 come from -70 -> -100?
>
>This is really confusing me.

I don't really understand your question, the definition of range

range(...)
     range([start,] stop[, step]) -> list of integers

     Return a list containing an arithmetic progression of integers.
     range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) 
defaults to 0.
     When step is given, it specifies the increment (or decrement).
     For example, range(4) returns [0, 1, 2, 3].  The end point 
is omitted!
     These are exactly the valid indices for a list of 4 elements.

So you are basically telling python to start from -10, and then 
subtract -30 until it reaches -100.

From rikard.bosnjakovic at gmail.com  Tue Apr 17 14:41:28 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 17 Apr 2007 14:41:28 +0200
Subject: [Tutor] sys.argv?
In-Reply-To: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
Message-ID: <d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>

On 4/17/07, python at uni-code.com <python at uni-code.com> wrote:

> I've been reading the python tutorial trying to get used to the style
> tryna understand it.  So I come across this: "sys.argv[0]" in the tutorial
> on python.org.  What is "sys.argv"?  How does it work? Can someone give me
> a simple example on how to use it?

sys.argv is a list containing all the arguments sent to the program at
invokation. The name "argv" is derived from the C-world; argument
values.


-- 
- Rikard - http://bos.hack.org/cv/

From detroit371 at gmail.com  Tue Apr 17 16:09:05 2007
From: detroit371 at gmail.com (Lawrence Shafer)
Date: Tue, 17 Apr 2007 09:09:05 -0500
Subject: [Tutor] Trouble with "RuntimeError: underlying C/C++ object has
	been deleted".
Message-ID: <4624D501.2050005@gmail.com>

Hello List,

I am just learning Python/PyQt4, and have a problem I cannot figure out.
Here's what happens.

Traceback (most recent call last):
   File "iac.py", line 124, in on_actionOpen_triggered
     self.open()
   File "iac.py", line 66, in open
     if self.isUntitled and self.textBrowser.document().isEmpty() and not
self.isWindowModified():
RuntimeError: underlying C/C++ object has been deleted


I have copied several parts of other programs, so that's probably where
this is coming from. All I want is to load a .txt file into
self.textBrowser, so some of the functionality is unneeded at this time,
except for filter saving and loading. If someone understands what is
going on, that would be great!

Files are attached.

Thanks!
Lawrence

-------------- next part --------------
A non-text attachment was scrubbed...
Name: iac.py
Type: application/x-python
Size: 8981 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070417/bde73457/attachment-0003.bin 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: filterEdit_ui.py
Type: application/x-python
Size: 6953 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070417/bde73457/attachment-0004.bin 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: iac_ui.py
Type: application/x-python
Size: 14040 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070417/bde73457/attachment-0005.bin 

From akap at isd.dp.ua  Tue Apr 17 16:31:09 2007
From: akap at isd.dp.ua (Alexander Kapshuk)
Date: Tue, 17 Apr 2007 17:31:09 +0300
Subject: [Tutor] 'word jumble' game
Message-ID: <70831DC71E5D814C9D1FA8A96653215E08ECC0C2@server.isd.dp.ua>

Hello Everyone,

 

This is Alexander Kapshuk writing here again ...

 

Could you please have a look at the code below and let me know of any
shortcuts that could be used there.

 

The code works fine as it is. I was just wandering if there was a
better, more compact and elegant way of writing the program.

 

Thanking you all in advance.

 

Alexander Kapshuk

 

 

# Word Jumble Game

#

# The computer picks a random word and then "jumbles" it.

# The player has to guess the original word.

#

# Should the player be stuck and require a hint, they will be prompted
for a hint.

# If the player answers 'yes', the appropriate hint will be displayed
and the player will be asked to guess again.

# If the player answers 'no', they will be asked to guess again and
awarded some points if they manage to guess the jumbled word without
ever asking for a hint.

 

import random

 

# create a sequence of words to choose from

WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")

 

# pick one word randomly from the sequence

word = random.choice(WORDS)

 

# create a variable to use later to see if the guess is correct

correct = word

 

# create hints for all the jumbled words

hint0 = "\nIt's the best programming language for the absolute beginner
...\n"

hint1 = "\nIt's what this program does to words to make it difficult to
guess them ...\n"

hint2 = "\nIt's not difficult ...\n"

hint3 = "\nIt's not easy ...\n"

hint4 = "\nIt's not a question ...\n"

hint5 = "\nIt's a musical instrument you have to hit with 2 small sticks
...\n"

 

# create a jumbled version of the word

jumble = ""

 

while word:

    position = random.randrange(len(word))

    jumble += word[position]

    word = word[:position] + word[(position + 1):]

 

# start the game

print \

"""

            Welcome to Word Jumple!

 

    Unscramble the letters to make a word.

    (Press the enter key at the prompt to quit.)

"""

print "The jumble:", jumble

 

guess = raw_input("\nYour guess: ")

guess = guess.lower()

score = 0

while (guess != correct) and (guess != ""):

    print "\nSorry, that's not it.\n"

    hint_prompt = raw_input("Would you like a hint? Y/N: ")

    hint_prompt = hint_prompt.lower()

    if hint_prompt == "yes" and correct == WORDS[0]:

        print hint0

    elif hint_prompt == "yes" and correct == WORDS[1]:

        print hint1

    elif hint_prompt == "yes" and correct == WORDS[2]:

        print hint2

    elif hint_prompt == "yes" and correct == WORDS[3]:

        print hint3

    elif hint_prompt == "yes" and correct == WORDS[4]:

        print hint4

    elif hint_prompt == "yes" and correct == WORDS[5]:

        print hint5

    elif hint_prompt == "no":

        score += 50

    

    guess = raw_input("Your guess: ")

    guess = guess.lower()

 

    if guess == correct and hint_prompt == "no":

        print "\nThat's it! You guessed it!\n"

        print "Because you never asked for a hint you get", score,
"points.\n"

 

print "\nThanks for playing."

 

raw_input("\n\nPress the enter key to exit.")

    

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070417/9ef35d15/attachment.html 

From govindgoyal at gmail.com  Tue Apr 17 17:28:35 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Tue, 17 Apr 2007 20:58:35 +0530
Subject: [Tutor] Error in my code
Message-ID: <f96f96bc0704170828g7daadec5x7e85bc12d1d17633@mail.gmail.com>

Hi,

I am executing following lines of code:

def WEP40_KEY(n):
  params = urllib.urlencode({})
  headers = {"Connection": "Keep-Alive","Authorization": ""}
  conn = httplib.HTTPConnection(HOST)
  conn.request("GET", "/w_sec.htm HTTP/1.1", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
 params = urllib.urlencode({'wsecurity':"WEP",'wep_auth':"Shared+Key",'wepenc':"128+bit",'wep_key_no':"key1",'ascii_key1':"12345678901234567890123456",'ascii_key2':"",'ascii_key3':"",'ascii_key4':"",'passphrase':"",'wpa_psk':"12345678",'key_lifetime':"65535",'wpa_enc':"TKIP",'save':"Save",'message':
"",'todo':""})
    headers = {"Connection": "Keep-Alive","Authorization": ""}
    conn = httplib.HTTPConnection(HOST)
    conn.request("POST", "w_sec.htm", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
    conn.close()

WEP40_KEY(sys.argv)



I am getting following error:


C:\Documents and Settings\Govindadya\Desktop\Marvell>Marvell_WEP40.py
192.168.1.
16
  File "C:\Documents and
Settings\Govindadya\Desktop\Marvell\Marvell_WEP40.py",
line 41
   * response = conn.getresponse()
                                ^
IndentationError: unindent does not match any outer indentation level*

**

Can anybody help me out on this?

Best Regards,

Govind
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070417/3c5cb378/attachment.htm 

From jason.massey at gmail.com  Tue Apr 17 18:23:12 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Tue, 17 Apr 2007 11:23:12 -0500
Subject: [Tutor] 'word jumble' game
In-Reply-To: <70831DC71E5D814C9D1FA8A96653215E08ECC0C2@server.isd.dp.ua>
References: <70831DC71E5D814C9D1FA8A96653215E08ECC0C2@server.isd.dp.ua>
Message-ID: <7e3eab2c0704170923n5f6f9aaexf4b2a425ee8d6825@mail.gmail.com>

The main thing your program lacks is flexibility.  Adding new puzzles
requires chaining together a series of if..else statements and creating
variables for each hint.

Here's my quick version.  I store the puzzles and the hints in a two-tuple
sequence.  Following this method you could easily add additional hints for
each puzzle.

 (I changed up the scoring system a bit too...just my spin on it)

import random

# create a series of puzzles to choose from
puzzles = (("python","It's the best programming language for the absolute
beginner ..."),
           ("jumble","It's what this program does to words to make it
difficult to guess them ..."),
           ("easy","It's not difficult ..."),
           ("difficult","It's not easy ..."),
           ("answer","It's not a question ..."),
           ("xylophone","It's a musical instrument you have to hit with 2
small sticks ..."))


# pick one word randomly from the sequence
which_puzzle = random.choice(range(len(puzzles)))
correct_word = puzzles[which_puzzle][0]
jumbled_word = list(correct_word)
hint = puzzles[which_puzzle][1]

random.shuffle(jumbled_word)
jumbled_word = ''.join(jumbled_word)

print \
"""
            Welcome to Word Jumple!

    Unscramble the letters to make a word.
    (Press the enter key at the prompt to quit.)
"""


score = 0
while 1:
    print "The jumble:", jumbled_word
    guess = raw_input("\nYour guess: ")
    guess = guess.lower()

    if guess == '':
            break

    if guess != correct_word:
        print "Sorry that's not it."
        hint_prompt = raw_input("Would you like a hint? Y/N: ")
        hint_prompt = hint_prompt.lower()
        if hint_prompt.startswith('y'):
            print hint+"\n"
            score -= 50

    if guess == correct_word:
        score += 200
        print "\nThat's it! You guessed it!\n"
        if score == 200:
            print "Because you never asked for a hint you get %d points.\n"
% (score)
        else:
            print "Since you asked for a hint or two you're score is %d
points.\n" % (score)
        break


print "\nThanks for playing."


On 4/17/07, Alexander Kapshuk <akap at isd.dp.ua> wrote:
>
>  Hello Everyone,
>
>
>
> This is Alexander Kapshuk writing here again ?
>
>
>
> Could you please have a look at the code below and let me know of any
> shortcuts that could be used there.
>
>
>
> The code works fine as it is. I was just wandering if there was a better,
> more compact and elegant way of writing the program.
>
>
>
> Thanking you all in advance.
>
>
>
> Alexander Kapshuk
>
>
>
>
>
> # Word Jumble Game
>
> #
>
> # The computer picks a random word and then "jumbles" it.
>
> # The player has to guess the original word.
>
> #
>
> # Should the player be stuck and require a hint, they will be prompted for
> a hint.
>
> # If the player answers 'yes', the appropriate hint will be displayed and
> the player will be asked to guess again.
>
> # If the player answers 'no', they will be asked to guess again and
> awarded some points if they manage to guess the jumbled word without ever
> asking for a hint.
>
>
>
> import random
>
>
>
> # create a sequence of words to choose from
>
> WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
>
>
>
> # pick one word randomly from the sequence
>
> word = random.choice(WORDS)
>
>
>
> # create a variable to use later to see if the guess is correct
>
> correct = word
>
>
>
> # create hints for all the jumbled words
>
> hint0 = "\nIt's the best programming language for the absolute beginner
> ...\n"
>
> hint1 = "\nIt's what this program does to words to make it difficult to
> guess them ...\n"
>
> hint2 = "\nIt's not difficult ...\n"
>
> hint3 = "\nIt's not easy ...\n"
>
> hint4 = "\nIt's not a question ...\n"
>
> hint5 = "\nIt's a musical instrument you have to hit with 2 small sticks
> ...\n"
>
>
>
> # create a jumbled version of the word
>
> jumble = ""
>
>
>
> while word:
>
>     position = random.randrange(len(word))
>
>     jumble += word[position]
>
>     word = word[:position] + word[(position + 1):]
>
>
>
> # start the game
>
> print \
>
> """
>
>             Welcome to Word Jumple!
>
>
>
>     Unscramble the letters to make a word.
>
>     (Press the enter key at the prompt to quit.)
>
> """
>
> print "The jumble:", jumble
>
>
>
> guess = raw_input("\nYour guess: ")
>
> guess = guess.lower()
>
> score = 0
>
> while (guess != correct) and (guess != ""):
>
>     print "\nSorry, that's not it.\n"
>
>     hint_prompt = raw_input("Would you like a hint? Y/N: ")
>
>     hint_prompt = hint_prompt.lower()
>
>     if hint_prompt == "yes" and correct == WORDS[0]:
>
>         print hint0
>
>     elif hint_prompt == "yes" and correct == WORDS[1]:
>
>         print hint1
>
>     elif hint_prompt == "yes" and correct == WORDS[2]:
>
>         print hint2
>
>     elif hint_prompt == "yes" and correct == WORDS[3]:
>
>         print hint3
>
>     elif hint_prompt == "yes" and correct == WORDS[4]:
>
>         print hint4
>
>     elif hint_prompt == "yes" and correct == WORDS[5]:
>
>         print hint5
>
>     elif hint_prompt == "no":
>
>         score += 50
>
>
>
>     guess = raw_input("Your guess: ")
>
>     guess = guess.lower()
>
>
>
>     if guess == correct and hint_prompt == "no":
>
>         print "\nThat's it! You guessed it!\n"
>
>         print "Because you never asked for a hint you get", score,
> "points.\n"
>
>
>
> print "\nThanks for playing."
>
>
>
> raw_input("\n\nPress the enter key to exit.")
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070417/01f91eb2/attachment.html 

From Mike.Hansen at atmel.com  Tue Apr 17 18:43:06 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Tue, 17 Apr 2007 10:43:06 -0600
Subject: [Tutor] Error in my code
In-Reply-To: <f96f96bc0704170828g7daadec5x7e85bc12d1d17633@mail.gmail.com>
References: <f96f96bc0704170828g7daadec5x7e85bc12d1d17633@mail.gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E74F9D3@poccso.US.ad.atmel.com>

If what you posted is exactly what your code looks like, then you've got
an indentation problem. Since Python doesn't use {}'s for code blocks,
it uses indentation instead, and it's somewhat picky about indentation.

I think all the code after the first conn.request should line up with
the conn.request.

def WEP40_KEY(n):
  params = urllib.urlencode({})
  headers = {"Connection": "Keep-Alive","Authorization": ""}
  conn = httplib.HTTPConnection(HOST)
  conn.request ("GET", "/w_sec.htm HTTP/1.1", params, headers)
  response = conn.getresponse()
  print response.status, response.reason
  params =
urllib.urlencode({'wsecurity':"WEP",'wep_auth':"Shared+Key",'wepenc':"12
8+bit",'wep_key_no':"key1",'ascii_key1':"12345678901234567890123456",'as
cii_key2':"",'ascii_key3':"",'ascii_key4':"",'passphrase':"",'wpa_psk':"
12345678",'key_lifetime':"65535",'wpa_enc':"TKIP",'save':"Save",'message
': "",'todo':""}) 
  headers = {"Connection": "Keep-Alive","Authorization": ""}
  conn = httplib.HTTPConnection(HOST)
  conn.request("POST", "w_sec.htm", params, headers) 
  response = conn.getresponse()
  print response.status, response.reason
  conn.close() 

It looks like your indenting 2 spaces. I believe the recommendation is 4
spaces. You might read the style guide.

http://www.python.org/doc/essays/styleguide.html

Out of curiosity, what editor are you using to write your code? You can
configure many editors to automatically indent for you, change tabs to
spaces, and set tabs to 4 spaces.

Mike

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of govind goyal
> Sent: Tuesday, April 17, 2007 9:29 AM
> To: tutor at python.org
> Subject: [Tutor] Error in my code
> 
> Hi,
>  
> I am executing following lines of code:
>  
> def WEP40_KEY(n):
>   params = urllib.urlencode({})
>   headers = {"Connection": "Keep-Alive","Authorization": ""}
>   conn = httplib.HTTPConnection(HOST)
>   conn.request ("GET", "/w_sec.htm HTTP/1.1", params, headers)
>     response = conn.getresponse()
>     print response.status, response.reason
>  params = 
> urllib.urlencode({'wsecurity':"WEP",'wep_auth':"Shared+Key",'w
> epenc':"128+bit",'wep_key_no':"key1",'ascii_key1':"12345678901
234567890123456",'ascii_key2':"",'ascii_key3':"",'ascii_key4':"",'passph
rase':"",'wpa_psk':"1234567>
8",'key_lifetime':"65535",'wpa_enc':"TKIP",'save':"Save",'mess
> age': "",'todo':""}) 
>     headers = {"Connection": "Keep-Alive","Authorization": ""}
>     conn = httplib.HTTPConnection(HOST)
>     conn.request("POST", "w_sec.htm", params, headers) 
>     response = conn.getresponse()
>     print response.status, response.reason
>     conn.close()
>     
> WEP40_KEY(sys.argv)
>  
>  
>  
> I am getting following error:
>  
> 
> C:\Documents and 
> Settings\Govindadya\Desktop\Marvell>Marvell_WEP40.py 192.168.1.
> 16
>   File "C:\Documents and 
> Settings\Govindadya\Desktop\Marvell\Marvell_WEP40.py",
> line 41
>     response = conn.getresponse()
>                                 ^
> IndentationError: unindent does not match any outer indentation level
> 
>  
> 
> Can anybody help me out on this?
> 
> Best Regards,
> 
> Govind
> 
>  
> 
> 

From rikard.bosnjakovic at gmail.com  Tue Apr 17 20:46:30 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 17 Apr 2007 20:46:30 +0200
Subject: [Tutor] sys.argv?
In-Reply-To: <462507E9.5030605@verizon.net>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
Message-ID: <d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>

On 4/17/07, Kirk Bailey <deliberatus at verizon.net> wrote:

> IF my memory serves well, argument 0 in that list is the name of the
> program itself, as well as the path to it if any was provided.

Stop replying to my mailbox.


-- 
- Rikard - http://bos.hack.org/cv/

From mac at nkoni.org  Tue Apr 17 21:59:45 2007
From: mac at nkoni.org (Giulio 'Mac' Maistrelli)
Date: Tue, 17 Apr 2007 21:59:45 +0200
Subject: [Tutor] Learning Python in cooperative, challenging way.
Message-ID: <46252731.4040302@nkoni.org>

Hello everybody,

	I hope this is the right place to make this question. If not I would appreciate
help in getting pointed towards a different resource...

	I just began to learn python. It is a nice language to learn, and I am using
"dive into python" which is also a nicely written book... yet I am missing a lot
two aspects in this learning experience:

1) The co-operation / interaction with other learners (and/or teachers).
2) The challenge

To clarify point #2: Python - as any learning - IS challenging, but as I am
learning it "just for fun" and without any real need to fulfil, I don't have any
"operational challenge", if that makes any sense in English... :-/

So far the best I could find has been: #1 --> this mailing list #2 -->
http://www.pythonchallenge.com

Any more suggestions from your side?

Thank you very much in advance,
Mac.

From rabidpoobear at gmail.com  Tue Apr 17 22:44:24 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 17 Apr 2007 15:44:24 -0500
Subject: [Tutor] sys.argv?
In-Reply-To: <d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
Message-ID: <462531A8.8030808@gmail.com>

Rikard Bosnjakovic wrote:
> On 4/17/07, Kirk Bailey <deliberatus at verizon.net> wrote:
>
>   
>> IF my memory serves well, argument 0 in that list is the name of the
>> program itself, as well as the path to it if any was provided.
>>     
>
> Stop replying to my mailbox.
>   
I really wish this list would start mungin' some headers already.


From python at uni-code.com  Tue Apr 17 23:03:05 2007
From: python at uni-code.com (python at uni-code.com)
Date: Tue, 17 Apr 2007 17:03:05 -0400 (EDT)
Subject: [Tutor] Python Browser based?
Message-ID: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>

How can I used python online.  I'm getting my hoster to install python and
I'm wondering how Do I use python online?

From bgailer at alum.rpi.edu  Tue Apr 17 23:12:22 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 17 Apr 2007 14:12:22 -0700
Subject: [Tutor] Python Browser based?
In-Reply-To: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
References: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
Message-ID: <46253836.4090809@alum.rpi.edu>

python at uni-code.com wrote:
> How can I used python online.  I'm getting my hoster to install python and
> I'm wondering how Do I use python online?
>   
Could you be more specific?

-- 
Bob Gailer
510-978-4454


From tms43 at clearwire.net  Tue Apr 17 23:21:30 2007
From: tms43 at clearwire.net (Teresa Stanton)
Date: Tue, 17 Apr 2007 14:21:30 -0700
Subject: [Tutor] Python Browser based?
In-Reply-To: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
References: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
Message-ID: <003901c78136$5f545d50$2dbbe942@samiam>

I would like more information about this as well.  I found something on
sourceforge about using python modules to run a web cam.  I've got the
files, but not quite sure how to use the web server.

 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of python at uni-code.com
Sent: Tuesday, April 17, 2007 2:03 PM
To: tutor at python.org
Subject: [Tutor] Python Browser based?

How can I used python online.  I'm getting my hoster to install python and
I'm wondering how Do I use python online?
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor



From bgailer at alum.rpi.edu  Tue Apr 17 23:41:12 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 17 Apr 2007 14:41:12 -0700
Subject: [Tutor] Python for CGI (was Python Browser based?)
In-Reply-To: <003901c78136$5f545d50$2dbbe942@samiam>
References: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
	<003901c78136$5f545d50$2dbbe942@samiam>
Message-ID: <46253EF8.6070506@alum.rpi.edu>

Regarding using Python for CGI - Googling "python cgi" reveals many 
potentially useful links. These sound

http://www.cs.virginia.edu/~lab2q/
www.python.org/doc/essays/ppt/sd99east/sld038.htm

-- 
Bob Gailer
510-978-4454


From Mike.Hansen at atmel.com  Tue Apr 17 23:52:43 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Tue, 17 Apr 2007 15:52:43 -0600
Subject: [Tutor] Learning Python in cooperative, challenging way.
In-Reply-To: <46252731.4040302@nkoni.org>
References: <46252731.4040302@nkoni.org>
Message-ID: <57B026980605A64F9B23484C5659E32E74FA2F@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> 
> To clarify point #2: Python - as any learning - IS 
> challenging, but as I am
> learning it "just for fun" and without any real need to 
> fulfil, I don't have any
> "operational challenge", if that makes any sense in English... :-/
> 
> So far the best I could find has been: #1 --> this mailing list #2 -->
> http://www.pythonchallenge.com
> 
> Any more suggestions from your side?
> 
> Thank you very much in advance,
> Mac.

You look at some of the ideas at this page.

http://effbot.org/pyfaq/tutor-im-learning-python-what-should-i-program.h
tm

or http://tinyurl.com/yalvar

Mike

From ellenkidda at gmail.com  Wed Apr 18 02:57:10 2007
From: ellenkidda at gmail.com (Ellen Kidda)
Date: Tue, 17 Apr 2007 20:57:10 -0400
Subject: [Tutor] Empty Range for RandRange
Message-ID: <5716ca260704171757n6fd7d265mace2e375397416cd@mail.gmail.com>

Would someone kindly review the following code and error?  This sample
program is copied from Python Programming for the Absolute Beginner (2nd
ed.)  I'm running Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC v.1200 32
bit (Intel)] on win32.  (Python 2.3 is the version referenced in this
edition.)  Referenced lines 8 and 9 of the error are the 3rd and 2nd lines
from the last in the code.  Thank you very much.
Ellen

#Demonstrates string indexing

import  random

word = "index"

print "The word is: ", word, "\n"

high = len(word)

low = len(word)

for i in range(10):

    position = randrange(low, high)

    print "word[", position, "]\t", word[position]

raw_input("\n\nPress the enter key to exit.")


line 8, in -toplevel-position = random.randrange(low, high)  #line 9 error:
"empty range for randrange"
  File "C:\Python23\lib\random.py", line 178, in randrange
    raise ValueError, "empty range for randrange()"
ValueError: empty range for randrange()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070417/541c55f0/attachment.html 

From kent37 at tds.net  Wed Apr 18 03:09:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 17 Apr 2007 21:09:28 -0400
Subject: [Tutor] Empty Range for RandRange
In-Reply-To: <5716ca260704171757n6fd7d265mace2e375397416cd@mail.gmail.com>
References: <5716ca260704171757n6fd7d265mace2e375397416cd@mail.gmail.com>
Message-ID: <46256FC8.2020104@tds.net>

Ellen Kidda wrote:
> Would someone kindly review the following code and error?  This sample 
> program is copied from Python Programming for the Absolute Beginner (2nd 
> ed.)  I'm running Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC v.1200 
> 32 bit (Intel)] on win32.  (Python 2.3 is the version referenced in this 
> edition.)  Referenced lines 8 and 9 of the error are the 3rd and 2nd 
> lines from the last in the code.  Thank you very much.
> Ellen
> 
> #Demonstrates string indexing
> 
> import  random
> 
> word = "index"
> 
> print "The word is: ", word, "\n"
> 
> high = len(word) 
> 
> low = len(word)  

Notice that low and high are the same.
> 
> for i in range(10):
> 
>     position = randrange(low, high)

This picks from the range low <= number < high. Since low == high the 
range is empty.

Kent

> 
>     print "word[", position, "]\t", word[position]
> 
> raw_input("\n\nPress the enter key to exit.")
> 
> 
> 
> line 8, in -toplevel-position = random.randrange(low, high)  #line 9 
> error:  "empty range for randrange"
>   File "C:\Python23\lib\random.py", line 178, in randrange
>     raise ValueError, "empty range for randrange()"
> ValueError: empty range for randrange()
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From hugonz-lists at h-lab.net  Wed Apr 18 06:16:07 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Tue, 17 Apr 2007 23:16:07 -0500
Subject: [Tutor] Python Browser based?
In-Reply-To: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
References: <2988.70.230.187.68.1176843785.squirrel@uni-code.com>
Message-ID: <46259B87.3030006@h-lab.net>

Hi,

Do you want to:

1) use Python from a website or server without installing it in a computer?

2) use Python to do things with the Internet or servers, website, etc?

Hugo

python at uni-code.com wrote:
> How can I used python online.  I'm getting my hoster to install python and
> I'm wondering how Do I use python online?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tuto

From python at uni-code.com  Wed Apr 18 06:34:01 2007
From: python at uni-code.com (python at uni-code.com)
Date: Wed, 18 Apr 2007 00:34:01 -0400 (EDT)
Subject: [Tutor] celcius to farenheit converter.
Message-ID: <2687.70.230.187.68.1176870841.squirrel@uni-code.com>

I found this site and I'm practicing coding and I write this script, but
I'm unsure why its not working.  Everything goes well until it gets to the
part where it tries to calculate the formula.  Inputs work fine anyone
know what I did wrong?

###################################
#Temperature Converter
#Coding Practice for lamonte(uni-code.com)
###################################

temp = raw_input("Insert a temperature to convert.\n")

type = raw_input("Now choose a convertion: Celcius(c) or Farenheit(f)")

if type == "c":
	cel = (5/9)*(temp-32)
	print "Farhrenheit" +temp+" is equal to "+cel+" celcius.\n"
elif type == "f":
	far = (9/5)*(temp+32)
	print "Farhrenheit" +far+" is equal to "+temp+" celcius.\n"
else:
	print "Unknown Syntax!\n";

raw_input("\nPress enter to close program")

From rikard.bosnjakovic at gmail.com  Wed Apr 18 06:41:44 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 18 Apr 2007 06:41:44 +0200
Subject: [Tutor] sys.argv?
In-Reply-To: <462531A8.8030808@gmail.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
	<462531A8.8030808@gmail.com>
Message-ID: <d9e88eaf0704172141u6fdaeab8scece64adf7830ed0@mail.gmail.com>

On 4/17/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:

> I really wish this list would start mungin' some headers already.

I second that.

Not using a reply-to-tag is braindead.


-- 
- Rikard - http://bos.hack.org/cv/

From rikard.bosnjakovic at gmail.com  Wed Apr 18 06:49:22 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 18 Apr 2007 06:49:22 +0200
Subject: [Tutor] celcius to farenheit converter.
In-Reply-To: <2687.70.230.187.68.1176870841.squirrel@uni-code.com>
References: <2687.70.230.187.68.1176870841.squirrel@uni-code.com>
Message-ID: <d9e88eaf0704172149g6b92f281sf431ac4025bd0462@mail.gmail.com>

On 4/18/07, python at uni-code.com <python at uni-code.com> wrote:

> I found this site and I'm practicing coding and I write this script, but
> I'm unsure why its not working.  Everything goes well until it gets to the
> part where it tries to calculate the formula.  Inputs work fine anyone
> know what I did wrong?

In the future, please add what error message you get. That saves us
some type cutting and pasting the code, and running it.

The thing that's wrong with your code is that you try to multiply an
integer with a string. raw_input() returns a string, not an integer.
What you want to do is to convert it to an int first:

temp = raw_input("Insert a temperature to convert.\n")
temp_int = int(temp)

Also, print cannot mix ints and strings using string concatenation
(+). What you want to do is to use string formats.

So, the final code would be something like this:

temp = raw_input("Insert a temperature to convert.\n")
temp_int = int(temp)

type = raw_input("Now choose a convertion: Celcius(c) or Farenheit(f)")

if type == "c":
       cel = (5/9)*(temp_int-32)
       print "Farhrenheit %d is equal to %d celcius.\n" % (temp_int, cel)
elif type == "f":
       far = (9/5)*(temp+32)
       print "Farhrenheit %d is equal to %d celcius.\n" % (temp_int, far)
else:
       print "Unknown Syntax!\n";

raw_input("\nPress enter to close program")



-- 
- Rikard - http://bos.hack.org/cv/

From rabidpoobear at gmail.com  Wed Apr 18 07:07:39 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 18 Apr 2007 00:07:39 -0500
Subject: [Tutor] celcius to farenheit converter.
In-Reply-To: <d9e88eaf0704172149g6b92f281sf431ac4025bd0462@mail.gmail.com>
References: <2687.70.230.187.68.1176870841.squirrel@uni-code.com>
	<d9e88eaf0704172149g6b92f281sf431ac4025bd0462@mail.gmail.com>
Message-ID: <4625A79B.6080601@gmail.com>

Rikard Bosnjakovic wrote:
> On 4/18/07, python at uni-code.com <python at uni-code.com> wrote:
>
>   
>> I found this site and I'm practicing coding and I write this script, but
>> I'm unsure why its not working.  Everything goes well until it gets to the
>> part where it tries to calculate the formula.  Inputs work fine anyone
>> know what I did wrong?
>>     
>
> if type == "c":
>        cel = (5/9)*(temp_int-32)
>   
a side-note:
5/9 is 0 in Python 2.5 and earlier.
'/' defaults to integer division if both sides are integers as well.
What you'd want to do is 5.0/9  or 5/9.0 or 5.0/9.0 or just 0.555555555
same applies to your 9/5 below.
>        print "Farhrenheit %d is equal to %d celcius.\n" % (temp_int, cel)
> elif type == "f":
>        far = (9/5)*(temp+32)


From listsdl04 at yahoo.de  Wed Apr 18 12:35:53 2007
From: listsdl04 at yahoo.de (Guba)
Date: Wed, 18 Apr 2007 18:35:53 +0800
Subject: [Tutor] raw_input into range() function
Message-ID: <4625F489.8000603@yahoo.de>

Hello,

I am trying to do the exercises in Michael Dawson's "Absolute Beginner"
book. In chapter four ("for Loops, Strings, and Tuples") one of the
challenges is: "Write a program that counts for the user. Let the user
enter the starting number, the ending number, and the amount by which to
count."

The code I have come up with so far is further below; basically my
problem is that I don't know how to feed the range() function with the
user-input numbers it expects.

Your help is highly appreciated!

Guba


# Counting Program
# 2007-04-18

# Welcoming the player
print "Hello, let me do some counting for you!"

# Telling the player what to do & assigning that info to variables.
start_num = int(raw_input("Please give me a starting number. "))
end_num = int(raw_input("Please give me an ending number. "))
interval = int(raw_input("By which amount am I to count? "))

start_num == 0
end_num == 1
interval == 2

print "Counting:"
for i in range(0, 1, 2):
     print i


raw_input("\n\nHit Enter to exit.")





	
		
___________________________________________________________ 
Der fr?he Vogel f?ngt den Wurm. Hier gelangen Sie zum neuen Yahoo! Mail: http://mail.yahoo.de

From shiv_mbm at hotmail.com  Wed Apr 18 12:06:40 2007
From: shiv_mbm at hotmail.com (shiv k)
Date: Wed, 18 Apr 2007 10:06:40 +0000
Subject: [Tutor] which function replaced fork() in Python2.5?
Message-ID: <BAY121-F26CAB95346DCBAD65833FBF6500@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070418/6b81dae1/attachment.htm 

From kent37 at tds.net  Wed Apr 18 13:00:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 07:00:57 -0400
Subject: [Tutor] raw_input into range() function
In-Reply-To: <4625F489.8000603@yahoo.de>
References: <4625F489.8000603@yahoo.de>
Message-ID: <4625FA69.2010001@tds.net>

Guba wrote:

> The code I have come up with so far is further below; basically my
> problem is that I don't know how to feed the range() function with the
> user-input numbers it expects.

> # Telling the player what to do & assigning that info to variables.
> start_num = int(raw_input("Please give me a starting number. "))
> end_num = int(raw_input("Please give me an ending number. "))
> interval = int(raw_input("By which amount am I to count? "))
> 
> start_num == 0
> end_num == 1
> interval == 2
> 
> print "Counting:"
> for i in range(0, 1, 2):
>     print i

Just use the variable names instead of the numbers:
   for i in range(start_num, end_num, interval):

Kent

From kent37 at tds.net  Wed Apr 18 13:04:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 07:04:58 -0400
Subject: [Tutor] which function replaced fork() in Python2.5?
In-Reply-To: <BAY121-F26CAB95346DCBAD65833FBF6500@phx.gbl>
References: <BAY121-F26CAB95346DCBAD65833FBF6500@phx.gbl>
Message-ID: <4625FB5A.8040208@tds.net>

shiv k wrote:
> 
> 
> which function replaced fork() in Python2.5?

os.fork() hasn't moved, why do you think it was replaced?

Kent

From kent37 at tds.net  Wed Apr 18 13:05:36 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 07:05:36 -0400
Subject: [Tutor] sys.argv?
In-Reply-To: <d9e88eaf0704172141u6fdaeab8scece64adf7830ed0@mail.gmail.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>	<462507E9.5030605@verizon.net>	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>	<462531A8.8030808@gmail.com>
	<d9e88eaf0704172141u6fdaeab8scece64adf7830ed0@mail.gmail.com>
Message-ID: <4625FB80.4090807@tds.net>

Rikard Bosnjakovic wrote:
> On 4/17/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> 
>> I really wish this list would start mungin' some headers already.
> 
> I second that.
> 
> Not using a reply-to-tag is braindead.

Please don't start this thread again.

Kent

From rikard.bosnjakovic at gmail.com  Wed Apr 18 13:42:54 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 18 Apr 2007 13:42:54 +0200
Subject: [Tutor] sys.argv?
In-Reply-To: <4625FB80.4090807@tds.net>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
	<462531A8.8030808@gmail.com>
	<d9e88eaf0704172141u6fdaeab8scece64adf7830ed0@mail.gmail.com>
	<4625FB80.4090807@tds.net>
Message-ID: <d9e88eaf0704180442r2cf2bad6p9eba622d221acef8@mail.gmail.com>

On 4/18/07, Kent Johnson <kent37 at tds.net> wrote:

> Please don't start this thread again.

We didn't start it, rather it just never ends.


-- 
- Rikard - http://bos.hack.org/cv/

From singletoned at gmail.com  Wed Apr 18 13:55:35 2007
From: singletoned at gmail.com (Ed Singleton)
Date: Wed, 18 Apr 2007 12:55:35 +0100
Subject: [Tutor] Mixing generator expressions with list definitions
Message-ID: <34bb7f5b0704180455i4d4ef1d9n48ce64474313472f@mail.gmail.com>

I would like to be able to do something along the lines of:

>>> my_list = [1, 2, x for x in range(3,6), 6]

However this doesn't work.  Is there any way of achieving this kind of thing?

I tried:

>>> my_list = [1, 2, *(x for x in range(3,6)), 6]

which also doesn't work.

I wrote a quick function that allows me to use the generator
expression as long as it is the last argument:

>>> def listify(*args):
...     return [arg for arg in args]
...
>>> my_list = listify(1,2, *(x for x in range(3,6)))

but obviously this limits me to using it only at the end of a list.

Any clues on this greatly appreciated.

Thanks

Ed

From kent37 at tds.net  Wed Apr 18 14:17:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 08:17:34 -0400
Subject: [Tutor] Mixing generator expressions with list definitions
In-Reply-To: <34bb7f5b0704180455i4d4ef1d9n48ce64474313472f@mail.gmail.com>
References: <34bb7f5b0704180455i4d4ef1d9n48ce64474313472f@mail.gmail.com>
Message-ID: <46260C5E.2020105@tds.net>

Ed Singleton wrote:
> I would like to be able to do something along the lines of:
> 
>>>> my_list = [1, 2, x for x in range(3,6), 6]
> 
> However this doesn't work.  Is there any way of achieving this kind of thing?

my_list = [1, 2] + range(3,6) + [6]

or, to build it in steps,
my_list = [1, 2]
my_list.extent(range(3, 6))
my_list.append(6)

By the way I can't think of any reason to write "x for x in range(3, 6)" 
instead of just "range(3, 6)". range() returns a list which can be used 
almost anywhere the generator expression can be. If you need an explicit 
iterator use iter(range(3, 6)).

> I wrote a quick function that allows me to use the generator
> expression as long as it is the last argument:
> 
>>>> def listify(*args):
> ...     return [arg for arg in args]

or
   return list(args)

Kent
> ...
>>>> my_list = listify(1,2, *(x for x in range(3,6)))
> 
> but obviously this limits me to using it only at the end of a list.
> 
> Any clues on this greatly appreciated.
> 
> Thanks
> 
> Ed
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From kent37 at tds.net  Wed Apr 18 14:18:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 08:18:45 -0400
Subject: [Tutor] Mixing generator expressions with list definitions
In-Reply-To: <46260C5E.2020105@tds.net>
References: <34bb7f5b0704180455i4d4ef1d9n48ce64474313472f@mail.gmail.com>
	<46260C5E.2020105@tds.net>
Message-ID: <46260CA5.8080104@tds.net>

Kent Johnson wrote:

> my_list.extent(range(3, 6))

should be
   my_list.extend(range(3, 6))

Kent

From abdulhafid at gmail.com  Wed Apr 18 14:30:18 2007
From: abdulhafid at gmail.com (Abu Ismail)
Date: Wed, 18 Apr 2007 13:30:18 +0100
Subject: [Tutor] Questions of Maths
Message-ID: <787e86df0704180530m6132666bl1b368f6cad85eb5e@mail.gmail.com>

Hi,

I am working on an implementation of an L-system in Python. I hate
using turtle module since it uses Tk and as my IDE also uses Tk I have
to close my editor before I can test the program. So I am implementing
the graphics using PIL.

Now to the problem.

Say you have a line AB with co-ords (x1,y1) and (x2,y2). Say you also
have a point C with co-ords (x3,y3).

Question: how to determine whether point C is to the left or to the
right of the line AB?

Any suggestions would be welcome.

Ta,
AH

From singletoned at gmail.com  Wed Apr 18 14:43:03 2007
From: singletoned at gmail.com (Ed Singleton)
Date: Wed, 18 Apr 2007 13:43:03 +0100
Subject: [Tutor] Mixing generator expressions with list definitions
In-Reply-To: <46260C5E.2020105@tds.net>
References: <34bb7f5b0704180455i4d4ef1d9n48ce64474313472f@mail.gmail.com>
	<46260C5E.2020105@tds.net>
Message-ID: <34bb7f5b0704180543t434195a6lb7dc730bcf61af45@mail.gmail.com>

On 4/18/07, Kent Johnson <kent37 at tds.net> wrote:
> Ed Singleton wrote:
> > I would like to be able to do something along the lines of:
> >
> >>>> my_list = [1, 2, x for x in range(3,6), 6]
> >
> > However this doesn't work.  Is there any way of achieving this kind of thing?
>
> my_list = [1, 2] + range(3,6) + [6]

I thought I'd got past the point where there were stupidly simple
answers to my questions ;)  Oh well.  Thanks yet again, Kent.

> or, to build it in steps,
> my_list = [1, 2]
> my_list.extent(range(3, 6))
> my_list.append(6)

Yeah, that's how I had ben doing it.  I don't really like it for some
reason, though I'm not clear why I don't like it.  I think maybe
because it's quite verbose so it's a bit difficult for me to read it
afterwards, and makes typos more likely ;)

> By the way I can't think of any reason to write "x for x in range(3, 6)"
> instead of just "range(3, 6)". range() returns a list which can be used
> almost anywhere the generator expression can be. If you need an explicit
> iterator use iter(range(3, 6)).

Sorry, I oversimplfied my example.  I'm actually doing:

widgets = [(organisation_widget,(),{'organisation':organisation})]
widgets.extend([(event_widget,(),{'event':event}) for event in
organisation.events])
widgets.append((event_form,(),{'values':values}))

so that later on I can just iterate through the widgets like so:

for (widget, args, kwargs) in widgets:
    widget.display(*args, **kwargs)

Ed

From andre.roberge at gmail.com  Wed Apr 18 14:51:55 2007
From: andre.roberge at gmail.com (Andre Roberge)
Date: Wed, 18 Apr 2007 09:51:55 -0300
Subject: [Tutor] Questions of Maths
In-Reply-To: <787e86df0704180530m6132666bl1b368f6cad85eb5e@mail.gmail.com>
References: <787e86df0704180530m6132666bl1b368f6cad85eb5e@mail.gmail.com>
Message-ID: <7528bcdd0704180551u119ee618je9e01eda456a0ed0@mail.gmail.com>

On 4/18/07, Abu Ismail <abdulhafid at gmail.com> wrote:
> Hi,
>
> I am working on an implementation of an L-system in Python. I hate
> using turtle module since it uses Tk and as my IDE also uses Tk I have
> to close my editor before I can test the program. So I am implementing
> the graphics using PIL.
>
> Now to the problem.
>
> Say you have a line AB with co-ords (x1,y1) and (x2,y2). Say you also
> have a point C with co-ords (x3,y3).
>
> Question: how to determine whether point C is to the left or to the
> right of the line AB?
>
1. Write an equation for the line AB in the form x = Wy + Z  (as
opposed to y = mx + b, which is the usual form).
2. Substitute the value for y3 in that equation - it will give you the
value of x on that line (call it X3).
3. Compare x3 with X3.

A quick derivation gave me (please verify)
x = [(x2-x1) y + x1 y2 - x2 y1]/(y2-y1)
where the multiplication signs are implicit.

Good luck!

Andr?

> Any suggestions would be welcome.
>
> Ta,
> AH
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From deliberatus at verizon.net  Wed Apr 18 15:00:39 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 18 Apr 2007 10:00:39 -0300
Subject: [Tutor] sys.argv?
In-Reply-To: <d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
Message-ID: <46261677.7020208@verizon.net>

I never talk to mailboxes, nor to other inanimate objects; I was talking 
to you.

Rikard Bosnjakovic wrote:
> On 4/17/07, Kirk Bailey <deliberatus at verizon.net> wrote:
> 
>> IF my memory serves well, argument 0 in that list is the name of the
>> program itself, as well as the path to it if any was provided.
> 
> Stop replying to my mailbox.
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From deliberatus at verizon.net  Wed Apr 18 15:01:56 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 18 Apr 2007 10:01:56 -0300
Subject: [Tutor] sys.argv?
In-Reply-To: <462531A8.8030808@gmail.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
	<462531A8.8030808@gmail.com>
Message-ID: <462616C4.1030708@verizon.net>

use a replyto header, or swap around things so the FROM is the list 
address, not the submitter, or kill me, or give me food, or something.

Luke Paireepinart wrote:
> Rikard Bosnjakovic wrote:
>> On 4/17/07, Kirk Bailey <deliberatus at verizon.net> wrote:
>>
>>   
>>> IF my memory serves well, argument 0 in that list is the name of the
>>> program itself, as well as the path to it if any was provided.
>>>     
>> Stop replying to my mailbox.
>>   
> I really wish this list would start mungin' some headers already.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rikard.bosnjakovic at gmail.com  Wed Apr 18 16:05:30 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 18 Apr 2007 16:05:30 +0200
Subject: [Tutor] sys.argv?
In-Reply-To: <46261677.7020208@verizon.net>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
	<46261677.7020208@verizon.net>
Message-ID: <d9e88eaf0704180705y3682dc9ej990e49415656c7e8@mail.gmail.com>

On 4/18/07, Kirk Bailey <deliberatus at verizon.net> wrote:

> I never talk to mailboxes, nor to other inanimate objects; I was talking
> to you.

I'm not interested in listening to your ifs about your memory.

-- 
- Rikard - http://bos.hack.org/cv/

From kent37 at tds.net  Wed Apr 18 17:01:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 11:01:48 -0400
Subject: [Tutor] which function replaced fork() in Python2.5?
In-Reply-To: <BAY121-F16A427CF21C638DB79A46FF6500@phx.gbl>
References: <BAY121-F16A427CF21C638DB79A46FF6500@phx.gbl>
Message-ID: <462632DC.6030300@tds.net>

shiv k wrote:
> 
> 
> 
> MR Kent its there in ubuntu but if we see the same in windows xp there 
> is no fork() instead there are spawn family.

fork() is not supported under Windows.

Kent

From deliberatus at verizon.net  Wed Apr 18 16:32:18 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 18 Apr 2007 11:32:18 -0300
Subject: [Tutor] sys.argv?
In-Reply-To: <d9e88eaf0704180705y3682dc9ej990e49415656c7e8@mail.gmail.com>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
	<46261677.7020208@verizon.net>
	<d9e88eaf0704180705y3682dc9ej990e49415656c7e8@mail.gmail.com>
Message-ID: <46262BF2.7040408@verizon.net>

My memory is fine, as is my grip on reality as well as courtesy to my 
fellow pythonistas.

Good day to you sir.

Rikard Bosnjakovic wrote:
> On 4/18/07, Kirk Bailey <deliberatus at verizon.net> wrote:
> 
>> I never talk to mailboxes, nor to other inanimate objects; I was talking
>> to you.
> 
> I'm not interested in listening to your ifs about your memory.
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From deliberatus at verizon.net  Wed Apr 18 16:34:09 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 18 Apr 2007 11:34:09 -0300
Subject: [Tutor] sys.argv?
In-Reply-To: <4625FB80.4090807@tds.net>
References: <1389.70.230.187.68.1176809219.squirrel@uni-code.com>
	<d9e88eaf0704170541h48177f99r53b6062ed16ac562@mail.gmail.com>
	<462507E9.5030605@verizon.net>
	<d9e88eaf0704171146h84bb6fbp3fc5831181e2a469@mail.gmail.com>
	<462531A8.8030808@gmail.com>
	<d9e88eaf0704172141u6fdaeab8scece64adf7830ed0@mail.gmail.com>
	<4625FB80.4090807@tds.net>
Message-ID: <46262C61.8020603@verizon.net>

As long as the PROBLEM lives, the THREAD will rise from the dead over 
and over. Kill the problem, you kill the thread.

Kent Johnson wrote:
> Rikard Bosnjakovic wrote:
>> On 4/17/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>>
>>> I really wish this list would start mungin' some headers already.
>> I second that.
>>
>> Not using a reply-to-tag is braindead.
> 
> Please don't start this thread again.
> 
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From jameshcunningham at uky.edu  Wed Apr 18 17:54:47 2007
From: jameshcunningham at uky.edu (James Cunningham)
Date: Wed, 18 Apr 2007 11:54:47 -0400
Subject: [Tutor] screen scraping web-based email
Message-ID: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>

Hello. I've been playing with Python for a while, and even have some
small scripts in my employ, but I have a bit of a problem and I'm not
sure how to proceed.

I'm starting graduate school (econ!) in the Fall; the school I'll be
attending uses Lotus for email and allows neither forwarding nor
POP/IMAP access. This is - for many, many reasons - *quite*
unacceptable to me.

I'd like to write a daemon that logs into the text-based web client
every so often, scrapes for new email, and uses smtplib to send that
email to another email address. But I really don't know how I'd go
about logging in and staying logged in without a browser.

Hints are appreciated. Am I wrong-headed about this? Any other options
available to me?

(I know I could do it with a torturous combination of applescript and
python ... but I'd like to avoid that, plus I'd like something
remotely portable.)

From kent37 at tds.net  Wed Apr 18 18:15:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 18 Apr 2007 12:15:26 -0400
Subject: [Tutor] screen scraping web-based email
In-Reply-To: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
References: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
Message-ID: <4626441E.4080002@tds.net>

James Cunningham wrote:

> I'd like to write a daemon that logs into the text-based web client
> every so often, scrapes for new email, and uses smtplib to send that
> email to another email address. But I really don't know how I'd go
> about logging in and staying logged in without a browser.
> 
> Hints are appreciated. Am I wrong-headed about this? Any other options
> available to me?

This might be a starting point:
http://pywebmail.sourceforge.net/

Otherwise mechanize and Beautiful Soup will give you some high-level 
tools to get started with:
http://wwwsearch.sourceforge.net/mechanize/
http://www.crummy.com/software/BeautifulSoup/

Kent

From jameshcunningham at uky.edu  Wed Apr 18 18:29:24 2007
From: jameshcunningham at uky.edu (James Cunningham)
Date: Wed, 18 Apr 2007 12:29:24 -0400
Subject: [Tutor] screen scraping web-based email
In-Reply-To: <4626441E.4080002@tds.net>
References: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
	<4626441E.4080002@tds.net>
Message-ID: <20070418122924050433.50b88bb3@uky.edu>

On Wed, 18 Apr 2007 12:15:26 -0400, Kent Johnson wrote:
> James Cunningham wrote:
> 
>> I'd like to write a daemon that logs into the text-based web client
>> every so often, scrapes for new email, and uses smtplib to send that
>> email to another email address. But I really don't know how I'd go
>> about logging in and staying logged in without a browser.
>> 
>> Hints are appreciated. Am I wrong-headed about this? Any other options
>> available to me?
> 
> This might be a starting point:
> http://pywebmail.sourceforge.net/
> 
> Otherwise mechanize and Beautiful Soup will give you some high-level 
> tools to get started with:
> http://wwwsearch.sourceforge.net/mechanize/
> http://www.crummy.com/software/BeautifulSoup/
> 
> Kent


pywebmail sounds great, and mechanize is actually just what I was 
looking for. Thanks a lot, especially for the quick response!

Best,
James

From bgailer at alum.rpi.edu  Wed Apr 18 20:19:31 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 18 Apr 2007 11:19:31 -0700
Subject: [Tutor] raw_input into range() function
In-Reply-To: <4625F489.8000603@yahoo.de>
References: <4625F489.8000603@yahoo.de>
Message-ID: <46266133.1020501@alum.rpi.edu>

Guba wrote:
> Hello,
>
> I am trying to do the exercises in Michael Dawson's "Absolute Beginner"
> book. In chapter four ("for Loops, Strings, and Tuples") one of the
> challenges is: "Write a program that counts for the user. Let the user
> enter the starting number, the ending number, and the amount by which to
> count."
>
> The code I have come up with so far is further below; basically my
> problem is that I don't know how to feed the range() function with the
> user-input numbers it expects.
>
> Your help is highly appreciated!
>
> Guba
>
>
> # Counting Program
> # 2007-04-18
>
> # Welcoming the player
> print "Hello, let me do some counting for you!"
>
> # Telling the player what to do & assigning that info to variables.
> start_num = int(raw_input("Please give me a starting number. "))
> end_num = int(raw_input("Please give me an ending number. "))
> interval = int(raw_input("By which amount am I to count? "))
So far so good, if the user enters integers for all 3 inputs. All you 
need now is:

print "Counting:"
for i in range(start_num, end_num, interval):
    print i
>
> start_num == 0
> end_num == 1
> interval == 2
These are expressions that compare a variable to a constant. They 
contribute nothing to the program.


-- 
Bob Gailer
510-978-4454


From bensherman at gmail.com  Wed Apr 18 20:25:02 2007
From: bensherman at gmail.com (Ben Sherman)
Date: Wed, 18 Apr 2007 14:25:02 -0400
Subject: [Tutor] raw_input into range() function
In-Reply-To: <4625F489.8000603@yahoo.de>
References: <4625F489.8000603@yahoo.de>
Message-ID: <5a56471e0704181125y4580077at6aab43b6ae6d30a8@mail.gmail.com>

On 4/18/07, Guba <listsdl04 at yahoo.de> wrote:
> Hello,
>
> I am trying to do the exercises in Michael Dawson's "Absolute Beginner"
> book. In chapter four ("for Loops, Strings, and Tuples") one of the
> challenges is: "Write a program that counts for the user. Let the user
> enter the starting number, the ending number, and the amount by which to
> count."
>
> The code I have come up with so far is further below; basically my
> problem is that I don't know how to feed the range() function with the
> user-input numbers it expects.
>
> Your help is highly appreciated!
>
> Guba
>
>
> # Counting Program
> # 2007-04-18
>
> # Welcoming the player
> print "Hello, let me do some counting for you!"
>
> # Telling the player what to do & assigning that info to variables.
> start_num = int(raw_input("Please give me a starting number. "))
> end_num = int(raw_input("Please give me an ending number. "))
> interval = int(raw_input("By which amount am I to count? "))
>
> start_num == 0
> end_num == 1
> interval == 2
>
> print "Counting:"
> for i in range(0, 1, 2):
>      print i
>
>
> raw_input("\n\nHit Enter to exit.")


Your attempt to read input is never used, and your variable
assignments are not correct.

You are using the test operator '==' instead of the assignment
operator '='.  The lines:
"""
start_num == 0
end_num == 1
interval == 2
"""
do something you aren't trying to do here.  Those lines are testing to
see if start_num equals zero, and then ignoring what the test result
is.  They don't actually *do* anything.

Your code should look like this:

print "Hello, let me do some counting for you!"

start_num = int(raw_input("Please give me a starting number. "))
end_num = int(raw_input("Please give me an ending number. "))
interval = int(raw_input("By which amount am I to count? "))

print "Counting:"
for i in range(start_num, end_num, interval):
    print i

From alan.gauld at btinternet.com  Wed Apr 18 21:16:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Apr 2007 20:16:14 +0100
Subject: [Tutor] which function replaced fork() in Python2.5?
References: <BAY121-F26CAB95346DCBAD65833FBF6500@phx.gbl>
Message-ID: <f05qqc$1i5$1@sea.gmane.org>


"shiv k" <shiv_mbm at hotmail.com> wrote 

> which function replaced fork() in Python2.5?
 
Try the subprocess module.
I think it can do a similar job even on Windows...

Alan G.


From alan.gauld at btinternet.com  Wed Apr 18 21:20:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Apr 2007 20:20:00 +0100
Subject: [Tutor] Questions of Maths
References: <787e86df0704180530m6132666bl1b368f6cad85eb5e@mail.gmail.com>
Message-ID: <f05r1f$2tq$1@sea.gmane.org>


"Abu Ismail" <abdulhafid at gmail.com> wrote

> I am working on an implementation of an L-system in Python. I hate
> using turtle module since it uses Tk and as my IDE also uses Tk I 
> have
> to close my editor before I can test the program.

Why so? Don''t you have a multi-tasking OS?
If so just run a command line window alongside your editor
and run the code in that!

> Say you have a line AB with co-ords (x1,y1) and (x2,y2). Say you 
> also
> have a point C with co-ords (x3,y3).
>
> Question: how to determine whether point C is to the left or to the
> right of the line AB?

Derive the equation of the line.
Use it to determine the y coordinate for x3
If y3 is greater than the calculated y then your point is above the 
line.

HTH,

Alan G. 



From alan.gauld at btinternet.com  Wed Apr 18 21:27:41 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Apr 2007 20:27:41 +0100
Subject: [Tutor] screen scraping web-based email
References: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
Message-ID: <f05rfr$5iu$1@sea.gmane.org>


"James Cunningham" <jameshcunningham at uky.edu> wrote

> I'd like to write a daemon that logs into the text-based web client
> every so often, scrapes for new email, and uses smtplib to send that
> email to another email address.

Kent has pointed you at useful add-on modules.
Using the standard library consider the urllib2 library
(way better than urllib) and I believe the email module
rather than the smtlib is the current preferred route.

But I'd still recommend Beautiful Soup for parsing the HTML
the HTMLParser module can be used but its less reliable
and more work.

PS. I'm currently writing a tutorial topic on this very subject
and I'm trying to use the standard libs for the first time (since
I want my tutor to be based on the standard library) and it's
proving to be a "learning opportunity"!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Wed Apr 18 21:29:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Apr 2007 20:29:40 +0100
Subject: [Tutor] Multiple lines with the command line
References: <C8A091151D3C0449BA9A31F3FAC94AFA0AC57B6B@exchs015.ats.iastate.edu>
Message-ID: <f05rji$68j$1@sea.gmane.org>


"Kharbush, Alex [ITCSV]" <alexf4 at iastate.edu> wrote

> I need multiple entries with the os.system(cmd)line

> MY PROBLEM is that i need to enter multiple lines of 
> input into unix. os.system() takes only one argument

How about uysing popen instead?
Or the new Popen class in the subprocess module...

Alan G.


From janos.juhasz at VELUX.com  Wed Apr 18 22:42:36 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 18 Apr 2007 22:42:36 +0200
Subject: [Tutor] Questions of Maths
In-Reply-To: <mailman.21575.1176904809.32030.tutor@python.org>
Message-ID: <OF8B7AB473.44F4727A-ONC12572C1.006948E0-C12572C1.0071C31A@velux.com>

Hi Abu,

> Question: how to determine whether point C is to the left or to the
> right of the line AB?

When the line given by A(Xa,Ya) and B(Xb, Yb),
the area of the A-B-C triangle can be calculated with the value of next 
determinant / 2

| Xa, Ya, 1 |
| Xb, Yb, 1 |
| Xc, Yc, 1 | / 2

So:

Area = ( Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb) ) / 2

Area > 0 | the points are clockwise (C is on the left)
Area < 0 | the points are counterclockwise (C is on the right)
Area = 0 | the points are on the same line 


It can be written in a python function

###########
def TriArea(a, b, c):
    #Area = (Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb)) /2
    return ( a[0] * (b[1]-c[1]) - b[0] * (a[1]-c[1]) + c[0] * (a[1]-b[1]) 
)/2

###########
# to test it.
print TriArea((0,0), (10,0), (2,2))
print TriArea((0,0), (10,0), (2,-2))
print TriArea((0,0), (10,0), (2,0))
###########


The biggest advantage of this calculation is that,
it never goes to zero division exception.



Best regards,
Janos

From amonroe at columbus.rr.com  Thu Apr 19 01:04:09 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed, 18 Apr 2007 19:04:09 -0400
Subject: [Tutor] screen scraping web-based email
In-Reply-To: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
References: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
Message-ID: <1741473532427.20070418190409@columbus.rr.com>


> I'm starting graduate school (econ!) in the Fall; the school I'll be
> attending uses Lotus for email

You can drive the fat client via COM if you install the Win32
extensions for python.

> (I know I could do it with a torturous combination of applescript and

Except judging by this, you're on a MAC... so maybe not. Still,
working WITH the app (using its APIs) is bound to better than working
AGAINST it (screen scraping).

Alan


From atpridgen at mail.utexas.edu  Thu Apr 19 02:31:26 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Wed, 18 Apr 2007 19:31:26 -0500
Subject: [Tutor] How to program to python the right way?
Message-ID: <f989e6210704181731i65efdb87o3368f8955489489b@mail.gmail.com>

Hello everyone,

I have pretty much finished hacking on my Thesis and I have come to
the conclusion,
I really do not know how to use Python to it "full" extent.  Some of
the things I have really messed up in my implementation are
serialization (specifically sub-classes), classes, and instantiating
them the "correct" way, and there are some things I have not tried,
but I would like to like contained execution and thread management.
Are there any books (with examples) out there that show some of these
techniques and explain the gotchas that come with the package.  Thanks
in advance.

Adam

From list at adamgomaa.com  Thu Apr 19 02:34:14 2007
From: list at adamgomaa.com (Adam Gomaa)
Date: Wed, 18 Apr 2007 20:34:14 -0400
Subject: [Tutor] Seeking python projects
In-Reply-To: <88dc53b0704141440h530a7d33w14a83229b4afeee7@mail.gmail.com>
References: <88dc53b0704141440h530a7d33w14a83229b4afeee7@mail.gmail.com>
Message-ID: <4626B906.70107@adamgomaa.com>

Writing your own programs is a good idea. However, this is primarily a
good idea with small programs. For example, when learning Python, I
wrote a set of backup scripts for my computer; I still use them and
they've served me well.

If you want to write 'complete applications,' you're probably better off
helping with a project that has already started. This is important for a
few reasons. First, you'll learn about Python packaging and
documentation standards, and possibly things like unit tests as well.
These are things that often escape new programmers, but are very
important for large-scale projects. Second, you'll be far more likely to
make a contribution this way. If you decide to implement your own
py(insert App Name here), you'll probably never get done. Scratch that,
you'll almost certainly never get done (I speak from experience). Find a
open-source Python project that needs someone (Sourceforge actually has
a 'job listings' page) and help them out instead. You'll learn a lot of
practical things and quickly become a better programmer, as opposed to
simply reimplementing the same mistakes over and over as I did :-)

Asrar Kadri wrote:
> Hi folks,
>  
> I want to practice Python programming by developing complete applications.
>  
> Where can I get such problems, which can improve my Python programming
> skills.
>  
> Thanks in anticipation.
>  
> Regards,
>  
> Asrar
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From andreas at kostyrka.org  Thu Apr 19 02:48:58 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 19 Apr 2007 02:48:58 +0200
Subject: [Tutor] which function replaced fork() in Python2.5?
In-Reply-To: <f05qqc$1i5$1@sea.gmane.org>
References: <BAY121-F26CAB95346DCBAD65833FBF6500@phx.gbl>
	<f05qqc$1i5$1@sea.gmane.org>
Message-ID: <20070419004858.GK26355@andi-lap.lan>

* Alan Gauld <alan.gauld at btinternet.com> [070418 21:28]:
> 
> "shiv k" <shiv_mbm at hotmail.com> wrote 
> 
> > which function replaced fork() in Python2.5?
Replaced?

>>> sys.version, os.fork
('2.5 (release25-maint, Dec  9 2006, 14:35:53) \n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)]', <built-in function fork>)

Andreas

From jakieabraham at yahoo.com  Thu Apr 19 08:07:32 2007
From: jakieabraham at yahoo.com (Jacob Abraham)
Date: Wed, 18 Apr 2007 23:07:32 -0700 (PDT)
Subject: [Tutor] Builtin "property" decorator hiding exceptions
Message-ID: <8368.47473.qm@web54110.mail.re2.yahoo.com>

Hi,

   The sample script below throws the exception "AttributeError: input" rather than the expected exception "AttributeError: non_existent_attribute".  

   Please help me write a decorator or descriptor of my own that fixes the issue.

class Sample(object):
    def __init__(self):
        self.arguments = {}

    def __getattr__(self, name):
        ret_val = self.arguments.get(name, None)
        if ret_val != None: return ret_val
        raise AttributeError, name
    
    @property
    def input(self):
        self.non_existent_attribute
    

sample = Sample()
sample.input


Regards,
Jacob Abraham



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From andreas at kostyrka.org  Thu Apr 19 08:26:57 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 19 Apr 2007 08:26:57 +0200
Subject: [Tutor] Builtin "property" decorator hiding exceptions
In-Reply-To: <8368.47473.qm@web54110.mail.re2.yahoo.com>
References: <8368.47473.qm@web54110.mail.re2.yahoo.com>
Message-ID: <20070419062657.GL26355@andi-lap.lan>

I know, this might sound stupid, but property is not a decorator. :)

Andreas

* Jacob Abraham <jakieabraham at yahoo.com> [070419 08:25]:
> Hi,
> 
>    The sample script below throws the exception "AttributeError: input" rather than the expected exception "AttributeError: non_existent_attribute".  
> 
>    Please help me write a decorator or descriptor of my own that fixes the issue.
> 
> class Sample(object):
>     def __init__(self):
>         self.arguments = {}
> 
>     def __getattr__(self, name):
>         ret_val = self.arguments.get(name, None)
>         if ret_val != None: return ret_val
>         raise AttributeError, name
>     
>     @property
>     def input(self):
>         self.non_existent_attribute
>     
> 
> sample = Sample()
> sample.input
> 
> 
> Regards,
> Jacob Abraham
> 
> 
> 
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Thu Apr 19 08:42:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 19 Apr 2007 07:42:34 +0100
Subject: [Tutor] screen scraping web-based email
References: <9a5576390704180854w6c26db7cs496c57ef824aaf39@mail.gmail.com>
	<1741473532427.20070418190409@columbus.rr.com>
Message-ID: <f07318$8dh$1@sea.gmane.org>


"R. Alan Monroe" <amonroe at columbus.rr.com> wrote

> You can drive the fat client via COM if you install the Win32
> extensions for python.
>
>> (I know I could do it with a torturous combination of applescript 
>> and
>
> Except judging by this, you're on a MAC... so maybe not. Still,
> working WITH the app (using its APIs) is bound to better than 
> working
> AGAINST it (screen scraping).

Good point Alan. The OP can use Python to drive applescript
in a similar way to Windows users driving COM. The MacPython
package includes functions to interface to applescript.

There are examples of doing this in the book MacOS Hacks
by O'Reilly (albeit from Perl, but the Python interface is, I believe,
very similar)

So that might be an alternative route.


Alan G




From andreas at kostyrka.org  Thu Apr 19 10:27:23 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 19 Apr 2007 10:27:23 +0200
Subject: [Tutor] Builtin "property" decorator hiding exceptions
In-Reply-To: <9680.89845.qm@web54109.mail.re2.yahoo.com>
References: <9680.89845.qm@web54109.mail.re2.yahoo.com>
Message-ID: <20070419082723.GM26355@andi-lap.lan>

* Jacob Abraham <jakieabraham at yahoo.com> [070419 10:08]:
> Hi Andreas Kostyrka,
> 
>    I am aware that property is a data descriptor. And I still don't see why if can't be uses as a decorator since decorators were created to fix the issue.
> 
> getx= property(getx)

Simple, they don't return function objects. Basically, function
objects (methods) do the __get__ protocol that property is doing to
make the self parameter binding.

decorators, if you expect them to work like normal methods do have
certain limits what they can return.

Ever wondered why practically all (well, I did it for a closed source
contract once differently) decorators are functions that return
interior nested functions, instead of returning callable object
instances? That's why.

Andreas

From nswitanek at stanford.edu  Thu Apr 19 10:42:03 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Thu, 19 Apr 2007 01:42:03 -0700
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
In-Reply-To: <mailman.21673.1176964988.32030.tutor@python.org>
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu>

Alan,

Please let us know when you have a draft of your tutorial on Beautiful
Soup and such. I'd be eager to have a look!

Thanks,
Nick

From kent37 at tds.net  Thu Apr 19 12:31:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 19 Apr 2007 06:31:58 -0400
Subject: [Tutor] Builtin "property" decorator hiding exceptions
In-Reply-To: <20070419082723.GM26355@andi-lap.lan>
References: <9680.89845.qm@web54109.mail.re2.yahoo.com>
	<20070419082723.GM26355@andi-lap.lan>
Message-ID: <4627451E.6090200@tds.net>

Andreas Kostyrka wrote:
> * Jacob Abraham <jakieabraham at yahoo.com> [070419 10:08]:
>> Hi Andreas Kostyrka,
>>
>>    I am aware that property is a data descriptor. And I still don't see why if can't be uses as a decorator since decorators were created to fix the issue.
>>
>> getx= property(getx)
> 
> Simple, they don't return function objects.

That is not a requirement, afaik. classmethod() and staticmethod() don't 
return function objects either and they are usable as decorators.

@property
def foo()...

is equivalent to
def foo()...
foo = property(foo)

which is the usual usage.

To argue from authority :-) Ian Bicking agrees with me:
http://blog.ianbicking.org/property-decorator.html

Kent

From kent37 at tds.net  Thu Apr 19 12:44:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 19 Apr 2007 06:44:56 -0400
Subject: [Tutor] Builtin "property" decorator hiding exceptions
In-Reply-To: <8368.47473.qm@web54110.mail.re2.yahoo.com>
References: <8368.47473.qm@web54110.mail.re2.yahoo.com>
Message-ID: <46274828.4030300@tds.net>

Jacob Abraham wrote:
> Hi,
> 
>    The sample script below throws the exception "AttributeError: input" rather than the expected exception "AttributeError: non_existent_attribute".  
> 
>    Please help me write a decorator or descriptor of my own that fixes the issue.
> 
> class Sample(object):
>     def __init__(self):
>         self.arguments = {}
> 
>     def __getattr__(self, name):
>         ret_val = self.arguments.get(name, None)
>         if ret_val != None: return ret_val
>         raise AttributeError, name
>     
>     @property
>     def input(self):
>         self.non_existent_attribute
>     
> 
> sample = Sample()
> sample.input

I don't fully understand what is going on here but it seems that it is 
your __getattr__() that is hiding the exception.

If I take out __getattr__(), I get
AttributeError: 'Sample' object has no attribute 'non_existent_attribute'

I think this is what is happening:
- the input attribute is fetched
- input is a descriptor so its __get__ method is called
- __get__ tries to find non_existent_attribute by the usual methods, 
which fail
- __get__ calls __getattr__ which raises AttributeError
- __get__ raises AttributeError

OK, so think about it - trying to access .input has raised an 
AttributeError, i.e. attribute access through the normal mechanism has 
failed.

Now __getattr__ is called for input and again AttributeError is raised; 
this is the error you see.

If you put some print statements into __getattr__ you can see this is 
the order of events.

This is not the behaviour you want but it does make a certain sense.

If you raise a different exception in __getattr__ it is propagated out.

Kent

From alan.gauld at btinternet.com  Thu Apr 19 12:01:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 19 Apr 2007 11:01:18 +0100
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
References: <mailman.21673.1176964988.32030.tutor@python.org>
	<21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu>
Message-ID: <f07elt$fak$1@sea.gmane.org>


"Switanek, Nick" <nswitanek at stanford.edu> wrote

> Please let us know when you have a draft of your tutorial on 
> Beautiful
> Soup and such. I'd be eager to have a look!

Here is the current draft, the concepts bits are all there  (nothing
on Beautiful Soup as yet) but the example is giving me some headaches
so it could change significantly over the next weeks. But early 
feedback
is always welcome!

The idea is to do the example using only the standard library
tools then repeat with BS to show how much easier it is.
But I'm hitting problems getting the standard tools to work!

Alan G. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070419/2389b0c6/attachment-0001.htm 

From abdulhafid at gmail.com  Thu Apr 19 13:05:07 2007
From: abdulhafid at gmail.com (Abu Ismail)
Date: Thu, 19 Apr 2007 12:05:07 +0100
Subject: [Tutor] Questions of Maths
In-Reply-To: <OF8B7AB473.44F4727A-ONC12572C1.006948E0-C12572C1.0071C31A@velux.com>
References: <mailman.21575.1176904809.32030.tutor@python.org>
	<OF8B7AB473.44F4727A-ONC12572C1.006948E0-C12572C1.0071C31A@velux.com>
Message-ID: <787e86df0704190405i4c44bd4fj6687e00bcc4999b1@mail.gmail.com>

Thank you very much guys, this has been most helpful.

At the moment I run the program as Alan suggests. However, the goal is
to incorporate the program into Glade2 GUI and I am not sure that it
will work with Tk, although I must admit I have not tried it out yet.

Abu Ismail

On 4/18/07, J?nos Juh?sz <janos.juhasz at velux.com> wrote:
> Hi Abu,
>
> > Question: how to determine whether point C is to the left or to the
> > right of the line AB?
>
> When the line given by A(Xa,Ya) and B(Xb, Yb),
> the area of the A-B-C triangle can be calculated with the value of next
> determinant / 2
>
> | Xa, Ya, 1 |
> | Xb, Yb, 1 |
> | Xc, Yc, 1 | / 2
>
> So:
>
> Area = ( Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb) ) / 2
>
> Area > 0 | the points are clockwise (C is on the left)
> Area < 0 | the points are counterclockwise (C is on the right)
> Area = 0 | the points are on the same line
>
>
> It can be written in a python function
>
> ###########
> def TriArea(a, b, c):
>     #Area = (Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb)) /2
>     return ( a[0] * (b[1]-c[1]) - b[0] * (a[1]-c[1]) + c[0] * (a[1]-b[1])
> )/2
>
> ###########
> # to test it.
> print TriArea((0,0), (10,0), (2,2))
> print TriArea((0,0), (10,0), (2,-2))
> print TriArea((0,0), (10,0), (2,0))
> ###########
>
>
> The biggest advantage of this calculation is that,
> it never goes to zero division exception.
>
>
>
> Best regards,
> Janos
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Thu Apr 19 13:32:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 19 Apr 2007 07:32:40 -0400
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
In-Reply-To: <f07elt$fak$1@sea.gmane.org>
References: <mailman.21673.1176964988.32030.tutor@python.org>	<21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu>
	<f07elt$fak$1@sea.gmane.org>
Message-ID: <46275358.6050301@tds.net>

Alan Gauld wrote:
> 
> "Switanek, Nick" <nswitanek at stanford.edu> wrote
> 
>> Please let us know when you have a draft of your tutorial on Beautiful
>> Soup and such. I'd be eager to have a look!
> 
> Here is the current draft, the concepts bits are all there  (nothing
> on Beautiful Soup as yet) but the example is giving me some headaches
> so it could change significantly over the next weeks. But early feedback
> is always welcome!

FWIW most real-world HTML parsers (including Beautiful Soup) seem to be 
based directly on SMTPlib, not htmllib or HTMLParser.

On a lawyerly note, I think your Google example violates Google's terms 
of service which prohibits any automated access.
http://www.google.com/accounts/TOS

Kent

From mail at timgolden.me.uk  Thu Apr 19 13:46:36 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 19 Apr 2007 12:46:36 +0100
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
In-Reply-To: <46275358.6050301@tds.net>
References: <mailman.21673.1176964988.32030.tutor@python.org>	<21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu>	<f07elt$fak$1@sea.gmane.org>
	<46275358.6050301@tds.net>
Message-ID: <4627569C.5050604@timgolden.me.uk>

Kent Johnson wrote:
> FWIW most real-world HTML parsers (including Beautiful Soup) seem to be 
> based directly on SMTPlib, not htmllib or HTMLParser.

I'm assuming you mean sgmllib here?

TJG

From kent37 at tds.net  Thu Apr 19 13:54:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 19 Apr 2007 07:54:07 -0400
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
In-Reply-To: <4627569C.5050604@timgolden.me.uk>
References: <mailman.21673.1176964988.32030.tutor@python.org>	<21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu>	<f07elt$fak$1@sea.gmane.org>
	<46275358.6050301@tds.net> <4627569C.5050604@timgolden.me.uk>
Message-ID: <4627585F.6050507@tds.net>

Tim Golden wrote:
> Kent Johnson wrote:
>> FWIW most real-world HTML parsers (including Beautiful Soup) seem to 
>> be based directly on SMTPlib, not htmllib or HTMLParser.
> 
> I'm assuming you mean sgmllib here?

:-) yes, I mean sgmllib.SGMLParser

Kent

From alan.gauld at btinternet.com  Thu Apr 19 16:07:30 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 19 Apr 2007 15:07:30 +0100
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
References: <mailman.21673.1176964988.32030.tutor@python.org>	<21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu><f07elt$fak$1@sea.gmane.org>
	<46275358.6050301@tds.net>
Message-ID: <f07t3h$7ei$1@sea.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote

> On a lawyerly note, I think your Google example violates Google's 
> terms
> of service which prohibits any automated access.
> http://www.google.com/accounts/TOS

Thanks for pointing that out Kent.

It probably explains why they send me a Restricted HTTP error.
I was going to try fooling them by messing with the http headers
but I'll find a friendlier web site... The reason for trying to use
Google was that they do offer an XML/RPC route in and I
was intending to go on to show how much easier a proper
API was.

Oh well, another bright idea bites the dust.

Alan G.

PS I didn't actually intend to send the draft to the group
but hit ReplyAll out of habit. It was only meant to go to
Nick... But in this case it's probably as well I did!




From alan.gauld at btinternet.com  Thu Apr 19 16:10:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 19 Apr 2007 15:10:35 +0100
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
References: <mailman.21673.1176964988.32030.tutor@python.org>	<21EB45BA6A0A4844B97D46A7721CFDF203649B74@gsb-exchmb02.stanford.edu><f07elt$fak$1@sea.gmane.org>
	<46275358.6050301@tds.net>
Message-ID: <f07t99$8bo$1@sea.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote in

> FWIW most real-world HTML parsers (including Beautiful Soup) seem to 
> be
> based directly on SMTPlib, not htmllib or HTMLParser.

Yes, I noticed that, although htmllib is itself based on sgmllib...
And it has a better event based parsing model but unfortunately
it doesn't throw errors when you get an http error back,
which makes HTMLParser much more user friendly for
beginners...

Alan G. 



From alan.gauld at btinternet.com  Thu Apr 19 16:17:50 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 19 Apr 2007 15:17:50 +0100
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
Message-ID: <f07tmt$aat$1@sea.gmane.org>


"Alan Gauld" <alan.gauld at btinternet.com> wrote

> it doesn't throw errors when you get an http error back,

Oops, confusing myself here.
Its urllib2 that throws errors and nothing to do with HTMLParser.
The advantage of HTMLParser is the lack of a need for a 
formatter and writer object.

Sorry for any confusion.

Alan G


From kent37 at tds.net  Thu Apr 19 16:40:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 19 Apr 2007 10:40:18 -0400
Subject: [Tutor] screen scraping web-based email (Alan Gauld)
In-Reply-To: <f07tmt$aat$1@sea.gmane.org>
References: <f07tmt$aat$1@sea.gmane.org>
Message-ID: <46277F52.5050407@tds.net>

Alan Gauld wrote:
> "Alan Gauld" <alan.gauld at btinternet.com> wrote
> 
>> it doesn't throw errors when you get an http error back,
> 
> Oops, confusing myself here.
> Its urllib2 that throws errors and nothing to do with HTMLParser.
> The advantage of HTMLParser is the lack of a need for a 
> formatter and writer object.

sgmllib doesn't need a formatter either, that is added by htmllib.

Kent

From jmh at physics.ucdavis.edu  Thu Apr 19 22:31:20 2007
From: jmh at physics.ucdavis.edu (Michael Hannon)
Date: Thu, 19 Apr 2007 13:31:20 -0700
Subject: [Tutor] Custom metaclass?
Message-ID: <4627D198.3090401@physics.ucdavis.edu>

Greetings.  I've been looking at O'Reilly's "Python Cookbook", 2nd 
edition, just for my own edification.  In particular, I'm looking at 
chapter 6, "Object-Oriented Programming".

Recipe 6.3, "Restricting Attribute Setting", intends to solve the 
problem that,  by default, users can add and modify attributes of class 
instances, or even classes themselves, as in the following example:

     >>> class Foo(object): pass
     ...
     >>> f = Foo()
     >>> f.age = 42
     >>> f.age
     42
     >>> Foo.loc = 'Tralfamadore'
     >>> g = Foo()
     >>> g.loc
     'Tralfamadore'

The approach, in essence, is a fairly standard one: redefine the 
__setattr__ method to add some logic to enforce whatever restrictions 
you choose, but the details are a bit convoluted.  Copyright law 
probably prohibits me from posting the entire recipe, but here's the 
piece that leads to my question (see below):

class NoNewAttrs(object):
     """ subclasses of NoNewAttrs inhibit addition of new attributes,
         while allowing existing attributed to be set to new values.
     """
     # block the addition new attributes to instances of this class
     __setattr__ = no_new_attributes(object.__setattr__)
     class __metaclass__(type):
         "simple custom metaclass to block adding new attrs to this class"
         __setattr__ = no_new_attributes(type.__setattr__)

(Beware line breaks introduced by email software.)

Finally, my question: can somebody enlighten me as to how and why the 
"custom metaclass",

     class __metaclass__(type):

does something useful?

Thanks.

					- Mike
-- 
Michael Hannon            mailto:hannon at physics.ucdavis.edu
Dept. of Physics          530.752.4966
University of California  530.752.4717 FAX
Davis, CA 95616-8677

From project5 at redrival.net  Fri Apr 20 08:41:22 2007
From: project5 at redrival.net (Andrei)
Date: Fri, 20 Apr 2007 06:41:22 +0000 (UTC)
Subject: [Tutor] Custom metaclass?
References: <4627D198.3090401@physics.ucdavis.edu>
Message-ID: <loom.20070420T081850-546@post.gmane.org>

Michael Hannon <jmh <at> physics.ucdavis.edu> writes:
<snip>
> The approach, in essence, is a fairly standard one: redefine the 
> __setattr__ method to add some logic to enforce whatever restrictions 
> you choose, but the details are a bit convoluted.  Copyright law 
> probably prohibits me from posting the entire recipe, but here's the 
<snip>

Well, here's a dummy that simply ignores requests to add attributes, instead
printing a message about the attempt to the console, so we have a concrete
example to look at:

def no_new_attributes(*args, **kwargs):
    print 'called ', args, kwargs
    return no_new_attributes

class NoNewAttrs(object):
    __setattr__ = no_new_attributes(object.__setattr__)
    class __metaclass__(type):
        __setattr__ = no_new_attributes(type.__setattr__)
    
nna = NoNewAttrs()
#NoNewAttrs.__setattr__ = object.__setattr__
nna.x = 5
try:
    print 'object nna.x =' + str(nna.x)
except:
    print 'object nna.x doesn\'t exist'

NoNewAttrs.x = 5
try:
    print 'class nna.x =', nna.x
except:
    print 'class nna.x doesn\'t exist'

> Finally, my question: can somebody enlighten me as to how and why the 
> "custom metaclass",
> 
>      class __metaclass__(type):
> 
> does something useful?

A metaclass is to a class like a class is to an object. The way a class
customizes the behavior of an object, a metaclass customizes the behavior of a
class. It's all a bit mind-bending and I don't think I'm an expert on the
subject, but let's see how far we get.

Try running the example above with the  __metaclass__ code and without: you'll
see that if you leave it out, you can still add attributes to the class itself
(even though not to the object), so your console will say:

  object nna.x doesn't exist
  class nna.x = 5

If however you put the metaclass in, you'll get:

  object nna.x doesn't exist
  called  (<class '__main__.NoNewAttrs'>, 'x', 5) {}
  class nna.x = class nna.x doesn't exist

Without the metaclass code, it would be trivial to work around the __setattr__
limitation. Just try uncommenting the line "NoNewAttrs.__setattr__ =
object.__setattr__". If you disabled the metaclass, you'll see that nna.x will
be set. If the metaclass is enabled, it will not be set.

This being Python, you can still work around all this metaclass safety by adding
using this code:

NoNewAttrs.__metaclass__.__setattr__ = type.__setattr__
NoNewAttrs.__setattr__ = object.__setattr__
nna.x = 5
print 'After reset: nna.x =', nna.x

Run this and you'll see it will have restored the attribute-setting
functionality even if it's theoretically blocked. I'm not sure there is a way to
absolutely completely stop users from adding attributes.


Yours,

Andrei


From Mike.Hansen at atmel.com  Fri Apr 20 22:16:02 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Fri, 20 Apr 2007 14:16:02 -0600
Subject: [Tutor] Question about cgi module
Message-ID: <57B026980605A64F9B23484C5659E32E74FC06@poccso.US.ad.atmel.com>

Part of the web app that I'm writing will allow users to upload small
images to be stored in a database. Is there a way to limit how big of a
file that the user can upload? Is there some cgi setting that would
prevent a user from upload a huge file, or stop at a certain size and
error? 

Mike

From andreas at kostyrka.org  Fri Apr 20 22:38:59 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 20 Apr 2007 22:38:59 +0200
Subject: [Tutor] Question about cgi module
In-Reply-To: <57B026980605A64F9B23484C5659E32E74FC06@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E74FC06@poccso.US.ad.atmel.com>
Message-ID: <20070420203859.GP4118@andi-lap>

* Mike Hansen <Mike.Hansen at atmel.com> [070420 22:32]:
> Part of the web app that I'm writing will allow users to upload small
> images to be stored in a database. Is there a way to limit how big of a
> file that the user can upload? Is there some cgi setting that would
> prevent a user from upload a huge file, or stop at a certain size and
> error?

Not really. Perhaps.

You need envision the situtation:

http wise, the client assembles its request, and starts to send it to
the server. the http server is allowed to drop a http connection
anytime, and because file uploads are POSTs, the client should not
resent it without manual intervention by the user.

cgi wise, you need to check how your http server handles it.

Furthermore, you've got the little problem, that the standard cgi
module probably won't support that directly.

After having taken a view on the technical side, let's look at it from
the users perspective:

a) the error comes after the file was uploaded. Not much you can do
against that (Well, if you manage to interpret a Content-Length
header, you might abort the upload earlier, in theory).

b) aborting the request gives no sensible feedback to the user.

The typical solution for that is to use AJAX:

1.) get an unique id for the upload.
2.) post the file to an url containing the unique id.
3.) check the status of the upload via an AJAX method to give sensible
status messages, including errors.

(you need the unique id so that the AJAX calls can retrieve the status)

Andreas

From python at uni-code.com  Fri Apr 20 01:59:04 2007
From: python at uni-code.com (python at uni-code.com)
Date: Thu, 19 Apr 2007 19:59:04 -0400 (EDT)
Subject: [Tutor] Python 2.4 or Python 2.5?
Message-ID: <4019.70.133.170.213.1177027144.squirrel@uni-code.com>

Im confused When i had python 2.4 all my scripts work correctly should i
reinstall python 2.4?  Or should I keep 2.5?  Where can I find information
on coding for python 2.5?

From rikard.bosnjakovic at gmail.com  Sat Apr 21 09:18:49 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sat, 21 Apr 2007 09:18:49 +0200
Subject: [Tutor] Python 2.4 or Python 2.5?
In-Reply-To: <4019.70.133.170.213.1177027144.squirrel@uni-code.com>
References: <4019.70.133.170.213.1177027144.squirrel@uni-code.com>
Message-ID: <d9e88eaf0704210018w26ef6fdka7e84124f0472b5e@mail.gmail.com>

On 4/20/07, python at uni-code.com <python at uni-code.com> wrote:

> Im confused When i had python 2.4 all my scripts work correctly should i
> reinstall python 2.4?  Or should I keep 2.5?  Where can I find information
> on coding for python 2.5?

Context?


-- 
- Rikard - http://bos.hack.org/cv/

From alan.gauld at btinternet.com  Sat Apr 21 09:32:38 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 21 Apr 2007 08:32:38 +0100
Subject: [Tutor] Python 2.4 or Python 2.5?
References: <4019.70.133.170.213.1177027144.squirrel@uni-code.com>
Message-ID: <f0cen6$spu$1@sea.gmane.org>

<python at uni-code.com> wrote

> Im confused When i had python 2.4 all my scripts work correctly 
> should i
> reinstall python 2.4?  Or should I keep 2.5?  Where can I find 
> information
> on coding for python 2.5?

Coding for 2.4 is not significantly different to coding for 2.4.
Your 2.4 scripts should all still work provided you have set
up the same environment. The most likely change is that
you had some configuration settings for 2.4 that have
changed or not been set in 2.5. (for example are your
PYTHONPATH and PATH settings still correct?)

However without any information about what the problem is
it is hard to make a recommendation.

Alan G. 



From kent37 at tds.net  Sat Apr 21 13:02:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 21 Apr 2007 07:02:44 -0400
Subject: [Tutor] Python 2.4 or Python 2.5?
In-Reply-To: <4019.70.133.170.213.1177027144.squirrel@uni-code.com>
References: <4019.70.133.170.213.1177027144.squirrel@uni-code.com>
Message-ID: <4629EF54.1070405@tds.net>

python at uni-code.com wrote:
> Im confused When i had python 2.4 all my scripts work correctly should i
> reinstall python 2.4?  Or should I keep 2.5?  Where can I find information
> on coding for python 2.5?

Each .x release of Python comes with a "What's New" document that 
details the changes since the previous release. For Python 2.5 you can 
read it here:
http://docs.python.org/whatsnew/whatsnew25.html

There are usually very few changes that are incompatible with old code. 
The biggest roadblock to updating is availability of third-party 
extensions. The API for C extensions is *not* compatible between dot 
releases so extension modules usually have to be re-released for a new 
Python release.

Python 2.5 has been out for a while now so most extension modules have 
been updated. But if there is something you depend on you should check 
its availability before upgrading.

You can also have two versions of Python on the same machine without any 
trouble.

You will have to re-install any add-on modules and packages you use.

Kent

From kent37 at tds.net  Sat Apr 21 13:06:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 21 Apr 2007 07:06:51 -0400
Subject: [Tutor] How to program to python the right way?
In-Reply-To: <f989e6210704181731i65efdb87o3368f8955489489b@mail.gmail.com>
References: <f989e6210704181731i65efdb87o3368f8955489489b@mail.gmail.com>
Message-ID: <4629F04B.80402@tds.net>

Adam Pridgen wrote:
> Hello everyone,
> 
> I have pretty much finished hacking on my Thesis and I have come to
> the conclusion,
> I really do not know how to use Python to it "full" extent.  Some of
> the things I have really messed up in my implementation are
> serialization (specifically sub-classes), classes, and instantiating
> them the "correct" way, and there are some things I have not tried,
> but I would like to like contained execution and thread management.
> Are there any books (with examples) out there that show some of these
> techniques and explain the gotchas that come with the package.  Thanks
> in advance.

I think the Python Cookbook is an excellent book for learning idiomatic 
Python.

Your question is pretty vague, can you ask a more specific question 
about an area where you are having trouble?

Kent

From pthanos at gmail.com  Sat Apr 21 15:39:26 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Sat, 21 Apr 2007 15:39:26 +0200
Subject: [Tutor] Exceptions while dealing with MySQL
Message-ID: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>

Hello list,

I am developing a network management system that relies heavily on a
MySQL database. The logic of the program is unavoidably coupled with
query results I get from various tables.

This is OK as long the mysql server has 100% uptime, but it hardly
does. Say that I have to make at least 20 different kinds of queries
here and there in different parts of my code(all together more than a
thousand queries). What is the best approach to make error checking
possible, with the least amount of code duplication?

Right now my code is probably ill-structured in terms of the database
backend. A MySQLdb.connection object is juggled around as an arguement
to my own program's objects, so that they can retrieve the info they
need from the database tables when needed. After a whole program
iteration has finished, the connection object is destroyed and a new
one is cerated for the next iteration.

This means that a 5-minute downtime of the SQL server will cause my
program to crash. It is really too much trouble checking for
exceptions every time I make a simple query. What approach should I
try take?

Thanks a lot. A better backend design will make my application much more robust.

Thanos

From kent37 at tds.net  Sat Apr 21 16:36:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 21 Apr 2007 10:36:02 -0400
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
Message-ID: <462A2152.101@tds.net>

Thanos Panousis wrote:
> Hello list,
> 
> I am developing a network management system that relies heavily on a
> MySQL database. The logic of the program is unavoidably coupled with
> query results I get from various tables.
> 
> This is OK as long the mysql server has 100% uptime, but it hardly
> does. Say that I have to make at least 20 different kinds of queries
> here and there in different parts of my code(all together more than a
> thousand queries). What is the best approach to make error checking
> possible, with the least amount of code duplication?
> 
> Right now my code is probably ill-structured in terms of the database
> backend. A MySQLdb.connection object is juggled around as an arguement
> to my own program's objects, so that they can retrieve the info they
> need from the database tables when needed. After a whole program
> iteration has finished, the connection object is destroyed and a new
> one is cerated for the next iteration.
> 
> This means that a 5-minute downtime of the SQL server will cause my
> program to crash. It is really too much trouble checking for
> exceptions every time I make a simple query. What approach should I
> try take?

What do you want to have happen when the server is down? Should the 
program wait and retry?

One possibility would be to wrap the database connection in a class 
which checks for exceptions and retries. If you are only doing queries 
(no updates) this might work OK. Or perhaps the wrapper could test for 
availability of the database before making a request.

Kent

From pthanos at gmail.com  Sat Apr 21 17:22:27 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Sat, 21 Apr 2007 17:22:27 +0200
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <462A2152.101@tds.net>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
	<462A2152.101@tds.net>
Message-ID: <4dcb3660704210822l4ebae9ao7647b2022ef8b8aa@mail.gmail.com>

Well, the best thing to do is to just keep on asking until the server
is up. Sending emails and other logging can be done inside whatever
wrapper function.

So if wrappers is a good way to go, how should I pursue this? Just
making my own wrapper functions or subclassing from MySQLdb?

Is it really possible that this is not a very common problem to which
others have already provided some kind of solution? Or is it just
rather easy to resolve so everyone just re-does it?

On 4/21/07, Kent Johnson <kent37 at tds.net> wrote:
> Thanos Panousis wrote:
> > Hello list,
> >
> > I am developing a network management system that relies heavily on a
> > MySQL database. The logic of the program is unavoidably coupled with
> > query results I get from various tables.
> >
> > This is OK as long the mysql server has 100% uptime, but it hardly
> > does. Say that I have to make at least 20 different kinds of queries
> > here and there in different parts of my code(all together more than a
> > thousand queries). What is the best approach to make error checking
> > possible, with the least amount of code duplication?
> >
> > Right now my code is probably ill-structured in terms of the database
> > backend. A MySQLdb.connection object is juggled around as an arguement
> > to my own program's objects, so that they can retrieve the info they
> > need from the database tables when needed. After a whole program
> > iteration has finished, the connection object is destroyed and a new
> > one is cerated for the next iteration.
> >
> > This means that a 5-minute downtime of the SQL server will cause my
> > program to crash. It is really too much trouble checking for
> > exceptions every time I make a simple query. What approach should I
> > try take?
>
> What do you want to have happen when the server is down? Should the
> program wait and retry?
>
> One possibility would be to wrap the database connection in a class
> which checks for exceptions and retries. If you are only doing queries
> (no updates) this might work OK. Or perhaps the wrapper could test for
> availability of the database before making a request.
>
> Kent
>

From danfan1981 at yahoo.com  Sat Apr 21 19:11:57 2007
From: danfan1981 at yahoo.com (FAN Ying Wai)
Date: Sat, 21 Apr 2007 10:11:57 -0700 (PDT)
Subject: [Tutor] No speedup in
Message-ID: <812226.14223.qm@web54302.mail.re2.yahoo.com>

Hi,
I am using Python Thread library for my parallel
processing course 
project. I am doing matrix convolution on a
multi-processor machine. I 
just found out that no speed-up is obtained with
threading. It is 
probably because of something called GIL in Python.
How can I get around 
that GIL and get speed-up?
Thanks in advance.
Daniel



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From pthanos at gmail.com  Sat Apr 21 19:27:15 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Sat, 21 Apr 2007 19:27:15 +0200
Subject: [Tutor] No speedup in
In-Reply-To: <812226.14223.qm@web54302.mail.re2.yahoo.com>
References: <812226.14223.qm@web54302.mail.re2.yahoo.com>
Message-ID: <4dcb3660704211027x44a8397fq48d6bebcacf15fc6@mail.gmail.com>

You cannot get around the GIL in python.

Maybe you could try passing chunks of your matrix that are copies of
the submatrises you want to multiply using threads. This way it will
be different objects, thus no GIL....I could be awfully wrong though,
I am a beginner in threads as well.

On 4/21/07, FAN Ying Wai <danfan1981 at yahoo.com> wrote:
> Hi,
> I am using Python Thread library for my parallel
> processing course
> project. I am doing matrix convolution on a
> multi-processor machine. I
> just found out that no speed-up is obtained with
> threading. It is
> probably because of something called GIL in Python.
> How can I get around
> that GIL and get speed-up?
> Thanks in advance.
> Daniel
>
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From atpridgen at mail.utexas.edu  Sat Apr 21 20:24:18 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Sat, 21 Apr 2007 13:24:18 -0500
Subject: [Tutor] How to program to python the right way?
In-Reply-To: <4629F04B.80402@tds.net>
References: <f989e6210704181731i65efdb87o3368f8955489489b@mail.gmail.com>
	<4629F04B.80402@tds.net>
Message-ID: <f989e6210704211124x98c900di11f63093411bc75d@mail.gmail.com>

I guess the problem I am trying to quell really revolves around style
and the proper way to do application programming with Python.  So one
of the things I found out the hard way about is classes.

I started of programming my Python Classes using the old style,
because I did not understand how the process works when a class is
instantiated.


class Foo:
    string = ""
    int = 0


On 4/21/07, Kent Johnson <kent37 at tds.net> wrote:
> Adam Pridgen wrote:
> > Hello everyone,
> >
> > I have pretty much finished hacking on my Thesis and I have come to
> > the conclusion,
> > I really do not know how to use Python to it "full" extent.  Some of
> > the things I have really messed up in my implementation are
> > serialization (specifically sub-classes), classes, and instantiating
> > them the "correct" way, and there are some things I have not tried,
> > but I would like to like contained execution and thread management.
> > Are there any books (with examples) out there that show some of these
> > techniques and explain the gotchas that come with the package.  Thanks
> > in advance.
>
> I think the Python Cookbook is an excellent book for learning idiomatic
> Python.
>
> Your question is pretty vague, can you ask a more specific question
> about an area where you are having trouble?
>
> Kent
>

From Adam.Pridgen at gmail.com  Sat Apr 21 20:25:04 2007
From: Adam.Pridgen at gmail.com (Adam Pridgen)
Date: Sat, 21 Apr 2007 13:25:04 -0500
Subject: [Tutor] How to program to python the right way?
In-Reply-To: <f989e6210704211124x98c900di11f63093411bc75d@mail.gmail.com>
References: <f989e6210704181731i65efdb87o3368f8955489489b@mail.gmail.com>
	<4629F04B.80402@tds.net>
	<f989e6210704211124x98c900di11f63093411bc75d@mail.gmail.com>
Message-ID: <f989e6210704211125o15d098a5jb3f4abfbd55d33ee@mail.gmail.com>

Disregard this email, gmail mis-fired.

On 4/21/07, Adam Pridgen <atpridgen at mail.utexas.edu> wrote:
> I guess the problem I am trying to quell really revolves around style
> and the proper way to do application programming with Python.  So one
> of the things I found out the hard way about is classes.
>
> I started of programming my Python Classes using the old style,
> because I did not understand how the process works when a class is
> instantiated.
>
>
> class Foo:
>     string = ""
>     int = 0
>
>
> On 4/21/07, Kent Johnson <kent37 at tds.net> wrote:
> > Adam Pridgen wrote:
> > > Hello everyone,
> > >
> > > I have pretty much finished hacking on my Thesis and I have come to
> > > the conclusion,
> > > I really do not know how to use Python to it "full" extent.  Some of
> > > the things I have really messed up in my implementation are
> > > serialization (specifically sub-classes), classes, and instantiating
> > > them the "correct" way, and there are some things I have not tried,
> > > but I would like to like contained execution and thread management.
> > > Are there any books (with examples) out there that show some of these
> > > techniques and explain the gotchas that come with the package.  Thanks
> > > in advance.
> >
> > I think the Python Cookbook is an excellent book for learning idiomatic
> > Python.
> >
> > Your question is pretty vague, can you ask a more specific question
> > about an area where you are having trouble?
> >
> > Kent
> >
>

From eike.welk at gmx.net  Sat Apr 21 20:34:49 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Sat, 21 Apr 2007 20:34:49 +0200
Subject: [Tutor] No speedup in
In-Reply-To: <812226.14223.qm@web54302.mail.re2.yahoo.com>
References: <812226.14223.qm@web54302.mail.re2.yahoo.com>
Message-ID: <200704212034.50546.eike.welk@gmx.net>

Hello Ying Wai!

If you are using NumPy you should ask your question on the NumPy 
mailing list: 
http://projects.scipy.org/mailman/listinfo/numpy-discussion

There is some project to simplify parallel computing with Python 
called IPython1, which is part of the IPython project:
http://ipython.scipy.org/moin/IPython1
 
Regards, Eike.


From andreas at kostyrka.org  Sat Apr 21 21:35:49 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 21 Apr 2007 21:35:49 +0200
Subject: [Tutor] No speedup in
In-Reply-To: <4dcb3660704211027x44a8397fq48d6bebcacf15fc6@mail.gmail.com>
References: <812226.14223.qm@web54302.mail.re2.yahoo.com>
	<4dcb3660704211027x44a8397fq48d6bebcacf15fc6@mail.gmail.com>
Message-ID: <20070421193549.GR4118@andi-lap>

* Thanos Panousis <pthanos at gmail.com> [070421 19:56]:
> You cannot get around the GIL in python.
> 
> Maybe you could try passing chunks of your matrix that are copies of
> the submatrises you want to multiply using threads. This way it will
> be different objects, thus no GIL....I could be awfully wrong though,
> I am a beginner in threads as well.

That won't help either. The G in GIL stands for global. There are
basically two way around this:

a) use multiple processes (aka fork), and communicate the results back
to the main program.
b) use a C-language level extension to do the heavy lifting, and make
this extension give up the GIL, while doing the heavy lifting.

Andreas

> 
> On 4/21/07, FAN Ying Wai <danfan1981 at yahoo.com> wrote:
> > Hi,
> > I am using Python Thread library for my parallel
> > processing course
> > project. I am doing matrix convolution on a
> > multi-processor machine. I
> > just found out that no speed-up is obtained with
> > threading. It is
> > probably because of something called GIL in Python.
> > How can I get around
> > that GIL and get speed-up?
> > Thanks in advance.
> > Daniel
> >
> >
> >
> > __________________________________________________
> > Do You Yahoo!?
> > Tired of spam?  Yahoo! Mail has the best spam protection around
> > http://mail.yahoo.com
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From kent37 at tds.net  Sat Apr 21 23:08:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 21 Apr 2007 17:08:40 -0400
Subject: [Tutor] No speedup in
In-Reply-To: <200704212034.50546.eike.welk@gmx.net>
References: <812226.14223.qm@web54302.mail.re2.yahoo.com>
	<200704212034.50546.eike.welk@gmx.net>
Message-ID: <462A7D58.8080404@tds.net>

Eike Welk wrote:
> There is some project to simplify parallel computing with Python 
> called IPython1, which is part of the IPython project:
> http://ipython.scipy.org/moin/IPython1

See also Parallel Python (and others on the links page):
http://www.parallelpython.com/

Kent

From alan.gauld at btinternet.com  Sun Apr 22 01:00:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Apr 2007 00:00:14 +0100
Subject: [Tutor] Exceptions while dealing with MySQL
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
Message-ID: <f0e52e$smh$1@sea.gmane.org>

"Thanos Panousis" <pthanos at gmail.com> wrote

> I am developing a network management system that relies heavily on a
> MySQL database. The logic of the program is unavoidably coupled with
> query results I get from various tables.

That's pretty unusual, it normally indicates a non OO design.

> This is OK as long the mysql server has 100% uptime, but it hardly
> does.

Welcome to the real world... :-)

> thousand queries). What is the best approach to make error checking
> possible, with the least amount of code duplication?

Either write a generic wrapper around the execution of a query,
possibly by building a query class or just wrap all the queries in
try/except clauses....

> program to crash. It is really too much trouble checking for
> exceptions every time I make a simple query.

Welcome to the real world again.
In industrial strength code every file access, every database
query, every memory allocation (fortunately not often an issue
in Python!) and every network connection has to be protected.
Before try/except style programming that meant that around
75% of all code was error handling. With try/except we can
keep that down to 50%, sometimes less. But if reliability matters
you gotta catch the errors.

> What approach should I try take?

- genericize the queries so you catch  errors in one place.
- catch the errors
- do both if you have any doubts

or alternatively, pray....

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From rohan.deshpande at gmail.com  Sun Apr 22 10:51:10 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Sun, 22 Apr 2007 09:51:10 +0100
Subject: [Tutor] IDE / development environment
Message-ID: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>

Hey guys,

I've been using Linux for a long time but this is my first foray into app
development.  Therefore, I have never had to properly set up a development
environment for myself.  I am partial to vim as an editor, and have
configured it for the python templating language i'm using with Pylons
called Mako, as well as using python.vim.  However, I have not figured out
how to do file management in a productive manner, quickly switching between
files.

What does everyone use as their development environment for Python,
particularly web dev?

Thanks much.

Always looking for a faster way,
Rohan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070422/d0b73ccd/attachment.htm 

From eike.welk at gmx.net  Sun Apr 22 12:29:11 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Sun, 22 Apr 2007 12:29:11 +0200
Subject: [Tutor] IDE / development environment
In-Reply-To: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
Message-ID: <200704221229.12326.eike.welk@gmx.net>

On Sunday 22 April 2007 10:51, Rohan Deshpande wrote:
> What does everyone use as their development environment for Python,
> particularly web dev?

I use PyDev an extension for Eclipse:
http://pydev.sourceforge.net/

It is good at syntax completion but it is quite slow.
PyDev also lacks an interactive console.

Regards Eike.


From rikard.bosnjakovic at gmail.com  Sun Apr 22 12:41:47 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sun, 22 Apr 2007 12:41:47 +0200
Subject: [Tutor] IDE / development environment
In-Reply-To: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
Message-ID: <d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>

On 4/22/07, Rohan Deshpande <rohan.deshpande at gmail.com> wrote:

> What does everyone use as their development environment for Python,

Emacs.


-- 
- Rikard - http://bos.hack.org/cv/

From rohan.deshpande at gmail.com  Sun Apr 22 13:20:31 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Sun, 22 Apr 2007 12:20:31 +0100
Subject: [Tutor] screen scraping without the request
Message-ID: <e5a6f5430704220420x52b53ffsac604a22735e5f33@mail.gmail.com>

Hi All,

the previous thread on screen scraping got me thinking of starting a similar
project.  However, the problem is I have no idea what the POST request is as
there is no escape string after the URL when the resulting page comes up.  I
essentially need to pull the HTML from a page that is generated on a users
machine and pipe it into a python script.  How should I go about doing
this?  Is it possible/feasible to decipher the POST request and get the
HTML, or use some screen scraping python libs a la the javascript DOM hacks?
I was thinking of the possibilities of the former, but the interaction on
the site is such that the user enters a username/password and goes through a
couple links before getting to the page I need.  Perhaps Python can use the
session cookie and then pull the right page?

Sorry this sounds so vague. I've never done anything like this so I'm not
sure where to begin.

Quite puzzled,
Rohan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070422/3a8eef31/attachment.htm 

From kent37 at tds.net  Sun Apr 22 13:38:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 22 Apr 2007 07:38:22 -0400
Subject: [Tutor] screen scraping without the request
In-Reply-To: <e5a6f5430704220420x52b53ffsac604a22735e5f33@mail.gmail.com>
References: <e5a6f5430704220420x52b53ffsac604a22735e5f33@mail.gmail.com>
Message-ID: <462B492E.7050404@tds.net>

Rohan Deshpande wrote:
> Hi All,
> 
> the previous thread on screen scraping got me thinking of starting a 
> similar project.  However, the problem is I have no idea what the POST 
> request is as there is no escape string after the URL when the resulting 
> page comes up.  I essentially need to pull the HTML from a page that is 
> generated on a users machine and pipe it into a python script.  How 
> should I go about doing this?  Is it possible/feasible to decipher the 
> POST request and get the HTML, or use some screen scraping python libs a 
> la the javascript DOM hacks? I was thinking of the possibilities of the 
> former, but the interaction on the site is such that the user enters a 
> username/password and goes through a couple links before getting to the 
> page I need.  Perhaps Python can use the session cookie and then pull 
> the right page?

I think the mechanize library can help with this (though the site is 
down at the moment so I can't check):
http://wwwsearch.sourceforge.net/mechanize/

Kent

From rikard.bosnjakovic at gmail.com  Sun Apr 22 15:14:39 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sun, 22 Apr 2007 15:14:39 +0200
Subject: [Tutor] IDE / development environment
In-Reply-To: <9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>
	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>
Message-ID: <d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>

On 4/22/07, Jia Lu <roka100 at gmail.com> wrote:

> SPE under Linux
> PyScripter under windows

Stop replying to my mailbox.

-- 
- Rikard - http://bos.hack.org/cv/

From akfoughty at att.net  Sun Apr 22 16:31:28 2007
From: akfoughty at att.net (Angela K. Foughty)
Date: Sun, 22 Apr 2007 08:31:28 -0600
Subject: [Tutor] IDE / development environment
In-Reply-To: <d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>
	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>
Message-ID: <462B71C0.7080406@att.net>

Hey, you know what?  Whether someone replies to the list address or your 
address, it's still going to end up in your mailbox, so chill out.  It's 
a simple matter to change the list preferences to make the list address 
the reply-to address.  If the list owner won't do that, your beef is 
with him and not with people who reply to posts, and meanwhile, I'm 
tired of getting your complaints in MY mailbox.

A.

Rikard Bosnjakovic wrote:
> On 4/22/07, Jia Lu <roka100 at gmail.com> wrote:
>
>   
>> SPE under Linux
>> PyScripter under windows
>>     
>
> Stop replying to my mailbox.
>
>   

From teachv at taconic.net  Sun Apr 22 16:25:55 2007
From: teachv at taconic.net (Vince Teachout)
Date: Sun, 22 Apr 2007 10:25:55 -0400
Subject: [Tutor] IDE / development environment
In-Reply-To: <462B71C0.7080406@att.net>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>
	<462B71C0.7080406@att.net>
Message-ID: <462B7073.4050003@taconic.net>

Angela K. Foughty wrote:
> Hey, you know what?  Whether someone replies to the list address or your 
> address, it's still going to end up in your mailbox, so chill out.  It's 
> a simple matter to change the list preferences to make the list address 
> the reply-to address.  If the list owner won't do that, your beef is 
> with him and not with people who reply to posts, and meanwhile, I'm 
> tired of getting your complaints in MY mailbox.
>   
I just twit-filtered him.  I got tired of his one line robotic complaint 
in MY mailbox.

From rabidpoobear at gmail.com  Sun Apr 22 16:37:47 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 22 Apr 2007 09:37:47 -0500
Subject: [Tutor] IDE / development environment
In-Reply-To: <462B71C0.7080406@att.net>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>
	<462B71C0.7080406@att.net>
Message-ID: <462B733B.9030903@gmail.com>

Angela K. Foughty wrote:
> Hey, you know what?  Whether someone replies to the list address or your 
> address, it's still going to end up in your mailbox, so chill out.  It's 
> a simple matter to change the list preferences to make the list address 
> the reply-to address.  If the list owner won't do that, your beef is 
> with him and not with people who reply to posts, and meanwhile, I'm 
> tired of getting your complaints in MY mailbox.
>   
It would be really funny if Rikard wrote a scathing rebuttal here and 
forgot to hit reply-all and sent it direct to you. :D
Seriously, though.  Let us not start any flameage.  It was so nice and 
cool in here.
I think Rikard is pretty justified in complaining.  It's pretty annoying 
when replies obviously meant for the list aren't sent there,
and you have to act as the middle-man, forwarding their e-mails for 
them.  Why'd we set up this intricate system of interconnected computers 
if humans end up doing the routing?
On the other hand, it's not too hard to have a nicer attitude about it.  
"Please stop replying to my mailbox," for example.
Angela - I don't think it's so much that the e-mail is in his inbox, 
just that it's in ONLY his inbox, and he feels bad letting it rot there,
for fear that the person who can't remember whether to use reply or 
reply-all for this group may have had something useful to contribute -
and he thus is forced to route their messages to the list and take up 
his valuable time.
-Luke
> A.
>
> Rikard Bosnjakovic wrote:
>   
>> On 4/22/07, Jia Lu <roka100 at gmail.com> wrote:
>>
>>   
>>     
>>> SPE under Linux
>>> PyScripter under windows
>>>     
>>>       
>> Stop replying to my mailbox.
>>
>>   
>>     
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From rabidpoobear at gmail.com  Sun Apr 22 16:43:03 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 22 Apr 2007 09:43:03 -0500
Subject: [Tutor] screen scraping without the request
In-Reply-To: <462B492E.7050404@tds.net>
References: <e5a6f5430704220420x52b53ffsac604a22735e5f33@mail.gmail.com>
	<462B492E.7050404@tds.net>
Message-ID: <462B7477.9010109@gmail.com>

Kent Johnson wrote:
> Rohan Deshpande wrote:
>   
>> Hi All,
>>
>> the previous thread on screen scraping got me thinking of starting a 
>> similar project.  However, the problem is I have no idea what the POST 
>> request is as there is no escape string after the URL when the resulting 
>> page comes up.  I essentially need to pull the HTML from a page that is 
>> generated on a users machine and pipe it into a python script.  How 
>> should I go about doing this?  Is it possible/feasible to decipher the 
>> POST request and get the HTML, or use some screen scraping python libs a 
>> la the javascript DOM hacks? I was thinking of the possibilities of the 
>> former, but the interaction on the site is such that the user enters a 
>> username/password and goes through a couple links before getting to the 
>> page I need.  Perhaps Python can use the session cookie and then pull 
>> the right page?
>>     
Have you tried using Firebug?  It's an extension for Firefox.
You might be able to run it while you're navigating the site, and see 
the communciation between you and the server and get the POST that way,
but I'm not completely certain about that.
-Luke

From rohan.deshpande at gmail.com  Sun Apr 22 16:52:44 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Sun, 22 Apr 2007 15:52:44 +0100
Subject: [Tutor] screen scraping without the request
In-Reply-To: <462B7477.9010109@gmail.com>
References: <e5a6f5430704220420x52b53ffsac604a22735e5f33@mail.gmail.com>
	<462B492E.7050404@tds.net> <462B7477.9010109@gmail.com>
Message-ID: <e5a6f5430704220752h666fadccra34e7cccf9560b7d@mail.gmail.com>

Hi Luke/Kent,

Assuming I can find the POST, is mechanize the way to go to mimic browser
functionality? or do i need other/extra libraries?
Thanks,
Rohan

On 4/22/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> Kent Johnson wrote:
> > Rohan Deshpande wrote:
> >
> >> Hi All,
> >>
> >> the previous thread on screen scraping got me thinking of starting a
> >> similar project.  However, the problem is I have no idea what the POST
> >> request is as there is no escape string after the URL when the
> resulting
> >> page comes up.  I essentially need to pull the HTML from a page that is
> >> generated on a users machine and pipe it into a python script.  How
> >> should I go about doing this?  Is it possible/feasible to decipher the
> >> POST request and get the HTML, or use some screen scraping python libs
> a
> >> la the javascript DOM hacks? I was thinking of the possibilities of the
> >> former, but the interaction on the site is such that the user enters a
> >> username/password and goes through a couple links before getting to the
> >> page I need.  Perhaps Python can use the session cookie and then pull
> >> the right page?
> >>
> Have you tried using Firebug?  It's an extension for Firefox.
> You might be able to run it while you're navigating the site, and see
> the communciation between you and the server and get the POST that way,
> but I'm not completely certain about that.
> -Luke
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070422/5f1bff3c/attachment.html 

From alan.gauld at btinternet.com  Sun Apr 22 17:19:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Apr 2007 16:19:53 +0100
Subject: [Tutor] IDE / development environment
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com><462B71C0.7080406@att.net>
	<462B733B.9030903@gmail.com>
Message-ID: <f0fufa$fiv$1@sea.gmane.org>

"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

> for fear that the person who can't remember whether to use reply or
> reply-all for this group

I won't get into the whole philospohy bit here but the rule is
quite simple and standard and should work on any standard
mail tool..

Read the From header.
Reply sends it to whoever/whatever is in that header
(OK technically it sends it to the Reply-To header if set).
Reply All sends it to all the recipients of the oiriginal mail.

Mail sent via Python's Mailman comes from the original
sender and is CCd to the list, therefore you need Reply All
to reply to the list.. Reply replies to the sender.

Just use the tools as they were designed and it is very simple.

Having said that I do appreciate that web mail tools in particular
are often quite brain-dead and make Reply All hard to find - I
recently got caught out by a web tool that hasd ReplyAll as
its default and I wound up sending to the list when I intended
sending to the sender!!

Alan G.




From teachv at taconic.net  Sun Apr 22 17:36:49 2007
From: teachv at taconic.net (Vince Teachout)
Date: Sun, 22 Apr 2007 11:36:49 -0400
Subject: [Tutor] IDE / development environment
In-Reply-To: <f0fufa$fiv$1@sea.gmane.org>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com><462B71C0.7080406@att.net>	<462B733B.9030903@gmail.com>
	<f0fufa$fiv$1@sea.gmane.org>
Message-ID: <462B8111.4060606@taconic.net>

Alan Gauld wrote:
> Having said that I do appreciate that web mail tools in particular
> are often quite brain-dead and make Reply All hard to find - I
> recently got caught out by a web tool that hasd ReplyAll as
> its default and I wound up sending to the list when I intended
> sending to the sender!!
>
>   

I have a cousin who inadvertantly sent some extremely juicy personal 
information to our family mailing list because of that same problem.  
Can the list be set to set the FROM to be from the list, instead of from 
the original FROM?  That way clicking reply replies to the list, and you 
have to make an extra effort (reply all) to reply to the orignal sender, 
as well.   It may not be standard, but it sure makes it a lot easier. 

I actually sympathize with the original poster - it is annoying to get 2 
copies of the email.  I just found his solution to be even MORE 
annoying, after a while.  :-|

-- 
Vince Teachout
Caracal Software
www.caracal.net
518-733-9411


From clajo04 at mac.com  Sun Apr 22 18:24:02 2007
From: clajo04 at mac.com (John Clark)
Date: Sun, 22 Apr 2007 12:24:02 -0400
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <f0e52e$smh$1@sea.gmane.org>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
	<f0e52e$smh$1@sea.gmane.org>
Message-ID: <004501c784fa$a46e9730$fefea8c0@haengma>

Alan Gauld wrote:

>"Thanos Panousis" <pthanos at gmail.com> wrote
>
>> I am developing a network management system that relies heavily on a 
>> MySQL database. The logic of the program is unavoidably coupled with 
>> query results I get from various tables.
>
>That's pretty unusual, it normally indicates a non OO design.
>

Database persistance has always been a frustration of mine in OO design -
does anyone have pointers to patterns that can be used to decouple the
database connection/transaction/cursor/cache management with the logic of
the objects in the domain of the solution?  I know that there is a text book
out there called "Database Access Patterns", can anyone provide a
recommendation or a critique of the book?  Are there other (better)
references I should be consulting in designing the database interaction
layer of my application?

Thanks,
-John Clark 


From mwalsh at groktech.org  Sun Apr 22 18:49:56 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 22 Apr 2007 11:49:56 -0500
Subject: [Tutor] IDE / development environment
In-Reply-To: <200704221229.12326.eike.welk@gmx.net>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
	<200704221229.12326.eike.welk@gmx.net>
Message-ID: <462B9234.3060705@groktech.org>

Eike Welk wrote:
> On Sunday 22 April 2007 10:51, Rohan Deshpande wrote:
>> What does everyone use as their development environment for Python,
>> particularly web dev?
> 
> I use PyDev an extension for Eclipse:
> http://pydev.sourceforge.net/

+1 for pydev. The additional plugins (wtp, aptana, and subclipse, etc)
make it particularly nice for web development -- however, I agree, it is
a bit heavy.

> 
> It is good at syntax completion but it is quite slow.
> PyDev also lacks an interactive console.

The 'pydev extensions' plugin (which is a $42.50 add on to the open
source pydev) appears to have an interactive console view. I can't say
that I've ever used it -- since you can make your own as an eclipse
external tool. I must admit it is far from a command line replacement,
but it suits my needs. YMMV.

Choose 'External Tools', from the Run >> External Tools menu, while in
the PyDev perspective (or any other where the Run menu is available).
Select 'Program' in the left-hand pane, and click the new configuration
button. Change the Name field to something appropriate
('python-interactive'), and in the location field specify the path to
the python binary (ex. '/usr/bin/python' or 'C:\Python25\python'). I use
'${container_loc}' in the working directory field, and you must specify
at least '-i' in arguments. Click apply to save, and Run to test it out.

If you want to run your module and drop into an interactive interpreter
after, you can do something very similar under the Run >> Run >> Python
Run menu item -- specifying '-i' in the VM arguments field on the
Arguments tab.

HTH,
Marty

> 
> Regards Eike.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From mwalsh at groktech.org  Sun Apr 22 19:02:48 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 22 Apr 2007 12:02:48 -0500
Subject: [Tutor] screen scraping without the request
In-Reply-To: <462B7477.9010109@gmail.com>
References: <e5a6f5430704220420x52b53ffsac604a22735e5f33@mail.gmail.com>	<462B492E.7050404@tds.net>
	<462B7477.9010109@gmail.com>
Message-ID: <462B9538.6010802@groktech.org>

Hi Rohan,

You might also try the LiveHTTPHeaders firefox extension, it is also
very good for this type of reverse engineering.

http://livehttpheaders.mozdev.org/index.html

HTH,
Marty

Luke Paireepinart wrote:
> Kent Johnson wrote:
>> Rohan Deshpande wrote:
>>   
>>> Hi All,
>>>
>>> the previous thread on screen scraping got me thinking of starting a 
>>> similar project.  However, the problem is I have no idea what the POST 
>>> request is as there is no escape string after the URL when the resulting 
>>> page comes up.  I essentially need to pull the HTML from a page that is 
>>> generated on a users machine and pipe it into a python script.  How 
>>> should I go about doing this?  Is it possible/feasible to decipher the 
>>> POST request and get the HTML, or use some screen scraping python libs a 
>>> la the javascript DOM hacks? I was thinking of the possibilities of the 
>>> former, but the interaction on the site is such that the user enters a 
>>> username/password and goes through a couple links before getting to the 
>>> page I need.  Perhaps Python can use the session cookie and then pull 
>>> the right page?
>>>     
> Have you tried using Firebug?  It's an extension for Firefox.
> You might be able to run it while you're navigating the site, and see 
> the communciation between you and the server and get the POST that way,
> but I'm not completely certain about that.
> -Luke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Sun Apr 22 19:32:10 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Apr 2007 18:32:10 +0100
Subject: [Tutor] Exceptions while dealing with MySQL
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com><f0e52e$smh$1@sea.gmane.org>
	<004501c784fa$a46e9730$fefea8c0@haengma>
Message-ID: <f0g67b$rfd$1@sea.gmane.org>

"John Clark" <clajo04 at mac.com> wrote

>>> MySQL database. The logic of the program is unavoidably coupled 
>>> with
>>> query results I get from various tables.
>>That's pretty unusual, it normally indicates a non OO design.
>
> Database persistance has always been a frustration of mine in OO 
> design -

Pesistence on its own is not too dificult, what is more difficult
is trying to use a relational database to actually manage objects.
For persistence you only need to fetch data from the database
when you create/initialise the instance and save it back when
the object is deleted. You rely on using the in-memory copy
while it is in memory.

For searches etc you can use  meta classes and class methods
to do the intelligent management of the instances so that access
is either steered to an existing instance or a new instance is
created. Searches and Lists can be done in class methods.

So if you are happy that you will never instantiate all objects,
or can afford to load it all in RAM, its not too hard. The problems
start when you have big data sets or complex, cross object
queries - but you need to ask why? Usually if your objects
are right the queries will be relatively simple since the objects
reflect your usage.

> does anyone have pointers to patterns that can be used to decouple 
> the
> database connection/transaction/cursor/cache management with the 
> logic of
> the objects in the domain of the solution?

I usually use a meta-class for that and manage these things
at a class level. If you have complex cross-instance queries going
on, first ask why?, if that doesn't help then consider building 
relationship
objects to manage the relations including the data access.

Recall from Information Engineering that interseection tables
(ie many to many relatinships) are actually data representations
of management processes. In OOP we normally build managemernt
processes as objects (controllers on Jacobsen speak) or as class
methods (possibly paired across the related objects) whichever
is most appropriate.

Or use an existing ORM such as SQLObject or Alchemy.

Or better still an OODB if you have control of that decision.

> out there called "Database Access Patterns", can anyone provide a
> recommendation or a critique of the book?  Are there other (better)

Sorry, hadn't heard of it till now.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From pgarceau at gmail.com  Sun Apr 22 20:11:23 2007
From: pgarceau at gmail.com (Peter Garceau)
Date: Sun, 22 Apr 2007 14:11:23 -0400
Subject: [Tutor] IDE / development environment
In-Reply-To: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
Message-ID: <12a834ef0704221111k6653831aha1536af22b67d187@mail.gmail.com>

On 4/22/07, Rohan Deshpande <rohan.deshpande at gmail.com> wrote:

>
> What does everyone use as their development environment for Python,
> particularly web dev?


I've been using PIDA for a while. http://pida.co.uk/

It's not nearly as fancy as Eclipse, but it does everything that I need it
to do. I think it fits your needs particularly well, since it allow you
embed vim and you won't need to change your current settings.

Peter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070422/479f2653/attachment.html 

From kent37 at tds.net  Sun Apr 22 20:38:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 22 Apr 2007 14:38:19 -0400
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <004501c784fa$a46e9730$fefea8c0@haengma>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>	<f0e52e$smh$1@sea.gmane.org>
	<004501c784fa$a46e9730$fefea8c0@haengma>
Message-ID: <462BAB9B.8080007@tds.net>

John Clark wrote:
> I know that there is a text book
> out there called "Database Access Patterns", can anyone provide a
> recommendation or a critique of the book?  Are there other (better)
> references I should be consulting in designing the database interaction
> layer of my application?

I like Martin Fowler's "Patterns of Enterprise Application Architecture".

Kent

From rob.andrews at gmail.com  Sun Apr 22 20:51:06 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Sun, 22 Apr 2007 13:51:06 -0500
Subject: [Tutor] IDE / development environment
In-Reply-To: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
Message-ID: <8d757d2e0704221151g8395553k4b716fd9bb645d5a@mail.gmail.com>

> What does everyone use as their development environment for Python,
> particularly web dev?

Komodo (by ActiveState). For web dev in dynamic languages, it's tough
to actually beat.

I scored mine at a $100 discount thanks to a coupon ActiveState handed
out at PyCon this year.

-Rob A.

From ebbaalm at uiuc.edu  Sun Apr 22 21:02:17 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 22 Apr 2007 14:02:17 -0500
Subject: [Tutor] An identity question
Message-ID: <7a4620dc0704221202k435a7682i6e5f19daa65f6b7b@mail.gmail.com>

The differences in cases 1 and 3 vs. 2 is due to 'common values' of
name assignments being treated a bit differently, right? Also, it's
clear why case 5 evaluates to false.  But, why does the case 4
equality check evaluate to True, whereas case 1 and 3 don't?

case 1:
>>> a = 10000
>>> b = 10000
>>> a is b
False

case 2:
>>> a = 10
>>> b = 10
>>> a is b
True

case 3:
>>> def foo2(v):
...     return v
...
>>> A1 = foo2(10000)
>>> B1 = foo2(10000)
>>> A1 is B1
False

case 4:
>>> def foo():
...     x = 10000
...     return x
...
>>> A = foo()
>>> B = foo()
>>> A is B
True

case 5:
>>> C1 = foo2(10000)
>>> D1 = foo2(10001)
>>> C1 is D1
False

Thanks!

From kent37 at tds.net  Sun Apr 22 21:13:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 22 Apr 2007 15:13:39 -0400
Subject: [Tutor] An identity question
In-Reply-To: <7a4620dc0704221202k435a7682i6e5f19daa65f6b7b@mail.gmail.com>
References: <7a4620dc0704221202k435a7682i6e5f19daa65f6b7b@mail.gmail.com>
Message-ID: <462BB3E3.40707@tds.net>

Cecilia Alm wrote:
> The differences in cases 1 and 3 vs. 2 is due to 'common values' of
> name assignments being treated a bit differently, right? Also, it's
> clear why case 5 evaluates to false.  But, why does the case 4
> equality check evaluate to True, whereas case 1 and 3 don't?
> 
> case 4:
>>>> def foo():
> ...     x = 10000
> ...     return x
> ...
>>>> A = foo()
>>>> B = foo()
>>>> A is B
> True

I think in this case foo() has an internal reference to the constant 
10000. It returns the same reference each time.

Kent

From ebbaalm at uiuc.edu  Sun Apr 22 21:24:56 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 22 Apr 2007 14:24:56 -0500
Subject: [Tutor] An identity question
In-Reply-To: <462BB3E3.40707@tds.net>
References: <7a4620dc0704221202k435a7682i6e5f19daa65f6b7b@mail.gmail.com>
	<462BB3E3.40707@tds.net>
Message-ID: <7a4620dc0704221224qb04ff5akf97c80e5de4a866a@mail.gmail.com>

OK. I guess the same holds for the below list-internal values. It
doesn't seem that this could lead to unexpected aliasing 'conflict'
when assigning new values to names.
Thanks,
C

>>> def foo3():
...    x = [232131, 321321, 432432]
...    return x
...
>>> a = foo3()
>>> b = foo3()
>>> a is b
False
>>> a[0] is b[0]
True
>>> a[0] = 100
>>> a[0] is b[0]
False
>>> a
[100, 321321, 432432]
>>> b
[232131, 321321, 432432]



2007/4/22, Kent Johnson <kent37 at tds.net>:
> Cecilia Alm wrote:
> > The differences in cases 1 and 3 vs. 2 is due to 'common values' of
> > name assignments being treated a bit differently, right? Also, it's
> > clear why case 5 evaluates to false.  But, why does the case 4
> > equality check evaluate to True, whereas case 1 and 3 don't?
> >
> > case 4:
> >>>> def foo():
> > ...     x = 10000
> > ...     return x
> > ...
> >>>> A = foo()
> >>>> B = foo()
> >>>> A is B
> > True
>
> I think in this case foo() has an internal reference to the constant
> 10000. It returns the same reference each time.
>
> Kent
>


-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

From andreas at kostyrka.org  Sun Apr 22 22:41:32 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sun, 22 Apr 2007 22:41:32 +0200
Subject: [Tutor] An identity question
In-Reply-To: <7a4620dc0704221202k435a7682i6e5f19daa65f6b7b@mail.gmail.com>
References: <7a4620dc0704221202k435a7682i6e5f19daa65f6b7b@mail.gmail.com>
Message-ID: <20070422204132.GU4118@andi-lap>

* Cecilia Alm <ebbaalm at uiuc.edu> [070422 22:34]:
> The differences in cases 1 and 3 vs. 2 is due to 'common values' of
> name assignments being treated a bit differently, right? Also, it's
> clear why case 5 evaluates to false.  But, why does the case 4
> equality check evaluate to True, whereas case 1 and 3 don't?

Case 1 returns False, because a and b are different objects (albeit
representing the same value)
Case 2 returns True, because small integers return always the same
object (it's an optimization).
Case 3 returns False, because the integer objects are generated again
seperatly.
Case 4 returns True, because x is always the same object, created
inside of foo()
Case 5, well 10000 != 10001.

Andreas

> 
> case 1:
> >>> a = 10000
> >>> b = 10000
> >>> a is b
> False
> 
> case 2:
> >>> a = 10
> >>> b = 10
> >>> a is b
> True
> 
> case 3:
> >>> def foo2(v):
> ...     return v
> ...
> >>> A1 = foo2(10000)
> >>> B1 = foo2(10000)
> >>> A1 is B1
> False
> 
> case 4:
> >>> def foo():
> ...     x = 10000
> ...     return x
> ...
> >>> A = foo()
> >>> B = foo()
> >>> A is B
> True
> 
> case 5:
> >>> C1 = foo2(10000)
> >>> D1 = foo2(10001)
> >>> C1 is D1
> False
> 
> Thanks!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Mon Apr 23 01:00:55 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 23 Apr 2007 00:00:55 +0100
Subject: [Tutor] Exceptions while dealing with MySQL
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>	<f0e52e$smh$1@sea.gmane.org><004501c784fa$a46e9730$fefea8c0@haengma>
	<462BAB9B.8080007@tds.net>
Message-ID: <f0gpfo$c02$1@sea.gmane.org>


"Kent Johnson" <kent37 at tds.net> wrote
>
> I like Martin Fowler's "Patterns of Enterprise Application 
> Architecture".


I agree, except the title can be slightly misleading. Just to make it
clear, the book is about application architecture for larger scale
applications (not really enterprise scale just larger scale than the
usual book examples) and has virtually nothing to say about
enterprise architecture in the sense of say Zachman etc.

But as a book about application architectures its a very good guide.
I rate it along with Booch's classic OOAD book which deals with
similar issues in a different context.

Alan G




From rikard.bosnjakovic at gmail.com  Mon Apr 23 02:21:40 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 23 Apr 2007 02:21:40 +0200
Subject: [Tutor] IDE / development environment
In-Reply-To: <462B7073.4050003@taconic.net>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>
	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>
	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>
	<462B71C0.7080406@att.net> <462B7073.4050003@taconic.net>
Message-ID: <d9e88eaf0704221721u2659d00bm26132d82802d1f2e@mail.gmail.com>

On 4/22/07, Vince Teachout <teachv at taconic.net> wrote:

> I just twit-filtered him.  I got tired of his one line robotic complaint
> in MY mailbox.

Good for you, because as long as this list keeps being braindead about
not adding reply-to-tags (i.e. forever) I'm piping it back in here.

And now, Alan, see the charm of "reply all": this mail gets three
recipients: the list and two persons on the list, meaning they both
will get two copies. The next person replying this mail will add it up
to another person, and in the final step there is no need for the list
anymore, because everyone is in the CC-field.

Isn't that beauty?


-- 
- Rikard - http://bos.hack.org/cv/

From kent37 at tds.net  Mon Apr 23 04:59:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 22 Apr 2007 22:59:07 -0400
Subject: [Tutor] IDE / development environment
In-Reply-To: <d9e88eaf0704221721u2659d00bm26132d82802d1f2e@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>	<462B71C0.7080406@att.net>
	<462B7073.4050003@taconic.net>
	<d9e88eaf0704221721u2659d00bm26132d82802d1f2e@mail.gmail.com>
Message-ID: <462C20FB.6030801@tds.net>

Rikard Bosnjakovic wrote:

> And now, Alan, see the charm of "reply all": this mail gets three
> recipients: the list and two persons on the list, meaning they both
> will get two copies. The next person replying this mail will add it up
> to another person, and in the final step there is no need for the list
> anymore, because everyone is in the CC-field.

Feel free to edit the CC fields.

You can configure your own mail preferences so you only get one copy of 
mails that are sent to you and to the list.

Kent

From rabidpoobear at gmail.com  Mon Apr 23 10:00:56 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 23 Apr 2007 03:00:56 -0500
Subject: [Tutor] IDE / development environment
In-Reply-To: <462C20FB.6030801@tds.net>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>	<d9e88eaf0704220341h7923cbcex7de688bf1d3bb470@mail.gmail.com>	<9a1e512f0704220359x1cfd14e5pf3967b1c312a0a3c@mail.gmail.com>	<d9e88eaf0704220614l3d0f172es5df65f0653c52f8c@mail.gmail.com>	<462B71C0.7080406@att.net>	<462B7073.4050003@taconic.net>	<d9e88eaf0704221721u2659d00bm26132d82802d1f2e@mail.gmail.com>
	<462C20FB.6030801@tds.net>
Message-ID: <462C67B8.8060908@gmail.com>

Kent Johnson wrote:
> Rikard Bosnjakovic wrote:
>
>   
>> And now, Alan, see the charm of "reply all": this mail gets three
>> recipients: the list and two persons on the list, meaning they both
>> will get two copies. The next person replying this mail will add it up
>> to another person, and in the final step there is no need for the list
>> anymore, because everyone is in the CC-field.
>>     
>
> Feel free to edit the CC fields.
>
> You can configure your own mail preferences so you only get one copy of 
> mails that are sent to you and to the list.
>   
I only ever get one copy, even when people CC me.
I'm CCing this to you, Rikard, as motivation for you to figure out how 
to configure yours this way :P
-Luke

From Mike.Hansen at atmel.com  Mon Apr 23 16:59:46 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Mon, 23 Apr 2007 08:59:46 -0600
Subject: [Tutor] IDE / development environment
In-Reply-To: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E74FC60@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Rohan Deshpande
> Sent: Sunday, April 22, 2007 2:51 AM
> To: tutor at python.org
> Subject: [Tutor] IDE / development environment
> 
> Hey guys,
> 
> I've been using Linux for a long time but this is my first 
> foray into app development.  Therefore, I have never had to 
> properly set up a development environment for myself.  I am 
> partial to vim as an editor, and have configured it for the 
> python templating language i'm using with Pylons called Mako, 
> as well as using python.vim.  However, I have not figured out 
> how to do file management in a productive manner, quickly 
> switching between files.
> 
> What does everyone use as their development environment for 
> Python, particularly web dev? 
> 
> Thanks much.
> 
> Always looking for a faster way,
> Rohan
> 

I primarily use VIM. What do you mean by "switching between files"? You
might look at the mini-buffer explorer plug-in. It makes it easy to
switch between buffers.

Mike

From humbolt at comcast.net  Mon Apr 23 17:17:39 2007
From: humbolt at comcast.net (Robert H. Haener IV)
Date: Mon, 23 Apr 2007 11:17:39 -0400
Subject: [Tutor] IDE / development environment
In-Reply-To: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
References: <e5a6f5430704220151x60a6b479k1c997b4d7af0eb77@mail.gmail.com>
Message-ID: <462CCE13.7030808@comcast.net>

Rohan Deshpande wrote:
> What does everyone use as their development environment for Python,
> particularly web dev?

I primarily use SPE in both Windows and Linux, though I occasionally use vim/gvim in both environments.  Oddly enough, I've started using the Python interactive prompt for basic math in place of a calculator app.


-Robert

From rfquerin at gmail.com  Mon Apr 23 18:34:45 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Mon, 23 Apr 2007 12:34:45 -0400
Subject: [Tutor] Podcast aggregator - OPML Parsing?
Message-ID: <7d81675b0704230934n11002ce5y89b6fe76bbdd3e56@mail.gmail.com>

I'd like to try my hand at writing a very simple podcast aggregator
for linux. I'll be using wxPython and have found the Universal Feed
Parser which looks good for me to use, but I'm having trouble finding
a similar module that might parse OPML files. Does anybody know of a
good one? Or should I do that myself.

From john.destefano at gmail.com  Mon Apr 23 22:43:45 2007
From: john.destefano at gmail.com (John DeStefano)
Date: Mon, 23 Apr 2007 16:43:45 -0400
Subject: [Tutor] Tkinter import error
Message-ID: <f2160e0d0704231343o4a1a9f3cva2339c42a87b1c1@mail.gmail.com>

Hi all,

I've been lurking for a while; I'm just picking up Python and most of
the posts have been a bit over my head.

I've run into an error that I've seen reported in several places, but
none of the fixes seem to be working for me: when I try to "import
Tkinter" I get a configuration error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter

I actually have 2.3, 2.4, and 2.5 on this system (RHEL4 Linux), and I
compiled 2.5 from scratch.  I've tried installing the tkinter package
for my OS and re-compiling Python (with both "make clean" and "make
distclean" first), but I still get the same error.  I also checked to
make sure that "Tkinter.py" exists in the path shown in the error, and
it is there (dated the last time I recompiled Python 2.5).

What else can I try?

Thank you,
~John

From rabidpoobear at gmail.com  Tue Apr 24 00:51:22 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 23 Apr 2007 17:51:22 -0500
Subject: [Tutor] Tkinter import error
In-Reply-To: <f2160e0d0704231343o4a1a9f3cva2339c42a87b1c1@mail.gmail.com>
References: <f2160e0d0704231343o4a1a9f3cva2339c42a87b1c1@mail.gmail.com>
Message-ID: <462D386A.4030103@gmail.com>

John DeStefano wrote:
> Hi all,
>
> I've been lurking for a while; I'm just picking up Python and most of
> the posts have been a bit over my head.
>
> I've run into an error that I've seen reported in several places, but
> none of the fixes seem to be working for me: when I try to "import
> Tkinter" I get a configuration error:
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in <module>
>     import _tkinter # If this fails your Python may not be configured for Tk
> ImportError: No module named _tkinter
>
> I actually have 2.3, 2.4, and 2.5 on this system (RHEL4 Linux), and I
> compiled 2.5 from scratch.  I've tried installing the tkinter package
> for my OS and re-compiling Python (with both "make clean" and "make
> distclean" first), but I still get the same error.  I also checked to
> make sure that "Tkinter.py" exists in the path shown in the error, and
> it is there (dated the last time I recompiled Python 2.5).
>
> What else can I try?
>   
So the problem is in your 2.5 install?
Can you just use a binary package or do you need to compile from scratch?
You can use the #! first line in your source code to specify which 
Python interpreter to use, I believe,
so you could direct it at one of your other installs for now until you 
get 2.5 working....
Just a thought.
-Luke

From alan.gauld at btinternet.com  Tue Apr 24 01:09:21 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 00:09:21 +0100
Subject: [Tutor] Tkinter import error
References: <f2160e0d0704231343o4a1a9f3cva2339c42a87b1c1@mail.gmail.com>
Message-ID: <f0jebj$6vr$1@sea.gmane.org>


"John DeStefano" <john.destefano at gmail.com> wrote

> I've run into an error that I've seen reported in several places, 
> but
> none of the fixes seem to be working for me: when I try to "import
> Tkinter" I get a configuration error:
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in 
> <module>
>    import _tkinter # If this fails your Python may not be configured 
> for Tk
> ImportError: No module named _tkinter

Have you specifically selected Tkinter when you compiled the code?
I believe you need to set something via configure... Alternatively
find an rpm with Tkinter configured already, that should be pretty
easy.

> make sure that "Tkinter.py" exists in the path shown in the error, 
> and
> it is there (dated the last time I recompiled Python 2.5).

I don't think its the .py file is the problem its the library that the 
.py
file wraps.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




From john.destefano at gmail.com  Tue Apr 24 02:34:25 2007
From: john.destefano at gmail.com (John DeStefano)
Date: Mon, 23 Apr 2007 20:34:25 -0400
Subject: [Tutor] Tkinter import error
In-Reply-To: <462D386A.4030103@gmail.com>
References: <f2160e0d0704231343o4a1a9f3cva2339c42a87b1c1@mail.gmail.com>
	<462D386A.4030103@gmail.com>
Message-ID: <f2160e0d0704231734l7dfb406q4bee018db48f17a1@mail.gmail.com>

On 4/23/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> So the problem is in your 2.5 install?

Well, I get the same error no matter whether I try to import Tkinter
while running 2.3, 2.4, or 2.5.

> Can you just use a binary package or do you need to compile from scratch?

I don't need to compile from scratch, just thought that was the
preferred way to do things, and that it might pick up
already-installed packages and avoid errors such as this one.  Do most
Linux binaries come with Tkinter support already installed?

> You can use the #! first line in your source code to specify which
> Python interpreter to use, I believe,
> so you could direct it at one of your other installs for now until you
> get 2.5 working....

I think it's more of a system/configuration problem than one
specifically with 2.5.  The other Python versions give the same exact
error.

Thanks,
~John

From rabidpoobear at gmail.com  Tue Apr 24 08:42:14 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 24 Apr 2007 01:42:14 -0500
Subject: [Tutor] detecting data member changes
Message-ID: <462DA6C6.40002@gmail.com>

Supposing I have a class like this:

class wiimote(object):
    def __init__(self):
        self.leds = [0,0,0,0]
    def updateLEDs(self):
        do_stuff()#write correct output report to wiimote to toggle LEDs.

So basically what I want to do is that whenever the self.leds variable 
is changed, the updateLEDs method is called.
( I can't call it constantly in a loop because 1) the wii remote freaks 
out, and 2) that seems pretty ineffiicent.)
I know I could use a __setattr__ but then I'd have to access the leds 
using a dictionary with an 'LED' key mapped to the status array.
It's not necessarily a bad thing for my own use, but it seems like it'd 
be off-putting to other people using my library.
So is there a way to detect such changes that's Pythonic?
Thanks,
-Luke

From alan.gauld at btinternet.com  Tue Apr 24 09:31:16 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 08:31:16 +0100
Subject: [Tutor] detecting data member changes
References: <462DA6C6.40002@gmail.com>
Message-ID: <f0kbon$c4b$1@sea.gmane.org>

"Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>
> class wiimote(object):
>    def __init__(self):
>        self.leds = [0,0,0,0]
>    def updateLEDs(self):
>        do_stuff()#write correct output report to wiimote to toggle 
> LEDs.
>
> So basically what I want to do is that whenever the self.leds 
> variable
> is changed, the updateLEDs method is called.

I'm not sure what your concern is here.
Since leds is an attribute of this class and therefore should only
be changed by a message to this class, then it should be easy
enough to ensure that each method that updates the leds calls
updateLED() when it makes a change

Or are you concerned about the possibility of someone directly
modifying leds from outside the class (naughty!). If its the latter
then you have the usual Python options:
- Make it single underscored and comment the fact that
  mods should call update:LED() - The pythonic way of consenting 
adults.
- Use the double underscore to make leds private
- Use setattr as you describe - I'm not clear why you need dictionary
  access though?
- Use a property to make "direct access" via a method
- Make leds a class which uses setattr...

Or am I missing something else?

> I know I could use a __setattr__ but then I'd have to access the 
> leds
> using a dictionary with an 'LED' key mapped to the status array.
> It's not necessarily a bad thing for my own use, but it seems like 
> it'd
> be off-putting to other people using my library.

Given that users of your class shouldn't be accessing leds directly
the format of the data should be of no interest to them. And a format
that discourages direct access would be a good thing - provided
your message interface makkes use of the class easy.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From ceasar102 at yahoo.com  Tue Apr 24 09:45:13 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Tue, 24 Apr 2007 00:45:13 -0700 (PDT)
Subject: [Tutor] scope/namespaces
Message-ID: <152601.97522.qm@web56107.mail.re3.yahoo.com>

Something in python disturbs me ,

when i write a for loop,

i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. Is it different in python?

       
---------------------------------
Ahhh...imagining that irresistible "new car" smell?
 Check outnew cars at Yahoo! Autos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070424/c5633aa8/attachment.html 

From rikard.bosnjakovic at gmail.com  Tue Apr 24 11:21:01 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 24 Apr 2007 11:21:01 +0200
Subject: [Tutor] scope/namespaces
In-Reply-To: <152601.97522.qm@web56107.mail.re3.yahoo.com>
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>
Message-ID: <d9e88eaf0704240221r592bc56fsf65e6b8daa655f52@mail.gmail.com>

On 4/24/07, ammar azif <ceasar102 at yahoo.com> wrote:

> i am able to access the variable declared in that loop after the loop
> finishes which i am not able to do in languages like c/c++ or java. Is it
> different in python?

I'm not sure what you mean with "different", but the loop-variable is
not destroyed upon the exit of the for-loop:

>>> z
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'z' is not defined
>>> for z in (1,2,3): pass
...
>>> print z
3


-- 
- Rikard - http://bos.hack.org/cv/

From klappnase at freenet.de  Tue Apr 24 11:26:00 2007
From: klappnase at freenet.de (Michael Lange)
Date: Tue, 24 Apr 2007 11:26:00 +0200
Subject: [Tutor] Tkinter import error
In-Reply-To: <f0jebj$6vr$1@sea.gmane.org>
References: <f2160e0d0704231343o4a1a9f3cva2339c42a87b1c1@mail.gmail.com>
	<f0jebj$6vr$1@sea.gmane.org>
Message-ID: <20070424112600.535c38ac.klappnase@freenet.de>

On Tue, 24 Apr 2007 00:09:21 +0100
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> 
> "John DeStefano" <john.destefano at gmail.com> wrote
> 
> > I've run into an error that I've seen reported in several places, 
> > but
> > none of the fixes seem to be working for me: when I try to "import
> > Tkinter" I get a configuration error:
> > Traceback (most recent call last):
> >  File "<stdin>", line 1, in <module>
> >  File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in 
> > <module>
> >    import _tkinter # If this fails your Python may not be configured 
> > for Tk
> > ImportError: No module named _tkinter
> 
> Have you specifically selected Tkinter when you compiled the code?
> I believe you need to set something via configure... Alternatively
> find an rpm with Tkinter configured already, that should be pretty
> easy.

Usually there is no need to pass extra arguments to configure.
My guess is that you missed to install Tcl / Tk and/or the Tcl/Tk development
packages before compiling python.

Michael


From kent37 at tds.net  Tue Apr 24 12:30:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 06:30:18 -0400
Subject: [Tutor] detecting data member changes
In-Reply-To: <462DA6C6.40002@gmail.com>
References: <462DA6C6.40002@gmail.com>
Message-ID: <462DDC3A.7070300@tds.net>

Luke Paireepinart wrote:
> Supposing I have a class like this:
> 
> class wiimote(object):
>     def __init__(self):
>         self.leds = [0,0,0,0]
>     def updateLEDs(self):
>         do_stuff()#write correct output report to wiimote to toggle LEDs.
> 
> So basically what I want to do is that whenever the self.leds variable 
> is changed, the updateLEDs method is called.
> ( I can't call it constantly in a loop because 1) the wii remote freaks 
> out, and 2) that seems pretty ineffiicent.)

Make leds a property:

class wiimote(object):
     def __init__(self):
         self._leds = [0, 0, 0, 0]

     def _set_leds(self, leds):
         self._leds = leds
         self._updateLEDs()

     def _get_leds(self):
         return self._leds

     leds = property(_get_leds, _set_leds)

     def _updateLEDs(self):
         print self._leds

w = wiimote()
print w.leds
w.leds = [1, 2, 3, 4]
print w.leds

I renamed _updateLEDs because it doesn't seem like this should be part 
of the public interface.

If you don't like having _set_leds and _get_leds in the namespace of 
wiimote, use one of the recipes here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698

> I know I could use a __setattr__ but then I'd have to access the leds 
> using a dictionary with an 'LED' key mapped to the status array.
> It's not necessarily a bad thing for my own use, but it seems like it'd 
> be off-putting to other people using my library.

I don't understand this part. It seems to me this would work:
def __setattr__(self, name, value):
   object.__setattr__(self, name, value)
   if name == 'leds':
     self._updateLEDs()

Kent

From ktn_vrce at yahoo.com  Tue Apr 24 12:26:34 2007
From: ktn_vrce at yahoo.com (Ketan Joshi)
Date: Tue, 24 Apr 2007 03:26:34 -0700 (PDT)
Subject: [Tutor] Question on UserDict class - copy function
Message-ID: <20070424102634.78404.qmail@web58705.mail.re1.yahoo.com>

Hello All,

I am very new to Python scripting. I have just started learning about Python. 
I have a question regarding UserDict class.

UserDict class has a copy function which is defined as follows:
def copy(self):
    if self.__class__ is UserDict:
        return UserDict(self.data)
    import copy
    return copy.copy(self)

Here, as I understand, copy module is capable of making a copy of any python object. If so, why isn't this function defined as:

def copy(self):
    import copy
    return copy.copy(self)

In other words, what is the need to use the if statement first and then import the copy module?
    if self.__class__ is UserDict:

        return UserDict(self.data)

Thanks and Regards,
Ketan Joshi



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070424/71051414/attachment.html 

From kent37 at tds.net  Tue Apr 24 12:34:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 06:34:42 -0400
Subject: [Tutor] scope/namespaces
In-Reply-To: <152601.97522.qm@web56107.mail.re3.yahoo.com>
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>
Message-ID: <462DDD42.3030806@tds.net>

ammar azif wrote:
> Something in python disturbs me ,
> 
> when i write a for loop,
> 
> i am able to access the variable declared in that loop after the loop 
> finishes which i am not able to do in languages like c/c++ or java. Is 
> it different in python?

Yes, it is different. In Python a block is not a scope. Names bound 
within the block, including the loop variable, are accessible outside 
the block.

Kent

From govindgoyal at gmail.com  Tue Apr 24 14:06:59 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Tue, 24 Apr 2007 17:36:59 +0530
Subject: [Tutor] + converted to 25 in http string
Message-ID: <f96f96bc0704240506x5bebb124q97278c509da820da@mail.gmail.com>

Hi,

I am using http to automate my Access point(AP) configuration where I sent
following strings to AP server through script.

params = urllib.urlencode
({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",*
'wire_mode':"b+only",*
'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})

Above string I captured using a tool ethereal and then implementing this in
my script.
But the problem is that when I run this script all configurations in AP are
OK except the parameter marked as bold in above string.

I used the same tool ethereal to see what string is actually passing to
Access point while I run my script and I got following:

 params = urllib.urlencode
({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",*
'wire_mode':"b25only",*
'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})

In conclusion,the character "+" is getting converted into"25" whenever I run
script.Thats why all other configuartions are OK except above mentioned
case.

Can anybody help to resolve this issue?

Best Regards,

Govind Goyal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070424/1b28a130/attachment.html 

From mwalsh at groktech.org  Tue Apr 24 14:47:31 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Tue, 24 Apr 2007 07:47:31 -0500
Subject: [Tutor] + converted to 25 in http string
In-Reply-To: <f96f96bc0704240506x5bebb124q97278c509da820da@mail.gmail.com>
References: <f96f96bc0704240506x5bebb124q97278c509da820da@mail.gmail.com>
Message-ID: <462DFC63.6010206@groktech.org>

Hi,

govind goyal wrote:
> Hi,
> 
> I am using http to automate my Access point(AP) configuration where I sent
> following strings to AP server through script.
> 
> params = urllib.urlencode
> ({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",*
> 'wire_mode':"b+only",*
> 'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})

You might consider having a look at the urllib quote_plus and
unquote_plus methods for clarification. I suspect the value you have
captured with ethereal is already quoted ('+' signs for spaces, etc) --
so you would have to unquote_plus it to find the correct value for use
in your script.

.>> urllib.unquote_plus('b+only')
'b only'

And, it appears that urllib.urlencode quotes the parameters while
constructing the query-string:

.>> params = urllib.urlencode({'write_mode': 'b only'})
.>> params
'write_mode=b+only'

HTH,
Marty

> 
> Above string I captured using a tool ethereal and then implementing this in
> my script.
> But the problem is that when I run this script all configurations in AP are
> OK except the parameter marked as bold in above string.
> 
> I used the same tool ethereal to see what string is actually passing to
> Access point while I run my script and I got following:
> 
> params = urllib.urlencode
> ({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",*
> 'wire_mode':"b25only",*
> 'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})
> 
> In conclusion,the character "+" is getting converted into"25" whenever I
> run
> script.Thats why all other configuartions are OK except above mentioned
> case.
> 
> Can anybody help to resolve this issue?
> 
> Best Regards,
> 
> Govind Goyal
> 

From kent37 at tds.net  Tue Apr 24 14:55:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 08:55:22 -0400
Subject: [Tutor] + converted to 25 in http string
In-Reply-To: <f96f96bc0704240506x5bebb124q97278c509da820da@mail.gmail.com>
References: <f96f96bc0704240506x5bebb124q97278c509da820da@mail.gmail.com>
Message-ID: <462DFE3A.701@tds.net>

govind goyal wrote:
> Hi,
>  
> I am using http to automate my Access point(AP) configuration where I 
> sent following strings to AP server through script.
>  
> params = 
> urllib.urlencode({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",*'wire_mode':"b+only",* 
> 'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})
>  
> Above string I captured using a tool ethereal and then implementing this 
> in my script.
> But the problem is that when I run this script all configurations in AP 
> are OK except the parameter marked as bold in above string.

'+' is not a valid character in parameters so it is escaped to %2B by 
urlencode:

In [10]: import urllib
In [11]: params = 
urllib.urlencode({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",'wire_mode':"b+only", 
'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})
In [12]: params
Out[12]: 
'ssid=wifi&ssid_enable=ssid_enable&ap=ap&int_ac=everyone&WRegion=USA&w_channel=6&lan_ac=everyone&wire_mode=b%2Bonly'


> I used the same tool ethereal to see what string is actually passing to 
> Access point while I run my script and I got following:
>  
> params = 
> urllib.urlencode({'WRegion':"USA",'ssid':"wifi",'ap':"ap",'ssid_enable':"ssid_enable",*'wire_mode':"b25only", 
> *'w_channel':6,'lan_ac':"everyone",'int_ac':"everyone"})

Where did this come from? This is not the output of ethereal...
>  
> In conclusion,the character "+" is getting converted into"25" whenever I 
> run script.Thats why all other configuartions are OK except above 
> mentioned case.

Interestingly, %25 is the escaped representation of '%'. So I wonder if 
your parameters are being url-encoded twice?

Can you show a little more of your code, and the actual string captured 
from ethereal?

Kent

From ezra.taylor at gmail.com  Tue Apr 24 15:07:39 2007
From: ezra.taylor at gmail.com (Ezra Taylor)
Date: Tue, 24 Apr 2007 09:07:39 -0400
Subject: [Tutor] scope/namespaces
In-Reply-To: <462DDD42.3030806@tds.net>
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>
	<462DDD42.3030806@tds.net>
Message-ID: <eb90f15e0704240607u5bdf0296ue3fba16ad80dc9@mail.gmail.com>

Sorry about that kent.  I just realized I emailed you directly.

Ezra

On 4/24/07, Kent Johnson <kent37 at tds.net> wrote:
>
> ammar azif wrote:
> > Something in python disturbs me ,
> >
> > when i write a for loop,
> >
> > i am able to access the variable declared in that loop after the loop
> > finishes which i am not able to do in languages like c/c++ or java. Is
> > it different in python?
>
> Yes, it is different. In Python a block is not a scope. Names bound
> within the block, including the loop variable, are accessible outside
> the block.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Ezra Taylor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070424/0b01891d/attachment.htm 

From kent37 at tds.net  Tue Apr 24 15:18:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 09:18:18 -0400
Subject: [Tutor] scope/namespaces
In-Reply-To: <eb90f15e0704240605k5db5d72amd85318375616cf1f@mail.gmail.com>
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>	
	<462DDD42.3030806@tds.net>
	<eb90f15e0704240605k5db5d72amd85318375616cf1f@mail.gmail.com>
Message-ID: <462E039A.7070202@tds.net>

Ezra Taylor wrote:
> Hello Kent:
>                     How can we limit this functionality so that python 
> behaves similar to other know languages.  Maybe I should be asking what 
> are the benifits of allow variables not being bound to a block of code.

Why is this a problem? Don't try to turn Python into Java, you might as
well stay with Java.

One advantage is, you can define a variable in a conditional block or a
try block without having to declare it first. For example:
if something:
   x = 3
else:
   x = 5

or
try:
   x = foo()
finally:
   cleanup()

# do something with x

It has long annoyed my that in Java these snippets would have to be
prefixed with
int x;

Kent
> 
> Ezra
> 
> On 4/24/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
> 
>     ammar azif wrote:
>      > Something in python disturbs me ,
>      >
>      > when i write a for loop,
>      >
>      > i am able to access the variable declared in that loop after the loop
>      > finishes which i am not able to do in languages like c/c++ or
>     java. Is
>      > it different in python?
> 
>     Yes, it is different. In Python a block is not a scope. Names bound
>     within the block, including the loop variable, are accessible outside
>     the block.
> 
>     Kent
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> Ezra Taylor



From john.destefano at gmail.com  Tue Apr 24 15:37:35 2007
From: john.destefano at gmail.com (John DeStefano)
Date: Tue, 24 Apr 2007 09:37:35 -0400
Subject: [Tutor] Tkinter import error
Message-ID: <f2160e0d0704240637m4a03156fje1559777def0d3fc@mail.gmail.com>

Michael Lange <klappnase at freenet.de> wrote:
> Usually there is no need to pass extra arguments to configure.
> My guess is that you missed to install Tcl / Tk and/or the Tcl/Tk development
> packages before compiling python.

That was it: I had both Tcl and Tk installed, but not the development
packages for either one.  I installed those, recompiled, and all is
well.

Thanks!

From rabidpoobear at gmail.com  Tue Apr 24 16:27:25 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 24 Apr 2007 09:27:25 -0500
Subject: [Tutor] detecting data member changes
In-Reply-To: <462DDC3A.7070300@tds.net>
References: <462DA6C6.40002@gmail.com> <462DDC3A.7070300@tds.net>
Message-ID: <462E13CD.1010007@gmail.com>


>
> Make leds a property:
>
> class wiimote(object):
>     def __init__(self):
>         self._leds = [0, 0, 0, 0]
>
>     def _set_leds(self, leds):
>         self._leds = leds
>         self._updateLEDs()
>
>     def _get_leds(self):
>         return self._leds
>
>     leds = property(_get_leds, _set_leds)
>
>     def _updateLEDs(self):
>         print self._leds
>
> w = wiimote()
> print w.leds
> w.leds = [1, 2, 3, 4]
> print w.leds
Wow, that's cool.  I need to read more about properties.
>
> I renamed _updateLEDs because it doesn't seem like this should be part 
> of the public interface.
Yeah, it was prepended with an underscore in my code, I forgot to put it 
when I simplified the code here.  *embarrassed*
>
> If you don't like having _set_leds and _get_leds in the namespace of 
> wiimote, use one of the recipes here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
>
>> I know I could use a __setattr__ but then I'd have to access the leds 
>> using a dictionary with an 'LED' key mapped to the status array.
>> It's not necessarily a bad thing for my own use, but it seems like 
>> it'd be off-putting to other people using my library.
>
> I don't understand this part. It seems to me this would work:
> def __setattr__(self, name, value):
>   object.__setattr__(self, name, value)
>   if name == 'leds':
>     self._updateLEDs()
What I meant was that it'd require people to access the variable via
classinstance['leds']
instead of
classinstance.leds
which is what I was aiming for.
I apologize, I should've waited till the morning to e-mail so I could be 
more coherent.

Is this properties method acceptable Python form or is it more proper to 
have modifying member functions like Alan said?
Or is it really up to me on how I want to implement it?
Thanks,
-Luke
>
> Kent
>


From rikard.bosnjakovic at gmail.com  Tue Apr 24 16:46:03 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 24 Apr 2007 16:46:03 +0200
Subject: [Tutor] Question on UserDict class - copy function
In-Reply-To: <20070424102634.78404.qmail@web58705.mail.re1.yahoo.com>
References: <20070424102634.78404.qmail@web58705.mail.re1.yahoo.com>
Message-ID: <d9e88eaf0704240746h5ede8031i99193a98f15546a0@mail.gmail.com>

On 4/24/07, Ketan Joshi <ktn_vrce at yahoo.com> wrote:

> If so, why isn't this function defined as:
>
> def copy(self):
>     import copy
>     return copy.copy(self)

The if-case in your code makes sure that the property __class__ is of
UserDict-inheritance. I believe it's there in case of multiple
classes.

class Gas:
  def __init__(self):
    pass
class Oil:
  def __init__(self):
    self.foo = Gas()
    self.dict = UserDict()

b = Oil()

b.__class__ will be __main__.Oil, and if you pass the entire class
around and want a copy of the dict-property, the copy()-method in
UserDict will first it is a UserDict-instance before copying it. If it
isn't, it creates one out of the existing data.


-- 
- Rikard - http://bos.hack.org/cv/

From kent37 at tds.net  Tue Apr 24 16:54:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 10:54:07 -0400
Subject: [Tutor] detecting data member changes
In-Reply-To: <462E13CD.1010007@gmail.com>
References: <462DA6C6.40002@gmail.com> <462DDC3A.7070300@tds.net>
	<462E13CD.1010007@gmail.com>
Message-ID: <462E1A0F.2080003@tds.net>

Luke Paireepinart wrote:

>>> I know I could use a __setattr__ but then I'd have to access the leds 
>>> using a dictionary with an 'LED' key mapped to the status array.
>>> It's not necessarily a bad thing for my own use, but it seems like 
>>> it'd be off-putting to other people using my library.
>>
>> I don't understand this part. It seems to me this would work:
>> def __setattr__(self, name, value):
>>   object.__setattr__(self, name, value)
>>   if name == 'leds':
>>     self._updateLEDs()
> What I meant was that it'd require people to access the variable via
> classinstance['leds']
> instead of
> classinstance.leds
> which is what I was aiming for.
> I apologize, I should've waited till the morning to e-mail so I could be 
> more coherent.

No, the above code should work with classinstance.leds. Maybe you are 
confusing __setattr__ - which affects attributes like .leds - with 
__setitem__ which is used for classinstance['leds']

> 
> Is this properties method acceptable Python form or is it more proper to 
> have modifying member functions like Alan said?

Alan and I don't always agree on questions like this. I don't take such 
a hard position about direct attribute access. IMO using a property is 
more Pythonic than making an explicit method. But I think one of the 
nice things about Python is you don't have to write explicit getters and 
setters; you can use plain attribute access to get at plain data, then 
if you need to add some behaviour just change the attribute to a property.

> Or is it really up to me on how I want to implement it?

Of course, it's your code, right?

Kent

From nephish at gmail.com  Tue Apr 24 17:04:33 2007
From: nephish at gmail.com (shawn bright)
Date: Tue, 24 Apr 2007 10:04:33 -0500
Subject: [Tutor] how to stop a function
Message-ID: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>

hello all,

i have a gui app that uses functions to respond to gui events.

like
def on_start_button_clicked(self, stuff):
    do this or that.

now there is one function that i have a kinda nested if else
conditions that i need to stop if necessary

if value == 1:
    if next_val == 4:
       do this or that
    else:
       here i need the function to just die
    do somthing here

is there something i can do to make this happen?

thanks

From andreengels at gmail.com  Tue Apr 24 17:18:18 2007
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 24 Apr 2007 17:18:18 +0200
Subject: [Tutor] Fwd:  how to stop a function
In-Reply-To: <6faf39c90704240818w1146afb6y44ee9cade6de8808@mail.gmail.com>
References: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
	<6faf39c90704240818w1146afb6y44ee9cade6de8808@mail.gmail.com>
Message-ID: <6faf39c90704240818u7087ac58uae0ab292f2507ddb@mail.gmail.com>

---------- Forwarded message ----------
From: Andre Engels <andreengels at gmail.com>
Date: 24 apr. 2007 17:18
Subject: Re: [Tutor] how to stop a function
To: shawn bright <nephish at gmail.com>


2007/4/24, shawn bright <nephish at gmail.com>:
> hello all,
>
> i have a gui app that uses functions to respond to gui events.
>
> like
> def on_start_button_clicked(self, stuff):
>     do this or that.
>
> now there is one function that i have a kinda nested if else
> conditions that i need to stop if necessary
>
> if value == 1:
>     if next_val == 4:
>        do this or that
>     else:
>        here i need the function to just die

    else:
         return



--
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels


-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels

From kent37 at tds.net  Tue Apr 24 17:25:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 11:25:26 -0400
Subject: [Tutor] how to stop a function
In-Reply-To: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
References: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
Message-ID: <462E2166.6000807@tds.net>

shawn bright wrote:
> now there is one function that i have a kinda nested if else
> conditions that i need to stop if necessary
> 
> if value == 1:
>     if next_val == 4:
>        do this or that
>     else:
>        here i need the function to just die
>     do somthing here
> 
> is there something i can do to make this happen?

return

Kent

From nephish at gmail.com  Tue Apr 24 17:27:27 2007
From: nephish at gmail.com (shawn bright)
Date: Tue, 24 Apr 2007 10:27:27 -0500
Subject: [Tutor] how to stop a function
In-Reply-To: <462E2166.6000807@tds.net>
References: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
	<462E2166.6000807@tds.net>
Message-ID: <384c93600704240827p7537764eibb8724e51c953783@mail.gmail.com>

jeeze, thanks, sorry, stupid question.

On 4/24/07, Kent Johnson <kent37 at tds.net> wrote:
> shawn bright wrote:
> > now there is one function that i have a kinda nested if else
> > conditions that i need to stop if necessary
> >
> > if value == 1:
> >     if next_val == 4:
> >        do this or that
> >     else:
> >        here i need the function to just die
> >     do somthing here
> >
> > is there something i can do to make this happen?
>
> return
>
> Kent
>

From rabidpoobear at gmail.com  Tue Apr 24 18:23:01 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 24 Apr 2007 11:23:01 -0500
Subject: [Tutor] detecting data member changes
In-Reply-To: <462E1A0F.2080003@tds.net>
References: <462DA6C6.40002@gmail.com> <462DDC3A.7070300@tds.net>
	<462E13CD.1010007@gmail.com> <462E1A0F.2080003@tds.net>
Message-ID: <462E2EE5.8040307@gmail.com>


> No, the above code should work with classinstance.leds. Maybe you are 
> confusing __setattr__ - which affects attributes like .leds - with 
> __setitem__ which is used for classinstance['leds']
Ah, yes. You hit the hail on the nead there, Kent.  Thanks for 
clarifying that for me.
>
>>
>> Is this properties method acceptable Python form or is it more proper 
>> to have modifying member functions like Alan said?
>
> Alan and I don't always agree on questions like this. I don't take 
> such a hard position about direct attribute access. IMO using a 
> property is more Pythonic than making an explicit method. But I think 
> one of the nice things about Python is you don't have to write 
> explicit getters and setters; you can use plain attribute access to 
> get at plain data, then if you need to add some behaviour just change 
> the attribute to a property.
I can see how some people might be surprised to know that changing 
classinstance.leds automagically sends a communication packet to the wii 
remote without their knowledge, but if they're aware of the side-effect, 
it seems to be a more elegant way of doing things to me (with properties 
vs. an explicit method), at least in this case.
>
>> Or is it really up to me on how I want to implement it?
>
> Of course, it's your code, right?
Yes, but it's code I plan on open-sourcing, so I'm trying to make it 
clear what's happening in case I get other developers to help in the future.

-Luke

From pthanos at gmail.com  Tue Apr 24 18:24:45 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Tue, 24 Apr 2007 18:24:45 +0200
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <f0gpfo$c02$1@sea.gmane.org>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
	<f0e52e$smh$1@sea.gmane.org> <004501c784fa$a46e9730$fefea8c0@haengma>
	<462BAB9B.8080007@tds.net> <f0gpfo$c02$1@sea.gmane.org>
Message-ID: <4dcb3660704240924n60865a0ayf8fc6d0ce0017312@mail.gmail.com>

Thanks to everybody for the replies. I got some nice pointers.

I know my design is nasty, but that is because I am learning...Putting
object orientation in the mix, I have this question:

I have an object, person, which is assosiated with some statistical
data. Say for each person object, I need an object variable called
"hairColor". This haircolor variable has to be filled through an SQL
query, so the object must have some way to access a database cursor.
The cool thing would be that all person objects use the same
connection/cursor to get their haircolors filled in, so there would be
only one connection to the SQL server.

Could this  done with a class variable? From what I understand, it
fits nice because its available to all objects of the class, and it is
unique. So would this be a nice way to have objects of the same class
share a "pipe" to the sql database?


On 4/23/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Kent Johnson" <kent37 at tds.net> wrote
> >
> > I like Martin Fowler's "Patterns of Enterprise Application
> > Architecture".
>
>
> I agree, except the title can be slightly misleading. Just to make it
> clear, the book is about application architecture for larger scale
> applications (not really enterprise scale just larger scale than the
> usual book examples) and has virtually nothing to say about
> enterprise architecture in the sense of say Zachman etc.
>
> But as a book about application architectures its a very good guide.
> I rate it along with Booch's classic OOAD book which deals with
> similar issues in a different context.
>
> Alan G
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Tue Apr 24 18:35:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 12:35:23 -0400
Subject: [Tutor] detecting data member changes
In-Reply-To: <462E2EE5.8040307@gmail.com>
References: <462DA6C6.40002@gmail.com> <462DDC3A.7070300@tds.net>
	<462E13CD.1010007@gmail.com> <462E1A0F.2080003@tds.net>
	<462E2EE5.8040307@gmail.com>
Message-ID: <462E31CB.1030809@tds.net>

Luke Paireepinart wrote:
> I can see how some people might be surprised to know that changing 
> classinstance.leds automagically sends a communication packet to the wii 
> remote without their knowledge, but if they're aware of the side-effect, 
> it seems to be a more elegant way of doing things to me (with properties 
> vs. an explicit method), at least in this case.

I think so.

>>> Or is it really up to me on how I want to implement it?
>>
>> Of course, it's your code, right?
> Yes, but it's code I plan on open-sourcing, so I'm trying to make it 
> clear what's happening in case I get other developers to help in the 
> future.

Using properties in this way is accepted practice.

Kent

From rikard.bosnjakovic at gmail.com  Tue Apr 24 18:52:48 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 24 Apr 2007 18:52:48 +0200
Subject: [Tutor] how to stop a function
In-Reply-To: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
References: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
Message-ID: <d9e88eaf0704240952g44e06660mbf5021f51933b8bb@mail.gmail.com>

On 4/24/07, shawn bright <nephish at gmail.com> wrote:

> is there something i can do to make this happen?

Use the keyword "return".


-- 
- Rikard - http://bos.hack.org/cv/

From alan.gauld at btinternet.com  Tue Apr 24 19:14:19 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 18:14:19 +0100
Subject: [Tutor] detecting data member changes
References: <462DA6C6.40002@gmail.com> <462DDC3A.7070300@tds.net>
	<462E13CD.1010007@gmail.com>
Message-ID: <f0ldtu$q54$1@sea.gmane.org>

"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

> Is this properties method acceptable Python form or is it more 
> proper to
> have modifying member functions like Alan said?

Properties is fine and was one of the options that I suggested.

However I didn't mean you should have modifying member
functions in the sense of set/get merthods - I actually hate
those generally!

What I meant is that, whatever a wiimote is, it should be offering
up a behaviour oriented inteface that, as a side-effect, changes
the internal leds attribute. OOP is all about abstracting some
higher level object into a set of behaviours. The attributes of an
object should only really be there to support those higher
behaviours. So what is it that a wiimote does? And how
does that behaviour affect the leds? That is the set of methods
to build. (Since I've never heard of a wiimote I have no idea
what the abstract behaviour might be!)

For example, if I build a lamp object I might have an
_isLit boolean attribute internally.
Now I could write a method to set the _isLit attribute to
True or False

lamp = Lamp()
lamp.setIsLit(True)
lamp.setIsLit(False)

And superficioally it looks like OK code that does the job.

But that's not how people intuitively think of lamps.
They light them or turn them off. So the code is better if
the Lamp class provides on/off methods that control the
_isLit attribute:

lamp = Lamp()
lamp.on()
lamp.off()

And its easier to use so there no temptaiuon to mess with the
attribute directly and I can change the _isLit type from Boolean
to a number or a string or whatever I want and the client code
is unaffected.

Thats what I mean about providing a message interface that negates
the need for users of the class to know or care about the leds 
attribute.
If you make it intuitive and easy to use the class via messages then
there is no incentive to go messing with the internals.

However if you do need direct access to a data attribute then
direct access is usually OK. If the class is primarily there to
store some bit oif data (but that should be the exception in
OOP) then you might as well offer direct access as write
get/set methods.... But if you want to ensure some kind of
behaviour is associated with the attribute then use a property
or setattr().

> Or is it really up to me on how I want to implement it?

Ultimately, it's always up to the programmer how you
implement it! :-)

But some techniques make your life a bit easier is all.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From ebbaalm at uiuc.edu  Tue Apr 24 19:16:31 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Tue, 24 Apr 2007 12:16:31 -0500
Subject: [Tutor] No return statement
Message-ID: <7a4620dc0704241016y29644742p583a0ff590bb08da@mail.gmail.com>

My apologies for asking a trivial question about programming practice.

As mentioned in the online tutorial
(http://docs.python.org/tut/node6.html#SECTION006700000000000000000),
functions which lack a return statement ('procedures') actually return "None".
For such functions, I assume it's preferred to not catch "None" in a variable.

Example:
>>> def printme(x):
	print x

Preferred function call:	
>>> printme(10)
10

Alternative (where None is caught into z):
>>> z = printme(10)
10
(And then one could print None)
>>> print z
None

From alan.gauld at btinternet.com  Tue Apr 24 19:22:17 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 18:22:17 +0100
Subject: [Tutor] scope/namespaces
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>
Message-ID: <f0lect$t38$1@sea.gmane.org>

"ammar azif" <ceasar102 at yahoo.com> wrote 

> Something in python disturbs me ,
> 
> when i write a for loop, i am able to access the variable 
> declared in that loop after the loop finishes which i am 
> not able to do in languages like c/c++ or java. 

That's a very recent change to C/C++ (1999 apparently), 
you used to be able to do that. In fact I hadn't realised that 
you couldn't any more! It was only when I wrote a test 
program I discovered you were right...

> Is it different in python?

Yes. Once you create a name within a scope it stays 
there and loops or code blocks are not a separate scope 
in Python 

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




From alan.gauld at btinternet.com  Tue Apr 24 19:27:37 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 18:27:37 +0100
Subject: [Tutor] scope/namespaces
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>	<462DDD42.3030806@tds.net><eb90f15e0704240605k5db5d72amd85318375616cf1f@mail.gmail.com>
	<462E039A.7070202@tds.net>
Message-ID: <f0lems$v2i$1@sea.gmane.org>

> Ezra Taylor wrote:
>>                     How can we limit this functionality so that 
>> python
>> behaves similar to other know languages.

There are many other languages that work like Python.
Including the original versions of C and C++...

And other languages that don't have explicit loop constructs
at all! Others only have while loops...

> Maybe I should be asking what
> are the benifits of allow variables not being bound to a block of 
> code.

For one thing you can find out how far a loop got to if it was
exited via a break.

for n in range(25):
    if doit(item[n]) == False: break

print 'The loop stopped at item', n

There are lots of things that languages do differently, otherwise
there would be no point in having different languages! Embrace
the differences as an opportunity to see things differently. ;-)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From jeffreythurley at gmail.com  Tue Apr 24 19:29:16 2007
From: jeffreythurley at gmail.com (J.T. Hurley)
Date: Tue, 24 Apr 2007 13:29:16 -0400
Subject: [Tutor] Clarification on Debugging under IDLE
Message-ID: <7a0ef750704241029t2e194919u63781c159b6212b6@mail.gmail.com>

On the debug control, what is the difference between "go," over," and "out?"

Thank you,

J.T.

From alan.gauld at btinternet.com  Tue Apr 24 19:49:03 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 18:49:03 +0100
Subject: [Tutor] Exceptions while dealing with MySQL
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com><f0e52e$smh$1@sea.gmane.org>
	<004501c784fa$a46e9730$fefea8c0@haengma><462BAB9B.8080007@tds.net>
	<f0gpfo$c02$1@sea.gmane.org>
	<4dcb3660704240924n60865a0ayf8fc6d0ce0017312@mail.gmail.com>
Message-ID: <f0lfv2$6k2$1@sea.gmane.org>


"Thanos Panousis" <pthanos at gmail.com> wrote

> data. Say for each person object, I need an object variable called
> "hairColor". This haircolor variable has to be filled through an SQL
> query, so the object must have some way to access a database cursor.
> The cool thing would be that all person objects use the same
> connection/cursor to get their haircolors filled in, so there would 
> be
> only one connection to the SQL server.
>
> Could this  done with a class variable? From what I understand, it
> fits nice because its available to all objects of the class,

Absolutely and that would be a good choice provided you don't
need connections/cursors from each class to the same database.
If that's the case you may prefer to create the connection globally
and pass a reference into your classes via init.

Alan G. 



From andreengels at gmail.com  Tue Apr 24 20:00:25 2007
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 24 Apr 2007 20:00:25 +0200
Subject: [Tutor] No return statement
In-Reply-To: <7a4620dc0704241016y29644742p583a0ff590bb08da@mail.gmail.com>
References: <7a4620dc0704241016y29644742p583a0ff590bb08da@mail.gmail.com>
Message-ID: <6faf39c90704241100p15b950aaid458750caee68ce@mail.gmail.com>

My opinion is that one should not create or set a variable if its
value is not used. In the case mentioned, you know what the return
value will be, so there seems to be no reason to keep it.

2007/4/24, Cecilia Alm <ebbaalm at uiuc.edu>:
> My apologies for asking a trivial question about programming practice.
>
> As mentioned in the online tutorial
> (http://docs.python.org/tut/node6.html#SECTION006700000000000000000),
> functions which lack a return statement ('procedures') actually return "None".
> For such functions, I assume it's preferred to not catch "None" in a variable.
>
> Example:
> >>> def printme(x):
>         print x
>
> Preferred function call:
> >>> printme(10)
> 10
>
> Alternative (where None is caught into z):
> >>> z = printme(10)
> 10
> (And then one could print None)
> >>> print z
> None
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels

From kent37 at tds.net  Tue Apr 24 20:01:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 14:01:19 -0400
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <4dcb3660704240924n60865a0ayf8fc6d0ce0017312@mail.gmail.com>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>	<f0e52e$smh$1@sea.gmane.org>
	<004501c784fa$a46e9730$fefea8c0@haengma>	<462BAB9B.8080007@tds.net>
	<f0gpfo$c02$1@sea.gmane.org>
	<4dcb3660704240924n60865a0ayf8fc6d0ce0017312@mail.gmail.com>
Message-ID: <462E45EF.7060608@tds.net>

Thanos Panousis wrote:
> I have an object, person, which is assosiated with some statistical
> data. Say for each person object, I need an object variable called
> "hairColor". This haircolor variable has to be filled through an SQL
> query, so the object must have some way to access a database cursor.
> The cool thing would be that all person objects use the same
> connection/cursor to get their haircolors filled in, so there would be
> only one connection to the SQL server.
> 
> Could this  done with a class variable? From what I understand, it
> fits nice because its available to all objects of the class, and it is
> unique. So would this be a nice way to have objects of the same class
> share a "pipe" to the sql database?

Perhaps you should look into object-relational mappers such as SQLObject 
or SQLAlchemy.

Kent

From alan.gauld at btinternet.com  Tue Apr 24 20:02:13 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 19:02:13 +0100
Subject: [Tutor] scope/namespaces
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>
	<f0lect$t38$1@sea.gmane.org>
Message-ID: <f0lgnp$bot$1@sea.gmane.org>

Correcting my own post!

"Alan Gauld" <alan.gauld at btinternet.com> wrote 

> That's a very recent change to C/C++ (1999 apparently), 

Actually only a recent change in C. Its always been true of C++.
But in C up until recently(*) you couldn't define a loop
variable in the loop it had to be outside:

int x;
for (x=0;....)

(*)I'm not sure whether the C++ style loop definition was 
introduced in the original ANSI standard or the later 
revision (none of my books malke it clear), but I think it was 
the revision.

But C++ always had loop variables as part of block scope.

Sory for any confusion,

Alan G.




From ebbaalm at uiuc.edu  Tue Apr 24 20:05:10 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Tue, 24 Apr 2007 13:05:10 -0500
Subject: [Tutor] No return statement
In-Reply-To: <6faf39c90704241100p15b950aaid458750caee68ce@mail.gmail.com>
References: <7a4620dc0704241016y29644742p583a0ff590bb08da@mail.gmail.com>
	<6faf39c90704241100p15b950aaid458750caee68ce@mail.gmail.com>
Message-ID: <7a4620dc0704241105k485e047t3e4e41d425674372@mail.gmail.com>

OK, that's my opinion too.

Thanks!

2007/4/24, Andre Engels <andreengels at gmail.com>:
> My opinion is that one should not create or set a variable if its
> value is not used. In the case mentioned, you know what the return
> value will be, so there seems to be no reason to keep it.
>
> 2007/4/24, Cecilia Alm <ebbaalm at uiuc.edu>:
> > My apologies for asking a trivial question about programming practice.
> >
> > As mentioned in the online tutorial
> > (http://docs.python.org/tut/node6.html#SECTION006700000000000000000),
> > functions which lack a return statement ('procedures') actually return "None".
> > For such functions, I assume it's preferred to not catch "None" in a variable.
> >
> > Example:
> > >>> def printme(x):
> >         print x
> >
> > Preferred function call:
> > >>> printme(10)
> > 10
> >
> > Alternative (where None is caught into z):
> > >>> z = printme(10)
> > 10
> > (And then one could print None)
> > >>> print z
> > None
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> --
> Andre Engels, andreengels at gmail.com
> ICQ: 6260644  --  Skype: a_engels
>


-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

From kent37 at tds.net  Tue Apr 24 20:05:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 14:05:15 -0400
Subject: [Tutor] Clarification on Debugging under IDLE
In-Reply-To: <7a0ef750704241029t2e194919u63781c159b6212b6@mail.gmail.com>
References: <7a0ef750704241029t2e194919u63781c159b6212b6@mail.gmail.com>
Message-ID: <462E46DB.7080406@tds.net>

J.T. Hurley wrote:
> On the debug control, what is the difference between "go," over," and "out?"

What debug control are you using?

Debuggers usually have three kinds of stepping. The names vary but the 
concepts are the same:

step in - execute the next line of code; if it is a subroutine call, 
stop at the first line of code in the subroutine

step over - execute the next line of code; if it is a subroutine call, 
execute the entire subroutine and stop at the line of code after the call

step out - execute the current subroutine until reaching a return statement

Kent

From alan.gauld at btinternet.com  Tue Apr 24 20:09:15 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 19:09:15 +0100
Subject: [Tutor] Clarification on Debugging under IDLE
References: <7a0ef750704241029t2e194919u63781c159b6212b6@mail.gmail.com>
Message-ID: <f0lh4u$eg4$1@sea.gmane.org>


"J.T. Hurley" <jeffreythurley at gmail.com> wrote

> On the debug control, what is the difference between "go," over," 
> and "out?"

Cabeat, I haven't checked, but from memory:

go = Run the program from the current point onwards
until you hit the next break point or until it ends.

over = step over the function on the current line
(ie don't step into it)

out = run the rest of the function and stop when
you exit it back to the level above. Often used to fix
an accidental step-into

Alan G. 



From alan.gauld at btinternet.com  Tue Apr 24 20:05:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 19:05:59 +0100
Subject: [Tutor] No return statement
References: <7a4620dc0704241016y29644742p583a0ff590bb08da@mail.gmail.com>
Message-ID: <f0lgur$d6n$1@sea.gmane.org>

"Cecilia Alm" <ebbaalm at uiuc.edu> wrote

> functions which lack a return statement ('procedures') actually 
> return "None".
> For such functions, I assume it's preferred to not catch "None" in a 
> variable.

You can catch it if you like, but since functions with no return
*always* return None there is little point. You know what the
value will be before you even call the function.

Where catching the value is more important is where the function
only has some return statements:

def f(x):
   if x: return 42

Now f() returns None if x is not True so it makers sense to
catch the reurn value and test for None.

But such a function style is very bad practice IMHO!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From bensherman at gmail.com  Tue Apr 24 20:14:18 2007
From: bensherman at gmail.com (Ben Sherman)
Date: Tue, 24 Apr 2007 14:14:18 -0400
Subject: [Tutor] scope/namespaces
In-Reply-To: <f0lgnp$bot$1@sea.gmane.org>
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>
	<f0lect$t38$1@sea.gmane.org> <f0lgnp$bot$1@sea.gmane.org>
Message-ID: <5a56471e0704241114x24d42734s81240b0526254f54@mail.gmail.com>

Am I wrong in my memory?  When I was a wee lad prior to 99 for sure),
I thought I would initialize my loops with:

for (int x=0; x <10; x++) {
}

I am rapidly veering off topic.


On 4/24/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> Correcting my own post!
>
> "Alan Gauld" <alan.gauld at btinternet.com> wrote
>
> > That's a very recent change to C/C++ (1999 apparently),
>
> Actually only a recent change in C. Its always been true of C++.
> But in C up until recently(*) you couldn't define a loop
> variable in the loop it had to be outside:
>
> int x;
> for (x=0;....)
>
> (*)I'm not sure whether the C++ style loop definition was
> introduced in the original ANSI standard or the later
> revision (none of my books malke it clear), but I think it was
> the revision.
>
> But C++ always had loop variables as part of block scope.
>
> Sory for any confusion,
>
> Alan G.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From pthanos at gmail.com  Tue Apr 24 20:15:46 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Tue, 24 Apr 2007 20:15:46 +0200
Subject: [Tutor] Exceptions while dealing with MySQL
In-Reply-To: <462E45EF.7060608@tds.net>
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com>
	<f0e52e$smh$1@sea.gmane.org> <004501c784fa$a46e9730$fefea8c0@haengma>
	<462BAB9B.8080007@tds.net> <f0gpfo$c02$1@sea.gmane.org>
	<4dcb3660704240924n60865a0ayf8fc6d0ce0017312@mail.gmail.com>
	<462E45EF.7060608@tds.net>
Message-ID: <4dcb3660704241115j75315a5bkceda6644eb075e3d@mail.gmail.com>

I checked the SQLAlchemy and SQLObject projects, but they are not
really relevant to what I am doing(moreover they are more than I can
chew just yet:).

I managed to get a class variable to hold a cursor via something like

class person:
    cursor = MySQLdb.connect(stuff).cursor()

BUT when I make a function inside my class called myConnect, where I
do error checking and so on, I can't make it work:

class person:
    cursor = myConnect()

    __init(self)___:
        more things here....

   myConnect(self):
       try:
             return MySQLdb.connect(stuff).cursor()
       catch:
              print "Error!"

When trying to run this I get NameError: name 'myConnect' is not
defined. Any pointers for my OO-blindness?

Thanks a lot...


On 4/24/07, Kent Johnson <kent37 at tds.net> wrote:
> Thanos Panousis wrote:
> > I have an object, person, which is assosiated with some statistical
> > data. Say for each person object, I need an object variable called
> > "hairColor". This haircolor variable has to be filled through an SQL
> > query, so the object must have some way to access a database cursor.
> > The cool thing would be that all person objects use the same
> > connection/cursor to get their haircolors filled in, so there would be
> > only one connection to the SQL server.
> >
> > Could this  done with a class variable? From what I understand, it
> > fits nice because its available to all objects of the class, and it is
> > unique. So would this be a nice way to have objects of the same class
> > share a "pipe" to the sql database?
>
> Perhaps you should look into object-relational mappers such as SQLObject
> or SQLAlchemy.
>
> Kent
>

From jeffreythurley at gmail.com  Tue Apr 24 21:45:17 2007
From: jeffreythurley at gmail.com (J.T. Hurley)
Date: Tue, 24 Apr 2007 15:45:17 -0400
Subject: [Tutor] Clarification on Debugging under IDLE
In-Reply-To: <f0lh4u$eg4$1@sea.gmane.org>
References: <7a0ef750704241029t2e194919u63781c159b6212b6@mail.gmail.com>
	<f0lh4u$eg4$1@sea.gmane.org>
Message-ID: <7a0ef750704241245y24dd3f1bx534bacb55580341@mail.gmail.com>

Kent: I'm using IDLE's built-in debugger.

Alan: I just tried it out, and you were spot-on.

Thank you both for your assistance. I think I've got the hang of it
now. It'll certainly speed me up now that I don't have to step through
each function.

Thanks again,

J.T.

From alan.gauld at btinternet.com  Tue Apr 24 22:06:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 21:06:29 +0100
Subject: [Tutor] Exceptions while dealing with MySQL
References: <4dcb3660704210639w15821fc2k6e4a774272ec4f7e@mail.gmail.com><f0e52e$smh$1@sea.gmane.org>
	<004501c784fa$a46e9730$fefea8c0@haengma><462BAB9B.8080007@tds.net>
	<f0gpfo$c02$1@sea.gmane.org><4dcb3660704240924n60865a0ayf8fc6d0ce0017312@mail.gmail.com><462E45EF.7060608@tds.net>
	<4dcb3660704241115j75315a5bkceda6644eb075e3d@mail.gmail.com>
Message-ID: <f0lo0p$vee$1@sea.gmane.org>

"Thanos Panousis" <pthanos at gmail.com> wrote in

> I managed to get a class variable to hold a cursor via something 
> like
>
> class person:
>    cursor = MySQLdb.connect(stuff).cursor()
>
> BUT when I make a function inside my class called myConnect, where I
> do error checking and so on, I can't make it work:

Your Python OOP is a bit mixed up here.

> class person:
>    cursor = myConnect()
>
>    __init(self)___:
>        more things here....

You need to add def statements and the underscores
come before the parens

      def __init__(self)

>   myConnect(self):

Similarly here. BUT this is an instance method (via the self 
parameter),
it will not work at the class level.

>       try:
>             return MySQLdb.connect(stuff).cursor()
>       catch:

And this should be except not catch...

>              print "Error!"

> When trying to run this I get NameError: name 'myConnect' is not
> defined. Any pointers for my OO-blindness?

You can just make the connect call directly at the class level.

class Person:
     cursor = MySQLdb.connect(...).cursor()

You can then access it in your objects methods using either

self.cursor
or
Person.cursor

Personally I prefer the second since it makes it clear its a
class variable...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From rschroev_nospam_ml at fastmail.fm  Tue Apr 24 22:12:38 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Tue, 24 Apr 2007 22:12:38 +0200
Subject: [Tutor] scope/namespaces
In-Reply-To: <5a56471e0704241114x24d42734s81240b0526254f54@mail.gmail.com>
References: <152601.97522.qm@web56107.mail.re3.yahoo.com>	<f0lect$t38$1@sea.gmane.org>
	<f0lgnp$bot$1@sea.gmane.org>
	<5a56471e0704241114x24d42734s81240b0526254f54@mail.gmail.com>
Message-ID: <f0lobn$6o7$1@sea.gmane.org>

Ben Sherman schreef:
> Am I wrong in my memory?  When I was a wee lad prior to 99 for sure),
> I thought I would initialize my loops with:
> 
> for (int x=0; x <10; x++) {
> }

If that was in C, it must have been a special feature of your compiler.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven


From alan.gauld at btinternet.com  Tue Apr 24 22:12:50 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Apr 2007 21:12:50 +0100
Subject: [Tutor] scope/namespaces
References: <152601.97522.qm@web56107.mail.re3.yahoo.com><f0lect$t38$1@sea.gmane.org>
	<f0lgnp$bot$1@sea.gmane.org>
	<5a56471e0704241114x24d42734s81240b0526254f54@mail.gmail.com>
Message-ID: <f0locm$9vi$1@sea.gmane.org>

"Ben Sherman" <bensherman at gmail.com> wrote

> Am I wrong in my memory?  When I was a wee lad prior to 99 for 
> sure),
> I thought I would initialize my loops with:
>
> for (int x=0; x <10; x++) {

You certainly could in C++ but I'm less sure about C.
You certainly couldn't do that in C prior to ANSI C
(in 1991/2?). However I don't think the C++ bits got
incorporated into C until the C update in '99. However
that didn't stop some compilers supporting them.
For example the C++ // comment style was supported
by most ANSI compilers even though it wasn't in the
original ANSI standard.

> I am rapidly veering off topic.

Me too :-)

Alan G.
Who hasn't used vanilla C in anger for at least 10 years!
(And C++ for 4 or 5...)





From kent37 at tds.net  Tue Apr 24 20:45:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 24 Apr 2007 14:45:13 -0400
Subject: [Tutor] Clarification on Debugging under IDLE
In-Reply-To: <462E46DB.7080406@tds.net>
References: <7a0ef750704241029t2e194919u63781c159b6212b6@mail.gmail.com>
	<462E46DB.7080406@tds.net>
Message-ID: <462E5039.50402@tds.net>

Kent Johnson wrote:
> J.T. Hurley wrote:
>> On the debug control, what is the difference between "go," over," and "out?"
> 
> What debug control are you using?
> 
> Debuggers usually have three kinds of stepping. The names vary but the 
> concepts are the same:
> 
> step in - execute the next line of code; if it is a subroutine call, 
> stop at the first line of code in the subroutine
> 
> step over - execute the next line of code; if it is a subroutine call, 
> execute the entire subroutine and stop at the line of code after the call
> 
> step out - execute the current subroutine until reaching a return statement

I should add

go/continue/run - run until a breakpoint is hit, or the program ends

run to cursor - set a temp breakpoint at the line containing the cursor, 
then go

From pthanos at gmail.com  Wed Apr 25 09:42:09 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Wed, 25 Apr 2007 09:42:09 +0200
Subject: [Tutor] Custom objects throw what exception?
Message-ID: <4dcb3660704250042n52455f68he56be797777c67cc@mail.gmail.com>

The tutor list is definately helping me perform my OO-python babysteps.

I want to ask this. Say I have some objects of my own, and using the
example I posted in a previous post, say I have a person object with a
instance variable called hairColor.

The hairColor property is set via an exotic function that could go
wrong and produce an exception.

How should I hanlde this? Should I catch the exception in the
person.__init__(self,color) "construtor"? and if I do so, what happens
the code that is waiting for a person object to arrive with a call
like p = person(). What exception should the person class throw, if
any?

From mail at sphinx.net.ru  Tue Apr 24 17:12:03 2007
From: mail at sphinx.net.ru (Dmitry Dzhus)
Date: Tue, 24 Apr 2007 19:12:03 +0400
Subject: [Tutor] how to stop a function
In-Reply-To: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
	(shawn bright's message of "Tue\, 24 Apr 2007 10\:04\:33 -0500")
References: <384c93600704240804u28db8f1el647891ca9d643e83@mail.gmail.com>
Message-ID: <873b2pn6ws.fsf@sphinx.net.ru>


Maybe `return`?

-- 
Happy Hacking.

Dmitry "Sphinx" Dzhus
http://sphinx.net.ru

From kent37 at tds.net  Wed Apr 25 15:25:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 25 Apr 2007 09:25:47 -0400
Subject: [Tutor] Custom objects throw what exception?
In-Reply-To: <4dcb3660704250042n52455f68he56be797777c67cc@mail.gmail.com>
References: <4dcb3660704250042n52455f68he56be797777c67cc@mail.gmail.com>
Message-ID: <462F56DB.1030901@tds.net>

Thanos Panousis wrote:
> The tutor list is definately helping me perform my OO-python babysteps.
> 
> I want to ask this. Say I have some objects of my own, and using the
> example I posted in a previous post, say I have a person object with a
> instance variable called hairColor.
> 
> The hairColor property is set via an exotic function that could go
> wrong and produce an exception.
> 
> How should I hanlde this? Should I catch the exception in the
> person.__init__(self,color) "construtor"? and if I do so, what happens
> the code that is waiting for a person object to arrive with a call
> like p = person(). What exception should the person class throw, if
> any?

Don't hide the exception. If you can intelligently *handle* the 
exception and create a person object that is initialized in a reasonable 
way, do so. Otherwise let some kind of exception propagate back to the 
caller so they know there is a problem.

If you catch the exception in person.__init__() then the code that calls 
person() will get whatever person object you create. The caller will not 
know that there was a problem with the color.

A ValueError might be appropriate. You can also define your own 
exception for example
   class HairColorError(Exception): pass

then in your code you can
   raise HairColorError('%s is not a valid hair color' % color)

Kent

From kerravon at gmail.com  Wed Apr 25 18:22:50 2007
From: kerravon at gmail.com (Alex Dering)
Date: Wed, 25 Apr 2007 12:22:50 -0400
Subject: [Tutor] 100 Programs?
Message-ID: <198cd5f0704250922m763a2314t9a18d3543eb9a06c@mail.gmail.com>

Can anyone recommend a list of progressively harder Python programming
assignments for the self-learner?

My suspicion is that if I arrive at a point where I am proficient in Python,
I still won't trust myself to be the judge of that. So I'm trying to get a
list of specific tasks/problems/projects (with expected time requirements)
that would allow me to say "Well, I did that in 2 hours 20 minutes and the
expected time to complete it was 2 hours 30 minutes, so I'm at least
*that*skilled."

Example:
Beginner Level
Each of these should take someone who knows what he or she is doing one
session of less than an hour to complete. These should try to combine
several simple tasks, but not to the point of hopelessly confusing the
programmer. As an example, when I took calculus, the teacher would delight
in saying, "Now, let's take the derivative of a simple function, say, x
cubed raised to the ln of e raised to the negative x times sin x squared." I
don't need to be shown I don't know everything; I already know that.

Intermediate Level
These should take a proficient intermediate between 1 hour and 3 hours each.

Advanced Level
These should be expected to require at least 3 hours and possibly up to a
week. These should be programs that a single programmer is capable of doing.
And -- yes, and -- these should be portfolio-worthy. Items that, when you
start looking for a job or a freelance assignment, you can point to and
actually get some sort of respect for.

Many thanks for all help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070425/74483b49/attachment.html 

From rohan.deshpande at gmail.com  Wed Apr 25 18:40:22 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Wed, 25 Apr 2007 17:40:22 +0100
Subject: [Tutor] 100 Programs?
In-Reply-To: <198cd5f0704250922m763a2314t9a18d3543eb9a06c@mail.gmail.com>
References: <198cd5f0704250922m763a2314t9a18d3543eb9a06c@mail.gmail.com>
Message-ID: <e5a6f5430704250940s6d450918ub1708d7a268919f@mail.gmail.com>

Well there's always pythonchallenge.com, but it's both a riddle and a
programming exercise.  And, they're not entirely python specific (except for
a couple), but it's a start.

-Rohan

On 4/25/07, Alex Dering <kerravon at gmail.com> wrote:
>
> Can anyone recommend a list of progressively harder Python programming
> assignments for the self-learner?
>
> My suspicion is that if I arrive at a point where I am proficient in
> Python, I still won't trust myself to be the judge of that. So I'm trying to
> get a list of specific tasks/problems/projects (with expected time
> requirements) that would allow me to say "Well, I did that in 2 hours 20
> minutes and the expected time to complete it was 2 hours 30 minutes, so I'm
> at least *that* skilled."
>
> Example:
> Beginner Level
> Each of these should take someone who knows what he or she is doing one
> session of less than an hour to complete. These should try to combine
> several simple tasks, but not to the point of hopelessly confusing the
> programmer. As an example, when I took calculus, the teacher would delight
> in saying, "Now, let's take the derivative of a simple function, say, x
> cubed raised to the ln of e raised to the negative x times sin x squared." I
> don't need to be shown I don't know everything; I already know that.
>
> Intermediate Level
> These should take a proficient intermediate between 1 hour and 3 hours
> each.
>
> Advanced Level
> These should be expected to require at least 3 hours and possibly up to a
> week. These should be programs that a single programmer is capable of doing.
> And -- yes, and -- these should be portfolio-worthy. Items that, when you
> start looking for a job or a freelance assignment, you can point to and
> actually get some sort of respect for.
>
> Many thanks for all help.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070425/3668645e/attachment.htm 

From washakie at gmail.com  Wed Apr 25 21:47:26 2007
From: washakie at gmail.com (John Washakie)
Date: Wed, 25 Apr 2007 21:47:26 +0200
Subject: [Tutor] best search/replace method?
Message-ID: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>

Folks,

I'm writing a program which will read in an html file, and then
replace certain elements, such as the title, and various paths defined
for images. I can make a 'source' file with ImagePathReplaceMe and
TitleReplaceMe text in it, then search for that and replace it. With
sed my script would be three lines:

cat raw.html |
sed 's/ImagePathReplaceMe/NewPathToImage/g' |
sed 's/TitleReplaceMe/NewTitle/g' > new.html

However, this is going to be part of an Plone product so I want to use
Python. What is the best method to accomplish this?

Thanks,
john

From rikard.bosnjakovic at gmail.com  Wed Apr 25 22:21:48 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 25 Apr 2007 22:21:48 +0200
Subject: [Tutor] best search/replace method?
In-Reply-To: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>
References: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>
Message-ID: <d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>

On 4/25/07, John Washakie <washakie at gmail.com> wrote:

> cat raw.html |
> sed 's/ImagePathReplaceMe/NewPathToImage/g' |
> sed 's/TitleReplaceMe/NewTitle/g' > new.html

One line's sufficient:

sed -e 's/ImagePathReplaceMe/NewPathToImage/g;s/TitleReplaceMe/NewTitle/g'
raw.html > new.html

> However, this is going to be part of an Plone product so I want to use
> Python. What is the best method to accomplish this?

d = open("raw.html").read()
d.replace("ImagePathReplaceMe", "NewPathToImage")
d.replace("TitleReplaceMe", "TitleReplaceMe")
x = open("new.html", "w")
x.write(d)
x.close()

Untested.


-- 
- Rikard - http://bos.hack.org/cv/

From washakie at gmail.com  Wed Apr 25 23:20:11 2007
From: washakie at gmail.com (John Washakie)
Date: Wed, 25 Apr 2007 23:20:11 +0200
Subject: [Tutor] best search/replace method?
In-Reply-To: <d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>
References: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>
	<d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>
Message-ID: <aaf235960704251420r3928f11eo7704518158cab4f7@mail.gmail.com>

Tested. Failed...

I thought it would be something like that, but that doesn't work..
perhaps because 'ImagePathReplaceMe' isn't separate from the rest of
the path??? Maybe replace has some options... I'll look into that.

.

On 4/25/07, Rikard Bosnjakovic <rikard.bosnjakovic at gmail.com> wrote:
> On 4/25/07, John Washakie <washakie at gmail.com> wrote:
>
> > cat raw.html |
> > sed 's/ImagePathReplaceMe/NewPathToImage/g' |
> > sed 's/TitleReplaceMe/NewTitle/g' > new.html
>
> One line's sufficient:
>
> sed -e 's/ImagePathReplaceMe/NewPathToImage/g;s/TitleReplaceMe/NewTitle/g'
> raw.html > new.html
>
> > However, this is going to be part of an Plone product so I want to use
> > Python. What is the best method to accomplish this?
>
> d = open("raw.html").read()
> d.replace("ImagePathReplaceMe", "NewPathToImage")
> d.replace("TitleReplaceMe", "TitleReplaceMe")
> x = open("new.html", "w")
> x.write(d)
> x.close()
>
> Untested.
>
>
> --
> - Rikard - http://bos.hack.org/cv/
>

From rabidpoobear at gmail.com  Wed Apr 25 23:30:14 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 25 Apr 2007 16:30:14 -0500
Subject: [Tutor] best search/replace method?
In-Reply-To: <d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>
References: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>
	<d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>
Message-ID: <462FC866.3080006@gmail.com>

Rikard Bosnjakovic wrote:
> On 4/25/07, John Washakie <washakie at gmail.com> wrote:
>
>   
>> cat raw.html |
>> sed 's/ImagePathReplaceMe/NewPathToImage/g' |
>> sed 's/TitleReplaceMe/NewTitle/g' > new.html
>>     
>
> One line's sufficient:
>
> sed -e 's/ImagePathReplaceMe/NewPathToImage/g;s/TitleReplaceMe/NewTitle/g'
> raw.html > new.html
>
>   
>> However, this is going to be part of an Plone product so I want to use
>> Python. What is the best method to accomplish this?
>>     
>
> d = open("raw.html").read()
> d.replace("ImagePathReplaceMe", "NewPathToImage")
> d.replace("TitleReplaceMe", "TitleReplaceMe")
>   
replace isn't a modifying function, so you'd have to do something like this:
d = open("raw.html").read()
x = open("new.html","w")
x.write(d.replace("ImagePathReplaceMe", 
"NewPathToImage").replace("TitleReplaceMe", "TitleReplaceMe"))
x.close()

or just store the strings after replacement in a temporary variable.
> x = open("new.html", "w")
> x.write(d)
> x.close()
>
> Untested.
>
>
>   


From rabidpoobear at gmail.com  Wed Apr 25 23:31:30 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 25 Apr 2007 16:31:30 -0500
Subject: [Tutor] best search/replace method?
In-Reply-To: <aaf235960704251420r3928f11eo7704518158cab4f7@mail.gmail.com>
References: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>	<d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>
	<aaf235960704251420r3928f11eo7704518158cab4f7@mail.gmail.com>
Message-ID: <462FC8B2.6010906@gmail.com>

John Washakie wrote:
> Tested. Failed...
>
> I thought it would be something like that, but that doesn't work..
> perhaps because 'ImagePathReplaceMe' isn't separate from the rest of
> the path???
It doesn't matter what surrounds the string to be replaced in the target 
string.
Refer to my other e-mail on why Rikard's didn't work.
-Luke

From washakie at gmail.com  Wed Apr 25 23:38:44 2007
From: washakie at gmail.com (John Washakie)
Date: Wed, 25 Apr 2007 23:38:44 +0200
Subject: [Tutor] best search/replace method?
In-Reply-To: <462FC8B2.6010906@gmail.com>
References: <aaf235960704251247h7d3e1fd5r34ca3f956d6edffe@mail.gmail.com>
	<d9e88eaf0704251321s6e20b051ycc2d80fafc63b5e9@mail.gmail.com>
	<aaf235960704251420r3928f11eo7704518158cab4f7@mail.gmail.com>
	<462FC8B2.6010906@gmail.com>
Message-ID: <aaf235960704251438t65308a55ledb003a3e5ee8136@mail.gmail.com>

Excellent. Thanks Luke, that seems to be working....

On 4/25/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> John Washakie wrote:
> > Tested. Failed...
> >
> > I thought it would be something like that, but that doesn't work..
> > perhaps because 'ImagePathReplaceMe' isn't separate from the rest of
> > the path???
> It doesn't matter what surrounds the string to be replaced in the target
> string.
> Refer to my other e-mail on why Rikard's didn't work.
> -Luke
>

From nswitanek at stanford.edu  Thu Apr 26 03:36:18 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Wed, 25 Apr 2007 18:36:18 -0700
Subject: [Tutor] python internet archive API?
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF20364A169@gsb-exchmb02.stanford.edu>

I'm a novice Python programmer, and I've been looking for a way to
collect archived web pages. I would like to use the data on Internet
Archive, via the "Wayback Machine". Look, for example, at
http://web.archive.org/web/*/http://www.python.org
<http://web.archive.org/web/*/http:/www.python.org> . I'd like to crawl
down the first few levels of links of each of the updated archived pages
(the ones with *'s next to them). The site's robots.txt exclusions are
complete, so a screen-scraping strategy doesn't seem doable. 

 

Does anyone have any suggestions for a way to go about this
pythonically? 

 

Many thanks,

Nick

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070425/090df5d8/attachment.htm 

From nswitanek at stanford.edu  Thu Apr 26 04:06:55 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Wed, 25 Apr 2007 19:06:55 -0700
Subject: [Tutor] sys.path, managing modules and packages
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF20364A16E@gsb-exchmb02.stanford.edu>

Can someone help me better understand how I ought to manage the modules
and packages that I download? I often find that I can't use the code
I've just downloaded, despite putting it into Lib/site-packages. Often
I've added the subdirectory path via sys.path.append, but this seems to
go only one level down, whereas I thought that when trying to import
something python would search all subdirectories of the directories in
the sys.path. I'd be glad for some basic instruction on the steps I need
to take between downloading code from sourceforge and importing the
functions in my scripts or at the command line.

 

Thanks,

Nick

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070425/dc041557/attachment.htm 

From carroll at tjc.com  Thu Apr 26 05:58:20 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 25 Apr 2007 20:58:20 -0700 (PDT)
Subject: [Tutor] Averaging a list of lists with a listcomp?
Message-ID: <Pine.LNX.4.44.0704252044390.20666-100000@violet.rahul.net>

I have a list (of arbitrary length) of lists, each sublist having a fixed
number N of items, all integers.

I would like to produce a list of N items, each item of which is an 
integer which is the average of the elements in the same position of each 
of the sublists of the original list.

I realize the wording above is all hash, so here's the example:

Say the original list is: [[10, 20, 30], [50, 20, 90], [30, 20, 30]]

I want the new list to be: [30, 20, 50]

Because the average of the first elements 10, 50, 30 is 30; second 
elements 20, 20, 20 is 20; and third elements 30, 90, 30 is 50.

Since I'm taking a list and producing another list, I figured this would 
be a good candidate for a list comprehension; but I don't see a good 
approach. 

My attempt is below, but I can see the list comp approach is pretty yucky.  
As you can see, I've got a working solution, but in an effort to think 
more pythonically about list comprehensions, I'd like to see what a good 
list comprehension approach is.

(note: I know there's an integer division issue here; ignore that, I just 
picked easy numbers to keep the example clean.)

My approach:

###################################
orig = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
average = [30, 20, 50]

# iterative approach
L1 = [0, 0, 0]
for item in orig:
    for i in range(0,3):
        L1[i] += item[i]
L1 = [x/len(orig) for x in L1]
print L1

#list comp approach
L2 = [
    sum([x[0] for x in orig])/len(orig),
    sum([x[1] for x in orig])/len(orig),
    sum([x[2] for x in orig])/len(orig)
    ]
#ew, yuck, hard-coded list indices!
print L2

assert L1 == L2 == average
###################################



From john at fouhy.net  Thu Apr 26 06:29:44 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 26 Apr 2007 16:29:44 +1200
Subject: [Tutor] Averaging a list of lists with a listcomp?
In-Reply-To: <Pine.LNX.4.44.0704252044390.20666-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0704252044390.20666-100000@violet.rahul.net>
Message-ID: <5e58f2e40704252129i5fd615d9s46d2c0e69486d9fa@mail.gmail.com>

On 26/04/07, Terry Carroll <carroll at tjc.com> wrote:
> I have a list (of arbitrary length) of lists, each sublist having a fixed
> number N of items, all integers.
>
> I would like to produce a list of N items, each item of which is an
> integer which is the average of the elements in the same position of each
> of the sublists of the original list.

I don't think you're going to be able to do it with a single listcomp
based on the original list.  The reason I say this is because you need
to iterate over your _entire_ list (of arbitary length) in order to
compute _each_ element of the result list.

If you want a one-line solution, your best bet is to transform your
start list: instead of [[10, 20, 30], [50, 20, 90], [30, 20, 30]],
you'd like to have [[10,50,30], [20,20,20], [30,90,30]].  Then, it
would be easy.

Well, there's actually a simple way to do this transformation.  You
can use the zip function:

>>> zip([10, 20, 30], [50, 20, 90], [30, 20, 30])
[(10, 50, 30), (20, 20, 20), (30, 90, 30)]

And we can go a step further:

>>> orig = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
>>> zip(*orig)
[(10, 50, 30), (20, 20, 20), (30, 90, 30)]

So, here is your one-line solution:

>>> [sum(x)/len(x) for x in zip(*orig)]
[30, 20, 50]

HTH! :-)

-- 
John.

From rikard.bosnjakovic at gmail.com  Thu Apr 26 07:09:55 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 26 Apr 2007 07:09:55 +0200
Subject: [Tutor] sys.path, managing modules and packages
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF20364A16E@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF20364A16E@gsb-exchmb02.stanford.edu>
Message-ID: <d9e88eaf0704252209t3651e035we458637ce93c81ad@mail.gmail.com>

On 4/26/07, Switanek, Nick <nswitanek at stanford.edu> wrote:

> Can someone help me better understand how I ought to manage the modules and
> packages that I download? I often find that I can't use the code I've just
> downloaded, despite putting it into Lib/site-packages. Often I've added the
> subdirectory path via sys.path.append, but this seems to go only one level
> down, whereas I thought that when trying to import something python would
> search all subdirectories of the directories in the sys.path. I'd be glad
> for some basic instruction on the steps I need to take between downloading
> code from sourceforge and importing the functions in my scripts or at the
> command line.

You can use the environment-variable $PYTHONPATH for localized modules
you download. I have for example PYTHONPATH=~/hacks/python/modules,
and I put all downloaded modules in there.


-- 
- Rikard - http://bos.hack.org/cv/

From rabidpoobear at gmail.com  Thu Apr 26 08:39:47 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 26 Apr 2007 01:39:47 -0500
Subject: [Tutor] python internet archive API?
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF20364A169@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF20364A169@gsb-exchmb02.stanford.edu>
Message-ID: <46304933.1080901@gmail.com>

Switanek, Nick wrote:
>
> I?m a novice Python programmer, and I?ve been looking for a way to 
> collect archived web pages. I would like to use the data on Internet 
> Archive, via the ?Wayback Machine?. Look, for example, at 
> http://web.archive.org/web/*/http://www.python.org 
> <http://web.archive.org/web/*/http:/www.python.org>. I?d like to crawl 
> down the first few levels of links of each of the updated archived 
> pages (the ones with *?s next to them). The site?s robots.txt 
> exclusions are complete, so a screen-scraping strategy doesn?t seem 
> doable.
>
What does the robots.txt have to do with anything?
Just ignore it.
If the robots.txt is telling you not to do something, you know that they 
don't want you to do it.
But if have a valid reason, just do it anyway.
>
> Does anyone have any suggestions for a way to go about this pythonically?
>
> Many thanks,
>
> Nick
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From carroll at tjc.com  Thu Apr 26 09:09:18 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 26 Apr 2007 00:09:18 -0700 (PDT)
Subject: [Tutor] Averaging a list of lists with a listcomp?
In-Reply-To: <5e58f2e40704252129i5fd615d9s46d2c0e69486d9fa@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0704260007250.3771-100000@violet.rahul.net>

On Thu, 26 Apr 2007, John Fouhy wrote:

> So, here is your one-line solution:
> 
> >>> [sum(x)/len(x) for x in zip(*orig)]
> [30, 20, 50]

Beautiful.  Thanks.

I wasn't looking for a one-liner, exactly, but just something that was 
more straightforward and pythonic than what I was doing.  But I find that 
that's often what one-liners are, as long as they aren't one-liners for 
one-linerness's sake!


From andreas at kostyrka.org  Thu Apr 26 09:14:15 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 26 Apr 2007 09:14:15 +0200
Subject: [Tutor] Averaging a list of lists with a listcomp?
In-Reply-To: <Pine.LNX.4.44.0704252044390.20666-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0704252044390.20666-100000@violet.rahul.net>
Message-ID: <20070426071415.GC20140@andi-lap.la.revver.com>

* Terry Carroll <carroll at tjc.com> [070426 07:14]:
> I have a list (of arbitrary length) of lists, each sublist having a fixed
> number N of items, all integers.
> 
> I would like to produce a list of N items, each item of which is an 
> integer which is the average of the elements in the same position of each 
> of the sublists of the original list.
> 
> I realize the wording above is all hash, so here's the example:
> 
> Say the original list is: [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
> 
> I want the new list to be: [30, 20, 50]

Something like this?
>>> src = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
>>> [sum(x)/len(x) for x in zip(*src)]
[30, 20, 50]

Andreas

From coollikestevie at gmail.com  Thu Apr 26 09:53:17 2007
From: coollikestevie at gmail.com (Stevie Broadfoot)
Date: Thu, 26 Apr 2007 17:53:17 +1000
Subject: [Tutor] Feeding a list into a function as arguments
Message-ID: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>

I have a list... say for example

list = ["hello", "there"]

and i have a function

def printout(firstword, secondword):
    print firstword
    print secondword

and i want to call

the function like this

printout(list)

but that doesnt work because it takes the list as an argument.

How can I get around this problem?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070426/907bac9e/attachment.htm 

From rikard.bosnjakovic at gmail.com  Thu Apr 26 10:39:33 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 26 Apr 2007 10:39:33 +0200
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
Message-ID: <d9e88eaf0704260139x238f6f27u711a9de39c21eea@mail.gmail.com>

On 4/26/07, Stevie Broadfoot <coollikestevie at gmail.com> wrote:

> How can I get around this problem?

def printout(somelist):
  for x in somelist:
    print x



-- 
- Rikard - http://bos.hack.org/cv/

From andreengels at gmail.com  Thu Apr 26 10:42:29 2007
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 26 Apr 2007 10:42:29 +0200
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <6faf39c90704260129t53d15614p7e7ec1832105e336@mail.gmail.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
	<6faf39c90704260129t53d15614p7e7ec1832105e336@mail.gmail.com>
Message-ID: <6faf39c90704260142v2e3dc543xd63538dfaa1a0305@mail.gmail.com>

2007/4/26, Stevie Broadfoot <coollikestevie at gmail.com>:
> I have a list... say for example
>
> list = ["hello", "there"]
>
> and i have a function
>
> def printout(firstword, secondword):
>     print firstword
>     print secondword
>
> and i want to call
>
> the function like this
>
> printout(list)
>
> but that doesnt work because it takes the list as an argument.
>
> How can I get around this problem?

I see two simple ways, maybe there are more:

1. simply use
printout(list[0],list[1])

2. Change the definition of printout to:

def printout(firstword, secondword = None):
    if secondword is None:
        (firstword,secondword) = firstword
    print firstword
    print secondword


--
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels

From andreas at kostyrka.org  Thu Apr 26 10:47:30 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 26 Apr 2007 10:47:30 +0200
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
Message-ID: <20070426084730.GD20140@andi-lap.la.revver.com>

* Stevie Broadfoot <coollikestevie at gmail.com> [070426 09:56]:
>    I have a list... say for example
> 
>    list = ["hello", "there"]
> 
>    and i have a function
> 
>    def printout(firstword, secondword):
>        print firstword
>        print secondword
> 
>    and i want to call
> 
>    the function like this
> 
>    printout(list)
printout(*list)

Andreas

From kent37 at tds.net  Thu Apr 26 13:44:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 26 Apr 2007 07:44:19 -0400
Subject: [Tutor] sys.path, managing modules and packages
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF20364A16E@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF20364A16E@gsb-exchmb02.stanford.edu>
Message-ID: <46309093.4020401@tds.net>

Switanek, Nick wrote:
> Can someone help me better understand how I ought to manage the modules 
> and packages that I download? I often find that I can?t use the code 
> I?ve just downloaded, despite putting it into Lib/site-packages.

site-packages should just contain the module or package itself. For 
example suppose you download the latest version of the wunderbar 
package. It unzips to a folder called wunderbar-0.99 which contains a 
doc folder, an example folder and a wunderbar folder which is the actual 
package. It is the wunderbar folder that should go in site-packages.

Many Python packages come with a setup script called setup.py that does 
the right thing. In this case, just go to the dir containing setup.py 
and type
   python setup.py install

If the downloaded code is a single module (file) rather than a package 
(directory), then put the file into site-packages. Don't put it in a 
subdirectory within site-packages.

> Often 
> I?ve added the subdirectory path via sys.path.append, but this seems to 
> go only one level down, whereas I thought that when trying to import 
> something python would search all subdirectories of the directories in 
> the sys.path.

No, Python doesn't search subdirectories except when looking for 
subpackages. The top-level module or package that you import must be in 
a file or directory that is directly contained in one of the dirs in 
sys.path.

Kent

From coollikestevie at gmail.com  Thu Apr 26 16:00:45 2007
From: coollikestevie at gmail.com (Stevie Broadfoot)
Date: Fri, 27 Apr 2007 00:00:45 +1000
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <20070426084730.GD20140@andi-lap.la.revver.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
	<20070426084730.GD20140@andi-lap.la.revver.com>
Message-ID: <bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>

This is the best answer i've gotten so far... but its still not working...

what exactly does the star do?

the other solutions people provided do not suit my needs, my printout
function was just an example, what i need it for is more complicated.
I actually just need to feed the members of the list into the function...
and this is to be applied to different functions with different numbers of
arguments needed.

On 4/26/07, Andreas Kostyrka <andreas at kostyrka.org> wrote:
>
> * Stevie Broadfoot <coollikestevie at gmail.com> [070426 09:56]:
> >    I have a list... say for example
> >
> >    list = ["hello", "there"]
> >
> >    and i have a function
> >
> >    def printout(firstword, secondword):
> >        print firstword
> >        print secondword
> >
> >    and i want to call
> >
> >    the function like this
> >
> >    printout(list)
> printout(*list)
>
> Andreas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070427/b6bc5ae0/attachment.htm 

From coollikestevie at gmail.com  Thu Apr 26 16:03:57 2007
From: coollikestevie at gmail.com (Stevie Broadfoot)
Date: Fri, 27 Apr 2007 00:03:57 +1000
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
	<20070426084730.GD20140@andi-lap.la.revver.com>
	<bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>
Message-ID: <bec363f0704260703wdfbd186s3811c1b4517c0e5e@mail.gmail.com>

actually scrap that, it works perfectly :) thank you very much for your
help. One last question, does this only work on lists? or will tuples work
too and what else?

On 4/27/07, Stevie Broadfoot <coollikestevie at gmail.com> wrote:
>
> This is the best answer i've gotten so far... but its still not working...
>
> what exactly does the star do?
>
> the other solutions people provided do not suit my needs, my printout
> function was just an example, what i need it for is more complicated.
> I actually just need to feed the members of the list into the function...
> and this is to be applied to different functions with different numbers of
> arguments needed.
>
> On 4/26/07, Andreas Kostyrka <andreas at kostyrka.org> wrote:
> >
> > * Stevie Broadfoot <coollikestevie at gmail.com> [070426 09:56]:
> > >    I have a list... say for example
> > >
> > >    list = ["hello", "there"]
> > >
> > >    and i have a function
> > >
> > >    def printout(firstword, secondword):
> > >        print firstword
> > >        print secondword
> > >
> > >    and i want to call
> > >
> > >    the function like this
> > >
> > >    printout(list)
> > printout(*list)
> >
> > Andreas
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070427/30c88f61/attachment.html 

From washakie at gmail.com  Thu Apr 26 16:19:03 2007
From: washakie at gmail.com (John Washakie)
Date: Thu, 26 Apr 2007 16:19:03 +0200
Subject: [Tutor] a way to glob over http?
Message-ID: <aaf235960704260719h3ee6fe28i2e7dd5801cf55939@mail.gmail.com>

Hello all,

I'm writing a program which take input about a path. The path may be
http or absolute or local. Once I have the path, I want to search the
directory for images (type also defined by user), then get a count on
the number of images in order to build the rest of my program:

searchPath = imageRoot + '*' + imgExt
avail = glob.glob(searchPath)  #will glob work over http?

One option would be to preform some testing first to see if the user
has input a local or http path, then I could use urllib I guess? (I am
not familiar with this yet). However, another concern arises in that
some directories on http servers are not readable, even if a readable
image is located in them... but that's another question for another
time.

Thanks,
john

From andreas at kostyrka.org  Thu Apr 26 17:51:27 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 26 Apr 2007 17:51:27 +0200
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>
	<20070426084730.GD20140@andi-lap.la.revver.com>
	<bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>
Message-ID: <20070426155127.GG20140@andi-lap.la.revver.com>

It works for me.

andreas at andi-lap:~> python /tmp/q.py
hello
there
andreas at andi-lap:~> cat /tmp/q.py 
list = ["hello", "there"]

def printout(firstword, secondword):
    print firstword                 
    print secondword
	
printout(*list)

What does it do?

It passes the arguments from an iterable.

It works the other way too:

def help(*args):
    print help
    
help()      => prints ()
help(1,2,3) => prints (1,2,3)

Andreas


* Stevie Broadfoot <coollikestevie at gmail.com> [070426 16:08]:
>    This is the best answer i've gotten so far... but its still not working...
> 
>    what exactly does the star do?
> 
>    the other solutions people provided do not suit my needs, my printout
>    function was just an example, what i need it for is more complicated.
>    I actually just need to feed the members of the list into the function...
>    and this is to be applied to different functions with different numbers of
>    arguments needed.
> 
>    On 4/26/07, Andreas Kostyrka <[1]andreas at kostyrka.org> wrote:
> 
>      * Stevie Broadfoot <[2]coollikestevie at gmail.com> [070426 09:56]:
>      >    I have a list... say for example
>      >
>      >    list = ["hello", "there"]
>      >
>      >    and i have a function
>      >
>      >    def printout(firstword, secondword):
>      >        print firstword
>      >        print secondword
>      >
>      >    and i want to call
>      >
>      >    the function like this
>      >
>      >    printout(list)
>      printout(*list)
> 
>      Andreas
> 
> References
> 
>    Visible links
>    1. mailto:andreas at kostyrka.org
>    2. mailto:coollikestevie at gmail.com

From kent37 at tds.net  Thu Apr 26 18:07:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 26 Apr 2007 12:07:48 -0400
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <bec363f0704260703wdfbd186s3811c1b4517c0e5e@mail.gmail.com>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>	<20070426084730.GD20140@andi-lap.la.revver.com>	<bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>
	<bec363f0704260703wdfbd186s3811c1b4517c0e5e@mail.gmail.com>
Message-ID: <4630CE54.4080108@tds.net>

Stevie Broadfoot wrote:
> actually scrap that, it works perfectly :) thank you very much for your 
> help. One last question, does this only work on lists? or will tuples 
> work too and what else?

It will work on any sequence including lists and tuples.

Kent

From kent37 at tds.net  Thu Apr 26 18:14:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 26 Apr 2007 12:14:25 -0400
Subject: [Tutor] Feeding a list into a function as arguments
In-Reply-To: <4630CE54.4080108@tds.net>
References: <bec363f0704260053j1bfd24b6wab6582b738c8a664@mail.gmail.com>	<20070426084730.GD20140@andi-lap.la.revver.com>	<bec363f0704260700r22efe8b5ufb4591907075cecb@mail.gmail.com>	<bec363f0704260703wdfbd186s3811c1b4517c0e5e@mail.gmail.com>
	<4630CE54.4080108@tds.net>
Message-ID: <4630CFE1.5070408@tds.net>

Kent Johnson wrote:
> Stevie Broadfoot wrote:
>> actually scrap that, it works perfectly :) thank you very much for your 
>> help. One last question, does this only work on lists? or will tuples 
>> work too and what else?
> 
> It will work on any sequence including lists and tuples.

More precisely, it will work with any iterable - even a dict (which 
passes the *keys* of the dict) or a generator expression:

In [14]: def p(*args):
    ....:     print args
    ....:
    ....:
In [15]: p(*dict(foo=1, bar=2))
('foo', 'bar')
In [16]: p(*(x*x for x in range(4)))
(0, 1, 4, 9)

Kent

From marshall.jiang at gmail.com  Fri Apr 27 03:23:59 2007
From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1))
Date: Thu, 26 Apr 2007 21:23:59 -0400
Subject: [Tutor] Question about formating string with dictionary
Message-ID: <a678270c0704261823j737b6be2xc798e4fb657ccce7@mail.gmail.com>

Hello everyone,

The program that I am working on right now have a template for string
formatting.
My question is that is it possible to use multiple dictionary to format the
string.

For example
x = {'foo':1234, 'bar': 5678}
y = {'spam':'hello','cheese':'good-bye'}

is there any way to use his pseudo code
template = \
"""Foo = %(foo)s
bar = %(bar)s
spame = %(spam)s
cheese = %(cheese)s"""

print template %x,y

Thanks

Marshall
-- 
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as
equals.
    Sir Winston Churchill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070426/93ae00b3/attachment.html 

From john at fouhy.net  Fri Apr 27 04:04:40 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 27 Apr 2007 14:04:40 +1200
Subject: [Tutor] Question about formating string with dictionary
In-Reply-To: <a678270c0704261823j737b6be2xc798e4fb657ccce7@mail.gmail.com>
References: <a678270c0704261823j737b6be2xc798e4fb657ccce7@mail.gmail.com>
Message-ID: <5e58f2e40704261904x6f999244q78af92e8ae7eba2@mail.gmail.com>

On 27/04/07, Shuai Jiang (Runiteking1) <marshall.jiang at gmail.com> wrote:
> Hello everyone,
>
> The program that I am working on right now have a template for string
> formatting.
> My question is that is it possible to use multiple dictionary to format the
> string.
>
> For example
> x = {'foo':1234, 'bar': 5678}
> y = {'spam':'hello','cheese':'good-bye'}
>
> is there any way to use his pseudo code
> template = \
> """Foo = %(foo)s
> bar = %(bar)s
> spame = %(spam)s
> cheese = %(cheese)s"""
>
> print template %x,y

My best suggestion would be to write a function to combine multiple
dictionaries into one.  eg:

def combine(*dicts):
    """ Combine multiple dictionaries into one.  Rightmost
dictionaries have precedence. """
    res = {}
    for d in dicts:
        res.update(d)
    return res

Then:

x = {'foo':1234, 'bar': 5678}
y = {'spam':'hello','cheese':'good-bye'}

"""Foo = %(foo)s
bar = %(bar)s
spame = %(spam)s
cheese = %(cheese)s""" % combine(x, y)

HTH!

-- 
John.

From shiv_mbm at hotmail.com  Fri Apr 27 13:05:12 2007
From: shiv_mbm at hotmail.com (shiv k)
Date: Fri, 27 Apr 2007 11:05:12 +0000
Subject: [Tutor] ImportError: No module named mpcp
Message-ID: <BAY121-F19C30D16BAE37D27577D70F64F0@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070427/ac1d9aec/attachment.htm 

From shiv_mbm at hotmail.com  Fri Apr 27 13:28:51 2007
From: shiv_mbm at hotmail.com (shiv k)
Date: Fri, 27 Apr 2007 11:28:51 +0000
Subject: [Tutor] how to un-install a python module
Message-ID: <BAY121-F38DC6B2DCD0D06D26ACA29F64F0@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070427/1f581456/attachment.htm 

From rikard.bosnjakovic at gmail.com  Fri Apr 27 14:18:15 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 27 Apr 2007 14:18:15 +0200
Subject: [Tutor] ImportError: No module named mpcp
In-Reply-To: <BAY121-F19C30D16BAE37D27577D70F64F0@phx.gbl>
References: <BAY121-F19C30D16BAE37D27577D70F64F0@phx.gbl>
Message-ID: <d9e88eaf0704270518r2ebc8854y1d1286874eefceb8@mail.gmail.com>

On 4/27/07, shiv k <shiv_mbm at hotmail.com> wrote:

>  When I launch a command-line interpreter, mpcp exists

Sounds like a PATH-issue (environment variable). Check both your
PYTHONPATH and PATH, and make sure mpcp is in either python's
site-lib/ or in your PYTHONPATH.


-- 
- Rikard - http://bos.hack.org/cv/

From srini_iyyer_bio at yahoo.com  Fri Apr 27 23:10:16 2007
From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer)
Date: Fri, 27 Apr 2007 14:10:16 -0700 (PDT)
Subject: [Tutor] priting keys and its values of a dictionary in a single row
Message-ID: <554151.79675.qm@web38115.mail.mud.yahoo.com>

Dear group,

I have a dictionary (huge) and there are 19K keys for
this dictionary. The values for the could be a max 19K
again. 

simpler version of it:

mydict=
{'a':['apple','ant','anchor','arrow'],'b':['ball','baby',boy','bus'],'c':['cat','call']}

in a different list, i have keys:
mlist = ['a','b','c']

I want to print in the following way:
a,apple,ant,anchor,arrow
b,ball,baby,boy,bus
c,cat call

I cannot think of a simple way to do that (may be a
mental block). could any one help me please. 

Thanks
srini


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From billburns at pennswoods.net  Sat Apr 28 00:26:04 2007
From: billburns at pennswoods.net (Bill Burns)
Date: Fri, 27 Apr 2007 18:26:04 -0400
Subject: [Tutor] priting keys and its values of a dictionary in a single
 row
In-Reply-To: <554151.79675.qm@web38115.mail.mud.yahoo.com>
References: <554151.79675.qm@web38115.mail.mud.yahoo.com>
Message-ID: <4632787C.9000808@pennswoods.net>

Srinivas Iyyer wrote:
> Dear group,
> 
> I have a dictionary (huge) and there are 19K keys for
> this dictionary. The values for the could be a max 19K
> again. 
> 
> simpler version of it:
> 
> mydict=
> {'a':['apple','ant','anchor','arrow'],'b':['ball','baby',boy','bus'],'c':['cat','call']}
> 
> in a different list, i have keys:
> mlist = ['a','b','c']
> 
> I want to print in the following way:
> a,apple,ant,anchor,arrow
> b,ball,baby,boy,bus
> c,cat call
> 
> I cannot think of a simple way to do that (may be a
> mental block). could any one help me please. 
> 
> Thanks
> srini
> 

Try this:

for key in mlist: print '%s,%s' % (key, ','.join(mydict[key]))

Bill


From coollikestevie at gmail.com  Sat Apr 28 07:32:52 2007
From: coollikestevie at gmail.com (Stevie Broadfoot)
Date: Sat, 28 Apr 2007 15:32:52 +1000
Subject: [Tutor] compiling python into an executable
Message-ID: <bec363f0704272232n31e3339qde64e7a757e7e8ca@mail.gmail.com>

what is a good program to make an executable for all platforms. Like i know
py2app is for osx and py2exe is for windows or something like that, but what
can I use for linux, windows and macosx. Or does there not exist such a
program? I'm on ubuntu edgy eft at the moment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070428/1d89eda7/attachment.html 

From alan.gauld at btinternet.com  Sat Apr 28 09:27:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 28 Apr 2007 08:27:48 +0100
Subject: [Tutor] compiling python into an executable
References: <bec363f0704272232n31e3339qde64e7a757e7e8ca@mail.gmail.com>
Message-ID: <f0ut2a$22e$1@sea.gmane.org>

"Stevie Broadfoot" <coollikestevie at gmail.com> wrote 

> what is a good program to make an executable for all platforms. 

I'm not totally clear what you are expecting here.
Python scripts are executable on all platforms as they stand, 
you just need the appropriate interpreter to be installed. 
Much like a Java program can run on any platform that 
has the JVM installed.

> py2app is for osx 

I thought py2app simply packaged a Python application 
into a MacOS app 'bundle', ie the standard Mac file format/structure.
Python still needs to be installed on the Mac, albeit as part of 
the bundle.

> py2exe is for windows 

Whereas py2exe produces a binary format file containing 
the python interpreter plus any files needed for your 
application. This file works like a normal windows binary 
executable.

> can I use for linux, windows and macosx. 

It is impossible to produce a single executable binary file
that will run natively on all 3 OS, so if that's what you are 
looking for it doesn't exist. The nerarest thing would be to 
use Jython and compile into Java bytecode, relying on 
the fact that most computers now have a JVM installed.

However, if you only want a single tool to produce three 
different native executable formats then I suspect Gordon 
MacMillan's installer might be the closest, although I'm not 
sure of its status since I haven't heard of anyone using it 
recently. But it certainly didv Linux and Windows and I 
wouldn't be surprised if it now did Mac too...

> Or does there not exist such a program? 
> I'm on ubuntu edgy eft at the moment.

These kind of executable bundling programs aren't 
that commonly used on Unix programs because there 
is a long tradition of using scripting languages on Unix.
Nearly all Unix installs come with a range of interpreters 
(sh, sed, awk, m4, perl, Tcl, scheme, etc) and adding Python, 
in the rare case that its not there already,  is unlikely 
to stress out any Unix admin.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From rohan.deshpande at gmail.com  Sat Apr 28 12:54:32 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Sat, 28 Apr 2007 11:54:32 +0100
Subject: [Tutor] priting keys and its values of a dictionary in a single
	row
In-Reply-To: <4632787C.9000808@pennswoods.net>
References: <554151.79675.qm@web38115.mail.mud.yahoo.com>
	<4632787C.9000808@pennswoods.net>
Message-ID: <e5a6f5430704280354y7fc2d8c2r70dc3d14fe6d925d@mail.gmail.com>

Or, get rid of the extra variable and do:

for i in m.items():
  print i[0] + ',' + ",".join(i[1])

On 4/27/07, Bill Burns <billburns at pennswoods.net> wrote:
>
> Srinivas Iyyer wrote:
> > Dear group,
> >
> > I have a dictionary (huge) and there are 19K keys for
> > this dictionary. The values for the could be a max 19K
> > again.
> >
> > simpler version of it:
> >
> > mydict=
> >
> {'a':['apple','ant','anchor','arrow'],'b':['ball','baby',boy','bus'],'c':['cat','call']}
> >
> > in a different list, i have keys:
> > mlist = ['a','b','c']
> >
> > I want to print in the following way:
> > a,apple,ant,anchor,arrow
> > b,ball,baby,boy,bus
> > c,cat call
> >
> > I cannot think of a simple way to do that (may be a
> > mental block). could any one help me please.
> >
> > Thanks
> > srini
> >
>
> Try this:
>
> for key in mlist: print '%s,%s' % (key, ','.join(mydict[key]))
>
> Bill
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070428/a27c404d/attachment.htm 

From andreas at kostyrka.org  Sat Apr 28 13:00:30 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 28 Apr 2007 13:00:30 +0200
Subject: [Tutor] priting keys and its values of a dictionary in a single
	row
In-Reply-To: <e5a6f5430704280354y7fc2d8c2r70dc3d14fe6d925d@mail.gmail.com>
References: <554151.79675.qm@web38115.mail.mud.yahoo.com>
	<4632787C.9000808@pennswoods.net>
	<e5a6f5430704280354y7fc2d8c2r70dc3d14fe6d925d@mail.gmail.com>
Message-ID: <20070428110027.GE12088@andi-lap.la.revver.com>

* Rohan Deshpande <rohan.deshpande at gmail.com> [070428 12:58]:
That assumes he wants to output all elements.

Andreas

>    Or, get rid of the extra variable and do:
> 
>    for i in m.items():
>      print i[0] + ',' + ",".join(i[1])
> 
>    On 4/27/07, Bill Burns < [1]billburns at pennswoods.net> wrote:

From webdev at mozaicsands.com  Sun Apr 29 02:51:51 2007
From: webdev at mozaicsands.com (Mozaic Web Development)
Date: Sat, 28 Apr 2007 17:51:51 -0700
Subject: [Tutor] urllib2 and content-type header
Message-ID: <2FE253EA-717D-4469-9845-8F799BF0A605@mozaicsands.com>

Hello -

I'm trying to work with the Basecamp API with Python, and am running  
into a bit of an issue. I'm using a Basecamp class that wraps the API  
that was written by Jochen Kupperschmidt (if you are reading this,  
thanks!) With some help from the basecamp forums, I think I've  
identified the issue, in that the urllib2 request that is being  
generated is being sent out with a 'Content-type: application/x-www- 
form-urlencoded', whereas Basecamp is expecting a header with  
'Content-Type: application/xml'. Ok, great - from the docs I see that  
this is the default. But from what I can tell, the class compensates  
for this and should be overriding the default - but catching the  
request in a proxy, it isn't! So any tips would be greatly appreciated..

here are the relevant parts of the class:

import base64, urllib2
import elementtree.ElementTree as ET #(I'm running python 2.4)

class Basecamp(object):

     def __init__(self, baseURL, username, password):
         self.baseURL = baseURL
         if self.baseURL[-1] == '/':
             self.baseURL = self.baseURL[:-1]
         self.opener = urllib2.build_opener()
         self.opener.addheaders = [
             ('Content-Type', 'application/xml'),
             ('Accept', 'application/xml'),
             ('Authorization', 'Basic %s' \
                 % base64.encodestring('%s:%s' % (username, password)))]

     def _request(self, path, data=None):
         if isinstance(data, ET._ElementInterface):
             data = ET.tostring(data)
         req = urllib2.Request(url=self.baseURL + path, data=data)
         return self.opener.open(req).read()

So I don't know why the Content-Type that is being set in  
self.opener.addheaders isn't sticking.. Thank you, I apologize if  
this email is a bit long..
Thanks!
-Eric


From mjekl at iol.pt  Sun Apr 29 15:31:57 2007
From: mjekl at iol.pt (mjekl at iol.pt)
Date: Sun, 29 Apr 2007 14:31:57 +0100
Subject: [Tutor] compiling python into an executable
In-Reply-To: <bec363f0704272232n31e3339qde64e7a757e7e8ca@mail.gmail.com>
References: <bec363f0704272232n31e3339qde64e7a757e7e8ca@mail.gmail.com>
Message-ID: <f7fb86a51796.4634ac5d@iol.pt>

I think what you are looking for is:

http://pyinstaller.python-hosting.com/

Best,
Miguel

_______________________________________________________________________________________
Sabe qual e o credito pessoal MAIS FACIL DE PAGAR no futuro?
Aquele em que as PRESTACOES DESCEM ao longo do emprestimo?
Saiba mais em: http://www.iol.pt/correio/rodape.php?dst=0704171

-------------- next part --------------
what is a good program to make an executable for all platforms. Like i know
py2app is for osx and py2exe is for windows or something like that, but what
can I use for linux, windows and macosx. Or does there not exist such a
program? I'm on ubuntu edgy eft at the moment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070429/8326f86b/attachment.htm 
-------------- next part --------------
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

From agilfoy at frontiernet.net  Sun Apr 29 18:50:25 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Sun, 29 Apr 2007 16:50:25 +0000
Subject: [Tutor] The IDLE subprocess
Message-ID: <20070429165025.b0418czn239c00gk@webmail.frontiernet.net>

Often, when I am developing code, I get an error message saying that  
"IDLE's subprocess can't make connection"

Sometimes this happends when I have IDLE open, and am about to hit F5  
to run a program-in-process.
Sometimes it happens when I opne up IDLE the first time.

It's often fixed on restart of the program, not even restart of the computer.

A big deal or not?
And what does the subprocess do, anyway?
-- 
"Computers were the first God-Satan collaboration project."
"Blind faith in bad leadership is not patriotism."

"One of the most horrible features of war is that all the war-propaganda, all
the screaming and lies and hatred, comes invariably from people who are not
fighting."-George Orwell, _Homage to Catalonia






From rabidpoobear at gmail.com  Sun Apr 29 19:36:26 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 29 Apr 2007 12:36:26 -0500
Subject: [Tutor] The IDLE subprocess
In-Reply-To: <20070429165025.b0418czn239c00gk@webmail.frontiernet.net>
References: <20070429165025.b0418czn239c00gk@webmail.frontiernet.net>
Message-ID: <4634D79A.3050201@gmail.com>

Alan Gilfoy wrote:
> Often, when I am developing code, I get an error message saying that  
> "IDLE's subprocess can't make connection"
>
> Sometimes this happends when I have IDLE open, and am about to hit F5  
> to run a program-in-process.
> Sometimes it happens when I opne up IDLE the first time.
>
> It's often fixed on restart of the program, not even restart of the computer.
>
> A big deal or not?
> And what does the subprocess do, anyway?
>   
This usually happens when you run a python script that doesn't terminate 
correctly.
So it seems like it exits, but if you go to the task manager, you can 
see an extra pythonw.exe process still running.
Terminating it should fix everything.
(I assume you're on Windows, because I don't think this problem would 
arise on Linux, but if it did, I expect the solution to be similar.)

It's not a big deal.
The subprocess runs your python program as a separate process of IDLE, 
so that when your program blocks for input, for example,
IDLE won't block also. So you can see all your output and such.  It's 
especially useful to run in subprocess mode when you're
editing Pygame windows, because if they crash without subprocess, you 
have to terminate Pygame as well as IDLE.
(again, assuming you're on Windows, because on Linux I think it just 
opens in subprocess mode all the time,
whereas on Windows if you right-click something and choose "edit with 
idle" it doesn't open in subprocess mode.)


From washakie at gmail.com  Sun Apr 29 19:50:12 2007
From: washakie at gmail.com (John Washakie)
Date: Sun, 29 Apr 2007 19:50:12 +0200
Subject: [Tutor] listing files in an html directory
Message-ID: <aaf235960704291050l51f42b14w5364493899d18cc7@mail.gmail.com>

Hello all,

I'm trying to write a program which will take a path, look in it for
all files matching a certain pattern, then create javascript player to
play them. A key part of the code at this point is:

searchPath = imageRoot + '*' + imgExt
avail = glob.glob(searchPath)  #will glob work over http?

where searchPath is constructed from imageRoot and imgExt which are
user input variables. I don't think glob will work over http, is there
a urllib version perhaps? Any suggestions?

Thanks!

From rabidpoobear at gmail.com  Sun Apr 29 19:57:44 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 29 Apr 2007 12:57:44 -0500
Subject: [Tutor] listing files in an html directory
In-Reply-To: <aaf235960704291050l51f42b14w5364493899d18cc7@mail.gmail.com>
References: <aaf235960704291050l51f42b14w5364493899d18cc7@mail.gmail.com>
Message-ID: <4634DC98.8030506@gmail.com>

John Washakie wrote:
> Hello all,
>
> I'm trying to write a program which will take a path, look in it for
> all files matching a certain pattern, then create javascript player to
> play them. A key part of the code at this point is:
>
> searchPath = imageRoot + '*' + imgExt
> avail = glob.glob(searchPath)  #will glob work over http?
>
> where searchPath is constructed from imageRoot and imgExt which are
> user input variables. I don't think glob will work over http, is there
> a urllib version perhaps? Any suggestions?
>   
Most http servers disallow directory listing.
Even ones that do (like Apache default) there has to be no index.html in 
the directory, and they
dump the directory listing to a webpage you'd have to parse.
-Luke

From necmettin.begiter at gmail.com  Mon Apr 30 09:50:00 2007
From: necmettin.begiter at gmail.com (Necmettin Begiter)
Date: Mon, 30 Apr 2007 10:50:00 +0300
Subject: [Tutor] StringIO and dictionaries
Message-ID: <200704301050.01539.necmettin.begiter@gmail.com>

I want to run an external python script inside my script. So here is what I 
came up with:

Print codename for testing purposes.
Define an empty dictionary.
Read the file.
Do StringIO assignments and run the code.
Get the outputs and append them to the dictionary.
Print the outputs for testing purposes.


The code:
codeOut= {}
codeErr= {}

Print codename for testing purposes:
	print codename
Note: codename is a parameter that is passed to the function for the first 
parts (keys) of codeOut and codeErr dictionaries; and it prints the given 
name (deneme in this case) correctly.

Read the file:
	localfile= open(filename,'r')
	code2run= localfile.readlines()
	localfile.close()

Do StringIO assignments and run the code:
	codOut= StringIO.StringIO()
	codErr= StringIO.StringIO()
	sys.stdout= codOut
	sys.stderr= codErr
	exec code2run
	sys.stdout= sys.__stdout__
	sys.stderr= sys.__stderr__

Get the outputs and append them to the dictionary.
	erroroutput= codErr.getvalue()
	normaloutput= codOut.getvalue()
	codeOut.append({codename:erroroutput})
	codeErr.append({codename:normaloutput})

Print the outputs (just for testing):
	print codename
	print normaloutput
	print erroroutput
	print codeOut
	print codeErr

And I get nothing. Is there something I am doing wrong? Because I have read 
the parts on dictionaries and stringio and googled, but I can't find the 
problem. Any comments, suggestions? Or could someone please tell me if there 
is something wrong with my code?

-- 
Necmettin Begiter
Blog: http://begiter.blogspot.com/feeds/posts/default

From ebbaalm at uiuc.edu  Mon Apr 30 15:42:34 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Mon, 30 Apr 2007 08:42:34 -0500
Subject: [Tutor] iterating
Message-ID: <7a4620dc0704300642w40641d9r5eb0c4b598b61d34@mail.gmail.com>

1) Unordered maps/collections like sets and dictionaries also seem to
support iterating over set members or dictionary keys with "for x in
y" syntax. As far as I can tell, the following three ways generally
behave the same way, or is there a difference in behavior between:

a) for key in dictionary:
b) for key in dictionary.keys():
c)  mykeys = dictionary.keys()
     for k in mykeys:

2) The following three ways for manipulating objects in a list with a
function will generally do the same thing, right? (but the last two
have a shorter syntax).

a)  newls = []
     for entry in mylist:
        newls.append(function(entry))

b)  newlist = map(function, mylist)

c)  newlist = [function(entry) for entry in mylist]

From alex.dering at gmail.com  Sat Apr 28 12:49:27 2007
From: alex.dering at gmail.com (Alexander Dering)
Date: Sat, 28 Apr 2007 06:49:27 -0400
Subject: [Tutor] Problem with "Hello, World"
Message-ID: <2df89cb20704280349l68f42f1w8028eb766793725b@mail.gmail.com>

So I've written my first python program (the ubiquitous 'Hello, World').

Already, I'm having problems. First, the question I can't find the answer
to.

Where (exactly) am I supposed to save my files? When I wrote "hello.py"
there was no clearly stated "Make sure you save it HERE or else Python won't
know where to look for it."

In case that won't solve the problem, here are the gory details.

I wrote "hello.py" with TextWrangler. I can get it to run from TextWrangler
by clicking on the "run in terminal" command. And it runs beautifully. A
masterful demonstration of my ability to follow directions.

But I can't get it to run directly from Python. If I go to the terminal and
type "python hello.py" (which is what the instructions say I should be
doing!) I get the following:

>>> hello.py
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'hello' is not defined
>>>

When I run debugger (in TextWrangler) I get the following:

Traceback (most recent call last):
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/pdb.py",
line 9, in ?
    import cmd
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/cmd.py",
line 48, in ?
    import string
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/string.py",
line 83, in ?
    import re as _re
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/re.py",
line 5, in ?
    from sre import *
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py",
line 97, in ?
    import sre_compile
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre_compile.py",
line 17, in ?
    assert _sre.MAGIC == MAGIC, "SRE module mismatch"
AssertionError: SRE module mismatch
logout
[Process completed]


All help gratefully taken with both hands!

Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070428/3eca5f25/attachment.htm 

From rikard.bosnjakovic at gmail.com  Mon Apr 30 17:15:31 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 30 Apr 2007 17:15:31 +0200
Subject: [Tutor] Problem with "Hello, World"
In-Reply-To: <2df89cb20704280349l68f42f1w8028eb766793725b@mail.gmail.com>
References: <2df89cb20704280349l68f42f1w8028eb766793725b@mail.gmail.com>
Message-ID: <d9e88eaf0704300815j31378810j93bc190bda387c59@mail.gmail.com>

On 4/28/07, Alexander Dering <alex.dering at gmail.com> wrote:

>  But I can't get it to run directly from Python. If I go to the terminal and
> type "python hello.py" (which is what the instructions say I should be
> doing!) I get the following:
>
> >>> hello.py
>  Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'hello' is not defined
> >>>

What you are doing above is typing "python", then - IN python - typing
"hello.py". This does not work, since you're in the interpreter and
the function "hello.py" is unknown to Python.

So try again: "python hello.py" in the command interpreter. Or if you
are in the python interpreter, you might try "import hello" and see
what happens.


-- 
- Rikard - http://bos.hack.org/cv/

From kent37 at tds.net  Mon Apr 30 17:17:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 30 Apr 2007 11:17:42 -0400
Subject: [Tutor] iterating
In-Reply-To: <7a4620dc0704300642w40641d9r5eb0c4b598b61d34@mail.gmail.com>
References: <7a4620dc0704300642w40641d9r5eb0c4b598b61d34@mail.gmail.com>
Message-ID: <46360896.9090207@tds.net>

Cecilia Alm wrote:
> 1) Unordered maps/collections like sets and dictionaries also seem to
> support iterating over set members or dictionary keys with "for x in
> y" syntax. As far as I can tell, the following three ways generally
> behave the same way, or is there a difference in behavior between:
> 
> a) for key in dictionary:
> b) for key in dictionary.keys():
> c)  mykeys = dictionary.keys()
>      for k in mykeys:

These are equivalent in most common usage but there is a difference 
which can be significant. Calling dict.keys() creates an actual list 
with all the keys in it which is not created when you iterate the 
dictionary directly. In most cases this doesn't matter but for a huge 
dictionary it might. Also if you are adding or deleting from the dict 
during the iteration then dict.keys() is safer because the list of keys 
is created before the add and delete. Using dict.iterkeys() is more 
equivalent to 'for key in dictionary' because it doesn't create the 
intermediate list.

Of course using c) you will also have the variable mykeys available 
which is not the case in a) and b)
> 
> 2) The following three ways for manipulating objects in a list with a
> function will generally do the same thing, right? (but the last two
> have a shorter syntax).
> 
> a)  newls = []
>      for entry in mylist:
>         newls.append(function(entry))
> 
> b)  newlist = map(function, mylist)
> 
> c)  newlist = [function(entry) for entry in mylist]

Yes, pretty much. After a) and c) the entry variable will still be 
defined. For c) this is considered a bug and IIRC will change with 
Python 3. IMO modern usage tends toward c).

Kent

From ebbaalm at uiuc.edu  Mon Apr 30 17:46:38 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Mon, 30 Apr 2007 10:46:38 -0500
Subject: [Tutor] Fwd:  iterating
In-Reply-To: <7a4620dc0704300846l1295841aradffda308a1b9161@mail.gmail.com>
References: <7a4620dc0704300642w40641d9r5eb0c4b598b61d34@mail.gmail.com>
	<46360896.9090207@tds.net>
	<7a4620dc0704300846l1295841aradffda308a1b9161@mail.gmail.com>
Message-ID: <7a4620dc0704300846l73bafcddue01546469f11b94a@mail.gmail.com>

2007/4/30, Kent Johnson <kent37 at tds.net>:
. Also if you are adding or deleting from the dict
> during the iteration then dict.keys() is safer because the list of keys
> is created before the add and delete.

Thanks for the response; by adding and deleting, I assume you refer to
adding or deleting keys (rather than changing the value associated
with the key).



--
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute


-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

From bgailer at alum.rpi.edu  Mon Apr 30 18:43:03 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 30 Apr 2007 09:43:03 -0700
Subject: [Tutor] StringIO and dictionaries
In-Reply-To: <200704301050.01539.necmettin.begiter@gmail.com>
References: <200704301050.01539.necmettin.begiter@gmail.com>
Message-ID: <46361C97.50205@alum.rpi.edu>

Necmettin Begiter wrote:
> I want to run an external python script inside my script. So here is what I 
> came up with:
>
> Print codename for testing purposes.
> Define an empty dictionary.
> Read the file.
> Do StringIO assignments and run the code.
> Get the outputs and append them to the dictionary.
> Print the outputs for testing purposes.
>
>
> The code:
> codeOut= {}
> codeErr= {}
>
> Print codename for testing purposes:
> 	print codename
> Note: codename is a parameter that is passed to the function for the first 
> parts (keys) of codeOut and codeErr dictionaries; and it prints the given 
> name (deneme in this case) correctly.
>
> Read the file:
> 	localfile= open(filename,'r')
> 	code2run= localfile.readlines()
> 	localfile.close()
>
> Do StringIO assignments and run the code:
> 	codOut= StringIO.StringIO()
> 	codErr= StringIO.StringIO()
> 	sys.stdout= codOut
> 	sys.stderr= codErr
> 	exec code2run
> 	sys.stdout= sys.__stdout__
> 	sys.stderr= sys.__stderr__
>
> Get the outputs and append them to the dictionary.
> 	erroroutput= codErr.getvalue()
> 	normaloutput= codOut.getvalue()
> 	codeOut.append({codename:erroroutput})
>   
I'm confused when you "assign" errorputput to codeOut and normaloutput 
to codeErr.

Also unclear why you use dictionaries in the first place.

When I run this program from a command prompt I get:
 
File "begiter.py", line 21, in <module>
    codeOut.append({codename:erroroutput})
AttributeError: 'dict' object has no attribute 'append'

However when I run it from my IDE (PythonWin) the traceback does not 
show. In fact sys.stdout= sys.__stdout__  does not restore the print to 
the interactive window.

So there are 2 problems. Fix the first by either
codeOut.update({codename:erroroutput})
or (preferred):
codeOut[codename]=normaloutput

> 	codeErr.append({codename:normaloutput})
>
> Print the outputs (just for testing):
> 	print codename
> 	print normaloutput
> 	print erroroutput
> 	print codeOut
> 	print codeErr
>
> And I get nothing. 
> Is there something I am doing wrong? Because I have read 
> the parts on dictionaries and stringio and googled, but I can't find the 
> problem. Any comments, suggestions? Or could someone please tell me if there 
> is something wrong with my code?
>
>   


-- 
Bob Gailer
510-978-4454


From kent37 at tds.net  Mon Apr 30 21:03:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 30 Apr 2007 15:03:51 -0400
Subject: [Tutor] Fwd:  iterating
In-Reply-To: <7a4620dc0704300846l73bafcddue01546469f11b94a@mail.gmail.com>
References: <7a4620dc0704300642w40641d9r5eb0c4b598b61d34@mail.gmail.com>	<46360896.9090207@tds.net>	<7a4620dc0704300846l1295841aradffda308a1b9161@mail.gmail.com>
	<7a4620dc0704300846l73bafcddue01546469f11b94a@mail.gmail.com>
Message-ID: <46363D97.6070109@tds.net>

Cecilia Alm wrote:
> 2007/4/30, Kent Johnson <kent37 at tds.net>:
> . Also if you are adding or deleting from the dict
>> during the iteration then dict.keys() is safer because the list of keys
>> is created before the add and delete.
> 
> Thanks for the response; by adding and deleting, I assume you refer to
> adding or deleting keys (rather than changing the value associated
> with the key).

Right, I think changing a value will be safe.

Kent