I tried a little test and got hooked on giving it the same name as the module I wanted to import. It may be common sense, but I didn't know it, so I'll make a note of it.
Suppose you want to test the math module and write a file called math.py.
math.py
import math
print(math.pi)
Doing this will result in an error.
Execution result
$ python math.py
Traceback (most recent call last):
File "math.py", line 1, in <module>
import math
File "/home/xxxx/math.py", line 2, in <module>
print(math.pi)
AttributeError: partially initialized module 'math' has no attribute 'pi' (most likely due to a circular import)
The cause is that I imported myself and circulated as stated in the error.
(most likely due to a circular import)
I didn't know it right away, so I tried printing it appropriately.
math.py
print("math")
import math
print(math.pi)
Execution result
$ python math.py
math
math
Traceback (most recent call last):
File "math.py", line 2, in <module>
import math
File "/home/xxxx/math.py", line 3, in <module>
print(math.pi)
AttributeError: partially initialized module 'math' has no attribute 'pi' (most likely due to a circular import)
math
is displayed twice. At last, I knew that I was referring to myself.
The second import of the same file will be ignored, so go ahead and get an error because math.pi
is missing.
It works if you change the file name. Avoid the same file name that you want to import.
Recommended Posts