Tech Learner
Tech Learner

Reputation: 241

change in import in python3

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.

Upvotes: 4

Views: 838

Answers (3)

U13-Forward
U13-Forward

Reputation: 71570

Try changing the __init__.py to the below code:

from TestPak.TestModule import TestFun

Upvotes: 1

jedwards
jedwards

Reputation: 30210

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).

Upvotes: 4

user6764549
user6764549

Reputation:

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.

Upvotes: 0

Related Questions