Python Import Error but in the same directory - python

This may seem like a easy question, but I have tried my best to figure it out.
I have two files:
Car.py and Dealership.py
They are in the same directory. Dealership.py contains a bunch of methods and another class that I would like to use in Car.py. The class name is "worker".
So in Car.py I write at the top of the file:
from Dealership import worker
I have also tried:
import Dealership
I continually get this error:
No module named Dealership
I can't understand why. As far as I know, and according to pydocs, I am writing the imports correctly, and the files are in the same directory.
Thanks for any advice

You need to add the current directory to the sys.path, so that the Python will try to find the module here.
import sys
sys.path.append(".")

Related

Python: How to import a file

I'm using Python 3.95, and have two files:
shapes.py, which defines class Circle, class Square, and class Triangle
textures.py, which defines class Smooth and class Rough
I'd like to be able to do something like:
from .shapes import *
but I get error ImportError: attempted relative import with no known parent package.
All files are stored in the same folder, and I'm trying to execute Python from that folder, on Python files stored in that folder.
There are numerous posts on SO describing this error, and I've tried their solutions, but to no avail. It seems like some of this depends on Python 2 vs 3, some depends on which folder you're executing from, some depends on packages and modules (which I do not entirely understand).
Some things I've tried which have not worked:
Creating an __init__.py file
Using from shapes import * instead of from .shapes import *
Using from .shapes import Circle
Adding these lines:
import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
This is likely a basic mistake: I'm not trying to build a module or package for distribution, I simply want to put different classes into different files, instead of all my classes in one giant file. How can I do so?
The current directory is only prepended to sys.path automatically if the script is the python file (not if the script is the first argument to python like python app.py).
I think that you can either:
add #! /usr/bin/env python at the start of the main file and make it executable with chmod +x main.py
append the right directoy to sys.path, as it seems to me that you are trying to append the parent dir. SCRIPT_DIR in your last attempt is already the current directory and you don't need to call dirname on it again.
There's no need for a relative import if your main script needs to use a module in the same folder. If you have a main.py and a shapes.py (containing for example a function fun1()), just use any of these:
import shapes
shapes.fun1()
from shapes import fun1
fun1()
from shapes import *
fun1()
Note that the latter is not preferable, since it's not at all clear what you're importing and if shapes.py is later changed to include something that shadows something from an earlier import, it may break your code in surprising ways. Surprise is bad.
If you're writing a package called shapes, create a folder called shapes, put an __init__.py in it, and a Python file which could be called shapes.py or anything you want, as you'll be importing what's relevant from the __init__.py.
Then shapes/__init__.py could be something like:
from .shapes import *
Here, using the * makes a bit more sense, although I'd still favour from .shapes import fun1. The . is not needed, but here it makes sense, because it is relative to another file that's also in the package.
And shapes/shapes.py might be something like:
from .other_mod import fun2
def fun1():
fun2()
Here, the . makes sense if shapes.py and other_mod.py are always going to be sitting next to each other in the package, but perhaps move around within the internal structure. Or perhaps you want to use the explicit . to avoid conflicts with other names.
If other_mod.py is something like:
def fun2():
print('hello')
You could write a main.py in the same folder where the shapes folder sits and the code with shapes imports above would work.
Can you try create new folder and add [shapes.py,textures.py,init.py] files into shapes folder
backend/
|
|------folder_shapes/shapes.py
|------folder_shapes/textures.py
|------folder_shapes/__init__.py
|------your_script.py
|
Then try import from your_script.py

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.

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

Python3 unable to find a package module

I have a file called dns_poison.py that needs to call a package called netscanner. When i try and load the icmpscan module from dns_poison.py I get this message:
ModuleNotFoundError: No module named 'icmpscan'
I've done a sys.path and can confirm that the correct path is in place. The files are located at D:\PythonProjects\Networking\tools and D:\PythonProjects appears when I do a sys.path.
Here is my directory structure:
dns_poison.py
netscanner/
__init__.py
icmpscan.py
Code snippets for the files are as follows:
dns_poison.py
import netscanner
netscanner\__init__.py
from icmpscan import ICMPScan
netscanner\icmpscan.py
class ICMPScan:
def __init__(self, target, count=2, timeout=1):
self.target = target
self.count = count
self.timeout = timeout
self.active_hosts = []
# further code below here....
I don't understand why it cannot find the module, as I've used this exact same method on other python projects without any problems. Any help would be much appreciated.
When you run python dns_poison.py, the importer checks the module path then the local directory and eventually finds your netscanner package that has the following available:
netscanner
netscanner.icmpscan
netscanner.icmpscan.ICMPScan
Now I ask you, where is just icmpscan? The importer cannot find because well, it doesnt exist. The PYTHONPATH exists at wherever dns_poison.py resides, and doesn't append itself to include the absolute path of any imported modules because that simply not how it works. So netscanner can be found because its at the same level as dns_poison.py, but the importer has no clue where icmpscan.py exists because you havent told it. So you have two options to alter your __init__.py:
from .icmpscan import ICMPScan which works with Python 3.x
from netscanner.icmpscan import ICMPScan which works with both Python 2.x/3.x
Couple of references for you:
Python Import System
Python Modules recommend you ref section 6.4.2 Intra-package References
The most simple way to think about this is imports should be handled relative to the program entry-point file. Personally I find this the most simple and fool-proof way of handling import paths.
In your example, I would have:
from netscanner.icmpscan import ICMPScan
In the main file, rather than add it to init.py.

Importing class from file in parent directory

I have python code that is structured like this:
src
--->commoncode.py
--->folder1
--->file1.py
--->folder2
--->file2.py
--->folder3
--->file3.py
I want to use the code that is in commoncode.py in the files fileN.py. I have tried includingfrom . import commoncode but that does not work (ImportError: cannot import name 'commoncode').
I am able to use the code with import commoncode if I include a symlink in each of the subfolders but that seems hacky and sort of defeats the purpose of having common code.
The only code in commoncode.py right now is class commoncode():.
Let me know if there is any information that I can further provide that would be useful.
Since you're not using packages, one way is to modify your path:
import sys
sys.path.insert(0, "..")
from commoncode import <whatever>
# Now you can access imported symbols from commoncode.py
usually when importing you need to import as follows,
from (Name of the module) import (name of the class within the module).
so in your case, if I understood correctly I believe it would be:
from (Name of the common code module) import commoncode.
at the top of any of your modules you wish to use commoncode in, this is how it would be imported.
Please make sure that you haven't missed any capital or lowercase letters as well, as it is case sensitive when you import. Hope this could be of some help.

Categories