Digital Communication


Digital Communication

Python type(): determine type


The Python type() function is a built-in Python function for working with object types. A basic function of Python, it belongs to the core of the language.

What is the Python type() function for?

The Python type() function is used in two very different cases :

  1. To determine the type of a Python object;
  2. To create a new dynamic type.

We will first consider the first casemuch more used for daily development.

Determining the type of an object with type()

Python is a dynamic typed language. This means that types are only determined at runtime and are tied to values ​​rather than variables. Result: it is necessary to determine the type of an object at run time.

We call Python’s type() function and pass an object as the only parameter. We receive in return the type of the object, for example intOr str:

assert type(42) == int
# Type of `str(42)` is `str`
assert type(str(42)) == str


If we call the type() function in Python’s REPL, text representation contains “class” instead of “type” :

# Returns "<class ‘int’>" inside REPL


What seems confusing at first turns out to be logical: in Python, “Everything is an object”. In Python, the type of an object corresponds to its class. So, calling the type() function is generally equivalent to reading the attribute __class__:

# Should hold in most cases
assert type(obj) is obj.__class__


Create a new type with type()

Now let’s look at the second possible use of the Python type() function. Called with three argumentsthis function allows us to dynamically create a new type:

type(name, bases, dict, **kwds)


In this form, the Python type() function works like the keyword class. The code Type = type("Type", bases, dict)roughly corresponds to the following class definition:

class <Type>(<bases>):


Below, you will find some concrete examples of the use of the Python type() function to create new types. First, here is an overview of the arguments:

name bases dict **kwds
Name of new type as string Tuple with base classes Dict with attributes of the new class Other arguments for instantiating the metaclass

With Deploy Now by IONOS, deploy your websites and apps with GitHub!

How does the Python type() function work?

When using the type() function to determine the type of an object, the following rule applies: return value is not a thong but a independent object :

# Value returned by `type(42)` is not a string
assert type(42) != ‘int’
# We get back an object named `int`
assert type(42) == int


Now let’s see some examples of values ​​returned by the type() function for objects of different types:

# Python objects of different types
different_objs = None, True, 42, ‘John’, (‘Walter’, ‘White’), ...
# Print out the type of each object
for obj in different_objs:
  print(f"{obj}: {type(obj)}")


call type() textual representation
type(None) <class ‘NoneType’>
type(True) <class ‘bool’>
type(42) <class ‘int’>
type(‘John’) <class ‘str’>
type((‘Walter’, ‘White’)) <class ‘tuple’>
type(…) <class ‘ellipsis’>

We can ask the question of type of object returned by type() ? To answer this one, let’s call the Python type() function and pass the value returned by another type() call:

# Returns: "<class ‘type’>"


We see it clearly here: in addition to Python’s built-in type() function, there is the type typeof the same name. This is the type of all other Python types, as can be seen in this example:

# DifferentPython objects
different_objs = None, True, 42, ‘John’, (‘Walter’, ‘White’), ...
# Check the type of each object’s type
for obj in different_objs:
  # Show that the type’s type is always `type`
  assert type(type(obj)) is type


The type of each Python type is therefore type. Does this seem confusing to you? There is even better: even the type of the object typeis also type. And this can continue endlessly, like a snake biting its tail:

# It’s `type` all the way down
assert type(type(type(type))) is type


To avoid confusion, one must delve into understanding Python’s OOP system in more depth. The embedded object typeof Python represents what is called a metaclass. A metaclass behaves with a class as a class behaves with an object. In other words, a metaclass is a template for a class, while a class is a template for an object:

Model Instance
Class Object
Metaclass Class
Example : type int, stretc.
Example :int 42
Example : str “Walter White”

How to use the type() function in Python?

Typically, Python’s type() function is used to determine the type of an object at run time. This is still useful because Python is a dynamically typed language. In a statically typed language like Java, a type is bound to a variable by declaration and cannot be changed at runtime:

// Declare variable as `boolean`
boolean answer;
// Attempting to assign `int` value
// Throws type error
answer = 42;


On the other hand, in Python variables are just names that refer to typed values. While the code is running, a name can at any time refer to a value of another type. To determine the type of a Python variable at run time, we will use the type() function:

# Assign boolean value
answer = True
# Show that type is `bool`
assert type(answer) is bool
# Reassign integer value
answer = 42
# Show that type is now `int`
assert type(answer) is int


Checking the Type of Function Arguments in Python

When defining a function, it is often necessary to check that the arguments meet certain criteria. For example, an argument can only fall within a certain range, or only arguments of defined types are allowed. To avoid runtime errors, for example.

Let’s illustrate the use of the type() function using an example: we will define a function that adds a list of numbers. For this to work, we need to make sure that each argument is indeed a number. In this case, type() will be used in an instruction assert:

# Function to add up numeric arguments
def add_numbers(*args):
  result = 0
  # Check each argument
  for arg in args:
    # Abort with error message if argument is not an `int` or `float`
    assert type(arg) in (int, float), f"Argument `{arg}` is not a number"
    # Add argument’s value to total
    result += arg
  return result

# Show that it works for numbers
assert add_numbers(35, 7) == 42
# The following will fail
add_numbers(29, ‘thirteen’)


Debugging in the Python REPL with the type() function

One of the advantages of using an interpreted language such as Python is interactive code execution in REPL loop (Read-Eval-Print-Loop). This approach helps in doing rapid prototyping and live debugging by inspecting objects in memory.

Let’s imagine the following scenario: our code includes a variable answerwhich must contain a Boolean value. We notice that the type does not match what is expected and use Python’s type() function to display the actual type. It turns out that we mistakenly wrote the Boolean value in quotation marks, a common careless error especially among beginners:

# Accidentally set to string
answer = ‘False’
# Assertion will fail
assert type(answer) is bool
# Correct to boolean value
answer = False
# Now assertion holds
assert type(answer) is bool


Create Python classes dynamically with the type() function

As we have seen, Python classes can be created dynamically, that is to say at run time, with the type() function. This is very useful for class families and we will illustrate it with the example of HTML tags. Let’s start by creating a base class Tagwhose objects can display themselves as HTML code:

# Class representing HTML tag
class Tag:
  # Initialize HTML tag with contents
  def __init__(self, *args):
    # Join contents of tag
    self.content = "".join([arg.__str__() for arg in args])
  # String representation returns HTML
  def __str__(self):
    return f"<{}>{self.content}</{}>"


Afterwards, we specialize the base class by inheritance on the respective specific tags as <p>Or <h1>. To do this, we call the type() function with three arguments:

# Create `P` class
P = type(‘P’, (Tag,), {"name": ‘p’})


  1. Name of the new class as a string;

  2. Base class tuples;

    Python allows multiple inheritance; to derive from a single class, we will use the notation (ClassName,).

  3. Dict with class name and other inputs as needed.

    Inputs can also be functions.

Afterwards, we are going to instantiate a tag p and check that the display is working correctly:

# Instantiate `p` tag
greeting = P("Hello world")
assert str(greeting) == ‘<p>Hello world</p>‘


The same effect can be obtained by analogous class definition :

# Create `P` class
class P(Tag):
  name = ‘p’


As another example, let’s create classes for headers with type(). As the creation of classes is done dynamically, it is possible to create by List Comprehension the classes for the six levels of headers in just one time :

h_1_to_6 = ( f"h{n}" for n in range(1, 7) )
headings = [type(heading, (Tag,), {"name": heading}) for heading in h_1_to_6]


As we have shown, it is interesting to use the type() function to easily create multiple related subclasses. The more complex example of defining classes for modeling playing cards illustrates this approach. Let’s start by defining a superclass Cardusing a keyword class:

# Class representing abstract playing card
class Card:
  def __init__(self, number):
    self.number = number
  # String representation
  def __str__(self):
    return f"{self.number} of {self.suite}"


Afterwards, let’s create subclasses for the four suits of cards using type():

# Create concrete types for each suite
Clubs = type(‘Clubs’, (Card,), {‘suite’: ‘Clubs’})
Diamonds = type(‘Diamonds’, (Card,), {‘suite’: ‘Diamonds’})
Hearts = type(‘Hearts’, (Card,), {‘suite’: ‘Hearts’})
Spades = type(‘Spades’, (Card,), {‘suite’: ‘Spades’})


Now it is possible to instantiate individual cards easily :

# Instantiate a 7 of Spades
card = Spades(7)
# Show that it worked
assert str(card) == ‘7 of Spades’


What are the limitations of the type() function?

As we have seen, the Python type() function is useful. However, there is some applications for which the function reaches its limits. Fortunately, Python has suitable approaches: we’ll look at a few of them.

Breaking down inheritance hierarchies with isinstance()

The type() function only determines the actual type of a Python object without considering the inheritance hierarchy. The resulting dilemma is illustrated by the playing card example used above. The type of a 7 of spades should be both “card” and “spades”. However, the type() function cannot determine this:

# Create a Seven of Spades
card = Spades(7)
# Our card is a Spade alright
assert type(card) is Spades
# But not a card??
assert type(card) is not Card


To correctly break down the underlying polymorphismwe will use the function isinstance().

# Seven of Spades is a `Spade`
assert isinstance(card, Spades)
# And is also a `Card`
assert isinstance(card, Card)


Python object type recognition made simple with match-case

As we showed above, the type() function in Python is often used to determine the type of an object at runtime. For distinguish between several types of objectwe use in this case a construction if-elif-else:

# Determine type of object
if type(obj) is int:
elif type(obj) is float:
elif type(obj) is ...:
  print("Something else")


Since version 3.10, however, Python recognizes the instruction match-case. This allows in particular to recognize types without calling the type() function.

In a block caseit is possible to use constructor functions like int(obj)Or str(obj). The block is matched if the object has the corresponding type:

# Example object
obj = 42
# Determine object type
match obj:
  case int(obj):
    print(f"{obj} is `int`")
  case float(obj):
    print(f"{obj} is `float`")
  case _:
    print(f"{obj} is something else")


Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact