|
3 | 3 | return [value for value in cls.__dict__.values() if isinstance(value, cls)] |
4 | 4 |
|
5 | 5 | @classmethod |
6 | | - def by_name(cls, name): |
| 6 | + def by_name( |
| 7 | + cls, |
| 8 | + name: str, |
| 9 | + match: str = "equals", |
| 10 | + all: bool = False, |
| 11 | + ): |
| 12 | + """ |
| 13 | + Search for instances in the openMINDS instance library based on their name. |
| 14 | + |
| 15 | + This includes properties "name", "lookup_label", "family_name", "full_name", "short_name", "abbreviation", and "synonyms". |
| 16 | + |
| 17 | + Note that not all metadata classes have a name. |
| 18 | + |
| 19 | + Args: |
| 20 | + name (str): a string to search for. |
| 21 | + match (str, optional): either "equals" (exact match - default) or "contains". |
| 22 | + all (bool, optional): Whether to return all objects that match the name, or only the first. Defaults to False. |
| 23 | + """ |
| 24 | + namelike_properties = ("name", "lookup_label", "family_name", "full_name", "short_name", "abbreviation") |
7 | 25 | if cls._instance_lookup is None: |
8 | 26 | cls._instance_lookup = {} |
9 | 27 | for instance in cls.instances(): |
10 | | - cls._instance_lookup[instance.name] = instance |
11 | | - if instance.synonyms: |
12 | | - for synonym in instance.synonyms: |
13 | | - cls._instance_lookup[synonym] = instance |
14 | | - return cls._instance_lookup[name] |
| 28 | + keys = [] |
| 29 | + for prop_name in namelike_properties: |
| 30 | + if hasattr(instance, prop_name): |
| 31 | + keys.append(getattr(instance, prop_name)) |
| 32 | + if hasattr(instance, "synonyms"): |
| 33 | + for synonym in instance.synonyms or []: |
| 34 | + keys.append(synonym) |
| 35 | + for key in keys: |
| 36 | + if key in cls._instance_lookup: |
| 37 | + cls._instance_lookup[key].append(instance) |
| 38 | + else: |
| 39 | + cls._instance_lookup[key] = [instance] |
| 40 | + if match == "equals": |
| 41 | + matches = cls._instance_lookup.get(name, None) |
| 42 | + elif match == "contains": |
| 43 | + matches = [] |
| 44 | + for key, instances in cls._instance_lookup.items(): |
| 45 | + if name in key: |
| 46 | + matches.extend(instances) |
| 47 | + else: |
| 48 | + raise ValueError("'match' must be either 'equals' or 'contains'") |
| 49 | + if all: |
| 50 | + return matches |
| 51 | + elif len(matches) > 0: |
| 52 | + return matches[0] |
| 53 | + else: |
| 54 | + return None |
0 commit comments