After all, what should I use to do type comparisons in Python?

Difference between ʻisand==`

== is judged by "whether it is the same value", while ʻis` is judged by "whether it is the same object". For example, in the following example

>>> a = "hello"
>>> b = "hello"

Both objects have the same value, so when compared with ==, it returns True.

>>> a == b
True

However, ʻis is judged by "is it the same object?" In Python, when you create an object, it is given a unique number. ʻIs is identified by its number. You can check the number with ʻid () `.

>>> id(a)
2827074142256
>>> id(b)
2827074145520
>>> a is b
False

You can also compare types with ʻis instance`

ʻIs instanceis a function that compares the classes of objects. If it inherits another class, it returnsTrue` even when compared to the parent class

>>> class customint(int):
...     pass
...
>>> c = customint()
>>> type(c) == int
False
>>> type(c) is int
False
>>> isinstance(c, int)
True

Measure the execution time

things to do

Execute each function 10,000,000 times (10 million times) and measure the execution time Repeat this 10 times to calculate the average For reference, I also run a function that loops 10,000,000 times without doing anything

Source code

#!/usr/bin/env python3
# coding: utf-8

from time import time

intvar = 0
n = 10 ** 7


def gettime(name, num=10):
    """
Execute 10 times, measure the execution time, and calculate the average
    """
    def func(fn):
        def wrapper(*args, **kwargs):
            strat_t = time()
            for a in range(num):
                fn(*args, **kwargs)
            dur = (time() - strat_t) / 10
            print(name, "\t:", dur)
        return wrapper
    return func


@gettime("simple\t")
def simple():
    for x in range(n):
        pass


@gettime("equal\t")
def equal():
    for x in range(n):
        res = type(intvar) == int


if type(intvar) == True:
    pass


@gettime("is\t")
def iscompare():
    for x in range(n):
        res = type(intvar) is int


@gettime("isinstance")
def isinstancecompare():
    for x in range(n):
        res = isinstance(intvar, int)


if __name__ == '__main__':
    simple()
    equal()
    iscompare()
    isinstancecompare()

result

(Unit: seconds)

Execution environment Windows 10
Intel Core i7-8550U @ 1.80GHz
RAM:16GB
Sakura's VPS(v3) 1G
Empty loop 0.1508335590362549 0.37562224864959715
== 0.8364578723907471 1.9130330801010131
is 0.8253042459487915 1.799116063117981
isinstance 0.5259079456329345 1.3679522275924683

Consideration

Execution time is == > is >>> isinstance It became a feeling. So

――I want to do type comparison considering inheritance ――I'm not sure about inheritance, but I just want to find speed

In case of ʻis instance`,

--I want to ignore inheritance and perform type comparison

In that case, use ʻis`.

Impressions

I used the decorator for the first time, but it's really convenient

Recommended Posts

After all, what should I use to do type comparisons in Python?
What should I do with the Python directory structure after all?
What command should I type to list currently available modules like gem list in python?
VRM output for VRoid cluster, what should I do after all?
What to do when the value type is ambiguous in Python?
I want to do Dunnett's test in Python
[Python] What I did to do Unit Test
What to do if you can't use scikit grid search in Python
What should I do with DICOM in MPEG2?
[Question] What happens when I use% in python?
What to do to get google spreadsheet in python
What I do when imitating embedded go in python
I tried to summarize how to use pandas in python
I want to use the R dataset in python
I want to do something in Python when I finish
What I learned in Python
What to do if ʻarguments [0] .scrollIntoView ();` fails in python selenium
I want to do something like sort uniq in Python
What to do when "SSL: CERTIFICATE_VERIFY_FAILED _ssl.c: 1056" appears in Python
[Python] How to do PCA in Python
What to do with PYTHON release?
How to use Mysql in python
How to use ChemSpider in Python
How to use PubChem in Python
What to do if you get a minus zero in Python
MacBookPro Setup After all I want to do a clean installation
What I was addicted to with json.dumps in Python base64 encoding
How to use the asterisk (*) in Python. Maybe this is all? ..
[Python] When you want to use all variables in another file
I wanted to do something like an Elixir pipe in Python
What to do if you can't use the trash in Lubuntu 18.04.
What automation should I do in RPA, VBA, and programming languages?
What to do when ModuleNotFoundError: No module named'XXX' occurs in Python
I tried to implement PLSA in Python
[Introduction to Python] How to use class in Python?
I tried to implement permutation in Python
How to do R chartr () in Python
I tried to implement PLSA in Python 2
I want to use jar from python
Data analysis, what do you do after all?
Easy way to use Wikipedia in Python
I tried to implement ADALINE in Python
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
How to use __slots__ in Python class
How to use regular expressions in Python
What to do after installing Linux (Ubuntu)
How to use is and == in Python
What I did to save Python memory
What skills do I need to program with the FBX SDK Python?
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
What to do if there is a decimal in python json .dumps
What to do if No Python documentation found for ... appears in pydoc
A memorandum because I stumbled on trying to use MeCab in Python
I want to do a monkey patch only partially safely in Python
What to do if PyInstaller3.5 gives an error in Python3.8 (TypeError: an integer is required (got type bytes))
[Python] What to do if an error occurs in pip (pyinstaller, pyautogui, etc.)
How to use the C library in Python
I want to visualize the transfer status of the 2020 J League, what should I do?
[Python] How to use two types of type ()
I want to use MATLAB feval with python