{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 18. \\_\\_missing\\_\\_ 을 사용해 키에 따라 다른 디폴트 값을 생성하는 방법을 알아두라" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "setdefault와 defaultdict 모두 사용하기가 적당하지 않은 경우가 있다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "pictures = {}\n", "path = 'profile_1234.png'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "if (handle := pictures.get(path)) is None:\n", " try:\n", " handle = open(path, 'a+b')\n", " except OSError:\n", " print(f'경로를 열 수 없습니다: {path}')\n", " raise\n", " else:\n", " pictures[path] = handle" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "handle.seek(0)\n", "image_data = handle.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "setdefault를 활용하는 방법도 있다" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "try:\n", " handle = pictures.setdefault(path, open(path, 'a+b'))\n", "except OSError:\n", " print(f'경로를 열 수 없습니다: {path}')\n", " raise\n", "else:\n", " handle.seek(0)\n", " image_data = handle.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이 코드는 문제가 많다.\n", "\n", "파일 핸들을 만드는 내장 함수인 open이 딕셔너리에 경로가 있는지 여부와 관계없이 항상 호출된다.\n", "\n", "내부 상태를 관리하려 한다면 프로필 사진의 상태를 관리하기 위해 defaultdict을 쓸 수 있다고 가정할수도 있다." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "from collections import defaultdict" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def open_picture(profile_path):\n", " try:\n", " return open(profile_path, 'a+b')\n", " except OSError:\n", " print(f'경로를 열 수 없습니다: {profile_path}')\n", " raise" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "open_picture() missing 1 required positional argument: 'profile_path'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m<ipython-input-7-951e7d5de294>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mpictures\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdefaultdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mopen_picture\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mhandle\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpictures\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mpath\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[0mhandle\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mseek\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mimage_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mhandle\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: open_picture() missing 1 required positional argument: 'profile_path'" ] } ], "source": [ "pictures = defaultdict(open_picture)\n", "handle = pictures[path]\n", "handle.seek(0)\n", "image_data = handle.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "문제는 defaultdict 생성자에 전달한 함수는 인자를 받을수 없다는데 있다.\n", "\n", "이는 defaultdict이 호출하는 도우미 함수가 처리 중인 키를 알 수 없다는 뜻이다.\n", "\n", "이로 인해 파일 경로를 사용해 open을 호출할 방법이 없다.\n", "\n", "이런 상황에서는 setdefault와 defaultdict 모두 필요한 기능을 제공하지 못한다." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "class Pictures(dict):\n", " def __missing__(self, key):\n", " value = open_picture(key)\n", " self[key] = value\n", " return value" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "pictures = Pictures()\n", "handle = pictures[path]\n", "handle.seek(0)\n", "image_data = handle.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "dict 타입의 하위 클래스를 만들고 \\_\\_missing\\_\\_ 특별 메서드를 구현하면 키가 없는 경우를 처리하는 로직을 커스텀화 할 수 있다." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'profile_1234.png': <_io.BufferedRandom name='profile_1234.png'>}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pictures" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 기억해야 할 내용\n", "- 디폴트 값을 만드는 계산 비용이 높거나 만드는 과정에서 예외가 발생할 수 있는 상황에서는 dict의 setdefault 메서드를 사용하지마라\n", "- defaultdict에 전달되는 함수는 인자를 받지 않는다. 따라서 접근에 사용한 키 값에 맞는 디폴트 값을 생성하는 것은 불가능하다.\n", "- 디폴트 키를 만들 때 어떤 키를 사용했는지 반드시 알아야 하는 상황이라면 직접 dict의 하위클래스와 \\_\\_missing\\_\\_ 메서드를 정의하면 된다." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "first argument must be callable or None", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m<ipython-input-12-b9ece99d44ca>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdefaultdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"aa.txt\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'a'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: first argument must be callable or None" ] } ], "source": [ "defaultdict(open(\"aa.txt\", '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.2" } }, "nbformat": 4, "nbformat_minor": 4 }