signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@dualmethod<EOL><INDENT>def map(cls, iterable, func, *a, **kw):<DEDENT> | return cls(func(x, *a, **kw) for x in iterable)<EOL> | Iterable-first replacement of Python's built-in `map()` function. | f12747:c0:m4 |
@dualmethod<EOL><INDENT>def filter(cls, iterable, cond, *a, **kw):<DEDENT> | return cls(x for x in iterable if cond(x, *a, **kw))<EOL> | Iterable-first replacement of Python's built-in `filter()` function. | f12747:c0:m5 |
@dualmethod<EOL><INDENT>def unique(cls, iterable, key=None):<DEDENT> | if key is None:<EOL><INDENT>key = lambda x: x<EOL><DEDENT>def generator():<EOL><INDENT>seen = set()<EOL>seen_add = seen.add<EOL>for item in iterable:<EOL><INDENT>key_val = key(item)<EOL>if key_val not in seen:<EOL><INDENT>seen_add(key_val)<EOL>yield item<EOL><DEDENT><DEDENT><DEDENT>return cls(generator())<EOL> | Yields unique items from *iterable* whilst preserving the original order. | f12747:c0:m6 |
@dualmethod<EOL><INDENT>def chunks(cls, iterable, n, fill=None):<DEDENT> | return cls(itertools.zip_longest(*[iter(iterable)] * n, fillvalue=fill))<EOL> | Collects elements in fixed-length chunks. | f12747:c0:m7 |
@dualmethod<EOL><INDENT>def concat(cls, iterables):<DEDENT> | def generator():<EOL><INDENT>for it in iterables:<EOL><INDENT>for element in it:<EOL><INDENT>yield element<EOL><DEDENT><DEDENT><DEDENT>return cls(generator())<EOL> | Similar to #itertools.chain.from_iterable(). | f12747:c0:m8 |
@dualmethod<EOL><INDENT>def chain(cls, *iterables):<DEDENT> | def generator():<EOL><INDENT>for it in iterables:<EOL><INDENT>for element in it:<EOL><INDENT>yield element<EOL><DEDENT><DEDENT><DEDENT>return cls(generator())<EOL> | Similar to #itertools.chain.from_iterable(). | f12747:c0:m9 |
@dualmethod<EOL><INDENT>def attr(cls, iterable, attr_name):<DEDENT> | return cls(getattr(x, attr_name) for x in iterable)<EOL> | Applies #getattr() on all elements of *iterable*. | f12747:c0:m10 |
@dualmethod<EOL><INDENT>def item(cls, iterable, key):<DEDENT> | return cls(x[key] for x in iterable)<EOL> | Applies `__getitem__` on all elements of *iterable*. | f12747:c0:m11 |
@dualmethod<EOL><INDENT>def of_type(cls, iterable, types):<DEDENT> | return cls(x for x in iterable if isinstance(x, types))<EOL> | Filters using #isinstance(). | f12747:c0:m12 |
@dualmethod<EOL><INDENT>def partition(cls, iterable, pred):<DEDENT> | t1, t2 = itertools.tee(iterable)<EOL>return cls(itertools.filterfalse(pred, t1), filter(pred, t2))<EOL> | Use a predicate to partition items into false and true entries. | f12747:c0:m13 |
@dualmethod<EOL><INDENT>def count(cls, iterable):<DEDENT> | iterable = iter(iterable)<EOL>count = <NUM_LIT:0><EOL>while True:<EOL><INDENT>try:<EOL><INDENT>next(iterable)<EOL><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT>count += <NUM_LIT:1><EOL><DEDENT>return count<EOL> | Returns the number of items in an iterable. | f12747:c0:m19 |
def __iter__(self): | for key in self.__slots__:<EOL><INDENT>yield getattr(self, key)<EOL><DEDENT> | Iterate over the values of the record in order. | f12748:c0:m2 |
def __len__(self): | return len(self.__slots__)<EOL> | Returns the number of slots in the record. | f12748:c0:m3 |
def __getitem__(self, index_or_key): | if isinstance(index_or_key, int):<EOL><INDENT>return getattr(self, self.__slots__[index_or_key])<EOL><DEDENT>elif isinstance(index_or_key, str):<EOL><INDENT>if index_or_key not in self.__slots__:<EOL><INDENT>raise KeyError(index_or_key)<EOL><DEDENT>return getattr(self, index_or_key)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT> | Read the value of a slot by its index or name.
:param index_or_key:
:raise TypeError:
:raise IndexError:
:raise KeyError: | f12748:c0:m4 |
def __setitem__(self, index_or_key, value): | if isinstance(index_or_key, int):<EOL><INDENT>setattr(self, self.__slots__[index_or_key], value)<EOL><DEDENT>elif isinstance(index_or_key, str):<EOL><INDENT>if index_or_key not in self.__slots__:<EOL><INDENT>raise KeyError(index_or_key)<EOL><DEDENT>setattr(self, index_or_key, value)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT> | Set the value of a slot by its index or name.
:param index_or_key:
:raise TypeError:
:raise IndexError:
:raise KeyError: | f12748:c0:m5 |
def items(self): | for key in self.__slots__:<EOL><INDENT>yield key, getattr(self, key)<EOL><DEDENT> | Iterator for the key-value pairs of the record. | f12748:c0:m9 |
def keys(self): | return iter(self.__slots__)<EOL> | Iterator for the member names of the record. | f12748:c0:m10 |
def values(self): | for key in self.__slots__:<EOL><INDENT>yield getattr(self, key)<EOL><DEDENT> | Iterator for the values of the object, like :meth:`__iter__`. | f12748:c0:m11 |
@classmethod<EOL><INDENT>def new(cls, __name, __fields, **defaults):<DEDENT> | name = __name<EOL>fields = __fields<EOL>fieldset = set(fields)<EOL>if isinstance(fields, str):<EOL><INDENT>if '<STR_LIT:U+002C>' in fields:<EOL><INDENT>fields = fields.split('<STR_LIT:U+002C>')<EOL><DEDENT>else:<EOL><INDENT>fields = fields.split()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fields = list(fields)<EOL><DEDENT>for key in defaults.keys():<EOL><INDENT>if key not in fields:<EOL><INDENT>fields.append(key)<EOL><DEDENT><DEDENT>class _record(cls):<EOL><INDENT>__slots__ = fields<EOL>__defaults__ = defaults<EOL><DEDENT>_record.__name__ = name<EOL>return _record<EOL> | Creates a new class that can represent a record with the
specified *fields*. This is equal to a mutable namedtuple.
The returned class also supports keyword arguments in its
constructor.
:param __name: The name of the recordclass.
:param __fields: A string or list of field names.
:param defaults: Default values for fields. The defaults
may list field names that haven't been listed in *fields*. | f12748:c0:m13 |
def synchronized(obj): | if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return obj.synchronizable_condition<EOL><DEDENT>elif callable(obj):<EOL><INDENT>@functools.wraps(obj)<EOL>def wrapper(self, *args, **kwargs):<EOL><INDENT>with self.synchronizable_condition:<EOL><INDENT>return obj(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return wrapper<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT> | This function has two purposes:
1. Decorate a function that automatically synchronizes access to the object
passed as the first argument (usually `self`, for member methods)
2. Synchronize access to the object, used in a `with`-statement.
Note that you can use #wait(), #notify() and #notify_all() only on
synchronized objects.
# Example
```python
class Box(Synchronizable):
def __init__(self):
self.value = None
@synchronized
def get(self):
return self.value
@synchronized
def set(self, value):
self.value = value
box = Box()
box.set('foobar')
with synchronized(box):
box.value = 'taz\'dingo'
print(box.get())
```
# Arguments
obj (Synchronizable, function): The object to synchronize access to, or a
function to decorate.
# Returns
1. The decorated function.
2. The value of `obj.synchronizable_condition`, which should implement the
context-manager interface (to be used in a `with`-statement). | f12751:m0 |
def wait(obj, timeout=None): | if timeout is None:<EOL><INDENT>return obj.synchronizable_condition.wait()<EOL><DEDENT>else:<EOL><INDENT>return obj.synchronizable_condition.wait(timeout)<EOL><DEDENT> | Wait until *obj* gets notified with #notify() or #notify_all(). If a timeout
is specified, the function can return without the object being notified if
the time runs out.
Note that you can only use this function on #synchronized() objects.
# Arguments
obj (Synchronizable): An object that can be synchronized.
timeout (number, None): The number of seconds to wait for the object to get
notified before returning. If not value or the value #None is specified,
the function will wait indefinetily. | f12751:m1 |
def wait_for_condition(obj, cond, timeout=None): | with synchronized(obj):<EOL><INDENT>if timeout is None:<EOL><INDENT>while not cond(obj):<EOL><INDENT>wait(obj)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>t_start = time.time()<EOL>while not cond(obj):<EOL><INDENT>t_delta = time.time() - t_start<EOL>if t_delta >= timeout:<EOL><INDENT>return False<EOL><DEDENT>wait(obj, timeout - t_delta)<EOL><DEDENT><DEDENT><DEDENT>return True<EOL> | This is an extended version of #wait() that applies the function *cond* to
check for a condition to break free from waiting on *obj*. Note that *obj*
must be notified when its state changes in order to check the condition.
Note that access to *obj* is synchronized when *cond* is called.
# Arguments
obj (Synchronizable): The object to synchronize and wait for *cond*.
cond (function): A function that accepts *obj* as an argument. Must return
#True if the condition is met.
timeout (number, None): The maximum number of seconds to wait.
# Returns
bool: #True if the condition was met, #False if not and a timeout ocurred. | f12751:m2 |
def notify(obj): | return obj.synchronizable_condition.notify()<EOL> | Notify *obj* so that a single thread that is waiting for the object with
#wait() can continue. Note that you can only use this function on
#synchronized() objects.
# Arguments
obj (Synchronizable): The object to notify. | f12751:m3 |
def notify_all(obj): | return obj.synchronizable_condition.notify_all()<EOL> | Like #notify(), but allow all waiting threads to continue. | f12751:m4 |
def as_completed(jobs): | jobs = tuple(jobs)<EOL>event = threading.Event()<EOL>callback = lambda f, ev: event.set()<EOL>[job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs]<EOL>[job.add_listener(Job.ERROR, callback, once=True) for job in jobs]<EOL>while jobs:<EOL><INDENT>event.wait()<EOL>event.clear()<EOL>jobs, finished = split_list_by(jobs, lambda x: x.finished)<EOL>for job in finished:<EOL><INDENT>yield job<EOL><DEDENT><DEDENT> | Generator function that yields the jobs in order of their
completion. Attaches a new listener to each job. | f12751:m5 |
def split_list_by(lst, key): | first, second = [], []<EOL>for item in lst:<EOL><INDENT>if key(item):<EOL><INDENT>second.append(item)<EOL><DEDENT>else:<EOL><INDENT>first.append(item)<EOL><DEDENT><DEDENT>return (first, second)<EOL> | Splits a list by the callable *key* where a negative result will cause the
item to be put in the first list and a positive into the second list. | f12751:m6 |
def reraise(tpe, value, tb=None): | Py3 = (sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3>)<EOL>if value is None:<EOL><INDENT>value = tpe()<EOL><DEDENT>if Py3:<EOL><INDENT>if value.__traceback__ is not tb:<EOL><INDENT>raise value.with_traceback(tb)<EOL><DEDENT>raise value<EOL><DEDENT>else:<EOL><INDENT>exec('<STR_LIT>')<EOL><DEDENT> | Reraise an exception from an exception info tuple. | f12751:m7 |
@property<EOL><INDENT>@synchronized<EOL>def state(self):<DEDENT> | return self.__state<EOL> | The job's state, one of #PENDING, #RUNNING, #ERROR, #SUCCESS or #CANCELLED. | f12751:c2:m2 |
@property<EOL><INDENT>@synchronized<EOL>def result(self):<DEDENT> | if self.__cancelled:<EOL><INDENT>raise Job.Cancelled<EOL><DEDENT>elif self.__state in (Job.PENDING, Job.RUNNING):<EOL><INDENT>raise Job.InvalidState('<STR_LIT>'.format(self.__state))<EOL><DEDENT>elif self.__state == Job.ERROR:<EOL><INDENT>reraise(*self.__exception)<EOL><DEDENT>elif self.__state == Job.SUCCESS:<EOL><INDENT>return self.__result<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>'.format(self.__state))<EOL><DEDENT> | The result of the jobs execution. Accessing this property while the job is
pending or running will raise #InvalidState. If an exception occured during
the jobs execution, it will be raised.
# Raises
InvalidState: If the job is not in state #FINISHED.
Cancelled: If the job was cancelled.
any: If an exception ocurred during the job's execution. | f12751:c2:m3 |
@property<EOL><INDENT>@synchronized<EOL>def exception(self):<DEDENT> | if self.__state in (Job.PENDING, Job.RUNNING):<EOL><INDENT>raise self.InvalidState('<STR_LIT>'.format(self.__state))<EOL><DEDENT>elif self.__state == Job.ERROR:<EOL><INDENT>assert self.__exception is not None<EOL>return self.__exception<EOL><DEDENT>elif self.__state in (Job.RUNNING, Job.SUCCESS, Job.CANCELLED):<EOL><INDENT>assert self.__exception is None<EOL>return None<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>'.format(self.__state))<EOL><DEDENT> | The exception that occured while the job executed. The value is #None if
no exception occurred.
# Raises
InvalidState: If the job is #PENDING or #RUNNING. | f12751:c2:m4 |
@property<EOL><INDENT>@synchronized<EOL>def pending(self):<DEDENT> | return self.__state == Job.PENDING<EOL> | True if the job is #PENDING. | f12751:c2:m5 |
@property<EOL><INDENT>@synchronized<EOL>def running(self):<DEDENT> | return self.__state == Job.RUNNING<EOL> | True if the job is #RUNNING. | f12751:c2:m6 |
@property<EOL><INDENT>@synchronized<EOL>def finished(self):<DEDENT> | return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)<EOL> | True if the job run and finished. There is no difference if the job
finished successfully or errored. | f12751:c2:m7 |
@property<EOL><INDENT>@synchronized<EOL>def cancelled(self):<DEDENT> | return self.__cancelled<EOL> | This property indicates if the job was cancelled. Note that with this flag
set, the job can still be in any state (eg. a pending job can also be
cancelled, starting it will simply not run the job). | f12751:c2:m8 |
@synchronized<EOL><INDENT>def get(self, default=None):<DEDENT> | if not self.__cancelled and self.__state == Job.SUCCESS:<EOL><INDENT>return self.__result<EOL><DEDENT>else:<EOL><INDENT>return default<EOL><DEDENT> | Get the result of the Job, or return *default* if the job is not finished
or errored. This function will never explicitly raise an exception. Note
that the *default* value is also returned if the job was cancelled.
# Arguments
default (any): The value to return when the result can not be obtained. | f12751:c2:m9 |
def cancel(self): | with synchronized(self):<EOL><INDENT>cancelled = self.__cancelled<EOL>if not cancelled:<EOL><INDENT>self.__cancelled = True<EOL>notify_all(self)<EOL><DEDENT><DEDENT>if not cancelled:<EOL><INDENT>self._trigger_event(Job.CANCELLED)<EOL><DEDENT> | Cancels the job. Functions should check the #Job.cancelled flag from time
to time to be able to abort pre-emptively if the job was cancelled instead
of running forever. | f12751:c2:m10 |
@synchronized<EOL><INDENT>def _trigger_event(self, event):<DEDENT> | if event is None or event not in self.__listeners:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(event))<EOL><DEDENT>if event in self.__event_set:<EOL><INDENT>raise RuntimeError('<STR_LIT>'.format(event))<EOL><DEDENT>self.__event_set.add(event)<EOL>listeners = self.__listeners[event] + self.__listeners[None]<EOL>self.__listeners[event][:] = (l for l in self.__listeners[event] if not l.once)<EOL>self.__listeners[None][:] = (l for l in self.__listeners[None] if not l.once)<EOL>for listener in listeners:<EOL><INDENT>listener.callback(self, event)<EOL><DEDENT> | Private. Triggers and event and removes all one-off listeners for that event. | f12751:c2:m11 |
def add_listener(self, event, callback, once=False): | if not callable(callback):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if isinstance(event, str):<EOL><INDENT>event = [event]<EOL><DEDENT>for evn in event:<EOL><INDENT>if evn not in self.__listeners:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(evn))<EOL><DEDENT><DEDENT>for evn in event:<EOL><INDENT>event_passed = False<EOL>with synchronized(self):<EOL><INDENT>event_passed = (evn in self.__event_set)<EOL>if not (once and event_passed):<EOL><INDENT>self.__listeners[evn].append(Job._Listener(callback, once))<EOL><DEDENT><DEDENT><DEDENT>if event_passed:<EOL><INDENT>callback(self, event)<EOL><DEDENT> | Register a *callback* for the specified *event*. The function will be
called with the #Job as its first argument. If *once* is #True, the
listener will be removed after it has been invoked once or when the
job is re-started.
Note that if the event already ocurred, *callback* will be called
immediately!
# Arguments
event (str, list of str): The name or multiple names of an event, or None
to register the callback to be called for any event.
callback (callable): A function.
once (bool): Whether the callback is valid only once. | f12751:c2:m12 |
def wait(self, timeout=None): | def cond(self):<EOL><INDENT>return self.__state not in (Job.PENDING, Job.RUNNING) or self.__cancelled<EOL><DEDENT>if not wait_for_condition(self, cond, timeout):<EOL><INDENT>raise Job.Timeout<EOL><DEDENT>return self.result<EOL> | Waits for the job to finish and returns the result.
# Arguments
timeout (number, None): A number of seconds to wait for the result
before raising a #Timeout exception.
# Raises
Timeout: If the timeout limit is exceeded. | f12751:c2:m13 |
def start(self, as_thread=True, daemon=False, __state_check=True): | if __state_check:<EOL><INDENT>with synchronized(self):<EOL><INDENT>if self.__cancelled and self.__state == Job.PENDING:<EOL><INDENT>self.__state = Job.CANCELLED<EOL>assert self.__exception is None<EOL>assert self.__result is None<EOL>self._trigger_event(Job.CANCELLED)<EOL>return None<EOL><DEDENT>if self.__state == Job.RUNNING:<EOL><INDENT>raise Job.InvalidState('<STR_LIT>')<EOL><DEDENT>elif self.__state not in (Job.PENDING, Job.ERROR, Job.SUCCESS, Job.CANCELLED):<EOL><INDENT>raise RuntimeError('<STR_LIT>'.format(self.__state))<EOL><DEDENT>self.__state = Job.RUNNING<EOL>self.__cancelled = False<EOL>self.__result = None<EOL>self.__exception = None<EOL>self.__event_set.clear()<EOL>self.__thread = None<EOL>for listeners in self.__listeners.values():<EOL><INDENT>listeners[:] = (l for l in listeners if not l.once)<EOL><DEDENT><DEDENT><DEDENT>if as_thread:<EOL><INDENT>thread = threading.Thread(target=self.start, args=(False, False, False))<EOL>thread.setDaemon(daemon)<EOL>with synchronized(self):<EOL><INDENT>assert not self.__thread or not self.__thread.running<EOL>self.__thread = thread<EOL><DEDENT>thread.start()<EOL>return self<EOL><DEDENT>try:<EOL><INDENT>result = None<EOL>exception = None<EOL>try:<EOL><INDENT>result = self.run()<EOL>state = Job.SUCCESS<EOL><DEDENT>except Exception: <EOL><INDENT>if self.print_exc:<EOL><INDENT>traceback.print_exc()<EOL><DEDENT>exception = Job.ExceptionInfo(*sys.exc_info())<EOL>state = Job.ERROR<EOL><DEDENT>with synchronized(self):<EOL><INDENT>cancelled = self.__cancelled<EOL>self.__result = result<EOL>self.__exception = exception<EOL>self.__state = Job.CANCELLED if cancelled else state<EOL><DEDENT>self._trigger_event(state)<EOL><DEDENT>finally:<EOL><INDENT>with synchronized(self):<EOL><INDENT>notify_all(self)<EOL><DEDENT>if self.__dispose_inputs:<EOL><INDENT>self.__target = None<EOL>self.__args = None<EOL>self.__kwargs = None<EOL>self.data = None<EOL>for listeners in self.__listeners.values():<EOL><INDENT>listeners[:] = []<EOL><DEDENT><DEDENT><DEDENT>return self<EOL> | Starts the job. If the job was run once before, resets it completely. Can
not be used while the job is running (raises #InvalidState).
# Arguments
as_thread (bool): Start the job in a separate thread. This is #True by
default. Classes like the #ThreadPool calls this function from its own
thread and passes #False for this argument.
daemon (bool): If a thread is created with *as_thread* set to #True,
defines whether the thread is started as a daemon or not. Defaults to
#False.
# Returns
Job: The job object itself. | f12751:c2:m14 |
def run(self): | if self.__target is not None:<EOL><INDENT>return self.__target(self, *self.__args, **self.__kwargs)<EOL><DEDENT>raise NotImplementedError<EOL> | This method is the actual implementation of the job. By default, it calls
the target function specified in the #Job constructor. | f12751:c2:m15 |
@staticmethod<EOL><INDENT>def factory(start_immediately=True):<DEDENT> | def decorator(func):<EOL><INDENT>def wrapper(*args, **kwargs):<EOL><INDENT>job = Job(task=lambda j: func(j, *args, **kwargs))<EOL>if start_immediately:<EOL><INDENT>job.start()<EOL><DEDENT>return job<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL> | This is a decorator function that creates new `Job`s with the wrapped
function as the target.
# Example
```python
@Job.factory()
def some_longish_function(job, seconds):
time.sleep(seconds)
return 42
job = some_longish_function(2)
print(job.wait())
```
# Arguments
start_immediately (bool): #True if the factory should call #Job.start()
immediately, #False if it should return the job in pending state. | f12751:c2:m16 |
def start(self): | if self.__running:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>[t.start() for t in self.__threads]<EOL>self.__running = True<EOL> | Starts the #ThreadPool. Must be ended with #stop(). Use the context-manager
interface to ensure starting and the #ThreadPool. | f12751:c3:m4 |
def pending_jobs(self): | return self.__queue.snapshot()<EOL> | Returns a list of all Jobs that are pending and waiting to be processed. | f12751:c3:m5 |
def current_jobs(self): | jobs = []<EOL>with synchronized(self.__queue):<EOL><INDENT>for worker in self.__threads:<EOL><INDENT>with synchronized(worker):<EOL><INDENT>if worker.current:<EOL><INDENT>jobs.append(worker.current)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return jobs<EOL> | Returns a snapshot of the Jobs that are currently being processed by the
ThreadPool. These jobs can not be found in the #pending_jobs() list. | f12751:c3:m6 |
def clear(self): | with synchronized(self.__queue):<EOL><INDENT>jobs = self.__queue.snapshot()<EOL>self.__queue.clear()<EOL><DEDENT>return jobs<EOL> | Removes all pending Jobs from the queue and return them in a list. This
method does **no**t call #Job.cancel() on any of the jobs. If you want
that, use #cancel_all() or call it manually. | f12751:c3:m7 |
def cancel_all(self, cancel_current=True): | with synchronized(self.__queue):<EOL><INDENT>jobs = self.clear()<EOL>if cancel_current:<EOL><INDENT>jobs.extend(self.current_jobs())<EOL><DEDENT><DEDENT>[j.cancel() for j in jobs]<EOL>return jobs<EOL> | Similar to #clear(), but this function also calls #Job.cancel() on all
jobs. Also, it **includes** all jobs that are currently being executed if
*cancel_current* is True.
# Arguments
cancel_current (bool): Also cancel currently running jobs and include them
in the returned list of jobs.
# Returns
list: A list of the #Job#s that were canceled. | f12751:c3:m8 |
def submit(self, target=None, task=None, args=(), kwargs=None, front=False,<EOL>dispose_inputs=None): | if not self.__running:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if dispose_inputs is None:<EOL><INDENT>dispose_inputs = self.dispose_inputs<EOL><DEDENT>if isinstance(task, Job):<EOL><INDENT>if args or kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if task.state != Job.PENDING:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>job = task<EOL><DEDENT>elif task is not None:<EOL><INDENT>if kwargs is None:<EOL><INDENT>kwargs = {}<EOL><DEDENT>job = Job(task=task, args=args, kwargs=kwargs, dispose_inputs=dispose_inputs)<EOL><DEDENT>elif target is not None:<EOL><INDENT>if kwargs is None:<EOL><INDENT>kwargs = {}<EOL><DEDENT>job = Job(target=target, args=args, kwargs=kwargs, dispose_inputs=dispose_inputs)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>job.print_exc = self.print_exc<EOL>if front:<EOL><INDENT>self.__queue.appendleft(job)<EOL><DEDENT>else:<EOL><INDENT>self.__queue.append(job)<EOL><DEDENT>return job<EOL> | Submit a new #Job to the ThreadPool.
# Arguments
task (function, Job): Either a function that accepts a #Job, *args* and
*kwargs* or a #Job object that is in #~Job.PENDING state.
target (function): A function object that accepts *args* and *kwargs*.
Only if *task* is not specified.
args (list, tuple): A list of arguments to be passed to *job*, if it is
a function.
kwargs (dict): A dictionary to be passed as keyword arguments to *job*,
if it is a function.
front (bool): If #True, the job will be inserted in the front of the queue.
# Returns
Job: The job that was added to the queue.
# Raises
TypeError: If a #Job object was passed but *args* or *kwargs* are non-empty.
RuntimeError: If the ThreadPool is not running (ie. if it was shut down). | f12751:c3:m9 |
def wait(self, timeout=None): | if not self.__running:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.__queue.wait(timeout)<EOL> | Block until all jobs in the ThreadPool are finished. Beware that this can
make the program run into a deadlock if another thread adds new jobs to the
pool!
# Raises
Timeout: If the timeout is exceeded. | f12751:c3:m10 |
def shutdown(self, wait=True): | if self.__running:<EOL><INDENT>for thread in self.__threads:<EOL><INDENT>assert thread.isAlive()<EOL>self.__queue.append(None)<EOL><DEDENT>self.__running = False<EOL><DEDENT>if wait:<EOL><INDENT>self.__queue.wait()<EOL>for thread in self.__threads:<EOL><INDENT>thread.join()<EOL><DEDENT><DEDENT> | Shut down the ThreadPool.
# Arguments
wait (bool): If #True, wait until all worker threads end. Note that pending
jobs are still executed. If you want to cancel any pending jobs, use the
#clear() or #cancel_all() methods. | f12751:c3:m11 |
def submit_multiple(self, functions, target=False, task=False): | if target or not task:<EOL><INDENT>return JobCollection([self.submit(target=func) for func in functions])<EOL><DEDENT>else:<EOL><INDENT>return JobCollection([self.submit(task=func) for func in functions])<EOL><DEDENT> | Submits a #Job for each element in *function* and returns a #JobCollection. | f12751:c3:m12 |
def new_event_type(self, name, mergeable=False): | self.event_types[name] = self.EventType(name, mergeable)<EOL> | Declare a new event. May overwrite an existing entry. | f12751:c5:m2 |
def add_event(self, name, data=None): | try:<EOL><INDENT>mergeable = self.event_types[name].mergeable<EOL><DEDENT>except KeyError:<EOL><INDENT>if self.strict:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(name))<EOL><DEDENT>mergeable = False<EOL><DEDENT>if mergeable and data is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>with self.lock:<EOL><INDENT>if mergeable:<EOL><INDENT>for ev in self.events:<EOL><INDENT>if ev.type == name:<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT>self.events.append(self.Event(name, data, time.clock()))<EOL><DEDENT> | Add an event of type *name* to the queue. May raise a
`ValueError` if the event type is mergeable and *data* is not None
or if *name* is not a declared event type (in strict mode). | f12751:c5:m3 |
def pop_event(self): | with self.lock:<EOL><INDENT>if not self.events:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self.events.popleft()<EOL><DEDENT> | Pop the next queued event from the queue.
:raise ValueError: If there is no event queued. | f12751:c5:m4 |
def pop_events(self): | with self.lock:<EOL><INDENT>events = self.events<EOL>self.events = collections.deque()<EOL>return events<EOL><DEDENT> | Pop all events and return a `collections.deque` object. The
returned container can be empty. This method is preferred over
`pop_event()` as it is much faster as the lock has to be acquired
only once and also avoids running into an infinite loop during
event processing. | f12751:c5:m5 |
@synchronized<EOL><INDENT>def clear(self):<DEDENT> | self._tasks -= len(self._deque)<EOL>self._deque.clear()<EOL>notify_all(self)<EOL> | Clears the queue. Note that calling #wait*( immediately after clear can
still block when tasks are currently being processed since this method can
only clear queued items. | f12751:c6:m5 |
@synchronized<EOL><INDENT>def get(self, block=True, timeout=None, method='<STR_LIT>'):<DEDENT> | if method not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(method))<EOL><DEDENT>t_start = time.clock()<EOL>while not self:<EOL><INDENT>if not block:<EOL><INDENT>raise self.Empty<EOL><DEDENT>if timeout is None:<EOL><INDENT>wait(self)<EOL><DEDENT>else:<EOL><INDENT>t_delta = time.clock() - t_start<EOL>if t_delta > timeout:<EOL><INDENT>raise Timeout<EOL><DEDENT>wait(self, timeout - t_delta)<EOL><DEDENT><DEDENT>return getattr(self, method)()<EOL> | If *block* is True, this method blocks until an element can be removed from
the deque with the specified *method*. If *block* is False, the function
will raise #Empty if no elements are available.
# Arguments
block (bool): #True to block and wait until an element becomes available,
#False otherwise.
timeout (number, None): The timeout in seconds to use when waiting for
an element (only with `block=True`).
method (str): The name of the method to use to remove an element from the
queue. Must be either `'pop'` or `'popleft'`.
# Raises
ValueError: If *method* has an invalid value.
Timeout: If the *timeout* is exceeded. | f12751:c6:m14 |
@synchronized<EOL><INDENT>def wait(self, timeout=None):<DEDENT> | t_start = time.clock()<EOL>if not wait_for_condition(self, lambda s: s._tasks == <NUM_LIT:0>, timeout):<EOL><INDENT>raise Timeout<EOL><DEDENT> | Waits until all tasks completed or *timeout* seconds passed.
# Raises
Timeout: If the *timeout* is exceeded. | f12751:c6:m15 |
def sleep(self): | current = time.time()<EOL>if self.last < <NUM_LIT:0>:<EOL><INDENT>self.last = current<EOL>return<EOL><DEDENT>delta = current - self.last<EOL>if delta < self.seconds:<EOL><INDENT>time.sleep(self.seconds - delta)<EOL>self.last = time.time()<EOL><DEDENT> | Sleeps until the interval has passed since the last time this function was
called. This is a synonym for #__call__(). The first time the function is
called will return immediately and not block. Therefore, it is important to
put the call at the beginning of the timed block, like this:
# Example
```python
clock = Clock(fps=50)
while True:
clock.sleep()
# Processing ...
``` | f12751:c7:m1 |
def bind(self, __fun, *args, **kwargs): | with self._lock:<EOL><INDENT>if self._running or self._completed or self._cancelled:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self._worker:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self._worker = functools.partial(__fun, *args, **kwargs)<EOL><DEDENT>return self<EOL> | Bind a worker function to the future. This worker function will be
executed when the future is executed. | f12752:c0:m2 |
def add_done_callback(self, fun): | with self._lock:<EOL><INDENT>if self._completed:<EOL><INDENT>fun()<EOL><DEDENT>else:<EOL><INDENT>self._done_callbacks.append(fun)<EOL><DEDENT><DEDENT> | Adds the callback *fun* to the future so that it be invoked when the
future completed. The future completes either when it has been completed
after being started with the :meth:`start` method (independent of whether
an error occurs or not) or when either :meth:`set_result` or
:meth:`set_exception` is called.
If the future is already complete, *fun* will be invoked directly.
The function *fun* must accept the future as its sole argument. | f12752:c0:m3 |
def enqueue(self): | with self._lock:<EOL><INDENT>if self._enqueued:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self._running:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self._completed:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if not self._worker:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self._enqueued = True<EOL><DEDENT> | Mark the future as being enqueued in some kind of executor for futures.
Calling :meth:`start()` with the *as_thread* parameter as :const:`True`
will raise a :class:`RuntimeError` after this method has been called.
This method will also validate the state of the future. | f12752:c0:m4 |
def start(self, as_thread=True): | with self._lock:<EOL><INDENT>if as_thread:<EOL><INDENT>self.enqueue() <EOL><DEDENT>if self._cancelled:<EOL><INDENT>return<EOL><DEDENT>self._running = True<EOL>if as_thread:<EOL><INDENT>self._thread = threading.Thread(target=self._run)<EOL>self._thread.start()<EOL>return self<EOL><DEDENT><DEDENT>self._run()<EOL> | Execute the future in a new thread or in the current thread as specified
by the *as_thread* parameter.
:param as_thread: Execute the future in a new, separate thread. If this
is set to :const:`False`, the future will be executed in the calling
thread. | f12752:c0:m5 |
def enqueued(self): | with self._lock:<EOL><INDENT>return self._enqueued<EOL><DEDENT> | :return: :const:`True` if the future is enqueued, meaning that it is about
to be or already being executed. | f12752:c0:m8 |
def running(self): | with self._lock:<EOL><INDENT>return self._running<EOL><DEDENT> | :return: :const:`True` if the future is running, :const:`False` otherwise. | f12752:c0:m9 |
def done(self): | with self._lock:<EOL><INDENT>return self._completed<EOL><DEDENT> | :return: :const:`True` if the future completed, :const:`False` otherwise. | f12752:c0:m10 |
def cancelled(self): | with self._lock:<EOL><INDENT>return self._cancelled<EOL><DEDENT> | Checks if the future has been cancelled. | f12752:c0:m11 |
def result(self, timeout=None, do_raise=True): | with self._lock:<EOL><INDENT>self.wait(timeout, do_raise=do_raise)<EOL>if self._exc_info:<EOL><INDENT>if not do_raise:<EOL><INDENT>return None<EOL><DEDENT>self._exc_retrieved = True<EOL>reraise(*self._exc_info)<EOL><DEDENT>if self._cancelled:<EOL><INDENT>if not do_raise:<EOL><INDENT>return None<EOL><DEDENT>raise self.Cancelled()<EOL><DEDENT>return self._result<EOL><DEDENT> | Retrieve the result of the future, waiting for it to complete or at
max *timeout* seconds.
:param timeout: The number of maximum seconds to wait for the result.
:param do_raise: Set to False to prevent any of the exceptions below
to be raised and return :const:`None` instead.
:raise Cancelled: If the future has been cancelled.
:raise Timeout: If the *timeout* has been exceeded.
:raise BaseException: Anything the worker has raised.
:return: Whatever the worker bound to the future returned. | f12752:c0:m12 |
def exception(self, timeout=None, do_raise=True): | with self._lock:<EOL><INDENT>self.wait(timeout, do_raise=do_raise)<EOL>if not self._exc_info:<EOL><INDENT>return None<EOL><DEDENT>self._exc_retrieved = True<EOL>if self._cancelled:<EOL><INDENT>raise self.Cancelled()<EOL><DEDENT>return self._exc_info[<NUM_LIT:1>]<EOL><DEDENT> | Returns the exception value by the future's worker or :const:`None`.
:param timeout:
:param do_raise:
:param Cancelled:
:param Timeout:
:return: :const:`None` or an exception value. | f12752:c0:m13 |
def exc_info(self, timeout=None, do_raise=True): | with self._lock:<EOL><INDENT>self.wait(timeout, do_raise=do_raise)<EOL>if not self._exc_info:<EOL><INDENT>return None<EOL><DEDENT>self._exc_retrieved = True<EOL>if self._cancelled:<EOL><INDENT>raise self.Cancelled()<EOL><DEDENT>return self._exc_info<EOL><DEDENT> | Returns the exception info tuple raised by the future's worker or
:const:`None`.
:param timeout:
:param do_raise:
:param Cancelled:
:param Timeout:
:return: :const:`None` or an exception info tuple. | f12752:c0:m14 |
def cancel(self, mark_completed_as_cancelled=False): | with self._lock:<EOL><INDENT>if not self._completed or mark_completed_as_cancelled:<EOL><INDENT>self._cancelled = True<EOL><DEDENT>callbacks = self._prepare_done_callbacks()<EOL><DEDENT>callbacks()<EOL> | Cancel the future. If the future has not been started yet, it will never
start running. If the future is already running, it will run until the
worker function exists. The worker function can check if the future has
been cancelled using the :meth:`cancelled` method.
If the future has already been completed, it will not be marked as
cancelled unless you set *mark_completed_as_cancelled* to :const:`True`.
:param mark_completed_as_cancelled: If this is :const:`True` and the
future has already completed, it will be marked as cancelled anyway. | f12752:c0:m15 |
def set_result(self, result): | with self._lock:<EOL><INDENT>if self._enqueued:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self._result = result<EOL>self._completed = True<EOL>callbacks = self._prepare_done_callbacks()<EOL><DEDENT>callbacks()<EOL> | Allows you to set the result of the future without requiring the future
to actually be executed. This can be used if the result is available
before the future is run, allowing you to keep the future as the interface
for retrieving the result data.
:param result: The result of the future.
:raise RuntimeError: If the future is already enqueued. | f12752:c0:m16 |
def set_exception(self, exc_info): | if not isinstance(exc_info, tuple):<EOL><INDENT>if not isinstance(exc_info, BaseException):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>raise exc_info<EOL><DEDENT>except:<EOL><INDENT>exc_info = sys.exc_info()<EOL>exc_info = (exc_info[<NUM_LIT:0>], exc_info[<NUM_LIT:1>], exc_info[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>with self._lock:<EOL><INDENT>if self._enqueued:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self._exc_info = exc_info<EOL>self._completed = True<EOL>callbacks = self._prepare_done_callbacks()<EOL><DEDENT>callbacks()<EOL> | This method allows you to set an exception in the future without requring
that exception to be raised from the futures worker. This method can be
called on an unbound future.
:param exc_info: Either an exception info tuple or an exception value.
In the latter case, the traceback will be automatically generated
from the parent frame.
:raise RuntimeError: If the future is already enqueued. | f12752:c0:m17 |
def wait(self, timeout=None, do_raise=False): | if timeout is not None:<EOL><INDENT>timeout = float(timeout)<EOL>start = time.clock()<EOL><DEDENT>with self._lock:<EOL><INDENT>while not self._completed and not self._cancelled:<EOL><INDENT>if timeout is not None:<EOL><INDENT>time_left = timeout - (time.clock() - start)<EOL><DEDENT>else:<EOL><INDENT>time_left = None<EOL><DEDENT>if time_left is not None and time_left <= <NUM_LIT:0.0>:<EOL><INDENT>if do_raise:<EOL><INDENT>raise self.Timeout()<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>self._lock.wait(time_left)<EOL><DEDENT><DEDENT>return True<EOL> | Wait for the future to complete. If *timeout* is specified, it must be a
floating point number representing the maximum number of seconds to wait.
:param timeout: The maximum number of seconds to wait for the future
to complete.
:param do_raise: Raise :class:`Timeout` when a timeout occurred.
:raise Timeout: If a timeout occurred and *do_raise* was True.
:return: :const:`True` if the future completed, :const:`False` if a
timeout occurred and *do_raise* was set to False. | f12752:c0:m18 |
def enqueue(self, future): | future.enqueue()<EOL>with self._lock:<EOL><INDENT>if self._shutdown:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self._queue.append(future)<EOL>if len(self._running) == len(self._workers):<EOL><INDENT>self._new_worker()<EOL><DEDENT>self._lock.notify_all()<EOL><DEDENT> | Enqueue a future to be processed by one of the threads in the pool.
The future must be bound to a worker and not have been started yet. | f12752:c1:m3 |
def submit(self, __fun, *args, **kwargs): | future = Future().bind(__fun, *args, **kwargs)<EOL>self.enqueue(future)<EOL>return future<EOL> | Creates a new future and enqueues it. Returns the future. | f12752:c1:m4 |
def cancel(self, cancel_running=True, mark_completed_as_cancelled=False): | with self._lock:<EOL><INDENT>for future in self._queue:<EOL><INDENT>future.cancel(mark_completed_as_cancelled)<EOL><DEDENT>if cancel_running:<EOL><INDENT>for future in self._running:<EOL><INDENT>future.cancel(mark_completed_as_cancelled)<EOL><DEDENT><DEDENT>self._queue.clear()<EOL><DEDENT> | Cancel all futures queued in the pool. If *cancel_running* is True,
futures that are currently running in the pool are cancelled as well. | f12752:c1:m5 |
def shutdown(self, wait=True): | with self._lock:<EOL><INDENT>self._shutdown = True<EOL>self._lock.notify_all()<EOL><DEDENT>if wait:<EOL><INDENT>self.wait()<EOL><DEDENT> | Shut down the pool. If *wait* is True, it will wait until all futures
are completed. Alternatively, you can use the #wait() method to wait
with timeout supported. | f12752:c1:m6 |
def wait(self, timeout=None): | tbegin = _get_timeout_begin(timeout)<EOL>with self._lock:<EOL><INDENT>while self._queue or self._running:<EOL><INDENT>remainder = _get_timeout_remainder(tbegin, timeout)<EOL>if remainder is not None and remainder <= <NUM_LIT:0.0>:<EOL><INDENT>return False <EOL><DEDENT>self._lock.wait(remainder)<EOL><DEDENT>if self._shutdown:<EOL><INDENT>for worker in self._workers:<EOL><INDENT>worker.join()<EOL><DEDENT><DEDENT><DEDENT>return True<EOL> | Wait until all futures are completed. You should call this method only
after calling #shutdown(). Returns #False if all futures are complete,
#False if there are still some running. | f12752:c1:m7 |
def _raise_error_if_negative(val): | if val < <NUM_LIT:0>:<EOL><INDENT>raise IOError(val, api.py_aa_status_string(val))<EOL><DEDENT> | Raises an :class:`IOError` if `val` is negative. | f12759:m0 |
def _raise_i2c_status_code_error_if_failure(code): | if code != I2C_STATUS_OK:<EOL><INDENT>raise IOError(code, status_string(code))<EOL><DEDENT> | Raises an :class:`IOError` if `code` is not :data:`I2C_STATUS_OK`. | f12759:m2 |
def api_version(): | return _to_version_str(api.py_version() & <NUM_LIT>)<EOL> | Returns the underlying C module (aardvark.so, aardvark.pyd) as a string.
It returns the same value as :attr:`Aardvark.api_version` but you don't
need to open a device. | f12759:m5 |
def find_devices(): | <EOL>num_devices = api.py_aa_find_devices(<NUM_LIT:0>, array.array('<STR_LIT:H>'))<EOL>_raise_error_if_negative(num_devices)<EOL>if num_devices == <NUM_LIT:0>:<EOL><INDENT>return list()<EOL><DEDENT>ports = array.array('<STR_LIT:H>', (<NUM_LIT:0>,) * num_devices)<EOL>unique_ids = array.array('<STR_LIT:I>', (<NUM_LIT:0>,) * num_devices)<EOL>num_devices = api.py_aa_find_devices_ext(len(ports), len(unique_ids),<EOL>ports, unique_ids)<EOL>_raise_error_if_negative(num_devices)<EOL>if num_devices == <NUM_LIT:0>:<EOL><INDENT>return list()<EOL><DEDENT>del ports[num_devices:]<EOL>del unique_ids[num_devices:]<EOL>devices = list()<EOL>for port, uid in zip(ports, unique_ids):<EOL><INDENT>in_use = bool(port & PORT_NOT_FREE)<EOL>dev = dict(<EOL>port=port & ~PORT_NOT_FREE,<EOL>serial_number=_unique_id_str(uid),<EOL>in_use=in_use)<EOL>devices.append(dev)<EOL><DEDENT>return devices<EOL> | Return a list of dictionaries. Each dictionary represents one device.
The dictionary contains the following keys: port, unique_id and in_use.
`port` can be used with :func:`open`. `serial_number` is the serial number
of the device (and can also be used with :func:`open`) and `in_use`
indicates whether the device was opened before and can currently not be
opened.
.. note::
There is no guarantee, that the returned information is still valid
when you open the device. Esp. if you open a device by the port, the
unique_id may change because you've just opened another device. Eg. it
may be disconnected from the machine after you call :func:`find_devices`
but before you call :func:`open`.
To open a device by its serial number, you should use the :func:`open`
with the `serial_number` parameter. | f12759:m6 |
def open(port=None, serial_number=None): | if port is None and serial_number is None:<EOL><INDENT>dev = Aardvark()<EOL><DEDENT>elif serial_number is not None:<EOL><INDENT>for d in find_devices():<EOL><INDENT>if d['<STR_LIT>'] == serial_number:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_raise_error_if_negative(ERR_UNABLE_TO_OPEN)<EOL><DEDENT>dev = Aardvark(d['<STR_LIT:port>'])<EOL>if dev.unique_id_str() != serial_number:<EOL><INDENT>dev.close()<EOL>_raise_error_if_negative(ERR_UNABLE_TO_OPEN)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>dev = Aardvark(port)<EOL><DEDENT>return dev<EOL> | Open an aardvark device and return an :class:`Aardvark` object. If the
device cannot be opened an :class:`IOError` is raised.
The `port` can be retrieved by :func:`find_devices`. Usually, the first
device is 0, the second 1, etc.
If you are using only one device, you can therefore omit the parameter
in which case 0 is used.
Another method to open a device is to use the serial number. You can either
find the number on the device itself or in the in the corresponding USB
property. The serial number is a string which looks like `NNNN-MMMMMMM`.
Raises an :class:`IOError` if the port (or serial number) does not exist,
is already connected or an incompatible device is found.
.. note::
There is a small chance that this function raises an :class:`IOError`
although the correct device is available and not opened. The
open-by-serial-number method works by scanning the devices. But as
explained in :func:`find_devices`, the returned information may be
outdated. Therefore, :func:`open` checks the serial number once the
device is opened and if it is not the expected one, raises
:class:`IOError`. No retry mechanism is implemented.
As long as nobody comes along with a better idea, this failure case is
up to the user. | f12759:m7 |
def close(self): | api.py_aa_close(self.handle)<EOL>self.handle = None<EOL> | Close the device. | f12759:c0:m3 |
def unique_id(self): | return api.py_aa_unique_id(self.handle)<EOL> | Return the unique identifier of the device. The identifier is the
serial number you can find on the adapter without the dash. Eg. the
serial number 0012-345678 would be 12345678. | f12759:c0:m4 |
def unique_id_str(self): | return _unique_id_str(self.unique_id())<EOL> | Return the unique identifier. But unlike :func:`unique_id`, the ID
is returned as a string which has the format NNNN-MMMMMMM. | f12759:c0:m5 |
@property<EOL><INDENT>def enable_i2c(self):<DEDENT> | config = self._interface_configuration(CONFIG_QUERY)<EOL>return config == CONFIG_GPIO_I2C or config == CONFIG_SPI_I2C<EOL> | Set this to `True` to enable the hardware I2C interface. If set to
`False` the hardware interface will be disabled and its pins (SDA and
SCL) can be used as GPIOs. | f12759:c0:m7 |
@property<EOL><INDENT>def enable_spi(self):<DEDENT> | config = self._interface_configuration(CONFIG_QUERY)<EOL>return config == CONFIG_SPI_GPIO or config == CONFIG_SPI_I2C<EOL> | Set this to `True` to enable the hardware SPI interface. If set to
`False` the hardware interface will be disabled and its pins (MISO,
MOSI, SCK and SS) can be used as GPIOs. | f12759:c0:m9 |
@property<EOL><INDENT>def i2c_bitrate(self):<DEDENT> | ret = api.py_aa_i2c_bitrate(self.handle, <NUM_LIT:0>)<EOL>_raise_error_if_negative(ret)<EOL>return ret<EOL> | I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz. | f12759:c0:m11 |
@property<EOL><INDENT>def i2c_pullups(self):<DEDENT> | ret = api.py_aa_i2c_pullup(self.handle, I2C_PULLUP_QUERY)<EOL>_raise_error_if_negative(ret)<EOL>return ret<EOL> | Setting this to `True` will enable the I2C pullup resistors. If set
to `False` the pullup resistors will be disabled.
Raises an :exc:`IOError` if the hardware adapter does not support
pullup resistors. | f12759:c0:m13 |
@property<EOL><INDENT>def target_power(self):<DEDENT> | ret = api.py_aa_target_power(self.handle, TARGET_POWER_QUERY)<EOL>_raise_error_if_negative(ret)<EOL>return ret<EOL> | Setting this to `True` will activate the power pins (4 and 6). If
set to `False` the power will be deactivated.
Raises an :exc:`IOError` if the hardware adapter does not support
the switchable power pins. | f12759:c0:m15 |
@property<EOL><INDENT>def i2c_bus_timeout(self):<DEDENT> | ret = api.py_aa_i2c_bus_timeout(self.handle, <NUM_LIT:0>)<EOL>_raise_error_if_negative(ret)<EOL>return ret<EOL> | I2C bus lock timeout in ms.
Minimum value is 10 ms and the maximum value is 450 ms. Not every value
can be set and will be rounded to the next possible number. You can
read back the property to get the actual value.
The power-on default value is 200 ms. | f12759:c0:m17 |
def i2c_master_write(self, i2c_address, data, flags=I2C_NO_FLAGS): | data = array.array('<STR_LIT:B>', data)<EOL>status, _ = api.py_aa_i2c_write_ext(self.handle, i2c_address, flags,<EOL>len(data), data)<EOL>_raise_i2c_status_code_error_if_failure(status)<EOL> | Make an I2C write access.
The given I2C device is addressed and data given as a string is
written. The transaction is finished with an I2C stop condition unless
I2C_NO_STOP is set in the flags.
10 bit addresses are supported if the I2C_10_BIT_ADDR flag is set. | f12759:c0:m19 |
def i2c_master_read(self, addr, length, flags=I2C_NO_FLAGS): | data = array.array('<STR_LIT:B>', (<NUM_LIT:0>,) * length)<EOL>status, rx_len = api.py_aa_i2c_read_ext(self.handle, addr, flags,<EOL>length, data)<EOL>_raise_i2c_status_code_error_if_failure(status)<EOL>del data[rx_len:]<EOL>return bytes(data)<EOL> | Make an I2C read access.
The given I2C device is addressed and clock cycles for `length` bytes
are generated. A short read will occur if the device generates an early
NAK.
The transaction is finished with an I2C stop condition unless the
I2C_NO_STOP flag is set. | f12759:c0:m20 |
def i2c_master_write_read(self, i2c_address, data, length): | self.i2c_master_write(i2c_address, data, I2C_NO_STOP)<EOL>return self.i2c_master_read(i2c_address, length)<EOL> | Make an I2C write/read access.
First an I2C write access is issued. No stop condition will be
generated. Instead the read access begins with a repeated start.
This method is useful for accessing most addressable I2C devices like
EEPROMs, port expander, etc.
Basically, this is just a convenient function which internally uses
`i2c_master_write` and `i2c_master_read`. | f12759:c0:m21 |
def poll(self, timeout=None): | if timeout is None:<EOL><INDENT>timeout = -<NUM_LIT:1><EOL><DEDENT>ret = api.py_aa_async_poll(self.handle, timeout)<EOL>_raise_error_if_negative(ret)<EOL>events = list()<EOL>for event in (POLL_I2C_READ, POLL_I2C_WRITE, POLL_SPI,<EOL>POLL_I2C_MONITOR):<EOL><INDENT>if ret & event:<EOL><INDENT>events.append(event)<EOL><DEDENT><DEDENT>return events<EOL> | Wait for an event to occur.
If `timeout` is given, if specifies the length of time in milliseconds
which the function will wait for events before returing. If `timeout`
is omitted, negative or None, the call will block until there is an
event.
Returns a list of events. In case no event is pending, an empty list is
returned. | f12759:c0:m22 |
def enable_i2c_slave(self, slave_address): | ret = api.py_aa_i2c_slave_enable(self.handle, slave_address,<EOL>self.BUFFER_SIZE, self.BUFFER_SIZE)<EOL>_raise_error_if_negative(ret)<EOL> | Enable I2C slave mode.
The device will respond to the specified slave_address if it is
addressed.
You can wait for the data with :func:`poll` and get it with
`i2c_slave_read`. | f12759:c0:m23 |
def disable_i2c_slave(self): | ret = api.py_aa_i2c_slave_disable(self.handle)<EOL>_raise_error_if_negative(ret)<EOL> | Disable I2C slave mode. | f12759:c0:m24 |
def i2c_slave_read(self): | data = array.array('<STR_LIT:B>', (<NUM_LIT:0>,) * self.BUFFER_SIZE)<EOL>status, addr, rx_len = api.py_aa_i2c_slave_read_ext(self.handle,<EOL>self.BUFFER_SIZE, data)<EOL>_raise_i2c_status_code_error_if_failure(status)<EOL>if addr == <NUM_LIT>:<EOL><INDENT>addr = <NUM_LIT><EOL><DEDENT>del data[rx_len:]<EOL>return (addr, bytes(data))<EOL> | Read the bytes from an I2C slave reception.
The bytes are returned as a string object. | f12759:c0:m25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.