简体   繁体   中英

How to import list from main.py to task.py with Python 3 PyCharm?

How can I use a list from main.py, in the task.py? Code below.

main.py:

import task.py
list_list = ["test1","test2"]
task.print_func()

task.py:

from main import list_list
def print_func():
     for x in list_list:
          print(x)

In this way I got the following error:

AttributeError: module 'task' has no attribute 'print_func'

You are creating a circular dependency (see eg 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:

  1. 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.
  2. Execute as little code as possible on indent level 0 in a python file you want to import somewhere else. Read eg 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)

You have to use below code.

main.py

import task
list_list = ["test1","test2"]

if __name__=="__main__":
    task.print_func()

task.py

from main import list_list

def print_func():
     for x in list_list:
          print(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM