{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Imposing `typesystem` on a class\n", "\n", "## Properties\n", "\n", "It is often necessary to allow only certain values to be assigned to an attribute of a class. That can be achieved using properties. For instance, if we want to implement class `Square` and allow only positive values for the square edge length `a`, the implementation would be:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Square:\n", " def __init__(self, a):\n", " self.a = a\n", "\n", " @property\n", " def a(self):\n", " return self._a\n", "\n", " @a.setter\n", " def a(self, value):\n", " if value <= 0:\n", " raise ValueError(\"Edge length must be positive (a>0).\")\n", " else:\n", " self._a = value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, if we attempt to use an invalid value to set the edge length `a`, an exception will be raised. " ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception raised.\n" ] } ], "source": [ "s = Square(a=5) # Instantiate the class with correct attribute value\n", "\n", "try:\n", " s.a = -3\n", "except ValueError:\n", " print(\"Exception raised.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Imposing typesystem using `ubermagutil.typesystem`\n", "\n", "In large projects with a large number of classes, a lot of input checks have to be performed. This makes the code grow and it causes a lot of code repetition. An example of the `ubermagutil` usage for the previously shown `Square` class is" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import ubermagutil.typesystem as ts\n", "\n", "\n", "@ts.typesystem(a=ts.Scalar(positive=True))\n", "class Square:\n", " def __init__(self, a):\n", " self.a = a\n", "\n", "\n", "s = Square(a=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we try to set an invalid value:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception raised.\n" ] } ], "source": [ "try:\n", " s.a = -3\n", "except ValueError:\n", " print(\"Exception raised.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, if we want to define `MyClass` with the following attributes:\n", "\n", "- `a` - an unsigned integer\n", "- `b` - a three-dimensional vector\n", "- `c` - one of the allowed values from the set `{'left', 'right'}`\n", "- `d` - variable of type `list`\n", "- `name` - a valid Python variable name" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "@ts.typesystem(\n", " a=ts.Scalar(expected_type=int, unsigned=True),\n", " b=ts.Vector(size=3),\n", " c=ts.Subset(sample_set={\"left\", \"right\"}, unpack=False),\n", " d=ts.Typed(expected_type=list),\n", " name=ts.Name(),\n", ")\n", "class MyClass:\n", " def __init__(self, a, b, c, d, name):\n", " self.a = a\n", " self.b = b\n", " self.c = c\n", " self.d = d\n", " self.name = name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can attempt passing invalid values expect them to be rejected by the imposed typesystem." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mc.a: Exception raised.\n", "mc.b: Exception raised.\n", "mc.c: Exception raised.\n", "mc.d: Exception raised.\n", "mc.name: Exception raised.\n" ] } ], "source": [ "mc = MyClass(\n", " a=5, b=(1, 2, 3), c=\"right\", d=[1, 2, \"abc\"], name=\"myclass\"\n", ") # valid initialisation\n", "\n", "# Set mc.a with float\n", "try:\n", " mc.a = 3.14\n", "except TypeError:\n", " print(\"mc.a: Exception raised.\")\n", "\n", "# Set mc.b with a two-dimensional vector\n", "try:\n", " mc.b = (10, 11)\n", "except ValueError:\n", " print(\"mc.b: Exception raised.\")\n", "\n", "# Set mc.c with an invalid value of the string\n", "try:\n", " mc.c = \"down\"\n", "except ValueError:\n", " print(\"mc.c: Exception raised.\")\n", "\n", "# Set mc.c with an invalid value of tuple\n", "try:\n", " mc.d = (1, 2, 3, 4)\n", "except TypeError:\n", " print(\"mc.d: Exception raised.\")\n", "\n", "# Set mc.name with an invalid Python variable name\n", "try:\n", " mc.name = \"Nikola Tesla\" # contains spaces\n", "except ValueError:\n", " print(\"mc.name: Exception raised.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Deleting an attribute\n", "\n", "Deleting an attribute is never allowed and an `AttributeError` is raised." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception raised.\n" ] } ], "source": [ "# Attempt to delete an attribute.\n", "try:\n", " del mc.a\n", "except AttributeError:\n", " print(\"Exception raised.\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }