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

后端 未结 13 1031
南旧
南旧 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:45

    The most Pythonic way to check the type of an object is... not to check it.

    Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!

    Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.

    0 讨论(0)
  • 2020-11-21 07:45

    You can check for type of a variable using __name__ of a type.

    Ex:

    >>> a = [1,2,3,4]  
    >>> b = 1  
    >>> type(a).__name__
    'list'
    >>> type(a).__name__ == 'list'
    True
    >>> type(b).__name__ == 'list'
    False
    >>> type(b).__name__
    'int'
    
    0 讨论(0)
  • 2020-11-21 07:49
    isinstance(o, str)
    

    Link to docs

    0 讨论(0)
  • 2020-11-21 07:51

    You can check with the below line to check which character type the given value is:

    def chr_type(chrx):
        if chrx.isalpha()==True:
            return 'alpha'
        elif chrx.isdigit()==True:
            return 'numeric'
        else:
            return 'nothing'
    
    chr_type("12)
    
    0 讨论(0)
  • 2020-11-21 07:53

    I think the best way is to typing well your variables. You can do this by using the "typing" library.

    Example:

    from typing import NewType UserId = NewType ('UserId', int) some_id = UserId (524313)`

    See https://docs.python.org/3/library/typing.html

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题