0

I have a code that runs in Python 2.7 but not in 3.5 and I can't find the reason. It has to do with importing.

The root folder has a subfolder called s. From the root folder, I am running the script a.py which includes the line from s import *.

In the folder s, there is a file called b.py which has the import line: from c import c which tries to import the class saved in c.py which is located in the subfolder s as well.

When I run the script a.py from the root folder, I get the ImportError saying "No module named c".

In Python 2.7 this runs without problems. Can someone please suggest what may be the issue and how this should be done differently in Python 3.5?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
splinter
  • 3,727
  • 8
  • 37
  • 82
  • Interesting. The configuration you described throws an ImportError in python2, and neither throws nor loads the module c in python3 for me. – Tamas Hegedus Jun 24 '16 at 15:33
  • 1
    Did you see http://stackoverflow.com/questions/12172791/changes-in-import-statement-python3? It looks related (i.e., "In Python 3, implicit relative imports within packages are no longer available"). – rkersh Jun 24 '16 at 15:35
  • See https://docs.python.org/3/whatsnew/2.5.html#pep-328-absolute-and-relative-imports – André Laszlo Jun 24 '16 at 16:05

1 Answers1

3

Implicit imports within packages are not available for Python 3, so to get this to work you will need to use an explicit relative import:

from .s import *

This should work for both Python 2 and Python 3. This also makes your intention more clear that you want to import from a relative package, not an installed package.

amicitas
  • 13,053
  • 5
  • 38
  • 50
  • Thanks so much, so simple :). I needed exactly that - the relative import stuff in p[ython 3 is a bit different. Thank you – splinter Jun 25 '16 at 11:34