Python type() Function

Rate this post

Python’s built-in type() function has two purposes. First, you can pass an object as an argument to check the type of this object. Second, you can pass three arguments—name, bases, and dict—to create a new type object that can be used to create instances of this new type.

Python type() Function Visual Explanation

Usage

Learn by example! Here’s an example on how to use the type() built-in function.

First, here’s how to use the type() function with one argument to check the type of a given object:

>>> type(42)
<class 'int'>
>>> type('Finxter')
<class 'str'>

Second, you can pass three arguments name, bases, and dict to create a new type:

>>> porsche = type('Car', (object,), {'speed': 100, 'electric':False})
>>> porsche
<class '__main__.Car'>
>>> porsche.speed
100
>>> porsche.electric
False

Let’s dive deeper into the powerful type() function to learn about it’s powerful features and usages!

Video type()

Let’s dive into the syntax of type() :

  • Syntax type() with one argument to check class of object
  • Syntax type() with three arguments to create new instance

Syntax type() with One Argument to Check Class of Object

Syntax: 
type(object)         # Returns class representation of object
ArgumentsobjectObject to be checked for type.
Return ValuestringReturns string representation of the object‘s class.

An example is the following:

>>> type(42)
<class 'int'>
>>> type('Finxter')
<class 'str'>

In both cases, a string representation of the object’s class is returned.

Syntax type() with Three Arguments to Create New Instance

Syntax: 
type(name, bases, dict)         # Create a new instance with class name, base classes as defined in bases, and initial attributes as defined in dict
ArgumentsnameNew instance has this class name.
basesA tuple of one or more base classes. For example, the tuple(object,) indicates that it only inherits from the base class object.
dictDictionary mapping attribute names to attribute values.
Return ValuenameReturns a new instance of class name as defined in the argument list.

An example is the following:

>>> porsche = type('Car', (object,), {'speed': 100, 'electric':False})
>>> porsche
<class '__main__.Car'>
>>> porsche.speed
100
>>> porsche.electric
False

If you want to create another instance of the class car, you’d need to do some copy&paste work:

>>> tesla = type('Car', (object,), {'speed': 100, 'electric': True})
>>> tesla.electric
True

To avoid this, you could also create a new lambda function to one-linerize the object creation process with type():

>>> new_car = lambda attributes: type('Car', (object,), attributes)
>>> porsche = new_car({'speed':100, 'electric': False})
>>> tesla = new_car({'speed': 100, 'electric': True})
>>> porsche.electric
False
>>> tesla.electric
True

Interactive Shell Exercise: Understanding type()

Consider the following interactive code:

Exercise: Which type does the porsche instance have? Run to check!


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Summary

Python’s built-in type() function has two purposes.

  • First, you can pass an object as an argument to check the type of this object.
  • Second, you can pass three arguments—name, bases, and dict—to create a new type object that can be used to create instances of this new type.

First, here’s how to use the type() function with one argument to check the type of a given object:

>>> type(42)
<class 'int'>
>>> type('Finxter')
<class 'str'>

Second, you can pass three arguments name, bases, and dict to create a new type:

>>> porsche = type('Car', (object,), {'speed': 100, 'electric':False})
>>> porsche
<class '__main__.Car'>
>>> porsche.speed
100
>>> porsche.electric
False

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!