I recently needed to call some synchronous code from asyncio. Thankfully, asyncio provides the run_in_executor
function, which runs the specified function in a different thread. Here is an example of using it:
Algorithms in Python
I recently decided to brush up on my algorithms and data structures by writing them in Python. Though these are not optimized, they could be helpful for reference. Here is the Github repo: https://github.com/calebmadrigal/algorithms-in-python.
A some of the algorithms included:
Recursion with asyncio
Recursion is awesome, but has the downside of growing the stack, which can limit its usefulness. Some languages like Scheme, however, have Tail-call optimization, which lets programmers write Tail-recursive functions that don't grow the call stack. Python does not have Tail-call optimization (TCO), but with asyncio, we can have something like Tail-call optimization. Basically, this method uses the asyncio event loop like a trampoline function.
Example:
Display List as Table in IPython Notebook
IPython Notebook provides hook methods like _repr_html_
which can be defined by Python objects to allow richer representations. Here's an example:
class ListTable(list):
""" Overridden list class which takes a 2-dimensional list of
the form [[1,2,3],[4,5,6]], and renders an HTML Table in
IPython Notebook. """
def _repr_html_(self):
html = ["<table>"]
for row in self:
html.append("<tr>")
for col in row:
html.append("<td>{0}</td>".format(col))
html.append("</tr>")
html.append("</table>")
return ''.join(html)
import random
table = ListTable()
table.append(['x', 'y', 'x-y', '(x-y)^2'])
for i in xrange(7):
x = random.uniform(0, 10)
y = random.uniform(0, 10)
table.append([x, y, x-y, (x-y)**2])
table
How To Draw Lines With Matplotlib
Simple example to show how to draw lines with Matplotlib (in IPython Notebook).
ipython notebook --pylab inline
import matplotlib.lines as lines
fig, ax = plt.subplots()
fig.set_size_inches(6,6) # Make graph square
scatter([-0.1],[-0.1],s=0.01) # Move graph window a little left and down
line1 = [(0,0), (1,0)]
line2 = [(0,0), (0,1)]
# Note that the Line2D takes a list of x values and a list of y values,
# not 2 points as one might expect. So we have to convert our points
# an x-list and a y-list.
(line1_xs, line1_ys) = zip(*line1)
(line2_xs, line2_ys) = zip(*line2)
ax.add_line(Line2D(line1_xs, line1_ys, linewidth=2, color='blue'))
ax.add_line(Line2D(line2_xs, line2_ys, linewidth=2, color='red'))
plot()
show()