code: def sub(pattern, repl, string, *args, **kwargs):
      
  
      flags = args[4] if len(args) > 4 else kwargs.get('flags', 0)
      is_replace = _is_replace(repl)
      is_string = isinstance(repl, (str, bytes))
      if is_replace and repl.use_format:
          raise ValueError("Compiled replace cannot be a format object!")
  
      pattern = compile_search(pattern, flags)
      return _re.sub(
          pattern, (compile_replace(pattern, repl) if is_replace or is_string else repl), string, *args, **kwargs
      )
docs: Apply `sub` after applying backrefs.