Skip to content

Instantly share code, notes, and snippets.

@amaarora
Created November 16, 2020 20:52
Show Gist options
  • Select an option

  • Save amaarora/4aafc1f6a298a41e0b10bd00aaf8720c to your computer and use it in GitHub Desktop.

Select an option

Save amaarora/4aafc1f6a298a41e0b10bd00aaf8720c to your computer and use it in GitHub Desktop.
aman_arora/git/fastcore/nbs/fastuple.ipynb
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "from fastcore.imports import *",
"execution_count": 1,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "#export\ndef listify(o):\n \"Convert `o` to a `list`\"\n if o is None: return []\n if isinstance(o, list): return o\n if isinstance(o, str) or is_array(o): return [o]\n if is_iter(o): return list(o)\n return [o]",
"execution_count": 2,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "#export\ndef is_array(x):\n \"`True` if `x` supports `__array__` or `iloc`\"\n return hasattr(x,'__array__') or hasattr(x,'iloc')",
"execution_count": 3,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "#export\ndef cycle(o):\n \"Like `itertools.cycle` except creates list of `None`s if `o` is empty\"\n o = listify(o)\n return itertools.cycle(o) if o is not None and len(o) > 0 else itertools.cycle([None])",
"execution_count": 4,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "#export\nnum_methods = \"\"\"\n __add__ __sub__ __mul__ __matmul__ __truediv__ __floordiv__ __mod__ __divmod__ __pow__\n __lshift__ __rshift__ __and__ __xor__ __or__ __neg__ __pos__ __abs__\n\"\"\".split()\nrnum_methods = \"\"\"\n __radd__ __rsub__ __rmul__ __rmatmul__ __rtruediv__ __rfloordiv__ __rmod__ __rdivmod__\n __rpow__ __rlshift__ __rrshift__ __rand__ __rxor__ __ror__\n\"\"\".split()\ninum_methods = \"\"\"\n __iadd__ __isub__ __imul__ __imatmul__ __itruediv__\n __ifloordiv__ __imod__ __ipow__ __ilshift__ __irshift__ __iand__ __ixor__ __ior__\n\"\"\".split()",
"execution_count": 5,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "#export\nclass fastuple(tuple):\n \"A `tuple` with elementwise ops and more friendly __init__ behavior\"\n def __new__(cls, x=None, *rest):\n if x is None: x = ()\n if not isinstance(x,tuple):\n if len(rest): x = (x,)\n else:\n try: x = tuple(iter(x))\n except TypeError: x = (x,)\n return super().__new__(cls, x+rest if rest else x)\n\n def _op(self,op,*args):\n if not isinstance(self,fastuple): self = fastuple(self)\n return type(self)(map(op,self,*map(cycle, args)))\n\n def mul(self,*args):\n \"`*` is already defined in `tuple` for replicating, so use `mul` instead\"\n return fastuple._op(self, operator.mul,*args)\n\n def add(self,*args):\n \"`+` is already defined in `tuple` for concat, so use `add` instead\"\n return fastuple._op(self, operator.add,*args)\n\ndef _get_op(op):\n if isinstance(op,str): op = getattr(operator,op)\n def _f(self,*args): return self._op(op,*args)\n return _f\n\nfor n in num_methods:\n if not hasattr(fastuple, n) and hasattr(operator,n): setattr(fastuple,n,_get_op(n))\n\nfor n in 'eq ne lt le gt ge'.split(): setattr(fastuple,n,_get_op(n))\nsetattr(fastuple,'__invert__',_get_op('__not__'))\nsetattr(fastuple,'max',_get_op(max))\nsetattr(fastuple,'min',_get_op(min))",
"execution_count": 6,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "fastuple.add((1,2),(-1), (-2))",
"execution_count": 7,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 7,
"data": {
"text/plain": "(<map at 0x7fedf00e35d0>)"
},
"metadata": {}
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.7.5",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"gist": {
"id": "",
"data": {
"description": "aman_arora/git/fastcore/nbs/fastuple.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment