isinstance() considered harmful
aleax at aleax.it
Thu Jan 24 10:42:33 CET 2002
"Jason Orendorff" <jason at jorendorff.com> wrote in message
news:mailman.1011836557.4656.python-list at python.org...
> I wish I could say "if supports(object, wfile.write): ..."
> instead of "if hasattr(object, 'write'): ..."
> or the equivalent try/except/else incantation.
Much better still would be having PEP 246, and code:
writemethod = adapt(object, wfile_protocol).write
You'd get a TypeError here if object was not adaptable to
the wfile_protocol. Or, you could pass a third argument
to adapt and have it returned (rather than an exception
raised) in case adaptation is impossible, thus enabling
other useful idioms. *sigh* how I dream of PEP 246...
> (In this pipe dream, wfile is a "builtin interface" that has
> descriptors for write, writelines, flush, close, seek/tell,
> softspace, and so on.)
In my vision, the protocols would be a bit more granular
than that. For example, ability to tell and seek would
not be in the same protocol as those connected to writing
nor of those connected to reading. If protocols are often
to be joined, some future incarnation of adapt could grow
to help that, while splitting a protocol into sensible
pieces is harder, and fat interfaces have some issues.
In my dreams, wfile_protocol might be something like (it
might well be built-in, but equivalent to Python source):
# one of these must be overridden (mutual dependency):
def write(self, data):
def writelines(self, lines):
for data in lines:
__mutual_dependencies__ = ( (write, writelines), )
# methods that may but need not be overridden:
def flush(self): pass
def close(self): pass
More information about the Python-list