1

Following is the file structure all are in same folder:

__init__.py gnewsclient.py test.py

1) __init__.py:

from .gnewsclient import gnewsclient

2) gnewsclient.py

class gnewsclient: //Some methods

Now I want to import methods from gnewsclient class of gnewsclient.py file inside test.py

I tried from gnewsclient import * but it says parent module not loaded '' cannot perform relative import.

Ice fire
  • 143
  • 3
  • 10

1 Answers1

1

Package layout:

 package
    | __init__.py
    | module1.py
    | module2.py

 script.py

If you want to import a function f1 from module1 in module2 do:
from package.module1 import f1.

Now, if you try to execute module2.py by doing python module2.py, it won't work because you are inside the package, so python does not find the path to the module and you will have the kind of error you got. So if you want to use or test your modules, you need to do it from outside the package, in script.py for instance:

Example of script.py:

from package.module1 import f1
from package.module2 import f2

print(f1())
print(f2())
j_4321
  • 15,431
  • 3
  • 34
  • 61
  • I could not understand why from package.module1 and why not from module1 as I am running test.py which is in same folder that of all other .py files – Ice fire Dec 14 '17 at 08:49
  • Utils.py is imported by gnewsclient.py and also by test.py so it is imported twice does that throw error. – Ice fire Dec 14 '17 at 08:52
  • @Icefire if there is no "loop" import (like import module1 in module2 and module2 in module1) duplicate imports don't throw errors. – j_4321 Dec 14 '17 at 09:04
  • No I am asking module 3 inside module 2 and also inside module 1 and in test.py we call module 3&1 will it cause error I think I have done it like this. – Ice fire Dec 14 '17 at 09:06
  • @Icefire No, I don't think so – j_4321 Dec 14 '17 at 09:10
  • check this -> https://imgur.com/a/evsDN https://imgur.com/a/34lf8 – Ice fire Dec 14 '17 at 09:40
  • @Icefire you need to run `test.py` from outside the package: go to `KWOC gnewsclient\gnewsclient` in the python console (not in `KWOC gnewsclient\gnewsclient\gnewsclient`) and import `gnewsclient.test`. – j_4321 Dec 14 '17 at 09:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161182/discussion-between-j-4321-and-ice-fire). – j_4321 Dec 14 '17 at 09:50
  • https://stackoverflow.com/questions/47816812/how-to-add-scrollbar-for-user-defined-canvas-class-tkinter – Ice fire Dec 14 '17 at 15:25