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.
Related
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.
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
Hello everyone im currently learning python and i im having some problems importing modules and packages. Actually i think is more of a problem with vscode.
i have this package called "paquete" with a module (funciones) that i want to import to my "main" with some fuctions in it to test if it all works correctly but i still getting "emphasized items and unresolved-import" warnings.
but for some reason it works just fine.
is more of a annoying thing.
EDIT:
module with the function "funcion"
the warning that appears in the main folder "prueba" is "emphasized items"
i tried what u guys told me to do but it stills shows the warnings
As you are trying to import a specific function from module in python
You should use in this manner:
from paquete import funciones
If you want to import full module then use:
import paquete
I can't tell whats in the funciones file. But normally this yellow import lines are telling you that you import functions, which you dont use.
Try this instead if you only want
funcion
to be imported.
from paquete.funcions import funcion
This is also better because you import only the functions you need, not all of the functions you declared in the other file. Also all imports of the other file will be loaded into your file if you import with an asterix.
The issue is you are doing all of this from within a directory named prueba. If you changed the import to from prueba.paquete.funciones import * it should work after you add a __init__.py file to your prueba directory. The other option is to use a relative import: from .paquete.funciones import *.
But do note that using import * is strongly discouraged when you are not working within the REPL. It's much better to import to the module and then reference things off the module, e.g. from prueba.paquete import funciones, from .paquete import funciones, or import prueba.paquete.funciones. That way you know exactly where things in your code came from without having to read the top of your file.
pip3 intall "name"
Use Pycharm, rather than Vscode
My structure is thus:
companynamespace/
__init__.py
projectpackage/
__init__.py
somemodule.py
companynamespace/__init__.py is empty
projectpackage/__init__.py has this line:
import companynamespace.projectpackage.somemodule as module_shortname
When I open up a python console and type import companynamespace.projectpackage (PYTHONPATH is set correctly for this), I get AttributeError: 'module' object has no attribute 'projectpackage' on the import companynamespace.projectpackage.somemodule as module_shortname line. If I remove the as module_shortname part (and make all the requisite substitutions in the rest of the file), everything imports correctly.
Can anyone tell me why this is? My Google-Fu fails me.
There is no need for absolute import in projectpackage/__init__.py, do relative one
import somemodule as module_shortname
The way you're doing it (with absolute import), would lead to circular import, which don't work very well in Python. When you're importing module, you're also calling __init__.py of parent modules. In your case, with absolute import you're also calling projectpackage/__init__.py in projectpackage/__init__.py.
Well, according to the PEP 221 your code seems to be legitimate. It could be a bug. The following workaround, which is equivalent of that expression, works for me (Python 2.6.6):
from companynamespace.projectpackage import somemodule as module_shortname
Hope it helps.
I've done what I shouldn't have done and written 4 modules (6 hours or so) without running any tests along the way.
I have a method inside of /mydir/__init__.py called get_hash(), and a class inside of /mydir/utils.py called SpamClass.
/mydir/utils.py imports get_hash() from /mydir/__init__.
/mydir/__init__.py imports SpamClass from /mydir/utils.py.
Both the class and the method work fine on their own but for some reason if I try to import /mydir/, I get an import error saying "Cannot import name get_hash" from /mydir/__init__.py.
The only stack trace is the line saying that __init__.py imported SpamClass. The next line is where the error occurs in in SpamClass when trying to import get_hash. Why is this?
This is a pretty easy problem to encounter. What's happening is this that the interpreter evaluates your __init__.py file line-by line. When you have the following code:
import mydir.utils
def get_hash(): return 1
The interpreter will suspend processing __init__.py at the point of import mydir.utils until it has fully executed 'mydir/utils.py' So when utils.py attempts to import get_hash(), it isn't defined because the interpreter hasn't gotten to it's definition yet.
To add to what the others have said, another good approach to avoiding circular import problems is to avoid from module import stuff.
If you just do standard import module at the top of each script, and write module.stuff in your functions, then by the time those functions run, the import will have finished and the module members will all be available.
You then also don't have to worry about situations where some modules can update/change one of their members (or have it monkey-patched by a naughty third party). If you'd imported from the module, you'd still have your old, out-of-date copy of the member.
Personally, I only use from-import for simple, dependency-free members that I'm likely to refer to a lot: in particular, symbolic constants.
In absence of more information, I would say you have a circular import that you aren't working around. The simplest, most obvious fix is to not put anything in mydir/__init__.py that you want to use from any module inside mydir. So, move your get_hash function to another module inside the mydir package, and import that module where you need it.