4

I am using python 3.4.4 and testing "init.py" feature by creating a sample package But unable to implement. The mentioned case is working perfectly in case of python 2.7.13 version. Can anyone tell me the mistake i am doing or is there any change in syntax of python 3.x versions. Please help me to learn Python 3?

Dir Structure:

TestPackage/
    __init__.py
    TestModule.py
run.py

Content of TestModule.py :

def TestFun():
    print("Welcome")

Content of __init__.py :

from TestModule import TestFun

Content of run.py :

from TestPackage import TestFun
TestFun()

When i execute run.py file, i got the following error:

Traceback (most recent call last):
  File "D:\CASE03\run01.py", line 1, in <module>
    from TestPackage import TestFun
  File "D:\CASE03\TestPackage\__init__.py", line 1, in <module>
    from TestModule import TestFun
ImportError: No module named 'TestModule'

But when i use python 2.7.13 it works perfectly fine. Please guide me.

Tech Learner
  • 241
  • 3
  • 12

3 Answers3

4

Inside of __init__.py, if you change

from TestModule import TestFun

to

from .TestModule import TestFun

You'll get the expected behavior.

See: PEP 328 (sections regarding relative imports using leading dots).

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • 1
    It is (a change in Python3). ([Here's another answer regarding the change](https://stackoverflow.com/a/12173406/736937)) – jedwards Jun 08 '18 at 03:06
1

Try changing the __init__.py to the below code:

from TestPak.TestModule import TestFun
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    While this will work, it will couple the contents of the init file with the package name (which may change). Not a huge deal, but the relative import (leading dot) exists and seems cleaner. – jedwards Jun 08 '18 at 03:08
0

The simplest solution is to set __init__.py as a blank file. In case you are interested in controlling what gets imported from your module when you do from Testmodule import *, you can include __all__ = ['TestFun'] in __init__.py file.