In the comments of https://gerrit.wikimedia.org/r/#/c/309325/ several possibilities for re-factoring (and at least one error in the current implementation) were identified. To not block T114166 these have been broken out to a separate task. The comments from there are copied in below for convenience:
in get_categories_from_source_page():
Is this not the same as the B case but for the list page?
If so (like for B above) one call to getCategoryFromCommonscat() should be enough.
Or are we doing the "is_template_present_in_page(commonsCatTemplate, page)" step for efficiency reasons. If so we could add a short comment or rebuild getCategoryFromCommonscat() with this logic.
in get_categories_from_upper_categories():
This could call on getCategoryFromCommonscat(). Alternatively reuse the logic in C (see two comments above) if that is chosen over getCategoryFromCommonscat() for efficiency reasons.
Note that here we use
new_cat = pywikibot.Category(site, new_cat_title)
which we don't in C so the logic here is likely more correct (as in the other one is probably broken).