How can I fix a very basic ImportError in Python3? - python-3.x

Similar to ImportError: Cannot import name X, I have a main.py file and, in the same folder, a few other python files bill.py and flatmate.py.
bill.py and flatmate.py each contain classes, nothing more.
Directory structure:
parentfolder
- main.py
- bill.py
- flatmate.py
- files
- pic.png
- doc.pdf
Sample code:
main.py:
import bill # won't work
from flatmate import Flatmate # won't work
...
bill.py:
class Bill:
def __init__(self, ...):
...
flatmate.py:
class Flatmate:
def __init__(self, ...):
...
I get an ImportError: cannot import name 'Bill' from 'bill' (c:\Users\lavid\Desktop\Python Experimente\Python OOP Kurs\App-2-Flatmates-Bill\bill.py). I am pretty sure I don't have circular references. What could be the cause of this problem?

Make sure that all files are next each others
try:
from . import module
if this doesn't work , add your files dir to the Question

Saving the referenced files before accessing them helped a lot.

Related

how to import a python class from different mains at different level of indentation

I am trying to structure a program with several modules as it is customary for python.
I have several modules containing classes and functions, and a usual main entry point.
Now I have built a different main that serves another (larger) purpose.
My structure is something like this:
-----main.py
|---module1
| |---subMain.py
| |---script1.py
| |---script2.py
| |---submodule1
| |---script3.py
|---module2
|---script4.py
Currently subMain.py imports all scripts from module1 with no problems.
Yet, if I try to run main.py by importing module1 files it fails.
#This works
#subMain.py
from script1 import *
#########
#script1.py
from submodule1.script3 import *
#This does not work
#main.py
#So far so good
from module1.script1 import *
#########
#script1.py
#this fails
from submodule1.script3 import *
#If I change it to the following, it works
from module1.submodule1.script3 import *
Is there a way to have script1 always work (no failure when including script3) without changing the import line?
In the end I figured the best way to do what I wanted was to build a wheel.
I need to import that same class into several projects and a wheel enables me to fix bugs only in one convenient location and reimport the de-bugged package on each project.
I actually found a workaround, maybe not the cleanest, but I got inspired by C++ #ifdef guards.
Basically I check the __name__ variable.
if __name__ == "__main__" :
from script1 import scriptObject as scriptObject
elif __name__ == "__main__" :
from module1.script1 import scriptObject as scriptObject
else :
raise Exception(f"__name__ = {__name__} is not a valid guard! Make sure project indentation is correct.")

Importing a Class from another python file in Vscode

I have made this class in python3:
#!/usr/bin/env python3
class Post():
def __init__(self):
self.title="this is my title"
self.content= "this is some content"
self.author= "Ata"
And then wanted to import this class into another file named "app.py":
#!/usr/bin/env python
# importing class from post.py into app.py
from post import Post
post= Post()
post2= Post()
print (post.content)
but get this error:
ImportError: cannot import name 'Post'
what is the problem with the code?
Finally, I got my answer... The only thing that I had to do in order to import my class into another python file was that I should have saved it. that's all and after this everything works fine.

Python import files from 3 layers

I have the following file structure
home/user/app.py
home/user/content/resource.py
home/user/content/call1.py
home/user/content/call2.py
I have imported resources.py in app.py as below:
import content.resource
Also, I have imported call1 and call2 in resource.py
import call1
import call2
The requirement is to run two tests individually.
run app.py
run resource.py
When I run app.py, it says cannot find call1 and call2.
When run resource.py, the file is running without any issues. How to run app.py python file to call import functions in resource.py and also call1.py and call2.py files?
All the 4 files having __init__ main function.
In your __init__ files, just create a list like this for each init, so for your user __init__: __all__ = ["app", "content"]
And for your content __init__: __all__ = ["resource", "call1", "call2"]
First try: export PYTHONPATH=/home/user<-- Make sure this is the correct absolute path.
If that doesn't solve the issue, try adding content to the path as well.
try: export PYTHONPATH=/home/user/:/home/user/content/
This should definitely work.
You will then import like so:
import user.app
import user.content.resource
NOTE
Whatever you want to use, you must import in every file. Don't bother importing in __init__. Just mention whatever modules that __init__ includes by doing __all__ = []
You have to import call1 and call2 in app.py if you want to call them there.

Python 3: Importing Files / Modules from Scattered Directories and Files

I have the following directory structure:
/home/pi
- project/
- p1v1.py
- tools1/
- __init__.py
- tools1a/
- __init__.py
- file1.py
- file2.py
- tools1a1/
- __init__.py
- file3.py
- file4.py
- tools1a2/
- __init__.py
- file5.py
- file6.py
I am trying to import all the modules from the file1.py into my project file p1v1.py
from file1 import *
but end up with either an
ImportError: attempted relative import with no known parent package
or an
ValueError: Attempted relative import in non-package
depending on what I use in p1v1.py because the functions in file1.py depend on file3.py and file4.py. I would like to use explicit imports (for clarity), but I'm not sure how to do this. Any advice would be appreciated.
Thank you!
Through trial and error eventually figured out how to solve this:
import sys
sys.path.insert(0,'..')
from tools1.tools1a.file1 import function as f1
Note: For this to work, I needed to be editing and executing my script p1v1.py out of the working directory /home/pi/project/. Hope this helps others with a similar problem!

Python 3.6 Importing a class from a parallel folder

I have a file structure as shown below,
MainFolder
__init__.py
FirstFolder
__init__.py
firstFile.py
SecondFolder
__init__.py
secondFile.py
Inside firstFile.py, I have a class named Math and I want to import this class in secondFile.py.
Code for firstFile.py
class Math(object):
def __init__(self, first_value, second_value):
self.first_value = first_value
self.second_value = second_value
def addition(self):
self.total_add_value = self.first_value + self.second_value
print(self.total_add_value)
def subtraction(self):
self.total_sub_value = self.first_value - self.second_value
print(self.total_sub_value)
Code for secondFile.py
from FirstFolder.firstFile import Math
Math(10, 2).addition()
Math(10, 2).subtraction()
When I tried running secondFile.py I get this error: ModuleNotFoundError: No module named 'First'
I am using Windows and the MainFolder is located in my C drive, under C:\Users\Name\Documents\Python\MainFolder
Possible solutions that I have tried are, creating the empty __init__.py for all main and sub folders, adding the dir of MainFolder into path under System Properties environment variable and using import sys & sys.path.append('\Users\Name\Documents\Python\MainFolder').
Unfortunately, all these solutions that I have found are not working. If anyone can highlight my mistakes to me or suggest other solutions, that would be great. Any help will be greatly appreciated!
There are potentially two issues. The first is with your import statement. The import statement should be
from FirstFolder.firstFile import Math
The second is likely that your PYTHONPATH environment variable doesn't include your MainFolder.
On linux and unix based systems you can do this temporarily on the commandline with
export PYTHONPATH=$PYTHONPATH:/path/to/MainFolder
On windows
set PYTHONPATH="%path%;C:\path\to\MainFolder"
If you want to set it permanently, use setx instead of set

Resources