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 @tulip.task
def run(): 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()) tulip.set_event_loop_policy(greentulip.GreenEventLoopPolicy())

View File

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

View File

@ -54,7 +54,8 @@ class Unix(SocketConnector, pq3.Unix):
class SocketFactory(pg_socket.SocketFactory): class SocketFactory(pg_socket.SocketFactory):
def __init__(self, *args, socket_extra=None, **kw): def __init__(self, *args, socket_extra=None, **kw):
super().__init__(*args, **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): def __call__(self, timeout=None):
if self.async: if self.async:
@ -104,7 +105,8 @@ if __name__ == '__main__':
@greentulip.task @greentulip.task
def db(): def db():
connection = connector_factory('pq://postgres@localhost:5432', async=True)() connection = connector_factory(
'pq://postgres@localhost:5432', async=True)()
connection.connect() connection.connect()
try: try:
@ -122,7 +124,8 @@ if __name__ == '__main__':
@tulip.task @tulip.task
def run(): 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.set_event_loop_policy(greentulip.GreenEventLoopPolicy())
tulip.get_event_loop().run_until_complete(run()) tulip.get_event_loop().run_until_complete(run())

View File

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

View File

@ -2,25 +2,21 @@
# Copyright (c) 2013 Yury Selivanov # Copyright (c) 2013 Yury Selivanov
# License: Apache 2.0 # License: Apache 2.0
## ##
"""Greensocket (non-blocking) for Tulip. """Greensocket (non-blocking) for Tulip.
Use ``greentulip.socket`` in the same way as you would use stdlib's Use ``greentulip.socket`` in the same way as you would use stdlib's
``socket.socket`` in ``greentulip.task`` tasks or coroutines invoked ``socket.socket`` in ``greentulip.task`` tasks or coroutines invoked
from them. from them.
""" """
import tulip import tulip
from socket import error, SOCK_STREAM
from socket import *
from socket import socket as std_socket from socket import socket as std_socket
from . import yield_from from . import yield_from
class socket: class socket:
def __init__(self, *args, _from_sock=None, **kwargs): def __init__(self, *args, _from_sock=None, **kwargs):
if _from_sock: if _from_sock:
self._sock = _from_sock self._sock = _from_sock
@ -56,7 +52,8 @@ class socket:
return proxy return proxy
def _copydoc(func): 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 return func
@_copydoc @_copydoc
@ -104,17 +101,17 @@ class socket:
return WriteFile(self._loop, self._sock) return WriteFile(self._loop, self._sock)
raise NotImplementedError raise NotImplementedError
bind = _proxy('bind') bind = _proxy('bind')
listen = _proxy('listen') listen = _proxy('listen')
getsockname = _proxy('getsockname') getsockname = _proxy('getsockname')
getpeername = _proxy('getpeername') getpeername = _proxy('getpeername')
gettimeout = _proxy('gettimeout') gettimeout = _proxy('gettimeout')
getsockopt = _proxy('getsockopt') getsockopt = _proxy('getsockopt')
setsockopt = _proxy('setsockopt') setsockopt = _proxy('setsockopt')
fileno = _proxy('fileno') fileno = _proxy('fileno')
detach = _proxy('detach') detach = _proxy('detach')
close = _proxy('close') close = _proxy('close')
shutdown = _proxy('shutdown') shutdown = _proxy('shutdown')
del _copydoc, _proxy del _copydoc, _proxy
@ -161,11 +158,12 @@ class WriteFile:
pass pass
def create_connection(address:tuple, timeout=None): def create_connection(address: tuple, timeout=None):
loop = tulip.get_event_loop() loop = tulip.get_event_loop()
host, port = address 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: for res in rslt:
af, socktype, proto, canonname, sa = res 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)) files.extend(list_dir('{}{}.'.format(prefix, name), path))
else: else:
if (name != '__init__.py' and if (name != '__init__.py' and
name.endswith(suffix) and name.endswith(suffix) and
not name.startswith(('.', '_'))): not name.startswith(('.', '_'))):
files.append(('{}{}'.format(prefix, name[:-3]), path)) files.append(('{}{}'.format(prefix, name[:-3]), path))
return files return files

View File

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

View File

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

View File

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