pep8-ify code

This commit is contained in:
Nikolay Kim 2013-07-23 10:15:57 -07:00
parent d0abe40dbf
commit bf4a25fd85
9 changed files with 62 additions and 56 deletions

View File

@ -29,7 +29,8 @@ def get():
@tulip.task
def run():
yield from tulip.wait([get(), sleeper()], return_when=tulip.FIRST_COMPLETED)
yield from tulip.wait(
[get(), sleeper()], return_when=tulip.FIRST_COMPLETED)
tulip.set_event_loop_policy(greentulip.GreenEventLoopPolicy())

View File

@ -32,7 +32,6 @@ class GreenConnection(connections.Connection):
if __name__ == '__main__':
import greentulip
import time
import tulip
@tulip.task
def sleeper():

View File

@ -54,7 +54,8 @@ class Unix(SocketConnector, pq3.Unix):
class SocketFactory(pg_socket.SocketFactory):
def __init__(self, *args, socket_extra=None, **kw):
super().__init__(*args, **kw)
self.async = socket_extra.get('async', False) if socket_extra else False
self.async = (socket_extra.get('async', False)
if socket_extra else False)
def __call__(self, timeout=None):
if self.async:
@ -104,7 +105,8 @@ if __name__ == '__main__':
@greentulip.task
def db():
connection = connector_factory('pq://postgres@localhost:5432', async=True)()
connection = connector_factory(
'pq://postgres@localhost:5432', async=True)()
connection.connect()
try:
@ -122,7 +124,8 @@ if __name__ == '__main__':
@tulip.task
def run():
yield from tulip.wait([db(), sleeper()], return_when=tulip.FIRST_COMPLETED)
yield from tulip.wait(
[db(), sleeper()], return_when=tulip.FIRST_COMPLETED)
tulip.set_event_loop_policy(greentulip.GreenEventLoopPolicy())
tulip.get_event_loop().run_until_complete(run())

View File

@ -3,11 +3,9 @@
# License: Apache 2.0
##
"""greentulip package allows to compose greenlets and tulip coroutines."""
__all__ = 'task', 'yield_from'
__all__ = ['task', 'yield_from']
import greenlet
@ -57,7 +55,8 @@ class GreenTask(tulip.Task):
# The task is in the greenlet, that means that we have a result
# for the "yield_from"
if exc is not None:
result = self._greenlet.throw(type(exc), exc, exc.__traceback__)
result = self._greenlet.throw(
type(exc), exc, exc.__traceback__)
else:
result = self._greenlet.switch(value)
@ -86,6 +85,7 @@ class GreenUnixSelectorLoop(_GreenLoopMixin, unix_events.SelectorEventLoop):
class GreenEventLoopPolicy(tulip.DefaultEventLoopPolicy):
def new_event_loop(self):
return GreenUnixSelectorLoop()
@ -98,22 +98,22 @@ def yield_from(future):
if __debug__:
if not isinstance(gl.parent, _LoopGreenlet):
raise RuntimeError(
'"greentulip.yield_from" requires GreenEventLoopPolicy '
'or compatible')
'"greentulip.yield_from" requires GreenEventLoopPolicy '
'or compatible')
# or something went horribly wrong...
if not isinstance(gl, _TaskGreenlet):
raise RuntimeError(
'"greentulip.yield_from" was supposed to be called from a '
'"greentulip.task" or a subsequent coroutine')
'"greentulip.yield_from" was supposed to be called from a '
'"greentulip.task" or a subsequent coroutine')
# ...ditto
task = gl.task
if not isinstance(future, futures.Future):
raise RuntimeError(
'greenlet.yield_from was supposed to receive only Futures, '
'got {!r} in task {!r}'.format(future, task))
'greenlet.yield_from was supposed to receive only Futures, '
'got {!r} in task {!r}'.format(future, task))
# "_wakeup" will call the "_step" method (which we overloaded in
# GreenTask, and therefore wakeup the awaiting greenlet)
@ -122,7 +122,7 @@ def yield_from(future):
# task cancellation has been delayed.
if task._must_cancel:
talk._fut_waiter.cancel()
task._fut_waiter.cancel()
# Jump out of the current task greenlet (we'll return to GreenTask._step)
return gl.parent.switch(_YIELDED)

View File

@ -2,25 +2,21 @@
# Copyright (c) 2013 Yury Selivanov
# License: Apache 2.0
##
"""Greensocket (non-blocking) for Tulip.
Use ``greentulip.socket`` in the same way as you would use stdlib's
``socket.socket`` in ``greentulip.task`` tasks or coroutines invoked
from them.
"""
import tulip
from socket import *
from socket import error, SOCK_STREAM
from socket import socket as std_socket
from . import yield_from
class socket:
def __init__(self, *args, _from_sock=None, **kwargs):
if _from_sock:
self._sock = _from_sock
@ -56,7 +52,8 @@ class socket:
return proxy
def _copydoc(func):
func.__doc__ = getattr(getattr(std_socket, func.__name__), '__doc__', None)
func.__doc__ = getattr(
getattr(std_socket, func.__name__), '__doc__', None)
return func
@_copydoc
@ -104,17 +101,17 @@ class socket:
return WriteFile(self._loop, self._sock)
raise NotImplementedError
bind = _proxy('bind')
listen = _proxy('listen')
bind = _proxy('bind')
listen = _proxy('listen')
getsockname = _proxy('getsockname')
getpeername = _proxy('getpeername')
gettimeout = _proxy('gettimeout')
getsockopt = _proxy('getsockopt')
setsockopt = _proxy('setsockopt')
fileno = _proxy('fileno')
detach = _proxy('detach')
close = _proxy('close')
shutdown = _proxy('shutdown')
gettimeout = _proxy('gettimeout')
getsockopt = _proxy('getsockopt')
setsockopt = _proxy('setsockopt')
fileno = _proxy('fileno')
detach = _proxy('detach')
close = _proxy('close')
shutdown = _proxy('shutdown')
del _copydoc, _proxy
@ -161,11 +158,12 @@ class WriteFile:
pass
def create_connection(address:tuple, timeout=None):
def create_connection(address: tuple, timeout=None):
loop = tulip.get_event_loop()
host, port = address
rslt = yield_from(loop.getaddrinfo(host, port, family=0, type=SOCK_STREAM))
rslt = yield_from(
loop.getaddrinfo(host, port, family=0, type=SOCK_STREAM))
for res in rslt:
af, socktype, proto, canonname, sa = res

View File

@ -78,8 +78,8 @@ def load_modules(basedir, suffix='.py'):
files.extend(list_dir('{}{}.'.format(prefix, name), path))
else:
if (name != '__init__.py' and
name.endswith(suffix) and
not name.startswith(('.', '_'))):
name.endswith(suffix) and
not name.startswith(('.', '_'))):
files.append(('{}{}'.format(prefix, name[:-3]), path))
return files

View File

@ -1,11 +1,11 @@
import os
from distutils.core import setup, Extension
from distutils.core import setup
setup(name='greentulip',
description="Greenlet based implementation of PEP 3156 event loop.",
url='https://github.com/1st1/greentulip/',
license='Apache 2.0',
packages=['greentulip'],
install_requires = ['greenlet'],
)
setup(
name='greentulip',
description="Greenlet based implementation of PEP 3156 event loop.",
url='https://github.com/1st1/greentulip/',
license='Apache 2.0',
packages=['greentulip'],
install_requires=['greenlet'],
)

View File

@ -2,8 +2,6 @@
# Copyright (c) 2013 Yury Selivanov
# License: Apache 2.0
##
import greentulip
import greentulip.socket as greensocket
@ -12,6 +10,7 @@ import unittest
class SocketTests(unittest.TestCase):
def setUp(self):
tulip.set_event_loop_policy(greentulip.GreenEventLoopPolicy())
self.loop = tulip.new_event_loop()
@ -22,13 +21,14 @@ class SocketTests(unittest.TestCase):
tulip.set_event_loop_policy(None)
def test_socket_docs(self):
self.assertTrue('accept connections' in greensocket.socket.listen.__doc__)
self.assertTrue('Receive' in greensocket.socket.recv.__doc__)
self.assertIn('accept connections', greensocket.socket.listen.__doc__)
self.assertIn('Receive', greensocket.socket.recv.__doc__)
def test_socket_setblocking(self):
sock = greensocket.socket()
self.assertEquals(sock.gettimeout(), 0)
with self.assertRaisesRegex(greensocket.error, 'does not support blocking mode'):
with self.assertRaisesRegex(
greensocket.error, 'does not support blocking mode'):
sock.setblocking(True)
def test_socket_echo(self):
@ -95,7 +95,8 @@ class SocketTests(unittest.TestCase):
thread = threading.Thread(target=client, args=(std_socket.socket,))
thread.setDaemon(True)
thread.start()
self.loop.run_until_complete(greentulip.task(server)(greensocket.socket))
self.loop.run_until_complete(
greentulip.task(server)(greensocket.socket))
thread.join(1)
self.assertEqual(check, 1)
@ -104,6 +105,7 @@ class SocketTests(unittest.TestCase):
thread = threading.Thread(target=server, args=(std_socket.socket,))
thread.setDaemon(True)
thread.start()
self.loop.run_until_complete(greentulip.task(client)(greensocket.socket))
self.loop.run_until_complete(
greentulip.task(client)(greensocket.socket))
thread.join(1)
self.assertEqual(check, 2)

View File

@ -71,8 +71,10 @@ class TaskTests(unittest.TestCase):
@greentulip.task
def foo():
with self.assertRaisesRegex(RuntimeError,
'greenlet.yield_from was supposed to receive only Futures'):
with self.assertRaisesRegex(
RuntimeError,
'greenlet.yield_from was supposed to receive '
'only Futures'):
greentulip.yield_from(bar())
fut = foo()
@ -85,8 +87,9 @@ class TaskTests(unittest.TestCase):
@tulip.task
def foo():
with self.assertRaisesRegex(RuntimeError,
'"greentulip.yield_from" was supposed to be called'):
with self.assertRaisesRegex(
RuntimeError,
'"greentulip.yield_from" was supposed to be called'):
greentulip.yield_from(bar())
fut = foo()