Type of compiled regex object in python

后端 未结 10 1071
一个人的身影
一个人的身影 2020-11-30 07:14

What is the type of the compiled regular expression in python?

In particular, I want to evaluate

isinstance(re.compile(\'\'), ???)

10条回答
  •  隐瞒了意图╮
    2020-11-30 07:47

    As an illustration of polymorphism, an alternate solution is to create wrapper classes which implement a common method.

    class Stringish (str):
        def matches (self, input):
            return self == input
    
    class Regexish (re):
        def matches (self, input):
            return self.match(input)
    

    Now your code can iterate over a list of alloweds containing objects instantiating either of these two classes completely transparently:

    for allowed in alloweds:
        if allowed.matches(input):
            ignored = False
            break
    

    Notice also how some code duplication goes away (though your original code could have been refactored to fix that separately).

提交回复
热议问题