2017年9月27日 星期三

[ Python 常見問題 ] Detect re (regexp) object in Python

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: 
>>> import re 
>>> rex = re.compile('') 
>>> rex 
<_sre .sre_pattern="" 0x7f63db414390="" at="" object="">


How-To 
re._pattern_type exists, and appears to do what you want: 
>>> isinstance(re.compile(''), re._pattern_type) 
True

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: 
>>> isinstance(re.compile('test'), type(re.compile('test'))) 
True 
>>> isinstance('test', type(re.compile('test'))) 
False

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: 
  1. try:  
  2.      rex.match(my_string)  
  3. except AttributeError:  
  4.      # rex is not an re  
  5. else:  
  6.      # rex is an re  
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): 
>>> ptn = re.compile('test') 
>>> str = 'string' 
>>> hasattr(ptn, 'match') and callable(ptn.match) // If object 'ptn' has attribute 'match' and it is callable 
True 
>>> hasattr(str, 'match') and callable(str.match) 
False


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...