Questions tagged [isinstance]

isinstance is a Python built-in function used to test whether or not a specific object is an instance of a particular class or type. It is available in both versions 2 and 3. Use this tag for questions explicitly dealing with the isinstance built-in.

isinstance is a Python built-in function used to test whether or not a specific object is an instance of a particular class or type. It is available in both versions 2 and 3. Use this tag for questions explicitly dealing with the isinstance built-in.

The schematics for the function are below:

isinstance(object, class-or-type-or-tuple) -> bool

where object is the object to test and class-or-type-or-tuple is a class, type, or tuple of classes and/or types.

When invoked, and given a single class or type as its second argument, the function will return either True or False depending on whether or not the first argument is an instance of the second. Below is a demonstration:

>>> isinstance(1, int)
True
>>> isinstance(1, str)
False
>>>

If the function is given a tuple of classes and/or types as its second argument, it will return either True or False depending on whether or not the first argument is an instance of any of the classes/types contained in the tuple. Below is a demonstration:

>>> isinstance('a', (int, str))
True
>>> isinstance('a', (int, bool))
False
>>>

It should also be noted that the following code:

isinstance('a', (int, str))

is equivalent to this:

isinstance('a', int) or isinstance('a', str)
230 questions
4
votes
1 answer

Python 3 isinstance unexpected behavior when importing class from different file?

I am trying to import a class from one file and check if is an instance of that class in the file that it was defined in. The problem is that instead of returning True from theisinstance() function, it returns False, because it was initialised in a…
Monolith
  • 1,067
  • 1
  • 13
  • 29
4
votes
1 answer

How do i use correctly the isinstance()

def convBin(): cont = [] rest = [] dev = [] decimal = [] print("Give me a number: ") valor = input() if isinstance(valor, int): while valor > 0: z = valor // 2 resto = x%2 …
Lunargenta
  • 65
  • 1
  • 8
4
votes
1 answer

Python assert isinstance() Vector

I am trying to implement a Vector3 class in python. If I would write the Vector3 class in c++ or c# i would have X, Y, and Z members stored as floats but in python I read that ducktyping is the way to go. So according to my c++/c# knowledge I wrote…
Stefan B
  • 541
  • 2
  • 6
  • 13
4
votes
0 answers

Why MutableMapping is not instance of dict?

I would like to create a dictionary-like object as recommended here. Here is my example: import collections class DictLike(collections.MutableMapping): def __init__(self, *args, **kwargs): self.store = dict() …
grundic
  • 4,641
  • 3
  • 31
  • 47
4
votes
1 answer

Use of isinstance() can overwrite type

Use of isinstance() changed the class type of dict Why is this happening? I know using builtins would prevent but I want to understand better why this is happening. 250 def printPretty(records,num,title='Summary:'): 251 import pdb;…
user113411
  • 69
  • 1
4
votes
2 answers

Which is the appropriate way to test for a dictionary type?

Why are there so many different ways to test for a dictionary? And what would be the most modern way to test if an object is a dictionary? adict = {'a': 1} In [10]: isinstance(adict, types.DictType) Out[10]: True In [11]: isinstance(adict,…
Jacques René Mesrine
  • 46,127
  • 27
  • 66
  • 104
4
votes
2 answers

How to make a file-like class work with "isinstance(cls, io.IOBase)"?

It seems that checking isinstance(..., io.IOBase) is the 'correct' way to determine if an object is 'file-like'. However, when defining my own file-like class, it doesn't seem to work: import io class file_like(): def __init__(self): …
kiri
  • 2,522
  • 4
  • 26
  • 44
4
votes
1 answer

python pillow (better PIL) encoding check bug

I've just installed a Pillow package to my virtualenv. Doing this: from PIL import Image, ImageFont, ImageDraw ImageFont.load_path('some_path') I'm getting an error: Traceback (most recent call last): File "", line 1, in File…
mnowotka
  • 16,430
  • 18
  • 88
  • 134
3
votes
2 answers

isinstance() and type() equivelence failure due to import mechanism (python/django)

In a Django project I'm working on I import a form in the view as follows #views.py from forms import SomeForm then in a test file I have #form_test.py from app.forms import SomeForm . . . self.assertTrue(isinstance(response.context['form'],…
powlo
  • 2,538
  • 3
  • 28
  • 38
3
votes
4 answers

Making 'isinstance' work with decorators

How does the Python isinstance function work internally? Is there anything I can do to alter its results, like define a special function inside a class or something? Here's my use case: class Decorator: def __init__(self, decorated): …
Paul Manta
  • 30,618
  • 31
  • 128
  • 208
3
votes
3 answers

How to properly check object types in Python?

Problem: I have to check that the a returned value is a Python dictionary. Q1. Which of these options is the proper way to do this? type(x) == dict type(x) == type(dict) isinstance(d, dict) Then there are the other variants using is operator…
Paolo
  • 20,112
  • 21
  • 72
  • 113
3
votes
1 answer

Difference between FileIO object and object returned by open(filename, mode)

Python has several io base classes including IOBase RawIOBase BufferedIOBase TextIOBase as well as several derived io classes: FileIO BytesIO Now, when i create a BytesIO object, the mro is: [, ,…
3
votes
3 answers

Faking whether an object is an Instance of a Class in Python

Suppose I have a class FakePerson which imitates all the attributes and functionality of a base class RealPerson without extending it. In Python 3, is it possible to fake isinstance() in order to recognise FakePerson as a RealPerson object by only…
Bentley Carr
  • 672
  • 1
  • 8
  • 24
3
votes
1 answer

Class instance fails isinstance check

Hi I have some code on my CI failing (local runs do not fail). The problem is that class instance fails isinstance() check. Code: File: main.py class MyController(SuperController): # Overrides default definition of get_variables_context() …
Peter Zaitcev
  • 316
  • 1
  • 14
3
votes
0 answers

Why is isinstance() returning different values for the same data depending on implementation?

I have a pandas dataframe df where I want to check the datatypes import pandas as pd import numpy as np df >>> a1 a2 a3 a4 0 5 10.08 22.9 50.45 1 25 13.80 43.0 NaN 2 2 8.30 15.0 17.00 print(df.dtypes) >>> a1 …
PyRsquared
  • 6,970
  • 11
  • 50
  • 86