{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Defining `otherwise` type\n", "\n", "In certain cases, it is required to be able to allow the \"else case\" when defining a particular attribute of a class. For instance, let us say our attribute should be a vector of size 3, but if it is not, a string should be allowed.\n", "\n", "A class with imposed typesystem would be:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import ubermagutil.typesystem as ts\n", "\n", "\n", "@ts.typesystem(a=ts.Vector(size=3, otherwise=str))\n", "class DecoratedClass:\n", " def __init__(self, a):\n", " self.a = a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can instantiate the class and pass the vector of length 3." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(0, 1, 2)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dc = DecoratedClass(a=(0, 1, 2))\n", "dc.a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because we also defined `otheriwse` parameter, we can also assign a string." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "dc.a = \"Mihajlo Pupin\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However if we pass an integer or a size 2 tuple, an exception is raised:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception raised.\n" ] } ], "source": [ "try:\n", " dc.a = 23\n", "except TypeError:\n", " print(\"Exception raised.\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception raised.\n" ] } ], "source": [ "try:\n", " dc.a = (1, 2)\n", "except ValueError:\n", " print(\"Exception raised.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Attempts to assign a new value to the attribute, did not affect its value." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Mihajlo Pupin'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dc.a" ] } ], "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.8.3" } }, "nbformat": 4, "nbformat_minor": 4 }