PyFunction (@NotNull PyFunction newFunction, @NotNull PyFile newFile, @Nullable PsiElement anchor) { if (mySourceFile == newFile) { // In the same file try inserting generated function at the top level but preferably right after the original scope owner final PsiElement surroundingStatement = PyPsiUtils.getParentRightBefore(myFunction, mySourceFile); if (anchor == null || surroundingStatement.getTextRange().getEndOffset() < anchor.getTextRange().getStartOffset()) { return (PyFunction)mySourceFile.addAfter(newFunction, surroundingStatement); } } // Insert at the end or before first top-level usage in the file return (PyFunction)newFile.addBefore(newFunction, anchor); }