What's the canonical way to check for type in Python?
Asked Answered
B

19

1900

How do I check if an object is of a given type, or if it inherits from a given type?

How do I check if the object o is of type str?


Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.

Baranowski answered 30/9, 2008 at 11:0 Comment(4)
It seems the most common reason for asking for this is that one wants to distinguish between strings and iterables of strings. This is a tricky question because strings are iterables of strings -- a single-character string is even a sequence of itself (last time I checked -- one probably shouldn't rely on it). But would anyone ever have use for something string-like? Yes. So the answer to "What should I do to distinguish between strings and other iterables of strings?" is properly: "It depends on what you are trying to do". :-DVallie
Python type annotations are now a thing. Take a look at mypyScrutiny
@Vallie A single-character string is still a sequence of itself in 2022, and has been for as far back as I can determine; and the behaviour is a necessary consequence of strings being iterables over the characters (technically, Unicode code points) in them, plus the lack of a separate type for those individual characters.Puparium
@Scrutiny realize your comment is several years old but for posterity: that's cool... when using a static analyzer. There is still a place for runtime checks, like "did this JSON I just parsed produce the expected type?".Superannuated
C
2229

Use isinstance to check if o is an instance of str or any subclass of str:

if isinstance(o, str):

To check if the type of o is exactly str, excluding subclasses of str:

if type(o) is str:

See Built-in Functions in the Python Library Reference for relevant information.


Checking for strings in Python 2

For Python 2, this is a better way to check if o is a string:

if isinstance(o, basestring):

because this will also catch Unicode strings. unicode is not a subclass of str; both str and unicode are subclasses of basestring. In Python 3, basestring no longer exists since there's a strict separation of strings (str) and binary data (bytes).

Alternatively, isinstance accepts a tuple of classes. This will return True if o is an instance of any subclass of any of (str, unicode):

if isinstance(o, (str, unicode)):
Caulis answered 30/9, 2008 at 11:7 Comment(7)
str.__subclasses__() only returns the direct subclasses of str, and does not do the same thing as issubclass() or isinstance(). (To do that, you would have to recursively call .__subclasses__().Lesley
This is a good answer, but I think it really ought to start with a warning that you usually shouldn't be doing this in Python. As it is, it seems to validate the assumption that this is a "canonical thing to do in Python", which it isn't.Fionnula
What's the difference between instance and "exactly"? If type(a) is Object then isn't it also true that isinstance(a, Object). However, if type(a) is SubClassOfObject, then type(a) is Object == False, but isinstance(a, Object) == True. Right?Brattishing
@Brattishing - a is b means a and b are the exact same thing, i.e. references to the same entity in memory. So a and b would have to be the exact same class, not subclasses, as with isinstance(). See for example https://mcmap.net/q/37456/-is-there-a-difference-between-quot-quot-and-quot-is-quotCarilyn
@JonCoombs According to the rationale of PEP 622, isinstance() is the second most called builtin function, after len(). I think we have to accept that isinstance is de facto canonical Python.Davao
@JonCoombs, I realise this is a long time coming, but I've recently had a need in Python to do exactly that. It's a neat way to prevent instantiation of base classes (have the dunder-new method throw an exception if the class type being allocated is the base class). There may be another way to do it with the ABC stuff but I'm in a hurry :-)Unfrequented
@paxdiablo: Yep, inheriting from ABC and defining at least one @abstractmethod is the way to do this for most use cases (where preventing instantiation of the base class is because you know it lacks necessary functionality that subclasses must implement). Regardless, Jon Coombs is right, you shouldn't usually do this. There are cases where it's needed (type-checking arguments to __init__ can be good, to establish invariants for attributes, rather than having things fail long after the mistake where the wrong types were passed), but most of the time, duck-typing is the way to go.Unrestrained
C
271

The most Pythonic way to check the type of an object is... not to check it.

Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!

Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.

Cutwork answered 30/9, 2008 at 17:40 Comment(26)
IMHO, the most Pythonic way is to cope with whatever argument which is given. In my code I often cannot know if I recieve an object or an array of objects, and I use type-checking internally to convert a single object to a one-element list.Kneedeep
Rather then just trying to use its write method there are times when you want to do this without causing an exception. In this case you could do... if hasattr(ob, "write") and callable(ob.write): Or save some dict access... func = getattr(ob, "write", None) if callable(func): ...Ensiform
Duck typing is about using an library. Type checking is about writing an library. Not the same problem domain.Chewink
So you say it is wrong to have a function that accepts both a string and a list of strings?Inferential
@RickyA, I disagree. Duck typing is about interacting with objects using interfaces with well-known semantics. This can apply either to library code or to the code that uses such a library.Cutwork
@tohecz, I don't think it's wrong, but if you have a way to treat objects more generically rather than check their type explicitly, then your code may be more generically applicable. I generally agree with @sastanin's approach for the kind of commonly-used convenience function which may either take a single item or a list of them: list_OF_strings = [list_OR_string] if isinstance(list_OR_string, basestring) else list_OR_string.Cutwork
@Ensiform Note that hasattr ignores all exceptions, including KeyboardInterrupt and similar. You should use getattr(obj, attr, None).Arbalest
@nyuszika7h, In Python3 hasattr only supresses an AttributeError - See: docs.python.org/3.4/library/functions.html#hasattrEnsiform
I'm confused by the suggestion. Right now I'm writing code that simulates algebraic expressions and I want to search the expression tree for any two numbers that can be summed, as one step in the process of simplification. How would you search an expression tree for two numbers that can be added without testing their types?Lafollette
@Addem: If the case where they're likely to be addable is common, just try it! try: a + b except TypeError: something_appropriate. If you're doing a type-check on the numbers you are fairly likely to miss some, as there's a lot of ways of storing numbers that doesn't subclass the base number classes.Conjunction
"The most Pythonic way to check the type of an object is... not to check it." This does not help at all when I am trying to debug my code...Crenation
Duck typing is not a form of abstraction (referring to answer). Since it avoids actual typing (typing is an abstraction) and deals with concrete implementations - like "does this method exist" or maybe more fitting "Does my nuclear power plan blow up or turn on the fans if I run powerplant.blow()" (who knows :))Scrivner
What if I pass an object that has the same method but returns something different? It will pass the try but will have an unexpected behavior.Putty
@Kneedeep I do not agree with you. Python is generally a strong typed language, so a function should NOT cope with whatever type it gets. If you expect an int, just try to use it as an int. It will be fine if you get a bool because that is a subclass of int. But don't use type checking to detect a str and convert it in that case. Using a str like an int will most likely fail. That's OK and what the user expects.Discourteous
@RodrigoE.Principe: sounds like a method hijacking a parent-class's signature. Can you provide an example? Anyway, that's why static type checking was introduced.Broeker
As well as mentioning try...except, you should also say that the except should not be a naked except, it should always specify the specific named exception(s) that could occur if the object's type was wrong e.g. except TypeError, KeyError, UserDefinedYachtError:. It should not implicitly catch other exceptions: MemoryError, OSError etc., especially dangerous ones. Naked except considered badBroeker
Writing API with that philosophy is hurtful. I prefer to type check for integer/str, as a matter of fact it's necessary even in API developmentTelegony
The try ... except pattern isn't going to do any good when the result is "wrong" for your use-case but doesn't raise an exception. For example, given a list of mixed types, you may want to call json.dumps only on the dicts in that list before passing the result to a csv writer because of what ends up happening with quoting in the output.Halden
@JacobLee: Sure. Did you reach the last paragraph of the answer? There's no one answer; it's best to use duck-typing if you can without causing other problems. When you can't, there's isinstance.Unrestrained
It's 2022. Things have changed since this answer was submitted. It's widely accepted that programming with types has many benefits.Hawkbill
Basically what @Ricky A. said, but a concrete example. If my custom object accepts dates, it's really important to know whether the date passed to it during initialization is a str or a datetime.date object. You can generally create a datetime.date object from a str, so you could still work with it, but you'd need to know it wasn't a datetime.date object first.Countrybred
A str could be anything: some could be parsed as dates, but others can't. If the purpose of the function is to operate on dates, let the caller deal with converting a particular str value to a datetime.date first (and any errors that might arise in the process) and provide your function with the resulting value.Piliform
somtimes you need isinstance for @overload-ed functionsAssuntaassur
@Kneedeep you know for your purpose, there's more_itertools.always_iterable()? A great library for similar stuff as well!Doorman
@Telegony if you write an external API (processing user or external input), I'd recommend pydantic. If you're writing a python API, I'd recommend to either indulge more into the Python philosophy and learn it's ways or use another language. I think it's better to switch language than to pursue a lonely fight against base idioms.Doorman
There are times when duck typing is beneficial. And then there are those times it is absolutely not beneficial. Even if python supports it, doesn't mean it's always beneficial to use duck typing, even in python. Using duck typing in the wrong place may lead to unforeseeable behavior, for example because the provided type only partially implements the asked features or implements the right methods with wrong meaning. To avoid such confusion it is best to type check in those cases.Salpiglossis
B
82

isinstance(o, str) will return True if o is an str or is of a type that inherits from str.

type(o) is str will return True if and only if o is a str. It will return False if o is of a type that inherits from str.

Baranowski answered 30/9, 2008 at 11:5 Comment(2)
Of course, this will fail if the object is not an instance of 'str', but of something string-like instead. Like unicode, mmap, UserString or any other user-defined type. The usual approach in Python is not to do typechecks.Lesley
This is very helpful. Because the difference between isinstance and type(var) == type('') is not clear.Kneedeep
B
57

In Python 3.10, you can use | in isinstance:

>>> isinstance(1223, int | str) 
True

>>> isinstance('abcd', int | str) 
True
Bindle answered 20/6, 2021 at 5:1 Comment(2)
One of the great things in python is that it avoids having random symbols all over the code. Unfortunately that property is slowly disappearing over time.Louvenialouver
Surely the example should actually use an integer in order to demonstrate the functionality?Puparium
C
45

After the question was asked and answered, type hints were added to Python. Type hints in Python allow types to be checked but in a very different way from statically typed languages. Type hints in Python associate the expected types of arguments with functions as runtime accessible data associated with functions and this allows for types to be checked. Example of type hint syntax:

def foo(i: int):
    return i

foo(5)
foo('oops')

In this case we want an error to be triggered for foo('oops') since the annotated type of the argument is int. The added type hint does not cause an error to occur when the script is run normally. However, it adds attributes to the function describing the expected types that other programs can query and use to check for type errors.

One of these other programs that can be used to find the type error is mypy:

mypy script.py
script.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "int"

(You might need to install mypy from your package manager. I don't think it comes with CPython but seems to have some level of "officialness".)

Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly list type or is anything iterable sufficient?).

The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate.

Python's type hints are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution.

The typing package offers type variables that can be used in type hints to express needed behaviors without requiring particular types. For example, it includes variables such as Iterable and Callable for hints to specify the need for any type with those behaviors.

While type hints are the most Pythonic way to check types, it's often even more Pythonic to not check types at all and rely on duck typing. Type hints are relatively new and the jury is still out on when they're the most Pythonic solution. A relatively uncontroversial but very general comparison: Type hints provide a form of documentation that can be enforced, allow code to generate earlier and easier to understand errors, can catch errors that duck typing can't, and can be checked statically (in an unusual sense but it's still outside of runtime). On the other hand, duck typing has been the Pythonic way for a long time, doesn't impose the cognitive overhead of static typing, is less verbose, and will accept all viable types and then some.

Craiova answered 6/5, 2016 at 16:12 Comment(4)
-1: mypy specifically calls itself a "static type checker" so I'm not sure where you got "type checking must be done at runtime" from.Hypothec
@Hypothec In retrospect, that was an unnecessary digression, but to get into it more, Python's type hints are turned into runtime data and mypy is a Python module that uses importlib to access that data. Whether this is "static type checking" is a philosophical question but it's different from what most would expect since the normal language interpreter and import machinery are involved.Craiova
That is not true either. It uses typed_ast, which itself is just a clone of ast with extra features. ast does not import modules; it parses them into an abstract syntax tree.Hypothec
Might be worthwhile to checkout the pure python type checker: type_enforced: pypi.org/project/type-enforcedSalesclerk
P
16
isinstance(o, str)

Link to docs

Precipitation answered 30/9, 2008 at 11:1 Comment(1)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.Turves
L
14

You can check for type of a variable using __name__ of a type.

Ex:

>>> a = [1,2,3,4]  
>>> b = 1  
>>> type(a).__name__
'list'
>>> type(a).__name__ == 'list'
True
>>> type(b).__name__ == 'list'
False
>>> type(b).__name__
'int'
Labelle answered 18/7, 2019 at 17:23 Comment(5)
That's a terrible way of checking the type of something. I can create a random class with the name I want, and it will pass your tests. It's even worse than duck-typing.Cyrie
This is such a terrible solution and it is a shame its rating is still in the positive. There already is the isinstance check and you should use it.Gabelle
The only conceivable case where this is even a quasi-reasonable solution is during live development, where you're constant reloading a module and want instances of classes made before the reload to still be detected as the same thing as instances made after the reload (you want the test to be wrong; they're not the same class, but you're pretending they're close). But it's terrible in every other context.Unrestrained
Thanks! This is exactly what I was looking for. In my code, I'm checking for a class type before the class it's defined. So, using its name seems to be the only viable way to avoid duck-typing. I'm glad this solution rating is positive.Eloiseloisa
@Atcold: If the class hasn't been defined, there are no objects of that type.Cunaxa
K
9

For more complex type validations I like typeguard's approach of validating based on python type hint annotations:

from typeguard import check_type
from typing import List

try:
    check_type('mylist', [1, 2], List[int])
except TypeError as e:
    print(e)

You can perform very complex validations in very clean and readable fashion.

check_type('foo', [1, 3.14], List[Union[int, float]])
# vs
isinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) 
Kasiekask answered 16/2, 2019 at 7:6 Comment(0)
E
7

I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that.

I would just call the required methods on your object and catch an AttributeError. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.

I've used this a lot when getting data off the web with urllib2.urlopen() which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because it implements the same read() method as a real file.

But I'm sure there is a time and place for using isinstance(), otherwise it probably wouldn't be there :)

Executioner answered 30/9, 2008 at 13:33 Comment(1)
A good example of when you must use it is if you are parsing a dynamic json object. You don't know ahead of time if a field is a string or a dictionary.Tiberius
R
7

The accepted answer answers the question in that it provides the answers to the asked questions.

Q: What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?

A: Use isinstance, issubclass, type to check based on types.

As other answers and comments are quick to point out however, there's a lot more to the idea of "type-checking" than that in python. Since the addition of Python 3 and type hints, much has changed as well. Below, I go over some of the difficulties with type checking, duck typing, and exception handling. For those that think type checking isn't what is needed (it usually isn't, but we're here), I also point out how type hints can be used instead.

Type Checking

Type checking is not always an appropriate thing to do in python. Consider the following example:

def sum(nums):
    """Expect an iterable of integers and return the sum."""
    result = 0
    for n in nums:
        result += n
    return result

To check if the input is an iterable of integers, we run into a major issue. The only way to check if every element is an integer would be to loop through to check each element. But if we loop through the entire iterator, then there will be nothing left for intended code. We have two options in this kind of situation.

  1. Check as we loop.

  2. Check beforehand but store everything as we check.

Option 1 has the downside of complicating our code, especially if we need to perform similar checks in many places. It forces us to move type checking from the top of the function to everywhere we use the iterable in our code.

Option 2 has the obvious downside that it destroys the entire purpose of iterators. The entire point is to not store the data because we shouldn't need to.

One might also think that checking if checking all of the elements is too much then perhaps we can just check if the input itself is of the type iterable, but there isn't actually any iterable base class. Any type implementing __iter__ is iterable.

Exception Handling and Duck Typing

An alternative approach would be to forgo type checking altogether and focus on exception handling and duck typing instead. That is to say, wrap your code in a try-except block and catch any errors that occur. Alternatively, don't do anything and let exceptions rise naturally from your code.

Here's one way to go about catching an exception.

def sum(nums):
    """Try to catch exceptions?"""
    try:
        result = 0
        for n in nums:
            result += n
        return result
    except TypeError as e:
        print(e)

Compared to the options before, this is certainly better. We're checking as we run the code. If there's a TypeError anywhere, we'll know. We don't have to place a check everywhere that we loop through the input. And we don't have to store the input as we iterate over it.

Furthermore, this approach enables duck typing. Rather than checking for specific types, we have moved to checking for specific behaviors and look for when the input fails to behave as expected (in this case, looping through nums and being able to add n).

However, the exact reasons which make exception handling nice can also be their downfall.

  1. A float isn't an int, but it satisfies the behavioral requirements to work.

  2. It is also bad practice to wrap the entire code with a try-except block.

At first these may not seem like issues, but here's some reasons that may change your mind.

  1. A user can no longer expect our function to return an int as intended. This may break code elsewhere.

  2. Since exceptions can come from a wide variety of sources, using the try-except on the whole code block may end up catching exceptions you didn't intend to. We only wanted to check if nums was iterable and had integer elements.

  3. Ideally we'd like to catch exceptions our code generators and raise, in their place, more informative exceptions. It's not fun when an exception is raised from someone else's code with no explanation other than a line you didn't write and that some TypeError occured.

In order to fix the exception handling in response to the above points, our code would then become this... abomination.

def sum(nums):
    """
    Try to catch all of our exceptions only.
    Re-raise them with more specific details.
    """
    result = 0

    try:
        iter(nums)
    except TypeError as e:
        raise TypeError("nums must be iterable")

    for n in nums:
        try:
            result += int(n)
        except TypeError as e:
            raise TypeError("stopped mid iteration since a non-integer was found")

    return result

You can kinda see where this is going. The more we try to "properly" check things, the worse our code is looking. Compared to the original code, this isn't readable at all.

We could argue perhaps this is a bit extreme. But on the other hand, this is only a very simple example. In practice, your code is probably much more complicated than this.

Type Hints

We've seen what happens when we try to modify our small example to "enable type checking". Rather than focusing on trying to force specific types, type hinting allows for a way to make types clear to users.

from typing import Iterable

def sum(nums: Iterable[int]) -> int:
    result = 0
    for n in nums:
        result += n
    return result

Here are some advantages to using type-hints.

  • The code actually looks good now!

  • Static type analysis may be performed by your editor if you use type hints!

  • They are stored on the function/class, making them dynamically usable e.g. typeguard and dataclasses.

  • They show up for functions when using help(...).

  • No need to sanity check if your input type is right based on a description or worse lack thereof.

  • You can "type" hint based on structure e.g. "does it have this attribute?" without requiring subclassing by the user.

The downside to type hinting?

  • Type hints are nothing more than syntax and special text on their own. It isn't the same as type checking.

In other words, it doesn't actually answer the question because it doesn't provide type checking. Regardless, however, if you are here for type checking, then you should be type hinting as well. Of course, if you've come to the conclusion that type checking isn't actually necessary but you want some semblance of typing, then type hints are for you.

Romanticize answered 9/5, 2021 at 21:18 Comment(1)
Using result += int(n) risks silent data loss. If n is a float, it'll be silently truncated (e.g. 2.5 would become 2). I strongly suggest using operator.index in place of int when you want this sort of semi-duck-typing solution; it will accept int, and anything which type which can, for all possible values, be losslessly converted to int (e.g. a numpy.int32 scalar, but not float or str).Unrestrained
T
6

To Hugo:

You probably mean list rather than array, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.

Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all

try:
   my_sequence.extend(o)
except TypeError:
  my_sequence.append(o)

One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.

I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ] around your single value when you pass it in if need be.

(Though this can cause errors with strings, as they do look like (are) sequences.)

Trappist answered 1/8, 2012 at 16:7 Comment(0)
R
2

If you have to check for the type of str or int please use instanceof. As already mentioned by others the explanation is to also include sub classes. One important example for sub classes from my perspective are Enums with data type like IntEnum or StrEnum. Which are a pretty nice way to define related constants. However, it is kind of annoying if libraries do not accept those as such types.

Example:

import enum

class MyEnum(str, enum.Enum):
    A = "a"
    B = "b"

print(f"is string: {isinstance(MyEnum.A, str)}")   # True
print(f"is string: {type(MyEnum.A) == str}")       # False!!!
print(f"is string: {type(MyEnum.A.value) == str}") # True
Raving answered 15/2, 2023 at 21:56 Comment(0)
S
2

Checking a float-like type with

isinstance(x, float)

or

type(x) is float

will return False if the type is not exactly a float, but, for example, a numpy.float32:

import pandas as pd
import numpy as np
x = pd.Series([0.2], dtype=np.float32)[0]

As pointed out in a comment of this thread, numpy's issubdtype can be used for this purpose.

To detect float-like types:

np.issubdtype(type(x), np.floating)
  • returns True for 2.0, pd.Series([2.0], dtype=np.float32)[0], and generally any float, np.float32, np.float64, ... type
  • returns False for 2, "2.0" (string), [2.0, 1.2] (list), and the like

To detect numeric (float- and int-like) types:

np.issubdtype(type(x), np.number)
  • returns True for 2, 2.0, pd.Series([2.0], dtype=np.float32)[0], pd.Series([2.0], dtype=np.int32)[0], and generally any float, np.float32, np.float64, ... type
  • returns False for "2" (string), [2.0, 1.2] (list) and the like

To detect pd.Index-like types:

np.issubdtype(type(x), pd.Index)
  • returns True for pd.Index, pd.Int64Index, pd.Float64Index, ...
Sukkoth answered 15/3 at 14:50 Comment(1)
In general please avoid adding new answers to old questions with multiple existing answers unless you are really really sure you're adding something both new and valuable, but in this case given the ubiquity of numpy and the multiplicity of number types I think this does add value. +1Superannuated
T
1

To check if an object is of a given type or if it inherits from a given type, you can use the isinstance() function. Here's how you can check if an object o is of type str:

o = "Hello, world!"

if isinstance(o, str):
    print("The object is of type str.")
else:
    print("The object is not of type str.")
Trixy answered 30/5, 2023 at 20:12 Comment(1)
this answer was already given above many years agoAssuntaassur
E
1

Python 3.10 introduced a new way to check for type that's often cleaner than if/instanceof(): the match statement. It can check for many types:

float(x) # Is it a floating point?
str(x)   # Is it a string?
int(x)   # Is it an integer?
...

For example, here's how you can handle some function that returns a variety of types, that each need to be handled differently:

def read_user_input() -> float | str | None:
    ...

# Get user input, rounding floats to 2 decimal places.
def user_input() -> str:
    match read_user_input()
        case float(a_number):
            n = str(round(2, a_number))
        case str(a_string):
            n = return str(round(2, float(a_string.strip())))
        case None:
            n = "(No input given)"

    return n

Bonus: When you check for type this way, type checkers can verify that that the match is exhaustive; that you've handled every possible type that you function will give you.

Extemporize answered 30/12, 2023 at 21:57 Comment(0)
P
0

In Python, you can use the built-in isinstance() function to check if an object is of a given type, or if it inherits from a given type.

To check if the object o is of type str, you would use the following code:

if isinstance(o, str):
# o is of type str

You can also use type() function to check the object type.

if type(o) == str:
# o is of type str

You can also check if the object is a sub class of a particular class using issubclass() function.

if issubclass(type(o),str):
# o is sub class of str
Polybasite answered 26/1, 2023 at 16:34 Comment(1)
Please read How to Answer, and check existing answers before contributing another answer to a question. All of this material is thoroughly covered already.Puparium
S
0

you can use the try and except statements to check the type with str,int,bool or float function to try and see if it's a valid type.

Basically in this example code, your trying to see if the variable 'string' is an integer which is not, so we can do something if there's an error.

string = 'h'

try:
    int(string)
except:
    print('the string variable is not an integer.')
Steffens answered 12/4 at 11:57 Comment(0)
R
-5

A simple way to check type is to compare it with something whose type you know.

>>> a  = 1
>>> type(a) == type(1)
True
>>> b = 'abc'
>>> type(b) == type('')
True
Rutty answered 31/5, 2020 at 20:42 Comment(0)
W
-14

I think the best way is to typing well your variables. You can do this by using the "typing" library.

Example:

from typing import NewType
UserId = NewType ('UserId', int)
some_id = UserId (524313`)

See https://docs.python.org/3/library/typing.html.

Wenonawenonah answered 24/12, 2019 at 9:21 Comment(1)
But you didn't demonstrate a check anywhere, did you? If you did, can you please explain where you're checking for the type in the code you have given?Knobby

© 2022 - 2024 — McMap. All rights reserved.