New restrain builtin function?

Pierre Rouleau prouleau at impathnetworks.com
Sun Mar 21 16:49:49 CET 2004


Robert Brewer wrote:


> I think if I were to write my own version today in pure Python,
> it'd be invoked as: limit(object, lower, upper), where <object> could be
> an iterable. I see that as a much more common use case; that is, mapping
> the same pair of boundaries to multiple items.
> 
> 

Interesting.  I had a simple one written in pure Python that was just 
checking the type of object to determine if it was a sequence
Agreed.  I had writte a pure Python one where I was looking for the 
object type with type(object).

def restrain(theObject, lowerBound, upperBound):
     if type(theObject) in [types.ListType, types.TupleType]:
         return map(lambda val,theMin,theMax: 
min(max(val,theMin),theMax) , theObject, lowerBound, upperBound)
     else:
         return  min(max(theObject, lowerBound), upperBound)

However,

1) I don't like using type(theObject) to check if it is a sequence 
because that does not allow iterable objects.
2) It does not allow the use case you just mentionned where the same 
boundary is applied to every member set.


So I wonder:

1) what's the easiest way to find if an object is iterable?  There is no 
'isiterable()' built in.  Would it be to try iterate over it and cath 
the potential exception or is there a better way?


Pierre Rouleau




More information about the Python-list mailing list