Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for [] operator

Tags:

python

How do I check whether an object supports [] operation in Python? I think of something like the following:

if supports(obj, ?[]?):
    print("Supports")  
like image 626
Max Avatar asked Sep 29 '11 23:09

Max


People also ask

How do you check if a string is an operator Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

What does the operator mean in C++?

In programming, an operator is a symbol that operates on a value or a variable. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction. Operators in C++ can be classified into 6 types: Arithmetic Operators.


1 Answers

You don't "check for support". You just use it:

try:
    a = obj[whatever]
except TypeError:
    # whatever your fall-back plan is when obj doesn't support [] (__getitem__) 

Writing your own isinstance is always the wrong thing to do. A new type that doesn't inherit from the collections ABC classes can still have the right behavior. Duck Typing means you can never rely on isinstance.

Writing your own hasattr test merely duplicates Python's internal checking that raises the exception. Since Python must do the test, why duplicate that?

Finally, "I think that with exception handling this code will be less readable." Is false. The Pythonic principle, accepted by many experienced Python programmers is that it's Easier to Ask Forgiveness That to Ask For Permission.

The language is designed to do this with exceptions.

like image 145
S.Lott Avatar answered Oct 17 '22 17:10

S.Lott