"has" Operator

Joonas Paalasmaa joonas at olen.to
Sat Jul 7 17:16:53 EDT 2001


Paul Sidorsky wrote:
> 
> I was thinking that Python might benefit from a "has" operator that
> would allow you to type something like this:
> 
> if myobject has someattribute:
>     foo()
> else:
>     bar()
> 
> This would be roughly equivalent to:
> 
> try:
>     uselessvar = myobject.someattribute
> execpt AttributeError:
>     bar()    # myobject does not have someattribute
> else:
>     foo()    # myobject has someattribute
> 
> ...but (IMO) the operator version would be much nicer and more
> readable.  (This idea came about when I actually tried to type in the
> former!  Python's syntax is so clean that it seemed to be a natural
> extension.)
> 
> The Inform interactive-fiction language provides "has" and "hasnt"
> operators that do something similar so this is not without precendent.
> But for Python, it admittedly may be nothing more than syntactic sugar.
> What does everyone else think?

Use builtin function hasattr.

>>> import sys
>>> hasattr(sys,"stin")
0
>>> hasattr(sys,"stdin")
1
>>>



More information about the Python-list mailing list