Re: [Tutor] How to invoke different member-function according to different object?

2012-01-06 Thread Steven D'Aprano

daedae11 wrote:


2. I think it's a little tedious, but I don't know how to improve it.



Welcome to programming!

In the school books and example code, you see a nice, clean, fifteen line 
function and think that programming is easy.


Then you try to write the program, and you start of with 15 lines of code. 
Then you add error handling, and you end up with 50 lines. Then you add a user 
interface, and you have 130 lines. Then the user interface needs error 
handling, and you have 250 lines of code. Then you try to improve the 
presentation of the output, and you have 600 lines of code. Add error handling 
to that, and a test suite, and before you know it, your 15 line function is 
buried in the middle of a 3,000 line application.


Real programs always end up much bigger and more complicated and tedious than 
the way you think they should be.




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


Re: [Tutor] Subclassing Exceptions

2012-01-06 Thread Steven D'Aprano

Devin Jeanpierre wrote:

Inheriting from SyntaxError doesn't work!  When I create a new exception, I
generally subclass from the built-in exception it most resembles, in case
there was some reason to also catch it via an ancestor.  But I'm not sure if
that is really all that useful an idea in practice.  How do you folk do it?


If somebody wanted to catch a ValueError, would they also mean to
catch my error? (The same with SyntaxError and so on). Probably not.


If your error represents a value error, then yes they would.

But in that case, why should I subclass ValueError instead of just using 
ValueError itself? Writing my own exceptions is only useful if I intend to 
give the caller the *choice* of either treating my exception the same or 
different from ValueError: that is, if my error is a more specific kind of 
ValueError. If it is not a specific kind of value error, then just use the 
generic built-in ValueError exception instead.



try:
x = some_function()
except MyValueError:
# treat my errors specially
except ValueError:
# any other kind of ValueError caught here

vs.

try:
x = some_function()
except ValueError:
# any kind of ValueError caught here, including MyValueError


The same goes for all exception types, although in practice I find that I 
generally only subclass ValueError.




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


Re: [Tutor] Subclassing Exceptions

2012-01-06 Thread Steven D'Aprano

Chris Fuller wrote:


class Foo(SyntaxError):

...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 

raise Foo(1,2,3)

Traceback (most recent call last):
  File "", line 1, in 
__main__.Foo: None


Inheriting from SyntaxError doesn't work!  When I create a new exception, I 
generally subclass from the built-in exception it most resembles, in case 
there was some reason to also catch it via an ancestor.  But I'm not sure if 
that is really all that useful an idea in practice.  How do you folk do it?


What do you mean, "doesn't work"? It looks like it works to me. You get a Foo 
exception, exactly as expected. The error message isn't what you expect, 
because you're making unwarranted assumptions about SyntaxError and how it works.


In general, when you override a method, you take full responsibility to 
perform everything that the superclass method was supposed to do. In this 
case, you fail to assign to msg as well as args. It is safer to overload a 
message rather than override it:


>>> class Spam(SyntaxError):
... def __init__(self, *args):
... if args:
... args  = ("I pity the fool who made a mistake",) + 
args[1:]
... super(Spam, self).__init__(*args)
...
>>>
>>> raise Spam('you made a mistake', 1, 2)
Traceback (most recent call last):
  File "", line 1, in 
__main__.Spam: I pity the fool who made a mistake



Unfortunately, there's no real consistency in what arguments exceptions are 
expected to take. The best thing is to read the docs, if they have any, or use 
introspection and trial and error to work out what they do.


>>> try:
... raise SyntaxError("you made a mistake")
... except SyntaxError, err:
... pass
...
>>> err.msg
'you made a mistake'


See dir(err) for more; you can use help(SyntaxError) but unfortunately it 
isn't very useful.



You probably shouldn't inherit from SyntaxError, since it represents syntax 
errors in the Python code being interpreted or compiled. Any syntax error in 
your own data structures should be independent of SyntaxError.





--
Steven



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


Re: [Tutor] Subclassing Exceptions

2012-01-06 Thread Devin Jeanpierre
> Inheriting from SyntaxError doesn't work!  When I create a new exception, I
> generally subclass from the built-in exception it most resembles, in case
> there was some reason to also catch it via an ancestor.  But I'm not sure if
> that is really all that useful an idea in practice.  How do you folk do it?

If somebody wanted to catch a ValueError, would they also mean to
catch my error? (The same with SyntaxError and so on). Probably not.
If they would, then I raise the relevant exception. It is very
possible to accidentally catch the wrong thing if you put too much in
a try block, and I don't like making that any easier.

-- Devin

On Fri, Jan 6, 2012 at 10:24 PM, Chris Fuller
 wrote:
> I had an interesting experience today.
>
> Python 2.7.1 (r271:86832, Nov 28 2010, 19:31:37)
> [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 class Foo(Exception):
> ...  def __init__(self, a,b,c):
> ...   self.args = (a,b,c)
> ...
 raise Foo(1,2,3)
> Traceback (most recent call last):
>  File "", line 1, in 
> __main__.Foo: (1, 2, 3)
 class Foo(SyntaxError):
> ...  def __init__(self, a,b,c):
> ...   self.args = (a,b,c)
> ...
 raise Foo(1,2,3)
> Traceback (most recent call last):
>  File "", line 1, in 
> __main__.Foo: None
>
>
> Inheriting from SyntaxError doesn't work!  When I create a new exception, I
> generally subclass from the built-in exception it most resembles, in case
> there was some reason to also catch it via an ancestor.  But I'm not sure if
> that is really all that useful an idea in practice.  How do you folk do it?
>
> By the way, inheriting from StandardError, the direct ancestor of
> SyntaxError, works as expected, and its parent is Exception.
>
> Cheers
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to invoke different member-function according to different object?

2012-01-06 Thread daedae11
I was asked to write a program to move files between ZIP(.zip) and 
TAR/GZIP(.tgz/.tar.gz) or TAR/BZIP2(.tbz/.tar.bz2) archive. 

my code is:


import zipfile;
import tarfile;
import os;
from os import path ;

def showAllFiles(fileObj):
if fileObj.filename.endswith("zip"):
if isinstance(fileObj, zipfile.ZipFile):
print "j"*20;
for name in fileObj.namelist():
print name;
else:
for name in fileObj.getnames():
print name; 

def moveFile(srcObj, dstObj):
fileName = raw_input("input the name of the file to move: ");
srcObj.extract(fileName);
if isinstance(dstObj, zipfile.ZipFile):
dstObj.write(fileName);
else:
dstObj.addfile(tarfile.TarInfo(fileName));
os.remove(fileName);

def main():
intro = """
enter a choice
(M)ove file from source file to destinatiom file
(S)how all the files in source file
(Q)uit
your choice is: """
srcFile = raw_input("input the source file name: ");
dstFile = raw_input("input the destination file name: ");
while True:
with ( zipfile.ZipFile(srcFile, "r") if srcFile.endswith("zip") else 
tarfile.open(srcFile, "r"+":"+path.splitext(srcFile)[1][1:]) ) as srcObj, \
( zipfile.ZipFile(dstFile, "r") if
   dstFile.endswith("zip") else
tarfile.open(dstFile, "w"+":"+path.splitext(dstFile)[1][1:]) ) as 
dstObj:
choice = raw_input(intro)[0].lower();
if choice == "s":
showAllFiles(srcObj);
elif choice == "m":
moveFile(srcObj, dstObj);
elif choice == "q":
break;
else:
print "invalid command!"

if __name__ == '__main__':
main();

But there are some problems.
1. It could extract file successfully, but can't add files to .tar.gz file.
2. I think it's a little tedious, but I don't know how to improve it.

Please  give me some help , thank you!




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


[Tutor] Subclassing Exceptions

2012-01-06 Thread Chris Fuller
I had an interesting experience today.

Python 2.7.1 (r271:86832, Nov 28 2010, 19:31:37) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(Exception):
...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 
>>> raise Foo(1,2,3)
Traceback (most recent call last):
  File "", line 1, in 
__main__.Foo: (1, 2, 3)
>>> class Foo(SyntaxError):
...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 
>>> raise Foo(1,2,3)
Traceback (most recent call last):
  File "", line 1, in 
__main__.Foo: None


Inheriting from SyntaxError doesn't work!  When I create a new exception, I 
generally subclass from the built-in exception it most resembles, in case 
there was some reason to also catch it via an ancestor.  But I'm not sure if 
that is really all that useful an idea in practice.  How do you folk do it?

By the way, inheriting from StandardError, the direct ancestor of  
SyntaxError, works as expected, and its parent is Exception.

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


Re: [Tutor] Making a Computer Guess My Number

2012-01-06 Thread Dave Angel

On 01/06/2012 03:05 PM, Garland W. Binns wrote:

Hello, I have been experimenting with trying to rewrite the following
script so that a computer tries to guess a number I'm thinking of:
https://gist.github.com/1572067

I was thinking that basically I need to create a while loop, and somehow
redefine the randrange depending on whether or not I provide raw input
saying that the guess is higher or lower.

  Can anyone offer any suggestions?

-

Sure.  Start from scratch.

Seriously, the program you're desiring has little to do with the one you 
already wrote, other than probably using print and raw_input.  The 
optimal answer doesn't even need any random calls in it.


Are you familiar with the concept of binary search?  That's what you 
should implement.


Take a crack at it, and see what you come up with.

Hint:  think of a way to express the thinking part (the alogorithm) as a 
function, and write that first.  Then you just write something that 
controls its calls to the function based on user input.


--

DaveA

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


[Tutor] Making a Computer Guess My Number

2012-01-06 Thread Garland W. Binns
Hello, I have been experimenting with trying to rewrite the following
script so that a computer tries to guess a number I'm thinking of:
https://gist.github.com/1572067

I was thinking that basically I need to create a while loop, and somehow
redefine the randrange depending on whether or not I provide raw input
saying that the guess is higher or lower.

 Can anyone offer any suggestions?

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


Re: [Tutor] Using Python for a client interactive map application

2012-01-06 Thread Lie Ryan

On 01/06/2012 04:16 AM, Alan Gauld wrote:

That's a non trivial application. It sounds a lot like Google maps?


If by map you meant real world maps, this task becomes pretty much 
trivial. It is fairly easy to embed Google Map in your own web app, and 
their API provides a lot for almost anything you would need to do.


Although Google Maps are often used for boring everyday tasks like 
ordering taxi, reporting potholes, finding public toilets, etc, etc 
http://mashable.com/2009/01/08/google-maps-mashups-tools/


These are also some examples of the quirkiest things you could do with 
Google Maps:


- http://geoquake.jp/en/webgame/DrivingSimulatorPerspective/
- http://www.class3outbreak.com/
- 
http://www.thekremercollection.com/art/artists/Abraham-Bloemaert/A-cottage-with-peasants-milking-goats/


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