pax_global_header00006660000000000000000000000064137513277340014526gustar00rootroot0000000000000052 comment=6d22d46585fd721f08680f28d7832ceefa4ede3d python-deepmerge-0.0.5/000077500000000000000000000000001375132773400150045ustar00rootroot00000000000000python-deepmerge-0.0.5/.gitignore000066400000000000000000000021061375132773400167730ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject .uranium bin include VERSION pip-selfcheck.json python-deepmerge-0.0.5/LICENSE000066400000000000000000000020601375132773400160070ustar00rootroot00000000000000MIT License Copyright (c) 2016 Yusuke Tsutsumi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-deepmerge-0.0.5/MANIFEST.in000066400000000000000000000000171375132773400165400ustar00rootroot00000000000000include VERSIONpython-deepmerge-0.0.5/README.rst000066400000000000000000000026631375132773400165020ustar00rootroot00000000000000========= deepmerge ========= A tools to handle merging of nested data structures in python. ------------ Installation ------------ deepmerge is available on `pypi `_: .. code-block:: bash pip install deepmerge ------- Example ------- **Generic Strategy** .. code-block:: python from deepmerge import always_merger base = {"foo": ["bar"]} next = {"foo": ["baz"]} expected_result = {'foo': ['bar', 'baz']} result = always_merger.merge(base, next) assert expected_result == result **Custom Strategy** .. code-block:: python from deepmerge import Merger my_merger = Merger( # pass in a list of tuple, with the # strategies you are looking to apply # to each type. [ (list, ["append"]), (dict, ["merge"]) ], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"] ) base = {"foo": ["bar"]} next = {"bar": "baz"} my_merger.merge(base, next) assert base == {"foo": ["bar"], "bar": "baz"} You can also pass in your own merge functions, instead of a string. For more information, see the `docs `_ ----- Tests ----- .. code-block:: shell $ pip install pytest $ pytest deepmerge/tests/ python-deepmerge-0.0.5/deepmerge/000077500000000000000000000000001375132773400167415ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/__init__.py000066400000000000000000000017121375132773400210530ustar00rootroot00000000000000from .merger import Merger from .strategy.core import STRATEGY_END # some standard mergers available # this merge will never raise an exception. # in the case of type mismatches, # the value from the second object # will override the previous one. always_merger = Merger( [ (list, "append"), (dict, "merge") ], ["override"], ["override"] ) # this merge strategies attempts # to merge (append for list, unify for dicts) # if possible, but raises an exception # in the case of type conflicts. merge_or_raise = Merger( [ (list, "append"), (dict, "merge") ], [], [] ) # a conservative merge tactic: # for data structures with a specific # strategy, keep the existing value. # similar to always_merger but instead # keeps existing values when faced # with a type conflict. conservative_merger = Merger( [ (list, "append"), (dict, "merge") ], ["use_existing"], ["use_existing"] ) python-deepmerge-0.0.5/deepmerge/compat.py000066400000000000000000000001001375132773400205650ustar00rootroot00000000000000try: string_type = basestring except: string_type = str python-deepmerge-0.0.5/deepmerge/exception.py000066400000000000000000000002301375132773400213040ustar00rootroot00000000000000class DeepMergeException(Exception): pass class StrategyNotFound(DeepMergeException): pass class InvalidMerge(DeepMergeException): pass python-deepmerge-0.0.5/deepmerge/merger.py000066400000000000000000000033001375132773400205700ustar00rootroot00000000000000from .strategy.list import ListStrategies from .strategy.dict import DictStrategies from .strategy.type_conflict import TypeConflictStrategies from .strategy.fallback import FallbackStrategies class Merger(object): """ :param type_strategies, List[Tuple]: a list of (Type, Strategy) pairs that should be used against incoming types. For example: (dict, "override"). """ PROVIDED_TYPE_STRATEGIES = { list: ListStrategies, dict: DictStrategies } def __init__(self, type_strategies, fallback_strategies, type_conflict_strategies): self._fallback_strategy = FallbackStrategies(fallback_strategies) expanded_type_strategies = [] for typ, strategy in type_strategies: if typ in self.PROVIDED_TYPE_STRATEGIES: strategy = self.PROVIDED_TYPE_STRATEGIES[typ](strategy) expanded_type_strategies.append((typ, strategy)) self._type_strategies = expanded_type_strategies self._type_conflict_strategy = TypeConflictStrategies( type_conflict_strategies ) def merge(self, base, nxt): return self.value_strategy([], base, nxt) def type_conflict_strategy(self, *args): return self._type_conflict_strategy(self, *args) def value_strategy(self, path, base, nxt): if not (isinstance(base, type(nxt)) or isinstance(nxt, type(base))): return self.type_conflict_strategy(path, base, nxt) for typ, strategy in self._type_strategies: if isinstance(nxt, typ): return strategy(self, path, base, nxt) return self._fallback_strategy(self, path, base, nxt) python-deepmerge-0.0.5/deepmerge/strategy/000077500000000000000000000000001375132773400206035ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/strategy/__init__.py000066400000000000000000000000001375132773400227020ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/strategy/core.py000066400000000000000000000024151375132773400221070ustar00rootroot00000000000000from ..exception import StrategyNotFound, InvalidMerge from ..compat import string_type STRATEGY_END = object() class StrategyList(object): NAME = None def __init__(self, strategy_list): if not isinstance(strategy_list, list): strategy_list = [strategy_list] self._strategies = [ self._expand_strategy(s) for s in strategy_list ] @classmethod def _expand_strategy(cls, strategy): """ :param strategy: string or function If the strategy is a string, attempt to resolve it among the built in strategies. Otherwise, return the value, implicitly assuming it's a function. """ if isinstance(strategy, string_type): method_name = "strategy_{0}".format(strategy) if not hasattr(cls, method_name): raise StrategyNotFound(strategy) return getattr(cls, method_name) return strategy def __call__(self, *args, **kwargs): for s in self._strategies: ret_val = s(*args, **kwargs) if ret_val is not STRATEGY_END: return ret_val raise InvalidMerge("no more strategies found for {0} and arguments {1}, {2}".format( self.NAME, args, kwargs )) python-deepmerge-0.0.5/deepmerge/strategy/dict.py000066400000000000000000000014041375132773400220770ustar00rootroot00000000000000from .core import StrategyList class DictStrategies(StrategyList): """ Contains the strategies provided for dictionaries. """ NAME = "dict" @staticmethod def strategy_merge(config, path, base, nxt): """ for keys that do not exists, use them directly. if the key exists in both dictionaries, attempt a value merge. """ for k, v in nxt.items(): if k not in base: base[k] = v else: base[k] = config.value_strategy(path + [k], base[k], v) return base @staticmethod def strategy_override(config, path, base, nxt): """ move all keys in nxt into base, overriding conflicts. """ return nxt python-deepmerge-0.0.5/deepmerge/strategy/fallback.py000066400000000000000000000006631375132773400227210ustar00rootroot00000000000000from .core import StrategyList class FallbackStrategies(StrategyList): """ The StrategyList containing fallback strategies. """ NAME = "fallback" @staticmethod def strategy_override(config, path, base, nxt): """ use nxt, and ignore base. """ return nxt @staticmethod def strategy_use_existing(config, path, base, nxt): """ use base, and ignore next. """ return base python-deepmerge-0.0.5/deepmerge/strategy/list.py000066400000000000000000000010341375132773400221260ustar00rootroot00000000000000from .core import StrategyList class ListStrategies(StrategyList): """ Contains the strategies provided for lists. """ NAME = "list" @staticmethod def strategy_override(config, path, base, nxt): """ use the list nxt. """ return nxt @staticmethod def strategy_prepend(config, path, base, nxt): """ prepend nxt to base. """ return nxt + base @staticmethod def strategy_append(config, path, base, nxt): """ append nxt to base. """ return base + nxt python-deepmerge-0.0.5/deepmerge/strategy/type_conflict.py000066400000000000000000000007351375132773400240240ustar00rootroot00000000000000from .core import StrategyList class TypeConflictStrategies(StrategyList): """ contains the strategies provided for type conflicts. """ NAME = "type conflict" @staticmethod def strategy_override(config, path, base, nxt): """ overrides the new object over the old object """ return nxt @staticmethod def strategy_use_existing(config, path, base, nxt): """ overrides the new object over the old object """ return base python-deepmerge-0.0.5/deepmerge/tests/000077500000000000000000000000001375132773400201035ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/tests/__init__.py000066400000000000000000000000001375132773400222020ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/tests/strategy/000077500000000000000000000000001375132773400217455ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/tests/strategy/__init__.py000066400000000000000000000000001375132773400240440ustar00rootroot00000000000000python-deepmerge-0.0.5/deepmerge/tests/strategy/test_core.py000066400000000000000000000016621375132773400243130ustar00rootroot00000000000000from deepmerge.strategy.core import StrategyList from deepmerge import STRATEGY_END def return_true_if_foo(config, path, base, nxt): if base == "foo": return True return STRATEGY_END def always_return_custom(config, path, base, nxt): return "custom" def test_single_value_allowed(): """ """ def strat(name): return name sl = StrategyList(strat) assert sl("foo") == "foo" def test_first_working_strategy_is_used(): """ In the case where the StrategyList has multiple values, the first strategy which returns a valid value (i.e. not STRATEGY_END) should be returned. """ sl = StrategyList([ return_true_if_foo, always_return_custom, ]) # return_true_if_foo will take. assert sl({}, [], "foo", "bar") is True # return_true_if_foo will fail, # which will then activea always_return_custom assert sl({}, [], "bar", "baz") == "custom" python-deepmerge-0.0.5/deepmerge/tests/test_full.py000066400000000000000000000020051375132773400224530ustar00rootroot00000000000000import pytest from deepmerge import ( always_merger, conservative_merger, merge_or_raise, ) def test_fill_missing_value(): base = { "foo": 0, "baz": 2 } nxt = { "bar": 1 } always_merger.merge(base, nxt) assert base == { "foo": 0, "bar": 1, "baz": 2 } def test_merge_or_raise_raises_exception(): base = { "foo": 0, "baz": 2 } nxt = { "bar": 1, "foo": "a string!" } with pytest.raises(Exception): merge_or_raise.merge(base, nxt) @pytest.mark.parametrize("base, nxt, expected", [ ("dooby", "fooby", "dooby"), (-10, "goo", -10) ]) def test_use_existing(base, nxt, expected): assert conservative_merger.merge(base, nxt) == expected def test_example(): base = {"foo": "value", "baz": ["a"]} next = {"bar": "value2", "baz": ["b"]} always_merger.merge(base, next) assert base == { "foo": "value", "bar": "value2", "baz": ["a", "b"] } python-deepmerge-0.0.5/deepmerge/tests/test_merger.py000066400000000000000000000013301375132773400227720ustar00rootroot00000000000000import pytest from deepmerge import Merger @pytest.fixture def custom_merger(): def merge_sets(merger, path, base, nxt): base |= nxt return base def merge_list(merger, path, base, nxt): if len(nxt) > 0: base.append(nxt[-1]) return base return Merger( [ (list, merge_list), (dict, "merge"), (set, merge_sets) ], [], [], ) def test_custom_merger_applied(custom_merger): result = custom_merger.merge({"foo"}, {"bar"}) assert result == {"foo", "bar"} def test_custom_merger_list(custom_merger): result = custom_merger.merge([1, 2, 3], [4, 5, 6]) assert result == [1, 2, 3, 6] python-deepmerge-0.0.5/docs/000077500000000000000000000000001375132773400157345ustar00rootroot00000000000000python-deepmerge-0.0.5/docs/Makefile000066400000000000000000000167021375132773400174020ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " epub3 to make an epub3" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" @echo " dummy to check syntax errors of document sources" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/deepmerge.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/deepmerge.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/deepmerge" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/deepmerge" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: epub3 epub3: $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 @echo @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." .PHONY: dummy dummy: $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy @echo @echo "Build finished. Dummy builder generates no files." python-deepmerge-0.0.5/docs/api.rst000066400000000000000000000002501375132773400172340ustar00rootroot00000000000000============= API Reference ============= .. autoclass:: deepmerge.merger.Merger :members: .. automodule:: deepmerge.exception :members: :undoc-members: python-deepmerge-0.0.5/docs/conf.py000066400000000000000000000231621375132773400172370ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # deepmerge documentation build configuration file, created by # sphinx-quickstart on Sun Nov 20 11:31:44 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'deepmerge' copyright = u'2016, Yusuke Tsutsumi' author = u'Yusuke Tsutsumi' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'0.1' # The full version, including alpha/beta/rc tags. release = u'0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # " v documentation" by default. # # html_title = u'deepmerge v0.1' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'deepmergedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'deepmerge.tex', u'deepmerge Documentation', u'Yusuke Tsutsumi', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'deepmerge', u'deepmerge Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'deepmerge', u'deepmerge Documentation', author, 'deepmerge', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False python-deepmerge-0.0.5/docs/guide.rst000066400000000000000000000062571375132773400175750ustar00rootroot00000000000000User Guide ---------- Simple Usage ============ deepmerge was written as a library to help construct merge functions, eliminating some of the boilerplate around recursing through common data structures and joining results. Although it's recommended to choose your own strategies, deepmerge does provided some preconfigured mergers for a common situations: * deepmerge.always_merger: always try to merge. in the case of mismatches, the value from the second object overrides the first o ne. * deepmerge.merge_or_raise: try to merge, raise an exception if an unmergable situation is encountered. * deepmerge.conservative_merger: similar to always_merger, but in the case of a conflict, use the existing value. Once a merger is constructed, it then has a merge() method that can be called: .. code-block:: python from deepmerge import always_merger base = {"foo": "value", "baz": ["a"]} next = {"bar": "value2", "baz": ["b"]} always_merger.merge(base, next) assert base == { "foo": "value", "bar": "value2", "baz": ["a", "b"] } Merges are Destructive ====================== You may have noticed from the example, but merging is a destructive behavior: it will modify the first argument passed in (the base) as part of the merge. This is intentional, as an implicit copy would result in a significant performance slowdown for deep data structures. If you need to keep the original objects unmodified, you can use the deepcopy method: .. code-block:: python from copy import deepcopy result = deepcopy(base) always_merger.merge(result, next) Authoring your own Mergers ========================== The :class:`deepmerge.merger.Merger` class enacts the merging strategy, and stores the configuration about the merging strategy chosen. The merger takes a list of a combination of strings or functions, which are expanded into strategies that are attempted in the order in the list. For example, a list of ["append", "merge"] will attempt the "append" strategy first, and attempt the merge strategy if append is not able to merge the structures. If none of the strategies were able to merge the structures (or if non exists), a :py:exc:`deepmerge.exception.InvalidMerge` exception is raised. ---------- Strategies ---------- The merger class alone does not make any decisions around merging the code. This is instead deferred to the strategies themselves. Built-in Strategies =================== If you name a strategy with a string, it will attempt to match that with the merge strategies that are built into deepmerge. You can see a list of which strategies exist for which types at :doc:`./strategies` Custom Strategies ================= Strategies are functions that satisfy the following properties: * have the function signature (config, path, base, nxt) * return the merged object, or None. Example: .. code-block:: python def append_last_element(config, path, base, nxt): """ a list strategy to append the last element of nxt only. """ if len(nxt) > 0: base.append(nxt[-1]) return base If a strategy fails, an exception should not be raised. This is to ensure it can be chained with other strategies, or the fall-back. python-deepmerge-0.0.5/docs/index.rst000066400000000000000000000033021375132773400175730ustar00rootroot00000000000000.. deepmerge documentation master file, created by sphinx-quickstart on Sun Nov 20 11:31:44 2016. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Deepmerge: merging nested data structures ========================================= Deepmerge is a flexible library to handle merging of nested data structures in Python (e.g. lists, dicts). It is available on `pypi `_, and can be installed via pip: .. code-block:: bash pip install deepmerge ------- Example ------- **Generic Strategy** .. code-block:: python from deepmerge import always_merger base = {"foo": ["bar"]} next = {"foo": ["baz"]} expected_result = {'foo': ['bar', 'baz']} result = always_merger.merge(base, next) assert expected_result == result **Custom Strategy** .. code-block:: python from deepmerge import Merger my_merger = Merger( # pass in a list of tuple, with the # strategies you are looking to apply # to each type. [ (list, ["append"]), (dict, ["merge"]) ], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"] ) base = {"foo": ["bar"]} next = {"bar": "baz"} my_merger.merge(base, next) assert base == {"foo": ["bar"], "bar": "baz"} Want to get started? see the :doc:`./guide` Contents: .. toctree:: :maxdepth: 2 guide strategies api Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-deepmerge-0.0.5/docs/strategies.rst000066400000000000000000000024021375132773400206360ustar00rootroot00000000000000========== Strategies ========== Authoring your own Strategy =========================== Your function should take the arguments of (``merger``, ``path``, ``base_value``, ``value_to_merge_in``). Strategies are passed as a list, and the merge runs through each strategy in the order passed into the merger, stopping at the first one to return a value that is not the sentinel value deepmerge.STRATEGY_END. For example, this function would not be considered valid for any base value besides the string "foo": .. code-block:: python from deepmerge import STRATEGY_END def return_true_if_foo(config, path, base, nxt): if base == "foo": return True return STRATEGY_END Note that the merger does not copy values before passing them into mergers for performance reasons. Builtin Strategies =========================== These are the built in strategies provided by deepmerge. .. autoclass:: deepmerge.strategy.type_conflict.TypeConflictStrategies :members: :undoc-members: .. autoclass:: deepmerge.strategy.fallback.FallbackStrategies :members: :undoc-members: .. autoclass:: deepmerge.strategy.dict.DictStrategies :members: :undoc-members: .. autoclass:: deepmerge.strategy.list.ListStrategies :members: :undoc-members: python-deepmerge-0.0.5/setup.py000066400000000000000000000022711375132773400165200ustar00rootroot00000000000000#!/usr/bin/env python import os import sys is_release = False if "--release" in sys.argv: sys.argv.remove("--release") is_release = True from setuptools import setup, find_packages base = os.path.dirname(os.path.abspath(__file__)) README_PATH = os.path.join(base, "README.rst") install_requires = [ ] tests_require = [] setup(name='deepmerge', setup_requires=["vcver"], vcver={"is_release": is_release, "path": base}, description='a toolset to deeply merge python dictionaries.', long_description=open(README_PATH).read(), author='Yusuke Tsutsumi', author_email='yusuke@tsutsumi.io', url='http://deepmerge.readthedocs.io/en/latest/', packages=find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 3 - Alpha', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Topic :: System :: Software Distribution', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', ], tests_require=tests_require ) python-deepmerge-0.0.5/ubuild.py000066400000000000000000000021071375132773400166420ustar00rootroot00000000000000import os import subprocess def main(build): build.packages.install(".", develop=True) def test(build): main(build) build.packages.install("pytest") build.packages.install("pytest-cov") pytest = os.path.join(build.root, "bin", "py.test") subprocess.call( [ pytest, "--cov", "deepmerge", "deepmerge/tests", "--cov-report", "term-missing", ] + build.options.args ) def publish(build): """ distribute the uranium package """ build.packages.install("wheel") build.packages.install("twine") # to use keyring build.packages.install("keyring") build.packages.install("python3-dbus") build.executables.run( ["python", "setup.py", "sdist", "bdist_wheel", "--universal", "--release"] ) build.executables.run(["twine", "upload", "dist/*"]) def build_docs(build): build.packages.install("sphinx") build.packages.install("sphinx_rtd_theme") return subprocess.call(["make", "html"], cwd=os.path.join(build.root, "docs")) python-deepmerge-0.0.5/uranium000077500000000000000000000032771375132773400164230ustar00rootroot00000000000000#!/usr/bin/env python # warmup should be added into everyone's root level repository. warmup will: # * download and set up a virtualenv # * install uranium # * run uranium import os ROOT = os.path.dirname(__file__) URANIUM_PATH = os.getenv('URANIUM_PATH', None) URANIUM_GITHUB_ACCOUNT = os.getenv('URANIUM_GITHUB_ACCOUNT', 'toumorokoshi') URANIUM_GITHUB_BRANCH = os.getenv('URANIUM_GITHUB_BRANCH', 'master') URANIUM_STANDALONE_URL = "https://raw.githubusercontent.com/{account}/uranium/{branch}/uranium/scripts/uranium_standalone".format(account=URANIUM_GITHUB_ACCOUNT, branch=URANIUM_GITHUB_BRANCH) CACHE_DIRECTORY = os.path.join(ROOT, ".uranium") CACHED_URANIUM_STANDALONE = os.path.join(CACHE_DIRECTORY, "uranium_standalone") def get_cached_standalone(): if not os.path.isfile(CACHED_URANIUM_STANDALONE): return None with open(CACHED_URANIUM_STANDALONE) as fh: return fh.read() def store_cached_standalone(body): if not os.path.exists(CACHE_DIRECTORY): os.makedirs(CACHE_DIRECTORY) with open(CACHED_URANIUM_STANDALONE, "wb+") as fh: fh.write(body) cached_standalone = get_cached_standalone() if URANIUM_PATH is not None: print("Executing uranium from " + URANIUM_PATH) execfile(os.path.realpath(URANIUM_PATH)) elif cached_standalone is not None: exec(cached_standalone) else: print("Downloading uranium from " + URANIUM_STANDALONE_URL) try: from urllib2 import urlopen as urlopen except: from urllib.request import urlopen as urlopen print("loading uranium bootstrapper...") body = urlopen(URANIUM_STANDALONE_URL).read() print("caching standalone uranium script...") store_cached_standalone(body) exec(body)