Find the definition of an object within a source closest to a given line

def get_definition_with_regex(source, token, start_line=-1):
    """
    Find the definition of an object within a source closest to a given line
    """
    if not token:
        return None
    if DEBUG_EDITOR:
        t0 = time.time()
    patterns = [  # python / cython keyword definitions
                r'^c?import.*\W{0}{1}',
                r'from.*\W{0}\W.*c?import ',
                r'from .* c?import.*\W{0}{1}',
                r'class\s*{0}{1}',
                r'c?p?def[^=]*\W{0}{1}',
                r'cdef.*\[.*\].*\W{0}{1}',
                # enaml keyword definitions
                r'enamldef.*\W{0}{1}',
                r'attr.*\W{0}{1}',
                r'event.*\W{0}{1}',
                r'id\s*:.*\W{0}{1}']

    matches = get_matches(patterns, source, token, start_line)

    if not matches:
        patterns = [r'.*\Wself.{0}{1}[^=!<>]*=[^=]',
                    r'.*\W{0}{1}[^=!<>]*=[^=]',
                    r'self.{0}{1}[^=!<>]*=[^=]',
                    r'{0}{1}[^=!<>]*=[^=]']
        matches = get_matches(patterns, source, token, start_line)
    # find the one closest to the start line (prefer before the start line)
    if matches:
        min_dist = len(source.splitlines())
        best_ind = 0
        for match in matches:
            dist = abs(start_line - match)
            if match <= start_line or not best_ind:
                if dist < min_dist:
                    min_dist = dist
                    best_ind = match
    if matches:
        if DEBUG_EDITOR:
            log_dt(LOG_FILENAME, 'regex definition match', t0)
        return best_ind
    else:
        if DEBUG_EDITOR:
            log_dt(LOG_FILENAME, 'regex definition failed match', t0)
        return None