This question already has answers here:
Circular import dependency in Python [duplicate]
(7 answers)
Closed last year.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Main\Programming\Python\Console\mod_project\auto_message_mod.py", line 5, in <module>
import mod
File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 77, in <module>
main()
File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 18, in main
main_program_menu()
File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 36, in main_program_menu
auto.auto_message_tools()
AttributeError: partially initialized module 'auto_message_mod' has no attribute 'auto_message_tools' (most likely due to a circular import)
I keep getting these errors while I try to import the file call auto_message_mod.py into mod.py and in mod.py, I tried to call the function auto_message_tools(these files are in the same folder). I also have imported the other files into mod.py and it worked perfectly. Except auto_message_mod.py. I have written import auto_message_mod as auto but it was not working. I have already tried auto.auto_message_tools() but didn't work. Can someone please help me?
Python is a scripting language, which is interpreted line by line. An import statement literally means that it will jump into that file and start reading over it, before jumping back to the original file and continuing to read through that. Read more here.
You can see that in your traceback, you import a file, which then calls a function that is presumably in the original.
The best way to fix this is to separate import-time code from run-time code. That means everything should import before the code is run, meaning all your code outside your main file should be only found within functions and classes. That means that you are much less likely to create a circular import like this, since all the code will already be initialised before you call any of it.
If that doesn't work, experimenting with moving culprit import statements to the bottom often helps, although it is stylistically bad, so I'd only use it as a last resort.
Related
I'm making a module file, and I need to get the global variables of the file that is using it.
I've tried importing it, and then getting the global variables of of that, but that gets me this error:
Traceback (most recent call last):
File "C:\Users\isaac\OneDrive\Coding\python\logger\file.py", line 1, in <module>
import logger
File "C:\Users\isaac\OneDrive\Coding\python\logger\logger.py", line 3, in <module>
import file as bla
File "C:\Users\isaac\OneDrive\Coding\python\logger\file.py", line 3, in <module>
log = logger.Logger('logfile', 'file')
AttributeError: partially initialized module 'logger' has no attribute 'Logger' (most likely due to a circular import)
Is there a way to get the global variables with open(...) or something like that?
There are two solutions to this. One is to take the global variables out of file and move them to a third file, say globals.py which can be imported by both.
In terms of accessing global variables by opening the file, you can try and parse the file yourself, or indeed use something like AST. I imagine though that the aforementioned technique will be adequate for your use case.
I've been working on a project where I have a file which needs to call a function from a file in a sub package/directory, which in turn is calling a function from another file in the same sub package. As such, I have a main file which is importing a sub file. This sub file is also importing another sub file which is in the same package.
The first sub file has no issue whatsoever importing the second sub file. The main file also has no issue importing the first sub file. However, when I put it all together and run the main file, Python thinks that the second sub file doesn't exist, which I find strange. I've simplified and visualised my problem with an example below:
I have the following file hierarchy:
test_package\
__init__.py
main_file.py
test_sub_package\
__init__.py
subfile1.py
subfile2.py
main_file code:
import test_sub_package.subfile1
subfile1 code:
import subfile2
subfile2 code:
def get_string():
return ("Hello, World!")
So, I would expect main_file to import subfile2 via subfile1. However this doesn't seem to be the case because I get an error:
Traceback (most recent call last):
File "...\Test\main_file.py", line 1, in <module>
import test_package.subfile1
File "...\Test\test_sub_package\subfile1.py", line 1, in <module>
import subfile2
ModuleNotFoundError: No module named 'subfile2'
I was a little surprised that I got this error before I even attempted to call the functionality in subfile2. Either way, I'm confused why this doesn't work. Am I just doing something stupid here or am I trying to do something Python fundamentally doesn't support. If anyone can give me a solution it would be most appreciated.
I suspect this is probably a duplicate but I couldn't find an answer to my specific problem. So, sorry in advance.
When you import a module into another module from the same directory you must use must use a relative import in subfile1.py you will need to write:
from . import subfile2
Note, that doesn't give subfile 1 access to get_string to use it in subfile1, you would need to either write subfile2.get_string() or import it directly with:
from .subfile2 import get_string
I have tried this out and it works, I hope this helps :)
Note: that, if you are running a python script, and you need to import a module in that same directory, you can just say import module_name. It makes a difference if it is a script you are running, or a module that is being used in some other script. For a detailed explanation as to why see here
(I assume from your error message that you want to run main.py, if this is not the case you will need to change import test_sub_package.subfile1 to from . import test_sub_package.subfile1)
main file should be:
from test_sub_package.subfile1 import get_string
get_string()
subfile1.py
import test_sub_package.subfile2
I have two python scripts, one has all functions I have defined (functions.py) and the other only runs those functions (running_functions.py).
I imported the functions into running_functions script using from functions import*
My problem is when I ran running_functions into python console using execfile('running_functions.py') at first worked like a charm, but if I don't close the python session and do some modifications into one function in functions.py (for example changing the number of parameters that getLabels() takes (from 4 to 5)) saved then and then I ran again running_functions.py with the same comand or when I called getLabels() I get the error:
With execfile()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "running_functions.py", line 82, in <module>
predict_labels = getLabels(pred_labels, ids_tr ,labels_tr,filenames_tr, filenames_ts)
TypeError: getLabels() takes exactly 4 arguments (5 given)
Calling the function
>>> predict_labels = getLabels(pred_labels, ids_tr ,labels_tr,filenames_tr, filenames_ts)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: getLabels() takes exactly 4 arguments (5 given)
To get it work again I have to close python session and then run again execfile() or rename functions.py or do little pythons scripts with modified function.
This is very annoying because all the code takes around 10 or 15 minutes and I don't like have a lot of little scripts. So, how can I avoid this error?
I wouldn't like to close every time the session and wouldn't like to use in each function pickle module. Is it wrong the way I imported the functions? And why python returns this error? Sorry for this silly questions
I would recommend skimming over how python imports work. In general it's considered bad practice to use glob imports like from module import *. It's not transparent and makes it difficult to take advantage of reload.
I would recommend rewriting your code to do the following :
import functions
functions.getLabels(...)
and then after you change getLabels or something, you can from the shell run the following :
reload(functions)
and that will re-import your changes without having to restart the python kernel.
I've found that I need to install 'glue' first.
But after that, this error is still there.
Traceback (most recent call last):
File "C:\Users\Saisa\Desktop\Code\python\myWebSpiderForPixiv_top100.py", line 1, in <module>
from gwpy.timeseries import TimeSeries
File "C:\Users\Saisa\AppData\Local\Programs\Python\Python35-32\lib\site-packages\gwpy\timeseries\__init__.py", line 27, in <module>
from .core import *
File "C:\Users\Saisa\AppData\Local\Programs\Python\Python35-32\lib\site-packages\gwpy\timeseries\core.py", line 45, in <module>
from ..data import (Array2D, Series)
File "C:\Users\Saisa\AppData\Local\Programs\Python\Python35-32\lib\site-packages\gwpy\data\__init__.py", line 29, in <module>
from glue.lal import (Cache, CacheEntry)
ImportError: No module named 'glue.lal'
Here is another idea of what you could try:
If I understand right, your directory hieracy looks something like this:
\root
\glue
\lal
\other
\another
and in lal there are the functions and classes and whatever you want. Is lal a directory or a file? If it is a directory, I don't understand why It is not working, I just wrote a analogue code and for me it worked perfectly. Maybe ther error is somewhere entierely else, sh*t happens in python, too. But if it is a file like lal.py you don't have to tell from glue.lal import (whatsoever)! This whatsoever are functions then in one file. Just type from glue import lal, it will import everything in there.
Your Problem is that Python does not know where to find the module. You must add the path to the Path Browser where the module code is saved in and then you can use the
import themoduleyouwant
Or
from themoduleyouwant import *
command.
You can find the Path Browser under "File >> Option >> Path Browser"
Usually, it will show you the standard libraries and your current working directory (cwd). So if you are looking for a quick solution, just take the directory of 'glue' and copy+paste it into your cwd.
Result: The Error will disappear.
I'm following some online python tutorials and i ran across this syntax error code twice now and can't figure out what's wrong.
Here's my code:
import urllib
import re
htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL")
htmltext = htmlfile.read()
regex = '<span id="yfs_l84_aapl">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern, html)
print price
I am using Enthought Python Distribution package (python version 2.7.3)
Here's the syntax error when i run the above script.
Traceback (most recent call last):
File "E:\python\scripts\stocks.py", line 4, in <module>
htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL")
File "e:\python27\lib\urllib.py", line 86, in urlopen
return opener.open(url)
File "e:\python27\lib\urllib.py", line 207, in open
return getattr(self, name)(url)
File "e:\python27\lib\urllib.py", line 291, in open_http
import httplib
File "e:\python27\lib\httplib.py", line 79, in <module>
import mimetools
File "e:\python27\lib\mimetools.py", line 6, in <module>
import tempfile
File "e:\python27\lib\tempfile.py", line 34, in <module>
from random import Random as _Random
File "E:\python\scripts\random.py", line 1
def random
^
SyntaxError: invalid syntax
I tried searching around to understand what's going on but no avail. What's python trying to tell me with all these traceback lines and why do I get a syntax error?
If you look at the stack trace, towards the bottom, you can see that the syntax error is in a file called E:\python\scripts\random.py. This script is one you've added to the system, and it appears to contain a syntax error. Because it's named random and is located in the Scripts directory, it is "overriding" the built-in random library.
Remove or rename that file and you should be good to go.
The import of module is controlled by sys.path. To a first approximation when your program executes import module the interpreter visits the directories on sys.path in turn. It looks for a module.pyc file and a module.py file in each directory, moving on to the next if it finds neither. When it finds one or both, if the .py is newer than the .pyc (in other words, if the source has been modified since the file was last compiled, or if the compiled file does not exist) then the interpreter compiles the .py file and attempts to write to it. There are no guarantees your process will be able to write in that particular directory.
Having identified the correct file the interpreter creates a new namespace, executes the code of the module with that namespace as local, then binds the name of the module with the namespace just created. So if you have bound a name in module it should (modulo any __all__ assignment in the module's code) be available within your importing module as module.name.
I suspect this question has taught you why it's not a good idea to duplicate the names of system libraries in your own code - a lesson we all have to learn!