concurrent-iterator 0.2.4__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- concurrent_iterator-0.4.0/LICENSE +165 -0
- concurrent_iterator-0.4.0/PKG-INFO +91 -0
- concurrent_iterator-0.4.0/README.md +58 -0
- {concurrent-iterator-0.2.4 → concurrent_iterator-0.4.0}/concurrent_iterator/__init__.py +21 -19
- concurrent_iterator-0.4.0/concurrent_iterator/dummy.py +52 -0
- concurrent_iterator-0.4.0/concurrent_iterator/process.py +175 -0
- concurrent_iterator-0.4.0/concurrent_iterator/py.typed +0 -0
- {concurrent-iterator-0.2.4 → concurrent_iterator-0.4.0}/concurrent_iterator/thread.py +36 -35
- concurrent_iterator-0.4.0/concurrent_iterator/utils.py +17 -0
- concurrent_iterator-0.4.0/concurrent_iterator.egg-info/PKG-INFO +91 -0
- {concurrent-iterator-0.2.4 → concurrent_iterator-0.4.0}/concurrent_iterator.egg-info/SOURCES.txt +8 -4
- concurrent_iterator-0.4.0/pyproject.toml +71 -0
- concurrent_iterator-0.4.0/setup.cfg +4 -0
- concurrent_iterator-0.4.0/setup.py +33 -0
- concurrent_iterator-0.4.0/tests/test_dummy.py +24 -0
- concurrent_iterator-0.4.0/tests/test_process.py +150 -0
- concurrent_iterator-0.4.0/tests/test_thread.py +32 -0
- concurrent-iterator-0.2.4/PKG-INFO +0 -22
- concurrent-iterator-0.2.4/concurrent_iterator/connections.py +0 -70
- concurrent-iterator-0.2.4/concurrent_iterator/dummy.py +0 -46
- concurrent-iterator-0.2.4/concurrent_iterator/process.py +0 -120
- concurrent-iterator-0.2.4/concurrent_iterator/utils.py +0 -9
- concurrent-iterator-0.2.4/concurrent_iterator.egg-info/PKG-INFO +0 -22
- concurrent-iterator-0.2.4/concurrent_iterator.egg-info/requires.txt +0 -1
- concurrent-iterator-0.2.4/setup.cfg +0 -8
- concurrent-iterator-0.2.4/setup.py +0 -37
- {concurrent-iterator-0.2.4 → concurrent_iterator-0.4.0}/concurrent_iterator.egg-info/dependency_links.txt +0 -0
- {concurrent-iterator-0.2.4 → concurrent_iterator-0.4.0}/concurrent_iterator.egg-info/top_level.txt +0 -0
- {concurrent-iterator-0.2.4 → concurrent_iterator-0.4.0}/concurrent_iterator.egg-info/zip-safe +0 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: concurrent-iterator
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Classes to run producers (iterators) and consumers (coroutines) in a background thread/process.
|
|
5
|
+
Home-page: https://github.com/jruere/concurrent-iterator
|
|
6
|
+
Author: Javier Ruere
|
|
7
|
+
Author-email: javier@ruere.com.ar
|
|
8
|
+
License: LGPLv3
|
|
9
|
+
Keywords: concurrency,parallelism,iterator,iterable,pipeline
|
|
10
|
+
Platform: POSIX
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
22
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
23
|
+
Classifier: Operating System :: POSIX
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Dynamic: author
|
|
29
|
+
Dynamic: author-email
|
|
30
|
+
Dynamic: home-page
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
Dynamic: platform
|
|
33
|
+
|
|
34
|
+
# concurrent-iterator
|
|
35
|
+
|
|
36
|
+
[](https://pypi.python.org/pypi/concurrent-iterator/)
|
|
37
|
+
[](https://pypi.python.org/pypi/concurrent-iterator/)
|
|
38
|
+
|
|
39
|
+
## Intro
|
|
40
|
+
|
|
41
|
+
Classes to run producers (iterators) and consumers (coroutines) in a background thread/process.
|
|
42
|
+
|
|
43
|
+
There are many libraries to create pipelines with stages running in separate processes, a nice
|
|
44
|
+
one is [parallelpipe](https://pypi.python.org/pypi/parallelpipe), but this library does something
|
|
45
|
+
different. It will lift the entire pipeline up to the point of the Producer into a separate process
|
|
46
|
+
or thread. It's a more coarse library but easier to integrate since things keep looking as normal generators.
|
|
47
|
+
|
|
48
|
+
## Implementations
|
|
49
|
+
|
|
50
|
+
There are currently 3 implementations:
|
|
51
|
+
|
|
52
|
+
* `dummy.Producer`: non-concurrent implementation
|
|
53
|
+
* `thread.Producer`: uses a background thread to run the generator
|
|
54
|
+
* `process.Producer`: uses a background process to run the generator
|
|
55
|
+
|
|
56
|
+
`dummy.Producer` is useless in practice.
|
|
57
|
+
|
|
58
|
+
`thread.Producer` is useful for IO bound generators.
|
|
59
|
+
|
|
60
|
+
`process.Producer` is useful for CPU or IO bound generators.
|
|
61
|
+
It has the complications of dealing with processes (different memory spaces,
|
|
62
|
+
logging, etc).
|
|
63
|
+
For logging, module [`multiprocessing-logging`](https://github.com/jruere/multiprocessing-logging) can be used.
|
|
64
|
+
|
|
65
|
+
> **Limitations:** `process.Producer`/`process.Consumer` with generators,
|
|
66
|
+
> coroutines and other unpicklable objects require the `fork` start method.
|
|
67
|
+
> Python 3.14 changes the default on Linux from `fork` to `forkserver`,
|
|
68
|
+
> and `spawn`/`forkserver` cannot pickle generators (`TypeError: cannot
|
|
69
|
+
> pickle 'generator' object`). In those cases `process.Producer` now raises
|
|
70
|
+
> `RuntimeError` with a clear message. Use `thread.Producer`/`thread.Consumer`,
|
|
71
|
+
> a picklable iterable (e.g. `iter([1,2,3])`), or force `fork` via
|
|
72
|
+
> `multiprocessing.set_start_method('fork', force=True)` or
|
|
73
|
+
> `multiprocessing.get_context('fork').Process`/`Queue` where `fork` is
|
|
74
|
+
> available (Linux).
|
|
75
|
+
|
|
76
|
+
## Usage
|
|
77
|
+
|
|
78
|
+
Basic example:
|
|
79
|
+
|
|
80
|
+
from concurrent_iterator.thread import Producer
|
|
81
|
+
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
items = Producer(slow_generator, maxsize=5)
|
|
85
|
+
|
|
86
|
+
for item in items:
|
|
87
|
+
[Do some time consuming task]
|
|
88
|
+
|
|
89
|
+
In the previous example, while doing some time consuming task, the
|
|
90
|
+
`slow_generator` will continue running in a background thread and will
|
|
91
|
+
pre-calculate up to 5 values.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# concurrent-iterator
|
|
2
|
+
|
|
3
|
+
[](https://pypi.python.org/pypi/concurrent-iterator/)
|
|
4
|
+
[](https://pypi.python.org/pypi/concurrent-iterator/)
|
|
5
|
+
|
|
6
|
+
## Intro
|
|
7
|
+
|
|
8
|
+
Classes to run producers (iterators) and consumers (coroutines) in a background thread/process.
|
|
9
|
+
|
|
10
|
+
There are many libraries to create pipelines with stages running in separate processes, a nice
|
|
11
|
+
one is [parallelpipe](https://pypi.python.org/pypi/parallelpipe), but this library does something
|
|
12
|
+
different. It will lift the entire pipeline up to the point of the Producer into a separate process
|
|
13
|
+
or thread. It's a more coarse library but easier to integrate since things keep looking as normal generators.
|
|
14
|
+
|
|
15
|
+
## Implementations
|
|
16
|
+
|
|
17
|
+
There are currently 3 implementations:
|
|
18
|
+
|
|
19
|
+
* `dummy.Producer`: non-concurrent implementation
|
|
20
|
+
* `thread.Producer`: uses a background thread to run the generator
|
|
21
|
+
* `process.Producer`: uses a background process to run the generator
|
|
22
|
+
|
|
23
|
+
`dummy.Producer` is useless in practice.
|
|
24
|
+
|
|
25
|
+
`thread.Producer` is useful for IO bound generators.
|
|
26
|
+
|
|
27
|
+
`process.Producer` is useful for CPU or IO bound generators.
|
|
28
|
+
It has the complications of dealing with processes (different memory spaces,
|
|
29
|
+
logging, etc).
|
|
30
|
+
For logging, module [`multiprocessing-logging`](https://github.com/jruere/multiprocessing-logging) can be used.
|
|
31
|
+
|
|
32
|
+
> **Limitations:** `process.Producer`/`process.Consumer` with generators,
|
|
33
|
+
> coroutines and other unpicklable objects require the `fork` start method.
|
|
34
|
+
> Python 3.14 changes the default on Linux from `fork` to `forkserver`,
|
|
35
|
+
> and `spawn`/`forkserver` cannot pickle generators (`TypeError: cannot
|
|
36
|
+
> pickle 'generator' object`). In those cases `process.Producer` now raises
|
|
37
|
+
> `RuntimeError` with a clear message. Use `thread.Producer`/`thread.Consumer`,
|
|
38
|
+
> a picklable iterable (e.g. `iter([1,2,3])`), or force `fork` via
|
|
39
|
+
> `multiprocessing.set_start_method('fork', force=True)` or
|
|
40
|
+
> `multiprocessing.get_context('fork').Process`/`Queue` where `fork` is
|
|
41
|
+
> available (Linux).
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
Basic example:
|
|
46
|
+
|
|
47
|
+
from concurrent_iterator.thread import Producer
|
|
48
|
+
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
items = Producer(slow_generator, maxsize=5)
|
|
52
|
+
|
|
53
|
+
for item in items:
|
|
54
|
+
[Do some time consuming task]
|
|
55
|
+
|
|
56
|
+
In the previous example, while doing some time consuming task, the
|
|
57
|
+
`slow_generator` will continue running in a background thread and will
|
|
58
|
+
pre-calculate up to 5 values.
|
|
@@ -1,21 +1,26 @@
|
|
|
1
|
-
|
|
2
|
-
from abc import ABCMeta, abstractmethod, abstractproperty
|
|
3
|
-
from collections import Iterator
|
|
1
|
+
from __future__ import annotations
|
|
4
2
|
|
|
3
|
+
from abc import ABCMeta, abstractmethod
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
from typing import Generic, TypeVar
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
T_co = TypeVar("T_co", covariant=True)
|
|
9
|
+
T_contra = TypeVar("T_contra", contravariant=True)
|
|
7
10
|
|
|
8
11
|
|
|
9
|
-
class StopIterationSentinel
|
|
12
|
+
class StopIterationSentinel:
|
|
10
13
|
"""Sentinel to signal the end of data."""
|
|
11
14
|
|
|
12
|
-
|
|
15
|
+
|
|
16
|
+
class ExceptionInUserIterable:
|
|
13
17
|
"""User-provided iterable raises an exception."""
|
|
14
18
|
|
|
15
|
-
def __init__(self, exception):
|
|
16
|
-
self.exception = exception
|
|
19
|
+
def __init__(self, exception: BaseException) -> None:
|
|
20
|
+
self.exception: BaseException = exception
|
|
21
|
+
|
|
17
22
|
|
|
18
|
-
class IProducer(Iterator):
|
|
23
|
+
class IProducer(Iterator[T_co], metaclass=ABCMeta):
|
|
19
24
|
"""Interface for Producers.
|
|
20
25
|
|
|
21
26
|
Implementations of this interface are "normal" iterators that accept an
|
|
@@ -23,10 +28,8 @@ class IProducer(Iterator):
|
|
|
23
28
|
iterator in parallel and buffering a number of values.
|
|
24
29
|
"""
|
|
25
30
|
|
|
26
|
-
__metaclass__ = ABCMeta
|
|
27
|
-
|
|
28
31
|
@abstractmethod
|
|
29
|
-
def __next__(self):
|
|
32
|
+
def __next__(self) -> T_co:
|
|
30
33
|
pass
|
|
31
34
|
|
|
32
35
|
|
|
@@ -34,13 +37,11 @@ class WillNotConsume(Exception):
|
|
|
34
37
|
"""The consumer refuses to accept the given value."""
|
|
35
38
|
|
|
36
39
|
|
|
37
|
-
class IConsumer(
|
|
40
|
+
class IConsumer(Generic[T_contra], metaclass=ABCMeta):
|
|
38
41
|
"""Wraps coroutine like objects to execute them in parallel."""
|
|
39
42
|
|
|
40
|
-
__metaclass__ = ABCMeta
|
|
41
|
-
|
|
42
43
|
@abstractmethod
|
|
43
|
-
def send(self, value, timeout=0):
|
|
44
|
+
def send(self, value: T_contra, timeout: float = 0) -> None:
|
|
44
45
|
"""Feeds a value to the consumer.
|
|
45
46
|
|
|
46
47
|
:param value: Value to send.
|
|
@@ -54,9 +55,10 @@ class IConsumer(object):
|
|
|
54
55
|
"""
|
|
55
56
|
|
|
56
57
|
@abstractmethod
|
|
57
|
-
def close(self):
|
|
58
|
+
def close(self) -> None:
|
|
58
59
|
"""Waits for the IConsumer to finish up and be destroyed."""
|
|
59
60
|
|
|
60
|
-
@
|
|
61
|
-
|
|
61
|
+
@property
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def closed(self) -> bool:
|
|
62
64
|
"""Whether the consumer has been closed."""
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable, Iterator
|
|
4
|
+
from typing import Any, TypeVar
|
|
5
|
+
|
|
6
|
+
from concurrent_iterator import IConsumer, IProducer
|
|
7
|
+
from concurrent_iterator.utils import check_open
|
|
8
|
+
|
|
9
|
+
T = TypeVar("T")
|
|
10
|
+
T_co = TypeVar("T_co", covariant=True)
|
|
11
|
+
T_contra = TypeVar("T_contra", contravariant=True)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Producer(IProducer[T_co]):
|
|
15
|
+
"""Dummy implementation that doesn't use concurrency."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, iterable: Iterable[T_co], maxsize: int | None = None) -> None:
|
|
18
|
+
"""In this implementation, maxsize is included to ease replacing
|
|
19
|
+
implementations but it's ignored.
|
|
20
|
+
"""
|
|
21
|
+
self._iterator: Iterator[T_co] = iter(iterable)
|
|
22
|
+
|
|
23
|
+
def __next__(self) -> T_co:
|
|
24
|
+
return next(self._iterator)
|
|
25
|
+
|
|
26
|
+
def next(self) -> T_co:
|
|
27
|
+
return self.__next__()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Consumer(IConsumer[T_contra]):
|
|
31
|
+
"""Dummy implementation that doesn't use concurrency.
|
|
32
|
+
|
|
33
|
+
The timeout parameter is ignored, this implementation will block forever.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, coroutine: Any) -> None:
|
|
37
|
+
self._coroutine: Any = coroutine
|
|
38
|
+
|
|
39
|
+
self._closed: bool = False
|
|
40
|
+
|
|
41
|
+
@check_open
|
|
42
|
+
def send(self, value: T_contra, timeout: float = 0) -> None:
|
|
43
|
+
self._coroutine.send(value)
|
|
44
|
+
|
|
45
|
+
@check_open
|
|
46
|
+
def close(self) -> None:
|
|
47
|
+
self._closed = True # Nothing to do.
|
|
48
|
+
self._coroutine.close()
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def closed(self) -> bool:
|
|
52
|
+
return self._closed
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import logging
|
|
5
|
+
import multiprocessing
|
|
6
|
+
import multiprocessing.queues
|
|
7
|
+
import pickle
|
|
8
|
+
from collections.abc import Iterable, Iterator
|
|
9
|
+
from queue import Full
|
|
10
|
+
from typing import Any, TypeVar, cast
|
|
11
|
+
|
|
12
|
+
from concurrent_iterator import (
|
|
13
|
+
ExceptionInUserIterable,
|
|
14
|
+
IConsumer,
|
|
15
|
+
IProducer,
|
|
16
|
+
StopIterationSentinel,
|
|
17
|
+
WillNotConsume,
|
|
18
|
+
)
|
|
19
|
+
from concurrent_iterator.utils import check_open
|
|
20
|
+
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
T_co = TypeVar("T_co", covariant=True)
|
|
23
|
+
T_contra = TypeVar("T_contra", contravariant=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Producer(IProducer[T_co]):
|
|
27
|
+
"""Uses a separate process to produce and buffer values from the given
|
|
28
|
+
iterable.
|
|
29
|
+
|
|
30
|
+
This implementation is useful for IO or CPU bound consumers.
|
|
31
|
+
|
|
32
|
+
See multiprocessing.Pool for a more useful abstraction for CPU bound
|
|
33
|
+
producers.
|
|
34
|
+
|
|
35
|
+
For logging to work properly, use multiprocessing-logging.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, iterable: Iterable[T_co], maxsize: int = 100, chunksize: int = 1) -> None:
|
|
39
|
+
assert chunksize > 0
|
|
40
|
+
assert maxsize >= chunksize
|
|
41
|
+
|
|
42
|
+
self._iterator: Iterator[T_co] = iter(iterable)
|
|
43
|
+
|
|
44
|
+
self._queue: Any = multiprocessing.Queue(maxsize // chunksize)
|
|
45
|
+
self._process: multiprocessing.Process = multiprocessing.Process(
|
|
46
|
+
target=self._run,
|
|
47
|
+
args=(self._iterator, self._queue, chunksize),
|
|
48
|
+
)
|
|
49
|
+
self._process.daemon = True
|
|
50
|
+
self._current_chunk: list[Any] | None = None
|
|
51
|
+
self._log: logging.Logger = logging.getLogger(__name__ + "." + type(self).__name__)
|
|
52
|
+
|
|
53
|
+
self._log.info("Starting process.")
|
|
54
|
+
try:
|
|
55
|
+
self._process.start()
|
|
56
|
+
except (TypeError, pickle.PicklingError) as e:
|
|
57
|
+
if multiprocessing.get_start_method() != "fork":
|
|
58
|
+
raise RuntimeError(
|
|
59
|
+
"process.Producer with generators and other unpicklable "
|
|
60
|
+
"iterables requires start method 'fork', got "
|
|
61
|
+
f"'{multiprocessing.get_start_method()}' (Python 3.14 defaults to 'forkserver'). Use "
|
|
62
|
+
"thread.Producer, a picklable iterable, or "
|
|
63
|
+
"multiprocessing.set_start_method('fork', force=True) / "
|
|
64
|
+
"multiprocessing.get_context('fork')."
|
|
65
|
+
) from e
|
|
66
|
+
raise
|
|
67
|
+
|
|
68
|
+
def __next__(self) -> T_co:
|
|
69
|
+
if self._current_chunk:
|
|
70
|
+
pass
|
|
71
|
+
elif self._queue is None:
|
|
72
|
+
self._log.debug("Producer is exhausted.")
|
|
73
|
+
raise StopIteration
|
|
74
|
+
else:
|
|
75
|
+
chunk: Any = self._queue.get()
|
|
76
|
+
if chunk is StopIterationSentinel or chunk == StopIterationSentinel:
|
|
77
|
+
self._process.join()
|
|
78
|
+
|
|
79
|
+
assert self._queue is not None
|
|
80
|
+
self._queue.close()
|
|
81
|
+
self._queue = None
|
|
82
|
+
raise StopIteration
|
|
83
|
+
else:
|
|
84
|
+
assert chunk
|
|
85
|
+
chunk.reverse() # To consume it from the end.
|
|
86
|
+
self._current_chunk = chunk
|
|
87
|
+
|
|
88
|
+
assert self._current_chunk is not None
|
|
89
|
+
item: Any = self._current_chunk.pop()
|
|
90
|
+
if isinstance(item, ExceptionInUserIterable):
|
|
91
|
+
self._process.join()
|
|
92
|
+
|
|
93
|
+
if self._queue is not None:
|
|
94
|
+
self._queue.close()
|
|
95
|
+
self._queue = None
|
|
96
|
+
|
|
97
|
+
raise item.exception
|
|
98
|
+
|
|
99
|
+
return cast(T_co, item)
|
|
100
|
+
|
|
101
|
+
def next(self) -> T_co:
|
|
102
|
+
return self.__next__()
|
|
103
|
+
|
|
104
|
+
def _run(self, iterator: Iterator[T_co], queue: Any, chunksize: int) -> None:
|
|
105
|
+
chunk: list[Any] = []
|
|
106
|
+
try:
|
|
107
|
+
while True:
|
|
108
|
+
# Items must be added one at a time to avoid losing items
|
|
109
|
+
# before an exception.
|
|
110
|
+
chunk.extend(itertools.islice(iterator, chunksize))
|
|
111
|
+
if not chunk:
|
|
112
|
+
queue.put(StopIterationSentinel) # Signal we are done.
|
|
113
|
+
break
|
|
114
|
+
else:
|
|
115
|
+
queue.put(chunk)
|
|
116
|
+
chunk = []
|
|
117
|
+
except Exception as e: # noqa: BLE001 # intentional: forward user iterable exception
|
|
118
|
+
self._log.exception("Exception on iterator.")
|
|
119
|
+
|
|
120
|
+
chunk.append(ExceptionInUserIterable(e))
|
|
121
|
+
queue.put(chunk)
|
|
122
|
+
queue.close()
|
|
123
|
+
queue.join_thread()
|
|
124
|
+
|
|
125
|
+
# Per PEP 255, this terminates the iterable.
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class Consumer(IConsumer[T_contra]):
|
|
129
|
+
"""Feeds the given coroutine in a separate process."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, coroutine: Any, maxsize: int = 1) -> None:
|
|
132
|
+
self._coroutine: Any = coroutine
|
|
133
|
+
|
|
134
|
+
self._closed: bool = False
|
|
135
|
+
self._queue: Any = multiprocessing.Queue(maxsize)
|
|
136
|
+
self._process: multiprocessing.Process = multiprocessing.Process(
|
|
137
|
+
target=self._run, args=(coroutine, self._queue)
|
|
138
|
+
)
|
|
139
|
+
self._process.daemon = True
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
self._process.start()
|
|
143
|
+
except (TypeError, pickle.PicklingError) as e:
|
|
144
|
+
if multiprocessing.get_start_method() != "fork":
|
|
145
|
+
raise RuntimeError(
|
|
146
|
+
"process.Consumer with unpicklable coroutines requires "
|
|
147
|
+
f"start method 'fork', got '{multiprocessing.get_start_method()}' (Python 3.14 defaults to "
|
|
148
|
+
"'forkserver'). Use thread.Consumer or "
|
|
149
|
+
"multiprocessing.set_start_method('fork', force=True) / "
|
|
150
|
+
"multiprocessing.get_context('fork')."
|
|
151
|
+
) from e
|
|
152
|
+
raise
|
|
153
|
+
|
|
154
|
+
@check_open
|
|
155
|
+
def send(self, value: T_contra, timeout: float = 0) -> None:
|
|
156
|
+
try:
|
|
157
|
+
self._queue.put(value, block=(timeout != 0), timeout=timeout)
|
|
158
|
+
except Full:
|
|
159
|
+
raise WillNotConsume()
|
|
160
|
+
|
|
161
|
+
@check_open
|
|
162
|
+
def close(self) -> None:
|
|
163
|
+
self._closed = True
|
|
164
|
+
self._queue.put(StopIterationSentinel)
|
|
165
|
+
self._process.join()
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def closed(self) -> bool:
|
|
169
|
+
return self._closed
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
def _run(coroutine: Any, queue: Any) -> None:
|
|
173
|
+
for value in iter(queue.get, StopIterationSentinel):
|
|
174
|
+
coroutine.send(value)
|
|
175
|
+
coroutine.close()
|
|
File without changes
|