What's the canonical way to check for type in Python?

后端 未结 13 1060
南旧
南旧 2020-11-21 07:34

What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?

Let\'s say I have an objec

13条回答
  •  旧巷少年郎
    2020-11-21 07:57

    To Hugo:

    You probably mean list rather than array, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.

    Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all

    try:
       my_sequence.extend(o)
    except TypeError:
      my_sequence.append(o)
    

    One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.

    I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ] around your single value when you pass it in if need be.

    (Though this can cause errors with strings, as they do look like (are) sequences.)

提交回复
热议问题