Re: [Tutor] please return flys in ointment

2013-07-08 Thread Steven D'Aprano
Comments on your code inline below.

On Sat, Jul 06, 2013 at 02:38:27PM -0700, Jim Mooney wrote:


> import sys
> 
> # Data
> ones = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five',
> '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
> 
> tens = {'2': 'twenty', '3': 'thirty', '4': 'forty', '5': 'fifty', '6':
> 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety'}
> 
> doubles = {'0': 'ten', '1': 'eleven', '2': 'twelve', '3': 'thirteen', '4':
> 'fourteen', '5': 'fifteen', '6': 'sixteen', '7': 'seventeen', '8': 
> 'eighteen', '9': 'nineteen'}
> 
> powers_of_1000 = (' thousand', ' million', ' billion', ' trillion',
> ' quadrillion', ' quintillion', ' sextillion', ' septillion', ' octillion',
> ' nonillion', ' decillion')
> 
> '''add these later, and also option for dollars-and-cents ending.
> 'vigintillion', 'novemdecillion', 'octodecillion', 'septendecillion',
> 'sexdecillion', 'quindecillion', 'quattuordecillion', 'tredecillion',
> 'duodecillion', 'undecillion',
> 'decillion', 'nonillion'
> '''
> 
> # Functions
> def make_triplets_from_input():
> '''Enter a positive integer. A list of triplets in the same order will
> be returned.
> Raise ValueError to loop on non-integer input, or return 'zero'
> trigger-value of
> 'xxx' if all zeroes are entered. If input is okay, strip leading
> zeroes, then
> zero-pad leftmost triplet to three characters, so all slices are
> triplets. Adjust
> input for different Python versions.'''
> while True:
> try:
> if sys.version[0:3] == '2.7':
> numbers_str = original = raw_input('Enter a positive
> integer, space \
> separated if desired.')
> elif sys.version[0:3] == '3.3':
> numbers_str = original = input('Enter a positive integer,
> space \
> separated if desired.')

A better way to handle this is to perform a check once, outside the 
function at the top of the file:

try:
raw_input
except NameError:
# Probably Python 3.
raw_input = input

and then just use raw_input inside the function. Or the other way 
around, if you prefer:

try:
raw_input
except NameError:
pass
else:
input = raw_input

Then, inside the function, just unconditionally call:

result = input("Prompt, or 'quit' to exit: ")
result = result.lower().strip()
if result == 'quit':
break



> else:
> print('Python versions 2.7 and 3.3 only supported')
> sys.exit()
> 
> numbers_str = ''.join(numbers_str.split())
> if numbers_str == '' or numbers_str == ' ': raise ValueError

Since you're splitting on whitespace, and joining with the empty string, 
you cannot get numbers_str == ' '.

Besides, no need to explicitly check for '' here, since the very next 
line will do so for you:

> numbers_int = int(numbers_str)
> if numbers_int == 0:
> print('Zero')
> sys.exit()

One should not treat "0" to mean "I want to quit".

> numbers_str = str(numbers_int)
> if len(numbers_str) > 36: raise ArithmeticError

ArithmeticError??? You're not doing arithmetic, how can this be an 
arithmetic error?

You should be able to handle implausibly/arbitrarily long numbers, just 
by chaining names (e.g. "billion billion billion billion..."). If you're 
going to force some arbitrary limit on the number, and then use an 
exception for flow-control (as you do here, catching ArithmeticError 
further on), please use a custom exception so as to not confuse the 
person reading your code. 


> break
> except KeyboardInterrupt:
> print('Program cancelled by user')
> sys.exit()

/me lip curls

I'm not sure I like that... 


> except ValueError as err:
> print(original, "is not an integer.")
> continue
> except ArithmeticError as err:
> print(original, "is too big.\n999...decillion is max: 10**37-1 or 
> 36 chars \
> or 12 groups of 3 chars")
> 
> leftpad = len(numbers_str) % 3 # zero-pad left, so we get all 3-character 
> triplets
> if leftpad == 0: leftpad = ''
> elif leftpad == 2: leftpad = '0'
> else: leftpad = '00'
> numbers_str = leftpad + numbers_str

leftpad = len(numbers_str) % 3
if leftpad != 0:
leftpad = 3-leftpad
numbers_str = '0'*leftpad + numbers_str



> triplets = [numbers_str[x:x+3] for x in range(0,len(numbers_str),3)]
> return (triplets, len(triplets))

See also the recipe for "grouper" in the documentation for itertools.



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


Re: [Tutor] please return flys in ointment

2013-07-08 Thread Jim Mooney
On 8 July 2013 00:12, Steven D'Apranocatching ArithmeticError

> further on), please use a custom exception
>

Well, an Arithmetic Error was better than bubbling up to a totally general
one. I'm not sure how do custom error code. Short example, please ;')

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


Re: [Tutor] please return flys in ointment

2013-07-08 Thread Dave Angel

On 07/08/2013 01:57 PM, Jim Mooney wrote:

On 8 July 2013 00:12, Steven D'Apranocatching ArithmeticError


further on), please use a custom exception



Well, an Arithmetic Error was better than bubbling up to a totally general
one. I'm not sure how do custom error code. Short example, please ;')

Jim



I think a ValueError might be best.  See the description:

http://docs.python.org/2/library/exceptions.html#exceptions.ValueError

exception ValueError
Raised when a built-in operation or function receives an argument that 
has the right type but an inappropriate value, and the situation is not 
described by a more precise exception such as IndexError.


To make a custom error, first pick another error that's a superset of 
what you're doing.  Then simply derive your error class from it.  As a 
minimum:


class TooHugeError (ValueError):
pass





--
DaveA

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


Re: [Tutor] please return flys in ointment

2013-07-08 Thread Jim Mooney
> To make a custom error, first pick another error that's a superset of what
> you're doing.  Then simply derive your error class from it.  As a minimum:
>
> class TooHugeError (ValueError):
> pass
>
> Actually, I didn't get to classes yet since I wanted to nail procedural -
I'm in no rush - but that looks simple enough.

Damn, computer is overheating again. I'll be glad when the AZ heatwave is
over so I can get back to more hours on the computer, but Reality
intervenes ;')

Jim

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



-- 
Jim

Most American jurors are not told, by power-mad judges, that they can
disregard the law, the evidence, and the instructions of the judge, if they
feel a law is unfair, and render a verdict of "innocent". They are kept in
the dark about this right, called Jury Nullification.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] AMQP listening and user-facing daemon

2013-07-08 Thread Alan Gauld

On 07/07/13 22:57, Justin Chiu wrote:


What is the best approach to writing a concurrent daemon that can
execute callbacks for different types of events (AMQP messages, parsed
output of a subprocess, HTTP requests)?


Given nobody replied to your previous request I suggest you try another 
forum.


The tutor list is for people learning Python and its standard library,
more general questions are best addressed to the general python
list or newsgroup. I see you have cross posted there too so hopefully 
somebody will pick up on it soon.


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

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


Re: [Tutor] custom error classes: how many of them does one need?

2013-07-08 Thread Dave Angel

On 07/08/2013 04:51 PM, Albert-Jan Roskam wrote:


   

haha, I hadn't even noticed the 'speling eror'. I was just thinking 'what the 
heck is a desert spoon'? ;-)


"A dessert spoon is a spoon designed specifically for eating dessert and 
sometimes used for soup or cereals."


On the other hand, a desert spoon might be one that's extremely light, 
so that it may be taken along by desert rats out foraging.


--
DaveA

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


Re: [Tutor] custom error classes: how many of them does one need?

2013-07-08 Thread Alan Gauld

On 08/07/13 21:51, Albert-Jan Roskam wrote:


I was just thinking 'what the heck is a desert spoon'? ;-)


It's the one half-way between a teaspoon and a tablespoon :-)

--
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] custom error classes: how many of them does one need?

2013-07-08 Thread Marc Tompkins
On Mon, Jul 8, 2013 at 1:51 PM, Albert-Jan Roskam  wrote:

> haha, I hadn't even noticed the 'speling eror'. I was just thinking 'what
> the heck is a desert spoon'? ;-)
>

Many years ago, I saw this painted on the side of a pie shop:
"My favorite people are the people of the dessert", said Lawrence as he
picked up his fork.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please return flys in ointment

2013-07-08 Thread Steven D'Aprano

On 09/07/13 05:47, Dave Angel wrote:

On 07/08/2013 01:57 PM, Jim Mooney wrote:

On 8 July 2013 00:12, Steven D'Apranocatching ArithmeticError


further on), please use a custom exception



Well, an Arithmetic Error was better than bubbling up to a totally general
one. I'm not sure how do custom error code. Short example, please ;')

Jim



I think a ValueError might be best.

[...]

class TooHugeError (ValueError):
pass


I would normally agree, but in Jim's code the exception is purely being used 
for internal flow control, it is not being exposed to the caller. So I wouldn't 
inherit from ValueError, I'd keep this a completely independent exception. I 
wouldn't even call it an Error, since it's actually a limitation of Jim's code, 
not an actual error.

Also, since Jim's code already catches ValueError, he would need ensure that he 
catches this *first*, otherwise it will be caught by the ValueError handler:

try:
raise TooHugeError
except TooHugeError:  # this must come first
...
except ValueError:  # otherwise this will catch it
...


Whereas if you keep the custom exception independent, the order of except 
clauses doesn't matter.


class TooHuge(Exception):
pass


try:
raise TooHuge
except ValueError:
print("bad value")
except TooHuge:
print("caught it")




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


Re: [Tutor] please return flys in ointment

2013-07-08 Thread Steven D'Aprano

On 09/07/13 05:59, Jim Mooney wrote:

To make a custom error, first pick another error that's a superset of what
you're doing.  Then simply derive your error class from it.  As a minimum:

class TooHugeError (ValueError):
 pass

Actually, I didn't get to classes yet since I wanted to nail procedural -

I'm in no rush - but that looks simple enough.

Damn, computer is overheating again. I'll be glad when the AZ heatwave is
over so I can get back to more hours on the computer, but Reality
intervenes ;')


That's what I keep telling my AGW-Denialist friend, but he prefers living in a 
fantasy world where human beings can inject four Hiroshima A-bombs worth of 
heat into the oceans and atmosphere every second without consequence. (The 
actual excess heat accumulated over the last decade is 8000 million million 
megajoules per year.) Global temperatures were increasing even over the last 
few years while the solar cycle was cooling, now that the solar cycle is 
returning to its heating phase, so get used to it, you're experiencing a small 
glimpse of the future.


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