if <assignment>:

Donn Cave donn at u.washington.edu
Tue Nov 26 13:03:10 EST 2002


Quoth Carl Banks <imbosol at vt.edu>:
| Duncan Booth wrote:
|> If you have more than one or two patterns, then you should really be
|> thinking about a loop rather than a long list of if statements: 
|> 
|> PATTERNS = [
|>  (regex1, action1),
|>  (regex2, action2),
|>  # ...
|> ]
|> 
|> for regex, action in PATTERNS:
|>    match = regex.match(string)
|>    if match:
|>        action(match)
|>        break
|> 
|> I don't see any need for assignment in an 'if' here.
|
| Other people often clamor for assignment if here, because the way you
| did is an unnatural and circumlocative way to do something most
| people, myself included, want to do as a sequential piece of code.

I think I can see that.  Not that there isn't any place for table
driven procedures, but it isn't ideal for everything.  I wouldn't
go so far as to say it makes sense to therefore give assignments
a value - don't like that idea at all - but ironically it seems to
me that the main argument for it stems from a weakness in Python
that isn't shared by languages like C that actually have this feature.

If instead of Python we were looking at a language that were more
specifically aimed at text analysis and a little less scrupulously
explicit, I could imagine the results of a match turning up in magic
state variables, like

    if (line ~ /^\(.*\): \(.*\)$/) {
        tag = $1
        val = $2
    } ...

In C, everything is naturally explicit, but the function value per se
is often just a boolean status and the data is returned by other means.

    if (regexp(line, "/^\(.*\): \(.*\)$/", &rv)) {
        tag = rv.group[0];
        val = rv.group[1];
    }

Of course it's part of the attraction that Python relieves us of pointers
and magic state variables, but in this matter it's kind of unfortunate
that the function value is the function return, so to speak.  Status has
to be communicated through special data values like None, or like the
negative return of string.find().

That can't be helped, but where reaches a sufficient level of annoyance,
seems to me the general outlines of the OOP solution are fairly obvious -

     if rv.match(line, "/^\(.*\): \(.*\)$/"):
         tag = rv.group[1]
         val = rv.group[2]

In other words, an object that stores the result of a computation and
returns its status (and maybe stores that, too, for its __nonzero__.)

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list