Can't figure out how to solve this circular import [closed] - python-3.x

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was splitting some functions into a separate file. Found the functions and helper functions. Set all the paths and import in other files so everything can still be called where necessary. But after removing an unused import from the original file it gives a circular import error it seems.
So there is an unused import and while there, every test (524) succeeds, but the branch cant be pushed because of the unused import. If we remove the import, the tests goes into circular import I think and wont start at all.
The first thing i tried is to change the regarding import statements from: from /module import /object --> import module
This made the tests start but everything went wrong after that.
After that I tried to find a way through the circular import path but I just lost track of everything while I dont know if it is even a solution.
`
Traceback (most recent call last):
File "/home/user/../.py", line 2, in <module>
from x.model import x
File "/home/user/../.py", line 1, in <module>
import A
File "/home/user/../.py", line 4, in <module>
import B
File "/home/user/../.py", line 1, in <module>
import C
File "/home/user/../.py", line 9, in <module>
import D
File "/home/user/../.py", line 4, in <module>
import E
File "/home/user/../.py", line 9, in <module>
from x.model import x
ImportError: cannot import name 'x'
`

If you are using imported Ive in /home/user/projects/.../nsx/utils.py file, inside some method or function, then you should remove import statement (i.e from ive.models import Ive) from top of file import statements(if you are doing so), and import it dynamically means put import statement at the place where you are using Ive inside the method or function.
# Assume `/home/user/projects/.../nsx/utils.py` file
# Don't import Ive here
# from ive.models import Ive
def func():
# import here
from ive.models import Ive
# use Ive here

Related

Unable to import openpyxl module [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
The Code below works just fine :
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
import os
os.chdir('c:\\users\\shivam\\Desktop')
wb = openpyxl.load_workbook('data.xlsx')
print(wb.sheetnames)
print(get_column_letter(27))
but when I try to import it as:
from openpyxl import *
import os
os.chdir('c:\\users\\shivam\\Desktop')
wb = openpyxl.load_workbook('data.xlsx')
print(wb.sheetnames)
print(get_column_letter(27))
it gives an error:
Traceback (most recent call last):
File "D:/python projects/excel.py", line 4, in <module>
wb = openpyxl.load_workbook('data.xlsx')
NameError: name 'openpyxl' is not defined
Why everything from the module is not getting imported all at once?
If you import a module like import openpyxl, then you should use openpyxl.load_workbook.
But while importing a module like from openpyxl import *, rather than importing the whole module you're importing all the classes and functions present inside the module, so there is no need of calling openpyxl.something(), just directly call the name of class or function like load_workbook

Module is imported, but is still rendering NameError

I am new to python packages and I am in process of learning how organize code into packages.
I tried out a small program for testing purpose and I am curious about an error that I encountered.
I have put the following package-structure (I am currently working with regular packages only as I don't have a good understanding of namespace packages):
parent/
main.py
p1/
__init__.py
The code in p1/__init__.py is as follows:
import math
print('p1 imported.')
The code in main.py is as follows:
from p1 import math
def main():
print(p1)
if __name__=='__main__':
main()
The output that it gives me is as follows:
path-to-parent>python3 main.py
p1 imported
Traceback (most recent call last):
File "main.py", line 12, in <module>
main()
File "main.py", line 8, in main
print(p1)
NameError: name 'p1' is not defined
I understand that it has imported math from sys.modules or the subsequent full search that it must have performed after encountering the import math statement in p1/__init__.py. It also executed the subsequent statement print('p1 imported') indicating that the module p1 has been imported. Then why does the NameError pop up?
With my reading of this page, my guess is that although the module p1 has been imported, it has not undergone the binding process because of the way it has been imported: from p1 import math.
I would still need help to understand this.
NOTE: I am using Anaconda Python 3.7.3 on windows 10 (64bit).
from p1 import math
def main():
print(p1)
if __name__=='__main__':
main()
p1 here is the name of the directory, it is not a python variable that can be used.
It is very roughly analogous to the following attempt:
with open('filename') as f:
print(filename)
Which will obviously raise NameError because filename is not defined.
Perhaps a better example is this:
from math import pi
print(math)
This also raises NameError because math is never defined as a variable that can be used outside of the import mechanism. math here is the name of the module from which pi is imported, but it can only be seen by the import mechanism.
It's much easier to demonstrate why what you're doing fails:
>>> from math import sin
>>> sin
<built-in function sin>
>>> math
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
The point is, that math.sin is imported as sin, but the math module that is needed for this is not stored for reference anywhere. For that reason, there is no local math object you could refer to.
If you want to refer to the math module as a whole, just import it as a whole. For your example, just import p1.

Cannot import namedtuple [duplicate]

This question already has answers here:
ImportError: cannot import name namedtuple
(2 answers)
Closed 3 years ago.
I am currently working in PYCHARM and it gives me the error whenever I run the program. I tried various methods to remove this error but to no avail.
What can I do to fix this issue?
import re
File "F:\Anaconda\envs\tensorflow\lib\re.py", line 125, in <module>
import functools
File "F:\Anaconda\envs\tensorflow\lib\functools.py", line 21, in <module>
from collections import namedtuple
ImportError: cannot import name 'namedtuple'
Check the module in stdlib named types, it gets imported instead.
You can either rename your module, or switch to absolute imports.
Hope this will help you.

how to write data from a point cloud file to a text file

I am trying to make a program that takes point cloud data and publishes the data into a txt file for some reason I am getting this error when I run my code:
File "readpts.py", line 14, in <module>
f.write("%d "%float(array[i][0].item()))
io.UnsupportedOperation: not writable
This should be a simple fix I just don't know what I am doing wrong. Here is my code:
import numpy as np
import open3d as o3d
pcd= o3d.io.read_point_cloud("cloud_cd.ply")
#print(pcd)
#print(np.asarray(pcd.points))
array=np.asarray(pcd.points)
f=open("cloud_cd.ply")
#print(type(float(array[0][0].item())))
for i in range(len(array)):
f.write("%d "%float(array[i][0].item()))
f.write("%d "%float(array[i][1].item()))
f.write("%d \n"%float(array[i][2].item()))
You are opening your file in read mode which is the default one when using the open function.
You should do something like this:
import numpy as np
import open3d as o3d
pcd= o3d.io.read_point_cloud("cloud_cd.ply")
array=np.asarray(pcd.points)
with open("points.txt", mode='w') as f: # I add the mode='w'
for i in range(len(array)):
f.write("%f "%float(array[i][0].item()))
f.write("%f "%float(array[i][1].item()))
f.write("%f \n"%float(array[i][2].item()))
The with allows to close the file even if an error occured.
Edit
For the rounding issue, it is due to the %d. In order to have a float, replace the %d with %f (done in the code above). If you want to have only two decimals: %.2f (more information in the doc).
If you are in python3.6+, you can use the formatted string.

python 3 import urllib.request module

I am learning to grab pictures from URL and found a Q&A here. Since it's Python 3, I changed import urllib to import urllib.request and
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
to
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg").
It doesn't work! It says AttributeError: 'module' object has no attribute 'urlretrieve'
I then changed urllib.urlretrieve to def request.urlretrieve and got SyntaxError: invalid syntax
I also tried def urlretrieve and it's not working either.
Could anyone tell me how to get it right? Thanks!
What if the URL contains more than one pic?
You need to use:
from urllib import request
request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
You can use also use:
import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
Since you have imported urllib.request module, doesn't it seem obvious that you should call its method urlretrieve(args) as urllib.request.urlretrieve(args).
When you type import <module>, you call its method using <module>.method(args) (As specified in above code).
Alternatively, you can import the module using from <module> import * and then call its method using method(args). Eg -
from urllib.request import *
urlretrieve(args).
Another way is to only import the method you need to use in your program using
from <module> import method and then call the method using method(args). Eg -
from urllib.request import urlretrieve and then call the method using
urlretrieve(args).
The urllib.request module for Python 3 is well documented here.

Resources