I am trying to import python code from one submodule to another, and I am getting an error, but only when I have more than co-dependant import from the package.
From my understanding, this "circular" importing is okay to do in Python. From the way I'd like the code to be organized, I do need these "co-dependant" imports and unless I really have to change it, I'd like to keep my code structured in the same submodules it currently is.
My directory/file structure:
./subm1/
./subm1_file.py
./subm2/
./subm2_file.py
./subm_main/
./subm_main_file.py
# subm1_file.py
# -------------
import subm_main.subm_main_file
print(subm_main.subm_main_file.test)
# subm2_file.py
# -------------
import subm_main.subm_main_file
print(subm_main.subm_main_file.test)
# subm_main_file.py
# -------------
import os
import sys
current_path = os.path.dirname(__file__)
sys.path.append(os.path.join(current_path+".."))
import subm1.subm1_file
import subm2.subm2_file
test = "test_variable"
I am running $ python subm_main_file.py while inside the subm_main directory
this works if I only use one module, so if in subm_main_file.py I comment out import subm1.subm1_file, it will run and print the test variable, and same if i comment out import subm2.subm2_file the error always comes one the second import. So in the code I show, the error is in subm2_file.py.
Error:
AttributeError: module 'subm_main' has no attribute 'subm_main_file'
It seems very strange to me that this works one time but not the second time with both import statements uncommented out. What can I do to fix this error (and hopefully keep my code organized in its current state)?
I cannot comment yet on a post but maybe your issue is that you need to place an init.py file inside the root and sub-directories if you want to keep your folder/code structure unchanged...
Related
On the following path:
main
system.py
|-----pid
init.py
pid.py
tunning_methods.py
pid.py has the following relevant import lines:
import tunning_methods
tunning_methods.py does not import any other file as it does not need it.
init.py is empty, and system.py has the following import lines:
import pid.tunning_methods
import pid.pid
every file has a function to test it on the format:
if __name__ == "__main__":
testfunc()
now when i try to run pid.py it runs just fine, however when i try to run system.py it raises an error saying the is no such module named tunning_methods.py on the pid.py file. I was able to solve that by importing "import pid.tunning_methods" on the pid.py it was like on the system vision of import path, instead of the pid, however the pid now does not run, more than that im having a lot of trouble with imports, this is just a piece of application that goes in to a much bigger one, its possible to do this for every import, however i want an easier solution, any ideas ?
tried to do the imports on the description and it did not work as i was intending.
for anyone having the same problem the suggestion that Michael gave worked, a relative import from . import tunning_methods.
I'm trying run an env_setup script that imports modules used in my main_script. But despite successfully running env_setup.py the modules are not being imported (presumably it is being run in its own environment).
Previously I know I have somehow sucesfully used:
from env_setup import *
However this fails for me now.
I tried a second approach using:
importlib.util.spec_from_file_location(name, location)
But this also fails.
Below is an example of what I am attempting (using the second approach in my main_script.py):
Example env_setup.py script:
import datetime # import module
print("modules imported!!!") # confirm import
Example main_script.py script:
# This first section should import `datetime` using `env_setup.py`
import importlib
spec = importlib.util.spec_from_file_location(
name='setup',
location='/home/solebay/my project/env_setup.py' # path to `set_up` script
)
my_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(my_mod)
# This returns "modules imported!!!"
# Here we run a basic command to check if `datetime` was imported...
now = datetime.datetime.now()
print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y')) # Should print time/date
# NameError: name 'datetime' is not defined
How do I get python to actually import the required modules into the environment running main_script.py? It creates a __pycache__ folder so I know the path is correct.
After dynamically importing a module you can either access the module directly by using my_mod.function() or import everything (imitate from module import *) like so:
import sys
sys.modules["setup"] = my_mod
from setup import *
del sys.modules["setup"] # Optional
After lots of searching I decided:
from env_setup import *
Should absolutely work.
I moved my most recent scripts to a fresh directory with a simpler tree and everything works.
I'm thinking it was a bug?
Update (Not a bug):
As per the useful suggestion of Bharel I ran..
import os
os.getcwd() # Returned 'wrong' directory
os.listdir() # Returned 'wrong' listing
Visual inspection of the folder tree showed that env_setup.py was present, but this file and others were absent from the true listing returned by os.listdir().
I'm running my code through the IDE "Atom" using the "Hydrogen" module. I opened a new window, added a new project folder and ran the command again and it updated.
I'm assuming I moved a folder and Atom didn't have a chance to update the path.
End result:
from env_setup import *
Works prefectly.
I have an import error with python on VS Code.
Although I had this error, I could run this code with no error.
Maybe, VS Code can not recognize the "import" statement.
I'm glad if anyone solve this problem.
Thank you.
Error on from statement :
Unable to import 'ClassSample'
main.py
#main.py
#path
sys.path.append('sampleClass/myClass')
#my class
from ClassSample import ClassSample #error on from statement : Unable to import 'ClassSample'
ClassSample.py
#ClassSample.py
class ClassSample:
#select param
def selectParam(self, param):
param = "_" + param
return param
The VSCode Intellisense can not analysis this code when linting:
sys.path.append("sampleClass/myClass")
So, it will prompt you with the import error.
This code can work because it's under the workspace folder directly. If you move sampleClass folder to another place, such as the sample folder, it will not work.
This is because you are using the relative path, it depends on the cwd-- workspace folder path by default.
It seems you confused yourself when importing.
You have to tell to python which directory you want to import a module. Since main.py is in another subdirectory, we need to move one folder up and locate the proper subdirectory hence the inclusion of sampleClass when importing.
from sampleClass.myClass import ClassSample
The above code worked when importing the class ClassSample. All you have to do now is to initialize it.
If you want a solution with minimal change, you could do:
from ..myClass.ClassSample import ClassSample
Where .. is moving one directory up which means you are basically doing sampleClass.myClass here.
Sample Code.
# from sampleClass.myClass import ClassSample
from ..myClass.ClassSample import ClassSample
my_class = ClassSample
I have a program, program1.py, that has this structure:
Program
--program1.py
--__init__.py
--data\
----__init__.py
----helper_data.py
--classes\
----__init__.py
----helper_class.py
In helper_class.py, there is an import statement from data.helper_data import *. When I run program1, this works perfectly.
I have a second program, program2.py. I have put program1.py on my PYTHONPATH. In program2.py, I use import program1. It finds the program, but when running the imports from program1.py, I get the following error stemming from the classes.helper_class: ModuleNotFoundError: No module named 'data.helper_data'.
I think I vaguely understand what's going on, but I can't figure out the fix or the search terms to find the answer. I've tried changing the import in program1 to from ..data.helper_data import * and get an error saying I've tried a relative import beyond the parent-level package. I've also tried from .data.helper_data import * and get the same ModuleNotFoundError.
What can I do?
I think You have to import "sys" package.
import sys
sys.path.append('E:\ToDataScientist') # this is where the "Program" folder exists
from Program.data.helper_data import aa # "aa" is the class or function in helper_data
from Program.data.helper_data import * # include all from helper_data
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