Skip to content

Instantly share code, notes, and snippets.

@lkluft
Created February 10, 2018 08:31
Show Gist options
  • Save lkluft/5dff2b820bbbf0ffa183c335f9842997 to your computer and use it in GitHub Desktop.
Save lkluft/5dff2b820bbbf0ffa183c335f9842997 to your computer and use it in GitHub Desktop.
Decorator that iterates over the first arg, if possible.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "from functools import wraps\nfrom collections import Iterable\n\n\ndef iterate_first_arg(func):\n \"\"\"Decorator that iterates over the first arg, if possible.\"\"\"\n @wraps(func)\n def wrapper(arg, *args, **kwargs):\n if isinstance(arg, Iterable) and not isinstance(arg, str):\n return [func(a, *args, **kwargs) for a in arg]\n else:\n return func(arg, *args, **kwargs)\n return wrapper\n\n \n@iterate_first_arg\ndef hello(name):\n \"\"\"Return welcome message.\"\"\"\n return f'Hello {name}!'\n \n\n# Single positional argument\nprint(hello('World'))\n\n# List argument\nprint(hello(['World', 'Foo', 'Bar']))\n\n# Generator argument\nprint(hello((w for w in ['World', 'Foo', 'Bar'])))",
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"text": "Hello World!\n['Hello World!', 'Hello Foo!', 'Hello Bar!']\n['Hello World!', 'Hello Foo!', 'Hello Bar!']\n",
"name": "stdout"
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.6.4",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"gist": {
"id": "",
"data": {
"description": "Decorator that iterates over the first arg, if possible.",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment