Fix the annotations in a method definition. The signature must be a single-line function def, no decorators.
(signature)
| 216 | return text |
| 217 | |
| 218 | def fix_annotations(signature): |
| 219 | """Fix the annotations in a method definition. |
| 220 | The signature must be a single-line function def, no decorators. |
| 221 | """ |
| 222 | # get the FunctionDef object from the parse tree |
| 223 | definition = ast.parse(signature).body[0] |
| 224 | annotations = [arg.annotation for arg in definition.args.args] |
| 225 | return_i = len(annotations) # index of annotation for return |
| 226 | annotations.append(definition.returns) |
| 227 | |
| 228 | # create a list of changes to apply to the annotations |
| 229 | changes = [] |
| 230 | for i,a in enumerate(annotations): |
| 231 | if a is not None: |
| 232 | old_text = signature[a.col_offset:a.end_col_offset] |
| 233 | text = annotation_text(a, old_text, (i == return_i)) |
| 234 | if text != old_text: |
| 235 | changes.append((a.col_offset, a.end_col_offset, text)) |
| 236 | |
| 237 | # apply changes to generate a new signature |
| 238 | if changes: |
| 239 | newsig = "" |
| 240 | lastpos = 0 |
| 241 | for begin,end,text in changes: |
| 242 | newsig += signature[lastpos:begin] |
| 243 | newsig += text |
| 244 | lastpos = end |
| 245 | newsig += signature[lastpos:] |
| 246 | signature = newsig |
| 247 | |
| 248 | return signature |
| 249 | |
| 250 | def push_signature(o, l, signature): |
| 251 | """Process a method signature and add it to the list. |
no test coverage detected