polymorphism w/out signatures?

Duncan Booth me at privacy.net
Fri May 7 04:21:29 EDT 2004


"Larry Bates" <lbates at swamisoft.com> wrote in 
news:lMWdncBA4LRcAgfd4p2dnA at comcast.com:

> I use:
> 
> class foo:
>     _stringtype=type('')
>     _tupletype=type(())
>     _listtype=type([])

You could just use the builtin names already supplied for these: str, 
tuple, and list have the same values you just assigned to _stringtype, 
_tupletype, and _listtype. Also, you forgot about unicode.

> 
>     def __init__(self, variable):
>     if type(variable) == _stringtype:
>         self.variable=variable # check for string type
>     if type(variable) in (_listtype, tupletype):
>         self.variable=str(variable) # check for list/tuple
>     .

If anyone has been subclassing str, list or tuple this won't work. You may 
not subclass builtin types very often, but it doesn't really hurt to use 
isinstance instead. That's why it is better to write:

    if isinstance(variable, (str, unicode)):
       ...

or:

    if isinstance(variable, basestring):
       ...

as either of these will catch subclassing.




More information about the Python-list mailing list