[Tutor] Test for type(object) == ???
Steven D'Aprano
steve at pearwood.info
Sat Feb 11 04:30:06 EST 2017
On Fri, Feb 10, 2017 at 07:34:35PM -0600, boB Stepp wrote:
> I was playing around with type() tonight. If I type (pun intended), I get:
>
> py3: type(5)
> <class 'int'>
>
> So I naively thought a test for type int should go like:
>
> py3: type(5) == "<class 'int'>"
> False
The interactive intepreter is great, but you have to remember that what
you see is not necessarily what you've got. What you *see* is the string
representation of the object:
py> print
<built-in function print>
but what you've actually got is the object itself; in this case, it is
the print function, and in your case, it is the int class.
Generally angle brackets < > mean that the text between the brackets is
just a display form, something intended for the human reader, and not a
programmable syntax. You then have to know (from experience) how to
refer to the object in code.
In the case of int, there are three distinct things here:
- the class (or type) itself, a blob of memory somewhere in the
interpreter containing various methods and attributes used for working
with integers;
- the name the interpreter knows that class by, namely "int";
- the string representation for the human reader, "<class 'int'>".
So long as you remember the difference between the object itself, the
name we use to talk about the object, and the way we visually display
the object, you can't go wrong :-)
(The nation Russia is not the same as a map of Russia, which is not the
same as the word Russia, which is not the same as the letters R u
s s i a, or even Р о с с и ́я for that matter).
As they say: the map is not the territory. Or in the words of Steven
Wright, "I have a map of the United States... Actual size. It says,
'Scale: 1 mile = 1 mile.' I spent last summer folding it."
> I finally stumbled onto the correct form:
>
> py3: type(5) == int
> True
type(5) returns the class that we call "int". The name "int" returns
that same class.
> So my question is why does "type(5)" result in "<class 'int'>",
No, that's just the string representation of int.
Inside the interactive interpreter, when you hit ENTER, the interpreter
evaluates the line of code you have, generates a result, and then does
the equivalent of:
print(repr(result))
(except that None is suppressed).
--
Steve
More information about the Tutor
mailing list