Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from django.utils.functional import cached_property"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class Foo(object):\n",
" @cached_property\n",
" def mutable(self):\n",
" return [1,2,3]\n",
" \n",
" @property\n",
" def immutable(self):\n",
" return [1,2,3]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"instance = Foo()\n",
"instance.mutable"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"instance.immutable"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\n",
"([1, 2, 3, 4], [1, 2, 3, 4])\n"
]
}
],
"source": [
"i_can_change_this = instance.mutable\n",
"print(i_can_change_this)\n",
"i_can_change_this.append(4)\n",
"print(i_can_change_this, instance.mutable)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What's happening above is that it's returning the value in the instance's `__dict__` and this can be changed because it's referenced. This is not what I want to happen."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\n",
"([1, 2, 3, 4], [1, 2, 3])\n"
]
}
],
"source": [
"never_changes = instance.immutable\n",
"print(never_changes)\n",
"never_changes.append(4)\n",
"print(never_changes, instance.immutable)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Above with the builtin property is exactly what I want to happen, but with a cached value."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment