How to import a python function from a sibling folder - python

This question has been asked before. Even though I couldn't get an answer that solves this issue.
I have the following directory and subdirectories:
I have a function hello() in test1.py that I want to import in test2.py.
test1.py:
def hello():
print("hello")
test2.py:
import demoA.test1 as test1
test1.hello()
Output:
Traceback (most recent call last):
File "c:/Users/hasli/Documents/Projects/test/demoB/test2.py", line 1, in <module>
import demoA.test1 as test1
ModuleNotFoundError: No module named 'demoA'
This is exactly as explained in https://www.freecodecamp.org/news/module-not-found-error-in-python-solved/ but I can't access hello()
I am using python 3: Python 3.8.9

You need to add demoA to the list of paths used for import.
import sys
sys.path.append('..')
import demoA.test1 as test1
test1.hello()

Related

How can I write the python import statements, such that the file works from both inside and outside its package? [duplicate]

This question already has answers here:
Relative imports for the billionth time
(12 answers)
Closed 1 year ago.
Here's a file structure I'm working with:
package_example/
main.py
the_package/
__init__.py
pkg_file_1.py
pkg_file_2.py
Here are the files:
# main.py
from the_package.pkg_file_1 import foo_1
def main():
foo_1()
if __name__ == "__main__":
main()
# pkg_file_1.py
from the_package import pkg_file_2
def foo_1():
print("this is the second version, foo_1")
pkg_file_2.foo_2()
if __name__ == "__main__":
foo_1()
# pkg_file_2.py
def foo_2():
print("this is foo_2")
If I run main.py, everything works fine.
But if I run pkg_file_1.py, I get:
Traceback (most recent call last):
File "the_package/pkg_file_1.py", line 1, in <module>
from the_package import pkg_file_2
ModuleNotFoundError: No module named 'the_package'
Obviously in this simplified example, it doesn't matter, since main.py and pkg_file_1.py run the same code.
But practically, I have test scripts baked into my package structure, so I can test the code in my new environment and data. But I'm scratching my head on how I'm supposed write import statements such that I don't get a ModuleNotFoundError from both inside or outside the package.
Edit: From pavel's suggest I tried changing pkg_file_1.py to:
from ..the_package import pkg_file_2
def foo_1():
print("this is the second version, foo_1")
pkg_file_2.foo_2()
if __name__ == "__main__":
foo_1()
But running that same file gives:
Traceback (most recent call last):
File "the_package/pkg_file_1.py", line 1, in <module>
from ..the_package import pkg_file_2
ImportError: attempted relative import with no known parent package
This is why we need relative import.
# pkg_file_1.py
from . import pkg_file_2
...
How to run main.py and pkg_file1.py from package_example dir:
python3 main.py
python3 -m the_package.pkg_file1

Is it possible to import a python file from outside the directory the main file is in?

I have a file structure that looks like this:
Liquid
|
[Truncate]
|_General_parsing
[Truncate]
.....|_'__init__.py'
.....|_'Processer.py'
.....|'TOKENIZER.py'
|_'__init__.py'
|_'errors.py'
[Truncate]
I want to import errors.py from Processer.py. Is that possible? I tried to use this:
from ..errors import *; error_manager = errorMaster()
Which causes this:
Traceback (most recent call last):
File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 17, in <module>
from ..errors import *; error_manager = errorMaster()
ImportError: attempted relative import with no known parent package
[Finished in 0.125s]
I've seen this post, but it's no help, even if it tries to solve the same ImportError. This isn't, either (at least not until I edited it), since I tried:
import sys
sys.path.insert(1, '../Liquid')
from errors import *; error_manager = errorMaster()
That gives
Traceback (most recent call last):
File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 19, in <module>
from errors import *; error_manager = errorMaster()
ModuleNotFoundError: No module named 'errors'
[Finished in 0.162s]
EDIT: Nevermind! I solved it! I just need to add .. to sys.path! Or . if .. doesn't solve your problem. But if those don't solve your problem: use some pathlib (came in python3.4+) magic and do:
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent))
or, if you want to use os: (gotten from this StackOverflow answer)
import os
os.path.join(os.path.dirname(__file__), '..')
I solved it! I have to add .. to sys.path instead

Simple case of __init__.py and import giving mysterious module not found

I've tried this from so many different angles but can't sort it out. Must be such a simple case. In Python 3.7.6:
Directory structure:
./modtest/
./modtest/__init__.py
./modtest/test1.py
./modtest/test2.py
test1.py:
import modtest
def x(i):
print(i)
y(i)
test2.py:
def y(i):
print(i)
__init__.py is an empty file.
When I attempt to run the code:
$ /Users/pitosalas/miniconda3/bin/python /Users/pitosalas/mydev/rsb_py/modtest/test1.py
Traceback (most recent call last):
File "/Users/pitosalas/mydev/rsb_py/modtest/test1.py", line 1, in <module>
import modtest
ModuleNotFoundError: No module named 'modtest
From what I read this should've worked. I'm sure there's something trivial wrong!
You are importing modtest in test1.py while this module itself resides inside of modtest. This can't be because modest wouldn't have yet been defined and added to the search path. So this is what you should have actually:
./modtest/
./modtest/__init__.py
./modtest/
./modtest/test2.py
./test1.py # this module must be outside of modtest

How to import a module from sub directory

I failed to import a module from sub directory in python. Below is my project structure.
./main.py
./sub
./sub/__init__.py
./sub/aname.py
when I run python main.py, I got this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
import sub.aname
File "/Users/dev/python/demo/sub/__init__.py", line 1, in <module>
from aname import print_func
ModuleNotFoundError: No module named 'aname'
I don't know it failed to load the module aname. Below is the source code:
main.py:
#!/usr/bin/python
import sub.aname
print_func('zz')
sub/__init__.py:
from aname import print_func
sub/aname.py:
def print_func( par ):
print ("Hello : ", par)
return
I am using python 3.6.0 on MacOS
There are several mistakes in your Python scripts.
Relative import
First, to do relative import, you must use a leading dots (see Guido's Decision about Relative Imports syntax).
In sub/__init__.py, replace:
from aname import print_func
with:
from .aname import print_func
Importing a function
To import a function from a given module you can use the from ... import ... statement.
In main.py, replace:
import sub.aname
with:
from sub import print_func
from sub import aname
aname.print_func('zz')
Probably the most elegant solution is to use relative imports in your submodule sub:
sub.__init__.py
from .aname import print_func
But you also need to import the print_func in main.py otherwise you'll get a NameError when you try to execute print_func:
main.py
from sub import print_func # or: from sub.aname import print_func
print_func('zz')

error when using import command in python

I'm new to python and now learning how to to import a module or a function, but I got these posted errors. The python code is saved under the name: hello_module.py
python code:
def hello_func():
print ("Hello, World!")
hello_func()
import hello_module
hello_module.hello_func()
error message:
Traceback (most recent call last):
File "C:/Python33/hello_module.py", line 9, in <module>
import hello_module
File "C:/Python33\hello_module.py", line 10, in <module>
hello_module.hello_func()
AttributeError: 'module' object has no attribute 'hello_func'
You cannot and should not import your own module. You defined hello_func in the current namespace, just use that directly.
You can put the function in a separate file, then import that:
File foo.py:
def def hello_func():
print ("Hello, World!")
File bar.py:
import foo
foo.hello_func()
and run bar.py as a script.
If you try to import your own module, it'll import itself again, and when you do that you import an incomplete module. It won't have it's attributes set yet, so hello_module.hello_func doesn't yet exist, and that breaks.

Categories

Resources