Comparing types

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 17 03:38:18 EST 2013


Jason Friedman wrote:

> I want to tell whether an object is a regular expression pattern.
> 
> Python 3.2.3 (default, Oct 19 2012, 20:10:41)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import re
>>>> s = "hello"
>>>> type(s)
> <class 'str'>
>>>> isinstance(s, str)
> True
>>>> my_pattern = re.compile(s)
>>>> type(my_pattern)
> <class '_sre.SRE_Pattern'>
>>>> isinstance(my_pattern, _sre.SRE_Pattern)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name '_sre' is not defined


Here are two ways to do this. The first is not portable, and is not
guaranteed to work, since the _sre module is private.


# Risky but obvious.
import _sre
isinstance(my_pattern, _sre.SRE_Pattern)


The second is guaranteed to work even if the _sre module disappears, is
renamed, or otherwise changes in any way.


# Safe.
PatternType = type(re.compile("."))
isinstance(my_pattern, PatternType)




-- 
Steven




More information about the Python-list mailing list