Re: [Tutor] TESTING

2018-11-02 Thread Alan Gauld via Tutor
On 02/11/2018 03:45, Avi Gross wrote:
> I am not totally up on the exact purposes of this group but have noted how
> many of the questions asked have been frustrating.

Unfortunately that goes with the territory.
We are a list catering to beginners to Python and, frequently,
to programming. As a result the participants often have little
or no experience of using technical mailing lists or fora.

> I wonder if it would make any sense to provide a template people might fill
> out to suit their needs.

The problem is how. Where would the template reside? We do
provide some hints on the welcome mails that go out but its
clear that most newcomers don't read it, so a template
would likely suffer the same fate.

But the biggest problem for a mailing list, unlike a web site,
is that there is nowhere to post information in a persistent
manner. You could go to the archive and search, but that takes
effort which newbies are unlikely to expend.

Also, we want to encourage people to use the list and a long
list of "rules" and formats is likely to drive them elsewhere.

> An example might be people who want you to pretty much do their homework for
> them from beginning to end.

This has been an issue as long as I've been on the internet
(ie since before 1986)and there is IMHO no cure other than
to consistently offer help but not solutions. Those who want
to learn will come back. Those who just want a quick fix
will just ask on Quora...

> But to do it ALL for someone generally is not the role of a tutor in the
> real world.

Absolutely.

> On the other hand, when someone discusses how to optimize their code, and
> shows the ways they already tried, it may be valid to present them with a
> complete program that illustrates it assuming this is not a homework problem
> but a more advanced person that may be interested.

And that's how we try to deal with it. If its a genuine
problem we will give more complete solutions, if its
(suspected) homework we give hints and tips.

> But, to make this message more meaningful, I have a question. In my reading
> I see Python has been bifurcated into often incompatible releases we call 2X
> and 3X. 

Yes, although 2.X is effectively deprecated. But industry
usage requires that it still gets some support.

> So, does anyone see any further breaks in Python such as when 4.0 comes
> along or will we have some backward compatibility for a while? 

Others can answer this better than I but so far each
generation of Python has been close to a decade apart
(v1 ~ 1991, v2 ~ c2000, v3 ~ c2010) So v4 would logically
appear around 2020, but I've seen no specific discussion
of that whereas both v2 and v3 had long debates about what
would be in/out and how much backward compatibility would
be included.

> one of the earlier guiding principles of Python was to have mainly one
> obvious way to do something and in my reading, I often see MANY ways

Yes, I've never bought the 1 obvious way line. Any decent
programming language offers multiple paths. Language idioms
may evolve to suggest a preferred option but in practice
you need alternatives for expressiveness.

> it. Much of this is caused by adding new features while retaining the old.

And is exacerbated by the Open Source model. Anyone can come up with a
"good idea" to "fix" an issue and it gets adopted. Just look at the long
history of how to start an external process from Python. system(),
popen() - and its several variants - exec(), command(), subprocess,,,

> especially when you use a package written by someone and then abandoned. 

That's always a problem with 3rd party libraries. If its in the core
language and standard library it should be maintained, or at least
go through a controlled and published obsolescence process.

> I wonder if others have written tools (such as in frozen programs) that
> gather up an exact snapshot of the environment needed when you submit a
> paper so it can be replicated!

That's really a configuration management issue and certainly such
tools exist, but they require you to store all the historical
versions within the CM system. The best I ever used was ClearCase
which had a concept of views, controlled by a text file. By changing
the view then restarting the tool it would magically recreate the
full disk image of the project as it had been frozen, including
code, compilers, debuggers etc. The only problem was when the OS
itself was incompatible and that required a virtual machine.
As a maintenance programmer it was absolutely brilliant. You could
take a bug report and within minutes have the relevant version
of the system loaded and ready to work, then next bug you had a
completely different version ready in the blink of an eye (well
maybe 2 or 3 minutes! :) But ClearCase cost megabucks.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_

Re: [Tutor] TESTING

2018-11-02 Thread Avi Gross
I am not totally up on the exact purposes of this group but have noted how
many of the questions asked have been frustrating.

I wonder if it would make any sense to provide a template people might fill
out to suit their needs.

An example might be people who want you to pretty much do their homework for
them from beginning to end. The purpose of a tutor is to guide someone in
learning how to do something for themselves. If they ask for an idea on an
algorithm in English or pseudocode on how to solve the problem, hey might be
given hints but not actual python code. If they wrote a snippet of code on
their own and wonder how to test it, again, there can be advice. If they ask
for the names of packages that might be useful, ditto. If they encounter an
error and can isolate it to a PART of the code, others might be willing to
point out that $ is not valid in Python user names (other than in regular
expressions or strings) and they should consider writing in a language like
PERL or a shell command language that uses it, albeit for another purpose.

But to do it ALL for someone generally is not the role of a tutor in the
real world.

On the other hand, when someone discusses how to optimize their code, and
shows the ways they already tried, it may be valid to present them with a
complete program that illustrates it assuming this is not a homework problem
but a more advanced person that may be interested.

But, to make this message more meaningful, I have a question. In my reading
I see Python has been bifurcated into often incompatible releases we call 2X
and 3X. Many times if you want something to be portable, you have to forgo
using some of the niftier new features. But for a language to evolve, you
sometimes need to bite the bullet. I was one of the earliest uses of C++
when I was at Bell Labs and the decision was then made to not just call it C
(or D or add-one-to-C or even ++C) but make a clean break with C and give it
a new name. The aforementioned PERL also split into incompatible languages. 

So, does anyone see any further breaks in Python such as when 4.0 comes
along or will we have some backward compatibility for a while? As I see it,
one of the earlier guiding principles of Python was to have mainly one
obvious way to do something and in my reading, I often see MANY ways to do
it. Much of this is caused by adding new features while retaining the old.
Yes, I also see places where a new feature is accompanied by deprecating an
older one and eventually removing it. But that too causes incompatibilities
especially when you use a package written by someone and then abandoned. I
recently ran into a problem with an R script I wrote a year or so ago that I
needed to modify in a minor way (re-scale the limits of the Y axis on a
graph) which I might have done in a few minutes. But the package I used to
do part of the work had been modified and the function just printed out that
I should use a replacement function which did not work. Reloading old
versions of the package still did not work because it had many dependencies
and getting them all correct was more work than rewriting my code after
reading what their code used to run.

I wonder if others have written tools (such as in frozen programs) that
gather up an exact snapshot of the environment needed when you submit a
paper so it can be replicated!

Avi

-Original Message-
From: Tutor  On Behalf Of
Mats Wichmann
Sent: Thursday, November 1, 2018 1:54 PM
To: tutor@python.org
Subject: Re: [Tutor] TESTING

On 11/1/18 11:24 AM, Mario Radomirovic wrote:
> All good
> 
> On Thu, 1 Nov 2018 6:17 pm Alan Gauld via Tutor  wrote:
> 
>> On 01/11/2018 14:01, richard mwenya via Tutor wrote:
>>> Hello.
>>> Everyone is quiet or is it my email thats not working?
>>
>> Just quiet, I've seen nothing in the moderators queue for 5 days. But 
>> that happens sometimes.
>>
>> I guess it just means nobody is having any Python issues right now.

or the ones who do gave up on us because people say they won't solve
homework problems :)


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


Re: [Tutor] TESTING

2018-11-01 Thread Mats Wichmann
On 11/1/18 11:24 AM, Mario Radomirovic wrote:
> All good
> 
> On Thu, 1 Nov 2018 6:17 pm Alan Gauld via Tutor  wrote:
> 
>> On 01/11/2018 14:01, richard mwenya via Tutor wrote:
>>> Hello.
>>> Everyone is quiet or is it my email thats not working?
>>
>> Just quiet, I've seen nothing in the moderators queue
>> for 5 days. But that happens sometimes.
>>
>> I guess it just means nobody is having any Python issues
>> right now.

or the ones who do gave up on us because people say they won't solve
homework problems :)


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


Re: [Tutor] TESTING

2018-11-01 Thread Mario Radomirovic
All good

On Thu, 1 Nov 2018 6:17 pm Alan Gauld via Tutor  wrote:

> On 01/11/2018 14:01, richard mwenya via Tutor wrote:
> > Hello.
> > Everyone is quiet or is it my email thats not working?
>
> Just quiet, I've seen nothing in the moderators queue
> for 5 days. But that happens sometimes.
>
> I guess it just means nobody is having any Python issues
> right now.
>
>
> --
> Alan G
> List moderator
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TESTING

2018-11-01 Thread Alan Gauld via Tutor
On 01/11/2018 14:01, richard mwenya via Tutor wrote:
> Hello.
> Everyone is quiet or is it my email thats not working?

Just quiet, I've seen nothing in the moderators queue
for 5 days. But that happens sometimes.

I guess it just means nobody is having any Python issues
right now.


-- 
Alan G
List moderator

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


Re: [Tutor] TESTING

2018-11-01 Thread Ian Clark
Hello,
i'm seeing your message

On Thu, Nov 1, 2018 at 7:03 AM richard mwenya via Tutor 
wrote:

> Hello.
> Everyone is quiet or is it my email thats not working?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] TESTING

2018-11-01 Thread richard mwenya via Tutor
Hello.
Everyone is quiet or is it my email thats not working?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing

2018-01-07 Thread Steven D'Aprano
On Mon, Jan 08, 2018 at 12:31:06AM +, Alan Gauld wrote:
> On 07/01/18 23:38, Steven D'Aprano wrote:
> > I've tried emailing in response to the os.path.realpath thread twice, 
> > and neither email has made it through.
> >
> > Alan, am I stuck in the moderator queue for some reason?
> 
> Nope, nothing from you there.
> 
> And your account settings all look fine.

I've made another attempt to send through my response to the realpath 
thread.



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


Re: [Tutor] Testing

2018-01-07 Thread boB Stepp
On Sun, Jan 7, 2018 at 5:38 PM, Steven D'Aprano  wrote:
> I've tried emailing in response to the os.path.realpath thread twice,
> and neither email has made it through.
>
> Alan, am I stuck in the moderator queue for some reason?

This one made it through.  My original answer to your post last night
took so long to appear on https://mail.python.org/pipermail/tutor that
I finally gave up and went to bed.  But it was there when I awoke
today!

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


[Tutor] Testing

2018-01-07 Thread Steven D'Aprano
I've tried emailing in response to the os.path.realpath thread twice, 
and neither email has made it through.

Alan, am I stuck in the moderator queue for some reason?



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


Re: [Tutor] More tutor testing required

2017-12-08 Thread Alan Gauld via Tutor
On 05/12/17 16:02, Alan Gauld via Tutor wrote:

> address the issues raised and the latest incarnation
> should work (although not well with Opera for some reason!)

I think I've now got scrolling to work on iOS/Safari
and Opera almost works... (a slight glitch when the
width is within a particular size range) If anyone
uses Opera mobile on a mobile device please let me
know if it looks OK.

I've also added a "menu button" that hides/shows
the TOC pane which should help on phones and other
narrow devices.

Once more any feedback is appreciated. Please
send direct to me rather than the list.

If this works I'll finally be able to start updating
the content!...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] More tutor testing required

2017-12-06 Thread Alan Gauld via Tutor
On 05/12/17 16:02, Alan Gauld via Tutor wrote:

> address the issues raised and the latest incarnation
> should work (although not well with Opera for some reason!)

Now better with Opera, although the contents panel is
still not quite right on small screens.

Still looking for feedback from iOS devices (or
even Safari on a desktop PC/laptop for that matter)

Any input appreciated.
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] More tutor testing required

2017-12-05 Thread Alan Gauld via Tutor
Folks,

A couple of weeks ago I asked for testers for my web tutor.
Many thanks to those who helped out. I've now tried to
address the issues raised and the latest incarnation
should work (although not well with Opera for some reason!)

As before I am particularly needful of feedback from
Apple users.

The url is:

http://www.alan-g.me.uk/l2p2/


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Testing print

2016-10-02 Thread Alan Gauld via Tutor
On 02/10/16 02:46, boB Stepp wrote:

>> case. If I know that the result is always an int I can
>> use the first case if I know its always a tuple I can
>> use the second. But not knowing which is just plain
>> messy.
> 
> So in which sorts of scenarios would you use argument unpacking?

Any time a tuple is returned.

The problem I had with your code is that sometimes
you return a string and sometimes a tuple. So I
can only use argument unpacking when I get the tuple.
If I always get a tuple then I can always use unpacking.
Its the mix of incompatible return types that causes
problems.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Testing print

2016-10-01 Thread boB Stepp
On Sat, Oct 1, 2016 at 7:19 PM, Alan Gauld via Tutor  wrote:
> On 01/10/16 23:08, boB Stepp wrote:
>> On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor  
>> wrote:
>>
>>> ... Personally I don't like functions that
>>> sometimes return one and sometimes two results. I'd rather
>>> you returned a None first argument in the first case
>>> to make it consistent.
>>
>> Why don't you like doing this?  What are the pluses and minuses as you
>> see them?
>
>
> Because client code has to guess which return value is relevant

[snip]

> So I need to introduce code to determine whether I got
> an int or a tuple back and then separate code for each
> case. If I know that the result is always an int I can
> use the first case if I know its always a tuple I can
> use the second. But not knowing which is just plain
> messy.

So in which sorts of scenarios would you use argument unpacking?

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


Re: [Tutor] Testing print

2016-10-01 Thread Alan Gauld via Tutor
On 01/10/16 23:08, boB Stepp wrote:
> On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor  
> wrote:
> 
>> ... Personally I don't like functions that
>> sometimes return one and sometimes two results. I'd rather
>> you returned a None first argument in the first case
>> to make it consistent.
> 
> Why don't you like doing this?  What are the pluses and minuses as you
> see them?  


Because client code has to guess which return value is relevant

consider

def f(x):
   if x%2:  # is odd
  return x,x+1
   else: return x

Now I want to use f on a collection of integers:

nums = [1,2,3,4]

for n in nums:
result = f(n)
if result <= 3:   # broken for 1 and 3
   print("success")
else: 

But if I change it to

for n in nums:
result = f(n)
if result[0] <= 3: # now broken for 2 and 4
   print("success")
else: 

So I need to introduce code to determine whether I got
an int or a tuple back and then separate code for each
case. If I know that the result is always an int I can
use the first case if I know its always a tuple I can
use the second. But not knowing which is just plain
messy.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Testing print

2016-10-01 Thread boB Stepp
On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor  wrote:

> ... Personally I don't like functions that
> sometimes return one and sometimes two results. I'd rather
> you returned a None first argument in the first case
> to make it consistent.

Why don't you like doing this?  What are the pluses and minuses as you
see them?  I actually almost wrote it to return None as you suggest,
but as I had not yet had an opportunity to play with argument
unpacking until now, I thought I would do so.  After all, it is about
the learning for me, not always doing things the same way I have been
doing them.

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


Re: [Tutor] Testing print

2016-10-01 Thread Alan Gauld via Tutor
On 01/10/16 16:12, boB Stepp wrote:

>>> This module will take a string and right justify it so that the last 
>>> character
>>> of the line will fall in column 70 of the display.  The results will be
>>> printed to stdout.'''
>>>
>> Do you need print_msgs()?
>> Won't it work the same with
>>
>>print(right_justify(input_string))
>>

> I would still need to unpack the arguments returned by right_justify()
> that get fed to print():

Ah, I read the assignment spec but not your comment (or code)
so didn't notice that your justify function sometimes returns
multiple arguments. Personally I don't like functions that
sometimes return one and sometimes two results. I'd rather
you returned a None first argument in the first case
to make it consistent.

But given you are returning multiple arguments then
yes you need:

> print(*right_justify(input_string))

But coming back to the issue of mixing display and logic
I'd probably just raise a ValueError if the input string is
too long and leave it as a user requirement to check
the length of the input or catch the error and display
whatever message they felt appropriate. (You can include
the error message in the raise if you feel the need)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Testing print

2016-10-01 Thread boB Stepp
On Sat, Oct 1, 2016 at 2:02 AM, Alan Gauld via Tutor  wrote:

> Do you need print_msgs()?
> Won't it work the same with
>
>print(right_justify(input_string))
>
> You are only feeding one line at a time into the print msgs.
>
> You could do it all in a new print_msgs() like:
>
> def print_msgs(formatter, msgs):
> for msg in msgs:
> print(formatter(msg))
>
> And main() reduces to
>
> def main():
> print_msgs(right_justify, input_strings)

I have to say this thought you gave ties in nicely with the other
thread ([Tutor] Passing functions as arguments to other functions) I
started in parallel with this one.  A practical example of passing a
function to another function...



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


Re: [Tutor] Testing print

2016-10-01 Thread boB Stepp
On Sat, Oct 1, 2016 at 2:02 AM, Alan Gauld via Tutor  wrote:
> On 01/10/16 05:24, boB Stepp wrote:
>
>> ===
>> '''Exerise 3.1 from "Think Python 2" by Allen Downey.
>>
>> This module will take a string and right justify it so that the last 
>> character
>> of the line will fall in column 70 of the display.  The results will be
>> printed to stdout.'''
>>
>> def right_justify(a_string):
>  
>> def print_msgs(*msgs):
>> '''Prints messages to stdout.'''
>>
>> for msg in msgs:
>> print(msg)
>>
>> def main(input_strings):
>> '''Run main program.'''
>>
>> print('0123456789' * 7)# Print a number guide to check length of 
>> line.
>> for input_string in input_strings:
>> print_msgs(*right_justify(input_string))
>
> Do you need print_msgs()?
> Won't it work the same with
>
>print(right_justify(input_string))
>
> You are only feeding one line at a time into the print msgs.

[snip]

> But I think I'd just leave it as you have it but
> without the print_msgs()...

I would still need to unpack the arguments returned by right_justify()
that get fed to print():

print(*right_justify(input_string))

And I would have to add an additional "\n" to msg in the else clause
of right_justify():

 msg = ("The string has too many characters (> 70)!\n" +
"Only a partial, 70 character line will be returned.\n")

so that the result formats the same as the original intent.  This
gives me main() now as:

def main(input_strings):
'''Run main program.'''

print('0123456789' * 7)# Print a number guide to check length of line.
for input_string in input_strings:
print(*right_justify(input_string))

Doing this did not occur to me because I was blind to treating
print(*args) like any other function in regards to argument unpacking.

One of the many wonderful things about Python is its consistency!

Thanks, Alan!



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


Re: [Tutor] Testing print

2016-10-01 Thread Alan Gauld via Tutor
On 01/10/16 05:24, boB Stepp wrote:

> ===
> '''Exerise 3.1 from "Think Python 2" by Allen Downey.
> 
> This module will take a string and right justify it so that the last character
> of the line will fall in column 70 of the display.  The results will be
> printed to stdout.'''
> 
> def right_justify(a_string):
 
> def print_msgs(*msgs):
> '''Prints messages to stdout.'''
> 
> for msg in msgs:
> print(msg)
> 
> def main(input_strings):
> '''Run main program.'''
> 
> print('0123456789' * 7)# Print a number guide to check length of line.
> for input_string in input_strings:
> print_msgs(*right_justify(input_string))

Do you need print_msgs()?
Won't it work the same with

   print(right_justify(input_string))

You are only feeding one line at a time into the print msgs.

You could do it all in a new print_msgs() like:

def print_msgs(formatter, msgs):
for msg in msgs:
print(formatter(msg))

And main() reduces to

def main():
print_msgs(right_justify, input_strings)

But I think I'd just leave it as you have it but
without the print_msgs()...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Testing print

2016-09-30 Thread boB Stepp
On Sat, Oct 1, 2016 at 12:12 AM, Richard Doksa  wrote:
>  unsubscibe please

If you wish to unsubscribe, go to the bottom of this page and follow
its instructions:

https://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Testing print

2016-09-30 Thread boB Stepp
On Fri, Sep 30, 2016 at 5:07 AM, Steven D'Aprano  wrote:

[snip]

> and preferably three:
>
> (1) function that does the calculation;
> (2) function that does the output;
> (3) function that calls (1) and then (2)
>
>
> If (1) and (2) are well-designed, then (3) is so trivial it needs no
> tests:
>
> def main():
> x = calculate(stuff)
> report(x)
>
> but of course it's not always that simple. Nevertheless, that's the
> ideal you should aim for.

OK, I want to make sure I have this thoroughly comprehended.  I have
rewritten my once simple program into the following:

===
'''Exerise 3.1 from "Think Python 2" by Allen Downey.

This module will take a string and right justify it so that the last character
of the line will fall in column 70 of the display.  The results will be
printed to stdout.'''

def right_justify(a_string):
'''This fucntion will take the string, "a_string", and right justify it by
padding it with spaces until its last character falls in column 70 of the
display.  If "a_string" has more than 70 characters, then "a_string" will
be truncated to 70 characters.  The padded or truncated string will be
returned along with a message if "a_string" is truncated.'''

if len(a_string) <= 70:
num_pad_spcs = 70 - len(a_string)
return ((' ' * num_pad_spcs) + a_string),# Note trailing comma.
else:
msg = ("The string has too many characters (> 70)!\n" +
"Only a partial, 70 character line will be returned.")
return msg, a_string[:70]

def print_msgs(*msgs):
'''Prints messages to stdout.'''

for msg in msgs:
print(msg)

def main(input_strings):
'''Run main program.'''

print('0123456789' * 7)# Print a number guide to check length of line.
for input_string in input_strings:
print_msgs(*right_justify(input_string))


if __name__ == '__main__':
input_strings = [
"Monty Python",
"She's a witch!",
"Beware of the rabbit!!!  She is a vicious beast who will rip"
" your throat out!",
""]
main(input_strings)
=

Does this meet the criteria of each function doing its specific thing?
 Or is there something else I need to decouple/improve?

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


Re: [Tutor] Testing print

2016-09-30 Thread boB Stepp
On Fri, Sep 30, 2016 at 5:07 AM, Steven D'Aprano  wrote:
> On Thu, Sep 29, 2016 at 09:24:51PM -0500, boB Stepp wrote:

>> Second, it seems that prints are often intermingled with the main
>> logic of a function and only serve to pass on a message to the user.
>
> Yeah, you normally shouldn't do that. Imagine if every time you called
> len(something), the len function was chatty and decided to print
> something. It would make it really hard to print anything where len() is
> involved as part of the calculation. Say I want to print a formatted
> table:
>
>     
> COLUMN 1  COLUMN 2  COLUMN 3
>     
> alpha secondgamma
>   letter
>     
>
> but got something like:
>
>
> hi this is len I just wanted to let you know I'm working hard
>  hi this is len I just wanted to let you know I'm working hard
>  hi this is len I just wanted to let you know I'm working hard
> 
> hi this is len I just wanted to let you know I'm working hard COLUMN
> 1 hi this is len oops something went wrong but that's okay I fixed it
> COLUMN 2 hi this is len I just wanted to let you know I'm working really
> hard you ought to be grateful okay COLUMN 3
> hi this is len I just wanted to let you know I'm working hard
>  hi this is len ...

  You're a funny guy, Steve!  I must confess, I have been very
cavalier in using prints in my functions.  It was not until I was
trying to imagine last night how to test the example function I gave
that it truly dawned on me that this has been a bad practice on my
part.  This TDD practice has been making me think about my coding
efforts in ways that I never considered previously.  Testing is a
very, very good thing!

Thanks, Steve!



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


Re: [Tutor] Testing print

2016-09-30 Thread Steven D'Aprano
On Thu, Sep 29, 2016 at 09:24:51PM -0500, boB Stepp wrote:
> Testing output of print functions (Py 3).  First off, is it worth it to do so?

Unless you are writing tests for the Python language itself, you can 
assume that print() itself is working.

You should test functions that call print: call the function (or method) 
and see that it does print what you expect.

But, in general, you should not intermingle *calculation* and *output*. 
There may be a few examples, but functions should do one, or the other, 
not both. This makes it easy to reason about, re-use, and test, both 
functions.

For example, suppose you have a function that takes a single string, 
formats it in some way, and then displays it in a dialog box. You should 
split that into two:

- take a string and format it;
- take a formatted string and display it.

Same applies to print, writing to log files, or writing output to any 
other file.

> Second, it seems that prints are often intermingled with the main
> logic of a function and only serve to pass on a message to the user.

Yeah, you normally shouldn't do that. Imagine if every time you called 
len(something), the len function was chatty and decided to print 
something. It would make it really hard to print anything where len() is 
involved as part of the calculation. Say I want to print a formatted 
table:

    
COLUMN 1  COLUMN 2  COLUMN 3
    
alpha secondgamma 
  letter
    

but got something like:


hi this is len I just wanted to let you know I'm working hard 
 hi this is len I just wanted to let you know I'm working hard 
 hi this is len I just wanted to let you know I'm working hard 

hi this is len I just wanted to let you know I'm working hard COLUMN 
1 hi this is len oops something went wrong but that's okay I fixed it 
COLUMN 2 hi this is len I just wanted to let you know I'm working really 
hard you ought to be grateful okay COLUMN 3
hi this is len I just wanted to let you know I'm working hard 
 hi this is len ...

etc. Chatty functions are *the worst*, unless they are specifically 
intended for reporting and output. Don't mix calculation and output.

Or rather, its okay to mix them, provided you have *at least* two 
separate functions:

(1) function that does the calculation;
(2) function that calls (1) and then does the output

and preferably three:

(1) function that does the calculation;
(2) function that does the output;
(3) function that calls (1) and then (2)


If (1) and (2) are well-designed, then (3) is so trivial it needs no 
tests:

def main():
x = calculate(stuff)
report(x)

but of course it's not always that simple. Nevertheless, that's the 
ideal you should aim for.


[...]
> def right_justify(a_string):
> '''This fucntion will take the string, "a_string", and right justify it by
> padding it with spaces until its last character falls in column 70 of the
> display.  The padded string will be returned.'''
> 
> if len(a_string) <= 70:
> num_pad_spcs = 70 - len(a_string)
> return (' ' * num_pad_spcs) + a_string
> else:
> print("The string has too many characters (> 70)!")
> print("Only a partial, 70 character line will be returned.")
> return a_string[:70]

Too chatty! It mixed output and calculation. Instead, you should just 
document what the function does ("pads or truncates the string to 
exactly 70 characters") and leave it at that, or if you must report on 
what it is doing, consider:

- print warning messages to stderr instead of stdout;

- write warnings to a log file;

- use the warnings module:

import warnings
warnings.warn("unable to pad string, as it is too long; truncating instead")

- raise an exception and stop processing.


[...]
> So (Even though this is a simple
> exercise.) should I test the prints?

If you don't test it, how do you know it works?


> Anyway, it would seem that the only way to capture the output of a
> print is to redirect the stdout to something I can capture and compare
> against.  Googling brings up some people doing something with mock
> objects, some redirecting to a string buffer, some to a file, some to
> other things.  What, in your opinion(s), is the cleanest way to handle
> this?

I find that using stringIO is the simplest and most obvious way to do 
it, although I don't have a lot of experience with the mock objects.



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


[Tutor] Testing print

2016-09-29 Thread boB Stepp
Testing output of print functions (Py 3).  First off, is it worth it to do so?

Second, it seems that prints are often intermingled with the main
logic of a function and only serve to pass on a message to the user.
For example, in an earlier thread (

Questions as to how to run the same unit test multiple times on
varying input data.:
https://mail.python.org/pipermail/tutor/2016-September/109686.html) I
finally wound up with this function:


def right_justify(a_string):
'''This fucntion will take the string, "a_string", and right justify it by
padding it with spaces until its last character falls in column 70 of the
display.  The padded string will be returned.'''

if len(a_string) <= 70:
num_pad_spcs = 70 - len(a_string)
return (' ' * num_pad_spcs) + a_string
else:
print("The string has too many characters (> 70)!")
print("Only a partial, 70 character line will be returned.")
return a_string[:70]


I had to consider the possibility that the string supplied to the
function was more than 70 characters long.  The exercise in "Think
Python2" did not give any input into how to handle such a case, so I
decided I would return 70 characters worth of the overly long string
and print a message to the user.  So (Even though this is a simple
exercise.) should I test the prints?  And if so, how to I separate
this out?  In my mind, if I am going to be testing calls to print,
then perhaps I should write a separate function, say "print_msg(msg)"
and put that in place of the prints in the else clause and then test
the print_msg function, where "print(msg)" would be isolated in its
own little function to be tested..

Anyway, it would seem that the only way to capture the output of a
print is to redirect the stdout to something I can capture and compare
against.  Googling brings up some people doing something with mock
objects, some redirecting to a string buffer, some to a file, some to
other things.  What, in your opinion(s), is the cleanest way to handle
this?

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


[Tutor] Testing tutor list server

2016-09-20 Thread Alan Gauld via Tutor
Just checkin'

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

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


[Tutor] testing, please disregard

2015-08-18 Thread Tim Johnson
I have had some problems with another python.org ML.
I am sending this to see if it is received.
Please disregard.
thanks
-- 
Tim 
http://www.akwebsoft.com, http://www.tj49.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing a string to see if it contains a substring (dw)

2015-01-23 Thread Mark Lawrence

On 22/01/2015 15:40, dw wrote:

Thanks for your good comments.
I do think I found a work around

body = ""
for x in range(0,len(line_array)):
 test_line = len(re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',
 line_array[x]))
 if test_line > 0:
 body = body + line_array[x]+"\n"


Using range in a Python for loop is often a code smell.  Your names are 
poor as well.  The Pythonic way is:-


body = ""
for line in line_array:
linelen = len(re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{4}', line))
if linelen > 0:
body += line + "\n"

Also note that although the above is adequate for small data sets, the 
performance dives terribly as the size of the data set goes up.  Your 
homework for this weekend is to research how one normally joins strings 
in Python and report back.  Have a good one :)


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] Testing a string to see if it contains a substring (Steve and Mark)

2015-01-23 Thread Mark Lawrence

On 22/01/2015 16:15, dw wrote:

Thanks so much Steve and Mark!
You've given me a lot to chew on. :-D
I'll pursue!
More Python FUN!!




Thanks for the thanks, but please don't change the subject as it breaks 
threading, making it more difficult for people to find things in future 
in the mailing list archives.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] Testing a string to see if it contains a substring (dw)

2015-01-23 Thread dw
Thanks for your good comments.
I do think I found a work around

body = ""
for x in range(0,len(line_array)):
test_line = len(re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',
line_array[x]))
if test_line > 0:
body = body + line_array[x]+"\n"

For each iteration re.findall returns a list object based upon the regex
search.
If an element contains "01/04/2013".the regex is found, and
re.findall returns it as a list object ['01/04/2013']
I can then perform a len function on that which will = 1, since the list
contains only one string object.
For the row in which the regex is not found, re.findall will return []
Which is essentially a list with 0 objects, and the len function will
then = 0.

Thanks Alan G for your example!!
It will be fun to try it!! :-]
I look for the KISS model in coding, and I like your example.
-- 
 bw...@fastmail.net

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


Re: [Tutor] Testing a string to see if it contains a substring (Steve and Mark)

2015-01-23 Thread dw
Thanks so much Steve and Mark!
You've given me a lot to chew on. :-D
I'll pursue!
More Python FUN!!




Based on your description, I think the best way to do this is:

# remove blank lines
line_array = [line for line in line_array if line != '\n']


Possibly this is even nicer:

# get rid of unnecessary leading and trailing whitespace on each line
# and then remove blanks
line_array = [line.strip() for line in line_array]
line_array = [line for line in line_array if line]


This is an alternative, but perhaps a little cryptic for those not 
familiar with functional programming styles:

line_array = filter(None, map(str.strip, line_array))

No regexes required!

However, it isn't clear from your example whether non-blank lines 
*always* include a date. Suppose you have to filter date lines from 
non-date lines?

Start with a regex and a tiny helper function, which we can use lambda 
to embed directly in the call to filter:

DATE = r'\d{2}/\d{2}/\d{4}'
line_array = filter(lambda line: re.search(DATE, line), line_array)

In Python version 3, you may need to wrap that in a call to list:

line_array = list(filter(lambda line: re.search(DATE, line),
line_array))

but that isn't needed in Python 2.

If that's a bit cryptic, here it is again as a list comp:

DATE = r'\d{2}/\d{2}/\d{4}'
line_array = [line for line in line_array if re.search(DATE, line)]


Let's get rid of the whitespace at the same time!

line_array = [line.strip() for line in line_array if 
  re.search(DATE, line)]


And if that's still too cryptic ("what's a list comp?") here it is again 
expanded out in full:


temp = []
for line in line_array:
if re.search(DATE, line):
temp.append(line.strip())
line_array = temp


How does this work? It works because the two main re functions, 
re.match and re.search, return None when then regex isn't found, and a 
MatchObject when it is found. None has the property that it is 
considered "false" in a boolean context, while MatchObjects are always 
consider "true".

We don't care *where* the date is found in the string, only whether or 
not it is found, so there is no need to check the starting position.



-- 
Steven

=
I'd use 
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime 
to test the first ten characters of the string.  I'll leave that and 
handling IndexError or ValueError to you :)
-- 
 bw...@fastmail.net

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


Re: [Tutor] Testing a string to see if it contains a substring

2015-01-21 Thread Mark Lawrence

On 21/01/2015 18:14, dw wrote:

Hello Python Friends.
I have a string array, called "line_array".

There may be up to 50 or more elements in the array.
So:
- line_array[1] may contain "01/04/2013  10:43 AM17,410,217
DEV-ALL-01-04-13.rlc\n"
- line_array[2] may contain "01/25/2013  03:21 PM17,431,230
DEV-ALL-01-25-2013.rlc\n"
- line_array[3] may contain "\n"

I want to retain all elements which are valid (i.e. contains a date
value xx/xx/)
So I'm using a regex search for the date value located at the start of
each element...this way

misc_int1 =
re.search(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',line_array[x]).start()

This method works really well when the regex date characters are found.
It returns the value 0 to misc_int1 because the date regex starts at 0
position.
I was hoping the .start() method would return a -1 value for the
instance in which the regex search string is not found.
That way I could iterate through the elements and retain only the valid
ones.

However, the .start() method throws an error if the regex search string
is not found.

Your suggestions greatly appreciated!
Thanks!!
d :-]



I'd use 
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime 
to test the first ten characters of the string.  I'll leave that and 
handling IndexError or ValueError to you :)


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] Testing a string to see if it contains a substring

2015-01-21 Thread Danny Yoo
How large will your array be in production?

If it going to be very large, you may want to consider a database.
You're simulating a collection of records as an in-memory sequence of
flat strings.  This design won't scale, so if you are working with a
lot of data, you may want to look into a dedicated database.



> This method works really well when the regex date characters are found.
> It returns the value 0 to misc_int1 because the date regex starts at 0
> position.
> I was hoping the .start() method would return a -1 value for the
> instance in which the regex search string is not found.
> That way I could iterate through the elements and retain only the valid
> ones.

With regards to your original question: the return type of a search()
is either a match object, or a None.  So your program's control-flow
logic should be accounting for these two possibilities.  At the
moment, the code assumes that it always gets a match object, but that
assumption doesn't hold and explains why you're seeing run-time error
messages.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing a string to see if it contains a substring

2015-01-21 Thread Steven D'Aprano
On Wed, Jan 21, 2015 at 10:14:42AM -0800, dw wrote:
> Hello Python Friends.
> I have a string array, called "line_array".

Do you mean a list of strings? "String array" is not a standard Python 
term, it could mean something from the array module, from numpy, or 
something completely different.

It's often good to give simplified example code, rather than try to 
describe it in words, e.g.:

line_array = ["line 1", "line 2"]

> There may be up to 50 or more elements in the array.
> So:
> - line_array[1] may contain "01/04/2013  10:43 AM17,410,217
> DEV-ALL-01-04-13.rlc\n"
> - line_array[2] may contain "01/25/2013  03:21 PM17,431,230
> DEV-ALL-01-25-2013.rlc\n"
> - line_array[3] may contain "\n"

What happened to line_array[0] ?


> I want to retain all elements which are valid (i.e. contains a date
> value xx/xx/)
> So I'm using a regex search for the date value located at the start of
> each element...this way

Based on your description, I think the best way to do this is:

# remove blank lines
line_array = [line for line in line_array if line != '\n']


Possibly this is even nicer:

# get rid of unnecessary leading and trailing whitespace on each line
# and then remove blanks
line_array = [line.strip() for line in line_array]
line_array = [line for line in line_array if line]


This is an alternative, but perhaps a little cryptic for those not 
familiar with functional programming styles:

line_array = filter(None, map(str.strip, line_array))

No regexes required!

However, it isn't clear from your example whether non-blank lines 
*always* include a date. Suppose you have to filter date lines from 
non-date lines?

Start with a regex and a tiny helper function, which we can use lambda 
to embed directly in the call to filter:

DATE = r'\d{2}/\d{2}/\d{4}'
line_array = filter(lambda line: re.search(DATE, line), line_array)

In Python version 3, you may need to wrap that in a call to list:

line_array = list(filter(lambda line: re.search(DATE, line), line_array))

but that isn't needed in Python 2.

If that's a bit cryptic, here it is again as a list comp:

DATE = r'\d{2}/\d{2}/\d{4}'
line_array = [line for line in line_array if re.search(DATE, line)]


Let's get rid of the whitespace at the same time!

line_array = [line.strip() for line in line_array if 
  re.search(DATE, line)]


And if that's still too cryptic ("what's a list comp?") here it is again 
expanded out in full:


temp = []
for line in line_array:
if re.search(DATE, line):
temp.append(line.strip())
line_array = temp


How does this work? It works because the two main re functions, 
re.match and re.search, return None when then regex isn't found, and a 
MatchObject when it is found. None has the property that it is 
considered "false" in a boolean context, while MatchObjects are always 
consider "true".

We don't care *where* the date is found in the string, only whether or 
not it is found, so there is no need to check the starting position.



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


Re: [Tutor] Testing a string to see if it contains a substring

2015-01-21 Thread Alan Gauld

On 21/01/15 18:14, dw wrote:


- line_array[1] may contain "01/04/2013  10:43 AM17,410,217
DEV-ALL-01-04-13.rlc\n"
- line_array[2] may contain "01/25/2013  03:21 PM17,431,230
DEV-ALL-01-25-2013.rlc\n"
- line_array[3] may contain "\n"

I want to retain all elements which are valid (i.e. contains a date
value xx/xx/)


You need a bit more detail.
Can a row contain anything other than just \n if there is no date?
Is the date always at the start and always the same length?


So I'm using a regex search for the date value located at the start of
each element...this way

misc_int1 =
re.search(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',line_array[x]).start()


You might be better with re.match() if its always at the start of the line.


This method works really well when the regex date characters are found.
It returns the value 0 to misc_int1 because the date regex starts at 0
position.
I was hoping the .start() method would return a -1 value for the
instance in which the regex search string is not found.


You can simply split the code over two lines and check the result:

result = re.search(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',line_array[x])
if result is not None:
   misc_intl = result.start()

There are no prizes for writing code on one line, so don't be afraid
to separate it out.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Testing a string to see if it contains a substring

2015-01-21 Thread dw
Hello Python Friends.
I have a string array, called "line_array".

There may be up to 50 or more elements in the array.
So:
- line_array[1] may contain "01/04/2013  10:43 AM17,410,217
DEV-ALL-01-04-13.rlc\n"
- line_array[2] may contain "01/25/2013  03:21 PM17,431,230
DEV-ALL-01-25-2013.rlc\n"
- line_array[3] may contain "\n"

I want to retain all elements which are valid (i.e. contains a date
value xx/xx/)
So I'm using a regex search for the date value located at the start of
each element...this way

misc_int1 =
re.search(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',line_array[x]).start()

This method works really well when the regex date characters are found.
It returns the value 0 to misc_int1 because the date regex starts at 0
position.
I was hoping the .start() method would return a -1 value for the
instance in which the regex search string is not found.
That way I could iterate through the elements and retain only the valid
ones.

However, the .start() method throws an error if the regex search string
is not found.

Your suggestions greatly appreciated!
Thanks!!
d :-]

-- 
 bw...@fastmail.net

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


Re: [Tutor] Testing a method in a class with nosetests

2013-04-21 Thread eryksun
On Sun, Apr 21, 2013 at 9:33 PM, Steven D'Aprano  wrote:
>
> it's NOT because you failed to post plain text, since you actually did.

Actually it's a multipart message with both plain text and HTML, with
the digest quoted in each version. It helps that the HTML is using
" " and  that map directly to "=A0" and "=0A". The  and
 tags are used for color and font styling, rather than layout.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing a method in a class with nosetests

2013-04-21 Thread Steven D'Aprano

On 22/04/13 10:49, Alex Baker wrote:

Hello,
I've been lurking tutor for the last couple months and have quite enjoyed it!



Welcome, and congratulations on your first post! Unfortunately I have to start 
with a complaint :-( but it's NOT because you failed to post plain text, since 
you actually did.

When starting a new thread, please create a new, blank email, don't reply to an 
existing email. Especially not when that email is a digest containing four 
complete emails completely unrelated to your post! The end result is that at 
the bottom of your post is a copy of a complete digest, nearly 200 lines worth 
of unrelated, irrelevant stuff. (And we're lucky it was only 200 lines, during 
a busy week, digests could potentially be thousands of lines!) And then you 
compounded it by replying to the first email, and so ended up with those 200 
lines quoted TWICE.



I'm having a problem testing a method using nosetests. The assignment (Learn Python the 
Hard Way) asks that I write tests for a package using assert_equal and assert_raises. 
I've conquered the assert_equals but I'm having issues with assert_raises. I can't figure 
out how am I supposed to test a method in a class with an __init__. I understand the 
assert_raises works assert_raises("ERROR", callable, parameters), and the 
parameters get sent to nosetests, but because of the __init__ I have no parameters to 
send.



Unfortunately, I'm not familiar with nose, and so I'm guessing, but I would say 
replace this call:


assert_raises("ParserError", _test_words("will fail"))

with this:

assert_raises("ParserError", _test_words, "will fail")

or possibly this:

assert_raises("ParserError", _test_words, ["will fail"])



I expect that the first version fails because the call to _test_words() 
function raises an exception before nose gets to handle it. This is why 
assert_raises takes a function argument, followed by its argument.




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


Re: [Tutor] Testing a method in a class with nosetests (Alex Baker)

2013-04-21 Thread Alex Baker
Dang, forgot to send in plain text! Sorry... 

Here is the GitHub link http://github.com/robotsmack/ex48



 From: "tutor-requ...@python.org" 
To: tutor@python.org 
Sent: Sunday, April 21, 2013 6:51 PM
Subject: Tutor Digest, Vol 110, Issue 87
 

Send Tutor mailing list submissions to
    tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
    http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
    tutor-requ...@python.org

You can reach the person managing the list at
    tutor-ow...@python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

   1. Py 3 package maturity - good links (Jim Mooney)
   2. Re: Py 3 package maturity - good links (Dave Angel)
   3. Testing a method in a class with nosetests (Alex Baker)


--

Message: 1
Date: Sun, 21 Apr 2013 09:24:06 -0700
From: Jim Mooney 
To: tutor@python.org
Subject: [Tutor] Py 3 package maturity - good links
Message-ID:
    
Content-Type: text/plain; charset="iso-8859-1"

> On the other hand, from the perspective of "When will the *majority* of
> publicly-available libraries and packages support Python 3, then the answer
> is "Right now". The Python 3 Wall of Shame turned mostly green some time
> ago,
> and is now known as the Python 3 Wall of Superpowers:
>
> https://python3wos.appspot.com/
>
> Based on the number of downloads, almost three quarters of the Top 50
> Python
> packages support Python 3:
>
> http://py3ksupport.appspot.com/
>

Thanks. Very useful links to save that would have taken time for me to find
on my own.

As for "syllabus," probably a dream for a dynamic language ;')  I was
thinking of the time my brother, a Lit grad, gave me a syllabus of
literature to read - still working on it forty years later.

Jim
*
*
-- next part --
An HTML attachment was scrubbed...
URL: 
<http://mail.python.org/pipermail/tutor/attachments/20130421/f1a36fa0/attachment-0001.html>

--

Message: 2
Date: Sun, 21 Apr 2013 16:05:42 -0400
From: Dave Angel 
To: tutor@python.org
Subject: Re: [Tutor] Py 3 package maturity - good links
Message-ID: <51744696.2090...@davea.name>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 04/21/2013 12:24 PM, Jim Mooney wrote:
>> On the other hand, from the perspective of "When will the *majority* of
>> publicly-available libraries and packages support Python 3, then the answer
>> is "Right now". The Python 3 Wall of Shame turned mostly green some time
>> ago,
>> and is now known as the Python 3 Wall of Superpowers:
>>
>> https://python3wos.appspot.com/
>>
>> Based on the number of downloads, almost three quarters of the Top 50
>> Python
>> packages support Python 3:
>>
>> http://py3ksupport.appspot.com/
>>
>
> Thanks. Very useful links to save that would have taken time for me to find
> on my own.
>
> As for "syllabus," probably a dream for a dynamic language ;')  I was
> thinking of the time my brother, a Lit grad, gave me a syllabus of
> literature to read - still working on it forty years later.
>
>
>
http://pymotw.com/2/
     This could be one way to learn about new (to you) Python modules in 
a systematic way.

On the other hand, if you're looking for a syllabus of studying 
languages (plural), consider
    1) a dynamic language
    2) a compile one
    3) an assembler
    4) other    (lisp, Forth, ML, Prolog, ...)

Each category is enough different that you have to learn all new habits. 
  But knowing each one is valuable when using the other three types.




-- 
DaveA


--

Message: 3
Date: Sun, 21 Apr 2013 17:49:09 -0700 (PDT)
From: Alex Baker 
To: "tutor@python.org" 
Subject: [Tutor] Testing a method in a class with nosetests
Message-ID:
    <1366591749.43705.yahoomail...@web120205.mail.ne1.yahoo.com>
Content-Type: text/plain; charset="iso-8859-1"

Hello,
I've been lurking tutor for the last couple months and have quite enjoyed it!

I'm having a problem testing a method using nosetests. The assignment (Learn 
Python the Hard Way) asks that I write tests for a package using assert_equal 
and assert_raises. I've?conquered the assert_equals but I'm having issues with 
assert_raises. I can't figure out how am I supposed to test a method in a class 
with an __init__. I understand the assert_raises works assert_raises("ERROR", 
callable, parameters), and the parameters get sent to nosetests, but because of 
the __init__ I have no parameters to send.


# 

[Tutor] Testing a method in a class with nosetests

2013-04-21 Thread Alex Baker
Hello,
I've been lurking tutor for the last couple months and have quite enjoyed it!

I'm having a problem testing a method using nosetests. The assignment (Learn 
Python the Hard Way) asks that I write tests for a package using assert_equal 
and assert_raises. I've conquered the assert_equals but I'm having issues with 
assert_raises. I can't figure out how am I supposed to test a method in a class 
with an __init__. I understand the assert_raises works assert_raises("ERROR", 
callable, parameters), and the parameters get sent to nosetests, but because of 
the __init__ I have no parameters to send.


# main module code
class ParserError(Exception):
    pass

class Parser(object):

    def __init__(self, word_list):
        self.word_list = word_list

    def parse_object(self):
        skip(self.word_list, 'stop')
        next = peek(self.word_list)

        if next == 'noun':
            return match(self.word_list, 'noun')
        if next == 'direction':
            return match(self.word_list, 'direction')
        else:
            raise ParserError("Expected a noun or direction next.")

# test code
from nose.tools import *
from ex48 import parser
from ex48 import lexicon

def _test_words(input):    
    words = lexicon.scan(input)
    test = parser.Parser(words)
    return test

def test_parse_object():    
    assert_equal(_test_words("the bear").parse_object(), 
                ('noun', 'bear'))
    assert_equal(_test_words("the the  princess").parse_object(),
                ('noun', 'princess'))
    assert_equal(_test_words("the nortH").parse_object(), 
                ('direction', 'north'))
    assert_raises("ParserError", _test_words("will fail"))

# nosetests output
ERROR: tests.parser_tests.test_parse_object
--
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/Users/robotsmack/hack/python_projects/ex48/tests/parser_tests.py", 
line 17, in test_parse_object
    assert_raises("ParserError", _test_words("will fail"))
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py",
 line 456, in assertRaises
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py",
 line 113, in __exit__
TypeError: issubclass() arg 2 must be a class or tuple of classes

Obviously a bunch a code was snipped, but I don't think its relevant to my 
question. But just in case, I'm currently fumbling my way through putting up 
the whole package on GitHub.

Thanks in advance!
_Alex



 From: "tutor-requ...@python.org" 
To: tutor@python.org 
Sent: Sunday, April 21, 2013 4:00 AM
Subject: Tutor Digest, Vol 110, Issue 86
 

Send Tutor mailing list submissions to
    tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
    http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
    tutor-requ...@python.org

You can reach the person managing the list at
    tutor-ow...@python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

   1. Time frame for Py 3 Maturity (Jim Mooney)
   2. Re: Time frame for Py 3 Maturity (Steven D'Aprano)
   3. Re: 3to2? (Steven D'Aprano)
   4. Re: Time frame for Py 3 Maturity (Alan Gauld)


--

Message: 1
Date: Sat, 20 Apr 2013 19:10:23 -0700
From: Jim Mooney 
To: tutor@python.org
Subject: [Tutor] Time frame for Py 3 Maturity
Message-ID:
    
Content-Type: text/plain; charset="iso-8859-1"

> This is why we tend to recommend 2.7 for anyone doing serious work in
> Python.
>

Understood. I am in no rush, but what do you think it the time frame when
Py 3 will be mature? A year from now? Two years? At some point I might want
to use it more practically. Or maybe there will be huge inflation, I'll go
broke, and have to use it more practically ;')

Also, is there a good syllabus for the best way to progress in this
language? One can certainly get sidetracked.

-- 
*Jim Mooney

Today is the day that would have been tomorrow if yesterday was today
*
-- next part --
An HTML attachment was scrubbed...
URL: 


--

Message: 2
Date: Sun, 21 Apr 2013 14:02:36 +1000
From: Steven D'Aprano 
To: tutor@python.org
Subject: Re: [Tutor] Time frame for Py 3 Maturity
Message-ID: <517364dc.3080...@pearwood.info>
Content-Type: text/plain; charset=UTF-8; format=flowed

On 21/04/13 12:10, Jim Mooney wrote:
>> This is why we tend to recommend 2.7 for anyone doing serious work in
>> Python.
>>
>
> Understood. I am in no rush, but what do you think it the time frame when
> Py 3 will be mature? A year from now

Re: [Tutor] Testing dymamically created methods

2012-01-10 Thread Thomas Maier
On Tue, Jan 10, 2012 at 3:31 PM, Walter Prins  wrote:
> Hi,
>
> On 10 January 2012 12:15, Thomas Maier  wrote:
>> This code works without py.test or nosetests. For example if I use print
>> instead of 'assert'.
>> Both py.test and nosetests failed to execute this correctly.
>> Or maybe they do execute it correctly, I just don't understand it..:)
>> They both report only single test was executed.
>> I would like to see test report for each method executed in 'for' loop.
>> Is it possible?
>
> For nose, I *think* you can basically achieve what you want by turning
> test_run() into a generator (by essentially replacing the call to the
> test_method() with a suitable "yield" statement.   See here:
> http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators
Works perfect.

> Additionally you might also look at the TestLoader functionality for
> taking further control over how and where your tests are loaded, e.g.
> see for example nose.loader.loadTestsFromGenerator() or
> nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other
> methods) here:
> http://readthedocs.org/docs/nose/en/latest/api/loader.html
Will try later.

> HTH, my $0.02 worth,
>
> Walter

Thank you very much!

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


Re: [Tutor] Testing dymamically created methods

2012-01-10 Thread Walter Prins
Hi,

On 10 January 2012 12:15, Thomas Maier  wrote:
> This code works without py.test or nosetests. For example if I use print
> instead of 'assert'.
> Both py.test and nosetests failed to execute this correctly.
> Or maybe they do execute it correctly, I just don't understand it..:)
> They both report only single test was executed.
> I would like to see test report for each method executed in 'for' loop.
> Is it possible?

For nose, I *think* you can basically achieve what you want by turning
test_run() into a generator (by essentially replacing the call to the
test_method() with a suitable "yield" statement.   See here:
http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators

Additionally you might also look at the TestLoader functionality for
taking further control over how and where your tests are loaded, e.g.
see for example nose.loader.loadTestsFromGenerator() or
nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other
methods) here:
http://readthedocs.org/docs/nose/en/latest/api/loader.html

HTH, my $0.02 worth,

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


[Tutor] Testing dymamically created methods

2012-01-10 Thread Thomas Maier
Hi all,

I would like to use some existing tool like py.test or nose to
run my tests, but I failed to do so.
The problem is as follow. I have tests:

### test_methods.py ###
def test_one():
assert 1 == 1

def test_two():
assert 1 == 1

#

I have abstraction layer that keeps information
about this test, like method name.
It's simple JSON file.

Then I have the test runner:

### test_runner.py ###
def read_test_definition():
   """read the JSON file and returns dict with test details"""

def test_run():
   my_test_data = read_test_definition()
   import test_methods
   for testid in my_test_data:
   my_method = my_test_data[testid]
   # here the 'my_method' is equal 'test_one' or 'test_two', hope
it's clear..
   test_method = getattr(test_methods, my_method)
   test_method()

###

This code works without py.test or nosetests. For example if I use print
instead of 'assert'.
Both py.test and nosetests failed to execute this correctly.
Or maybe they do execute it correctly, I just don't understand it..:)
They both report only single test was executed.
I would like to see test report for each method executed in 'for' loop.
Is it possible?

PS. Sorry for my ignorance, I just started to learn Python last week.

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


[Tutor] Testing, please ignore

2011-08-13 Thread Alan Gauld

Testing from new Ubuntu install... problems with Thunderbird settings...

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

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


Re: [Tutor] Testing for empty list

2009-10-19 Thread Alan Gauld

"Katt"  wrote

Just a newbie question, but when would you test for an empty list?  


When you are processing a list such that you are deleting items as you go.
When the list is empty stop processing!

And Python helps you do that by treating an empty list as a False 
boolean value so you can do


while myList:
process items from myList

This will keep on processing myList until all the items have 
been deleted. Note, this could be more times than the number 
of items in the list...for example:


counter = 0
myList = [12,24]
nines = []
while myList:
counter += 1
print "iteration number", counter
index = 0
while index < len(myList):# copes with disappearing members
 if myList[index]  % 9 == 0: # is it divisible by 9?
nines.append(myList[index])
del(myList[index]) # remove from list
 else: myList[index] -= 1
 index += 1 
print nines



while len(mylist) > 0:
   continue program
else:
   print "mylist is empty


That is the same as

while mylist:
 continue program
else:
 print 'mylist is empty'

HTH,


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

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


Re: [Tutor] Testing for empty list

2009-10-19 Thread Rich Lovely
2009/10/19 Katt 
>
> Hello all,
>
> Just a newbie question, but when would you test for an empty list?  Is it 
> part of a code error detection or an error check to make sure that there is 
> user input?
>
> Couldn't you just use something like:
>
> while len(mylist) > 0:
>   continue program
> else:
>   print "mylist is empty
>
> or is my lack of python knowledge preventing me from seeing the meaning of 
> the question?
>
> Thanks in advance,
>
> Katt
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

There's various situations, consider this simple implementation of a
queue of tasks that need completing:

from abc import abstractmethod

class QueueableItem(object):
"""abstract base class to allow tasks to be queued"""
def queue(self):
"""Add the task to the queue"""
queue.append(self)
def completed(self):
"""Mark the task as completed, and remove it from the queue"""
queue.remove(self)
@abstractmethod
def run(self, *args):
"""complete the queued task, should call self.completed()
after running."""

class PrintTask(QueueableItem):
def __init__(self, data):
self.data = data
def run(self, *args):
print self.data
self.completed()

def processQueue():
while queue:
queue[0].run()
print "Queue Processed\n"

if __name__ == "__main__":
queue = []
PrintTask("Hello").queue()
PrintTask("World").queue()
processQueue()

In this situtation, the while loop could be substituted for a for
loop, but consider the following task:

class TaskThePrecedent(QueueableItem):
def run(self, *args):
if precedentCompleted():
#do stuff
self.completed()
 else:
 queue.insert(0, PrecedentTask())

Yes, the precedentTask code could be pasted into the else block, but
what if more than one class used that precedent, or the precedent had
precedents itself, which in turn were used by multiple classes?

OK, That was pretty contrieved, and I'm sure other tutors can come up
with better examples, but I think it gives an idea of one of the many
situtations in which you might need to test for a lists contents.

I also put far too much work into it.  "Simple", my foot.

--
Rich "Roadie Rich" Lovely

There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-19 Thread Katt

Wayne wrote:

Hi, I think I recall seeing this here, but I wanted to make sure I'm
correct.
Is the best way to test for an empty list just test for the truth value?
I.e.

mylist = [1,2,3]

while mylist:
   print mylist.pop()

Thanks,
Wayne



My take is simple:  Use the above form if you *know* that mylist is in
fact a list.  If you don't know its type for sure (the name is a clue,
but not conclusive ;-) ) then use a more specific test.

In your case, you know it's a list, or least something that supports
pop().  So your form should be great.

DaveA



Hello all,

Just a newbie question, but when would you test for an empty list?  Is it 
part of a code error detection or an error check to make sure that there is 
user input?


Couldn't you just use something like:

while len(mylist) > 0:
   continue program
else:
   print "mylist is empty

or is my lack of python knowledge preventing me from seeing the meaning of 
the question?


Thanks in advance,

Katt 


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


Re: [Tutor] Testing for empty list

2009-10-19 Thread Stefan Behnel
Hi,

please don't top-post.


Todd Matsumoto wrote:
> I don't understand how the while loop efficiently tests if the list is
> empty.

It doesn't. It only tests a condition. And the result of the condition is
determined by the list itself, which knows if it's empty or not.

Stefan

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


Re: [Tutor] Testing for empty list

2009-10-19 Thread Todd Matsumoto
I don't understand how the while loop efficiently tests if the list is empty. 
Why would going through the entire list be a good test to simply see find out 
if the list is empty or not.

Wouldn't you want to test the list itself, rather than the contents of it?

Cheers,

T

 Original-Nachricht 
> Datum: Mon, 19 Oct 2009 04:52:40 -0400
> Von: Dave Angel 
> An: Wayne 
> CC: "tutor@python.org" 
> Betreff: Re: [Tutor] Testing for empty list

> 
> 
> Wayne wrote:
> > Hi, I think I recall seeing this here, but I wanted to make sure I'm
> > correct.
> > Is the best way to test for an empty list just test for the truth value?
> > I.e.
> >
> > mylist = [1,2,3]
> >
> > while mylist:
> >print mylist.pop()
> >
> > Thanks,
> > Wayne
> >
> >   
> My take is simple:  Use the above form if you *know* that mylist is in 
> fact a list.  If you don't know its type for sure (the name is a clue, 
> but not conclusive ;-) ) then use a more specific test.
> 
> In your case, you know it's a list, or least something that supports 
> pop().  So your form should be great.
> 
> DaveA
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT!
Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-19 Thread Dave Angel



Wayne wrote:

Hi, I think I recall seeing this here, but I wanted to make sure I'm
correct.
Is the best way to test for an empty list just test for the truth value?
I.e.

mylist = [1,2,3]

while mylist:
   print mylist.pop()

Thanks,
Wayne

  
My take is simple:  Use the above form if you *know* that mylist is in 
fact a list.  If you don't know its type for sure (the name is a clue, 
but not conclusive ;-) ) then use a more specific test.


In your case, you know it's a list, or least something that supports 
pop().  So your form should be great.


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


Re: [Tutor] Testing for empty list

2009-10-19 Thread Luke Paireepinart
On Mon, Oct 19, 2009 at 2:26 AM, Todd Matsumoto  wrote:

> The while loop will print each index of the list.

No it's printing each element of the list, not the index.


> In a way it checks that if the list is empty by printing the items. As far
> as I know there isn't any 'True' or 'False' output from a list.
>

I'm not sure what you mean here because...

>
> If you want to do something if mylist is empty you can check it like this:
>
> if not mylist:
>

An "if" statement checks a boolean state so the list must be evaluating to a
boolean somehow.  (It does, it's False if it's empty and True otherwise).
-Luke
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-19 Thread Alan Gauld

"Todd Matsumoto"  wrote


The while loop will print each index of the list.


No, the while does nothing with list indexes, that is entirely
down to the programmer. The while loop simply repeats for
as long as its test expression evaluates to True.


As far as I know there isn't any 'True' or 'False' output from a list.


Lists are considered True if they are non empty, in the
same way as strings.

So the OPs test is perfectly valid

while myList:
do something to reduce mylist
(or use break but then you should use while True)

If you want to do something if mylist is empty you can check it like 
this:


if not mylist:
  ... do something ...


Which is the logical inverse of what the OP was testing
in his while loop.

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



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


Re: [Tutor] Testing for empty list

2009-10-19 Thread Andre Engels
On Mon, Oct 19, 2009 at 3:29 AM, Wayne  wrote:
> Hi, I think I recall seeing this here, but I wanted to make sure I'm
> correct.
> Is the best way to test for an empty list just test for the truth value?
> I.e.
> mylist = [1,2,3]
> while mylist:
>    print mylist.pop()

Whether it is the 'best' way depends on what you mean by 'best', but I
do think it's the most idiomatically pythonic one.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-19 Thread Todd Matsumoto
The while loop will print each index of the list. In a way it checks that if 
the list is empty by printing the items. As far as I know there isn't any 
'True' or 'False' output from a list.

If you want to do something if mylist is empty you can check it like this:

if not mylist:
   ... do something ...

T

 Original-Nachricht 
> Datum: Sun, 18 Oct 2009 20:29:53 -0500
> Von: Wayne 
> An: "tutor@python.org" 
> Betreff: [Tutor] Testing for empty list

> Hi, I think I recall seeing this here, but I wanted to make sure I'm
> correct.
> Is the best way to test for an empty list just test for the truth value?
> I.e.
> 
> mylist = [1,2,3]
> 
> while mylist:
>print mylist.pop()
> 
> Thanks,
> Wayne
> 
> -- 
> To be considered stupid and to be told so is more painful than being
> called
> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every
> weakness,
> every vice, has found its defenders, its rhetoric, its ennoblement and
> exaltation, but stupidity hasn’t. - Primo Levi

-- 
Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 -
sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-18 Thread शंतनू


On 19-Oct-09, at 7:11 AM, vince spicer wrote:




On Sun, Oct 18, 2009 at 7:29 PM, Wayne  wrote:
Hi, I think I recall seeing this here, but I wanted to make sure I'm  
correct.


Is the best way to test for an empty list just test for the truth  
value? I.e.


mylist = [1,2,3]

while mylist:
   print mylist.pop()

Thanks,
Wayne


I believe it is better to check the list length, I think some  
changes are coming on evaling list



mylist = [1,2,3]

while len(mylist) > 0:
   print mylist.pop()


or

while mylist != []:
print mylist.pop()


or for reverse iteration without popping the values in the list.


for x in reversed(mylist):
print x


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


Re: [Tutor] Testing for empty list

2009-10-18 Thread vince spicer
On Sun, Oct 18, 2009 at 7:29 PM, Wayne  wrote:

> Hi, I think I recall seeing this here, but I wanted to make sure I'm
> correct.
> Is the best way to test for an empty list just test for the truth value?
> I.e.
>
> mylist = [1,2,3]
>
> while mylist:
>print mylist.pop()
>
> Thanks,
> Wayne
>
> --
> To be considered stupid and to be told so is more painful than being called
> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
> every vice, has found its defenders, its rhetoric, its ennoblement and
> exaltation, but stupidity hasn’t. - Primo Levi
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
I believe it is better to check the list length, I think some changes are
coming on evaling list


mylist = [1,2,3]

while len(mylist) > 0:
   print mylist.pop()






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


[Tutor] Testing for empty list

2009-10-18 Thread Wayne
Hi, I think I recall seeing this here, but I wanted to make sure I'm
correct.
Is the best way to test for an empty list just test for the truth value?
I.e.

mylist = [1,2,3]

while mylist:
   print mylist.pop()

Thanks,
Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing framework

2009-04-29 Thread Eike Welk
Hello Spir!

On Thursday 23 April 2009, spir wrote:
> I would like to refactor tests of an application in a consistent
> form. I have a ton of tests for each module, but they are all ad
> hoc things. doctest looks great. The issue is it seems based on
> command line-like testing:

I have researched a workable solution based on the "py.test" 
framework. 
http://codespeak.net/py/dist/test/test.html

(The nose framework works in a very similar way 
http://code.google.com/p/python-nose/)

I think doctests are only for small examples that illustrate the 
docstrings. The "unittest" library has problems with library modules 
that use each other; one has to tweak "sys.path" prior to testing. 
(Doctests probably have this problem with "sys.path" too.)


To use the "py.test" script you put all your test code into separate 
files. The filenames must start with "test_". These files contain 
test functions; their names must must also start with "test_". 
The "py.test" script searches for test files and uses a lot of magic 
to do the right thing, especially it fiddles with "sys.path"

Here is your example done with "py.test":

 start file "test_example.py" 

def test_factorial():
import example   #The import my also fail
fact5 = example.factorial(5)
assert fact5 == 120

 end file 

"py.test" can also execute tests written with the "unittest" library 
(important for me). The test files are then structured like this:

 start file "test_unittest_example.py" 

import unittest
pytest_plugins = "pytest_unittest"

class TestExample(unittest.TestCase):
#your existing unittest implementation goes here
pass

 end file -


"py.test" writes nicely formated stack traces, and code snippets into 
the terminal window. On Linux at least, it even uses a bit of color 
and bold text. If you are spoiled by graphical debuggers and 
clickable error messages (like me), you can also use the test files 
for debugging with your IDE. You put something like this at the end 
of the test file:

if __name__ == '__main__':
test_factorial()   #This test triggers the error

So, the simplicity of its main concepts makes "py.test" quite 
convenient.


Kind regards,
Eike. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing Frameworks and Organizations

2009-04-23 Thread Eike Welk
Hello Spir; hello all!


I have a similar question:
For projects with multiple packages (directories) and modules (files); 
where do you put your testcode, what framework do you use, and what 
design patterns do you employ?


I currently work on a project with one package and several modules. I 
use the unittest module and my testcode is currently a mess. I use 
the following pattern:

-- start of file (module_n) -
import my_package.module_1 as module_1 
import my_package.module_2 as module_2

#module code goes here

if __name__ == '__main__':
import unittest
# Self-testing code goes here.
-- end of file -

Files structured like this can't be run as scripts, because the 
interpreter won't find the imported modules in the first two lines. 
However it works from my IDE (Eclipse) and this is the reason why I 
didn't bother to change the testcode's sorry state until now. 

I would really like to know how the Python experts organize their 
testcode, and what is considered the recommended way to do it. 


Kind regards,
Eike.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing framework

2009-04-23 Thread Alan Gauld


"spir"  wrote


My app is about parsing, which input and output usually both are big
and complicated *strings*. So that I find the command line model
really unappropriate for expressing test cases and their expected 
results.


Any hint/pointer/comment welcome,


What about using command line redirection so you can prepare
the input data in a text file and pipe that into the tests. Would that
work for you?

Alan G 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing framework

2009-04-23 Thread Kent Johnson
On Thu, Apr 23, 2009 at 8:55 AM, spir  wrote:
> Hello,
>
> I would like to refactor tests of an application in a consistent form. I have 
> a ton of tests for each module, but they are all ad hoc things.

> My app is about parsing, which input and output usually both are big and 
> complicated *strings*. So that I find the command line model really 
> unappropriate for expressing test cases and their expected results.

The unittest module is the other option in the standard library. nose
and py.test are popular add-on testing packages. More on unittest, and
links to the others, here:
http://personalpages.tds.net/~kent37/kk/00014.html

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing framework

2009-04-23 Thread Oxymoron
Hello,

On Thu, Apr 23, 2009 at 10:55 PM, spir  wrote:

>
> My app is about parsing, which input and output usually both are big and
> complicated *strings*. So that I find the command line model really
> unappropriate for expressing test cases and their expected results.
>

Interesting - haven't really used Python's test frameworks here - and
perhaps my suggestion may be too basic - and if so I apologise - not sure
what you mean by command line model in the context. Could you not have a
directory with input files and expected output files, then write a test
runner going through input -> apply_operation -> assert(output) cycles? The
test runner can be as simple or as complicated as you want of course, so you
can configure tests say by pieces of parsing functionality, but they need
not deal with the tests' input themselves, which will mostly be
preconfigured (or partially dynamic with plugged in values) etc. Heck, you
could have configuration files for the test runner!

Have I completely missed your question?

-- K

-- 
There is more to life than increasing its speed.
-- Mahatma Gandhi
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] testing framework

2009-04-23 Thread spir
Hello,

I would like to refactor tests of an application in a consistent form. I have a 
ton of tests for each module, but they are all ad hoc things.
doctest looks great. The issue is it seems based on command line-like testing:

"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> import example
>>> example.factorial(5)
120
"""

My app is about parsing, which input and output usually both are big and 
complicated *strings*. So that I find the command line model really 
unappropriate for expressing test cases and their expected results.

Any hint/pointer/comment welcome,

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Testing 321

2008-04-01 Thread Evans Anyokwu
Please ignore, switching email address.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing the status of NFS mounts

2007-01-04 Thread Kent Johnson
Andrew Robert wrote:
> Hi everyone,
> 
> We have several NFS mounts that are in use.
> 
> Occasionally, the NFS mounts seem to go out to lunch.
> 
> The mounts appear active but are no longer functional.
> 
> Is there a Python module specific to NFS that I might use to 
> periodically check its status?
> 
> I imagine I could make a script to attempt a write on the share and 
> clean up after itself but I am hoping for a more elegant solution.
> 
> Any insight anyone can provide on this would be greatly  appreciated.

If the share is mounted on the test machine, seems to me a simple 
os.path.isdir() might do the trick. Otherwise, a quick 
Google turns up
http://www.citi.umich.edu/projects/nfsv4/pynfs/

HTH
Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Testing the status of NFS mounts

2007-01-04 Thread Andrew Robert

Hi everyone,

We have several NFS mounts that are in use.

Occasionally, the NFS mounts seem to go out to lunch.

The mounts appear active but are no longer functional.

Is there a Python module specific to NFS that I might use to periodically
check its status?

I imagine I could make a script to attempt a write on the share and clean up
after itself but I am hoping for a more elegant solution.

Any insight anyone can provide on this would be greatly  appreciated.

--
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachussetts Financial Services
Phone: 617-954-5882
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing u=unicode(str, 'utf-8') and u = str.decode('utf-8')

2006-04-06 Thread Kent Johnson
Keo Sophon wrote:
> Hi,
> 
> Today i tested u=unicode(str,'utf-8') and u=str.decode('utf-8'). Then in both 
> case I used:
> 
> if isinstance(u,str):
>print "just string"
> else:
>   print "unicode"
> 
> the result of both case are "unicode". So it seems u=unicode(str,'utf-8') and 
> u=str.decode('utf-8') are the same. How about the processing inside? is it 
> same?

I don't know the details of how they are implemented but they do have 
the same result. As far as I know you can use whichever form you find 
more readable.

There are a few special-purpose encodings for which the result of 
decode() is a byte string rather than a unicode string; for these 
encodings, you have to use str.decode(). For example:

In [42]: 'abc'.decode('string_escape')
Out[42]: 'abc'

In [44]: unicode('abc', 'string_escape')

Traceback (most recent call last):
   File "", line 1, in ?
TypeError: decoder did not return an unicode object (type=str)

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] testing u=unicode(str, 'utf-8') and u = str.decode('utf-8')

2006-04-05 Thread Keo Sophon
Hi,

Today i tested u=unicode(str,'utf-8') and u=str.decode('utf-8'). Then in both 
case I used:

if isinstance(u,str):
   print "just string"
else:
  print "unicode"

the result of both case are "unicode". So it seems u=unicode(str,'utf-8') and 
u=str.decode('utf-8') are the same. How about the processing inside? is it 
same?

Phon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing: doctest and unittest

2005-11-11 Thread Kent Johnson
Kent Johnson wrote:
> Alex Hunsley wrote:
>>Where do you seasoned pythonites see unittest and doctest in relation to 
>>each other? Do you only use one or the other?
> 
> 
> I think it is mostly personal preference. Doctest is nice where you
> create examples for others, maybe not so nice where you are creating
> exhaustive unit tests trying to exercise every corner case. unittest
> is perhaps easier to aggregate tests from multiple modules. Doctests
> integrate with unittest in Python 2.4. Personally I use unittest but
> I come from a Java background and learned TDD with JUnit which is
> related to unittest.

I have recently begun a project where I am using extreme test-driven 
development with unittest - writing very small tests, then writing the code to 
make the test pass [1]. In this case much of the code is testing access to data 
that I read from a text file. I think these tests would make very poor doctests 
because
- they are just exercising the accessors (attributes, actually) of a data 
class; they don't contribute much to understanding the class under test
- they rely on test files for the data, they won't run in isolation [2]

Most of my unit tests are crushingly boring reading, so for me I think unittest 
is a better fit.

[1] I like this style in general. In this case the programming is fairly 
exploratory - I have to figure out what data I need from the file, then figure 
out how to get it - which is an excellent fit for this style of programming. I 
figure out one bit of data, write a test for it, write the code to access the 
data, repeat.

[2] I know, some unit testing purists say unit tests shouldn't rely on external 
resources such as files and databases. I disagree :-) as long as the tests are 
fast I don't care what resources they use.

Kent

-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-09 Thread Danny Yoo
> I haven't written any code yet, but I was thinking I would like to test
> for either a windows environment (Is an X-Server running) or is this a
> strictly console (no X-server) environment and then do the appropriate
> thing for each environment. I am not sure that is any clearer, but I
> hope it is.

Hi Ken,

That makes sense.

Can you check to see if the DISPLAY environmental variable is set?  That
appears to be a fairly standard kludgy way to determine if the user is in
a graphical vs. non-graphical environment.  emacs, for example, appears to
check for DISPLAY before switching a terminal or X-Windows based UI.

Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-09 Thread Ken Stevens
On Wed, Nov 09, 2005 at 10:00:49PM -, Alan Gauld wrote:
> >How does one test for a running gui in python?
> >
> 
> Can you be more specific? A GUI is a feature of a program.
> The GUI is part of the program - although a few programs 
> can run in either GUI or Text mode, but they are the exception.
> 
> Can you give an example of what you want to test for?
> 
> Alan G


I haven't written any code yet, but I was thinking I would like to
test for either a windows environment (Is an X-Server running) or is
this a strictly console (no X-server) environment and then do the
appropriate thing for each environment. I am not sure that is any
clearer, but I hope it is.

Ken

-- 
Money is its own reward.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-09 Thread Alan Gauld
From: Ken Stevens [mailto:[EMAIL PROTECTED]
> Yes. Under Linux no x-server running? I guess it really wouldn't be
> applicable under a windows enviroment, 

OK,  I see what you wanted now, ignore my previous message
.
Note that X windows is a protocol and not a GUI. 
There are several GUI environments that can run 
under X, not all of them requre an X server on the 
local machine.

Secondly note that not all GUIs on Unix run 
under X - the Mac Aqua interface is one example, 
NeXT/OpenStep another, Squeak another and the 
original Sun SunView and OpenLook(*) were all 
non X based GUIs that are still occasionally found 
today.

(*)Later versions of openLook were ported to X, 
the original used display postscript as did NeXTstep.


HTH, (in a nit picking kind of way! :-)

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-09 Thread Alan Gauld
> How does one test for a running gui in python?
> 

Can you be more specific? A GUI is a feature of a program.
The GUI is part of the program - although a few programs 
can run in either GUI or Text mode, but they are the exception.

Can you give an example of what you want to test for?

Alan G
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing: doctest and unittest

2005-11-08 Thread Kent Johnson
Alex Hunsley wrote:
> Regards testing, I've been playing with both the unittest 
> (http://pyunit.sourceforge.net/pyunit.html) and doctest 
> (http://docs.python.org/lib/module-doctest.html). I was wondering what 
> peoples thoughts were on the effectiveness and convenience of one versus 
> the other. It seems to me that doctest is good for quicky and 
> straightforwards input/output tests for small units, whereas unittest 
> would be good for dynamic or complicated testing.
> 
> Where do you seasoned pythonites see unittest and doctest in relation to 
> each other? Do you only use one or the other?

I think it is mostly personal preference. Doctest is nice where you create 
examples for others, maybe not so nice where you are creating exhaustive unit 
tests trying to exercise every corner case. unittest is perhaps easier to 
aggregate tests from multiple modules. Doctests integrate with unittest in 
Python 2.4. Personally I use unittest but I come from a Java background and 
learned TDD with JUnit which is related to unittest.

Another option is py.test which is part of the PyPy project, not part of the 
standard library. Some people think it is simpler and more Pythonic than 
unittest. This page has good articles about doctest, unittest and py.test:
http://agiletesting.blogspot.com/2005/11/articles-and-tutorials-page-updated.html

-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-08 Thread John Fouhy
From: Ken Stevens [mailto:[EMAIL PROTECTED]
> Yes. Under Linux no x-server running? I guess it really wouldn't be
> applicable under a windows enviroment, although I would like my code
> to be transportable. Just under a MS windows enviroment it would
> always be a "gui" environment.

What happens if you try to create a GUI and X is not running? Maybe
you could just try to create a Tkinter.Tk() --- if it throws a python
exception (probably TclError), you could just catch that.

--
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-08 Thread Liam Clarke-Hutchinson

Hmm, no x-server. If you're looking to detect running Python GUI packages,
you could check the namespaces for 'em, but beyond that, I'm stumped.


-Original Message-
From: Ken Stevens [mailto:[EMAIL PROTECTED] 
Sent: Wednesday, 9 November 2005 1:23 p.m.
To: Liam Clarke-Hutchinson
Subject: Re: [Tutor] Testing for gui


On Wed, Nov 09, 2005 at 01:16:03PM +1300, Liam Clarke-Hutchinson wrote:
> 
> Hi Ken,
> 
> How do you mean? I assume you're referring to a non-Windows 
> environment? In Linux, I'd imagine that using os.popen("ps") would do 
> it.
> 
> Cheers,
> 
> Liam
> 

Yes. Under Linux no x-server running? I guess it really wouldn't be
applicable under a windows enviroment, although I would like my code
to be transportable. Just under a MS windows enviroment it would
always be a "gui" environment.

Thanks, Ken

-- 
Go 'way!  You're bothering me!

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for gui

2005-11-08 Thread Liam Clarke-Hutchinson

Hi Ken, 

How do you mean? I assume you're referring to a non-Windows environment? In
Linux, I'd imagine that using os.popen("ps") would do it.

Cheers, 

Liam 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Ken Stevens
Sent: Wednesday, 9 November 2005 1:12 p.m.
To: tutor@python.org
Subject: [Tutor] Testing for gui



How does one test for a running gui in python?

Thanks, Ken


-- 
A journey of a thousand miles starts under one's feet.
-- Lao Tsu
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Testing for gui

2005-11-08 Thread Ken Stevens

How does one test for a running gui in python?

Thanks, Ken


-- 
A journey of a thousand miles starts under one's feet.
-- Lao Tsu
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing: doctest and unittest

2005-11-08 Thread Alex Hunsley
Colin J. Williams wrote:

> Alex Hunsley wrote:
>
>> Regards testing, I've been playing with both the unittest 
>> (http://pyunit.sourceforge.net/pyunit.html) and doctest 
>> (http://docs.python.org/lib/module-doctest.html). I was wondering 
>> what peoples thoughts were on the effectiveness and convenience of 
>> one versus the other. It seems to me that doctest is good for quicky 
>> and straightforwards input/output tests for small units, whereas 
>> unittest would be good for dynamic or complicated testing.
>>
>> Where do you seasoned pythonites see unittest and doctest in relation 
>> to each other? Do you only use one or the other?
>>
>> ta,
>> alex
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>  
>>
> I looked at doctest and feel that it clutters the module text and so 
> would prefer unittest but I haven't yet got to formalizing my tests in 
> that way.
>
> See some of the numarray source as an example of clutter.  Some argue 
> that having the examples in the source is beneficial.  I agree but 
> feel that the clutter outweighs the benefit.

I also feel that the clutter aspect of doctest can be a little bit of a 
put off. I like the idea of the having the target code nicely seperate 
from the tests, and really thorough doctests could swamp the target code 
a little too much!
Plus, of course, if you write unittests, there are more options 
apparently available,  like using the graphical test runner, etc. 
doctest is simpler (not always necessarily a bad thing).

ta
alex


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing: doctest and unittest

2005-11-08 Thread Colin J. Williams
Alex Hunsley wrote:

>Regards testing, I've been playing with both the unittest 
>(http://pyunit.sourceforge.net/pyunit.html) and doctest 
>(http://docs.python.org/lib/module-doctest.html). I was wondering what 
>peoples thoughts were on the effectiveness and convenience of one versus 
>the other. It seems to me that doctest is good for quicky and 
>straightforwards input/output tests for small units, whereas unittest 
>would be good for dynamic or complicated testing.
>
>Where do you seasoned pythonites see unittest and doctest in relation to 
>each other? Do you only use one or the other?
>
>ta,
>alex
>
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
I looked at doctest and feel that it clutters the module text and so 
would prefer unittest but I haven't yet got to formalizing my tests in 
that way.

See some of the numarray source as an example of clutter.  Some argue 
that having the examples in the source is beneficial.  I agree but feel 
that the clutter outweighs the benefit.

Colin W.

Colin W.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] testing: doctest and unittest

2005-11-08 Thread Alex Hunsley
Regards testing, I've been playing with both the unittest 
(http://pyunit.sourceforge.net/pyunit.html) and doctest 
(http://docs.python.org/lib/module-doctest.html). I was wondering what 
peoples thoughts were on the effectiveness and convenience of one versus 
the other. It seems to me that doctest is good for quicky and 
straightforwards input/output tests for small units, whereas unittest 
would be good for dynamic or complicated testing.

Where do you seasoned pythonites see unittest and doctest in relation to 
each other? Do you only use one or the other?

ta,
alex


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing for modules?

2005-10-25 Thread Frank Moore
Shitiz Bansal wrote:

>try:
>   import 
>except:
>   
>   import 
>
>
>--- Ed Hotchkiss <[EMAIL PROTECTED]> wrote:
>
>  
>
Explicit is always better than implicit...

try:
import 
except ImportError:# Only catch import errors
   
import 

Cheers,
F.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing for modules?

2005-10-25 Thread Shitiz Bansal
try:
   import 
except:
   
   import 


--- Ed Hotchkiss <[EMAIL PROTECTED]> wrote:

> i have a generic script that is using several
> modules on windows and linux
> boxes. i need to have the scripts test if a module
> is installed, and then if
> not - then to install the module. can anyone give me
> a headsup on how to
> test for a module, returning something to indicate
> whether or not it is
> installed, then after that executing file to install
> the module.? just
> somewhere to start would be helpful! thanks in
> advance.
> 
> --
> edward hotchkiss
> > -- 
> http://mail.python.org/mailman/listinfo/python-list


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing for modules?

2005-10-24 Thread Bill Burns
Ed Hotchkiss wrote:
> i have a generic script that is using several modules on windows and 
> linux boxes. i need to have the scripts test if a module is installed, 
> and then if not - then to install the module. can anyone give me a 
> headsup on how to test for a module, returning something to indicate 
> whether or not it is installed, then after that executing file to 
> install the module.? just somewhere to start would be helpful! thanks in 
> advance.

Hi Ed,

You can at do this to test if a module is installed:

try:
 import SomeModule
except ImportError:
 print 'SomeModule is not installed!'

I'm not sure about the part regarding the module installation. I guess 
you would replace the print statement above with some code to install 
the module.

HTH,

Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing for modules?

2005-10-24 Thread Kent Johnson
Ed Hotchkiss wrote:
> i have a generic script that is using several modules on windows and 
> linux boxes. i need to have the scripts test if a module is installed, 
> and then if not - then to install the module. can anyone give me a 
> headsup on how to test for a module, returning something to indicate 
> whether or not it is installed, then after that executing file to 
> install the module.? just somewhere to start would be helpful! thanks in 
> advance.

I don't know a generic way to install a module but the testing part is easy - 
just try to import it:
try:
  import mymodule
except ImportError:
  # install mymodule

In general you need to download and unzip a module, then run 'python setup.py 
install'.

Kent
-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] testing for modules?

2005-10-24 Thread Ed Hotchkiss
i have a generic script that is using several modules on windows and linux boxes. i need to have the scripts test if a module is installed, and then if not - then to install the module. can anyone give me a headsup on how to test for a module, returning something to indicate whether or not it is installed, then after that executing file to install the module.? just somewhere to start would be helpful! thanks in advance.
-- edward hotchkiss 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for commandline args

2005-05-17 Thread Cedric BRINER
>  Also, I hear that optparse is much better than getopt.
this is a true pleasure to work with optparse. It was included in python2.3 and 
was primarly called python-optik

Ced.
-- 

Cedric BRINER
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for commandline args

2005-05-13 Thread Danny Yoo
>
> If I have arguments, the "different stuff" happens beautifully, thank
> you very much.  If I don't have arguments I get this:
>
> if sys.argv[1]:
> IndexError: list index out of range]
>
> So I'm doing something wrong.  I looked at getopt, but that seemed to be
> doing what I was already doing, except in a way I could not follow :-(


Hi William,

One difference between Python and Perl is their treatment of out-of-bound
indices on lists.  Python does not "autovivify" a list, nor does it
automagically extend lists to make indices fit.  So if there are no
command line arguments, doing:

sys.argv[1]

will raise the IndexError exception that you're seeing.  It is a
significant difference between those two languages, so be careful.


There are several ways of doing what you're doing.  One solution is to
check for list length, as Max suggests.  Another is to take a "slice" of
the argument list:

if sys.argv[1:]: ...

The expression:

   sys.argv[1:]

produces a list of all but the first entry in sys.argv.  And the condition
check should work fine because empty lists are treated as False in Python.



Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for commandline args

2005-05-13 Thread Max Noel

On May 14, 2005, at 01:30, William O'Higgins wrote:

> if sys.argv[1]:
> do stuff
> else:
> do different stuff
>
> If I have arguments, the "different stuff" happens beautifully, thank
> you very much.  If I don't have arguments I get this:
>
> if sys.argv[1]:
> IndexError: list index out of range]
>
> So I'm doing something wrong.  I looked at getopt, but that seemed  
> to be
> doing what I was already doing, except in a way I could not follow :-(

 How about this?


if len(sys.argv) > 1:
 # do stuff
else:
 # do different stuff


 Also, I hear that optparse is much better than getopt.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge  
a perfect, immortal machine?"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Testing for commandline args

2005-05-13 Thread William O'Higgins
I am writing a tiny commandline utility (re-writing it from Perl) and I
want the behaviour to change based on the presence of arguments.  The
conditional in Perl looks like this:

if (defined $ARGV[0]) {
do stuff
} else {
do different stuff

In Python I've nearly been successful, but something's wonky.  Here's
the code:

if sys.argv[1]:
do stuff
else:
do different stuff

If I have arguments, the "different stuff" happens beautifully, thank
you very much.  If I don't have arguments I get this:

if sys.argv[1]:
IndexError: list index out of range]

So I'm doing something wrong.  I looked at getopt, but that seemed to be
doing what I was already doing, except in a way I could not follow :-(

Any tips would be appreciated, thanks.
-- 

yours,

William



signature.asc
Description: Digital signature
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Testing

2005-01-18 Thread james . homme




Hi,
I have not been getting mail, so I thought I'd see what's up.

Thanks.

Jim

James D Homme,
Information Design + Development
Highmark Inc.
[EMAIL PROTECTED]
412-544-0527
"A gentle answer turns away wrath, but a harsh word stirs up anger."


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor