#πŸ”’ Unexpected ModuleNotFound

28 messages Β· Page 1 of 1 (latest)

light night
#
└── main/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ one.py
    └── sub/
        β”œβ”€β”€ __init__.py
        └── two.py
#one.py
from sub.two import Class

resource = 3

#two.py
from main import one

print(one.resource)

class Class:
    pass

When I execute one.py how come it raises ModuleNotFoundError: No module named 'main'?

lone bearBOT
#

@light night

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

white breach
#

Show the full terminal session?

#

You need main.sub.two

light night
# white breach Show the full terminal session?
Traceback (most recent call last):
  File "d:\vsc\test\main\one.py", line 1, in <module>
    from sub.two import Class
  File "d:\vsc\test\main\sub\two.py", line 1, in <module>
    from main import one
ModuleNotFoundError: No module named 'main'
glass basalt
#

Which command did you use to run this?

light night
light night
white breach
#

Ah don't use run on vscode

#

Use python -m main.one

light night
modern night
light night
modern night
sage swift
#

There's two ways to run code in python: as a script or as a module

light night
#

What does running it as a module do differently?

sage swift
#

When you do python one.py it runs "one.py" within the main directory. Everything above that level, including main, is inaccessible

light night
#

ohh

sage swift
#

When you do python -m main.one it runs the directory main as the module, importing the __init__, and then runs one.py underneath that. Because main is part of the project namespace from that perspective, you can import it

#

By default python -m main also runs __main__.py, but you dont' have one, hence the need to specify .one

light night
#

and it has acess to everything else including sub

sage swift
#

right

#

Everything at the level you're running, and below

light night
#

Ok that makes sense now

#

Thanks guys!

#

!close

lone bearBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.