PEP 403: Try a simple goless example

This commit is contained in:
Nick Coghlan 2014-07-26 01:59:36 +10:00
parent be2e5ec687
commit af3785aa35
1 changed files with 97 additions and 1 deletions

View File

@ -392,7 +392,103 @@ Constructs that verge on decorator abuse can be eliminated::
def f(): def f():
... ...
`goless <https://goless.readthedocs.org>`__ aims to bring support for
"goroutine" style programming to Python, but some aspects currently need
to be written out of order relative to their go counterparts. This PEP
allows the "select" example from the goless documentation to be written as
follows (assuming appropriate tweaks to some existing APIs, and an
alternative ``switch`` API that is like ``select`` but expects the cases
to be supplied as functions on a class)::
c1 = goless.chan()
c2 = goless.chan()
@in goless.go(func1)
def func1():
time.sleep(1)
c1.send('one')
@in goless.go(func2)
def func2():
time.sleep(2)
c2.send('two')
@in [goless.switch(cases) for i in range(2)]
class cases:
@goless.rcase(c1)
def chan1(chan, msg):
print("From channel 1:", msg)
@goless.rcase(c2)
def chan2(chan, msg):
print("From channel 2:", msg)
@goless.dcase()
def default(chan, msg):
print("From other channel:", msg)
Now, that ``goless`` example could be written as follows today (again,
assuming the addition of ``goless.switch`` and related changes)::
c1 = goless.chan()
c2 = goless.chan()
@goless.go
def func1():
time.sleep(1)
c1.send('one')
@goless.go
def func2():
time.sleep(2)
c2.send('two')
class cases:
@goless.rcase(c1)
def chan1(chan, msg):
print("From channel 1:", msg)
@goless.rcase(c2)
def chan2(chan, msg):
print("From channel 2:", msg)
@goless.dcase()
def default(chan, msg):
print("From other channel:", msg)
for i in range(2):
goless.switch(cases)
The ``@in`` version helps make it clear that the ``goless.go`` calls have
non-trivial side effects, as well as moving the ``switch`` call ahead
of the definition of the cases. However, it cries out for something more
readable, even if it's just syntactic sugar for an if-elif chain (as was
considered as one of the options in PEP 3103). That might look something
like::
for i in range(2):
switch goless.select() as chan, msg:
case chan is c1:
print("From channel 1:", msg)
case chan is c2:
print("From channel 2:", msg)
else:
print("From other channel:", msg)
Rather than the current::
for i in range(2):
chan, msg = goless.select()
if chan is c1:
print("From channel 1:", msg)
elif chan is c2:
print("From channel 2:", msg)
else:
print("From other channel:", msg)
(Note: the fact this doesn't appear to offer any particularly compelling
improvements to goless code *does* count heavily against the proposal)
Reference Implementation Reference Implementation
======================== ========================