Ronikos
Ronikos

Reputation: 447

Python: How to return data more that once during a function call

Is there any way that a function can be called once and then return data mutliple times at distinct times?

For example, suppose I had the following code:

def do_something():
    for i in range(1, 10):
        return 1

However, I want to be able to return more than one piece of data from a single function call, but at asynchronous times, is this possible?


For context, I have a program that generates word documents, converts them into pdfs and then combines them into a single pdf document. I want to be able to call an external function from the GUI to create the documents, and then display a progress bar that displays the current progress through the function.


Edit:

I am already aware of the yield function. I thought my specific problem at the bottom of the question would help. To be clearer, I am looking for is a way to return multiple values from a function and cause a different event for each value returned. Although it may be a poor example, what I want is to be able to do is something similar to a .then(){} in Javascript, but be able to perform the .then(){} using multiple returned values

Upvotes: 0

Views: 976

Answers (3)

bashrc
bashrc

Reputation: 4835

You are looking for generators.

Instead of returning you yield (read What does the "yield" keyword do in Python?) from your function.

def do_something():
    for i in range(1, 10):
        yield i

If you want this function to be called repeatedly you will need to have a wrapper that calls this function repeatedly. Somewhat similar to:

def worker():
    for i in do_something():
       UpdateProgress(i)
       sleep(prgressInterval)

    thread = Thread(target=worker)
    thread.start()

Upvotes: 0

harshil9968
harshil9968

Reputation: 3244

yield is the thing as mentioned by almost everyone for returning or getting multiple values from a function.

Having read your problem statement. Here is the solution I would devise for you.

Create a function to update status bar, the value of status bar would be fetched from a global variable. So global x=0 at starting, and in the update function it will first update the x = x+1 then after that it will increment the status bar.

def do_something():
    for i in range(1, 10):
        # fetch and perform operation on that Doc for PDF
        update_status_bar()

Upvotes: 1

chepner
chepner

Reputation: 531693

You want a generator:

def do_something():
    for i in range(1,10):
        yield i

nums = do_something()

Each time you call next on nums, the body of do_something will continue executing up to the next yield statement, at which point it returns that value.

>>> print next(nums)   # Outputs 1
>>> print next(nums)   # Outputs 2
>>> ...

Upvotes: 0

Related Questions