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
-1
votes
1 answer

Checking if an object is in a determined class python

I'm trying to create a class representing vectors (called Vector) and one representing matrices (called Matrix). The problem arised in defining the matrix-vector product: I don't see errors in the actual implementation, but I tried to add a check…
-1
votes
1 answer

Best way to check if a variable is a number (int, float, np.float32, np.int64, ...) in python?

I am running in this multiple times now and never found a satisfying solution. I want to check: Is variable some_var of a number type? More specific for me: Can it be compared to another number? (e.g. a string should fail) Numpy makes this somehow…
CodePrinz
  • 445
  • 5
  • 8
-1
votes
1 answer

How to programmatically find if the object type is of Google Protobuf?

I have a case where I receive objects from another module. The object type can be JSON String, dict or of Google Protobuf. I can use isinstance in python to determine whether it is JSON String or dict, but finding it difficult to use isinstance to…
user2896235
  • 339
  • 3
  • 17
-1
votes
1 answer

Matplotlib - TypeError: isinstance() arg 2 must be a type or tuple of types

I'm trying to make some plots using the matplotlib library. However, anytime I try to run plt.plot() I get the error: if (isinstance(marker, np.ndarray) and marker.ndim == 2 and TypeError: isinstance() arg 2 must be a type or tuple of types in the…
Jek Jek
  • 17
  • 2
-1
votes
1 answer

Appending dictionaries to list within a dictionary by asking if input is a list

I am working with a list of dictionaries within a dictionary. authors=['a','b'] new_item={'itemType': 'journalArticle', 'title': '', 'creators': [{'creatorType': 'author', 'firstName': '', 'lastName': ''}]} if type(authors) == 'list': …
Sati
  • 716
  • 6
  • 27
-1
votes
1 answer

Python isinstance returns false. Custom class

I have written the following code. class Mammal: def info(): return 'I have fur on my body.' def identity_mammal(): print('I am a mammal') class Primate(Mammal): def info(): return Mammal.info() + ' I have a…
Iscariot
  • 11
  • 5
-1
votes
2 answers

Using isinstance() to remove integers from a json

I'm coding in Python and working with a JSON file that has 2 columns of data; a key, and the number of times that key was found in the data I'm working with. My goal is to remove all keys that are integers. I've extracted the JSON as test_map, then…
-2
votes
1 answer

How to change value in a dict?

I have so many dict data with different formats and I want to change the key place to None. I create this function to read all value, but I can change it def test(T, data): if T: T.pop(0) for cle, valeur in data.items(): if…
-2
votes
1 answer

I have a class with one required and two optional parameters, and a repr method which returns with one of the optional params, whichever is given

class MyClass(): def __init__(self, name, high=None, low=None): self.name = name if low: self.low = low elif high: self.high = high else: raise Error("Not found") def…
Pranava
  • 15
  • 4
-2
votes
2 answers

isinstance on a list that contains int and str

I am trying to take out numbers from a list that contains both numbers and strings and move them into a new list. x = 0 list1 = ["a", "b", "c", 1, 2, 3, 4, 5, 6, "d", 7] list2 = [] for item in list1: if isinstance(item, int): …
-2
votes
1 answer

Why is this Isinstance function not working?

This does not print anything for some reason. main = 60 x = isinstance(main, int) if x == ("True"): print("True") elif x == ("False"): print("False")
-2
votes
1 answer

What argument 'isinstance' takes on declaring 'k' object?

class Point: def __init__(self, x_or_obj = 0, y = 0): if isinstance(x_or_obj, Point): self.x = x_or_obj.x self.y = x_or_obj.y else: self.x = x_or_obj self.y = y m = Point(1,2) k =…
Anton Ionov
  • 21
  • 1
  • 4
-2
votes
1 answer

Python: why does my function return an empty list?

I'm trying to write a function that returns all the strings within in a list. Uing the isinstance() method and a for loop, I append the strings to a new list and then return the list. However, the list is empty. Interestingly enough, when I use…
-2
votes
1 answer

Determine if a variable is an instance of any class

How to determine if a variable is an instance in Python 3? I consider something to be an instance if it has __dict__ attribute. Example: is_instance_of_any_class(5) # should return False is_instance_of_any_class([2, 3]) # should return…
Damian
  • 178
  • 11
-2
votes
2 answers

what is the difference in these two isinstances() definitions?

isinstance(list(), type(mylist)) isinstance(mylist, list) Is there any difference apart from the speed? I can see 2 is faster.
user2715898
  • 921
  • 3
  • 13
  • 20
1 2 3
15
16