Why does this import give me an error message when trying to import from 2 local modules? - python

I have the following code structure:
Graph API/
│── main.py
├── helper_functions/
├── defines.py
├── insights.py
insights.py imports 2 functions from defines.py at the beginning:
from defines import getCreds, makeApiCall
It then uses "makeApiCall" for this function:
def getUserMedia( params ) :
// Some code about url endpoints etc.
return makeApiCall( url, endpointParams, params['debug'] ) # make the api call
I want to use the getUserMedia function in the main.py script, so I import it with:
from helper_functions.insights import *
But I get the error:
Traceback (most recent call last):
File "/Users/Graph_API/main.py", line 1, in <module>
import helper_functions.insights
File "/Users/Graph_API/helper_functions/insights.py", line 1, in <module>
from defines import getCreds, makeApiCall
ModuleNotFoundError: No module named 'defines'
What leads to this error? When I use the getUserMedia function within insights.py it works fine. I already tried importing defines.py to main.py as well, but I get the same error.
I am pretty new to programming, so I would really appreciate your help :)

You should replace
from defines import getCreds, makeApiCall
With
from helper_functions.defines import getCreds, makeApiCall
Or
from .defines import getCreds, makeApiCall
You must give a path either from project directory as in the first example, or from the relative path from the insights file by adding a dot.
You could also consider adding init.py to the helper_functions folder. Checkout here: What is __init__.py for?

Related

Python ModuleNotFoundError: No module named 'classes'

This is the structure of my project at the moment.
classes/
├─ __init__.py
├─ card.py
├─ find.py
├─ player.py
├─ table.py
.gitignore
main.py
My __init__.py:
from .card import *
from .player import *
from .table import *
The problem is when I want to import from example player to table.py,
like this:
from classes import Player
from classes import Card, CardType, CardValue, HandValue
I get the following error message:
Traceback (most recent call last):
File "/home/adrian/Desktop/Programozas/Poker/classes/table.py", line 1, in <module>
from classes import Player
ModuleNotFoundError: No module named 'classes'
Do you have any idea?
Notice that this error is occurring in ".../classes/table.py", line 1, as you are trying to import classes.Player when both table.py and player.py are contained in classes. To do this in table.py, you would use from .player import Player just like you did in __init__.py (instead of from classes import Player).
Anything at the same level or above classes can be done using this method, but anything defined inside classes cannot call up to classes, as anything therein does not even know classes exists.
Edit: if you need to be able to run both main.py and table.py, you could do something like:
# in table.py
try:
from player import Player # this should work when running table.py directly
except:
from .player import Player # this should work when running main.py (it's a relative import)

ModuleNotFoundError when using a function from a custom module that imports another custom module

I have a folder structure similar to this (my example has all the necessary bits):
web-scraper/
scraper.py
modules/
__init__.py
config.py
website_one_scraper.py
Where config.py just stores some global variables. It looks a bit like:
global var1
var1 = "This is a test!"
Within website_one_scraper.py it looks like this:
import config
def test_function():
# Do some web stuff...
return = len(config.var1)
if __name__ == "__main__":
print(test_function)
And scraper.py looks like this:
from module import website_one_scraper
print(website_one_scraper.test_function())
website_scraper_one.py works fine when run by itself, and thus the code under if __name__ == "__main__" is run. However, when I run scraper.py, I get the error:
ModuleNotFoundError: No module named 'config'
And this is the full error and traceback (albeit with different names, as I've changed some names for the example above):
Traceback (most recent call last):
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\satellite_scraper.py", line 3, in
<module>
from modules import planet4589
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\modules\planet4589.py", line 5, in
<module>
import config
ModuleNotFoundError: No module named 'config'
Also note that In scraper.py I've tried replacing from modules import website_one_scraper with import website_one_scraper, from .modules import website_one_scraper, and from . import website_one_scraper, but they all don't work.
What could the cause of my error be? Could it be something to do with how I'm importing everything?
(I'm using Python 3.9.1)
In your website_scraper_one.py, instead of import config.py try to use from . import config
Explanation:
. is the current package or the current folder
config is the module to import

Error when importing python module from folders

I have a following directory structure:
source
source_1.py
__init__.py
source1.py has class Source defined
source1.py
class Source(object):
pass
I am able to import using this
>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>
However when trying to import using the below method it fails.
>>> from source import *
>>> source1.Source
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined
Please let me know how can we use the 2nd import ?
For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:
__all__ = ["source1"]
See the Python documentation for Importing * From a Package.

Python module not found because import statement is in other file than the one being executed

In the following structure:
src:
model:
- boardmodel.py
- tests.py
exceptions:
- exceptions.py
- visual.py
I'm running visual.py from the terminal. In my boardmodel.py, I have the following import:
from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
This line causes an error when running visual.py:
Traceback (most recent call last):
File "visual.py", line 3, in <module>
from model.boardModel import Board
File "/Users/sahandzarrinkoub/Documents/Programming/pythonfun/BouncingBalls/balls/src/model/boardModel.py", line 5, in <module>
from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
ModuleNotFoundError: No module named 'exceptions'
What is the correct way to solve this problem? Should I change the import statement inside boardmodel.py to from model.exceptions.exceptions import ZeroError....? That doesn't feel like a sustainable solution, because what if I want to use boardmodel.py in another context? Let me her your thoughts.
EDIT:
I changed the structure to:
src:
model:
- __init__.py
- boardmodel.py
- tests.py
exceptions:
- __init__.py
- exceptions.py
- visual.py
But still I get the same error.
Place an empty file called __init__.py in each of the subdirectories to make them packages.
See What is __init__.py for? for more details
Then, within boardmodel.py you need to either use relative imports
from .exceptions.exceptions import ...
or absolute ones (from the root of PYTHONPATH)
from model.exceptions.exceptions import ...
When you execute a script from the command line, the directory containing the script is automatically added to your PYTHONPATH, and becomes the root for import statements
You are not at the root of your package so you need relative import.
Add a dot before exceptions:
from .exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
One dot mean "from the current directory"…

Importing modules from different directories

I have a problem importing a module:
It is under this directory ./dao and the code that calls it is here ./core. Schematically represented as:
rnaspace/
__init__.py
core/
__init__.py
logger.py
dao/
__init__.py
storage_configuration_reader.py
This is the error message:
Traceback (most recent call last): File "logger.py", line 21, in <module>
from rnaspace.dao.storage_configuration_reader import storage_configuration_reader ImportError: No module named rnaspace.dao.storage_configuration_reader
This file it is there /rnaspace/dao/storage_configuration_reader.py and in the same folder the __init__.py file as follows:
""" Package dao
Gathers files that access to the plateform data
"""
If I understood well this question, it should work. I think that the problem is that one is not the subdirectory of the other (or that the path is not exaclly that one), there is a way to go around it? Or need I to apply the solution to this question?
EDIT
The __init__.py file of the rnaspace folder:
import rnaspace.dao.storage_configuration_reader as scr
def update_conf(conf_path, predictors_conf_dir):
scr.update_conf(conf_path, predictors_conf_dir)
from rnaspace.dao.storage_configuration_reader import storage_configuration_reader
That is wrong because there is no "storage_configuration_reader" directory in "dao" directory
This is how it should be:
from rnaspace.dao import storage_configuration_reader
EDIT:
or this way:
import rnaspace.dao.storage_configuration_reader
I finally found the solution in another question, it is using the module imp.
I just needed to add the name of the module, and the absolute path where it was:
imp.load_source("storage_configuration_reader","./rnaspace/dao/storage_configuration_reader.py")

Categories