Proper way to assert type of variable in Python

后端 未结 3 1151
遇见更好的自我
遇见更好的自我 2021-01-31 01:13

In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?

Here is an example fake function trying to do just this before

3条回答
  •  无人及你
    2021-01-31 01:57

    Doing type('') is effectively equivalent to str and types.StringType

    so type('') == str == types.StringType will evaluate to "True"

    Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

    isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

    class MyClass: pass
    
    print isinstance(MyClass(), MyClass) # -> True
    print isinstance(MyClass, MyClass()) # -> TypeError exception
    

    But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

提交回复
热议问题