Home > Blockchain >  How to import a list from within a function into another python module?
How to import a list from within a function into another python module?

Time:12-09

I've got 2 files. File 1 has a function and within it, a list. I'm trying to print the contents of that list in File2, however, I'm getting name errors?

Below is File1 where the function is kept, the list I'm trying to access in file 2 is called product.

def news_articles():
    search_metric = {
        "q": "covid",
        "apiKey": "d5da78e207f94fdc8eecd3530acf4edb"
    }
    base_url = "https://newsapi.org/v2/everything?"

    # fetching data in json format
    res = requests.get(base_url, params=search_metric)
    open_news = res.json()

    # getting all articles in a string article
    article = open_news["articles"]

    # empty list which will
    # contain all trending news
    global product
    product = []

    for s in article:
        product.append(s["title"])

In file2, I'm just trying to import the module and print(product)

CodePudding user response:

There is no need to make product list global. Try avoid making your functions depend on global variables. Most programmers found it a bad practice.

All you have to do is return product list from the news_articles() function. Then in your file2 you can simply print the result of that function which is the product list.

import file1
print(file1.news_articles())
  • Related