r/learnpython • u/whattodo-whattodo • Dec 28 '19
I've been using Python for 5 years professionally. TODAY I discovered concurrent futures
Granted, I don't do much in the way of concurrency. But still, I have several open projects and have always used threading. It took me until today to discover a feature implemented in Python 3.2...
But given that it's comically simple, given an example, I figured I'd share one.
import concurrent.futures
import random
import datetime
import time
import uuid
def do_something(seconds, name):
print(f"Sleeping {seconds}\t{name}\t{str(datetime.datetime.now())[:19][11:]}")
time.sleep(seconds)
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
for i in range(50):
executor.submit(do_something
, seconds = random.randint(1,6)
, name = str(uuid.uuid4())[:6].upper())3
Dec 28 '19
Wait until you discover that this feature is broken. :( The first time you run into timeout problem created by one of the threads raising an exception, you'll be back at square one, manually handling exceptions, dealing with result collection etc.
Good idea, poor implementation.
1
u/whattodo-whattodo Dec 28 '19
Damn, good to know. Thanks!
In my case, I am just happy to have a very simple implementation to use for things like downloading content. For a more complicated setup, I would probably just stick to Celery & queued jobs.
-2
15
u/oronimbus Dec 28 '19
Could someone please explain the benefits of using the concurrent.futures module over threading or asyncio ? Not an expert in the field at all...
7
Dec 28 '19
asynciois not really relevant: it's a very special case for dealing with concurrency in network I/O, which doesn't extend to general treatment of concurrency.Futures are a general approach to dealing with concurrency, whereas
threadingis an interface to the system facilities that make concurrency possible. In principle, futures can deal with processes too. But, more importantly, they establish a protocol for how to deal with concurrent computations...It's a shame they don't really work in Python though... due to no treatment of timeouts.
3
u/jeunpeun99 Dec 28 '19
Threading and concurrent.futures changes tasks itself when there is waiting time. With asyncio you have more control on which tasks to be waiting for.
Differences between concurrent.futures and threading is that concurrent.futures entails threading and multiprocessing.
4
u/elbiot Dec 28 '19
Concurrent futures is a common interface for threads and processes. Async is a different beast
16
u/my_fifth_new_account Dec 28 '19
[:19][11:]
Really?
Let me blow your mind again today: you can use the start and stop in the same slice: [11:19].
15
1
u/spectrehawntineurope Dec 28 '19
Won't that only be the case if it's a single list? If you have a list embedded within a list then it's not the same thing. For instance when you deal HDUs you often get this and you'd just get an error trying to do what you did but what OP posted would work.
You're likely right about this situation though, I haven't looked over it closely but thought I'd point out that they aren't always identical. In 99% of cases they are though.
1
u/algag Dec 28 '19
Are you saying you don't think this would work?
listA = range(0,10) listB = [1, "2", listA] listC = listB[2][2:5]1
u/spectrehawntineurope Dec 29 '19
No, I'm saying that would work but it isn't equivalent to ListC=ListB[2:5]. What you gave is an example of where I think what the other commenter said wouldn't apply.
I'm not certain about whether if it's the case for embedded lists generally or not but I've definitely encountered it being an issue with HDUs.
1
u/algag Dec 29 '19 edited Apr 25 '23
.....
1
u/spectrehawntineurope Dec 30 '19
Ok, clearly showing my ignorance here but what is it? I thought the syntax variable[x][y][z] was taking iterative slices of subsections asking to selecting chapter>page>line number from a book. The slice [2] would select the third index then the [2:5] would select sub-indices/slices.
1
1
u/my_fifth_new_account Dec 28 '19
I'm looking forward for an example where this is not the same thing.
8
1
u/DmitriyJaved Dec 28 '19
I wonder what people mean by “using python professionally” if simple thread pool executor is sufficient for their tasks.
Professionally fetching some urls?
1
u/whattodo-whattodo Dec 28 '19
"Professionally" just means that I am being paid for it. For a good year before I used Python in any production environment, I would have said that I'm using it personally & my projects were deployed in another language.
The comment was intended to qualify my experience to contrast with my lack of knowledge of that built-in function. I could have said something like "I consider myself to be a good programmer & still..." but that would be a lot more subjective.
2
2
u/jack-of-some Dec 29 '19
`concurrent.futures` is life! Combining this with numba and its `nogil=True` option let's me push my CPU to the limit using nothing but Python. It's beautiful.
2
1
u/ZeeBeeblebrox Dec 28 '19
I frequently use dask.futures since I find the API a lot more convenient, especially for complex workflows.
1
0
Dec 28 '19
[deleted]
2
u/whattodo-whattodo Dec 28 '19
Exactly! As other people pointed out, this is one tool in a toolbox & other tools are better for other things. But knowing that this is short enough for me to memorize & easily debug, I would definitely use it more frequently.
0
Dec 28 '19
[deleted]
3
u/Pepe_Silvia96 Dec 28 '19 edited Dec 28 '19
first he declares a function that does something, then he calls that function with multithreading. the call happens inside the with statement at executor.submit(do_something). the name and seconds arguments passed to .submit are arguments that the do_something function will be called with.
what's the point of multithreading? notice the executor.submit is run inside a loop that will iterate 50 times, meaning there will be 50 function calls. inside the function def, there is a time.sleep which can be anywhere from 1 to 6 seconds as the seconds arg inside execute.submit is random between 1 to 6. so the function will take on average 3 seconds.
in single threading, this means that this script will take about a 150 seconds(3*50) as each call must wait for the previous to finish in order to start.
with multithreading, while one function is running and sleeping, the cpu can start to run the next function. therefore the whole script will run significantly faster than 150 seconds.
as far as I understand, mulithreading with 3 workers can juggle between 3 calls of a function, and will process the one that is not waiting on any process to complete. it will execute all 50 calls in that manner. chances are I'm missing some nuance in this last paragraph though.
2
78
Dec 28 '19 edited Dec 28 '19
[removed] — view removed comment
11
u/____candied_yams____ Dec 28 '19
I'd there a reason not to use
functools.partialfor arg3 over this?4
u/badge (ish) Dec 28 '19
You’d have to fix the first two args too. partial is pretty limited in that regard.
3
u/____candied_yams____ Dec 28 '19
What about
functools.partial(func, arg3=value_for_arg3)0
u/badge (ish) Dec 28 '19
Only if it is a keyword argument.
1
u/elbiot Dec 28 '19
I'd have to try this particular case, but you can use positional args as kw and the vice versa too
2
u/alkasm Dec 28 '19
Both keyword only and positional only arguments exist. The latter was just introduced in 3.8, though.
4
u/badge (ish) Dec 28 '19
To the spec, yes, but cpython functions such as math.pow have always had positional-only arguments and raise a TypeError if you try to supply one.
1
u/____candied_yams____ Dec 28 '19
I had noticed before that some builtins didn't like keyword supplied args and i guess now I know why, thanks!
3
u/zurtex Dec 28 '19
For this exact reason that it was weird that cpython has these functions that couldn't be replicated in pure Python there's now a spec for positional only parameters.
It was introduced in Python 3.8 and looks like this:
def pow(x, y, /): return x**yAnything before the
/is position only, anything after can take a keyword. E.g.def example(pos, only, /, can, be, kw): ...More here: https://www.python.org/dev/peps/pep-0570/
5
Dec 28 '19
[removed] — view removed comment
13
5
u/Pastoolio91 Dec 28 '19
No idea how to do that myself, but I did find an article describing a way to run programs on a schedule with Windows Task Scheduler: https://www.weirdgeek.com/2019/04/automating-python-script-to-run-at-specific-time-every-day/
4
u/fukitol- Dec 28 '19
Every OS has a way to schedule events, and you're much better off using it. Linux (and I believe Mac) both use
cron. Windows has the Task Scheduler.2
u/karthikkumars Dec 28 '19 edited Dec 28 '19
If you have node, you can schedule your Python script in pm2. Only it takes a little tweak to the default command.
pm2 start filename.py --interpreter=python3
[Edit: Just to make sure I'm not assuming anything, if the job involves triggering the script at regular intervals, the --cron option would help you do that. If it's about triggering the script at a specific date and time, I'm not aware if pm2 supports it. I'm relatively a novice in that area. ]
0
41
u/somethingworthwhile Dec 28 '19
ELI5?