I am trying to work with python packages and modules for the first time and come across some import errors I don't understand.
My project has the following structure:
upper
├── __init__.py
├── upper_file.py # contains "from middle.middle_file import *"
└── middle
├── __init__.py
├── middle_file.py # contains "from lower.lower_file import Person, Animal"
└── lower
├── __init__.py
└── lower_file.py # contains the Classes Person and Animal
I can run middle_file.py and can create inside the file a Person() and Animal() without any problems.
If I try to run upper_file.py I get a ModuleNotFoundError: No module named 'lower' error.
However, I have no trouble importing Animal() or Person() in upper_file.py directly with from middle.lower.lower_file import *
If I change the import statement inside middle_file.py from from lower.lower_file import Person, Animal to from middle.lower.lower_file import Person, Animal I can successfully run upper_file.py but not middle_file.py itself (and pycharm underlines the import in middle_file.py red and says it doesn't know middle)
In the end, I need to access inside of upper_file.py a class that is located inside of middle_file.py, but middle_file.py itself depends on the imports of lower_file.py.
I already read through this answer and the docs but just don't get how it works and why it behaves the way it does.
Thanks for any help in advance.
You should use relative import to accomplish this. First link on Google I found some practical example that could help you understand better.
On middle_file try to use from .lower.lower_file import *. It should solve the issue on upper_file.
Related
As per title, I am trying to build a python package myself, I am already familiar with writing python packages reading notes from https://packaging.python.org/en/latest/tutorials/packaging-projects/ and https://docs.python.org/3/tutorial/modules.html#packages. These gave me an idea of how to write a bunch of object class/functions where I can import them.
What I want is to write a package like pandas and numpy, where I run import and they work as an "object", that is to say most/all the function is a dotted after the package.
E.g. after importing
import pandas as pd
import numpy as np
The pd and np would have all the functions and can be called with pd.read_csv() or np.arange(), and running dir(pd) and dir(np) would give me all the various functions available from them. I tried looking at the pandas src code to try an replicate their functionality. However, I could not do it. Maybe there is some parts of that I am missing or misunderstanding. Any help or point in the right direction to help me do this would be much appreciated.
In a more general example, I want to write a package and import it to have the functionalities dotted after it. E.g. import pypack and I can call pypack.FUNCTION() instead of having to import that function as such from pypack.module import FUNCTION and call FUNCTION() or instead of importing it as just a submodule.
I hope my question makes sense as I have no formal training in write software.
Let's assume you have a module (package) called my_library.
.
├── main.py
└── my_library/
└── __init__.py
/my_library/__init__.py
def foo(x):
return x
In your main.py you can import my_library
import my_library
print(my_library.foo("Hello World"))
The directory with __init__.py will be your package and can be imported.
Now consider a even deeper example.
.
├── main.py
└── my_library/
├── __init__.py
└── inner_module.py
inner_module.py
def bar(x):
return x
In your /my_library/__init__.py you can add
from .inner_module import bar
def foo(x):
return x
You can use bar() in your main as follows
import my_library
print(my_library.foo("Hello World"))
print(my_library.bar("Hello World"))
I did everything to resolve this issue.
I am a beginner with python. My Folder structure:
├─conversational-datasets-master-opensubtitles/
└── conversational-datasets-master/
└── opensubtitles/
└── create_data.py
└── create_data_test.py
in opensubtitles folder, I have two files
The first one is create_data.py which is for the train
the second one is create_data_test.py which is for testing
So the Question is
Whenever I am trying to run the create_data_test.py it shows this error (module not found error)
File "C:\Users\suppo\Desktop\conversational-datasets-master-opensubtitles\conversational-datasets-master\opensubtitles\create_data_test.py", line 15, in <module>
import opensubtiles.create_data.py
ModuleNotFoundError: No module named 'opensubtiles'
Try changing your import statement in create_data_test.py
from:
import opensubtitles.create_data.py
to:
import create_data
I think you just got a typo here ...
import opensubti t les.create_data.py
There are several posts of importing modules and classes in python. Take a look here... hope it helps
How to import the class within the same directory or sub directory?
from opensubtitles import create_data
from opensubtitles import create_data_test
This should work.
But if you are in the root folder, you may have to use joinpath, since there are hyphens in the folder names.
numpy.random.randn(100)
I understand numpy is the name of the imported module and randn is a method defined within the module but not sure what .random. is
Thanks and happy new year!
#Yann's answer is definetly correct but might not make the whole picture clear.
The best analogy for package structure are probably folders. Imagine the whole numpy package as big folder. In said folder are a bunch of files, these are our functions. But you also have subfolder. random is one of these subfolders. It contains more files (functions) who are grouped together because they have to do with the same thing, namely randomness.
numpy
├── arccos
├── vectorize
├── random
│ ├── randn
│ ├── <more functions in the random subfolder>
│ <more functions in the numpy folder>
The .random part is a module within numpy,how you can confirm this is to use the python interpreter
#first import numpy into the interpreter
import numpy
#this is so the interpreter displays the info about the random module
numpy.random
Output should be something like "<module 'numpy.random' from 'path to module'>
I have searched related questions and tested many solutions there, for example,
I found [a solution here]:https://askubuntu.com/a/470989/608783, but I found it does not work in my case...
I have the following file structure:
Folder1
Folder2
__init__.py
model.py
Folder3
__init__.py
test.py
In model.py I defined a class:class mymodel(), then in test.py I wanna to use mymodel, so I tried from ..Folder2 import mymodel, from ..Folder2.model import mymodel, but all failed with error ValueError: Attempted relative import in non-package.
What should I do? Thanks for any advice.
Edit: I am very sorry for not list out _init_.py files, they are indeed included in the Folder2 and Folder3. However, the content of them are different from which proposed by #anekix's solution.
The following are from my possibly wrong setting:
__init__.py in Folder2: from .model import mymodel
__init__.py in Folder3: empty
What is wrong with my two __init__.py, thank you again.
Update: One way to solve this problem is by set all __init__.py to empty and then follow #jeffy proposed solution. Another way is by #anekix proposed solution, which should also works for this kind of problem(you should have a try) although not in my case, possibly because the whole project of mine is too messy.
This could work:
import sys
sys.path.append("/path/to/Folder1")
from Folder2.model import classname
you should make both subfolders as a package(by creating __init__.py in both subfolders) for proper management and imports:
structure should be:
Folder1
Folder2
__init__.py
model.py
Folder3
__init__.py
test.py
inside folder2/__init__.py add this code below:
from model import *
# it imports everything defined in model.py so that
# you can access classes or functions from this python file
inside folder3/__init__.py folder3 add this code below:
from test import *
# it imports everything defined in test.py
Then from inside folder3 you can use the import as(assuming you have some file main.py in folder3) :
from folder2 import someClass
# someClass is a class defined in `model.py`
So steps are:
make `folder2` a package.
make `folder3` a package.
import using `folder1.someClass` or `folder2.someClass`.
By 'sibling' modules, I mean two submodules that exist at the same depth within a parent module.
I'm trying to create a flask project using Flask-Restful, and it recommends structuring the project using this schema:
myapi/
__init__.py
app.py # this file contains your app and routes
resources/
__init__.py
foo.py # contains logic for /Foo
bar.py # contains logic for /Bar
common/
__init__.py
util.py # just some common infrastructure
I really like this structure, but I'm not sure how to import something from the 'common' module into the 'resources' module. Can anyone help me out?
In common/__init__.py
from myapi.common.utils import A, B
In resource/foo.py
from myapi.common import A
You can also relative imports in __init__.py like from .utils import A.