interfaces?

Cliff Crawford cjc26 at nospam.cornell.edu
Thu Feb 1 21:18:07 EST 2001


* drewpc at colorado.edu <drewpc at colorado.edu> menulis:
| 
| Now, my question.  Is this something that people would be interested in
| seeing in Python?  If so, then I think I'll write up a PEP (Python
| Enhancement Proposal, http://python.sourceforge.net/peps/) about this.
| Comments?  Cheap shots?  One-liners?

Well, the usual way to indicate that a class implements, say, the file
interface, is to write a comment saying "this class implements the file
interface". ;)  You probably don't need anything more complicated than
that, since Python is dynamically typed, blah blah, etc. (where "blah
blah, etc." is meant to sum up the many discussions on c.l.py about this
very topic ;)  If you were really paranoid, you could always do
something like this:

def func(f):
    if not hasattr(f, "readlines"):
        raise NeedFileObjectError
    for line in f.readlines():
        # rest of function goes here

try:
    func(suspectedFileObject)
except NeedFileObjectError:
    print >>sys.stderr, "You must use a file object!"

Of course, most people would just leave out the hasattr() check, and let
func() raise an AttributeError if it's passed something which doesn't
act like a file object.

and-we-don't-need-to-declare-which-exceptions-our-functions-raise-
    either-<wink>-ly y'rs, Cliff


-- 
Cliff Crawford               http://www.people.cornell.edu/pages/cjc26/
                             print "Just another Python hacker"



More information about the Python-list mailing list