Python - returns values ​​from a function

I have this configuration file:

[test]
one: value1
two: value2

This function returns elements, values ​​from the test section of the configuration file, but when I call the function, I return only the first element (one, value1).

def getItemsAvailable(section):
    for (item, value) in config.items(section):
        return (item, value)

I call getItemsAvailable () with this function:

def test():
    item, value = getItemsAvailable('test')
    print (item, value)

I assume that I should create a list in the getItemsAvailable () function and return a list to read the values ​​of the test () function, true?

Any suggestions?

Thank!!

+4
source share
2 answers

Use a list comprehension. Change

for (item, value) in config.items(section):
    # the function returns at the end of the 1st iteration
    # hence you get only 1 tuple. 
    # You may also consider using a generator & 'yield'ing the tuples
    return (item, value) 

to

return [(item, value) for item, value in config.items(section)]

And regarding your function test():

def test():
    aList = getItemsAvailable('test')
    print (aList)
+2
source

Use the generator function:

def getItemsAvailable(section):
    for (item, value) in config.items(section):
        yield (item, value)

And we get the following elements:

def test():
    for item, value in getItemsAvailable('test'):
        print (item, value)
+1
source

Source: https://habr.com/ru/post/1628648/


All Articles