Repository: kedro-org/kedro
File: kedro/io/data_catalog.py (Python)

Code before:

                # Flag to turn on/off fuzzy-matching which can be time consuming and
                # slow down plugins like `kedro-viz`
                if suggest:
                    matches = difflib.get_close_matches(
                        data_set_name, self._data_sets.keys()
                    )
                    if matches:
                        suggestions = ", ".join(matches)
                        error_msg += (
                            f" - did you mean one of these instead: {suggestions}"
                        )

                raise DataSetNotFoundError(error_msg)

        data_set = self._data_sets[data_set_name]
        if version and isinstance(data_set, AbstractVersionedDataSet):
            # we only want to return a similar-looking dataset,
            # not modify the one stored in the current catalog
            data_set = data_set._copy(  # pylint: disable=protected-access
                _version=version
            )

        return data_set

    def _resolve_dataset(
        self, dataset_name: str, matched_pattern: str
    ) -> AbstractDataSet:
        """Get resolved AbstractDataSet from a factory config"""
        result = parse(matched_pattern, dataset_name)
        template_copy = copy.deepcopy(self.dataset_patterns[matched_pattern])
        # Resolve the factory config for the dataset
        for key, value in template_copy.items():
            if isinstance(value, Iterable) and "}" in value:
                string_value = str(value)
                # result.named: gives access to all dict items in the match result.
                # format_map fills in dict values into a string with {...} placeholders
                # of the same key name.
                try:
                    template_copy[key] = string_value.format_map(result.named)
                except KeyError as exc:
                    raise DataSetError(
                        f"Unable to resolve '{key}' for the pattern '{matched_pattern}'"
                    ) from exc
        # Create dataset from catalog template.
        return AbstractDataSet.from_config(dataset_name, template_copy)

    def load(self, name: str, version: str = None) -> Any:
        """Loads a registered data set.

        Args:

Review comment (bug):
I think this definitely conflicts with `_suggest_resume_scenario`, can you try to test with a fail pipeline and see if it breaks it?

Code after:
        3. Alphabetically
        """
        sorted_keys = sorted(
            data_set_patterns,
            key=lambda pattern: (
                -(cls._specificity(pattern)),
                -pattern.count("{"),
                pattern,
            ),
        )
        sorted_patterns = {}
        for key in sorted_keys:
            sorted_patterns[key] = data_set_patterns[key]
        return sorted_patterns

    @staticmethod
    def _specificity(pattern: str) -> int:
        """Helper function to check the length of exactly matched characters not inside brackets
        Example -
        specificity("{namespace}.companies") = 10
        specificity("{namespace}.{dataset}") = 1
        specificity("france.companies") = 16
        """
        # Remove all the placeholders from the pattern and count the number of remaining chars
        result = re.sub(r"\{.*?\}", "", pattern)
        return len(result)

    def _get_dataset(
        self, data_set_name: str, version: Version = None, suggest: bool = True
    ) -> AbstractDataSet:
        matched_pattern = self._match_pattern(self._dataset_patterns, data_set_name)
        if data_set_name not in self._data_sets and matched_pattern:
            # If the dataset is a patterned dataset, materialise it and add it to
            # the catalog
            data_set_config = self._resolve_config(data_set_name, matched_pattern)
            ds_layer = data_set_config.pop("layer", None)
            if ds_layer:
                self.layers = self.layers or {}
                self.layers.setdefault(ds_layer, set()).add(data_set_name)
            data_set = AbstractDataSet.from_config(
                data_set_name,
                data_set_config,
                self._load_versions.get(data_set_name),
                self._save_version,
            )
            if self._specificity(matched_pattern) == 0:
                self._logger.warning(
                    "Config from the dataset factory pattern '%s' in the catalog will be used to "
                    "override the default MemoryDataset creation for the dataset '%s'",
                    matched_pattern,
                    data_set_name,