I have the following structure:
app/
code/
script.py -- has a function called func
main.py
How can I import script.py from main.py ?
I tried from code.script import func and I got ModuleNotFoundError: No module named 'code.script'; 'code' is not a package
Place a __init__.py file in the code directory. This will allow your main.py code to import it as a module like you have tried there.
Indeed the best way is to add __init__.py in code directory because when a regular package is imported __init__.py file is implicitly executed and the objects it defines are bound to names in the package’s namespace.
FYI, as an alternative you can also to this in your main.py before the import:
import sys
sys.path.append("/path/to/script.py")
Related
There are lots of similar questions, but none of them seem to help me with this.
I have the following file structure:
rest_api
__init__.py
utils
__init__.py
config.py
foo
__init__.py
foo.py
I'd like to import the Config class from config.py, into foo.py. I attempt to run:
pipenv run python rest_api/foo/foo.py
I have tried numerous things, including adding the parent folder to PATH and using relative imports, but the import line always fails:
from rest_api.utils.config import Config
I get the following error:
ModuleNotFoundError: No module named 'rest_api'
I should mention that the __init__.py files are all empty. Not sure if they are neccessary, since I have Python 3.8.2.
Setup
test/
main.py
pkg/
a.py
__init__.py
main.py contains:
import pkg
pkg.a
__init__.py contains:
from . import a
main.py can be run without errors.
Question
Changing the content of __init__.py to
import a
gives the following error when running main.py:
Traceback (most recent call last):
File "C:/Users/me/PycharmProjects/test/main.py", line 1, in <module>
import pkg
File "C:\Users\me\PycharmProjects\test\pkg\__init__.py", line 1, in <module>
import a
ModuleNotFoundError: No module named 'a'
Interestingly, __init__.py can be executed directly with python __init__.py without errors.
What's going on?
When you run a python script, it's parent folder is added to sys.path
run main.py: sys.path[0] = '../test'
run init.py: sys.path[0] = '../test/pkg'
Your case: You try to "absolute-like" import a in __init__.py but the parent folder of a.py - which is '../test/pkg' - is not in the sys.path when you run main.py. This is why you get an error. However, your absolute import is incomplete as it should always start at the top level folder, e.g.
from test.pkg import a
Final answer to your question: You don't have to use relative imports!
See: PEP-8: Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path).
And keep in mind that relative imports don't work in a top-level-script when __name__ = "__main__", but from imported modules only.
You can learn more about absolute and relative imports here:
Absolute vs. explicit relative import of Python module
https://realpython.com/absolute-vs-relative-python-imports/
I suppose you are using Pycharm? Then that's one of the confusion cause.
For example, let's say your directory looks like this
project1
p1.py
test/
__init__.py
main.py
pkg/
a.py
__init__.py
If you run (F10) the main.py your default working directory will be project1/test, which does not contain the a.py so import a will not find anything.
But if you run (F10) the pkg/__init__.py your working directory will be project1/test/pkg which has the a.py, and it works like what you tested.
So in these situation, if you use from . import a it will look for the directory that file is, project1/test/pkg in this case, which will always work regardless your working directory.
I have a ROS package that I am working with and I am trying to import a python module from another directory in the same package. My file structure is the follow:
package/
src/
__init__.py
lab03/
map_helper.py
__init__.py
lab04/
foo.py
__init__.py
I want to use helper.py in foo.py
foo.py
from src.lab03 import map_helper as helper
However I am getting the following error:
from src.lab03 import map_helper as helper ImportError: No module named src.lab03
You need to add package directory to your sys path to be able to import packages
import sys
sys.path.append('../../../package')
from src.lab03 import map_helper as helper
Have you tried this?
from package.src.lab03 import map_helper as helper
My file stucture is :
top\
my_package\
__init__.py
functions.py
scripts\
test.py
main.py
I would like to import the content of functions.py in test.py.
In main.py, I can import functions.py with from my_package.functions import ....
I was expecting to be able to import functions.py in test.py with something like from ..my_package.functions import ... but it raises the following error :
SystemError: Parent module '' not loaded, cannot perform relative import
top directory shoudln't be a package because I want to be able to run main.py without being running a script in a package.
What is the proper/pythonic way import functions.py from test.py ?
I could add my_package to the PYTHONPATH, but my code would be less portable. I'm using Python 3.5
This is happening because as far as python is concerned my_package and scripts directories are not related to each other.
To solve your problem you can add __init__.py to your top directory and try using
from ..function import *
Suppose I have a project in the following structure
projectfoo/
|- mymodule/
|--|- __init__.py
|--|- library.py
|- preprocessor.py
and in the __init__.py in mymodule looks like this
from . import library #library itself has other functions
def some_function():
blar blar blar...
and the preprocessor.py would look like follows
import mymodule
def main():
something()
def something():
mymodule.some_function() # calls the function defined in __init__.py
if __name__ == '__main__':
main()
Then I started projectbar, which is using a lot of common code from projectfoo. So instead of copying and pasting code between projects, I wish to import projectfoo into project bar, as follows.
projectbar/
|- projectfoo/
|--|- mymodule/
|--|--|- __init__.py
|--|--|- library.py
|--|- preprocessor.py
|- index.py
So I am trying to import preprocessor in my index.py as follows
from projectfoo import preprocessor
However I am getting an error saying preprocessor.py is now unable to import mymodule.
ImportError: No module named 'mymodule'
Am I doing this correctly? I am using python3.4 running in ubuntu 14.04 in my setup.
EDIT: I also tried adding __init__.py to projectfoo, but I am still getting the same error
You are getting this error because you did not added the path of preprocessor as a library package
from sys import path as pylib #im naming it as pylib so that we won't get confused between os.path and sys.path
import os
pylib += [os.path.abspath(r'/projectfoo')]
from projectfoo import preprocessor
FYI: os.path will return the absolute path. but sys.path will return the path env. variable in system settings.
Hope it helps.
Try to add empty __init__.py to projectfoo folder.
You have to add an __init__.py file (can be empty) in your projectfoo/ folder to make it a valid module.
Then use relative imports to explicitly specify you're requesting the current module's submodule mymodule like this:
from .projectfoo import preprocessor
The . stands for the current module in which the file containing the import statement is located. Its parent module would be denoted as .., its "grandparent" would be ... etc.