1

If import an file in another file in the same folder.

file structure:

.
├── b
│   ├── c.py
│   ├── d.py
│   └── __init__.py
└── __init__.py

in d.py:

import b.c
print "import successfully"

update 1:

I use both

python d.py

and:

python b/d.py

the program cannot run and raise a ImportError.

To solve the problem, I use

    sys.path.insert(0, realpath(path_join(dirname(__file__), '../')))

However, It doesn't seems like the standard way.

Like some famous project: tornado or some what, always using this structure. but don't have the insert line.

autotest tools such as sniffer, autonose can run such structure if the import sentence is in a unittest file.

I don't know why.

PEP328 or PEP366 don't give me a great solution about this.

PEP8 recommend me to do things like this way.

The question also occur when import another module (in another file) such as:

├── a
│   ├── e.py
│   └── __init__.py
├── b
│   ├── c.py
│   ├── d.py
│   └── __init__.py
├── __init__.py
chao787
  • 1,760
  • 3
  • 18
  • 20
  • This answer [exists here](http://stackoverflow.com/a/6098238), [here](http://stackoverflow.com/a/456491) – invert Jul 10 '12 at 09:39
  • @invert I see this method, and it can do the thing. But someone's code run succuessfully in this way. but don't have insert path sentence. – chao787 Jul 10 '12 at 09:40

3 Answers3

1

You should use python b/d.py instead of python d.py.

Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79
0

Vinayak's answer works perfectly for Python v3.3.2. If a bunch of non-OOP Python modules exist in a directory 'dir', one can successfully import any of the methods from any of the files existing in 'dir' into a file (also existing in 'dir').

Steven
  • 1
-1

According to PEP328 the following code should work.

from . import c

Is my understanding correct?

Vinayak Kolagi
  • 1,831
  • 1
  • 13
  • 26
  • This gives me: `"ValueError: Attempted relative import in non-package"` – invert Jul 10 '12 at 09:30
  • @invert maybe you shuold add from __future __ import absolute_path in your file. relative path is a python 3 feature. – chao787 Jul 10 '12 at 09:32
  • @Vinayak-Kolagi relative path is not recommended, do you have some ideas to treat module as modules but not in a system way? – chao787 Jul 10 '12 at 09:35