How do I check whether an object supports [] operation in Python? I think of something like the following:
if supports(obj, ?[]?):
print("Supports")
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With