Skip to content

Instantly share code, notes, and snippets.

@con-cat
Last active July 2, 2024 03:56
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-path (root-in-project)
"Return a list of parts of the path to 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 path to the function or class, e.g. "foo.bar.baz.MyClass"
(append file-path-parts (list current-defun))
;; Otherwise, return path to the module, e.g. "foo.bar.baz"
file-path-parts)))
(defun python-import-statement (root-in-project)
(interactive (list "src"))
(let ((parts (con-cat/get-python-path root-in-project)))
(con-cat/message-and-copy (concat "from " (string-join (butlast parts) ".") " import " (car (last parts))))))
(defun python-path (root-in-project)
(interactive (list "src"))
(let ((parts (con-cat/get-python-path root-in-project)))
(con-cat/message-and-copy (string-join parts "."))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment