[getopt-sig] Extracting data formating from option parser

s.keim s.keim
Fri, 22 Feb 2002 10:52:55 +0100


I have already expressed in the list the idea to let the parser delegate 
string conversion and type checking to an helper object..
I would try to explain it more precisely.

Even if ,for the moment, I'm only interested in the string->value 
conversion, in the next part of the document I will call Formatter the 
object which has the responsibility of data conversion and type checking.
This is highly inspired from the NSFormatter class of the 
NextStep/MacOSX framework.
http://developer.apple.com/techpubs/macosx/Cocoa/Reference/Foundation/Java/
Classes/NSFormatter.html

String evaluation is a very common programming task you need it for 
sample:
- for interactive user interface
- text files processing
- command line management ;)
...
So Python is quite well featured in this area, mainly because 'type' 
functions (int, float, complex ...) can be used with a string parameter 
and return ValueError for invalid format.

I don't think that there is a really great need for more so we could 
define, for the input part, a Formatter as:
- an object callable with a string argument
- that return the value of the result or raise a ValueError

Some minors improvements could be defined:
* FormatValueError: inherit from ValueError and contain the index 
position of the error in the string
And, not related to option parsing but interesting for use in 
interactive UI:
* verify(xx) check an unfinished string for correctness
* complete(xxx) auto-completion features

An then, instead of hard-coding the conversion stuff in the parser, we 
could reuse predefined Formatter classes:
parser.add_option("-d",  "--date",  type=DateFormater ("%y/%m/%d") )

One argument against this idea is that the current Optik solution allow 
to share informations from the parser to the data conversion mechanism. 
To know if this is a rebuttal problem, I'd like to have some example of 
situation where you need this kind of informations from the parser for 
data conversion.

I think that the major strength of my proposal is that it is generic, so 
I would finish with an example of how  this could be used in gui 
programming:
date_form = DateFormater ("%y/%m/%d")
date_text = Text(dialog, formater=date_form)

and then you could write code like:
date_text.value = time.time()
new_time = date_text.value
without boring anymore with string conversions.

What are you opinions about this?
Do you think it would be interesting if I work on a more constructed 
proposal,  or  is it a definitively bad idea?