Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't import between files in the same folder

I’m trying to import Entity.py into Tower.py in the same directory, in order to instantiate the Entity class inside Tower.py. However, it keeps coming up with the same error.

folder
  |_ scripts
       |_ Tower.py
       |_ Entity.py
  |_ Main.py

Entity.py

class Entity:
   ...

Tower.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import Entity
 File "C:\...\scripts\Tower.py", line 3, in <module>
    import Entity
ModuleNotFoundError: No module named 'Entity'

I’m confused as to why this is happening and what I’m doing wrong.

>Solution :

Modules are relative to the working directory. So, if you are running the app using Main.py, every import will be relative to the directory of Main.py.

If you want to import the Entity to Tower, you must import it like

from scripts.Entity import Entity

or with relative like

from .Entity import Entity

And you must create a __init__.py file in your scripts folder to mark it as a package.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading