Search code examples
pythontypecheckingpython-internals

Why does type checking not work for what type returns?


I just tried to test:

if type(model_lines) == 'str':
    turn into a list using split

based on:

In [196]: type('a')
Out[196]: str

however, for x, a string:

In [193]: if type(x) == 'str':
    print 'string'
   .....:  

In [195]: if type(x) == type('a'):
    print 'string'
   .....:     
string

I am curious as to why I cannot use this output to check types, it seems cleaner and faster to read. What does type actually return that won't allow checking by its return display?


Solution

  • Because, type() returns the class for the object, not the string name of the class , so if you do something like the below, it would work -

    >>> if type('abcd') == str:
    ...     print("Blah")
    ...
    Blah
    >>> type('abcd')
    <class 'str'>
    

    As you note above, I checked return of type('abcd') against str class , not string 'str' .

    If you want the string representation of the class, use tpye(<something>).__name__ , to get the string name of the class, Though this is not needed for your case, just for your information. Example -

    >>> type('abcd').__name__
    'str'