Home > Software design >  Using a list from one function into another
Using a list from one function into another

Time:02-01

how are you all doing today? I have this code below, requesting in an API

import requests 


def Sults():
  headers = {
        "xxxxxxxxxxxxx",
        "Content-Type":"application/json;charset=UTF-8"
    } 
  url = "https://xxxxxxxxx/api/v1/implantacao/projeto?&dtInicio=2022-08-06T18:02:55Z"
  response = requests.get(url, headers=headers)
  data = response.json() 
  
  print(data) 
  unidades(data)
  testFunction()


def unidades(data):
  id = []
  
  for i in data['data']:
    print(i['nome'])
    print(i['dtInicio'])
    print(i['dtFim'])
    id.append(i['id'])
    print(i['responsavel']['nome'])
    print(i['modelo']) 

  
         
def testFunction():
  

How can i use the id list into this def testFunction? This id list for example returns this into the actual code: [1,2,5,6,7,9,10]

CodePudding user response:

Return the list from unidades() and then pass it as a parameter to testFunction().

def Sults():
  headers = {
        "xxxxxxxxxxxxx",
        "Content-Type":"application/json;charset=UTF-8"
    } 
  url = "https://xxxxxxxxx/api/v1/implantacao/projeto?&dtInicio=2022-08-06T18:02:55Z"
  response = requests.get(url, headers=headers)
  data = response.json() 
  
  print(data) 
  ids = unidades(data)
  testFunction(ids)

def unidades(data):
  id = []
  
  for i in data['data']:
    print(i['nome'])
    print(i['dtInicio'])
    print(i['dtFim'])
    id.append(i['id'])
    print(i['responsavel']['nome'])
    print(i['modelo']) 

  return id

def testFunction(id):
  # use id

CodePudding user response:

Depends on the actual code you'll be writing. What I can currently think of is if you make unidades() return the id list, and then add that into testFunction() as a parameter :D

Like so:

def unidades(data):
   id = []

   for i in data['data']:
       print(i['nome'])
       print(i['dtInicio'])
       print(i['dtFim'])
       id.append(i['id'])
       print(i['responsavel']['nome'])
       print(i['modelo'])
   return id

def Sults():
    # Do all the other stuff
  
    id_list = unidades(data)
    testFunction(id_list)

CodePudding user response:

Bad idea... but you can do like this... better off declaring a class

declare it global

import requests 
id=[]

def Sults():
  global id
  headers = {
        "xxxxxxxxxxxxx",
        "Content-Type":"application/json;charset=UTF-8"
    } 
  url = "https://xxxxxxxxx/api/v1/implantacao/projeto?&dtInicio=2022-08-06T18:02:55Z"
  response = requests.get(url, headers=headers)
  data = response.json() 
  
  print(data) 
  unidades(data)
  testFunction()


def unidades(data):
  global id
  id = []
  
  for i in data['data']:
    print(i['nome'])
    print(i['dtInicio'])
    print(i['dtFim'])
    id.append(i['id'])
    print(i['responsavel']['nome'])
    print(i['modelo']) 

  
         
def testFunction():
   global id
  • Related