Python parsing of "type" keywords


#1

I have a curiosity question. There was an exercise that asked the user to test for a whether a passed in value was of a certain type, “int” or “float”… for example. I thought I would have to compare it to a string:

if (type(num) == “int”):
do this
else:
do that

But that gets an error.
It turns out it is looking for a literal… no quotes around it. I noticed that if I do this:
print type(num)

the console shows something like <type: int> or <type: float>
So my question is regarding how does Python parse this when running a comparison?

In otherwords, how does <type: int> == int ? is this under the hood magic?


#2

types aren’t strings, similar to how a number is never equal to any string

Instead you would compare the type, to a type

int float str type list tuple set dict … and others, are all types (yes, type is a type, it’s at the top of the type hierarchy (all types are types))

So no, no magic whatsoever there. Not only is the type of 5 equal to int, they are one and the same value, you’d be comparing int to itself


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.