Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Determine the Type of an Object in Python?

#1
How to Determine the Type of an Object in Python?

How to Determine the Type of an Object in Python?

Problem Formulation


Every Python object is of a certain type, also called “class”. The class is a blueprint that shows the data and capabilities of each object/instance that is created after this blueprint.

Given a Python object (=instance). How to determine/check/get its type (=class)?

There are many variants of this question:

  • How to determine the type of an object?
  • How to check the type of an instance?
  • How to get the class of an object?
  • How to check the class of an instance?

Let’s start with a short overview how you can answer all of those in the most Pythonic way.

Solution Overview


In Python, the built-in functions type() and isinstance() help you determine the type of an object.

  • type(object) – Returns a string representation of the object’s type.
  • isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.

Here are two examples to check if an object is a list:

>>> type([1, 2, 3])
<class 'list'>
>>> isinstance([1, 2, 3], list)
True

You’d use type() to check for the exact type of an object. You’d use isinstance() to confirm your suspicions regarding the type of an object. The function isinstance() is more robust in that you don’t rely on tiny string differences, and it also works with type inheritance. For example, if A inherits from B which inherits from C, an object of type C is also an instance of A.


type() examples with one object argument:

>>> type([1, 2, 3]) is list
True
>>> type({1, 2, 3}) is dict
True
>>> type('123') is str
True
>>> type(0) is int
True

type() with custom objects:

>>> class Animal: pass >>> class Snake(Animal): pass >>> a = Animal()
>>> b = Snake()
>>> type(a) is Animal
True
>>> type(b) is Snake
True
>>> type(b) is Animal
False

The third example type(b) is Animal leads us to the following insight:

? Insight: type() returns only the immediate type of an object, but doesn’t work with inheritance.

If you want to overcome this weakness, you should use the isinstance() function that also works for inherited types:

>>> isinstance(Snake(), Animal)
True

You can also use it on built-in objects and types such as lists, tuples, sets, and dictionaries:

>>> isinstance([1, 2, 3], list)
True
>>> isinstance((1, 2, 3), tuple)
True
>>> isinstance({1: 'a', 2: 'b'}, dict)
True
>>> isinstance({1, 2, 3}, set)
True

The only use case where you’d prefer type() over isinstance() is if you actually need the type string representation of an object. Otherwise, isinstance() is a more flexible and expressive function.

type() vs isinstance()


The difference between type() and isinstance() is the return value which is a string representation for the former and a Boolean value for the latter. You’d use the type() function if you know nothing. If you already suspect an object to be of a certain type (=class), you can confirm your suspicion by using the isinstance() function.

Python type() Function


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.



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'>
Syntax: 
type(object) # Returns class representation of object

Arguments object Object to be checked for type.
Return Value string Returns string representation of the object‘s class.

Related Tutorial: Python type() Function

Python isinstance() Function


Python’s built-in isinstance(object, class) function takes an object and a class as input arguments. It returns True if the object is an instance of the class. Otherwise, it returns False. Instead of a class, you can also pass a tuple of classes to check if the object is an instance of any of the classes in the tuple—such as in isinstance(object, (class_A, class_B, ...)).



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

>>> isinstance(42, int)
True
>>> isinstance(42, (float, list, int))
True
>>> isinstance('42', (float, list, int))
False
Syntax: 
isinstance(object, class) # Check if object is instance of class
isinstance(object, (class_A, class_B, ...)) # Check if object is instance of any of the classes in the tuple

Arguments object Object that should be checked for class membership.
class or tuple of classes Class or tuple of classes this object may or may not belong to.
Return Value Boolean Returns whether the object belongs to the class (or the classes) or not.

The post How to Determine the Type of an Object in Python? first appeared on Finxter.



https://www.sickgaming.net/blog/2021/04/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] [Solved] TypeError: ‘int’ Object Is Not Subscriptable in Python xSicKxBot 0 24 03-31-2021, 08:56 PM
Last Post: xSicKxBot
  [Tut] [Solved] TypeError: ‘Module’ Object Is Not Callable in Python xSicKxBot 0 20 03-25-2021, 08:09 PM
Last Post: xSicKxBot
  [Tut] Python Celery – How to Get a Task Result Object by ID? xSicKxBot 0 17 03-18-2021, 06:52 PM
Last Post: xSicKxBot
  [Tut] Python object() Function xSicKxBot 0 67 02-16-2021, 08:16 PM
Last Post: xSicKxBot
  [Tut] How to Check if an Object is of Type List in Python? xSicKxBot 0 53 02-09-2021, 08:05 AM
Last Post: xSicKxBot
  [Tut] How to Fix “TypeError: len() of unsized object” xSicKxBot 0 62 01-31-2021, 12:55 PM
Last Post: xSicKxBot
  [Tut] What’s the Standard Way to Check for Type in Python? xSicKxBot 0 52 01-25-2021, 04:47 PM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 65 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] How to Get The Current Reference Count of an Object in Python? xSicKxBot 0 67 12-21-2020, 08:13 AM
Last Post: xSicKxBot
  [Tut] Python complex() — A Useless Python Feature? xSicKxBot 0 73 12-19-2020, 02:05 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
News - Nintendo Actually Responded To A ...
Last Post: xSicKxBot
Today 01:50 AM
» Replies: 0
» Views: 5
News - Rumour: Dragon Ball Z: Kakarot Co...
Last Post: xSicKxBot
Today 01:50 AM
» Replies: 0
» Views: 5
Xbox Wire - Next Week on Xbox: April 6 t...
Last Post: xSicKxBot
Yesterday 11:48 PM
» Replies: 0
» Views: 7
News - Ubisoft hires ex-Uber HR director...
Last Post: xSicKxBot
Yesterday 11:48 PM
» Replies: 0
» Views: 12
News - Blog: An essential guide to live ...
Last Post: xSicKxBot
Yesterday 11:48 PM
» Replies: 0
» Views: 13
[Tut] Python Dash Book
Last Post: xSicKxBot
Yesterday 05:52 PM
» Replies: 0
» Views: 6
(Indie Deal) Adventure Tales Bundle, Qua...
Last Post: xSicKxBot
Yesterday 05:52 PM
» Replies: 0
» Views: 7
News - Good Job! Is The Next Nintendo Sw...
Last Post: xSicKxBot
Yesterday 05:49 PM
» Replies: 0
» Views: 8
News - Random: Halo Instagram Shows Off ...
Last Post: xSicKxBot
Yesterday 05:49 PM
» Replies: 0
» Views: 7
News - Guide To Refresh Rates And Respon...
Last Post: xSicKxBot
Yesterday 05:49 PM
» Replies: 0
» Views: 16

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020