examples/experiments/compile_fn.ipynb
{
"cells": [
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"import string\n",
"from functools import lru_cache\n",
"from sidekick import fn\n",
"\n",
"\n",
"def specialized_fn(arity, kwargs=True):\n",
" \"\"\"\n",
" Creates an specialized fn class.\n",
" \"\"\"\n",
"\n",
"def specialized_fn_source(arity, kwargs=True):\n",
" \"\"\"\n",
" Compiles a specialized __call__ function with the given arity.\n",
"\n",
" Args:\n",
" arity (int):\n",
" Function arity\n",
" has_optional_args (bool):\n",
" If True, function has optional args.\n",
" \"\"\"\n",
" \n",
" lines = [\n",
" f'def __call__(self, {args_declaration(arity, kwargs)}):',\n",
" ' func = self._sk_function_',\n",
"\n",
" ]\n",
" return '\\n'.join(lines)\n",
"\n",
"\n",
"def args_declaration(n, opt):\n",
" args = list(string.ascii_lowercase[:n])\n",
" args[1:] = [f'{arg}=not_given' for arg in args[1:]]\n",
" if opt:\n",
" args.append('**kwargs')\n",
" return ', '.join(args)\n",
"\n",
"def partial_lambda(arity, fixed, name='func'):\n",
" return f'lambda {}'\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'def __call__(self, a, b=not_given, **kwargs):\\n func = self._sk_function_'"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"specialized_fn_source(2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}