├── .gitignore ├── .travis.yml ├── CHANGES.TXT ├── LICENSE.TXT ├── MANIFEST.in ├── README.rst ├── README.txt ├── USAGE.TXT ├── docs ├── Makefile ├── build │ └── latex │ │ └── nested_dict.pdf ├── make.bat └── source │ ├── conf.py │ ├── index.rst │ └── nested_dict.rst ├── ez_setup.py ├── nested_dict ├── __init__.py └── implementation.py ├── requirements.txt ├── setup.py ├── tests ├── __init__.py └── test_nested_dict.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg-info 3 | dist 4 | docs/build 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.6" 4 | - "2.7" 5 | - "3.3" 6 | - "3.4" 7 | - "3.5" 8 | - "pypy" 9 | - "pypy3" 10 | 11 | install: 12 | - pip install -r requirements.txt 13 | - pip install . 14 | 15 | script: 16 | - flake8 17 | - nosetests --with-coverage --cover-package nested_dict 18 | --cover-inclusive --cover-min-percentage 85 19 | - if [[ $TRAVIS_PYTHON_VERSION != pypy3 ]]; then make -C docs html; fi 20 | -------------------------------------------------------------------------------- /CHANGES.TXT: -------------------------------------------------------------------------------- 1 | = v. 1.0.6 = 2 | _17/August/2009_ 3 | 4 | Added to_dict() and __str__() 5 | 6 | = v. 1.0.0 beta = 7 | _08/August/2009_ 8 | 9 | Initial Release in Oxford 10 | 11 | -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy 2 | of this software and associated documentation files (the "Software"), to deal 3 | in the Software without restriction, including without limitation the rights 4 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | copies of the Software, and to permit persons to whom the Software is 6 | furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in 9 | all copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 17 | THE SOFTWARE. 18 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.py *.rst *.TXT *.yml *.txt 2 | recursive-include docs tests 3 | 4 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. note :: 2 | 3 | * Source code at https://github.com/bunbun/nested-dict 4 | * Documentation at http://nested-dict.readthedocs.org 5 | 6 | ############################################################################## 7 | ``nested_dict`` 8 | ############################################################################## 9 | ``nested_dict`` extends ``defaultdict`` to support python ``dict`` with multiple levels of nested-ness: 10 | 11 | ***************************************************************** 12 | Drop in replacement for ``dict`` 13 | ***************************************************************** 14 | 15 | 16 | .. <>> from nested_dict import nested_dict 21 | >>> nd= nested_dict() 22 | >>> nd["one"] = "1" 23 | >>> nd[1]["two"] = "1 / 2" 24 | >>> nd["uno"][2]["three"] = "1 / 2 / 3" 25 | >>> 26 | ... for keys_as_tuple, value in nd.items_flat(): 27 | ... print ("%-20s == %r" % (keys_as_tuple, value)) 28 | ... 29 | ('one',) == '1' 30 | (1, 'two') == '1 / 2' 31 | ('uno', 2, 'three') == '1 / 2 / 3' 32 | 33 | .. 34 | Python 35 | 36 | Each nested level is created magically when accessed, a process known as "auto-vivification" in perl. 37 | 38 | 39 | ****************************************************************************** 40 | Specifying the contained type 41 | ****************************************************************************** 42 | 43 | If you want the nested dictionary to hold 44 | * a collection (like the `set `__ in the first example) or 45 | * a scalar with useful default values such as ``int`` or ``str``. 46 | 47 | ============================== 48 | *dict* of ``list``\ s 49 | ============================== 50 | .. <`__\ s before iteration. 126 | 127 | You do not need to know beforehand how many levels of nesting you have: 128 | 129 | .. <`__\ ing for example). 163 | 164 | We can convert to and from a vanilla python ``dict`` using 165 | * ``nested_dict.to_dict()`` 166 | * ``nested_dict constructor`` 167 | 168 | .. <>> from nested_dict import nested_dict 173 | >>> nd= nested_dict() 174 | >>> nd["one"] = 1 175 | >>> nd[1]["two"] = "1 / 2" 176 | 177 | # 178 | # convert nested_dict -> dict and pickle 179 | # 180 | >>> nd.to_dict() 181 | {1: {'two': '1 / 2'}, 'one': 1} 182 | >>> import pickle 183 | >>> binary_representation = pickle.dumps(nd.to_dict()) 184 | 185 | # 186 | # convert dict -> nested_dict 187 | # 188 | >>> normal_dict = pickle.loads(binary_representation) 189 | >>> new_nd = nested_dict(normal_dict) 190 | >>> nd == new_nd 191 | True 192 | 193 | .. 194 | Python 195 | 196 | 197 | ############################################################################## 198 | ``defaultdict`` 199 | ############################################################################## 200 | ``nested_dict`` extends `collections.defaultdict `__ 201 | 202 | You can get arbitrarily-nested "auto-vivifying" dictionaries using `defaultdict `__. 203 | 204 | .. </dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nested_dict.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nested_dict.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/nested_dict" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nested_dict" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/build/latex/nested_dict.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bunbun/nested-dict/54a7656ea113ba5e1fc11c337121b278bf76aacd/docs/build/latex/nested_dict.pdf -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 2> nul 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\nested_dict.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\nested_dict.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # nested_dict documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Jun 5 18:33:34 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | import shlex 18 | import re 19 | 20 | sys.path.insert(0, os.path.abspath(os.path.join("..", ".."))) 21 | import nested_dict 22 | 23 | # If extensions (or modules to document with autodoc) are in another directory, 24 | # add these directories to sys.path here. If the directory is relative to the 25 | # documentation root, use os.path.abspath to make it absolute, like shown here. 26 | #sys.path.insert(0, os.path.abspath('.')) 27 | 28 | # -- General configuration ------------------------------------------------ 29 | 30 | # If your documentation needs a minimal Sphinx version, state it here. 31 | #needs_sphinx = '1.0' 32 | 33 | # Add any Sphinx extension module names here, as strings. They can be 34 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 35 | # ones. 36 | extensions = [ 37 | 'sphinx.ext.autodoc', 38 | 'sphinx.ext.todo', 39 | 'sphinx.ext.viewcode', 40 | ] 41 | 42 | # Add any paths that contain templates here, relative to this directory. 43 | templates_path = ['_templates'] 44 | 45 | # The suffix(es) of source filenames. 46 | # You can specify multiple suffix as a list of string: 47 | # source_suffix = ['.rst', '.md'] 48 | source_suffix = '.rst' 49 | 50 | # The encoding of source files. 51 | #source_encoding = 'utf-8-sig' 52 | 53 | # The master toctree document. 54 | master_doc = 'index' 55 | 56 | # General information about the project. 57 | project = u'nested_dict' 58 | copyright = u'2009, 2015, Leo Goodstadt' 59 | author = u'Leo Goodstadt' 60 | 61 | 62 | # Following the recommendations of PEP 396 we parse the version number 63 | # out of the module. 64 | def parse_version(module_file): 65 | """ 66 | Parses the version string from the specified file. 67 | This implementation is ugly, but there doesn't seem to be a good way 68 | to do this in general at the moment. 69 | """ 70 | f = open(module_file) 71 | s = f.read() 72 | f.close() 73 | match = re.findall("__version__ = '([^']+)'", s) 74 | return match[0] 75 | 76 | nested_dict_version = parse_version(os.path.join("..", "..", "nested_dict", "__init__.py")) 77 | 78 | 79 | 80 | # The version info for the project you're documenting, acts as replacement for 81 | # |version| and |release|, also used in various other places throughout the 82 | # built documents. 83 | # 84 | # The short X.Y version. 85 | version = nested_dict_version 86 | # The full version, including alpha/beta/rc tags. 87 | release = nested_dict_version 88 | 89 | # The language for content autogenerated by Sphinx. Refer to documentation 90 | # for a list of supported languages. 91 | # 92 | # This is also used if you do content translation via gettext catalogs. 93 | # Usually you set "language" from the command line for these cases. 94 | language = None 95 | 96 | # There are two options for replacing |today|: either, you set today to some 97 | # non-false value, then it is used: 98 | #today = '' 99 | # Else, today_fmt is used as the format for a strftime call. 100 | #today_fmt = '%B %d, %Y' 101 | 102 | # List of patterns, relative to source directory, that match files and 103 | # directories to ignore when looking for source files. 104 | exclude_patterns = ["README.rst"] 105 | 106 | # The reST default role (used for this markup: `text`) to use for all 107 | # documents. 108 | #default_role = None 109 | 110 | # If true, '()' will be appended to :func: etc. cross-reference text. 111 | #add_function_parentheses = True 112 | 113 | # If true, the current module name will be prepended to all description 114 | # unit titles (such as .. function::). 115 | #add_module_names = True 116 | 117 | # If true, sectionauthor and moduleauthor directives will be shown in the 118 | # output. They are ignored by default. 119 | #show_authors = False 120 | 121 | # The name of the Pygments (syntax highlighting) style to use. 122 | pygments_style = 'sphinx' 123 | 124 | # A list of ignored prefixes for module index sorting. 125 | #modindex_common_prefix = [] 126 | 127 | # If true, keep warnings as "system message" paragraphs in the built documents. 128 | #keep_warnings = False 129 | 130 | # If true, `todo` and `todoList` produce output, else they produce nothing. 131 | todo_include_todos = True 132 | 133 | 134 | # -- Options for HTML output ---------------------------------------------- 135 | 136 | # The theme to use for HTML and HTML Help pages. See the documentation for 137 | # a list of builtin themes. 138 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 139 | if not on_rtd: 140 | # a list of builtin themes. 141 | import sphinx_rtd_theme 142 | html_theme = "sphinx_rtd_theme" 143 | #html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 144 | #html_theme = 'alabaster' 145 | 146 | # Theme options are theme-specific and customize the look and feel of a theme 147 | # further. For a list of options available for each theme, see the 148 | # documentation. 149 | #html_theme_options = {} 150 | 151 | # Add any paths that contain custom themes here, relative to this directory. 152 | #html_theme_path = [] 153 | 154 | # The name for this set of Sphinx documents. If None, it defaults to 155 | # " v documentation". 156 | #html_title = None 157 | 158 | # A shorter title for the navigation bar. Default is the same as html_title. 159 | #html_short_title = None 160 | 161 | # The name of an image file (relative to this directory) to place at the top 162 | # of the sidebar. 163 | #html_logo = None 164 | 165 | # The name of an image file (within the static path) to use as favicon of the 166 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 167 | # pixels large. 168 | #html_favicon = None 169 | 170 | # Add any paths that contain custom static files (such as style sheets) here, 171 | # relative to this directory. They are copied after the builtin static files, 172 | # so a file named "default.css" will overwrite the builtin "default.css". 173 | html_static_path = ['_static'] 174 | 175 | # Add any extra paths that contain custom files (such as robots.txt or 176 | # .htaccess) here, relative to this directory. These files are copied 177 | # directly to the root of the documentation. 178 | #html_extra_path = [] 179 | 180 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 181 | # using the given strftime format. 182 | #html_last_updated_fmt = '%b %d, %Y' 183 | 184 | # If true, SmartyPants will be used to convert quotes and dashes to 185 | # typographically correct entities. 186 | #html_use_smartypants = True 187 | 188 | # Custom sidebar templates, maps document names to template names. 189 | #html_sidebars = {} 190 | 191 | # Additional templates that should be rendered to pages, maps page names to 192 | # template names. 193 | #html_additional_pages = {} 194 | 195 | # If false, no module index is generated. 196 | #html_domain_indices = True 197 | 198 | # If false, no index is generated. 199 | #html_use_index = True 200 | 201 | # If true, the index is split into individual pages for each letter. 202 | #html_split_index = False 203 | 204 | # If true, links to the reST sources are added to the pages. 205 | #html_show_sourcelink = True 206 | 207 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 208 | #html_show_sphinx = True 209 | 210 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 211 | #html_show_copyright = True 212 | 213 | # If true, an OpenSearch description file will be output, and all pages will 214 | # contain a tag referring to it. The value of this option must be the 215 | # base URL from which the finished HTML is served. 216 | #html_use_opensearch = '' 217 | 218 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 219 | #html_file_suffix = None 220 | 221 | # Language to be used for generating the HTML full-text search index. 222 | # Sphinx supports the following languages: 223 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 224 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 225 | #html_search_language = 'en' 226 | 227 | # A dictionary with options for the search language support, empty by default. 228 | # Now only 'ja' uses this config value 229 | #html_search_options = {'type': 'default'} 230 | 231 | # The name of a javascript file (relative to the configuration directory) that 232 | # implements a search results scorer. If empty, the default will be used. 233 | #html_search_scorer = 'scorer.js' 234 | 235 | # Output file base name for HTML help builder. 236 | htmlhelp_basename = 'nested_dictdoc' 237 | 238 | # -- Options for LaTeX output --------------------------------------------- 239 | 240 | latex_elements = { 241 | # The paper size ('letterpaper' or 'a4paper'). 242 | #'papersize': 'letterpaper', 243 | 244 | # The font size ('10pt', '11pt' or '12pt'). 245 | #'pointsize': '10pt', 246 | 247 | # Additional stuff for the LaTeX preamble. 248 | #'preamble': '', 249 | 250 | # Latex figure (float) alignment 251 | #'figure_align': 'htbp', 252 | } 253 | 254 | # Grouping the document tree into LaTeX files. List of tuples 255 | # (source start file, target name, title, 256 | # author, documentclass [howto, manual, or own class]). 257 | latex_documents = [ 258 | (master_doc, 'nested_dict.tex', u'nested\\_dict Documentation', 259 | u'Leo Goodstadt', 'manual'), 260 | ] 261 | 262 | # The name of an image file (relative to this directory) to place at the top of 263 | # the title page. 264 | #latex_logo = None 265 | 266 | # For "manual" documents, if this is true, then toplevel headings are parts, 267 | # not chapters. 268 | #latex_use_parts = False 269 | 270 | # If true, show page references after internal links. 271 | #latex_show_pagerefs = False 272 | 273 | # If true, show URL addresses after external links. 274 | #latex_show_urls = False 275 | 276 | # Documents to append as an appendix to all manuals. 277 | #latex_appendices = [] 278 | 279 | # If false, no module index is generated. 280 | #latex_domain_indices = True 281 | 282 | 283 | # -- Options for manual page output --------------------------------------- 284 | 285 | # One entry per manual page. List of tuples 286 | # (source start file, name, description, authors, manual section). 287 | man_pages = [ 288 | (master_doc, 'nested_dict', u'nested_dict Documentation', 289 | [author], 1) 290 | ] 291 | 292 | # If true, show URL addresses after external links. 293 | #man_show_urls = False 294 | 295 | 296 | # -- Options for Texinfo output ------------------------------------------- 297 | 298 | # Grouping the document tree into Texinfo files. List of tuples 299 | # (source start file, target name, title, author, 300 | # dir menu entry, description, category) 301 | texinfo_documents = [ 302 | (master_doc, 'nested_dict', u'nested_dict Documentation', 303 | author, 'nested_dict', 'One line description of project.', 304 | 'Miscellaneous'), 305 | ] 306 | 307 | # Documents to append as an appendix to all manuals. 308 | #texinfo_appendices = [] 309 | 310 | # If false, no module index is generated. 311 | #texinfo_domain_indices = True 312 | 313 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 314 | #texinfo_show_urls = 'footnote' 315 | 316 | # If true, do not generate a @detailmenu in the "Top" node's menu. 317 | #texinfo_no_detailmenu = False 318 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. note :: 2 | 3 | * Source code at https://github.com/bunbun/nested-dict 4 | * Documentation at http://nested-dict.readthedocs.org 5 | 6 | ############################################################################## 7 | ``nested_dict`` 8 | ############################################################################## 9 | 10 | ``nested_dict`` is a drop-in replacement extending python `dict `__ and 11 | `defaultdict `__ 12 | with multiple levels of nesting. 13 | 14 | You can created a deeply nested data structure without laboriously creating all the sub-levels along the way: 15 | 16 | .. <>> nd= nested_dict() 21 | >>> # magic 22 | >>> nd["one"][2]["three"] = 4 23 | 24 | .. 25 | Python 26 | 27 | 28 | Each nested level is created magically when accessed, a process known as "auto-vivification" in perl. 29 | 30 | 31 | ****************************************************************************** 32 | Specifying the contained type 33 | ****************************************************************************** 34 | 35 | You can specify that a particular level of nesting holds a specified **value type**, for example: 36 | * a collection (like a `set `__ or `list `__) or 37 | * a scalar with useful default values such as ``int`` or ``str``. 38 | 39 | 40 | **Examples**: 41 | 42 | ============================== 43 | *dict* of ``list``\ s 44 | ============================== 45 | .. <`__\ s before iteration. 121 | 122 | You do not need to know beforehand how many levels of nesting you have: 123 | 124 | .. <` 148 | * :ref:`keys_flat() ` 149 | * :ref:`values_flat() ` 150 | 151 | (:ref:`iteritems_flat() `, :ref:`iterkeys_flat() `, and :ref:`itervalues_flat() ` are python 2.7-style synonyms. ) 152 | 153 | ############################################################################## 154 | Converting to / from ``dict`` 155 | ############################################################################## 156 | 157 | The magic of ``nested_dict`` sometimes gets in the way (of `pickle `__\ ing for example). 158 | 159 | We can convert to and from a vanilla python ``dict`` using 160 | * :ref:`nested_dict.to_dict() ` 161 | * :ref:`the nested_dict constructor ` 162 | 163 | .. <>> from nested_dict import nested_dict 168 | >>> nd= nested_dict() 169 | >>> nd["one"] = 1 170 | >>> nd[1]["two"] = "1 / 2" 171 | 172 | # 173 | # convert nested_dict -> dict and pickle 174 | # 175 | >>> nd.to_dict() 176 | {1: {'two': '1 / 2'}, 'one': 1} 177 | >>> import pickle 178 | >>> binary_representation = pickle.dumps(nd.to_dict()) 179 | 180 | # 181 | # convert dict -> nested_dict 182 | # 183 | >>> normal_dict = pickle.loads(binary_representation) 184 | >>> new_nd = nested_dict(normal_dict) 185 | >>> nd == new_nd 186 | True 187 | 188 | .. 189 | Python 190 | 191 | ############################################################################## 192 | Updating with another dictionary 193 | ############################################################################## 194 | 195 | You can use the ``nested_dict.update(other)`` method to merge in the contents of another dictionary. 196 | 197 | If the ``nested_dict`` has a fixed nesting and a **value type**, then key / value pairs will be overridden 198 | from the other dict like in Python's standard library ``dict``. Otherwise they will be preserved as far as possible. 199 | 200 | For example, given a three-level nested ``nested_dict`` of ``int``: 201 | 202 | .. <>> d1 = nested_dict.nested_dict(3, int) 207 | >>> d1[1][2][3] = 4 208 | >>> d1[1][2][4] = 5 209 | 210 | >>> # integers have a default value of zero 211 | >>> default_value = d1[1][2][5] 212 | >>> print (default_value) 213 | 0 214 | >>> print (d1.to_dict()) 215 | {1: {2: {3: 4, 4: 5, 5:0}}} 216 | 217 | .. 218 | Python 219 | 220 | 221 | We can update this with any dictionary, not necessarily a three level ``nested_dict`` of ``int``. 222 | 223 | .. <>> # some other nested_dict 228 | >>> d2 = nested_dict.nested_dict() 229 | >>> d2[2][3][4][5] = 6 230 | >>> d1.update(d2) 231 | >>> print (d1.to_dict()) 232 | {1: {2: {3: 4, 4: 5, 5: 0}}, 2: {3: {4: {5: 6}}}} 233 | 234 | .. 235 | Python 236 | 237 | 238 | However, the rest of the dictionary maintains has the same default **value type** at the specified level of nesting 239 | 240 | .. <>> print (d1[2][3][4][5]) 245 | 6 246 | >>> # d1[2][3][???] == int() even though d1[2][3][4][5] = 6 247 | >>> print (d1[2][3][5]) 248 | 0 249 | .. 250 | Python 251 | 252 | ############################################################################## 253 | ``defaultdict`` 254 | ############################################################################## 255 | ``nested_dict`` extends `collections.defaultdict `__ 256 | 257 | You can get arbitrarily-nested "auto-vivifying" dictionaries using `defaultdict `__. 258 | 259 | .. <="+version) 148 | return 149 | except pkg_resources.VersionConflict: 150 | e = sys.exc_info()[1] 151 | if was_imported: 152 | sys.stderr.write( 153 | "The required version of distribute (>=%s) is not available,\n" 154 | "and can't be installed while this script is running. Please\n" 155 | "install a more recent version first, using\n" 156 | "'easy_install -U distribute'." 157 | "\n\n(Currently using %r)\n" % (version, e.args[0])) 158 | sys.exit(2) 159 | else: 160 | del pkg_resources, sys.modules['pkg_resources'] # reload ok 161 | return _do_download(version, download_base, to_dir, 162 | download_delay) 163 | except pkg_resources.DistributionNotFound: 164 | return _do_download(version, download_base, to_dir, 165 | download_delay) 166 | finally: 167 | if not no_fake: 168 | _create_fake_setuptools_pkg_info(to_dir) 169 | 170 | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, 171 | to_dir=os.curdir, delay=15): 172 | """Download distribute from a specified location and return its filename 173 | 174 | `version` should be a valid distribute version number that is available 175 | as an egg for download under the `download_base` URL (which should end 176 | with a '/'). `to_dir` is the directory where the egg will be downloaded. 177 | `delay` is the number of seconds to pause before an actual download 178 | attempt. 179 | """ 180 | # making sure we use the absolute path 181 | to_dir = os.path.abspath(to_dir) 182 | try: 183 | from urllib.request import urlopen 184 | except ImportError: 185 | from urllib2 import urlopen 186 | tgz_name = "distribute-%s.tar.gz" % version 187 | url = download_base + tgz_name 188 | saveto = os.path.join(to_dir, tgz_name) 189 | src = dst = None 190 | if not os.path.exists(saveto): # Avoid repeated downloads 191 | try: 192 | log.warn("Downloading %s", url) 193 | src = urlopen(url) 194 | # Read/write all in one block, so we don't create a corrupt file 195 | # if the download is interrupted. 196 | data = src.read() 197 | dst = open(saveto, "wb") 198 | dst.write(data) 199 | finally: 200 | if src: 201 | src.close() 202 | if dst: 203 | dst.close() 204 | return os.path.realpath(saveto) 205 | 206 | def _no_sandbox(function): 207 | def __no_sandbox(*args, **kw): 208 | try: 209 | from setuptools.sandbox import DirectorySandbox 210 | if not hasattr(DirectorySandbox, '_old'): 211 | def violation(*args): 212 | pass 213 | DirectorySandbox._old = DirectorySandbox._violation 214 | DirectorySandbox._violation = violation 215 | patched = True 216 | else: 217 | patched = False 218 | except ImportError: 219 | patched = False 220 | 221 | try: 222 | return function(*args, **kw) 223 | finally: 224 | if patched: 225 | DirectorySandbox._violation = DirectorySandbox._old 226 | del DirectorySandbox._old 227 | 228 | return __no_sandbox 229 | 230 | def _patch_file(path, content): 231 | """Will backup the file then patch it""" 232 | existing_content = open(path).read() 233 | if existing_content == content: 234 | # already patched 235 | log.warn('Already patched.') 236 | return False 237 | log.warn('Patching...') 238 | _rename_path(path) 239 | f = open(path, 'w') 240 | try: 241 | f.write(content) 242 | finally: 243 | f.close() 244 | return True 245 | 246 | _patch_file = _no_sandbox(_patch_file) 247 | 248 | def _same_content(path, content): 249 | return open(path).read() == content 250 | 251 | def _rename_path(path): 252 | new_name = path + '.OLD.%s' % time.time() 253 | log.warn('Renaming %s into %s', path, new_name) 254 | os.rename(path, new_name) 255 | return new_name 256 | 257 | def _remove_flat_installation(placeholder): 258 | if not os.path.isdir(placeholder): 259 | log.warn('Unkown installation at %s', placeholder) 260 | return False 261 | found = False 262 | for file in os.listdir(placeholder): 263 | if fnmatch.fnmatch(file, 'setuptools*.egg-info'): 264 | found = True 265 | break 266 | if not found: 267 | log.warn('Could not locate setuptools*.egg-info') 268 | return 269 | 270 | log.warn('Removing elements out of the way...') 271 | pkg_info = os.path.join(placeholder, file) 272 | if os.path.isdir(pkg_info): 273 | patched = _patch_egg_dir(pkg_info) 274 | else: 275 | patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) 276 | 277 | if not patched: 278 | log.warn('%s already patched.', pkg_info) 279 | return False 280 | # now let's move the files out of the way 281 | for element in ('setuptools', 'pkg_resources.py', 'site.py'): 282 | element = os.path.join(placeholder, element) 283 | if os.path.exists(element): 284 | _rename_path(element) 285 | else: 286 | log.warn('Could not find the %s element of the ' 287 | 'Setuptools distribution', element) 288 | return True 289 | 290 | _remove_flat_installation = _no_sandbox(_remove_flat_installation) 291 | 292 | def _after_install(dist): 293 | log.warn('After install bootstrap.') 294 | placeholder = dist.get_command_obj('install').install_purelib 295 | _create_fake_setuptools_pkg_info(placeholder) 296 | 297 | def _create_fake_setuptools_pkg_info(placeholder): 298 | if not placeholder or not os.path.exists(placeholder): 299 | log.warn('Could not find the install location') 300 | return 301 | pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) 302 | setuptools_file = 'setuptools-%s-py%s.egg-info' % \ 303 | (SETUPTOOLS_FAKED_VERSION, pyver) 304 | pkg_info = os.path.join(placeholder, setuptools_file) 305 | if os.path.exists(pkg_info): 306 | log.warn('%s already exists', pkg_info) 307 | return 308 | 309 | log.warn('Creating %s', pkg_info) 310 | f = open(pkg_info, 'w') 311 | try: 312 | f.write(SETUPTOOLS_PKG_INFO) 313 | finally: 314 | f.close() 315 | 316 | pth_file = os.path.join(placeholder, 'setuptools.pth') 317 | log.warn('Creating %s', pth_file) 318 | f = open(pth_file, 'w') 319 | try: 320 | f.write(os.path.join(os.curdir, setuptools_file)) 321 | finally: 322 | f.close() 323 | 324 | _create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info) 325 | 326 | def _patch_egg_dir(path): 327 | # let's check if it's already patched 328 | pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') 329 | if os.path.exists(pkg_info): 330 | if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): 331 | log.warn('%s already patched.', pkg_info) 332 | return False 333 | _rename_path(path) 334 | os.mkdir(path) 335 | os.mkdir(os.path.join(path, 'EGG-INFO')) 336 | pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') 337 | f = open(pkg_info, 'w') 338 | try: 339 | f.write(SETUPTOOLS_PKG_INFO) 340 | finally: 341 | f.close() 342 | return True 343 | 344 | _patch_egg_dir = _no_sandbox(_patch_egg_dir) 345 | 346 | def _before_install(): 347 | log.warn('Before install bootstrap.') 348 | _fake_setuptools() 349 | 350 | 351 | def _under_prefix(location): 352 | if 'install' not in sys.argv: 353 | return True 354 | args = sys.argv[sys.argv.index('install')+1:] 355 | for index, arg in enumerate(args): 356 | for option in ('--root', '--prefix'): 357 | if arg.startswith('%s=' % option): 358 | top_dir = arg.split('root=')[-1] 359 | return location.startswith(top_dir) 360 | elif arg == option: 361 | if len(args) > index: 362 | top_dir = args[index+1] 363 | return location.startswith(top_dir) 364 | if arg == '--user' and USER_SITE is not None: 365 | return location.startswith(USER_SITE) 366 | return True 367 | 368 | 369 | def _fake_setuptools(): 370 | log.warn('Scanning installed packages') 371 | try: 372 | import pkg_resources 373 | except ImportError: 374 | # we're cool 375 | log.warn('Setuptools or Distribute does not seem to be installed.') 376 | return 377 | ws = pkg_resources.working_set 378 | try: 379 | setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools', 380 | replacement=False)) 381 | except TypeError: 382 | # old distribute API 383 | setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools')) 384 | 385 | if setuptools_dist is None: 386 | log.warn('No setuptools distribution found') 387 | return 388 | # detecting if it was already faked 389 | setuptools_location = setuptools_dist.location 390 | log.warn('Setuptools installation detected at %s', setuptools_location) 391 | 392 | # if --root or --preix was provided, and if 393 | # setuptools is not located in them, we don't patch it 394 | if not _under_prefix(setuptools_location): 395 | log.warn('Not patching, --root or --prefix is installing Distribute' 396 | ' in another location') 397 | return 398 | 399 | # let's see if its an egg 400 | if not setuptools_location.endswith('.egg'): 401 | log.warn('Non-egg installation') 402 | res = _remove_flat_installation(setuptools_location) 403 | if not res: 404 | return 405 | else: 406 | log.warn('Egg installation') 407 | pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') 408 | if (os.path.exists(pkg_info) and 409 | _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): 410 | log.warn('Already patched.') 411 | return 412 | log.warn('Patching...') 413 | # let's create a fake egg replacing setuptools one 414 | res = _patch_egg_dir(setuptools_location) 415 | if not res: 416 | return 417 | log.warn('Patched done.') 418 | _relaunch() 419 | 420 | 421 | def _relaunch(): 422 | log.warn('Relaunching...') 423 | # we have to relaunch the process 424 | # pip marker to avoid a relaunch bug 425 | if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']: 426 | sys.argv[0] = 'setup.py' 427 | args = [sys.executable] + sys.argv 428 | sys.exit(subprocess.call(args)) 429 | 430 | 431 | def _extractall(self, path=".", members=None): 432 | """Extract all members from the archive to the current working 433 | directory and set owner, modification time and permissions on 434 | directories afterwards. `path' specifies a different directory 435 | to extract to. `members' is optional and must be a subset of the 436 | list returned by getmembers(). 437 | """ 438 | import copy 439 | import operator 440 | from tarfile import ExtractError 441 | directories = [] 442 | 443 | if members is None: 444 | members = self 445 | 446 | for tarinfo in members: 447 | if tarinfo.isdir(): 448 | # Extract directories with a safe mode. 449 | directories.append(tarinfo) 450 | tarinfo = copy.copy(tarinfo) 451 | tarinfo.mode = 448 # decimal for oct 0700 452 | self.extract(tarinfo, path) 453 | 454 | # Reverse sort directories. 455 | if sys.version_info < (2, 4): 456 | def sorter(dir1, dir2): 457 | return cmp(dir1.name, dir2.name) 458 | directories.sort(sorter) 459 | directories.reverse() 460 | else: 461 | directories.sort(key=operator.attrgetter('name'), reverse=True) 462 | 463 | # Set correct owner, mtime and filemode on directories. 464 | for tarinfo in directories: 465 | dirpath = os.path.join(path, tarinfo.name) 466 | try: 467 | self.chown(tarinfo, dirpath) 468 | self.utime(tarinfo, dirpath) 469 | self.chmod(tarinfo, dirpath) 470 | except ExtractError: 471 | e = sys.exc_info()[1] 472 | if self.errorlevel > 1: 473 | raise 474 | else: 475 | self._dbg(1, "tarfile: %s" % e) 476 | 477 | 478 | def main(argv, version=DEFAULT_VERSION): 479 | """Install or upgrade setuptools and EasyInstall""" 480 | tarball = download_setuptools() 481 | _install(tarball) 482 | 483 | 484 | if __name__ == '__main__': 485 | main(sys.argv[1:]) 486 | -------------------------------------------------------------------------------- /nested_dict/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """`nested_dict` provides dictionaries with multiple levels of nested-ness.""" 3 | __version__ = '1.61' 4 | from .implementation import nested_dict 5 | 6 | __all__ = ('nested_dict', ) 7 | -------------------------------------------------------------------------------- /nested_dict/implementation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """`nested_dict` provides dictionaries with multiple levels of nested-ness.""" 3 | from __future__ import print_function 4 | from __future__ import division 5 | 6 | ################################################################################ 7 | # 8 | # nested_dict.py 9 | # 10 | # Copyright (c) 2009, 2015 Leo Goodstadt 11 | # 12 | # Permission is hereby granted, free of charge, to any person obtaining a copy 13 | # of this software and associated documentation files (the "Software"), to deal 14 | # in the Software without restriction, including without limitation the rights 15 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | # copies of the Software, and to permit persons to whom the Software is 17 | # furnished to do so, subject to the following conditions: 18 | # 19 | # The above copyright notice and this permission notice shall be included in 20 | # all copies or substantial portions of the Software. 21 | # 22 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 | # THE SOFTWARE. 29 | # 30 | ################################################################################# 31 | 32 | 33 | from collections import defaultdict 34 | 35 | import sys 36 | 37 | 38 | def flatten_nested_items(dictionary): 39 | """ 40 | Flatten a nested_dict. 41 | 42 | iterate through nested dictionary (with iterkeys() method) 43 | and return with nested keys flattened into a tuple 44 | """ 45 | if sys.hexversion < 0x03000000: 46 | keys = dictionary.iterkeys 47 | keystr = "iterkeys" 48 | else: 49 | keys = dictionary.keys 50 | keystr = "keys" 51 | for key in keys(): 52 | value = dictionary[key] 53 | if hasattr(value, keystr): 54 | for keykey, value in flatten_nested_items(value): 55 | yield (key,) + keykey, value 56 | else: 57 | yield (key,), value 58 | 59 | 60 | class _recursive_dict(defaultdict): 61 | """ 62 | Parent class of nested_dict. 63 | 64 | Defined separately for _nested_levels to work 65 | transparently, so dictionaries with a specified (and constant) degree of nestedness 66 | can be created easily. 67 | 68 | The "_flat" functions are defined here rather than in nested_dict because they work 69 | recursively. 70 | 71 | """ 72 | 73 | def iteritems_flat(self): 74 | """Iterate through items with nested keys flattened into a tuple.""" 75 | for key, value in flatten_nested_items(self): 76 | yield key, value 77 | 78 | def iterkeys_flat(self): 79 | """Iterate through keys with nested keys flattened into a tuple.""" 80 | for key, value in flatten_nested_items(self): 81 | yield key 82 | 83 | def itervalues_flat(self): 84 | """Iterate through values with nested keys flattened into a tuple.""" 85 | for key, value in flatten_nested_items(self): 86 | yield value 87 | 88 | items_flat = iteritems_flat 89 | keys_flat = iterkeys_flat 90 | values_flat = itervalues_flat 91 | 92 | def to_dict(self, input_dict=None): 93 | """Convert the nested dictionary to a nested series of standard ``dict`` objects.""" 94 | # 95 | # Calls itself recursively to unwind the dictionary. 96 | # Use to_dict() to start at the top level of nesting 97 | plain_dict = dict() 98 | if input_dict is None: 99 | input_dict = self 100 | for key in input_dict.keys(): 101 | value = input_dict[key] 102 | if isinstance(value, _recursive_dict): 103 | # print "recurse", value 104 | plain_dict[key] = self.to_dict(value) 105 | else: 106 | # print "plain", value 107 | plain_dict[key] = value 108 | return plain_dict 109 | 110 | def __str__(self, indent=None): 111 | """Representation of self as a string.""" 112 | import json 113 | return json.dumps(self.to_dict(), indent=indent) 114 | 115 | 116 | class _any_type(object): 117 | pass 118 | 119 | 120 | def _nested_levels(level, nested_type): 121 | """Helper function to create a specified degree of nested dictionaries.""" 122 | if level > 2: 123 | return lambda: _recursive_dict(_nested_levels(level - 1, nested_type)) 124 | if level == 2: 125 | if isinstance(nested_type, _any_type): 126 | return lambda: _recursive_dict() 127 | else: 128 | return lambda: _recursive_dict(_nested_levels(level - 1, nested_type)) 129 | return nested_type 130 | 131 | 132 | if sys.hexversion < 0x03000000: 133 | iteritems = dict.iteritems 134 | else: 135 | iteritems = dict.items 136 | 137 | 138 | # _________________________________________________________________________________________ 139 | # 140 | # nested_dict 141 | # 142 | # _________________________________________________________________________________________ 143 | def nested_dict_from_dict(orig_dict, nd): 144 | """Helper to build nested_dict from a dict.""" 145 | for key, value in iteritems(orig_dict): 146 | if isinstance(value, (dict,)): 147 | nd[key] = nested_dict_from_dict(value, nested_dict()) 148 | else: 149 | nd[key] = value 150 | return nd 151 | 152 | 153 | def _recursive_update(nd, other): 154 | for key, value in iteritems(other): 155 | #print ("key=", key) 156 | if isinstance(value, (dict,)): 157 | 158 | # recursive update if my item is nested_dict 159 | if isinstance(nd[key], (_recursive_dict,)): 160 | #print ("recursive update", key, type(nd[key])) 161 | _recursive_update(nd[key], other[key]) 162 | 163 | # update if my item is dict 164 | elif isinstance(nd[key], (dict,)): 165 | #print ("update", key, type(nd[key])) 166 | nd[key].update(other[key]) 167 | 168 | # overwrite 169 | else: 170 | #print ("self not nested dict or dict: overwrite", key) 171 | nd[key] = value 172 | # other not dict: overwrite 173 | else: 174 | #print ("other not dict: overwrite", key) 175 | nd[key] = value 176 | return nd 177 | 178 | 179 | # _________________________________________________________________________________________ 180 | # 181 | # nested_dict 182 | # 183 | # _________________________________________________________________________________________ 184 | class nested_dict(_recursive_dict): 185 | """ 186 | Nested dict. 187 | 188 | Uses defaultdict to automatically add levels of nested dicts and other types. 189 | """ 190 | 191 | def update(self, other): 192 | """Update recursively.""" 193 | _recursive_update(self, other) 194 | 195 | def __init__(self, *param, **named_param): 196 | """ 197 | Constructor. 198 | 199 | Takes one or two parameters 200 | 1) int, [TYPE] 201 | 1) dict 202 | """ 203 | if not len(param): 204 | self.factory = nested_dict 205 | defaultdict.__init__(self, self.factory) 206 | return 207 | 208 | if len(param) == 1: 209 | # int = level 210 | if isinstance(param[0], int): 211 | self.factory = _nested_levels(param[0], _any_type()) 212 | defaultdict.__init__(self, self.factory) 213 | return 214 | # existing dict 215 | if isinstance(param[0], dict): 216 | self.factory = nested_dict 217 | defaultdict.__init__(self, self.factory) 218 | nested_dict_from_dict(param[0], self) 219 | return 220 | 221 | if len(param) == 2: 222 | if isinstance(param[0], int): 223 | self.factory = _nested_levels(*param) 224 | defaultdict.__init__(self, self.factory) 225 | return 226 | 227 | raise Exception("nested_dict should be initialised with either " 228 | "1) the number of nested levels and an optional type, or " 229 | "2) an existing dict to be converted into a nested dict " 230 | "(factory = %s. len(param) = %d, param = %s" 231 | % (self.factory, len(param), param)) 232 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | coverage 2 | flake8 3 | flake8-docstrings 4 | nose 5 | sphinx 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Copyright (C) 2015 Leo Goodstadt 4 | # 5 | # This file is part of nested_dict. 6 | # 7 | # nested_dict is free software: you can redistribute it and/or modify 8 | # it under the terms of the MIT license as found here 9 | # http://opensource.org/licenses/MIT. 10 | # 11 | """Setup module for nested-dict.""" 12 | 13 | import re 14 | import os 15 | 16 | # First, we try to use setuptools. If it's not available locally, 17 | # we fall back on ez_setup. 18 | try: 19 | from setuptools import setup 20 | except ImportError: 21 | from ez_setup import use_setuptools 22 | use_setuptools() 23 | from setuptools import setup 24 | 25 | 26 | # Following the recommendations of PEP 396 we parse the version number 27 | # out of the module. 28 | def parse_version(module_file): 29 | """ 30 | Parse the version string from the specified file. 31 | 32 | This implementation is ugly, but there doesn't seem to be a good way 33 | to do this in general at the moment. 34 | """ 35 | f = open(module_file) 36 | s = f.read() 37 | f.close() 38 | match = re.findall("__version__ = '([^']+)'", s) 39 | return match[0] 40 | 41 | 42 | f = open(os.path.join(os.path.dirname(__file__), "README.rst")) 43 | nested_dict_readme = f.read() 44 | f.close() 45 | nested_dict_version = parse_version(os.path.join("nested_dict", "__init__.py")) 46 | 47 | setup( 48 | name="nested_dict", 49 | version=nested_dict_version, 50 | description="Python dictionary with automatic and arbitrary levels of nestedness", 51 | long_description=nested_dict_readme, 52 | packages=["nested_dict"], 53 | author='Leo Goodstadt', 54 | author_email='nested_dict@llew.org.uk', 55 | url="http://pypi.python.org/pypi/nested_dict", 56 | install_requires=[], 57 | setup_requires=[], 58 | keywords=["nested", "dict", "defaultdict", "dictionary", "auto-vivification"], 59 | license="MIT", 60 | 61 | classifiers=[ 62 | "Programming Language :: Python", 63 | "Programming Language :: Python :: 2", 64 | "Programming Language :: Python :: 2.6", 65 | "Programming Language :: Python :: 2.7", 66 | "Programming Language :: Python :: 3", 67 | "Programming Language :: Python :: 3.3", 68 | "Programming Language :: Python :: 3.4", 69 | "Programming Language :: Python :: 3.5", 70 | "Programming Language :: Python :: Implementation :: PyPy", 71 | "Development Status :: 5 - Production/Stable", 72 | "Intended Audience :: End Users/Desktop", 73 | "Intended Audience :: Science/Research", 74 | "Intended Audience :: Financial and Insurance Industry", 75 | "Intended Audience :: Developers", 76 | 'Intended Audience :: Information Technology', 77 | "License :: OSI Approved :: MIT License", 78 | "Topic :: Scientific/Engineering", 79 | "Topic :: Software Development", 80 | "Topic :: Software Development :: Libraries", 81 | "Topic :: Scientific/Engineering", 82 | "Topic :: Utilities", 83 | ], 84 | 85 | test_suite="tests.test_nested_dict", 86 | ) 87 | 88 | # python setup.py register 89 | # flake8 *.py tests --exclude=ez_setup.py --max-line-length=100 90 | # nosetests --with-coverage --cover-package nested_dict --cover-inclusive --cover-min-percentage 85 91 | # make -C docs html 92 | # git tag -a v1.5.1 -m "Version 1.5.1" 93 | # python setup.py sdist --format=gztar,zip upload 94 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Test modules for nested-dict.""" 2 | -------------------------------------------------------------------------------- /tests/test_nested_dict.py: -------------------------------------------------------------------------------- 1 | """Test module for nested_dict.""" 2 | from __future__ import print_function 3 | 4 | 5 | import unittest 6 | import sys 7 | import os 8 | 9 | 10 | # make sure which nested_dict we are testing 11 | parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) 12 | sys.path.insert(0, parent_dir) 13 | 14 | 15 | class Test_nested_dict_constructor(unittest.TestCase): 16 | """Test nested_dict constructor parameters.""" 17 | 18 | def test_default(self): 19 | """Test constructor without parameters.""" 20 | from nested_dict import nested_dict 21 | nd = nested_dict() 22 | nd['new jersey']['mercer county']['plumbers'] = 3 23 | nd['new jersey']['mercer county']['programmers'] = 81 24 | nd['new jersey']['middlesex county']['programmers'] = 81 25 | nd['new jersey']['middlesex county']['salesmen'] = 62 26 | nd['new york']['queens county']['plumbers'] = 9 27 | nd['new york']['queens county']['salesmen'] = 36 28 | 29 | expected_result = sorted([ 30 | (('new jersey', 'mercer county', 'plumbers'), 3), 31 | (('new jersey', 'mercer county', 'programmers'), 81), 32 | (('new jersey', 'middlesex county', 'programmers'), 81), 33 | (('new jersey', 'middlesex county', 'salesmen'), 62), 34 | (('new york', 'queens county', 'plumbers'), 9), 35 | (('new york', 'queens county', 'salesmen'), 36), 36 | ]) 37 | all = sorted(tup for tup in nd.iteritems_flat()) 38 | self.assertEqual(all, expected_result) 39 | all = sorted(tup for tup in nd.items_flat()) 40 | self.assertEqual(all, expected_result) 41 | 42 | def test_bad_init(self): 43 | """Test with invalid constructor parameters.""" 44 | # 45 | # Maximum of four levels 46 | # 47 | import nested_dict 48 | try: 49 | nd3 = nested_dict.nested_dict(1, 2, 3) 50 | self.assertTrue("Should have throw assertion before getting here") 51 | # just so flake8 stops complaining! 52 | nd3[1][2][3] = "b" 53 | except Exception: 54 | pass 55 | # 56 | # levels not int 57 | # 58 | import nested_dict 59 | try: 60 | nd2 = nested_dict.nested_dict("a", "b") 61 | self.assertTrue("Should have throw assertion before getting here") 62 | # just so flake8 stops complaining! 63 | nd2[1][2] = "b" 64 | except Exception: 65 | pass 66 | 67 | def test_fixed_nesting(self): 68 | """Fixed levels of nesting, no type specified.""" 69 | # 70 | # Maximum of four levels 71 | # 72 | import nested_dict 73 | nd4 = nested_dict.nested_dict(4) 74 | # OK: Assign to "string" 75 | nd4[1][2][3][4] = "a" 76 | 77 | # Bad: Five levels is one too many 78 | try: 79 | nd4[1][2][3]["four"][5] = "b" 80 | self.assertTrue("Should have throw assertion before getting here") 81 | except KeyError: 82 | pass 83 | 84 | nd2 = nested_dict.nested_dict(2) 85 | # OK: Assign to "string" 86 | nd2[1][2] = "a" 87 | 88 | # Bad: Five levels is one too many 89 | try: 90 | nd2[1]["two"][3] = "b" 91 | self.assertTrue("Should have throw assertion before getting here") 92 | except KeyError: 93 | pass 94 | 95 | def test_list(self): 96 | """Test with nested type of `list`.""" 97 | import nested_dict 98 | nd = nested_dict.nested_dict(2, list) 99 | nd['new jersey']['mercer county'].append('plumbers') 100 | nd['new jersey']['mercer county'].append('programmers') 101 | nd['new jersey']['middlesex county'].append('salesmen') 102 | nd['new jersey']['middlesex county'].append('staff') 103 | nd['new york']['queens county'].append('cricketers') 104 | all = sorted(tup for tup in nd.iteritems_flat()) 105 | self.assertEqual(all, [(('new jersey', 'mercer county'), ['plumbers', 'programmers']), 106 | (('new jersey', 'middlesex county'), ['salesmen', 'staff']), 107 | (('new york', 'queens county'), ['cricketers']), 108 | ]) 109 | all = sorted(tup for tup in nd.itervalues_flat()) 110 | self.assertEqual(all, [['cricketers'], 111 | ['plumbers', 'programmers'], 112 | ['salesmen', 'staff']]) 113 | all = sorted(tup for tup in nd.values_flat()) 114 | self.assertEqual(all, [['cricketers'], 115 | ['plumbers', 'programmers'], 116 | ['salesmen', 'staff']]) 117 | all = sorted(tup for tup in nd.iterkeys_flat()) 118 | self.assertEqual(all, [('new jersey', 'mercer county'), 119 | ('new jersey', 'middlesex county'), 120 | ('new york', 'queens county')]) 121 | all = sorted(tup for tup in nd.keys_flat()) 122 | self.assertEqual(all, [('new jersey', 'mercer county'), 123 | ('new jersey', 'middlesex county'), 124 | ('new york', 'queens county')]) 125 | 126 | self.assertEqual(nd, {"new jersey": {"mercer county": ["plumbers", 127 | "programmers"], 128 | "middlesex county": ["salesmen", 129 | "staff"]}, 130 | "new york": {"queens county": ["cricketers"]}}) 131 | 132 | 133 | class Test_nested_dict_methods(unittest.TestCase): 134 | """Test methods of nested_dict.""" 135 | 136 | def test_iteritems_flat(self): 137 | """Test iteritems_flat method.""" 138 | import nested_dict 139 | a = nested_dict.nested_dict() 140 | a['1']['2']['3'] = 3 141 | a['A']['B'] = 15 142 | self.assertEqual(sorted(a.iteritems_flat()), [(('1', '2', '3'), 3), (('A', 'B'), 15)]) 143 | 144 | def test_iterkeys_flat(self): 145 | """Test iterkeys_flat method.""" 146 | import nested_dict 147 | a = nested_dict.nested_dict() 148 | a['1']['2']['3'] = 3 149 | a['A']['B'] = 15 150 | self.assertEqual(sorted(a.iterkeys_flat()), [('1', '2', '3'), ('A', 'B')]) 151 | 152 | def test_itervalues_flat(self): 153 | """Test itervalues_flat method.""" 154 | import nested_dict 155 | a = nested_dict.nested_dict() 156 | a['1']['2']['3'] = 3 157 | a['A']['B'] = 15 158 | self.assertEqual(sorted(a.itervalues_flat()), [3, 15]) 159 | 160 | def test_to_dict(self): 161 | """Test to_dict method.""" 162 | import nested_dict 163 | a = nested_dict.nested_dict() 164 | a['1']['2']['3'] = 3 165 | a['A']['B'] = 15 166 | 167 | normal_dict = a.to_dict() 168 | self.assertEqual(normal_dict, {'1': {'2': {'3': 3}}, 'A': {'B': 15}}) 169 | 170 | b = nested_dict.nested_dict(normal_dict) 171 | self.assertEqual(b, {'1': {'2': {'3': 3}}, 'A': {'B': 15}}) 172 | 173 | def test_str(self): 174 | """Test __str__ method.""" 175 | import nested_dict 176 | import json 177 | a = nested_dict.nested_dict() 178 | a['1']['2']['3'] = 3 179 | a['A']['B'] = 15 180 | self.assertEqual(json.loads(str(a)), {'1': {'2': {'3': 3}}, 'A': {'B': 15}}) 181 | 182 | def test_update(self): 183 | """Test update method.""" 184 | import nested_dict 185 | 186 | # 187 | # nested dictionary updates 188 | # 189 | d1 = nested_dict.nested_dict() 190 | d2 = nested_dict.nested_dict() 191 | d1[1][2][3] = 4 192 | d2[1][2][4] = 5 193 | d1.update(d2) 194 | d1.to_dict() 195 | self.assertEqual(d1.to_dict(), {1: {2: {3: 4, 4: 5}}}) 196 | 197 | # 198 | # dictionary updates 199 | # 200 | d1 = nested_dict.nested_dict() 201 | d2 = {1: {2: {4: 5}}} 202 | d1[1][2][3] = 4 203 | d2[1][2][4] = 5 204 | d1.update(d2) 205 | d1.to_dict() 206 | self.assertEqual(d1.to_dict(), {1: {2: {3: 4, 4: 5}}}) 207 | 208 | # 209 | # scalar overwrites 210 | # 211 | d1 = nested_dict.nested_dict() 212 | d2 = nested_dict.nested_dict() 213 | d1[1][2][3] = 4 214 | d2[1][2] = 5 215 | d1.update(d2) 216 | d1.to_dict() 217 | self.assertEqual(d1.to_dict(), {1: {2: 5}}) 218 | 219 | # 220 | # updates try to preserve the sort of nested_dict 221 | # 222 | d1 = nested_dict.nested_dict(3, int) 223 | d2 = nested_dict.nested_dict() 224 | d1[1][2][3] = 4 225 | d1[1][2][4] = 5 226 | d2[2][3][4][5] = 6 227 | d1.update(d2) 228 | d1.to_dict() 229 | self.assertEqual(d1.to_dict(), {1: {2: {3: 4, 4: 5}}, 2: {3: {4: {5: 6}}}}) 230 | # d1[2][3][4][5] = 6 but d1[2][3][4] should still be a default dict of int 231 | self.assertEqual(d1[2][3][5], 0) 232 | 233 | # 234 | # updates try to preserve the sort of nested_dict 235 | # 236 | d1 = nested_dict.nested_dict(3, list) 237 | d2 = {2: {3: {4: {5: 6}}}} 238 | d1[1][2][3].append(4) 239 | d1[1][2][4].append(4) 240 | d1.update(d2) 241 | d1.to_dict() 242 | self.assertEqual(d1.to_dict(), {1: {2: {3: [4], 4: [4]}}, 2: {3: {4: {5: 6}}}}) 243 | # d1[2][3][4][5] = 6 but d1[2][3][5] should still be a default dict of list 244 | d1[2][3][5].append(4) 245 | self.assertEqual(d1.to_dict(), {1: {2: {3: [4], 4: [4]}}, 2: {3: {4: {5: 6}, 5: [4]}}}) 246 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore=D203,E265 3 | exclude=ez_setup.py,docs/source/conf.py,build/* 4 | max-line-length=100 5 | --------------------------------------------------------------------------------