1

My Directory structure is as follows

microblog/__init__.py
         urls.py
         views.py
         wsgi.py
         settings/__init__.py
                 testing.py
                 base.py
                 local.py

In testing.py I have a relative import

from .base import *
...
...more code

When I try to run the testing.py from the command line in the directory microblog/settings using python testing.py

from .base import *
ValueError: Attempted relative import in non-package

Why does this not work. The settings directory is a valid package with a init.py . I do not get the ValueError from the command line only If I change the

from .base import *

to

from base import *

I am trying to understand why the relative local import fails and gives a ValueError when I run the "testing.py" package with a relative import in it from the command line.

harijay
  • 11,303
  • 12
  • 38
  • 52
  • I think this question has been answered..I just saw http://stackoverflow.com/questions/9123062/python-relative-import-example-code-does-not-work?lq=1. As icyrocks answer says when I run python testing.py . Then it automatically thinks the package is "main". To run a packagage with a realtive import from the command line I need to do "python -m microblog.settings.testing" – harijay Apr 19 '13 at 22:08
  • 1
    "Why does this not work." The error message tells you why! The script you are doing the import from, `testing`, is not a package. – kindall Apr 19 '13 at 22:09
  • Well it says testing is a non-package which didnt make sense to me because I assumed that testing is part of the package settings ..but as you say I didnt realize that "testing" is actually in a package "main" when run standalone.The answer from icyrock clarified this for me. Many other questions on stackoverflow address different aspects of relative imports which did not apply in my case since I did have testing in a package with a bonafide dunder init.py. – harijay Apr 19 '13 at 22:21
  • Even when imported as part of a package, `testing` is not a package, it is *in* the package `settings`. – kindall Apr 19 '13 at 22:39

1 Answers1

2

The answer from icyrock in this post clarifies exactly what I didnt understand about the python "repl".

In the Directory microblog/settings when I run

python testing.py

It actually puts testing in the package "main" and it does not know that testing is part of the package "settings". Instead running "testing.py" as a module as part of its normal package hierarchy using this

python -m microblog.settings.testing 

Runs it without any ValueError since now python knows that "testing" is part of package "settings" where the relative local import "from .base import *" makes perfect sense.

Community
  • 1
  • 1
harijay
  • 11,303
  • 12
  • 38
  • 52