1

My current directory structure

prem
.
├── __init__.py
├── test1.py
├── test2.py

test1.py

print 'test1.py'

test2.py

import  sys
sys.path.append('/opt/sw/p3/src/prem')
print sys.path
from . import test1

Error

    from . import test1
ValueError: Attempted relative import in non-package

When I display the path , I see this directory - /opt/sw/p3/src/prem

user1050619
  • 19,822
  • 85
  • 237
  • 413
  • Maybe just `import test1`? – Hyperboreus Apr 24 '14 at 19:39
  • import test1 works fine..but Im wondering why the relative import does not work – user1050619 Apr 24 '14 at 19:40
  • What are you doing to get that error? Are you running `test2.py` directly? If so, see [this question](http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py/) and [this one](http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time). – BrenBarn Apr 24 '14 at 19:45
  • Im running with -m option and still same issue – user1050619 Apr 24 '14 at 19:47
  • @user1050619: Please edit your question to include the precise command line you are using to run it. – BrenBarn Apr 24 '14 at 19:52

1 Answers1

1

If you are running test2.py directly, then prem is already the working directory.

calling from . is equivalent to calling the from prem however if prem is already your working directory, it will now attempt to find another package prem inside the current package

try this layout:

/my_program
    /prem
    ├── __init__.py
    ├── test1.py
    ├── test2.py
    main_test.py

main_test.py

import prem.test2

In this case, your working directory is now the one containing prem,my_program... meaning that the import in test2.py, will work because it will find the prem package within my_program

flakes
  • 21,558
  • 8
  • 41
  • 88