You are creating a circular dependency (see e.g. this explanation), which is something you generally want to avoid.
The program flow would roughly be as follows:
- You call
python main.py
import task
is executed, to load print_func
from task.py
task.py
is executed, going straight back to main.py
to retrieve list_list
...
To fix your problem, you could do the following:
main.py:
import task
list_list = ["test1","test2"]
# Only run this, if main.py is run directly, not in import
if __name__ == "__main__":
task.print_func()
task.py: (no changes)
from main import list_list
def print_func():
for x in list_list:
print(x)
This change allows task.py
to import list_list
without trying to execute task.print_func
which cannot be defined at that point (as its definition depends on list_list
).
Some general points:
- I don't see why you want to import
list_list
from main for use in task.print_func
- passing the list as argument would be better in my opinion.
- Execute as little code as possible on indent level 0 in a python file you want to import somewhere else. Read e.g. here: What does if __name__ == "__main__": do? for some details.
All things considered, I would do it as follows:
main.py
import task
if __name__ == "__main__":
list_list = ["test1","test2"]
task.print_func(list_list)
task.py:
def print_func(list_list):
for x in list_list:
print(x)