ModuleNotFoundError even though the module is recognized - python

My folder structure is:
|-fastapi
|-app
|-calc.py
|-tests
|-mytest.py
In mytest.py I'm trying to import calc.py, like this:
from app import calc
In mytest.py, app and calc are both highlighted green, and when I hover over them, it says (module). It seems to be recognized, but when I run it, I get the error. I know this has been asked before but I haven't found the solution.

I create the exact same file hierarchy in my machine and then made a random function called hello() in the calc.py file, this is the code which successfully calls the function in app folder,
import sys
sys.path.append('../')
from app import calc
print(calc.hello())
maybe I misunderstood the question so here's a much detailed answer with respect to behaviour of the IDE when importing a module,
as we can see in the image below, we can import a wrong module in almost any python IDE and it won't give an error until or unless it is a smart IDE with preinstalled extensions to check as it does for other scripting languages or it won't give an error just yet, below it can be seen,
we can see that IDE doesn't show any error just yet doesn't even give a warning of any sort, but when you run the code you get this error, this is the same error which OP gets when they run their code,
this can be tried for from app import calc and it will give you same error as it gives for from imagination import dreams.
but when you add couple lines of code which are,
import sys
sys.path.append('../')
it starts to import in a similar way which OP was trying to do but only with the additional lines of code, why?
This is because they have their files in parallel to each other, which can be seen in the folders which they mention,
|-fastapi
|-app
|-calc.py
|-tests
|-mytest.py
perhaps this answers the concern which a comment mentions, I took the liberty to assume a few things but more or less this is what's happening, please rectify this answer.

You need __init__.py in each folder to mark it as a package. It can be an empty file. Check the docs for more information.

You should check and ensure you do not have an already existing file named 'calc.py'.

Related

Python ModuleNotFound in file when it is called from other directory, but not when it is directly executed

So bascically I have a filestructure lile
directory
/subdirecrory
>view.py
>view_model.py
>controller.py
>main.py
My controller looks something like:
import view
startChat()
#^ for testing, to see if the import works when directly calling file
def startChat(socket):
#datahandling
view.startGui()
My view is simply:
import tkinter
def startGui():
gui = tkinter.Tk()
gui.mainloop()
And lastly, the main is:
from subdirectory import controller
if __name__ == '__main__':
controller.startChat(s)
I removed all the meat to reduce myself to the GUI starting. When I run the controller everything works as it should, if I put the main into the subdirectory it also works.
Important note: This is a fix, but not what I want. I will soon again need different files, folders and directories and unless there is no way to do this would like to know a solution to this problem that doesn't involve putting everything in the same folder.
If I run the program as it is right now, it will execute the controller.py, if i put a print() above the imports (of which i have a few, like sys and time, which all work), it will only fail once it reaches the import view
The errormessage is a:
Exception has occurred: ModuleNotFoundError
No module named 'chat_view
My theory is that when calling from another directory the runtime has no info about the folder it is put into, and can't do what would happen if I started it from the directory. Which is what I tried to fix in the first and third solution of the other things I have tried so far:
Putting "from subdirectory import view" but that didn't work
Looking up this question on Google to no success
Importing the view in the main
Adding an init.py into the /subdirectory
As you might see I am more trying around and guessing and I think it's unlikely I find the solution to this anytime soon, so I thought to ask here. I wouldn't be surprised if this is a duplicate, but I wasn't able to find what I was looking for.
Instead of an absolute import, you can use a relative import in your controller
from . import view
the dot means it will search in the same folder.
A weird thing worked that I hope someone else can EXPLAIN, but here for future reference what I did was:
I put all the files into a directory names "src" like
directory/src #this is how it is displayed in VSC, idk why it is not displayed as extra directory but like this?
main.py
/subdirectory
__init__.py
#other files
I did this to clean up my code but then in the controller the import import view didn't work anymore, so when I changed it to from subdirectory import view (which earlier caused an error) it now works calling it from the main.py
This is bizarre to me as all I did was add a directory, but it works, so, yes. This is the accepted answer for now, until someone explains it better than me then I will switch it

Does anyone using Repl.it? Not working another python file

As you know, there is Main.py and we can make a multiple files
even yesterday, I made a new file(not Main.py) named so.py and it works well when I press run button
but today I try to run like that there is nothing on the result screen
Well if it was working yesterday and not today, then it might be a connection issue when you were trying to run the code this time around. That sometimes happens to me as well, but a refresh or two should work.
You've probably done that already so try copying your code to a new repl and try again.
Check for missing code you might have deleted, like an import statement in main.py which would explain why code isn't showing up. Assuming you're calling code from a different file or package.
Kindly note that your question isn't very clear so more details pertaining to your question would be appreciated.
Okay, one thing to clarify is that repl always runs main.py so you'll have to enter the following to have access to functions from the other files.
import indeed
import so
If you're expecting to run so.py by itself on repl I don't think it's going to work.
Now that you have them imported you can use any function in so.py by using the . notation.
e.g:
so.print_hello()
Or you could also import a specific function into main.py using this method
from so import function_name, function2_name, etc...
To make it as clear as possible here is example code if I had done it.
In so.py
def print_hello():
print('Hello, World!')
In main.py
import so
so.print_hello()
Output will be
Hello, World!

Why does 'from file import function_name' fail in my interactive Python session but works in a script?

I am moving common functions shared between a couple of Python files in to a third common_commands.py file. To test the functions I imported a couple of functions using:
from common_commands import func_one, func_two
But got this error:
ImportError: cannot import name 'func_two'
So I tried only importing func_one and that worked fine but then importing just func_two gives me the same error again! Why?! And to make things even confusing, the exact same import line from above works perfectly fine when I put it in the scripts I am refactoring.
What is causing this odd behavior?
TL;DR:
I had renamed func_twosince starting my interactive shell. Starting a new shell got things working.
What I learned:
I don't understand all the inner workings of the interactive shell and what happens when you call import, but after quitting and starting a new shell the exact same import call worked.
When I started the shell func_two was old_func_two but then I decided to rename it, and then I tried to import it with the new name, and that failed. After scratching my head and doing some google foo I found nothing that helped in my case and tried starting a new shell and it worked!
So I decided to do a little more experimenting before asking this question and learned that I could rename the function as much as I wanted after starting the shell but only until I first imported the file in some way.
That is to say, as soon as I called from common_commands import func_one I can no longer rename any functions and import them with the new name, since the file has already been imported. I can, however, still import old_func_two. I also tried changing the 'guts' of func_two after importing it and then importing it again and it kept the original behavior. So from what I can tell, the first time you import a file (not a function or class, but the whole file) it is cached and all future imports are run on the cached version, not the real file on disk.
So, even if you only import func_one i.e. from common_commands import func_one and then rename or change func_two and then import it, you'll have to use the original name of func_two and you'll get the original functionality as well, even though you didn't explicitly import it earlier.

Properly Resolving Import Errors with Directories

My question here is more about the appropriate way to resolve import errors in a way that is considered "Pythonically correct," if there is such a term. I thought I had solution to my problem (posted below and updated), but even that turns out not work.
Context
I have looked at various responses to this (like How to resolve import errors in python?) and I think I've done those things, but I still have the question that I'm posting here.
Example
I have the following structure:
pacumen
rules
__init__.py
pacman_rules.py
pacman.py
game.py
In pacman_rules.py I have a class:
class PacmanRules:
....
In my pacman.py file, I have the following import statement:
from rules.pacman_rules import PacmanRules
Mind you, this was auto-generated by PyCharm. So PyCharm shows me that it resolves just fine.
However, when I run pacman.py from the command line, I get the following error:
ImportError: cannot import name PacmanRules
I have no idea why that's happening in this case, given the lines of code.
In pacman.py I also have this statement:
from game import GameStateData
That one is working just fine. Notice that the class GameStateData comes from my game.py file. So I'm guessing my issue is that I'm trying to import from a file in a different directory rather than from a file in the same directory.
Possible Solution (Update: Does Not Work)
So then I tried this import instead:
from rules import pacman_rules
That seems to work, but it requires me to change lines like this:
PacmanRules.getLegalActions(self)
to lines like this:
pacman_rules.PacmanRules.getLegalActions(self)
That just feels messy to me and seems to defeat the purpose of importing a class name so I can use it without having to preface it.
But, as it turns out, this doesn't work either. This just gets a different error:
ImportError: cannot import name pacman_rules
So that's my question here. Most questions seem to revolve around how to fix the issue; as it turns out I don't even have a "fix."
What I'm curious about is why the initial approach doesn't work (especially since PyCharm generates it) and if my proposed solution is the appropriate way to handle this.

IO error for saunter.ini while setting up py.Saunter

While setting up py.saunter on my system, I am getting an IO error for saunter.ini file.
Directory structure is exactly as shown in the example - https://github.com/Element-34/Py.Saunter-Examples
Below is the error message -
IOError: [Errno 2] No such file or directory: '/src/conf/saunter.ini'
ERROR: Module: Tests could not be imported
(file:/Users/.../PythonWorkspace/PySaunter/src/scripts/Tests.py)
I know there are lot of import related questions. Most of them suggest to add init.py if not already there. I have added init.py in every folder.
The code snippet which reads saunter.ini is as below -
def configure(self, config = "saunter.ini"):
self.config = ConfigParser.SafeConfigParser()
self.config.readfp(open(os.path.join("conf", config)))
Any help would be appreciated...
There isn't really enough here to diagnose the problem. But, in the examples directory there is actually two different projects (ebay and sauce) -- you have to be in one of them, not the top.
Also, Py.Saunter won't create saunter.ini for you. You need to create it (most easily by renaming saunter.ini.default).
Oh, and don't try and run it from checkout from Github -- it really does need to be from an egg. If there are bits missing from http://element34.ca/products/saunter/pysaunter which prevent you from getting started, let me know and I'll modify the page.
(Now if only I remembered by SO credentials...)
I was running the project from eclipse as a unit-test which is why it was throwing import errors.
Py.Saunter is an opinionated framework and does not support eclipse or any other IDE at this point.
It works fine when executed from the command line as illustrated in the site - http://element34.ca/products/saunter/pysaunter
Should ensure to execute from the home directory.

Categories

Resources