People seem to be pushing for a consistent method for checking the "x-ness" of objects (that is, interfaces that the object implements).<br><br>So I present an idea for a simple and straightforward type that provides a way to construct descriptions of object structures, and I'd like some help expanding it into a useful extension to Python's standard set of utilities.
<br><br>Its a basic constructor that produces callable interface-checking predicates (which can be use in things such as list comprehensions, filter, if statements, or even a new syntax for function signatures that allows for automatic interface-checking). These predicates check that an object matches the behavior described by the constructor . Since I can't think of a name for this constructor, and because I've never liked the term "interface", I'll just call it "can".
<br><br>Can takes an arbitrary number of keyword arguments and produces a callable object. The keys represent object attributes, while the values are behavior-checking predicates like the ones produced by can. Since the can constructor produces an object that can in turn be used in other can constructors, using previously defined interfaces in new constructions is fairly straight-forward
<br><br> callable = can(__call__ = object)#Returns an object that describes objects with a __call__ attribute<br> readable = can(read = callable) # ...with a callable read attribute
<br> writable = can(write = callable) # ...with a callable write attribute<br><br><br> #a join operator can be used to combine can objects...<br> #...for now I'll just use "and" and "or" to represent them.
<br> <br> isfilelike = readable and writable #returns an object that matches any type that is described<br> #by both readable and writable<br>
<br> IOable = readable or writable #any type that is readable or writable<br><br>objects that are constructed with can, when called, return True or False based on whether or not the passed object matches the behavior described.
<br><br> callable(hash) #returns True - as it would in the current version of Python.<br><br><br>Here's some more nifty examples:<br><br> iterable = can(__iter__=callable) or can(next=callable)<br> hashable = can(__hash__=callable)
<br><br> completefile = isfilelike and iterable and can(fileno=callable, close=callable)<br><br> def outlines(f, seq):<br> """Outputs a sequence of lines to a file-like object"""
<br> assert isfilelike(f), "%r is not a file-like object." % f<br> assert isiterable(seq), "%r must be iterable" % seq<br> f.write("\n".join(seq))<br><br> #a trivial example... you'd get similar error messages from Python builtins even without the assertions.
<br><br><br>As it stands, I don't think that this deserves to be in Python - but I think the basic premise could be used as a foundation for better things.<br> <br><br>-- <br>"What's money? A man is a success if he gets up in the morning and goes to bed at night and in between does what he wants to do." ~ Bob Dylan