Source From Here
Question
I wonder what is the proper pythonic backward- and forward-compatible method how check if an object is compiled re object. isinstance method cannot be easily used, while the resulting object claims to be _sre.SRE_Patternobject:
How-To
re._pattern_type exists, and appears to do what you want:
But this is not a good idea - per Python convention, names starting with _ are not part of the public API of a module and not part of the backward compatibility guarantees. So, using type(re.compile('')) is your best bet:
Though notice that this isn't guaranteed to work either, since the re module makes no mention of the object returned from re.compile() being of any particular class. And indeed, even if this was guaranteed, the most Pythonic and back- and forward- compatible way would be to rely on the interface, rather than the type. In other words, embracing duck typing and EAFP (It’s Easier to Ask Forgiveness than Permission), do something like this:
Or another useful approach given you only care about using function 'match' (
If a animal make sound of quack, it is possibly a duck...:p):
Question
I wonder what is the proper pythonic backward- and forward-compatible method how check if an object is compiled re object. isinstance method cannot be easily used, while the resulting object claims to be _sre.SRE_Patternobject:
How-To
re._pattern_type exists, and appears to do what you want:
But this is not a good idea - per Python convention, names starting with _ are not part of the public API of a module and not part of the backward compatibility guarantees. So, using type(re.compile('')) is your best bet:
Though notice that this isn't guaranteed to work either, since the re module makes no mention of the object returned from re.compile() being of any particular class. And indeed, even if this was guaranteed, the most Pythonic and back- and forward- compatible way would be to rely on the interface, rather than the type. In other words, embracing duck typing and EAFP (It’s Easier to Ask Forgiveness than Permission), do something like this:
- try:
- rex.match(my_string)
- except AttributeError:
- # rex is not an re
- else:
- # rex is an re
沒有留言:
張貼留言