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)):
Answer from Fredrik Johansson on Stack OverflowI'm doing a tutorial right now and they use it in multiple classes and I have no idea what it does for the program.
I've tried looking through the documentation, but it hasn't helped much and I can't find anyone talking about what it does.
Sorry if this is an googleable question, but maybe I've just been searching the wrong thing. All I can find is general type checking help instead of this specific function or library. Generally when it's used they'll import TYPE_CHECKING from typing and then use it like:
if TYPE_CHECKING:
# import from another file here
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)):
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.
Why if TYPE_CHECKING?
python - How does mypy use typing.TYPE_CHECKING to resolve the circular import annotation problem? - Stack Overflow
TYPE_CHECKING only imports should trigger errors on non-annotation usage
How to use type checking dynamically
I have a set of classes and functions that perform analysis on pandas series. It is meant to be able to plug in new analysis, that takes a dictionary of "required" pre-computed values, and each analysis "provides" a dictionary. This way I don't ahve to recompute the same values over and over... and I can arrange the analysis objects into a DAG, I can also tell before execution if there are required values that aren't provided.
class SometimesProvides(ColAnalysis):
provides_defaults = {'conditional_on_dtype':'xcvz'}
requires_summary = []
@staticmethod
def series_summary(ser, _sample_ser):
import pandas as pd
is_numeric = pd.api.types.is_numeric_dtype(ser)
if is_numeric:
return dict(conditional_on_dtype=True)
return {}
class DumbTableHints(ColAnalysis):
provides_defaults = {
'is_numeric':False, 'is_integer':False, 'histogram':[]}
requires_summary = ['conditional_on_dtype']
@staticmethod
def computed_summary(summary_dict):
return {'is_numeric':True,
'is_integer': summary_dict['conditional_on_dtype'],
'histogram': []}
sdf3, errs = produce_series_df(
test_df, order_analysis(DumbTableHints, SometimesProvides))That's a bit of a contrived example, but it should be enough to understand.
I understand how I can provide hinting for SometimesProvides.provides_defaults, and how I could verify that SometimesProvides.series_summary returns that type.
I don't know how, at runtime I can get a typing system to verify that the type of summary_dict going to DumbTableHints.summary_dict is as expected for that function.
This is all meant to be used interactively in the Jupyter notebook. So even if I could do this with mypy statically, that still wouldn't solve my problem. Also I think that the error messages from some Generic typing construction would be very hard to read in that case.
How would you all approach this?
There are five major type checkers for Python users: Mypy (PSF?), Pyright (Microsoft), Pyre (Meta), Pytype (Google) and the built-in type checker of PyCharm (JetBrains).
According to pypistats.org, Mypy is the most downloaded last month and most popular overall:
-
Mypy: 20.4M
-
Pyright: 1.5M, albeit just a CLI wrapper.
-
Pytype: 632K
-
Pyre: 600, and this is not a typo. I guess it is just installed indirectly?
These stats may not reflect the actual usage. I have no experience with Pyre and Pytype and have rarely, if ever, seen anyone using these two. For VSCode users, the go-to extension is Pylance, which ships with Pyright and has 84M installs thus far. Among the two Mypy competitors of it, one is made by Microsoft (127K installs) and one independent (172K installs). The Python Developer Survey 2022 by JetBrains shows that the number of users who use PyCharm as their primary IDE for Python programming is 29%, second only to VSCode (37%). The annual report of the same year says JetBrains have 15.9M users, but the number of PyCharm users or downloads are not mentioned. One popular and currently the only working Mypy plugin has mixed reviews.
Personally, I think Pyright is the best type checker. It has support for latest feature, doesn't choke on WIP code and the maintainers are very responsive. Mypy is not as good, but is quite decent. On the contrary, PyCharm's type checker has many major problems. It is either too lenient or just fails to infer the right types most of the times.
PyCharm users, how do you or your team type check your code? Do you use one or multiple of the first four type checkers? If so, is it via the CLI or a plugin? Do you just use whatever people around you use? Or do you don't care about type hinting at all?