Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active June 8, 2021 19:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save juancarlospaco/7a486056786919387ec6f5e83d693908 to your computer and use it in GitHub Desktop.
Save juancarlospaco/7a486056786919387ec6f5e83d693908 to your computer and use it in GitHub Desktop.
Python Versus Nim: Async

Python Versus Nim: Async

  • No performance benchmark.
  • Python ⟿ PEP-8
  • Nim ⟿ NEP1
  • Python ⟿ 3.7
  • Nim ⟿ 0.19
  • No Ofuscation, no Code-Golf.

This is to compare elegant, simple, expressive code. :cat:

import asyncdispatch
proc helloWorld() {.async.} =
echo "Hello World"
wait_for helloWorld()
import asyncio
async def async_function():
print("Hello World")
asyncio.run(async_function())
import asyncdispatch, os
type SomeObject = object
limit: int
iterator items(self: SomeObject): int =
for i in 0..self.limit:
sleep 1_000
yield i
proc asyncFunction() {.async.} =
for i in SomeObject(limit: 9):
echo i
wait_for asyncFunction()
import asyncio
class SomeObject(object):
def __init__(self, limit):
self.limit = limit
def __aiter__(self):
return self
async def __anext__(self):
if not self.limit:
raise StopAsyncIteration
self.limit -= 1
await asyncio.sleep(1)
return self.limit
async def async_function():
async for date in SomeObject(9):
print(date)
asyncio.run(async_function())
import asyncdispatch, threadpool
proc threadedFunction(i: int) {.async.} =
echo i
proc asyncFunction() {.async.} =
for i in 0..9:
discard spawn: threadedFunction(i)
wait_for asyncFunction()
import asyncio
def threaded_function(i):
print(i)
async def async_function():
for i in range(9):
await loop.run_in_executor(None, threaded_function, i)
loop = asyncio.get_event_loop()
loop.run_until_complete(async_function())
import asyncdispatch
proc asyncFunction(counter = 9) {.async, discardable.} =
echo counter
var count = counter
dec count
if count > 0:
discard sleepAsync(1_000)
asyncFunction(count)
wait_for asyncFunction()
import asyncio
def async_function(counter=9):
print(counter)
counter -= 1
if counter:
loop.call_later(1, async_function, counter)
else:
loop.stop()
loop = asyncio.get_event_loop()
loop.call_soon(async_function)
loop.run_forever()
import asyncdispatch
proc asyncFunction() {.async.} =
var remaining = 9
while true:
echo remaining
dec remaining
if not (remaining > 0):
break
await sleepAsync(1_000)
wait_for asyncFunction()
import asyncio
async def async_function():
remaining = 9
while True:
print(remaining)
remaining -= 1
if not remaining:
break
await asyncio.sleep(1)
asyncio.run(async_function())
@KolbyML
Copy link

KolbyML commented Nov 11, 2018

image
Is it too hard to write good Python ????

@juancarlospaco
Copy link
Author

PEP-8 & Chill.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment