{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Constant attributes\n", "\n", "Sometimes it is necessary to forbid the change of an attribute value after the initial assignment. When `ubermagutil.typesystem` is used, `const=True` can be passed to any descriptor to forbid the change of an attribute." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import ubermagutil.typesystem as ts\n", "\n", "\n", "@ts.typesystem(name=ts.Typed(expected_type=str, const=True))\n", "class Person:\n", " def __init__(self, name):\n", " self.name = name\n", "\n", "\n", "p = Person(name=\"Nikola Tesla\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we attempt to change the value of `person.name` attribute, `AttributeError` exception is raised:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception raised.\n" ] } ], "source": [ "try:\n", " p.name = \"James Clerk Maxwell\"\n", "except AttributeError:\n", " print(\"Exception raised.\")" ] } ], "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 }