Determining types in python with type()

The amount of information necessary to describe a type cannot fit into a single string; therefore types cannot simply be strings, nor should this information be stored with the data, so we are back to types as objects.
We will formally introduce the type() built-in function. The syntax is as follows:
The type() built-in function takes object and returns its type. The return object is a type object.


>>> type(4)
<type 'int'>
>>> type('Hello world')
<type 'str'>
>>> type(type(4))
<type 'type'>

In the examples above, we take an integer and a string and obtain their types using the type() built-in function; in order to also verify that types themselves are types, we call type() on the output of a type() call.
Note the interesting output from the type() function. It does not look like a typical Python data type, i.e., a number or string, but is something enclosed by greater-than and less-than signs. This syntax is generally a clue that what you are looking at is an object.
Objects may implement a printable string representation; however, this is not always the case. In these scenarios where there is no easy way to “display” an object, Python “prettyprints” a string representation of the object. The format is usually of the form: .
Any object displayed in this manner generally gives the object type, an object ID or location, or other pertinent information.


You may also like...