I can't import modules from other folders - python-3.x

I'm a bit new to the Python world. I'm using Python3 and having hard times with imports.
I was using PyCharm on Windows to write an application. Everything was working through the project until I switched to Linux and VS Code.
Now I can't use absolute imports for importing modules from other packages in the same project.
For example, I'd like to import from module cards all available card types.
I tested the classes and everything is ok. I'm only getting this issue with the import stuff.
The project structure:
/
|-cards
|-__init__.py
|-card.py
|-monster_card.py
|-spell_card.py
|-trap_card.py
|-ritual_card.py
|-deck
|-__init__py
|-deck.py
|-system
# This is the code in __init__.py in cads package
from . trap_card import TrapCard
from . spell_card import SpellCard
from . ritual_card import RitualCard
from . monster_card import MonsterCard
__all__ = [TrapCard, SpellCard, RitualCard, MonsterCard]
# The following line, for example, does not work from inside another package
# I'm trying to import the modules in cards from deck
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
When I try to import packages from another folders I get this error message:
Traceback (most recent call last):
File "/root/git-repos/Yu-Gi-Oh/decks/deck.py", line 3, in
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
ModuleNotFoundError: No module named 'cards'

When you call import *, python search the module from sys.path. You need to add your root dir into sys.path before call import stmt.
For your case, your root dir is /.
like:
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from cards import *
other way
Add file __init__.py into your root dir for make it become a module. Then change from cards import * to from .cards import *.

Related

Not able to load python custom module from another directory

I want to load a custom python module from another directory. This question also has been asked many times and I have followed lot of links, and I have a solution. However, it is not working for me. I am fairly new to Python and looks like I am making a simple mistake which I am not able to find.
Below is the hierarchy. I want to import 'extollo_keyvault.py' inside 'testCode.py'. I can see the path for 'extollo_keyvault.py' when I print 'sys.path', however, the script execution fails saying that unable to find that module
Code:
import os
import sys
path_to_extolloKeyvault_module = os.path.join(os.getcwd(), 'extollo_instance', 'hardened', 'extollo_keyvault.py')
sys.path.insert(0, path_to_extolloKeyvault_module)
import extollo_keyvault
Error:
Traceback (most recent call last):
File "c:/Users/manjug/source/repos/extollo-instance-march-31/extollo_instance/Instance/testCode.py", line 6, in <module>
import extollo_keyvault
ModuleNotFoundError: No module named 'extollo_keyvault'
Your current code includes /Instance.
Try this code:
import os
import sys
from pathlib import Path
path = Path(os.getcwd())
path_to_extolloKeyvault_module = os.path.join(path.parent.absolute(), 'extollo-instance-march-31', 'extollo_instance', 'hardened'
sys.path.insert(0, path_to_extolloKeyvault_module)
import extollo_keyvault

Having problem to import a module from different directory in python

Image of the code I have created init.py file in every folder
import Pages.login_page.LoginPage
>error:
>Traceback (most recent call last):
> File "D:\work\testAutomation\pythonEvaly\Tests\base_test.py", line 5, in ><module>
> import Pages.login_page.LoginPage
>ModuleNotFoundError: No module named 'Pages'
The import would look like:
from ..Pages.login_page import LoginPage
The double dots mean that it will look for a module named Pages in the parent directory of the script.
Note:
This will only work if you have a __init__.py in the Pages folder
Edit
This should work...
import sys
sys.path.append('../Pages')
import login_page.LoginPage
import home_page.HomePage
Before importing we should append the parent directory
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
#should import after above lines
from some_folder.some_file import some_module

Import don't run in python

I am developing a Django project and I am trying to run a test file but an error in the import occurre.
My folder hierarchy to be like the image:
see the image of function process_data inside of core.py
I am in the test directory trying to run my test file.
My import to be like the code:
from coordenadas.core import process_data
but, when I run my code an error is showed:
Traceback (most recent call last):
File "tests_class_moviment.py", line 1, in <module>
from coordenadas.core import process_data
ModuleNotFoundError: No module named 'coordenadas'
I am tryed use relative import
from .coordenadas.core import process_data
from .core import process_data
from ..coordenadas.core import process_data
from ..core import process_data
but the only way that no error is showed in pycharm is the
from coordenadas.core import process_data
Some idea how can I solve it?
On a partially unrelated note, absolute imports are definitely recommended over relative imports. PEP8:
Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.
As for the module error itself, adding an __init__.py file to the "coordenadas" directory will turn it into a module, which is exactly what you need.

Can't import relative module

The file structure for a module im creating goes as follows:
PIV
| __init__.py
| base.py
| core.py
| exceptions.py
.gitignore
LICENSE
requirements.txt
But whenever I run a file like core.py, I get the following error:
Traceback (most recent call last):
File "c:/Users/ghub4/OneDrive/Desktop/Python-Image-and-Video-tools/PIV/core.py", line 33, in <module>
from . import base
ImportError: attempted relative import with no known parent package
The same thing happens when I run the __init__.py file. I'm not sure on what went wrong because all of the python files are in the same folder. Can someone clarify what's the problem and explain how I should fix it?
Import code for core.py file:
from __future__ import absolute_import
import sys
import os
from PIL import Image
import io
from . import base
from . import exceptions
(The __init__.py folder has the same relative imports as in the core file but also including: from . import core)
Based upon the two links you will given below, here is what needed for the problem to solve:
Relative Imports error rectified
No module named base
You need to import the package as this
from mymodule import some_useful_method
Sometimes, we get the no module error, in this case, we can import like this
from module_name.classname import some_useful_method

"No module named" when importing from another package in python3.6

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

Resources