{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Python for Developers](http://ricardoduarte.github.io/python-for-desvelopers/#content)\n", "===================================\n", "First edition\n", "-----------------------------------\n", "\n", "Chapter 9: Scope of names\n", "=============================\n", "_____________________________\n", "\n", "The scope of names in Python are maintained by *Namespaces*, which are dictionaries that list the names of the objects (references) and the objects themselves.\n", "\n", "Normally, the names are defined in two dictionaries, which can be accessed through the functions `locals()` and `globals()`. These dictionaries are updated dynamically at runtime.\n", "\n", "![Namespaces](files/bpyfd_diags7.png)\n", "\n", "Global variables can be overshadowed by local variables (because the local scope is consulted before the global scope). To avoid this, you must declare the variable as global in the local scope.\n", "\n", "example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def addlist(list):\n", " \"\"\"\n", " Add lists of lists, recursively\n", " the result is global\n", " \"\"\"\n", " global add\n", " \n", " for item in list:\n", " if type(item) is list: # If item type is list\n", " addlist(item)\n", " else:\n", " add += item\n", "\n", "add = 0\n", "addlist([[1, 2], [3, 4, 5], 6])\n", "\n", "print add # 21" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "21\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using global variables is not considered a good development practice, as they make the system harder to understand, so it is better to avoid their use. The same applies to overshadowing variables." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "" ], "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 } ], "metadata": {} } ] }