Import a submodule in a Python module - python

I have already read Python: importing a sub‑package or sub‑module but this:
file content
============================================================================
main.py from mymodule.a import A; A()
mymodule/submodule/__init__.py (empty)
mymodule/submodule/b.py class B: pass
mymodule/__init__.py (empty)
mymodule/a.py (see below)
mymodule/a.py:
import submodule
class A:
def __init__(self):
self.b = submodule.B()
fails with:
File "a.py", line 1, in
import submodule
ModuleNotFoundError: No module named 'submodule'
when lauching the script main.py.
Question: how should I import submodule in mymodule/a.py?

TLDR:
mymodule/a.py:
from . import submodule
# or
import mymodule.submodule as submodule
Once you run your main.py, python adds to your sys.path the path to main.py folder. Python can now search subfolders to find modules trying to be imported. Once you import a.py, python DOES NOT add anything else to sys.path, therefore, to be able import subfolders, you need to do either relative importing (from . import submodule), which you can do because you aren't running a.py as your main file, OR do a full import, doing import mymodule.submodule, since python can search starting on main.py folder.

Related

Move python modules to subdirectory without breaking imports

Original project foo:
/foo
/module_a
/module_aa
/module_b
...
Where in the original project, module_b contains imports such as import module_a
In the new project, bar I'd like to have:
/bar
app.py
/foo
/module_a
/module_aa
/module_b
...
However, this breaks the imports in the foo subdirectory:
File "/bar/foo/module_b"
import module_a
ModuleNotFoundError: No module named 'module_a'
What should I do here, to avoid having to update/modify all of the import statements in the foo directory?
This is what relative imports are for. Change
import module_a
to
import .module_a
so that module_b will look in its own package for module_a, rather than in a directory on the Python search path that no longer contains module_a.
This is the cleanest I was able to get it working without modifying any of the original codebase:
/foo/__init__.py
import sys
sys.path.append("../foo")
from module_a import some_function_a
from module_b import some_other_function_b
sys.path.remove("../foo")
app.py
import foo
foo.somefunction_a()
foo.some_other_function_b()

ImportError:How to import function or class from parent directory [duplicate]

This question already has answers here:
How to fix "Attempted relative import in non-package" even with __init__.py
(22 answers)
Closed 8 months ago.
I am trying to import a class from parent directory to my script but I receive attempted relative import with no known parent packageerror, I have searched everywhere in the internet but still cannot fix the error. Here is my package structure:
A/
a.py
__init__.py
B/
__init__.py
c.py
Now assume I have class1 inside a.py module and I am trying to import it in the c.py module. I have tried:
from ..A.a import class1
But i get above error message I have tried to add the A folder to sys.path but still the same error. Can anyone explain how I can import a package from a function or class from parent directory to subdirectory (like from a.py to c.py)
The way I do this is my extending the path in the c.py file by appending it. Below is an example of this:
a.py (example module in the parent directory)
class class1:
def __init__(self):
print("This worked!")
c.py (example file invoking a.py in the parent directory)
# By importing the sys module, you can change many
# things including the system environment.
import sys
sys.path.append("../")
# Once you've added the parent directory, you can freely
# import as you would have normally.
from a import class1
instance = class1()
The reason why your .. didn't work is because imports starting with . or .. are for importing from within things being imported (the way I understand it). An example of this to use your example would be to add a d.py alongside a.py which could be imported from a.py by using from .d import *.

ModuleNotFoundError: Even with __init__.py file

I have 3 python file :
test.py
modules(folder) and in modules there 3 to files : module1.py module2.py init.py
test.py
./test.py
./modules
./modules/module1.py
./modules/module2.py
./modules/__init__.py
module1.py:
from module2 import temp
def print_temp():
print(temp)
if __name__=='__main__':
print_temp()
module2.py
temp =1
test.py
from modules.module1 import print_temp
print_temp()
When I run python test.py I got ModuleNotFoundError: No module named 'module2'
How can I fix that please?
When you import a module in Python, it searches the PYTHONPATH for a module / package with that name. But it doesn't search inside directories so you have to specify.
If you want to be able to run modules.module1 directly (as well as import it) then you must use the full path:
from modules.module2 import temp
But if you just want to be able to import the module and not run it directly it is better to use a relative import as it will still work even if the name of the package is changed:
from .module2 import temp

Python: import from other directory - name is not defined

I looked to several related questions:
Importing python file from other directory
and
how to import module from other directory in python?
but they do not really solve my problems.
So I have
|-1.py
|-my_app
|-a.py
|-b.py
From 1.py I did:
import sys
sys.path.insert (0, './my_app/')
from a import *
and I have the error: name a is not defined.
How could I call the class and functions I defined in a.py and b.py from 1.py?
Many thanks
You need to have an __init__.py file (it can be empty) under the my_app directory for it to be an importable package.

Python unittest failing to resolve import statements

I have a file structure that looks like the following
project
src
__init__.py
main.py
module.py
secondary.py
test
test_module.py
module.py
import secondary
x = False
secondary.py
pass
test_module.py
from unittest import TestCase
from src import module
class ModuleTest(TestCase):
def test_module(self):
self.assertTrue(module.x)
Invoking python3 -m unittest discover in /project/ gives an error:
File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
from src import module
File "/Users/Me/Code/project/src/module.py", line 1, in <module>
import secondary
ImportError: No module named 'secondary'
What can I do so that secondary.py is imported without error?
In Python 3 (and Python 2 with from __future__ import absolute_import), you must be explicit about what module you want when importing another module from the same package. The syntax you're using in module.py (import secondary) only works if secondary is a top-level module in a folder in the Python module search path.
To explicitly request a relative import from your own package, use from . import secondary instead. Or, make an absolute import, using the name of the package as well as the module (from src import secondary, or import src.secondary and use src.secondary elsewhere the module instead of just secondary).
Try adding this to the top of the test file
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Note: Depending on the project structure we have to specify the root folder

Categories