polymorphism in python

Robert Brewer fumanchu at amor.org
Wed Nov 26 21:20:50 EST 2003


Roy Smith wrote:
> But how often is it actually useful to do such a thing?  I can't 
> remember the last time I wanted to do something like that in 
> Python.  

And Jay O'Connor replied:
> Generally, if you are programming to the interface and not to 
> the class (which is what you are usually doing in OO programming,
> or should be if your language allows it) than testing for the 
> actual type of an object is usually a no-no

I find this comes up quite often in application interfaces; that is,
points at which your code manipulates someone else's code in someone
else's language. A prime example is forming valid SQL statements:

"SELECT * FROM xyz WHERE %(Name)s = %(Value)s" % ({'Name': fieldName,
'Value': fieldValue})

If fieldValue is an int, fine. If it's a string, you're probably going
to wrap '%(Value)s' in quote marks. So do you:

1) Explicitly check type.
2) Design your language so you can set attributes on basic type classes:
   def format_str_for_SQL(...):
      ...
   str.format_for_SQL = format_str_for_SQL
3) Use custom subclasses of basic types like int and str throughout the
app.
4) Same as #3, with metaclassing.
5) Hard-code every possible SQL statement.
6) Try: the SQL statement each way. Watch the permutation explosion with
multiple fields (now I'm just getting silly, but I've seen sillier
things in the field, sometimes written by me).

There are other ways. I'm probably going to go with option 1 in this
limited case, although in other cases option 3 has appeal.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list