Create a unique name. Arguments: candidate: used as the basis for the unique name, relevant to the user. obj: If not None, an object that will be associated with the unique name.
(self, candidate: str, obj: Optional[Any])
| 130 | self._name_suffix_regex = re.compile(r"(.*)_(\d+)$") |
| 131 | |
| 132 | def create_name(self, candidate: str, obj: Optional[Any]) -> str: |
| 133 | """Create a unique name. |
| 134 | |
| 135 | Arguments: |
| 136 | candidate: used as the basis for the unique name, relevant to the user. |
| 137 | obj: If not None, an object that will be associated with the unique name. |
| 138 | """ |
| 139 | if obj is not None and obj in self._obj_to_name: |
| 140 | return self._obj_to_name[obj] |
| 141 | |
| 142 | # delete all characters that are illegal in a Python identifier |
| 143 | candidate = self._illegal_char_regex.sub('_', candidate) |
| 144 | |
| 145 | if not candidate: |
| 146 | candidate = '_unnamed' |
| 147 | |
| 148 | if candidate[0].isdigit(): |
| 149 | candidate = f'_{candidate}' |
| 150 | |
| 151 | match = self._name_suffix_regex.match(candidate) |
| 152 | if match is None: |
| 153 | base = candidate |
| 154 | num = None |
| 155 | else: |
| 156 | base, num_str = match.group(1, 2) |
| 157 | num = int(num_str) |
| 158 | |
| 159 | candidate = base if num is None else f'{base}_{num}' |
| 160 | if not num: |
| 161 | num = self._base_count[base] |
| 162 | |
| 163 | while candidate in self._used_names or self._is_illegal_name(candidate, obj): |
| 164 | num += 1 |
| 165 | candidate = f'{base}_{num}' |
| 166 | |
| 167 | self._used_names.add(candidate) |
| 168 | self._base_count[base] = num |
| 169 | if obj is None: |
| 170 | self._unassociated_names.add(candidate) |
| 171 | else: |
| 172 | self._obj_to_name[obj] = candidate |
| 173 | return candidate |
| 174 | |
| 175 | def associate_name_with_obj(self, name: str, obj: Any): |
| 176 | """Associate a unique name with an object. |
no test coverage detected