enamlnative.core.eventloop package¶
Submodules¶
enamlnative.core.eventloop.common module¶
Lowest-common-denominator implementations of platform functionality.
-
class
enamlnative.core.eventloop.common.
Waker
[source]¶ Bases:
enamlnative.core.eventloop.interface.Waker
Create an OS independent asynchronous pipe.
For use on platforms that don’t have os.pipe() (or where pipes cannot be passed to select()), but do have sockets. This includes Windows and Jython.
-
writer
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
reader
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
reader_fd
¶ A value of type int.
By default, ints are strictly typed. Pass strict=False to the constructor to enable int casting for longs and floats.
-
fileno
()[source]¶ Returns the read file descriptor for this waker.
Must be suitable for use with
select()
or equivalent on the local platform.
-
__atom_members__
= {'reader': <atom.scalars.Value object at 0x7fad6b1d5910>, 'reader_fd': <atom.scalars.Int object at 0x7fad6b1d59b0>, 'writer': <atom.scalars.Value object at 0x7fad6b1d5c30>}¶
-
__module__
= 'enamlnative.core.eventloop.common'¶
-
__slots__
= ()¶
-
enamlnative.core.eventloop.concurrent module¶
Utilities for working with threads and Futures
.
Futures
are a pattern for concurrent programming introduced in
Python 3.2 in the concurrent.futures package. This package defines
a mostly-compatible Future class designed for use from coroutines,
as well as some utility functions for interacting with the
concurrent.futures package.
-
exception
enamlnative.core.eventloop.concurrent.
ReturnValueIgnoredError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.concurrent'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
enamlnative.core.eventloop.concurrent.
Future
[source]¶ Bases:
atom.atom.Atom
,object
Placeholder for an asynchronous result.
A
Future
encapsulates the result of an asynchronous operation. In synchronous applicationsFutures
are used to wait for the result from a thread or process pool; in Tornado they are normally used with .IOLoop.add_future or by yielding them in a .gen.coroutine.tornado.concurrent.Future is similar to concurrent.futures.Future, but not thread-safe (and therefore faster for use with single-threaded event loops).
In addition to
exception
andset_exception
, methodsexc_info
andset_exc_info
are supported to capture tracebacks in Python 2. The traceback is automatically available in Python 3, but in the Python 2 futures backport this information is discarded. This functionality was previously available in a separate classTracebackFuture
, which is now a deprecated alias for this class.Changed in version 4.0: tornado.concurrent.Future is always a thread-unsafe
Future
with support for theexc_info
methods. Previously it would be an alias for the thread-safe concurrent.futures.Future if that package was available and fall back to the thread-unsafe implementation if it was not.Changed in version 4.1: If a .Future contains an error but that error is never observed (by calling
result()
,exception()
, orexc_info()
), a stack trace will be logged when the .Future is garbage collected. This normally indicates an error in the application, but in cases where it results in undesired logging it may be necessary to suppress the logging by ensuring that the exception is observed:f.add_done_callback(lambda f: f.exception())
.-
__slots__
= ('__weakref__',)¶
-
__id__
¶ A value of type int.
By default, ints are strictly typed. Pass strict=False to the constructor to enable int casting for longs and floats.
-
then
¶ A value which is callable.
-
catch
¶ A value which is callable.
-
cancel
()[source]¶ Cancel the operation, if possible.
Tornado
Futures
do not support cancellation, so this method always returns False.
-
cancelled
()[source]¶ Returns True if the operation has been cancelled.
Tornado
Futures
do not support cancellation, so this method always returns False.
-
result
(timeout=None)[source]¶ If the operation succeeded, return its result. If it failed, re-raise its exception.
This method takes a
timeout
argument for compatibility with concurrent.futures.Future but it is an error to call it before the Future is done, so thetimeout
is never used.
-
exception
(timeout=None)[source]¶ If the operation raised an exception, return the Exception object. Otherwise returns None.
This method takes a
timeout
argument for compatibility with concurrent.futures.Future but it is an error to call it before the Future is done, so thetimeout
is never used.
-
add_done_callback
(fn)[source]¶ Attaches the given callback to the Future.
It will be invoked with the Future as its argument when the Future has finished running and its result is available. In Tornado consider using .IOLoop.add_future instead of calling add_done_callback directly.
-
set_result
(result)[source]¶ Sets the result of a
Future
.It is undefined to call any of the
set
methods more than once on the same object.
-
set_exc_info
(exc_info)[source]¶ Sets the exception information of a
Future.
Preserves tracebacks on Python 2.
New in version 4.0.
-
__atom_members__
= {'__id__': <atom.scalars.Int object at 0x7fad6b0e5690>, '_callbacks': <atom.instance.Instance object at 0x7fad6b0e55f0>, '_done': <atom.scalars.Bool object at 0x7fad6b0e52d0>, '_exc_info': <atom.scalars.Value object at 0x7fad6b0e5410>, '_log_traceback': <atom.scalars.Bool object at 0x7fad6b0e54b0>, '_result': <atom.scalars.Value object at 0x7fad6b0e5370>, '_tb_logger': <atom.scalars.Value object at 0x7fad6b0e5550>, 'catch': <atom.scalars.Callable object at 0x7fad6b0e57d0>, 'then': <atom.scalars.Callable object at 0x7fad6b0e5730>}¶
-
__module__
= 'enamlnative.core.eventloop.concurrent'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
enamlnative.core.eventloop.concurrent.
TracebackFuture
¶
-
enamlnative.core.eventloop.concurrent.
FUTURES
¶
-
class
enamlnative.core.eventloop.concurrent.
DummyExecutor
[source]¶ Bases:
atom.atom.Atom
-
__atom_members__
= {}¶
-
__module__
= 'enamlnative.core.eventloop.concurrent'¶
-
__slots__
= ()¶
-
-
enamlnative.core.eventloop.concurrent.
run_on_executor
(*args, **kwargs)[source]¶ Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a
callback
keyword argument and returns a future.The executor to be used is determined by the
executor
attributes ofself
. To use a different attribute name, pass a keyword argument to the decorator:@run_on_executor(executor='_thread_pool') def foo(self): pass
Changed in version 4.2: Added keyword arguments to use alternative attributes.
Changed in version 5.0: Always uses the current IOLoop instead of
self.io_loop
.
-
enamlnative.core.eventloop.concurrent.
return_future
(f)[source]¶ Decorator to make a function that returns via callback return a Future.
The wrapped function should take a
callback
keyword argument and invoke it with one argument when it has finished. To signal failure, the function can simply raise an exception (which will be captured by the .StackContext and passed along to theFuture
).From the caller’s perspective, the callback argument is optional. If one is given, it will be invoked when the function is complete with Future.result() as an argument. If the function fails, the callback will not be run and an exception will be raised into the surrounding .StackContext.
If no callback is given, the caller should use the
Future
to wait for the function to complete (perhaps by yielding it in a .gen.engine function, or passing it to .IOLoop.add_future).Usage:
@return_future def future_func(arg1, arg2, callback): # Do stuff (possibly asynchronous) callback(result) @gen.engine def caller(callback): yield future_func(arg1, arg2) callback()
Note that
@return_future
and@gen.engine
can be applied to the same function, provided@return_future
appears first. However, consider using@gen.coroutine
instead of this combination.
enamlnative.core.eventloop.gen module¶
tornado.gen
is a generator-based interface to make it easier to
work in an asynchronous environment. Code using the gen
module
is technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.
For example, the following asynchronous handler:
class AsyncHandler(RequestHandler):
@asynchronous
def get(self):
http_client = AsyncHTTPClient()
http_client.fetch("http://example.com",
callback=self.on_fetch)
def on_fetch(self, response):
do_something_with_response(response)
self.render("template.html")
could be written with gen
as:
class GenAsyncHandler(RequestHandler):
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
do_something_with_response(response)
self.render("template.html")
Most asynchronous functions in Tornado return a .Future; yielding this object returns its ~.Future.result.
You can also yield a list or dict of Futures
, which will be
started at the same time and run in parallel; a list or dict of results will
be returned when they are all finished:
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response1, response2 = yield [http_client.fetch(url1),
http_client.fetch(url2)]
response_dict = yield dict(response3=http_client.fetch(url3),
response4=http_client.fetch(url4))
response3 = response_dict['response3']
response4 = response_dict['response4']
If the ~functools.singledispatch library is available (standard in
Python 3.4, available via the singledispatch package on older
versions), additional types of objects may be yielded. Tornado includes
support for asyncio.Future
and Twisted’s Deferred
class when
tornado.platform.asyncio
and tornado.platform.twisted
are imported.
See the convert_yielded function to extend this mechanism.
Changed in version 3.2: Dict support added.
Changed in version 4.1: Support added for yielding asyncio
Futures and Twisted Deferreds
via singledispatch
.
-
exception
enamlnative.core.eventloop.gen.
KeyReuseError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
exception
enamlnative.core.eventloop.gen.
UnknownKeyError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
exception
enamlnative.core.eventloop.gen.
LeakedCallbackError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
exception
enamlnative.core.eventloop.gen.
BadYieldError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
exception
enamlnative.core.eventloop.gen.
ReturnValueIgnoredError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
enamlnative.core.eventloop.gen.
engine
(func)[source]¶ Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the coroutine decorator is recommended instead.
This decorator is similar to coroutine, except it does not return a .Future and the
callback
argument is not treated specially.In most cases, functions decorated with engine should take a
callback
argument and invoke it with their result when they are finished. One notable exception is the ~tornado.web.RequestHandler HTTP verb methods, which useself.finish()
in place of a callback argument.
-
enamlnative.core.eventloop.gen.
coroutine
(func, replace_callback=True)[source]¶ Decorator for asynchronous generators.
Any generator that yields objects from this module must be wrapped in either this decorator or engine.
Coroutines may “return” by raising the special exception Return(value) <Return>. In Python 3.3+, it is also possible for the function to simply use the
return value
statement (prior to Python 3.3 generators were not allowed to also return values). In all versions of Python a coroutine that simply wishes to exit early may use thereturn
statement without a value.Functions with this decorator return a .Future. Additionally, they may be called with a
callback
keyword argument, which will be invoked with the future’s result when it resolves. If the coroutine fails, the callback will not be run and an exception will be raised into the surrounding .StackContext. Thecallback
argument is not visible inside the decorated function; it is handled by the decorator itself.From the caller’s perspective,
@gen.coroutine
is similar to the combination of@return_future
and@gen.engine
.Warning
When exceptions occur inside a coroutine, the exception information will be stored in the .Future object. You must examine the result of the .Future object, or the exception may go unnoticed by your code. This means yielding the function if called from another coroutine, using something like .IOLoop.run_sync for top-level calls, or passing the .Future to .IOLoop.add_future.
-
enamlnative.core.eventloop.gen.
is_coroutine_function
(func)[source]¶ Return whether func is a coroutine function, i.e. a function wrapped with ~.gen.coroutine.
New in version 4.5.
-
exception
enamlnative.core.eventloop.gen.
Return
(value=None)[source]¶ Bases:
exceptions.Exception
Special exception to return a value from a coroutine.
If this exception is raised, its value argument is used as the result of the coroutine:
@gen.coroutine def fetch_json(url): response = yield AsyncHTTPClient().fetch(url) raise gen.Return(json_decode(response.body))
In Python 3.3, this exception is no longer necessary: the
return
statement can be used directly to return a value (previouslyyield
andreturn
with a value could not be combined in the same function).By analogy with the return statement, the value argument is optional, but it is never necessary to
raise gen.Return()
. Thereturn
statement can be used with no arguments instead.-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
enamlnative.core.eventloop.gen.
WaitIterator
(*args, **kwargs)[source]¶ Bases:
atom.atom.Atom
Provides an iterator to yield the results of futures as they finish.
Yielding a set of futures like this:
results = yield [future1, future2]
pauses the coroutine until both
future1
andfuture2
return, and then restarts the coroutine with the results of both futures. If either future is an exception, the expression will raise that exception and all the results will be lost.If you need to get the result of each future as soon as possible, or if you need the result of some futures even if others produce errors, you can use
WaitIterator
:wait_iterator = gen.WaitIterator(future1, future2) while not wait_iterator.done(): try: result = yield wait_iterator.next() except Exception as e: print("Error {} from {}".format(e, wait_iterator.current_future)) else: print("Result {} received from {} at {}".format( result, wait_iterator.current_future, wait_iterator.current_index))
Because results are returned as soon as they are available the output from the iterator will not be in the same order as the input arguments. If you need to know which future produced the current result, you can use the attributes
WaitIterator.current_future
, orWaitIterator.current_index
to get the index of the future from the input list. (if keyword arguments were used in the construction of the WaitIterator,current_index
will use the corresponding keyword).On Python 3.5, WaitIterator implements the async iterator protocol, so it can be used with the
async for
statement (note that in this version the entire iteration is aborted if any value raises an exception, while the previous example can continue past individual errors):async for result in gen.WaitIterator(future1, future2): print("Result {} received from {} at {}".format( result, wait_iterator.current_future, wait_iterator.current_index))
New in version 4.1.
Changed in version 4.3: Added
async for
support in Python 3.5.-
current_index
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
current_future
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
next
()[source]¶ Returns a .Future that will yield the next available result.
Note that this .Future will not be the same object as any of the inputs.
-
__atom_members__
= {'_finished': <atom.dict.Dict object at 0x7fad6b108370>, '_running_future': <atom.scalars.Value object at 0x7fad6b1085f0>, '_unfinished': <atom.dict.Dict object at 0x7fad6b108410>, 'current_future': <atom.scalars.Value object at 0x7fad6b108550>, 'current_index': <atom.scalars.Value object at 0x7fad6b1084b0>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.gen.
YieldPoint
[source]¶ Bases:
atom.atom.Atom
Base class for objects that may be yielded from the generator.
Deprecated since version 4.0: Use Futures <.Future> instead.
-
start
(runner)[source]¶ Called by the runner after the generator has yielded.
No other methods will be called on this object before
start
.
-
is_ready
()[source]¶ Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
-
get_result
()[source]¶ Returns the value to use as the result of the yield expression.
This method will only be called once, and only after is_ready has returned true.
-
__atom_members__
= {}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.gen.
Callback
(key)[source]¶ Bases:
enamlnative.core.eventloop.gen.YieldPoint
Returns a callable object that will allow a matching Wait to proceed.
The key may be any value suitable for use as a dictionary key, and is used to match
Callbacks
to their correspondingWaits
. The key must be unique among outstanding callbacks within a single run of the generator function, but may be reused across different runs of the same function (so constants generally work fine).The callback may be called with zero or one arguments; if an argument is given it will be returned by Wait.
Deprecated since version 4.0: Use Futures <.Future> instead.
-
key
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
runner
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
start
(runner)[source]¶ Called by the runner after the generator has yielded.
No other methods will be called on this object before
start
.
-
is_ready
()[source]¶ Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
-
get_result
()[source]¶ Returns the value to use as the result of the yield expression.
This method will only be called once, and only after is_ready has returned true.
-
__atom_members__
= {'key': <atom.scalars.Value object at 0x7fad6b108690>, 'runner': <atom.scalars.Value object at 0x7fad6b108730>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.gen.
Wait
[source]¶ Bases:
enamlnative.core.eventloop.gen.YieldPoint
Returns the argument passed to the result of a previous Callback.
Deprecated since version 4.0: Use Futures <.Future> instead.
-
runner
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
start
(runner)[source]¶ Called by the runner after the generator has yielded.
No other methods will be called on this object before
start
.
-
is_ready
()[source]¶ Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
-
get_result
()[source]¶ Returns the value to use as the result of the yield expression.
This method will only be called once, and only after is_ready has returned true.
-
__atom_members__
= {'runner': <atom.scalars.Value object at 0x7fad6b1087d0>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.gen.
WaitAll
(keys)[source]¶ Bases:
enamlnative.core.eventloop.gen.YieldPoint
Returns the results of multiple previous Callbacks <Callback>.
The argument is a sequence of Callback keys, and the result is a list of results in the same order.
WaitAll is equivalent to yielding a list of Wait objects.
Deprecated since version 4.0: Use Futures <.Future> instead.
-
keys
¶ A member which allows list values.
Assigning to a list creates a copy. The orginal list will remain unmodified. This is similar to the semantics of the assignment operator on the C++ STL container classes.
-
runner
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
start
(runner)[source]¶ Called by the runner after the generator has yielded.
No other methods will be called on this object before
start
.
-
is_ready
()[source]¶ Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
-
get_result
()[source]¶ Returns the value to use as the result of the yield expression.
This method will only be called once, and only after is_ready has returned true.
-
__atom_members__
= {'keys': <atom.list.List object at 0x7fad6b254c20>, 'runner': <atom.scalars.Value object at 0x7fad6b108870>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
enamlnative.core.eventloop.gen.
Task
(func, *args, **kwargs)[source]¶ Adapts a callback-based asynchronous function for use in coroutines.
Takes a function (and optional additional arguments) and runs it with those arguments plus a
callback
keyword argument. The argument passed to the callback is returned as the result of the yield expression.Changed in version 4.0:
gen.Task
is now a function that returns a .Future, instead of a subclass of YieldPoint. It still behaves the same way when yielded.
-
class
enamlnative.core.eventloop.gen.
YieldFuture
(future)[source]¶ Bases:
enamlnative.core.eventloop.gen.YieldPoint
-
key
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
future
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
io_loop
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
result_fn
¶ A value which is callable.
-
runner
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
__init__
(future)[source]¶ Adapts a .Future to the YieldPoint interface.
Changed in version 5.0: The
io_loop
argument (deprecated since version 4.1) has been removed.
-
start
(runner)[source]¶ Called by the runner after the generator has yielded.
No other methods will be called on this object before
start
.
-
is_ready
()[source]¶ Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
-
get_result
()[source]¶ Returns the value to use as the result of the yield expression.
This method will only be called once, and only after is_ready has returned true.
-
__atom_members__
= {'future': <atom.scalars.Value object at 0x7fad6b1089b0>, 'io_loop': <atom.scalars.Value object at 0x7fad6b108a50>, 'key': <atom.scalars.Value object at 0x7fad6b108910>, 'result_fn': <atom.scalars.Callable object at 0x7fad6b108af0>, 'runner': <atom.scalars.Value object at 0x7fad6b108b90>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
enamlnative.core.eventloop.gen.
multi
(children, quiet_exceptions=())[source]¶ Runs multiple asynchronous operations in parallel.
children
may either be a list or a dict whose values are yieldable objects.multi()
returns a new yieldable object that resolves to a parallel structure containing their results. Ifchildren
is a list, the result is a list of results in the same order; if it is a dict, the result is a dict with the same keys.That is,
results = yield multi(list_of_futures)
is equivalent to:results = [] for future in list_of_futures: results.append(yield future)
If any children raise exceptions,
multi()
will raise the first one. All others will be logged, unless they are of types contained in thequiet_exceptions
argument.If any of the inputs are YieldPoints <YieldPoint>, the returned yieldable object is a YieldPoint. Otherwise, returns a .Future. This means that the result of multi can be used in a native coroutine if and only if all of its children can be.
In a
yield
-based coroutine, it is not normally necessary to call this function directly, since the coroutine runner will do it automatically when a list or dict is yielded. However, it is necessary inawait
-based coroutines, or to pass thequiet_exceptions
argument.This function is available under the names
multi()
andMulti()
for historical reasons.Changed in version 4.2: If multiple yieldables fail, any exceptions after the first (which is raised) will be logged. Added the
quiet_exceptions
argument to suppress this logging for selected exception types.Changed in version 4.3: Replaced the class
Multi
and the functionmulti_future
with a unified functionmulti
. Added support for yieldables other than YieldPoint and .Future.
-
enamlnative.core.eventloop.gen.
Multi
(children, quiet_exceptions=())¶ Runs multiple asynchronous operations in parallel.
children
may either be a list or a dict whose values are yieldable objects.multi()
returns a new yieldable object that resolves to a parallel structure containing their results. Ifchildren
is a list, the result is a list of results in the same order; if it is a dict, the result is a dict with the same keys.That is,
results = yield multi(list_of_futures)
is equivalent to:results = [] for future in list_of_futures: results.append(yield future)
If any children raise exceptions,
multi()
will raise the first one. All others will be logged, unless they are of types contained in thequiet_exceptions
argument.If any of the inputs are YieldPoints <YieldPoint>, the returned yieldable object is a YieldPoint. Otherwise, returns a .Future. This means that the result of multi can be used in a native coroutine if and only if all of its children can be.
In a
yield
-based coroutine, it is not normally necessary to call this function directly, since the coroutine runner will do it automatically when a list or dict is yielded. However, it is necessary inawait
-based coroutines, or to pass thequiet_exceptions
argument.This function is available under the names
multi()
andMulti()
for historical reasons.Changed in version 4.2: If multiple yieldables fail, any exceptions after the first (which is raised) will be logged. Added the
quiet_exceptions
argument to suppress this logging for selected exception types.Changed in version 4.3: Replaced the class
Multi
and the functionmulti_future
with a unified functionmulti
. Added support for yieldables other than YieldPoint and .Future.
-
class
enamlnative.core.eventloop.gen.
MultiYieldPoint
(children, quiet_exceptions=())[source]¶ Bases:
enamlnative.core.eventloop.gen.YieldPoint
Runs multiple asynchronous operations in parallel.
This class is similar to multi, but it always creates a stack context even when no children require it. It is not compatible with native coroutines.
Changed in version 4.2: If multiple
YieldPoints
fail, any exceptions after the first (which is raised) will be logged. Added thequiet_exceptions
argument to suppress this logging for selected exception types.Changed in version 4.3: Renamed from
Multi
toMultiYieldPoint
. The nameMulti
remains as an alias for the equivalent multi function.Deprecated since version 4.3: Use multi instead.
-
__init__
(children, quiet_exceptions=())[source]¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
keys
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
children
¶ A member which allows list values.
Assigning to a list creates a copy. The orginal list will remain unmodified. This is similar to the semantics of the assignment operator on the C++ STL container classes.
-
unfinished_children
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
quiet_exceptions
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
start
(runner)[source]¶ Called by the runner after the generator has yielded.
No other methods will be called on this object before
start
.
-
is_ready
()[source]¶ Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
-
get_result
()[source]¶ Returns the value to use as the result of the yield expression.
This method will only be called once, and only after is_ready has returned true.
-
__atom_members__
= {'children': <atom.list.List object at 0x7fad6b254cc8>, 'keys': <atom.scalars.Value object at 0x7fad6b108c30>, 'quiet_exceptions': <atom.scalars.Value object at 0x7fad6b108d70>, 'unfinished_children': <atom.scalars.Value object at 0x7fad6b108cd0>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
enamlnative.core.eventloop.gen.
multi_future
(children, quiet_exceptions=())[source]¶ Wait for multiple asynchronous futures in parallel.
This function is similar to multi, but does not support YieldPoints <YieldPoint>.
New in version 4.0.
Changed in version 4.2: If multiple
Futures
fail, any exceptions after the first (which is raised) will be logged. Added thequiet_exceptions
argument to suppress this logging for selected exception types.Deprecated since version 4.3: Use multi instead.
-
enamlnative.core.eventloop.gen.
maybe_future
(x)[source]¶ Converts
x
into a .Future.If
x
is already a .Future, it is simply returned; otherwise it is wrapped in a new .Future. This is suitable for use asresult = yield gen.maybe_future(f())
when you don’t know whetherf()
returns a .Future or not.Deprecated since version 4.3: This function only handles
Futures
, not other yieldable objects. Instead of maybe_future, check for the non-future result types you expect (often justNone
), andyield
anything unknown.
-
enamlnative.core.eventloop.gen.
with_timeout
(timeout, future, quiet_exceptions=())[source]¶ Wraps a .Future (or other yieldable object) in a timeout.
Raises tornado.util.TimeoutError if the input future does not complete before
timeout
, which may be specified in any form allowed by .IOLoop.add_timeout (i.e. a datetime.timedelta or an absolute time relative to .IOLoop.time)If the wrapped .Future fails after it has timed out, the exception will be logged unless it is of a type contained in
quiet_exceptions
(which may be an exception type or a sequence of types).Does not support YieldPoint subclasses.
New in version 4.0.
Changed in version 4.1: Added the
quiet_exceptions
argument and the logging of unhandled exceptions.Changed in version 4.4: Added support for yieldable objects other than .Future.
-
enamlnative.core.eventloop.gen.
sleep
(duration)[source]¶ Return a .Future that resolves after the given number of seconds.
When used with
yield
in a coroutine, this is a non-blocking analogue to time.sleep (which should not be used in coroutines because it is blocking):yield gen.sleep(0.5)
Note that calling this function on its own does nothing; you must wait on the .Future it returns (usually by yielding it).
New in version 4.1.
-
class
enamlnative.core.eventloop.gen.
Runner
(gen, result_future, first_yielded)[source]¶ Bases:
atom.atom.Atom
Internal implementation of tornado.gen.engine.
Maintains information about pending callbacks and their results.
The results of the generator are stored in
result_future
(a .TracebackFuture)-
gen
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
result_future
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
future
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
yield_point
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
pending_callbacks
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
results
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
running
¶ A value of type bool.
-
finished
¶ A value of type bool.
-
had_exception
¶ A value of type bool.
-
io_loop
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
stack_context_deactivate
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
__init__
(gen, result_future, first_yielded)[source]¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
__atom_members__
= {'finished': <atom.scalars.Bool object at 0x7fad6a9af2d0>, 'future': <atom.scalars.Value object at 0x7fad6b108f50>, 'gen': <atom.scalars.Value object at 0x7fad6b108e10>, 'had_exception': <atom.scalars.Bool object at 0x7fad6a9af370>, 'io_loop': <atom.scalars.Value object at 0x7fad6a9af410>, 'pending_callbacks': <atom.scalars.Value object at 0x7fad6a9af0f0>, 'result_future': <atom.scalars.Value object at 0x7fad6b108eb0>, 'results': <atom.scalars.Value object at 0x7fad6a9af190>, 'running': <atom.scalars.Bool object at 0x7fad6a9af230>, 'stack_context_deactivate': <atom.scalars.Value object at 0x7fad6a9af4b0>, 'yield_point': <atom.scalars.Value object at 0x7fad6a9af050>}¶
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.gen.
Arguments
(args, kwargs)¶ Bases:
tuple
-
__dict__
= dict_proxy({'__module__': 'enamlnative.core.eventloop.gen', '__getstate__': <function __getstate__>, '__new__': <staticmethod object>, '_make': <classmethod object>, 'args': <property object>, '_replace': <function _replace>, '__slots__': (), '_asdict': <function _asdict>, '__repr__': <function __repr__>, 'kwargs': <property object>, '__dict__': <property object>, '_fields': ('args', 'kwargs'), '__getnewargs__': <function __getnewargs__>, '__doc__': 'Arguments(args, kwargs)'})¶
-
__getnewargs__
()¶ Return self as a plain tuple. Used by copy and pickle.
-
__getstate__
()¶ Exclude the OrderedDict from pickling
-
__module__
= 'enamlnative.core.eventloop.gen'¶
-
static
__new__
(args, kwargs)¶ Create new instance of Arguments(args, kwargs)
-
__repr__
()¶ Return a nicely formatted representation string
-
__slots__
= ()¶
-
args
¶ Alias for field number 0
-
kwargs
¶ Alias for field number 1
-
-
enamlnative.core.eventloop.gen.
convert_yielded
(*args, **kw)[source]¶ Convert a yielded object into a .Future.
The default implementation accepts lists, dictionaries, and Futures.
If the ~functools.singledispatch library is available, this function may be extended to support additional types. For example:
@convert_yielded.register(asyncio.Future) def _(asyncio_future): return tornado.platform.asyncio.to_tornado_future(asyncio_future)
New in version 4.1.
enamlnative.core.eventloop.http module¶
enamlnative.core.eventloop.interface module¶
Interfaces for platform-specific functionality.
This module exists primarily for documentation purposes and as base classes for other tornado.platform modules. Most code should import the appropriate implementation from tornado.platform.auto.
-
enamlnative.core.eventloop.interface.
set_close_exec
(fd)[source]¶ Sets the close-on-exec bit (
FD_CLOEXEC
)for a file descriptor.
-
class
enamlnative.core.eventloop.interface.
Waker
[source]¶ Bases:
atom.atom.Atom
A socket-like object that can wake another thread from
select()
.The ~tornado.ioloop.IOLoop will add the Waker’s fileno() to its
select
(orepoll
orkqueue
) calls. When another thread wants to wake up the loop, it calls wake. Once it has woken up, it will call consume to do any necessary per-wake cleanup. When theIOLoop
is closed, it closes its waker too.-
reader
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
writer
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
fileno
()[source]¶ Returns the read file descriptor for this waker.
Must be suitable for use with
select()
or equivalent on the local platform.
-
__atom_members__
= {'reader': <atom.scalars.Value object at 0x7fad6b1d5370>, 'writer': <atom.scalars.Value object at 0x7fad6b1d5410>}¶
-
__module__
= 'enamlnative.core.eventloop.interface'¶
-
__slots__
= ()¶
-
enamlnative.core.eventloop.ioloop module¶
An I/O event loop for non-blocking sockets.
Typical applications will use a single IOLoop object, in the
IOLoop.instance singleton. The IOLoop.start method should usually
be called at the end of the main()
function. Atypical applications may
use more than one IOLoop, such as one IOLoop per thread, or per unittest
case.
In addition to I/O events, the IOLoop can also schedule time-based events. IOLoop.add_timeout is a non-blocking alternative to time.sleep.
-
class
enamlnative.core.eventloop.ioloop.
IOLoop
[source]¶ Bases:
atom.atom.Atom
A level-triggered I/O loop.
We use
epoll
(Linux) orkqueue
(BSD and Mac OS X) if they are available, or else we fall back on select(). If you are implementing a system that needs to handle thousands of simultaneous connections, you should use a system that supports eitherepoll
orkqueue
.Example usage for a simple TCP server:
import errno import functools import tornado.ioloop import socket def connection_ready(sock, fd, events): while True: try: connection, address = sock.accept() except socket.error as e: if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return connection.setblocking(0) handle_connection(connection, address) if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("", port)) sock.listen(128) io_loop = tornado.ioloop.IOLoop.current() callback = functools.partial(connection_ready, sock) io_loop.add_handler(sock.fileno(), callback, io_loop.READ) io_loop.start()
By default, a newly-constructed IOLoop becomes the thread’s current IOLoop, unless there already is a current IOLoop. This behavior can be controlled with the
make_current
argument to the IOLoop constructor: ifmake_current=True
, the new IOLoop will always try to become current and it raises an error if there is already a current instance. Ifmake_current=False
, the new IOLoop will not try to become current.In general, an IOLoop cannot survive a fork or be shared across processes in any way. When multiple processes are being used, each process should create its own IOLoop, which also implies that any objects which depend on the IOLoop (such as .AsyncHTTPClient) must also be created in the child processes. As a guideline, anything that starts processes (including the tornado.process and multiprocessing modules) should do so as early as possible, ideally the first thing the application does after loading its configuration in
main()
.Changed in version 4.2: Added the
make_current
keyword argument to the IOLoop constructor.-
NONE
¶ A value which cannot be changed from its default.
-
READ
¶ A value which cannot be changed from its default.
-
WRITE
¶ A value which cannot be changed from its default.
-
ERROR
¶ A value which cannot be changed from its default.
-
static
instance
()[source]¶ Deprecated alias for IOLoop.current().
Changed in version 5.0: Previously, this method returned a global singleton IOLoop, in contrast with the per-thread IOLoop returned by current(). In nearly all cases the two were the same (when they differed, it was generally used from non-Tornado threads to communicate back to the main thread’s IOLoop). This distinction is not present in asyncio, so in order to facilitate integration with that package instance() was changed to be an alias to current(). Applications using the cross-thread communications aspect of instance() should instead set their own global variable to point to the IOLoop they want to use.
Deprecated since version 5.0.
-
static
initialized
()[source]¶ Returns true if there is a current IOLoop.
Changed in version 5.0: Redefined in terms of current() instead of instance().
Deprecated since version 5.0: This method only knows about IOLoop objects (and not, for example, asyncio event loops), so it is of limited use.
-
install
()[source]¶ Deprecated alias for make_current().
Changed in version 5.0: Previously, this method would set this IOLoop as the global singleton used by IOLoop.instance(). Now that instance() is an alias for current(), install() is an alias for make_current().
Deprecated since version 5.0.
-
static
clear_instance
()[source]¶ Deprecated alias for clear_current().
Changed in version 5.0: Previously, this method would clear the IOLoop used as the global singleton by IOLoop.instance(). Now that instance() is an alias for current(), clear_instance() is an alias for clear_instance().
Deprecated since version 5.0.
-
static
current
()[source]¶ Returns the current thread’s IOLoop.
If an IOLoop is currently running or has been marked as current by make_current, returns that instance. If there is no current IOLoop and
instance
is true, creates one.Changed in version 4.1: Added
instance
argument to control the fallback to IOLoop.instance().Changed in version 5.0: The
instance
argument now controls whether an IOLoop is created automatically when there is none, instead of whether we fall back to IOLoop.instance() (which is now an alias for this method)
-
make_current
()[source]¶ Makes this the IOLoop for the current thread.
An IOLoop automatically becomes current for its thread when it is started, but it is sometimes useful to call make_current explicitly before starting the IOLoop, so that code run at startup time can find the right instance.
Changed in version 4.1: An IOLoop created while there is no current IOLoop will automatically become current.
-
static
clear_current
()[source]¶ Clears the IOLoop for the current thread.
Intended primarily for use by test frameworks in between tests.
-
close
(all_fds=False)[source]¶ Closes the IOLoop, freeing any resources used.
If
all_fds
is true, all file descriptors registered on the IOLoop will be closed (not just the ones created by the IOLoop itself).Many applications will only use a single IOLoop that runs for the entire lifetime of the process. In that case closing the IOLoop is not necessary since everything will be cleaned up when the process exits. IOLoop.close is provided mainly for scenarios such as unit tests, which create and destroy a large number of
IOLoops
.An IOLoop must be completely stopped before it can be closed. This means that IOLoop.stop() must be called and IOLoop.start() must be allowed to return before attempting to call IOLoop.close(). Therefore the call to close will usually appear just after the call to start rather than near the call to stop.
Changed in version 3.1: If the IOLoop implementation supports non-integer objects for “file descriptors”, those objects will have their
close
method whenall_fds
is true.
-
add_handler
(fd, handler, events)[source]¶ Registers the given handler to receive the given events for
fd
.The
fd
argument may either be an integer file descriptor or a file-like object with afileno()
method (and optionally aclose()
method, which may be called when the IOLoop is shut down).The
events
argument is a bitwise or of the constantsIOLoop.READ
,IOLoop.WRITE
, andIOLoop.ERROR
.When an event occurs,
handler(fd, events)
will be run.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
update_handler
(fd, events)[source]¶ Changes the events we listen for
fd
.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
remove_handler
(fd)[source]¶ Stop listening for events on
fd
.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
set_blocking_signal_threshold
(seconds, action)[source]¶ Sends a signal if the IOLoop is blocked for more than
s
seconds.Pass
seconds=None
to disable. Requires Python 2.6 on a unixy platform.The action parameter is a Python signal handler. Read the documentation for the signal module for more information. If
action
is None, the process will be killed if it is blocked for too long.
-
set_blocking_log_threshold
(seconds)[source]¶ Logs a stack trace if the IOLoop is blocked for more than
s
seconds.Equivalent to
set_blocking_signal_threshold(seconds, self.log_stack)
-
log_stack
(signal, frame)[source]¶ Signal handler to log the stack trace of the current thread.
For use with set_blocking_signal_threshold.
-
start
()[source]¶ Starts the I/O loop.
The loop will run until one of the callbacks calls stop(), which will make the loop stop after the current event iteration completes.
-
stop
()[source]¶ Stop the I/O loop.
If the event loop is not currently running, the next call to start() will return immediately.
To use asynchronous methods from otherwise-synchronous code (such as unit tests), you can start and stop the event loop like this:
ioloop = IOLoop() async_method(ioloop=ioloop, callback=ioloop.stop) ioloop.start()
ioloop.start()
will return afterasync_method
has run its callback, whether that callback was invoked before or afterioloop.start
.Note that even after stop has been called, the IOLoop is not completely stopped until IOLoop.start has also returned. Some work that was scheduled before the call to stop may still be run before the IOLoop shuts down.
-
run_sync
(func, timeout=None)[source]¶ Starts the IOLoop, runs the given function, and stops the loop.
The function must return either a yieldable object or
None
. If the function returns a yieldable object, the IOLoop will run until the yieldable is resolved (and run_sync() will return the yieldable’s result). If it raises an exception, the IOLoop will stop and the exception will be re-raised to the caller.The keyword-only argument
timeout
may be used to set a maximum duration for the function. If the timeout expires, a tornado.util.TimeoutError is raised.This method is useful in conjunction with tornado.gen.coroutine to allow asynchronous calls in a
main()
function:@gen.coroutine def main(): # do stuff... if __name__ == '__main__': IOLoop.current().run_sync(main)
Changed in version 4.3: Returning a non-
None
, non-yieldable value is now an error.
-
time
()[source]¶ Returns the current time according to the IOLoop’s clock.
The return value is a floating-point number relative to an unspecified time in the past.
By default, the IOLoop’s time function is time.time. However, it may be configured to use e.g. time.monotonic instead. Calls to add_timeout that pass a number instead of a datetime.timedelta should use this function to compute the appropriate time, so they can work no matter what time function is chosen.
-
add_timeout
(deadline, callback, *args, **kwargs)[source]¶ Runs the
callback
at the timedeadline
from the I/O loop.Returns an opaque handle that may be passed to remove_timeout to cancel.
deadline
may be a number denoting a time (on the same scale as IOLoop.time, normally time.time), or a datetime.timedelta object for a deadline relative to the current time. Since Tornado 4.0, call_later is a more convenient alternative for the relative case since it does not require a timedelta object.Note that it is not safe to call add_timeout from other threads. Instead, you must use add_callback to transfer control to the IOLoop’s thread, and then call add_timeout from there.
Subclasses of IOLoop must implement either add_timeout or call_at; the default implementations of each will call the other. call_at is usually easier to implement, but subclasses that wish to maintain compatibility with Tornado versions prior to 4.0 must use add_timeout instead.
Changed in version 4.0: Now passes through
*args
and**kwargs
to the callback.
-
call_later
(delay, callback, *args, **kwargs)[source]¶ Runs the
callback
afterdelay
seconds have passed.Returns an opaque handle that may be passed to remove_timeout to cancel. Note that unlike the asyncio method of the same name, the returned object does not have a
cancel()
method.See add_timeout for comments on thread-safety and subclassing.
New in version 4.0.
-
call_at
(when, callback, *args, **kwargs)[source]¶ Runs the
callback
at the absolute time designated bywhen
.when
must be a number using the same reference point as IOLoop.time.Returns an opaque handle that may be passed to remove_timeout to cancel. Note that unlike the asyncio method of the same name, the returned object does not have a
cancel()
method.See add_timeout for comments on thread-safety and subclassing.
New in version 4.0.
-
remove_timeout
(timeout)[source]¶ Cancels a pending timeout.
The argument is a handle as returned by add_timeout. It is safe to call remove_timeout even if the callback has already been run.
-
add_callback
(callback, *args, **kwargs)[source]¶ Calls the given callback on the next I/O loop iteration.
It is safe to call this method from any thread at any time, except from a signal handler. Note that this is the only method in IOLoop that makes this thread-safety guarantee; all other interaction with the IOLoop must be done from that IOLoop’s thread. add_callback() may be used to transfer control from other threads to the IOLoop’s thread.
To add a callback from a signal handler, see add_callback_from_signal.
-
add_callback_from_signal
(callback, *args, **kwargs)[source]¶ Calls the given callback on the next I/O loop iteration.
Safe for use from a Python signal handler; should not be used otherwise.
Callbacks added with this method will be run without any .stack_context, to avoid picking up the context of the function that was interrupted by the signal.
-
spawn_callback
(callback, *args, **kwargs)[source]¶ Calls the given callback on the next IOLoop iteration.
Unlike all other callback-related methods on IOLoop,
spawn_callback
does not associate the callback with its caller’sstack_context
, so it is suitable for fire-and-forget callbacks that should not interfere with the caller.New in version 4.0.
-
add_future
(future, callback)[source]¶ Schedules a callback on the
IOLoop
when the given .Future is finished.The callback is invoked with one argument, the .Future.
-
handle_callback_exception
(callback)[source]¶ This method is called whenever a callback run by the IOLoop throws an exception.
By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions.
The exception itself is not passed explicitly, but is available in sys.exc_info.
-
split_fd
(fd)[source]¶ Returns an (fd, obj) pair from an
fd
parameter.We accept both raw file descriptors and file-like objects as input to add_handler and related methods. When a file-like object is passed, we must retain the object itself so we can close it correctly when the IOLoop shuts down, but the poller interfaces favor file descriptors (they will accept file-like objects and call
fileno()
for you, but they always return the descriptor itself).This method is provided for use by IOLoop subclasses and should not generally be used by application code.
New in version 4.0.
-
close_fd
(fd)[source]¶ Utility method to close an
fd
.If
fd
is a file-like object, we close it directly; otherwise we use os.close.This method is provided for use by IOLoop subclasses (in implementations of
IOLoop.close(all_fds=True)
and should not generally be used by application code.New in version 4.0.
-
__atom_members__
= {'ERROR': <atom.scalars.Constant object at 0x7fad6b105230>, 'NONE': <atom.scalars.Constant object at 0x7fad6b105050>, 'READ': <atom.scalars.Constant object at 0x7fad6b1050f0>, 'WRITE': <atom.scalars.Constant object at 0x7fad6b105190>, '_EPOLLERR': <atom.scalars.Constant object at 0x7fad6b0e5cd0>, '_EPOLLET': <atom.scalars.Constant object at 0x7fad6b0e5f50>, '_EPOLLHUP': <atom.scalars.Constant object at 0x7fad6b0e5d70>, '_EPOLLIN': <atom.scalars.Constant object at 0x7fad6b0e5af0>, '_EPOLLONESHOT': <atom.scalars.Constant object at 0x7fad6b0e5eb0>, '_EPOLLOUT': <atom.scalars.Constant object at 0x7fad6b0e5c30>, '_EPOLLPRI': <atom.scalars.Constant object at 0x7fad6b0e5b90>, '_EPOLLRDHUP': <atom.scalars.Constant object at 0x7fad6b0e5e10>, '_error_handler': <atom.scalars.Callable object at 0x7fad6b1052d0>}¶
-
__module__
= 'enamlnative.core.eventloop.ioloop'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.ioloop.
PollIOLoop
[source]¶ Bases:
enamlnative.core.eventloop.ioloop.IOLoop
Base class for IOLoops built around a select-like function.
For concrete implementations, see tornado.platform.epoll.EPollIOLoop (Linux), tornado.platform.kqueue.KQueueIOLoop (BSD and Mac), or tornado.platform.select.SelectIOLoop (all platforms).
-
time_func
¶ A value which is callable.
-
close
(all_fds=False)[source]¶ Closes the IOLoop, freeing any resources used.
If
all_fds
is true, all file descriptors registered on the IOLoop will be closed (not just the ones created by the IOLoop itself).Many applications will only use a single IOLoop that runs for the entire lifetime of the process. In that case closing the IOLoop is not necessary since everything will be cleaned up when the process exits. IOLoop.close is provided mainly for scenarios such as unit tests, which create and destroy a large number of
IOLoops
.An IOLoop must be completely stopped before it can be closed. This means that IOLoop.stop() must be called and IOLoop.start() must be allowed to return before attempting to call IOLoop.close(). Therefore the call to close will usually appear just after the call to start rather than near the call to stop.
Changed in version 3.1: If the IOLoop implementation supports non-integer objects for “file descriptors”, those objects will have their
close
method whenall_fds
is true.
-
add_handler
(fd, handler, events)[source]¶ Registers the given handler to receive the given events for
fd
.The
fd
argument may either be an integer file descriptor or a file-like object with afileno()
method (and optionally aclose()
method, which may be called when the IOLoop is shut down).The
events
argument is a bitwise or of the constantsIOLoop.READ
,IOLoop.WRITE
, andIOLoop.ERROR
.When an event occurs,
handler(fd, events)
will be run.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
update_handler
(fd, events)[source]¶ Changes the events we listen for
fd
.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
remove_handler
(fd)[source]¶ Stop listening for events on
fd
.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
set_blocking_signal_threshold
(seconds, action)[source]¶ Sends a signal if the IOLoop is blocked for more than
s
seconds.Pass
seconds=None
to disable. Requires Python 2.6 on a unixy platform.The action parameter is a Python signal handler. Read the documentation for the signal module for more information. If
action
is None, the process will be killed if it is blocked for too long.
-
start
()[source]¶ Starts the I/O loop.
The loop will run until one of the callbacks calls stop(), which will make the loop stop after the current event iteration completes.
-
stop
()[source]¶ Stop the I/O loop.
If the event loop is not currently running, the next call to start() will return immediately.
To use asynchronous methods from otherwise-synchronous code (such as unit tests), you can start and stop the event loop like this:
ioloop = IOLoop() async_method(ioloop=ioloop, callback=ioloop.stop) ioloop.start()
ioloop.start()
will return afterasync_method
has run its callback, whether that callback was invoked before or afterioloop.start
.Note that even after stop has been called, the IOLoop is not completely stopped until IOLoop.start has also returned. Some work that was scheduled before the call to stop may still be run before the IOLoop shuts down.
-
time
()[source]¶ Returns the current time according to the IOLoop’s clock.
The return value is a floating-point number relative to an unspecified time in the past.
By default, the IOLoop’s time function is time.time. However, it may be configured to use e.g. time.monotonic instead. Calls to add_timeout that pass a number instead of a datetime.timedelta should use this function to compute the appropriate time, so they can work no matter what time function is chosen.
-
call_at
(deadline, callback, *args, **kwargs)[source]¶ Runs the
callback
at the absolute time designated bywhen
.when
must be a number using the same reference point as IOLoop.time.Returns an opaque handle that may be passed to remove_timeout to cancel. Note that unlike the asyncio method of the same name, the returned object does not have a
cancel()
method.See add_timeout for comments on thread-safety and subclassing.
New in version 4.0.
-
remove_timeout
(timeout)[source]¶ Cancels a pending timeout.
The argument is a handle as returned by add_timeout. It is safe to call remove_timeout even if the callback has already been run.
-
add_callback
(callback, *args, **kwargs)[source]¶ Calls the given callback on the next I/O loop iteration.
It is safe to call this method from any thread at any time, except from a signal handler. Note that this is the only method in IOLoop that makes this thread-safety guarantee; all other interaction with the IOLoop must be done from that IOLoop’s thread. add_callback() may be used to transfer control from other threads to the IOLoop’s thread.
To add a callback from a signal handler, see add_callback_from_signal.
-
add_callback_from_signal
(callback, *args, **kwargs)[source]¶ Calls the given callback on the next I/O loop iteration.
Safe for use from a Python signal handler; should not be used otherwise.
Callbacks added with this method will be run without any .stack_context, to avoid picking up the context of the function that was interrupted by the signal.
-
__atom_members__
= {'ERROR': <atom.scalars.Constant object at 0x7fad6b105230>, 'NONE': <atom.scalars.Constant object at 0x7fad6b105050>, 'READ': <atom.scalars.Constant object at 0x7fad6b1050f0>, 'WRITE': <atom.scalars.Constant object at 0x7fad6b105190>, '_EPOLLERR': <atom.scalars.Constant object at 0x7fad6b0e5cd0>, '_EPOLLET': <atom.scalars.Constant object at 0x7fad6b0e5f50>, '_EPOLLHUP': <atom.scalars.Constant object at 0x7fad6b0e5d70>, '_EPOLLIN': <atom.scalars.Constant object at 0x7fad6b0e5af0>, '_EPOLLONESHOT': <atom.scalars.Constant object at 0x7fad6b0e5eb0>, '_EPOLLOUT': <atom.scalars.Constant object at 0x7fad6b0e5c30>, '_EPOLLPRI': <atom.scalars.Constant object at 0x7fad6b0e5b90>, '_EPOLLRDHUP': <atom.scalars.Constant object at 0x7fad6b0e5e10>, '_blocking_signal_threshold': <atom.scalars.Value object at 0x7fad6b105a50>, '_callbacks': <atom.instance.Instance object at 0x7fad6b1055f0>, '_cancellations': <atom.scalars.Int object at 0x7fad6b105690>, '_closing': <atom.scalars.Bool object at 0x7fad6b105870>, '_error_handler': <atom.scalars.Callable object at 0x7fad6b1052d0>, '_events': <atom.dict.Dict object at 0x7fad6b105550>, '_handlers': <atom.dict.Dict object at 0x7fad6b1054b0>, '_impl': <atom.scalars.Value object at 0x7fad6b105370>, '_pid': <atom.scalars.Int object at 0x7fad6b1059b0>, '_running': <atom.scalars.Bool object at 0x7fad6b105730>, '_stopped': <atom.scalars.Bool object at 0x7fad6b1057d0>, '_thread_ident': <atom.scalars.Value object at 0x7fad6b105910>, '_timeout_counter': <atom.scalars.Value object at 0x7fad6b105af0>, '_timeouts': <atom.list.List object at 0x7fad6b254a28>, '_waker': <atom.scalars.Value object at 0x7fad6b105b90>, 'time_func': <atom.scalars.Callable object at 0x7fad6b105410>}¶
-
__module__
= 'enamlnative.core.eventloop.ioloop'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.ioloop.
PeriodicCallback
(callback, callback_time)[source]¶ Bases:
atom.atom.Atom
Schedules the given callback to be called periodically.
The callback is called every
callback_time
milliseconds. Note that the timeout is given in milliseconds, while most other time-related functions in Tornado use seconds.If the callback runs for longer than
callback_time
milliseconds, subsequent invocations will be skipped to get back on schedule.start must be called after the PeriodicCallback is created.
Changed in version 5.0: The
io_loop
argument (deprecated since version 4.1) has been removed.-
io_loop
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
__init__
(callback, callback_time)[source]¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
callback
¶ A value which is callable.
-
callback_time
¶ A value of type float.
By default, ints and longs will be promoted to floats. Pass strict=True to the constructor to enable strict float checking.
-
__atom_members__
= {'_next_timeout': <atom.scalars.Float object at 0x7fad6b1080f0>, '_running': <atom.scalars.Bool object at 0x7fad6b105f50>, '_timeout': <atom.scalars.Float object at 0x7fad6b108050>, 'callback': <atom.scalars.Callable object at 0x7fad6b105e10>, 'callback_time': <atom.scalars.Float object at 0x7fad6b105eb0>, 'io_loop': <atom.scalars.Value object at 0x7fad6b108190>}¶
-
__module__
= 'enamlnative.core.eventloop.ioloop'¶
-
__slots__
= ()¶
-
enamlnative.core.eventloop.log module¶
Logging support for Tornado.
Tornado uses three logger streams:
These streams may be configured independently using the standard library’s
logging module. For example, you may wish to send tornado.access
logs
to a separate file for analysis.
-
class
enamlnative.core.eventloop.log.
Logger
[source]¶ Bases:
atom.atom.Atom
-
name
¶ A value of type unicode.
By default, plain strings will be promoted to unicode strings. Pass strict=True to the constructor to enable strict unicode checking.
-
__atom_members__
= {'name': <atom.scalars.Unicode object at 0x7fad6b1d5a50>}¶
-
__module__
= 'enamlnative.core.eventloop.log'¶
-
__slots__
= ()¶
-
enamlnative.core.eventloop.platforms module¶
EPoll-based IOLoop implementation for Linux systems.
-
class
enamlnative.core.eventloop.platforms.
EPollIOLoop
[source]¶ Bases:
enamlnative.core.eventloop.ioloop.PollIOLoop
-
__atom_members__
= {'ERROR': <atom.scalars.Constant object at 0x7fad6b105230>, 'NONE': <atom.scalars.Constant object at 0x7fad6b105050>, 'READ': <atom.scalars.Constant object at 0x7fad6b1050f0>, 'WRITE': <atom.scalars.Constant object at 0x7fad6b105190>, '_EPOLLERR': <atom.scalars.Constant object at 0x7fad6b0e5cd0>, '_EPOLLET': <atom.scalars.Constant object at 0x7fad6b0e5f50>, '_EPOLLHUP': <atom.scalars.Constant object at 0x7fad6b0e5d70>, '_EPOLLIN': <atom.scalars.Constant object at 0x7fad6b0e5af0>, '_EPOLLONESHOT': <atom.scalars.Constant object at 0x7fad6b0e5eb0>, '_EPOLLOUT': <atom.scalars.Constant object at 0x7fad6b0e5c30>, '_EPOLLPRI': <atom.scalars.Constant object at 0x7fad6b0e5b90>, '_EPOLLRDHUP': <atom.scalars.Constant object at 0x7fad6b0e5e10>, '_blocking_signal_threshold': <atom.scalars.Value object at 0x7fad6b105a50>, '_callbacks': <atom.instance.Instance object at 0x7fad6b1055f0>, '_cancellations': <atom.scalars.Int object at 0x7fad6b105690>, '_closing': <atom.scalars.Bool object at 0x7fad6b105870>, '_error_handler': <atom.scalars.Callable object at 0x7fad6b1052d0>, '_events': <atom.dict.Dict object at 0x7fad6b105550>, '_handlers': <atom.dict.Dict object at 0x7fad6b1054b0>, '_impl': <atom.scalars.Value object at 0x7fad6b105370>, '_pid': <atom.scalars.Int object at 0x7fad6b1059b0>, '_running': <atom.scalars.Bool object at 0x7fad6b105730>, '_stopped': <atom.scalars.Bool object at 0x7fad6b1057d0>, '_thread_ident': <atom.scalars.Value object at 0x7fad6b105910>, '_timeout_counter': <atom.scalars.Value object at 0x7fad6b105af0>, '_timeouts': <atom.list.List object at 0x7fad6b254a28>, '_waker': <atom.scalars.Value object at 0x7fad6b105b90>, 'time_func': <atom.scalars.Callable object at 0x7fad6b105410>}¶
-
__module__
= 'enamlnative.core.eventloop.platforms'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.platforms.
KQueueIOLoop
[source]¶ Bases:
enamlnative.core.eventloop.ioloop.PollIOLoop
-
__atom_members__
= {'ERROR': <atom.scalars.Constant object at 0x7fad6b105230>, 'NONE': <atom.scalars.Constant object at 0x7fad6b105050>, 'READ': <atom.scalars.Constant object at 0x7fad6b1050f0>, 'WRITE': <atom.scalars.Constant object at 0x7fad6b105190>, '_EPOLLERR': <atom.scalars.Constant object at 0x7fad6b0e5cd0>, '_EPOLLET': <atom.scalars.Constant object at 0x7fad6b0e5f50>, '_EPOLLHUP': <atom.scalars.Constant object at 0x7fad6b0e5d70>, '_EPOLLIN': <atom.scalars.Constant object at 0x7fad6b0e5af0>, '_EPOLLONESHOT': <atom.scalars.Constant object at 0x7fad6b0e5eb0>, '_EPOLLOUT': <atom.scalars.Constant object at 0x7fad6b0e5c30>, '_EPOLLPRI': <atom.scalars.Constant object at 0x7fad6b0e5b90>, '_EPOLLRDHUP': <atom.scalars.Constant object at 0x7fad6b0e5e10>, '_blocking_signal_threshold': <atom.scalars.Value object at 0x7fad6b105a50>, '_callbacks': <atom.instance.Instance object at 0x7fad6b1055f0>, '_cancellations': <atom.scalars.Int object at 0x7fad6b105690>, '_closing': <atom.scalars.Bool object at 0x7fad6b105870>, '_error_handler': <atom.scalars.Callable object at 0x7fad6b1052d0>, '_events': <atom.dict.Dict object at 0x7fad6b105550>, '_handlers': <atom.dict.Dict object at 0x7fad6b1054b0>, '_impl': <atom.scalars.Value object at 0x7fad6b105370>, '_pid': <atom.scalars.Int object at 0x7fad6b1059b0>, '_running': <atom.scalars.Bool object at 0x7fad6b105730>, '_stopped': <atom.scalars.Bool object at 0x7fad6b1057d0>, '_thread_ident': <atom.scalars.Value object at 0x7fad6b105910>, '_timeout_counter': <atom.scalars.Value object at 0x7fad6b105af0>, '_timeouts': <atom.list.List object at 0x7fad6b254a28>, '_waker': <atom.scalars.Value object at 0x7fad6b105b90>, 'time_func': <atom.scalars.Callable object at 0x7fad6b105410>}¶
-
__module__
= 'enamlnative.core.eventloop.platforms'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.platforms.
SelectIOLoop
[source]¶ Bases:
enamlnative.core.eventloop.ioloop.PollIOLoop
-
__atom_members__
= {'ERROR': <atom.scalars.Constant object at 0x7fad6b105230>, 'NONE': <atom.scalars.Constant object at 0x7fad6b105050>, 'READ': <atom.scalars.Constant object at 0x7fad6b1050f0>, 'WRITE': <atom.scalars.Constant object at 0x7fad6b105190>, '_EPOLLERR': <atom.scalars.Constant object at 0x7fad6b0e5cd0>, '_EPOLLET': <atom.scalars.Constant object at 0x7fad6b0e5f50>, '_EPOLLHUP': <atom.scalars.Constant object at 0x7fad6b0e5d70>, '_EPOLLIN': <atom.scalars.Constant object at 0x7fad6b0e5af0>, '_EPOLLONESHOT': <atom.scalars.Constant object at 0x7fad6b0e5eb0>, '_EPOLLOUT': <atom.scalars.Constant object at 0x7fad6b0e5c30>, '_EPOLLPRI': <atom.scalars.Constant object at 0x7fad6b0e5b90>, '_EPOLLRDHUP': <atom.scalars.Constant object at 0x7fad6b0e5e10>, '_blocking_signal_threshold': <atom.scalars.Value object at 0x7fad6b105a50>, '_callbacks': <atom.instance.Instance object at 0x7fad6b1055f0>, '_cancellations': <atom.scalars.Int object at 0x7fad6b105690>, '_closing': <atom.scalars.Bool object at 0x7fad6b105870>, '_error_handler': <atom.scalars.Callable object at 0x7fad6b1052d0>, '_events': <atom.dict.Dict object at 0x7fad6b105550>, '_handlers': <atom.dict.Dict object at 0x7fad6b1054b0>, '_impl': <atom.scalars.Value object at 0x7fad6b105370>, '_pid': <atom.scalars.Int object at 0x7fad6b1059b0>, '_running': <atom.scalars.Bool object at 0x7fad6b105730>, '_stopped': <atom.scalars.Bool object at 0x7fad6b1057d0>, '_thread_ident': <atom.scalars.Value object at 0x7fad6b105910>, '_timeout_counter': <atom.scalars.Value object at 0x7fad6b105af0>, '_timeouts': <atom.list.List object at 0x7fad6b254a28>, '_waker': <atom.scalars.Value object at 0x7fad6b105b90>, 'time_func': <atom.scalars.Callable object at 0x7fad6b105410>}¶
-
__module__
= 'enamlnative.core.eventloop.platforms'¶
-
__slots__
= ()¶
-
enamlnative.core.eventloop.posix module¶
Posix implementations of platform-specific functionality.
-
class
enamlnative.core.eventloop.posix.
Waker
[source]¶ Bases:
enamlnative.core.eventloop.interface.Waker
-
fileno
()[source]¶ Returns the read file descriptor for this waker.
Must be suitable for use with
select()
or equivalent on the local platform.
-
__atom_members__
= {'reader': <atom.scalars.Value object at 0x7fad6b1d5370>, 'writer': <atom.scalars.Value object at 0x7fad6b1d5410>}¶
-
__module__
= 'enamlnative.core.eventloop.posix'¶
-
__slots__
= ()¶
-
enamlnative.core.eventloop.stack_context module¶
StackContext allows applications to maintain threadlocal-like state that follows execution as it moves to other execution contexts.
The motivating examples are to eliminate the need for explicit
async_callback
wrappers (as in tornado.web.RequestHandler), and to
allow some additional context to be kept for logging.
This is slightly magic, but it’s an extension of the idea that an
exception handler is a kind of stack-local state and when that stack
is suspended and resumed in a new context that state needs to be
preserved. StackContext shifts the burden of restoring that state
from each call site (e.g. wrapping each .AsyncHTTPClient callback
in async_callback
) to the mechanisms that transfer control from
one context to another (e.g. .AsyncHTTPClient itself, .IOLoop,
thread pools, etc).
Example usage:
@contextlib.contextmanager
def die_on_error():
try:
yield
except Exception:
logging.error("exception in asynchronous operation",exc_info=True)
sys.exit(1)
with StackContext(die_on_error):
# Any exception thrown here *or in callback and its descendants*
# will cause the process to exit instead of spinning endlessly
# in the ioloop.
http_client.fetch(url, callback)
ioloop.start()
Most applications shouldn’t have to work with StackContext directly. Here are a few rules of thumb for when it’s necessary:
-
exception
enamlnative.core.eventloop.stack_context.
StackContextInconsistentError
[source]¶ Bases:
exceptions.Exception
-
__module__
= 'enamlnative.core.eventloop.stack_context'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
enamlnative.core.eventloop.stack_context.
StackContext
(context_factory)[source]¶ Bases:
atom.atom.Atom
Establishes the given context as a StackContext that will be transferred.
Note that the parameter is a callable that returns a context manager, not the context itself. That is, where for a non-transferable context manager you would say:
with my_context():
StackContext takes the function itself rather than its result:
with StackContext(my_context):
The result of
with StackContext() as cb:
is a deactivation callback. Run this callback when the StackContext is no longer needed to ensure that it is not propagated any further (note that deactivating a context does not affect any instances of that context that are currently pending). This is an advanced feature and not necessary in most applications.-
context_factory
¶ A value which is callable.
-
contexts
¶ A member which allows list values.
Assigning to a list creates a copy. The orginal list will remain unmodified. This is similar to the semantics of the assignment operator on the C++ STL container classes.
-
active
¶ A value of type bool.
-
old_contexts
¶ A member which allows tuple values.
If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
-
new_contexts
¶ A member which allows tuple values.
If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
-
__atom_members__
= {'active': <atom.scalars.Bool object at 0x7fad6b1d5b90>, 'context_factory': <atom.scalars.Callable object at 0x7fad6b1d5870>, 'contexts': <atom.list.List object at 0x7fad6b3bfc20>, 'new_contexts': <atom.tuple.Tuple object at 0x7fad6b1d5e10>, 'old_contexts': <atom.tuple.Tuple object at 0x7fad6b1d5d70>}¶
-
__module__
= 'enamlnative.core.eventloop.stack_context'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.stack_context.
ExceptionStackContext
(exception_handler)[source]¶ Bases:
atom.atom.Atom
Specialization of StackContext for exception handling.
The supplied
exception_handler
function will be called in the event of an uncaught exception in this context. The semantics are similar to a try/finally clause, and intended use cases are to log an error, close a socket, or similar cleanup actions. Theexc_info
triple(type, value, traceback)
will be passed to the exception_handler function.If the exception handler returns true, the exception will be consumed and will not be propagated to other exception handlers.
-
exception_handler
¶ A value which is callable.
-
active
¶ A value of type bool.
-
old_contexts
¶ A member which allows tuple values.
If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
-
new_contexts
¶ A member which allows tuple values.
If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
-
__atom_members__
= {'active': <atom.scalars.Bool object at 0x7fad6b1d5f50>, 'exception_handler': <atom.scalars.Callable object at 0x7fad6b1d5eb0>, 'new_contexts': <atom.tuple.Tuple object at 0x7fad6b0e50f0>, 'old_contexts': <atom.tuple.Tuple object at 0x7fad6b0e5050>}¶
-
__module__
= 'enamlnative.core.eventloop.stack_context'¶
-
__slots__
= ()¶
-
-
class
enamlnative.core.eventloop.stack_context.
NullContext
[source]¶ Bases:
atom.atom.Atom
Resets the StackContext.
Useful when creating a shared resource on demand (e.g. an .AsyncHTTPClient) where the stack that caused the creating is not relevant to future operations.
-
old_contexts
¶ A member which allows tuple values.
If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
-
__atom_members__
= {'old_contexts': <atom.tuple.Tuple object at 0x7fad6b0e5190>}¶
-
__module__
= 'enamlnative.core.eventloop.stack_context'¶
-
__slots__
= ()¶
-
-
enamlnative.core.eventloop.stack_context.
wrap
(fn)[source]¶ Returns a callable object that will restore the current StackContext when executed.
Use this whenever saving a callback to be executed later in a different execution context (either in a different thread or asynchronously in the same thread).
-
enamlnative.core.eventloop.stack_context.
run_with_stack_context
(context, func)[source]¶ Run a coroutine
func
in the given StackContext.It is not safe to have a
yield
statement within awith StackContext
block, so it is difficult to use stack context with .gen.coroutine. This helper function runs the function in the correct context while keeping theyield
andwith
statements syntactically separate.Example:
@gen.coroutine def incorrect(): with StackContext(ctx): # ERROR: this will raise StackContextInconsistentError yield other_coroutine() @gen.coroutine def correct(): yield run_with_stack_context(StackContext(ctx), other_coroutine)
New in version 3.1.
enamlnative.core.eventloop.util module¶
Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected that the functions and classes defined here will be useful to other applications, but they are documented here in case they are.
The one public-facing part of this module is the Configurable class and its ~Configurable.configure method, which becomes a part of the interface of its subclasses, including .AsyncHTTPClient, .IOLoop, and .Resolver.
-
enamlnative.core.eventloop.util.
is_finalizing
()¶
-
exception
enamlnative.core.eventloop.util.
TimeoutError
[source]¶ Bases:
exceptions.Exception
Exception raised by .with_timeout and .IOLoop.run_sync.
Changed in version 5.0:: Unified
tornado.gen.TimeoutError
andtornado.ioloop.TimeoutError
astornado.util.TimeoutError
. Both former names remain as aliases.-
__module__
= 'enamlnative.core.eventloop.util'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
enamlnative.core.eventloop.util.
ObjectDict
[source]¶ Bases:
typing.Dict
Makes a dictionary behave like an object, with attribute-style access.
-
__abstractmethods__
= frozenset([])¶
-
__args__
= None¶
-
__extra__
= None¶
-
__module__
= 'enamlnative.core.eventloop.util'¶
-
__next_in_mro__
¶ alias of
__builtin__.object
-
__orig_bases__
= (typing.Dict[str, typing.Any],)¶
-
__origin__
= None¶
-
__parameters__
= ()¶
-
classmethod
__subclasshook__
(subclass)¶
-
__tree_hash__
= 2580936¶
-
-
class
enamlnative.core.eventloop.util.
GzipDecompressor
[source]¶ Bases:
atom.atom.Atom
Streaming gzip decompressor.
The interface is like that of zlib.decompressobj (without some of the optional arguments, but it understands gzip headers and checksums.
-
decompressobj
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
decompress
(value, max_length=None)[source]¶ Decompress a chunk, returning newly-available data.
Some data may be buffered for later processing; flush must be called when there is no more input data to ensure that all data was processed.
If
max_length
is given, some input data may be left over inunconsumed_tail
; you must retrieve this value and pass it back to a future call to decompress if it is not empty.
-
unconsumed_tail
¶ Returns the unconsumed portion left over
-
flush
()[source]¶ Return any remaining buffered data not yet returned by decompress.
Also checks for errors such as truncated input. No other methods may be called on this object after flush.
-
__atom_members__
= {'decompressobj': <atom.scalars.Value object at 0x7fad6b1d5690>}¶
-
__module__
= 'enamlnative.core.eventloop.util'¶
-
__slots__
= ()¶
-
-
enamlnative.core.eventloop.util.
import_object
(name)[source]¶ Imports an object by name.
import_object(‘x’) is equivalent to ‘import x’. import_object(‘x.y.z’) is equivalent to ‘from x.y import z’.
>>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module
-
enamlnative.core.eventloop.util.
errno_from_exception
(e)[source]¶ Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno.
-
enamlnative.core.eventloop.util.
re_unescape
(s)[source]¶ Unescape a string escaped by re.escape.
May raise
ValueError
for regular expressions which could not have been produced by re.escape (for example, strings containing\d
cannot be unescaped).New in version 4.4.
-
class
enamlnative.core.eventloop.util.
Configurable
[source]¶ Bases:
object
Base class for configurable interfaces.
A configurable interface is an (abstract) class whose constructor acts as a factory function for one of its implementation subclasses. The implementation subclass as well as optional keyword arguments to its initializer can be set globally at runtime with configure.
By using the constructor as the factory method, the interface looks like a normal class, isinstance works as usual, etc. This pattern is most useful when the choice of implementation is likely to be a global decision (e.g. when ~select.epoll is available, always use it instead of ~select.select), or when a previously-monolithic class has been split into specialized subclasses.
Configurable subclasses must define the class methods configurable_base and configurable_default, and use the instance method initialize instead of
__init__
.-
classmethod
configurable_base
()[source]¶ Returns the base class of a configurable hierarchy.
This will normally return the class in which it is defined. (which is not necessarily the same as the cls classmethod parameter).
-
classmethod
configurable_default
()[source]¶ Returns the implementation class to be used if none is configured.
-
initialize
()[source]¶ Initialize a Configurable subclass instance.
Configurable classes should use initialize instead of
__init__
.Changed in version 4.2: Now accepts positional arguments in addition to keyword arguments.
-
classmethod
configure
(impl, **kwargs)[source]¶ Sets the class to use when the base class is instantiated.
Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters.
-
__dict__
= dict_proxy({'configurable_default': <classmethod object>, '__module__': 'enamlnative.core.eventloop.util', 'configurable_base': <classmethod object>, '__new__': <staticmethod object>, '_restore_configuration': <classmethod object>, 'configured_class': <classmethod object>, '__dict__': <attribute '__dict__' of 'Configurable' objects>, 'initialize': <function initialize>, '_Configurable__impl_class': None, '_save_configuration': <classmethod object>, '_Configurable__impl_kwargs': None, '__weakref__': <attribute '__weakref__' of 'Configurable' objects>, '__doc__': 'Base class for configurable interfaces.\n\n A configurable interface is an (abstract) class whose constructor\n acts as a factory function for one of its implementation subclasses.\n The implementation subclass as well as optional keyword arguments to\n its initializer can be set globally at runtime with `configure`.\n\n By using the constructor as the factory method, the interface\n looks like a normal class, `isinstance` works as usual, etc. This\n pattern is most useful when the choice of implementation is likely\n to be a global decision (e.g. when `~select.epoll` is available,\n always use it instead of `~select.select`), or when a\n previously-monolithic class has been split into specialized\n subclasses.\n\n Configurable subclasses must define the class methods\n `configurable_base` and `configurable_default`, and use the instance\n method `initialize` instead of ``__init__``.\n ', 'configure': <classmethod object>})¶
-
__module__
= 'enamlnative.core.eventloop.util'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
classmethod
-
class
enamlnative.core.eventloop.util.
ArgReplacer
(func, name)[source]¶ Bases:
atom.atom.Atom
Replaces one value in an
args, kwargs
pair.Inspects the function signature to find an argument by name whether it is passed by position or keyword. For use in decorators and similar wrappers.
-
name
¶ A value of type unicode.
By default, plain strings will be promoted to unicode strings. Pass strict=True to the constructor to enable strict unicode checking.
-
arg_pos
¶ A member class which supports value initialization.
A plain Value provides support for default values and factories, but does not perform any type checking or validation. It serves as a useful base class for scalar members and can be used for cases where type checking is not needed (like private attributes).
-
get_old_value
(args, kwargs, default=None)[source]¶ Returns the old value of the named argument without replacing it.
Returns
default
if the argument is not present.
-
__atom_members__
= {'arg_pos': <atom.scalars.Value object at 0x7fad6b1d5730>, 'name': <atom.scalars.Unicode object at 0x7fad6b1d57d0>}¶
-
__module__
= 'enamlnative.core.eventloop.util'¶
-
__slots__
= ()¶
-
replace
(new_value, args, kwargs)[source]¶ Replace the named argument in
args, kwargs
withnew_value
.Returns
(old_value, args, kwargs)
. The returnedargs
andkwargs
objects may not be the same as the input objects, or the input objects may be mutated.If the named argument was not found,
new_value
will be added tokwargs
and None will be returned asold_value
.
-