Python not able to import module - python

I have quite a number of different file which I want to use to create an API. The files are :
app.py -- main file
utils.py -- utilities file
recorder.py
consts.py
submitter.py
All of these files have a dependency on one another. However, when I try to import them in a particular file ( for ex - importing consts in recorder.py, I am getting error saying The module consts is not found.
I am importing it using :
from .consts import consts
Can someone tell me what am I doing wrong here, and how to solve this issue.
If i import it in the main app.py, it doesn't give any error. but it does when I want to access any consts in other files.
Thank you in advance
EDIT : Here is the folder structure :

When you say they are interdependent, that may be your issue. You cannot have two files that depend directly on one another with out some hacky solutions as youll run into the problem of importing one that tries to import the importer which tries to import the importee and so on forever.
Edit: i misunderstood how imports work, the problem comes from:
"If you import X from your main program, Python will load the code for
X and execute it. When Python reaches the import Y statement, it loads
the code for Y, and starts executing it instead.
At this time, Python has installed module objects for both X and Y in
sys.modules. But X doesn’t contain anything yet; the def spam
statement hasn’t been executed."
As stated in the link i included at the bottom of this response. The link also gives some possible solutions like changing when you import the different modules.
What we really need is to see the code for the files to understand how you are importing everything
this link should help you in your desire for circular dependency.

Related

Python file does not recognize imported functions from other Python files

I'm trying to make my code more organized by creating separate files for various functions. I'm testing out printing scenes of dialogue with a text scrolling code, and instead of keeping every line of dialogue in one file, I have moved it to a scene0.py file in the folder scenes. In that file, I define the function playscene0.
In a different folder called scenetext, I have a file called textstuff.py which contains the defined functions print_italics (which prints italics text), texttype (which makes each character type out individually like some video games do), and textscroll (which reads lists of dialog and formats it, plus timings with time.sleep).
That aforementioned scene0.py file uses from scenetext.textstuff import * to import the above functions, plus additional variables that go along with them (unique to that file). VSCode seems to initially recognize that all the functions being used in the playscene0 function have been successfully imported.
In my importtest file:
from scenes.scene0 import playscene0
playscene0()
This gives me:
NameError: name 'print_italics' is not defined
Though it very much is defined in the file it is derived from.
I've already looked into circular imports and how they cause problems, but that doesn't seem to be the cause here. I've tried importing both time and everything from scenetext.textstuff in the importtest file directly, but the problem persists.
Any suggestions are welcome, thank you
EDIT: After adding from scenetext.textstuff import print_italics to the importtest file, it gives me a different error upon running:
ImportError: cannot import name 'print_italics' from 'scenetext.textstuff' (/Users/[me]/vscode/VOYAGE/scenetext/textstuff.py)
Not sure what causes this.
You need to add an import to the importtest file - from scenetext.textstuff import print_italics, so that the function becomes "visible".
You should import the textstuff functions BEFORE you import the playscene function that uses them
from scenetect.textstuff import print_italics
from scenes.scene0 import playscene0
playscene0()

Change python import name without changing code and file structure

I currently have a package A from someone else that uses an import syntax like import A in its code, e.g. A/B/C/xx.py.
What I want to do is to reference package A in my project X, forming a package structure X/A like this. However, I need to meet the following two requirements:
not modify a single line of code in A
import A is not valid anywhere else unless it is in package X.
I spent a few days looking for a workaround, but none of it worked. All methods that do not throw an error result in import A being available everywhere else.
You could create a my_requirements.py file that does all imports leaving out module_name or again deleing module_name under the conditions that you demand. You would then just have to:
import my_requirements

Python Module not found error - not getting fixed

So I am pretty new with Python. I've been working on running with a code similar to one I hope to build myself (so a reference code). Aside from some bugs I need to work out with invalid syntax, all seems to work except for one issue with one particular .py file I have.
My structure is this:
MoodForecasting -> eval -> nsga_two.py
I do have _init_.py in eval folder though, so I'm not sure why this block of code isn't working.
I am trying to load one particular fucntion from it, so the structure should look like this
from nsga_two import PatientProblem
Unfortunately, I keep getting the error ModuleNotFoundError: No module named 'nsga_two'.
I checked nsga_two.py itself and found that it couldn't load inspyred. I went in and was able to fix this. So, nsga_two.py runs fine on its own. However, I cannot import it into the main script I will be working with.
Some extra details: I am working with the IDE Spyder with Python Custom Version 3.7.9.
I'm not sure if it is an issue with Spyder or just how I am loading in my working directory. (Most of my coding experience is in MatLab and R so having an IDE similar to RStudio and MatLab is the reason I chose to work in Spyder)
Edit:
I got a syntax error when using from eval import nsga_two.PatientProblem. Python didn't like the period. So, I instead tried it with no period. I got the error cannot import name 'nsga_twoPatientProblem' from 'eval' (C:\Users\name\Desktop\MoodForecasting-master\MoodForecasting-master\eval\__init__.py). I don't know why. But doing from eval import nsga_two works. nsga_two.py only consists of PatientProblem. This solve should be ok for this purpose. I'm just not sure why this could be happening.
Suppose your structure is like:
MoodForecasting-master/
main.py
eval/
__init__.py
nsga_two.py
When you run the main script to import something, the directory of that script is added to the module search path sys.path, .../MoodForecasting-master/ in this case. from nsga_two import PatientProblem raised ModuleNotFoundError because nsga_two.py is not in that directory.
As Iguananaut said, from eval import nsga_two.PatientProblem in the first comment has never been a valid statement. The valid ways of doing so are:
import by from eval import nsga_two and use as nsga_two.PatientProblem().
import by from eval.nsga_two import PatientProblem and use as PatientProblem() directly.
Module search starts from .../MoodForecasting-master/, first option go to .../MoodForecasting-master/eval/ to find nsga_two.py, second option go to .../MoodForecasting-master/eval/nsga.py to find attribute named PatientProblem.
The correct syntax would be:
from package.module import function
so:
from eval.nsga_two import PatientProblem

Does a package 'see' itself in __init__.py?

I have a flask app with the root folder called project_folder.
A code snippet from the __init__.py file of this project_folder package:
#jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
jti = decrypted_token['jti']
return project_folder.Model.RevokedTokenModel.is_jti_blacklisted(jti)
from project_folder.Controller.root import root
from project_folder.Controller import auth_controller
from project_folder.Controller import item_controller
Now the interesting thing is, that the project_folder package naturally has other smaller packages itself, which I'm importing to use them (for REST resources in this example). These are the last 3 lines, nothing throws an error so far.
But, if you take a look at the annotated function (in this example it always runs before some kind of JWT Token is being used), I am returning some inner package's function. Now when the logic truly runs this part the code breaks:
PROJECT_ROUTE\project_folder\__init__.py", line 38, in check_if_token_in_blacklist
return project_folder.Model.RevokedTokenModel.is_jti_blacklisted(jti)
NameError: name 'project_folder' is not defined
After thinking about it, it seems understandable. Importing from project_folder does import from the __init__.py file of the package, which is the actual file the interpreter currently is. So removing the package name prefix form the
return project_folder.Model.RevokedTokenModel.is_jti_blacklisted(jti)
to
return Model.RevokedTokenModel.is_jti_blacklisted(jti)
does not throw an error anymore.
The question is: Why is it only a problem inside the callback function and not with the last 3 imports?
This has to do with circular imports in python. Circular import is a form of circular dependency, created at the module import level.
How it works:
When you launch your application, python keeps a register (a kind of table) in which it records all the imported modules. When you call somewhere in your code a module, python will see in its registry if it has already been registered and loads it from there. You can access this registry via sys.module, which is actually a dictionary containing all the modules that have been imported since Python was started.
Example of use:
>>> import sys
>>> print('\n'.join(sys.modules.keys()))
So, since Python is an interpreted language, reading and execution of code is done line by line from top to bottom.
In your code, you put your imports at the bottom of your __init__.py file.
While browsing it, when python arrives at the line return project_folder.Model.RevokedTokenModel.is_jti_blacklisted(jti), it will look if the module exists in its register. Which is clearly not yet the case. That's why he raises an NameError: name 'project_folder' is not defined exception.

"No module named..." with certain project structure

I have the following project structure:
MainScript.py
ExampleFolder
├ MainImport.py
└ SecondaryImport.py
MainScript.py: import ExampleFolder.MainImport
MainImport.py: Import SecondaryImport
When I try to run MainImport.py it gets no errors, but when I try to run MainScript.py, I get an import error that says No module named 'SecondaryImport'.
My question is simple - is there any way that I can import only MainImport.py from MainScript.py without getting this error, and importing SecondaryImport.py? Thanks in advance!
I have also tried adding a blank file named __init__.py to the ExampleFolder, but the error still appears. I also read Python's official documentation, but I could not find the problem. Am I missing something? (:
I think using the statement import ExampleFolder.SecondaryImport would work.
If it does, the error might be happening because as mentioned in docs, import statements will usually start searching your main project directory where the python interpreter was called if your module is not in python itself.
Another way would be to use relative import statement like this:
import .secondaryimport in order to tell the python interpreter to look in the current directory. Hope this helps!
Taking a look at these links will help, I think (It helped me when I was stuck in a similar problem):
https://docs.python.org/3/library/sys.html#sys.path
https://realpython.com/absolute-vs-relative-python-imports/
I have also tried adding a blank file named __init__.py to the ExampleFolder
That's the way - you're creating a Python package from a directory that way. And with packages you have got namespace directory.file where file is a Python file also known as module in Python world.
Then you can do from mainscript.py:
from examplefolder import mainimport
For importing inside package you may use the following syntax inside mainscript.py:
import secondaryimport
and use it in that mainscript.py as:
sevondaryimport.SomeClass()
or you may just do:
from secondaryimport import SomeClass
and use it like:
SomeClass()
Btw, use lowercase in all the cases except classes names - only they should have CamelCase names.

Categories