Skip to content

Instantly share code, notes, and snippets.

@adagio
Created October 16, 2018 03:36
Show Gist options
  • Save adagio/25c5e84493d8394f15ac5f650e12b93a to your computer and use it in GitHub Desktop.
Save adagio/25c5e84493d8394f15ac5f650e12b93a to your computer and use it in GitHub Desktop.
enums.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "enums.ipynb",
"version": "0.3.2",
"provenance": [],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"[View in Colaboratory](https://colab.research.google.com/gist/adagio/25c5e84493d8394f15ac5f650e12b93a/enums.ipynb)"
]
},
{
"metadata": {
"id": "Syb1I3D7lyTM",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Creating Enumerations"
]
},
{
"metadata": {
"id": "Pks2oUUIhJrz",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 52
},
"outputId": "fdf0dba5-a2e4-434d-ab63-bc35a996c754"
},
"cell_type": "code",
"source": [
"import enum\n",
"\n",
"class BugStatus(enum.Enum):\n",
"\n",
" new = 7\n",
" incomplete = 6\n",
" invalid = 5\n",
" wont_fix = 4\n",
" in_progress = 3\n",
" fix_committed = 2\n",
" fix_released = 1\n",
"\n",
"\n",
"print(f\"Member name: {BugStatus.wont_fix.name}.\")\n",
"print(f\"Member value: {BugStatus.wont_fix.value}.\")\n"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Member name: wont_fix.\n",
"Member value: 4.\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "zYbNFauwl5G9",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Iteration"
]
},
{
"metadata": {
"id": "eMvW7jw5jZad",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 139
},
"outputId": "a15967cd-09ff-4fbe-edc1-b8a46ab906a7"
},
"cell_type": "code",
"source": [
"for status in BugStatus:\n",
" print(f'{status.name:15} = {status.value}')"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"new = 7\n",
"incomplete = 6\n",
"invalid = 5\n",
"wont_fix = 4\n",
"in_progress = 3\n",
"fix_committed = 2\n",
"fix_released = 1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "MgtJiqsClkhb",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Comparing Enums"
]
},
{
"metadata": {
"id": "m2wWEfq_lmmk",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 86
},
"outputId": "a1b1cf06-c836-48ee-be56-7383bdd55a20"
},
"cell_type": "code",
"source": [
"actual_state = BugStatus.wont_fix\n",
"desired_state = BugStatus.fix_released\n",
"\n",
"print(f'Equality:'\n",
" f' {actual_state == desired_state}'\n",
" f' {actual_state == BugStatus.wont_fix}')\n",
"print(f'Identity:'\n",
" f' {actual_state is desired_state}'\n",
" f' {actual_state is BugStatus.wont_fix}')\n",
"print('Ordered by value:')\n",
"try:\n",
" print('\\n'.join(' ' + s.name for s in sorted(BugStatus)))\n",
"except TypeError as err:\n",
" print(f' Cannot sort: {err}')"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Equality: False True\n",
"Identity: False True\n",
"Ordered by value:\n",
" Cannot sort: '<' not supported between instances of 'BugStatus' and 'BugStatus'\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "QPgQQBuSnzQP",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Use IntEnum class for enumerations where the members need to behave more like numbers—for example, to support comparisons."
]
},
{
"metadata": {
"id": "ZhwEKvpJnU-2",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 156
},
"outputId": "f2a4c097-49cc-4154-b964-02f73db432a6"
},
"cell_type": "code",
"source": [
"class BugStatus(enum.IntEnum):\n",
"\n",
" new = 7\n",
" incomplete = 6\n",
" invalid = 5\n",
" wont_fix = 4\n",
" in_progress = 3\n",
" fix_committed = 2\n",
" fix_released = 1\n",
"\n",
"\n",
"print('Ordered by value:')\n",
"print('\\n'.join(' ' + s.name for s in sorted(BugStatus)))"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Ordered by value:\n",
" fix_released\n",
" fix_committed\n",
" in_progress\n",
" wont_fix\n",
" invalid\n",
" incomplete\n",
" new\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "xAlj69GmoDB0",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Unique Enumeration Values"
]
},
{
"metadata": {
"id": "1_EPuvK_oEYU",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 191
},
"outputId": "b85eb11c-adc0-4628-8808-bf9d513f09e5"
},
"cell_type": "code",
"source": [
"class BugStatus(enum.Enum):\n",
"\n",
" new = 7\n",
" incomplete = 6\n",
" invalid = 5\n",
" wont_fix = 4\n",
" in_progress = 3\n",
" fix_committed = 2\n",
" fix_released = 1\n",
"\n",
" by_design = 4\n",
" closed = 1\n",
"\n",
"\n",
"for status in BugStatus:\n",
" print('{:15} = {}'.format(status.name, status.value))\n",
"\n",
"print('\\nSame: by_design is wont_fix: ',\n",
" BugStatus.by_design is BugStatus.wont_fix)\n",
"print('Same: closed is fix_released: ',\n",
" BugStatus.closed is BugStatus.fix_released)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"new = 7\n",
"incomplete = 6\n",
"invalid = 5\n",
"wont_fix = 4\n",
"in_progress = 3\n",
"fix_committed = 2\n",
"fix_released = 1\n",
"\n",
"Same: by_design is wont_fix: True\n",
"Same: closed is fix_released: True\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "seT2UhMOoYEB",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"by_design is alias of wont_fix\n",
"cannonical name is the first"
]
},
{
"metadata": {
"id": "OmTTVJgForNb",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 358
},
"outputId": "67915f4b-a1db-4a60-baff-8ad939ef040d"
},
"cell_type": "code",
"source": [
"@enum.unique\n",
"class BugStatus(enum.Enum):\n",
"\n",
" new = 7\n",
" incomplete = 6\n",
" invalid = 5\n",
" wont_fix = 4\n",
" in_progress = 3\n",
" fix_committed = 2\n",
" fix_released = 1\n",
"\n",
" # This will trigger an error with unique applied.\n",
" by_design = 4\n",
" closed = 1"
],
"execution_count": 0,
"outputs": [
{
"output_type": "error",
"ename": "ValueError",
"evalue": "ignored",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-18-4f2a777430ac>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;34m@\u001b[0m\u001b[0menum\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0munique\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mclass\u001b[0m \u001b[0mBugStatus\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0menum\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mEnum\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mnew\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m7\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mincomplete\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m6\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/lib/python3.6/enum.py\u001b[0m in \u001b[0;36munique\u001b[0;34m(enumeration)\u001b[0m\n\u001b[1;32m 832\u001b[0m [\"%s -> %s\" % (alias, name) for (alias, name) in duplicates])\n\u001b[1;32m 833\u001b[0m raise ValueError('duplicate values found in %r: %s' %\n\u001b[0;32m--> 834\u001b[0;31m (enumeration, alias_details))\n\u001b[0m\u001b[1;32m 835\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0menumeration\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 836\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mValueError\u001b[0m: duplicate values found in <enum 'BugStatus'>: by_design -> wont_fix, closed -> fix_released"
]
}
]
},
{
"metadata": {
"id": "5FVfWt9q4OKL",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Creating Enumerations Programmatically"
]
},
{
"metadata": {
"id": "9mRqyZ7_4P76",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 191
},
"outputId": "83c89a3c-73bc-4a91-9957-344e649f61dc"
},
"cell_type": "code",
"source": [
"BugStatus = enum.Enum(\n",
" value='BugStatus',\n",
" names=('fix_released fix_committed in_progress '\n",
" 'wont_fix invalid incomplete new'),\n",
")\n",
"\n",
"print('Member: {}'.format(BugStatus.new))\n",
"\n",
"print('\\nAll members:')\n",
"for status in BugStatus:\n",
" print('{:15} = {}'.format(status.name, status.value))\n"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Member: BugStatus.new\n",
"\n",
"All members:\n",
"fix_released = 1\n",
"fix_committed = 2\n",
"in_progress = 3\n",
"wont_fix = 4\n",
"invalid = 5\n",
"incomplete = 6\n",
"new = 7\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "tCPA4Zhs4mCt",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 156
},
"outputId": "0359bfa1-ce31-483e-8a16-31f652422302"
},
"cell_type": "code",
"source": [
"BugStatus = enum.Enum(\n",
" value='BugStatus',\n",
" names=[\n",
" ('new', 7),\n",
" ('incomplete', 6),\n",
" ('invalid', 5),\n",
" ('wont_fix', 4),\n",
" ('in_progress', 3),\n",
" ('fix_committed', 2),\n",
" ('fix_released', 1),\n",
" ],\n",
")\n",
"\n",
"print('All members:')\n",
"for status in BugStatus:\n",
" print('{:15} = {}'.format(status.name, status.value))"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"All members:\n",
"new = 7\n",
"incomplete = 6\n",
"invalid = 5\n",
"wont_fix = 4\n",
"in_progress = 3\n",
"fix_committed = 2\n",
"fix_released = 1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "F5x92WfC4qe2",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Non-integer Member Values"
]
},
{
"metadata": {
"id": "x7LF0ubL7cEt",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Using tuples"
]
},
{
"metadata": {
"id": "ypcJ68oY4scx",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 86
},
"outputId": "7bb07d26-c197-4eb6-c1f3-91ccf5a6bb8f"
},
"cell_type": "code",
"source": [
"class BugStatus(enum.Enum):\n",
"\n",
" new = (7, ['incomplete',\n",
" 'invalid',\n",
" 'wont_fix',\n",
" 'in_progress'])\n",
" incomplete = (6, ['new', 'wont_fix'])\n",
" invalid = (5, ['new'])\n",
" wont_fix = (4, ['new'])\n",
" in_progress = (3, ['new', 'fix_committed'])\n",
" fix_committed = (2, ['in_progress', 'fix_released'])\n",
" fix_released = (1, ['new'])\n",
"\n",
" def __init__(self, num, transitions):\n",
" self.num = num\n",
" self.transitions = transitions\n",
"\n",
" def can_transition(self, next_state):\n",
" return next_state.name in self.transitions\n",
"\n",
"\n",
"print('Name:', BugStatus.in_progress)\n",
"print('Value:', BugStatus.in_progress.value)\n",
"print('Custom attribute:', BugStatus.in_progress.transitions)\n",
"print('Using attribute:',\n",
" BugStatus.in_progress.can_transition(BugStatus.new))\n"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Name: BugStatus.in_progress\n",
"Value: (3, ['new', 'fix_committed'])\n",
"Custom attribute: ['new', 'fix_committed']\n",
"Using attribute: True\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "j6XTy64z7Yi7",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Using Objects"
]
},
{
"metadata": {
"id": "kiHWA51b7Cfs",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 86
},
"outputId": "43be1598-5a30-4dae-b03f-ba5dac565d94"
},
"cell_type": "code",
"source": [
"\n",
"class BugStatus(enum.Enum):\n",
"\n",
" new = {\n",
" 'num': 7,\n",
" 'transitions': [\n",
" 'incomplete',\n",
" 'invalid',\n",
" 'wont_fix',\n",
" 'in_progress',\n",
" ],\n",
" }\n",
" incomplete = {\n",
" 'num': 6,\n",
" 'transitions': ['new', 'wont_fix'],\n",
" }\n",
" invalid = {\n",
" 'num': 5,\n",
" 'transitions': ['new'],\n",
" }\n",
" wont_fix = {\n",
" 'num': 4,\n",
" 'transitions': ['new'],\n",
" }\n",
" in_progress = {\n",
" 'num': 3,\n",
" 'transitions': ['new', 'fix_committed'],\n",
" }\n",
" fix_committed = {\n",
" 'num': 2,\n",
" 'transitions': ['in_progress', 'fix_released'],\n",
" }\n",
" fix_released = {\n",
" 'num': 1,\n",
" 'transitions': ['new'],\n",
" }\n",
"\n",
" def __init__(self, vals):\n",
" self.num = vals['num']\n",
" self.transitions = vals['transitions']\n",
"\n",
" def can_transition(self, new_state):\n",
" return new_state.name in self.transitions\n",
"\n",
"\n",
"print('Name:', BugStatus.in_progress)\n",
"print('Value:', BugStatus.in_progress.value)\n",
"print('Custom attribute:', BugStatus.in_progress.transitions)\n",
"print('Using attribute:',\n",
" BugStatus.in_progress.can_transition(BugStatus.new))"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Name: BugStatus.in_progress\n",
"Value: {'num': 3, 'transitions': ['new', 'fix_committed']}\n",
"Custom attribute: ['new', 'fix_committed']\n",
"Using attribute: True\n"
],
"name": "stdout"
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment