Subject: bug#13570: [PATCH] 24.2; (python.el) "ValueError: Attempted relative import in non-package" with relative import.

From: Oleksandr Gavenko <[email-masked]>
Date: Mon, 28 Jan 2013 23:08:48 +0200

As I previously wrote python.el on C-c C-l (python-load-file) throw:

  ValueError: Attempted relative import in non-package

if module have relative import, like:

  from . import module
  from ..sound import module

Seems that 'eimport' from emacs2.py/emacs3.py already support packages. So I
improve 'python-load-file' in python.el by locating most top non-package
directory, see example:

  $ mkdir /home/user/pythonpath/package1/package2/
  $ touch /home/user/pythonpath/package1/package2/__init__.py
  $ touch /home/user/pythonpath/package1/__init__.py

  (defun foo ()
    (let ( (module "module") (path "/home/user/pythonpath/package1/package2/") )
      (while (file-exists-p (concat path "__init__.py"))
        (string-match "\\(.+/\\)\\([^/]+\\)/$" path)
        (setq module (concat (match-string 2 path) "." module))
        (setq path (match-string 1 path))
        )
      (list path module)))

The patch is:

--- old/python.el	2013-01-28 22:56:50.000000000 +0200
+++ new/python.el	2013-01-28 22:59:24.000000000 +0200
@@ -1703,8 +1703,12 @@
     (python-send-command
      (if (string-match "\\.py\\'" file-name)
 	 (let ((module (file-name-sans-extension
-			(file-name-nondirectory file-name))))
-	   (format "emacs.eimport(%S,%S)"
-		   module (file-name-directory file-name)))
+                        (file-name-nondirectory file-name)))
+               (path (file-name-directory file-name)))
+           (while (file-exists-p (concat path "__init__.py"))
+             (string-match "\\(.+/\\)\\([^/]+\\)/$" path)
+             (setq module (concat (match-string 2 path) "." module))
+             (setq path (match-string 1 path)))
+	   (format "emacs.eimport(%S,%S)" module path))
        (format "execfile(%S)" file-name)))
     (message "%s loaded" file-name)))

But newer python.el version no longer use emacs2.el.

I have no time to compile and debug latest Emacs but suggest use similar
technique to allow relative import...

-- 
Best regards!