Converting a string to the most probable type

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 7 20:34:16 EST 2008


On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote:

> Pierre Quentel <quentel.pierre at wanadoo.fr> writes:
>> I would like to know if there is a module that converts a string to a
>> value of the "most probable type"
> 
>     Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
>     >>> import this
>     The Zen of Python, by Tim Peters
>     ...
>     In the face of ambiguity, refuse the temptation to guess.

Good advice, but one which really only applies to libraries. At the 
application level, sometimes (but not always, or even most times!) 
guessing is the right thing to do.

E.g. spreadsheet applications don't insist on different syntax for 
strings, dates and numbers. You can use syntax to force one or the other, 
but by default the application will auto-detect what you want according 
to relatively simple, predictable and intuitive rules:

* if the string looks like a date, it's a date;
* if it looks like a number, it's a number;
* otherwise it's a string.

Given the user-base of the application, the consequences of a wrong 
guess, and the ease of fixing it, guessing is the right thing to do.

Auto-completion is another good example of guessing in the face of 
ambiguity. It's not guessing that is bad, but what you do with the guess.


-- 
Steven



More information about the Python-list mailing list