0

There's this app structure, where myapp is the root directory and "app" and "package1" two parallel packages:

myapp

  app
     __init__.py
     app.py

  package1
     __init__.py
     my_file.py
 
  __init__.py

*Note: the last __init__.py is located in the root directory "myapp"

Now, in the app.py, if I try to import the my_file.py

from ..package1 import my_file as my_variable

Then I get this error:

ImportError: attempted relative import with no known parent package

I've researched and found a possible solution here:

How to resolve ImportError: attempted relative import with no known parent package

I'd like to apply the "Solution 1", but don't understand exactly where should I put the main.py and which would be its internal code or if, conversely, it could be an empty file like __init__.py

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Jacke Dow
  • 179
  • 2
  • 12

1 Answers1

2

You should have a run function in app.py:

def run():
    # .... You code that should run as app

There should be no automatic running code in app.py

main.py should be on the same folder as myapp:

myapp
  app
     __init__.py
     app.py

  package1
     __init__.py
     my_file.py

  __init__.py
main.py

Now main.py should contain something like this:

from myapp.app import app

app.run()

and you can run it python main.py

Alternative you can also put a __main__.py file in myapp:

myapp
  app
     __init__.py
     app.py

  package1
     __init__.py
     my_file.py

  __init__.py
  __main__.py

The __main__.py should contain something like this:

from .app import app

app.run()

The you cann run it like this python -m myapp

MegaIng
  • 6,933
  • 1
  • 21
  • 34