ImportError on Python - python

I'm new to python and I'm having this problem that I can't figure it out.
My file structure is:
enter image description here
On Criador.py I have several functions, for example:
def doSomething():
pass
def doSomethingElse():
pass
and Im trying to use one of this functions on the Controller.py file:
The first thing I did was, on the Controller.py:
import Controller.Criador
and then tried to use that function as:
Controller.Criador.doSomething()
After running Controller.py, I got this error:
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
I tried several other things, like:
from . import Criador
or
from Controller.Criador import doSomething
or
from Controller import Criador
and nothing helped, just changed the errors to:
ImportError: cannot import name 'Criador'
and
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
and
ImportError: cannot import name 'Criador'
Can someone give me a light about this? I'm using PyCharm and it does not give me any error when I declare the imports, only when I run the file

If Controller.py and Criador.py are in the same folder, you can do this inside Controller.py:
import Criador
Criador.doSomething()

Related

Python: ModuleNotFoundError: No module named ''

I am running python code in docker.
I have the following file structure:
-my_dir
-test.py
-bird.py
-string_int_label_map_pb2.py
-inference.py
inference.py:
import test
import bird
from string_int_label_map_pb2 import StringIntLabelMap
test.py and bird.py both contain this code:
print('hello world!')
def this_is_test():
return 'hi'
In inference.py 'import test' throws no error(but 'hello world!' is never printed).
'import bird' throws: ModuleNotFoundError: No module named 'bird'. Finally
'import string_int_label_map_pb2 ' throws: ModuleNotFoundError: No module named 'string_int_label_map_pb2 '
Note: bird.py and test.py are not simultaneously existing in the dir, they are depticted as such only to make my point. They exist only when I rename the same file to either name to test if the name itself was to blame.
If one or the other is not in the folder but you still have import test and import bird in the inference.py, that's your issue. Python is trying to import both files but can not find the file.
I added bird.py to /worker/ (the WORKDIR path configured in the dockerfile) and sure enough "Hello world!" printed.
So the issue was that inference.py was not searching its parent dir for imports as I thought, but rather the path configured in WORKDIR.
Still don't understand why import test gave no errors since there was never a test.py file in /worker/.
I also had this problem, how did I solve the problem?
For example.
My directory:
--Application
---hooks
----init.py
----helpers.py
---model
----init.py
----model_person.py
In script model_person.py
import sys
sys.path.append('../')
from hooks.helpers import *
Thats all

Python import statement is not working for parent package

I'm using Python 3.9.5.
Based on this post, I'm trying to reuse some functions from the parent directory. Here's my code hierarchy:
github_repository
src
base
string_utilities.py
validation
email_validator.py
I also have __init__.py in all folders. In ALL of them.
Here's the string_utilities.py content:
def isNullOrEmpty(text: str):
return text is not None and len(text) > 0
And here's the email_validator.py content:
from src.base import string_utilities
def is_email(text: str):
if string_utilities.isNullOrEmpty(text):
return False
# logic to check email
return True
Now when I run python email_validator.py, I get this error:
ModuleNotFoundError: No module named 'src'
I have changed that frustrating import statement to all of these different forms, and I still get no results:
from ...src.base import string_utilities
which results in:
ImportError: attempted relative import with no known parent package
import src.base.string_utilities
Which causes compiler to not know the isNullOrEmpty function.
import ...src.base.string_utilities
Which results in:
Relative imports cannot be used with "import .a" form; use "from . import a" instead
I'm stuck at this point on how to reuse that function in this file. Can someone please help?

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

import of Python class from module in package

My structure looks something like this:
project/->
app.py
checker/->
exc.py
anc.py
My files are simple:
# app.py
from checker.exc import ExampleClass
# checker/exc.py:
from anc import AnotherClass
class ExampleClass(AnotherClass):
print('Example')
# checker/anc.py:
class AnotherClass:
print('AAAA')
When I run exc.py inside checker folder everything works ok, same when
I run app.py with module from package checker everything works perfect.
But when I run app.py which uses class from checker.exc, and exc need anc. I have an error ModuleNotFoundError: No module named anc
Realise this is a duct tape solution.
Change exc.py to:
try:
from anc import AnotherClass
print('abs import')
except ModuleNotFoundError:
from .anc import AnotherClass
print('rel import')
class ExampleClass(AnotherClass):
print('Example')
That way you can use absolute import when debugging, for instance, but rely on relative import when importing it running app.py on it's own.
The order in which you attempt to import them should reflect the expected use, with the one most expected to be used being attempted first. The error is the same if you switch the attempts.
Since the code is being run from the project folder, in order for exc.py to find anc.py you need to change exc.py to the following:
from .anc import AnotherClass
class ExampleClass(AnotherClass):
print('Example')
As berna1111's comment suggests, this may cause problems when running exc.py directly.

Python ImportLib 'No Module Named'

I'm trying to use a variable as a module to import from in Python.
Using ImportLib I have been successfully able to find the test...
sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)
... and by printing the select_module I can see that it succesfully finds the script:
<module 'script1' from 'C:\\Users\\.....">
However, when I try to use this variable in the code to import a module from it:
from selected_module import run
run(1337)
The program quits with the following error:
ImportError: No module named 'selected_module'
I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?
Import statements are not sensitive to variables! Their content are treated as literals
An example:
urllib = "foo"
from urllib import parse # loads "urllib.parse", not "foo.parse"
print(parse)
Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:
# ... your code here
run = selected_module.run # bind module function to local name

Categories