def _find_and_cache_best_function(self, dispatch_type):
result = self._dispatch_table.get(dispatch_type)<EOL>if result:<EOL><INDENT>return result<EOL><DEDENT>with self._write_lock:<EOL><INDENT>try:<EOL><INDENT>dispatch_mro = dispatch_type.mro()<EOL><DEDENT>except TypeError:<EOL><INDENT>dispatch_mro = ()<EOL><DEDENT>best_match = None<EOL>result_type = None<EOL>for candidate_type, candidate_func in self.implementations:<EOL><INDENT>if not issubclass(dispatch_type, candidate_type):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>match = dispatch_mro.index(candidate_type)<EOL><DEDENT>except ValueError:<EOL><INDENT>match = None<EOL><DEDENT>if best_match is None:<EOL><INDENT>if result and match is None:<EOL><INDENT>if self._preferred(candidate_type, over=result_type):<EOL><INDENT>result = candidate_func<EOL>result_type = candidate_type<EOL><DEDENT>elif self._preferred(result_type, over=candidate_type):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(self.func_name, dispatch_type))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = candidate_func<EOL>result_type = candidate_type<EOL>best_match = match<EOL><DEDENT><DEDENT>if (match or <NUM_LIT:0>) < (best_match or <NUM_LIT:0>):<EOL><INDENT>result = candidate_func<EOL>result_type = candidate_type<EOL>best_match = match<EOL><DEDENT><DEDENT>self._dispatch_table[dispatch_type] = result<EOL>return result<EOL><DEDENT>
Finds the best implementation of this function given a type.

        This function caches the result, and uses locking for thread safety.

        Returns:
            Implementing function, in below order of preference:
            1. Explicitly registered implementations (through
               multimethod.implement) for types that 'dispatch_type' either is
               or inherits from directly.
            2. Explicitly registered implementations accepting an abstract type
               (interface) in which dispatch_type participates (through
               abstract_type.register() or the convenience methods).
            3. Default behavior of the multimethod function. This will usually
               raise a NotImplementedError, by convention.

        Raises:
            TypeError: If two implementing functions are registered for
                different abstract types, and 'dispatch_type' participates in
                both, and no order of preference was specified using
                prefer_type.