"No module named" when importing from another package in python3.6 - python-3.x

If I execute demo2.py it works fine, the problem is when I execute main.py
|myPackage
|subPackage
demo.py
demo2.py
main.py
main.py
from ludikDriver.demo2 import demo2_print
demo2_print()
demo2.py
from demo import demoprint
def demo2_print():
print("demo2")
demoprint()
demo2_print()
demo.py
def demoprint():
print("demo")
Error:No module named 'demo'

Just use relative imports as suggested in pep 328.
from .demo import demoprint
You can do for the other package. Just as relative paths.

Your modules need context of themselves. You should have the "__init__.py" file in subPackage and myPackage. Then your import should be relative:
from . import demo
OR more in context of your example:
from .demo import demoprint

Your error is associated with the top line in demo.py:
from demo import demoprint
There is no module named demo

Related

ModuleNotFoundError: No module named 'module' while importing my own module VsCode MacOs Python 3.10

Structure:
|--folder/
|--a.py
|--main.py
When loading module 'main' into module 'a'
#a.py
import main
the following error occurs - ModuleNotFoundError: No module named 'main'.
PyCharm copes with this task, but VSCode does not. What's the matter?
Looking at your directory structure, I presume that a.py and main.py are in different directories. If that is the case, then the answers to [this question][1] should be useful. To elaborate a bit further, you can use the sys module to specify the path to the other module (main.py) i.e. if main.py is in a different directory from a.py.
import sys
sys.path.append('/path_to_main_module_directory/')
import main
print("This import is for the main module")
I hope this helps!
[1]: Importing files from different folder

Relative import doesn't work : ImportError: attempted relative import with no known parent package

This are the files:
parent_directory:
parent_directory/ecommerce:
parent_directory/ecommerce/payments:
What I'm trying to do is to use a relative import in products.py in order to import database.py. I know that I can just write import database but I want to learn relative imports. I've also tried to import main.py from the top level directory, parent_directory, but that doesn't work either so I thought I'll just try to do the easiest relative import possible and that is, importing a file from the same package.
This is the code for products.py inside parent_directory/ecommerce:
from .database import Database
class Product:
pass
And this is the code from the database.py file inside parent_directory/ecommerce:
if __name__ == "__main__":
import products
x = products.Product()
class Database:
pass
print("file : {0:<35} || name : {1:<20} || package : {2:<20}".format(
str(__file__).split("\\")[-1],
str(__name__),
str(__package__),
))
I tried several things like:
executing products.py with -m like python -m products.py
creating a py venv
adding all and package inside the files.
Here is my init.py file from parent_directory/ecommerce:
__all__ = ["database", "products"]
__package__ = "ecommerce"
No matter what I do, I always get this error: ImportError: attempted relative import with no known parent package. I know that this question has been asked before. I've tried many things out but nothing worked. Do you have any idea how to fix this ?
I found the solution to my problem.
I have to be outside the package and use -m and instead of using / to send the path, I have to use . instead so :
python -m parent_directory.ecommerce.products
This will fix the problem but I have to execute this line outside the top-level package ( in my case, the top level package is parent_directory ).
# Inside products.py
from .database import Database # works
from ..main import SomeRandomClass # works
class Product:
pass
I've found a way to import files from parent directories, since it's very easy to import them from sub-packages by using absolute imports.
# inside parent_directory/ecommerce/products.py trying to import parent_directory/main.py
import sys
import os
current_file = os.path.realpath(__file__)
current_dir_ecommerce = os.path.dirname(current_file)
parent_dir_parent_directory = os.path.dirname(current_dir_ecommerce)
sys.path.insert(0, parent_dir_parent_directory)
import main # works
I just added the parent directory to sys.path.

Where to import dependency while working with multiple files

Let's say there are two files - mask.py and main.py.
mask.py has some function that I'm importing into main.py.
So if that function in mask.py which I'm importing has dependency like "os", where should I import os - in mask.py or main.py.
Let us consider a scenario as you have stated by using two files mask.py and main.py.
mask.py
import os
def some_function():
os.environ['a_url'] = "something.com" # using dependency as you mentioned
main.py
from mask import some_function
# do something with the function
Now, coming to your query, if you use import os in main.py but not in mask.py, you will get NameError in mask.py saying:
NameError: name 'os' is not defined
This is because you need to import any dependency in the same file where it is used. Also, if both of your file uses this dependency, you need to import it in both the files.
Hope this clarifies your query.

import package from an other package

I have a very simple project architecture:
project/
__init__.py
dira/
__init__.py
a.py
dirb/
__init__.py
b.py
All the __init__.py are empty.
a.py only contains a "hello" function:
def hello(): return "hello world"
I want b.py to use the hello function from a.py.
What I tried so far:
Following answers from this question, I tried:
import ..dira.a as aa
aa.hello
But when running b.py I get a syntax error on ..a.a
I also tried to manually add the project directory to sys.path and then run:
import dira.a as aa
aa.hello
But when running b.py I get:
ImportError: No module named 'a'
What should I do? Why the solution I found doesn't work?
Short answer:
import ..dira is invalid syntax and only from ..dira.a import hello works
Working configuration: b.py:
from ..dira.a import hello
print(hello())
Also, from docs:
"Note that relative imports are based on the name of the current
module. Since the name of the main module is always "main",
modules intended for use as the main module of a Python application
must always use absolute imports."
So if you do relative imports you cannot call b.py directly. Apperently, you cannot do it from project level either. (Python interpreter in project folder, call import dirb.b)
An error occurs:
ValueError: attempted relative import beyond top-level package
But calling import project.dirb.b makes proper output:
hello world
EDIT: Why import project.dirb.b can be called only outside of project module?
Let's look at the problem from interpreter's side.
You call import project.dirb.b. It runs dirb/init.py, 'current module' is project.dirb
Interpreter finds command from ..dira.a import hello
It treats double dot ..dira.a as "move one module up and go to dira and import a.hello". 'Current module' is project.dirb, so parent module is project, thus it finds parent.dira
What happens when you call import dirb.b directly? It fails on trying to go level up in module hierarchy and reports error.
Thus, relative import makes project.dirb.b importable only outside of project.

A test running with nosetests fails with ImportError, but works with python command

When run a test with python mycore/tests4extractor.py it works. If run the test with nosetests ./mycore/tests4extractor.py it fails with ImportError: No module named extractor. I am in the helpers folder.
The project structure is:
helpers/
mycore/
__init__.py
extractor.py
tests4extractor.py
Setting PYTHONPATH to the absolute path to helpers and/or helpers/mycore doesn't help.
Answer
tests4extractor.py:
import mycore
from extractor import extract
should be changed to:
import mycore
from mycore.extractor import extract
And python should be run with python -mmycore.tests4_strings
Does tests4extractor.py contain import extractor?
Because mycore is a package, you need to use absolute imports:
from mycore import extractor
or relative imports:
from . import extractor

Resources