I had an import error with python on VS Code - python

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

Related

`Importlib` not actually importing modules?

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.

Python Can't Import Class From Parent Directory?

I am new to Python, so I might not be seeing the obvious solution to this. I have searched online for a solution and everyone seems to have the same answer. I am trying to import a file from a parent directory in Python. I am coming from JavaScript where you simply type import Function from '../ParenetDirectory/FileThatIncludesFunction' and you can import that module. Every website I have visited says you have to include the parent directory in your freakin' path to import it. Are we serious here? I assume I am missing something because it seems to me that Python would have a more elegant way to do this than editing your freaking path to import a class from a parent directory. Please tell me it does, or explain to me why it doesn't.
You can do this by using the sys module and adding the desired directory to its path.
"../ParenetDirectory/FileThatIncludesFunction.py" :
def Function():
return 'Hello, World!'
main.py :
import sys
sys.path.append('../ParenetDirectory')
from FileThatIncludesFunction import Function
print(Function())
Note that if you want to run this via cmd, make sure that the folder in cmd is exactly where the main.py file is located.

Path inserted into sys.path but import module still shows error, what am I missing?

Does anyone know the proper way to import a module in a different directory?
I have used the following codes below, it works but there is still a 'no module named ...' error.
The code runs fine but I do not know how to get the import to recognise the file.
import sys
path = r'C:\Users\User\OneDrive\Documents\Programming\Python'
sys.path.insert(0, path) # insert file path to the start of the path list
import random100Numbers # Here there is a no module named warning...
print(random100Numbers.rand100Num(90)) # code executes as it is
print(random100Numbers.rand100Num(-100)) # code executes as it is

Failure with more than one co-dependant/circular python import

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...

Correct syntax for import statement

Newbie here
I want to import a class from a file in another directory, in this case:
C:\Users\jose_\Desktop\my_ref\stack_class.py, using the from - import statement. I have an init.py file in said directory but cannot find the right sintax anywhere.
How do you put C:\Users\jose_\Desktop\my_ref\stack_class.py in the import part?
I have tried using these other two ways:
exec(open("file path on windows").read())
and the import sys and sys.path.insert
they both work, trying to do it with the import statement.
from C:\Users\jose_\Desktop\my_ref\stack_class.py import Stack #Error here
foo = Stack()
print(type(foo))
Error
File "C:/Users/jose_/OneDrive/Mis_Documentos/Educacion/Linkedin/Ex_Files_Python_Data_Structures_Queues/Exercise_Files/Ch02/02_02/End/main2.py", line 4
from C:\Users\jose_\Desktop\my_ref\stack_class.py import Stack
^
SyntaxError: invalid syntax
As far as I know, you cannot import from a file path in Python.
You can only import by passing a module name:
import module.submodule
# then
module.submodule.sth()
or
from module.submodule import sth
# then
sth()
And Python will search module/submodule.py and module/submodule/__init_.py in all the directories in sys.path.
So if you want to import from a file in another directory created by yourself (not included in the sys.path list) you have to append that directory to the list to tell Python where to find that module. Try to run:
import sys
sys.path.append('C:\\Users\\jose_\\Desktop\\my_ref')
from stack_class import Stack
# then
foo = Stack()
print(type(foo))
Edit
If you don't want to append to sys.path, you need to move your module to one of the diretories in sys.path, for example, the current directory . is also in sys.path, or Python won't know where the module is (C:\ is not in sys.path).
Python never imports from directories that are not included in sys.path (via import statements, I mean)!
Did you make sure to switch your forward slashes "\" with back slashes "/" ?
try using:
sys.path.extend('file path here')
to add the folder path to your python path, that way python knows where to look for the stack_class module - either that or navigate to the folder before importing
also make sure in the folder your init file is called __init__.py
you should then be able to do
from stack_class import Stack

Categories