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
0
votes
2 answers

replacing all instances of %X with Xth argument in args in python

I am currently trying to replace the occurrence of a number x with the xth argument in a string. Here is my code: def simple_format(format, *args): res = format.replace("%", "") for x in res: if (isinstance(x, int)): res…
Shsa
  • 17
  • 10
0
votes
1 answer

python is instance() - how to make it worth with classes other than builtins

Reading documentation for isinstance() and looking up examples online, examples only illustrate how to use it with builtin classes like: str, int, float, long I have code where the variable myObj.location will either be None if it hasn't been set…
TMWP
  • 1,545
  • 1
  • 17
  • 31
0
votes
0 answers

How to find which key got return "False"?

JSON data: new_dto_data = [{'DeviceInstanceId': 24, 'IsResetNeeded': False, 'ProductType': 'SLDW', 'Product': {'Family': 'SL DW'}, 'Device': {'DeviceFirmwareUpdate': {'DeviceUpdateStatus': None, 'DeviceUpdateInProgress': None,…
nrs
  • 937
  • 3
  • 17
  • 42
0
votes
1 answer

Using a Class Loader, how do I check Instance of For Two Classes

So in my scenario I am using the URLClassLoader and I've loaded a directory containing class a, b and c. class b extends class a, class c extends nothing. How can I check this in my code I have been trying to use b.isInstance(a) however this returns…
0
votes
1 answer

isinstance: How to manage set classes better

While writing some debugging python, I seem to have created a bit of ugly code that I would like to clean up. Here is the function in its entirety: def debug(message, variable=None): if variable and DEBUG: print("\n" +…
Robert J
  • 840
  • 10
  • 20
0
votes
2 answers

Can't get an object's class name in Python

I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object: >>> import re >>> x = re.compile('test') >>> x.__class__.__name__ Traceback (most recent call last): File "", line 1, in…
zumjinger
  • 41
  • 1
  • 5
0
votes
0 answers

Avoid long list of elif isinstance

I have the following construction with a long list of around 100 if .. elif. Is there a way do handle this more elegantly in python? if isinstance(scen_dep, Class1): scen_deps[someEnum.class2].append('1') elif isinstance(scen_dep,…
Nickpick
  • 6,163
  • 16
  • 65
  • 116
0
votes
1 answer

isinstance() method python returning wrong values

list_d = ["a","b","c",3,5,4,"d","e","f",1,"ee"] list_e = [] print("Before: %s"%(list_d)) print("Before: %s"%(list_e)) for item in list_d: if isinstance(item,int): list_d.pop(item) list_e.append(item) print("After:…
Minh Doan
  • 37
  • 7
0
votes
0 answers

Python's assert isinstance not working for type hinting in Visual Studio, but only for datetime.date

The code below has the tool tip "myDate: " when I mouse over myDate. from datetime import date assert isinstance(myDate,date) This only seems to happen with types from datetime. I have no problem with built-ins, like dict, other…
Robino
  • 4,530
  • 3
  • 37
  • 40
0
votes
1 answer

isinstance return improper result with nested application

I developed a tool and I want to use it in another application. Now, I just copy my tool in the new application. The file architecture is shown as below. . ├── inner │   ├── a │   │   ├── a.py │   │   └── __init__.py │   ├── b │   │   ├── b.py │  …
Ben Lee
  • 102
  • 1
  • 1
  • 9
0
votes
1 answer

Using basestring in is instance - Type mismatch warning

The warning is: Expected type 'Union[type, Tuple[type, ...]]', got 'Union[str, unicode]' instead. Am I doing something wrong?
0
votes
3 answers

Use isinstance with an undefined class

Assume that class MyClass is sometimes, but not always, defined. I have a function foo(a=None) in which argument a can be None, a string, or an object of MyClass. My question is: If MyClass is not defined in my Python session, how can I check the…
0
votes
0 answers

How to read special character input in python3?

In Python3, When I try to read the input foo(1,?i:int) from console: It gives syntax error! It can accept other inputs such as foo(1,2,2),foo('d',0). def foo(*x): #Multiple Argument function print(x)
Sumi
  • 11
  • 1
  • 1
  • 2
0
votes
1 answer

Python - Identifying Extraneous Types within a List

Suppose I have a 2-Dimensional list representing a matrix of numerical values (No, I am not using numPy for this). The allowed types within this list fall under the category of numbers.Number. Supposing that I wish to isolate any non-numerical…
S. Gamgee
  • 501
  • 5
  • 16
0
votes
2 answers

Check if item in a Python list is an int/number

I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this. list = [] i = 0 for row in reader: list.append([]) list[i].append(row[0]) ... …
Brendan
  • 908
  • 2
  • 15
  • 30