liveBook · Manning

Type function

As explained in Python How-To

type is a Python built-in function that returns the type of an object.

The type function is a Python built-in that returns an object’s type. Use it when runtime inspection helps a function accept different input forms, such as an integer or a list. section 10.1.1 section 10.1

Inspecting values

print(type(4)) # output: <class 'int'> print(type([4, 5])) # output: <class 'list'> section 10.1.1

Compare the returned type with a class to select behavior. In a task-filtering function, a list uses membership testing, while another value uses direct urgency comparison. section 10.1.1

Listing 10.1 Comparing an object’s type with a class
def filter_tasks(tasks, by_urgency):
   if type(by_urgency) is list:
       filtered = [x for x in tasks if x.urgency in by_urgency]
   else:
       filtered = [x for x in tasks if x.urgency == by_urgency]
   return filtered

Branches on whether by_urgency is a list, then filters tasks with membership or equality. section 10.1.1

Keep these distinctions in mind:

  • type(value) reports the value’s current runtime type. section 10.1.1
  • Python variables can later refer to values of another type; type inspection observes that current value rather than fixing the variable. section 6.3.1
  • Use isinstance for a more flexible instance check when superclass relationships matter. section 10.6

How Python How-To covers it

How deep it goes
Explains the return value and a worked type-based branch, while deferring superclass-friendly checks to isinstance.
Examples
Demonstrates integers, lists, reassigned variables, assertions, and a task-filtering function.
What it assumes
Assumes basic Python values and functions while introducing runtime object inspection and its role in flexible interfaces.
What you can do after
Apply it via Python’s built-in type function to inspect values and branch behavior for supported input types.
How it connects
Connects runtime introspection with object types, dynamic typing, type hinting, and isinstance.

Also explained in

Compare how 3 books explain type function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.