Bohdan
Bohdan

Reputation: 23

Build in type() function behaviour differs when run in method

I'm fairly new to Python and I don't understand this behavior:

In [62]: a = "string"

In [63]: type(a)                                                                                                                                                                                            
Out[63]: str

In [64]: def some_method(what):                                                                                                                                                                             
             var = type(what)
             if var == "str":
                 print("it is str")
             else:
                 print("it's NOT str")
             print("Val of passed arg is - ", what, "And 'var' is - ", var)

In [65]: some_method(a)                                                                                                                                                                                     
it's NOT str
Val of passed arg is -  string And 'var' is -  <class 'str'>

Could anyone explain as to why variable "var" has a value "class 'str'",

instead of how it's displayed in ipython3 RAPL - "str"?

Thanks.

Upvotes: 1

Views: 52

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160467

This is just IPython's way of displaying things. str isn't equal to 'str':

In [14]: type(a) == "str"
Out[14]: False

IPython defines its own displayhook which displays results to you, the original displayhook (found in sys.__displayhook__) makes this clear:

In [15]: sys.__displayhook__(type(''))
<class 'str'>

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599628

No it doesn't. In neither of those cases is the type equal to the string "str". It's equal to the type str.

In any case, to check if something is a string, you should use isinstance, again with the actual type object.

if isinstance(var, str):
    print("it is str")

Upvotes: 4

Pavel
Pavel

Reputation: 7562

You are comparing the type of a variable to a string rather than to a type. Just drop the quotes in your if-clause:

>>> a = "string"
>>> type(a)
<class 'str'>
>>> type(a) == str
True
>>> type(a) == "str"
False

Upvotes: 3

Related Questions