{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from inspect import stack" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "def fstring(s, **kwargs):\n", " caller = stack()[1][0]\n", " ns = caller.f_globals.copy()\n", " ns.update(caller.f_locals)\n", " caller.f_locals['q'] = 6\n", " print(caller.f_locals)\n", " ns.update(kwargs)\n", " return s.format(**ns)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Animal:\n", " name = 'bob'" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": true }, "outputs": [], "source": [ "y = 7\n", "\n", "def caller():\n", " x = 5\n", " bob = Animal\n", " s = fstring('His name is {bob.name}, {x:06x}, {y}, {z}', z=9)\n", " print(s)\n", " \n", " # The following does not work in Python 3.0 because the\n", " # list comprehension runs with its own local namespace.\n", " #t = [fstring('{i} {x} {y} {z}', z=11) for i in range(4)]\n", " #print(t)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'bob': , 'x': 5, 'q': 6}\n", "His name is bob, 000005, 7, 9\n" ] } ], "source": [ "caller()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'i': 0, '.0': }\n", "{'i': 1, '.0': }\n", "{'i': 2, '.0': }\n", "{'i': 3, '.0': }\n" ] }, { "data": { "text/plain": [ "['0 4 7 11', '1 4 7 11', '2 4 7 11', '3 4 7 11']" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[fstring('{i} {x} {y} {z}', x=4, z=11) for i in range(4)]" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'x' in globals()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "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.6.1" } }, "nbformat": 4, "nbformat_minor": 2 }