Skip to content

Instantly share code, notes, and snippets.

@con-cat
Last active December 31, 2023 04:54
Show Gist options
  • Save con-cat/369e7caae1d2c3ec6ddd40da373434e1 to your computer and use it in GitHub Desktop.
Save con-cat/369e7caae1d2c3ec6ddd40da373434e1 to your computer and use it in GitHub Desktop.
Emacs lisp function to return an import statement for a Python file or object
(defun con-cat/get-python-import-statement (root-in-project)
"Return an import statement for a Python file or object.
root-in-project is the optional path to a directory inside the project that the path should be relative to,
e.g. 'src' if your project is in ~/myproject and your Python files are in ~/myproject/src"
(unless (and (projectile-project-root) buffer-file-name (string= "py" (file-name-extension buffer-file-name)))
(user-error "Buffer isn't visiting a Python file in a Projectile project."))
(let*
;; Get the path of the file relative to projectile-project-root and root-in-project
((file-path (file-relative-name buffer-file-name (expand-file-name root-in-project (projectile-project-root))))
;; Get a list of string parts of the file path, e.g. foo/bar/baz.py == ("foo" "bar" "baz")
(file-path-parts (file-name-split (file-name-sans-extension file-path)))
;; Get the name of the function or class at point, if there is one
(current-defun (python-info-current-defun)))
(if current-defun
;; Return an import statement for the function or class, e.g. "from foo.bar.baz import MyClass"
(concat "from " (string-join file-path-parts ".") " import " current-defun)
;; Otherwise, return an import statement for the module, e.g. "from foo.bar import baz"
(concat "from " (string-join (butlast file-path-parts) ".") " import " (car (last file-path-parts))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment