ericvsmith-toposort-36129704f0a7/.hg_archival.txt0000644000000000000000000000016713003527544017740 0ustar 00000000000000repo: 641ad0e3f272bba47558e955319884471ce5e009 node: 36129704f0a7dbed9986b1b02f750c5e21e634e1 branch: default tag: 1.5 ericvsmith-toposort-36129704f0a7/.hgignore0000644000000000000000000000005013003527544016444 0ustar 00000000000000syntax: glob *.pyc dist build MANIFEST ericvsmith-toposort-36129704f0a7/.hgtags0000644000000000000000000000075713003527544016135 0ustar 00000000000000c82a59dca8a15e7f20960017b4a5ea6f463e451f 0.1 f1490e52efd9d3f8ce005c8bbb7007d2ea39864f 0.2 5ed2a40a608c6b034062e33459da4991b18abcf8 1.0 c335d14368a591c2818f06f88ce4b748c78815f1 1.1 c335d14368a591c2818f06f88ce4b748c78815f1 1.1 10cbe9dd923d280599ba6ae64f05db4c06333a62 1.1 63aab3edfecbf0232ba352dc70c1a38cd3f6c731 1.2 63aab3edfecbf0232ba352dc70c1a38cd3f6c731 1.2 f4d510c1e885f3aed6ab3a81cd6f6e4d8b423eb8 1.2 b3f4f29c2685aad55c47a37cbc9c040536a2a57f 1.3 9ef748788b05917300364bb339f6f779487f6a6b 1.4 ericvsmith-toposort-36129704f0a7/CHANGES.txt0000644000000000000000000000305313003527544016460 0ustar 00000000000000Change log ========== 1.5 2016-10-24 Eric V. Smith ---------------------------- * When a circular dependency error is detected, raise a specific exception, CircularDependencyError, which is a subclass of ValueError. The 'data' attribute of the exception will contain the data involved in the circular dependency (issue #2). Thanks lilydjwg for the initial patch. * To make building wheels easier, always require setuptools in setup.py (issue #5). * Mark wheel as being universal, that is, supporting both Python 2.7 and 3.x (issue #7). 1.4 2015-05-16 Eric V. Smith ---------------------------- * Removed 'test' package, so it won't get installed by bdist_*. It's still included in sdists. * No code changes. 1.3 2015-05-15 Eric V. Smith ---------------------------- * Fixed change log date. * No code changes. 1.2 2015-05-15 Eric V. Smith ---------------------------- * Changed RPM name to python3-toposort if running with python 3. * No code changes. 1.1 2014-07-24 Eric V. Smith ---------------------------- * Release version 1.1. No code changes. * Add a README.txt entry on running the test suite. * Fix missing test/__init__.py in the sdist. 1.0 2014-03-14 Eric V. Smith ---------------------------- * Release version 1.0. The API is stable. * Add MANIFEST.in to MANIFEST.in, so that it is created in the sdist (issue #1). 0.2 2014-02-11 Eric V. Smith ---------------------------- * Modify setup.py to produce a RPM name of python-toposort for bdist_rpm. 0.1 2014-02-10 Eric V. Smith ---------------------------- * Initial release. ericvsmith-toposort-36129704f0a7/LICENSE.txt0000644000000000000000000002613613003527544016501 0ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ericvsmith-toposort-36129704f0a7/MANIFEST.in0000644000000000000000000000006213003527544016402 0ustar 00000000000000include NOTICE *.txt MANIFEST.in test/__init__.py ericvsmith-toposort-36129704f0a7/NOTICE0000644000000000000000000000106113003527544015550 0ustar 00000000000000Copyright 2014 True Blade Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ericvsmith-toposort-36129704f0a7/README.txt0000644000000000000000000000653013003527544016350 0ustar 00000000000000======== toposort ======== Overview ======== Implements a topological sort algorithm. From `Wikipedia `_: In computer science, a topological sort (sometimes abbreviated topsort or toposort) or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. Input data description ====================== The input to the toposort function is a dict describing the dependencies among the input nodes. Each key is a dependent node, the corresponding value is a set containing the dependent nodes. Note that toposort does not care what the input node values mean: it just compares them for equality. The examples here usually use integers, but they could be any hashable type. Typical usage ============= The interpretation of the input data here is: If 2 depends on 11; 9 depends on 11, 8 and 10; 10 depends on 11 and 3 (and so on), then in what order should we process the items such that all nodes are processed before any of their dependencies?:: >>> from toposort import toposort, toposort_flatten >>> list(toposort({2: {11}, ... 9: {11, 8, 10}, ... 10: {11, 3}, ... 11: {7, 5}, ... 8: {7, 3}, ... })) [{3, 5, 7}, {8, 11}, {2, 10}, {9}] And the answer is: process 3, 5, and 7 (in any order); then process 8 and 11; then process 2 and 10; then process 9. Note that 3, 5, and 7 are returned first because they do not depend on anything. They are then removed from consideration, and then 8 and 11 don't depend on anything remaining. This process continues until all nodes are returned, or a circular dependency is detected. Circular dependencies ===================== A circular dependency will raise a CyclicDependencyError, which is derived from ValueError. Here 1 depends on 2, and 2 depends on 1:: >>> list(toposort({1: {2}, ... 2: {1}, ... })) Traceback (most recent call last): ... toposort.CircularDependencyError: Circular dependencies exist among these items: {1:{2}, 2:{1}} In addition, the 'data' attribute of the raised CyclicDependencyError will contain a dict containing the subset of the input data involved in the circular dependency. Module contents =============== ``toposort(data)`` Returns an iterator describing the dependencies among nodes in the input data. Each returned item will be a set. Each member of this set has no dependencies in this set, or in any set previously returned. ``toposort_flatten(data, sort=True)`` Like toposort(data), except that it returns a list of all of the depend values, in order. If sort is true, the returned nodes are sorted within each group before they are appended to the result:: >>> toposort_flatten({2: {11}, ... 9: {11, 8, 10}, ... 10: {11, 3}, ... 11: {7, 5}, ... 8: {7, 3}, ... }) [3, 5, 7, 8, 11, 2, 10, 9] Note that this result is the same as the first example: ``[{3, 5, 7}, {8, 11}, {2, 10}, {9}]``, except that the result is flattened, and within each set the nodes are sorted. Testing ======= To test, run 'python setup.py test'. On python >= 3.0, this also runs the doctests. ericvsmith-toposort-36129704f0a7/setup.cfg0000644000000000000000000000003213003527544016462 0ustar 00000000000000[bdist_wheel] universal=1 ericvsmith-toposort-36129704f0a7/setup.py0000644000000000000000000000343313003527544016363 0ustar 00000000000000from __future__ import print_function from setuptools import setup, Command # run our tests class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys, subprocess tests = [('test suite', ['-m', 'test.test_toposort']), ] if sys.hexversion >= 0x03000000: # Skip doctests for python < 3.0. They use set literal reprs, which # are different in 2.7. Testing under 3.x is good enough. tests.append(('doctests', ['-m' 'doctest', 'README.txt'])) for name, cmds in tests: print(name) errno = subprocess.call([sys.executable] + cmds) if errno != 0: raise SystemExit(errno) print('test complete') setup(name='toposort', version='1.5', url='https://bitbucket.org/ericvsmith/toposort', author='Eric V. Smith', author_email='eric@trueblade.com', description='Implements a topological sort algorithm.', long_description=open('README.txt').read() + '\n' + open('CHANGES.txt').read(), classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='Apache License Version 2.0', py_modules=['toposort'], cmdclass = {'test': PyTest}, ) ericvsmith-toposort-36129704f0a7/test/__init__.py0000644000000000000000000000000013003527544017724 0ustar 00000000000000ericvsmith-toposort-36129704f0a7/test/test_toposort.py0000644000000000000000000001641013003527544021131 0ustar 00000000000000####################################################################### # Tests for toposort module. # # Copyright 2014 True Blade Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Notes: # ######################################################################## import unittest from toposort import toposort, toposort_flatten, CircularDependencyError class TestCase(unittest.TestCase): def test_simple(self): self.assertEqual(list(toposort({2: {11}, 9: {11, 8}, 10: {11, 3}, 11: {7, 5}, 8: {7, 3}, })), [{3, 5, 7}, {8, 11}, {2, 9, 10}, ]) # make sure self dependencies are ignored self.assertEqual(list(toposort({2: {2, 11}, 9: {11, 8}, 10: {10, 11, 3}, 11: {7, 5}, 8: {7, 3}, })), [{3, 5, 7}, {8, 11}, {2, 9, 10}, ]) self.assertEqual(list(toposort({1: set()})), [{1}]) self.assertEqual(list(toposort({1: {1}})), [{1}]) def test_no_dependencies(self): self.assertEqual(list(toposort({1: {2}, 3: {4}, 5: {6}, })), [{2, 4, 6}, {1, 3, 5}]) self.assertEqual(list(toposort({1: set(), 3: set(), 5: set(), })), [{1, 3, 5}]) def test_empty(self): self.assertEqual(list(toposort({})), []) def test_strings(self): self.assertEqual(list(toposort({'2': {'11'}, '9': {'11', '8'}, '10': {'11', '3'}, '11': {'7', '5'}, '8': {'7', '3'}, })), [{'3', '5', '7'}, {'8', '11'}, {'2', '9', '10'}, ]) def test_objects(self): o2 = object() o3 = object() o5 = object() o7 = object() o8 = object() o9 = object() o10 = object() o11 = object() self.assertEqual(list(toposort({o2: {o11}, o9: {o11, o8}, o10: {o11, o3}, o11: {o7, o5}, o8: {o7, o3, o8}, })), [{o3, o5, o7}, {o8, o11}, {o2, o9, o10}, ]) def test_cycle(self): # a simple, 2 element cycle # make sure we can catch this both as ValueError and CircularDependencyError self.assertRaises(ValueError, list, toposort({1: {2}, 2: {1} })) with self.assertRaises(CircularDependencyError) as ex: list(toposort({1: {2}, 2: {1} })) self.assertEqual(ex.exception.data, {1: {2}, 2: {1}}) # an indirect cycle self.assertRaises(ValueError, list, toposort({1: {2}, 2: {3}, 3: {1}, })) with self.assertRaises(CircularDependencyError) as ex: list(toposort({1: {2}, 2: {3}, 3: {1}, })) self.assertEqual(ex.exception.data, {1: {2}, 2: {3}, 3: {1}}) # not all elements involved in a cycle with self.assertRaises(CircularDependencyError) as ex: list(toposort({1: {2}, 2: {3}, 3: {1}, 5: {4}, 4: {6}, })) self.assertEqual(ex.exception.data, {1: set([2]), 2: set([3]), 3: set([1])}) def test_input_not_modified(self): data = {2: {11}, 9: {11, 8}, 10: {11, 3}, 11: {7, 5}, 8: {7, 3, 8}, # includes something self-referential } orig = data.copy() results = list(toposort(data)) self.assertEqual(data, orig) def test_input_not_modified_when_cycle_error(self): data = {1: {2}, 2: {1}, 3: {4}, } orig = data.copy() self.assertRaises(ValueError, list, toposort(data)) self.assertEqual(data, orig) class TestCaseAll(unittest.TestCase): def test_sort_flatten(self): data = {2: {11}, 9: {11, 8}, 10: {11, 3}, 11: {7, 5}, 8: {7, 3, 8}, # includes something self-referential } expected = [{3, 5, 7}, {8, 11}, {2, 9, 10}] self.assertEqual(list(toposort(data)), expected) # now check the sorted results results = [] for item in expected: results.extend(sorted(item)) self.assertEqual(toposort_flatten(data), results) # and the unsorted results. break the results up into groups to compare them actual = toposort_flatten(data, False) results = [{i for i in actual[0:3]}, {i for i in actual[3:5]}, {i for i in actual[5:8]}] self.assertEqual(results, expected) class TestAll(unittest.TestCase): def test_all(self): import toposort # check that __all__ in the module contains everything that should be # public, and only those symbols all = set(toposort.__all__) # check that things in __all__ only appear once self.assertEqual(len(all), len(toposort.__all__), 'some symbols appear more than once in __all__') # get the list of public symbols found = set(name for name in dir(toposort) if not name.startswith('_')) # make sure it matches __all__ self.assertEqual(all, found) unittest.main() ericvsmith-toposort-36129704f0a7/toposort.py0000644000000000000000000000661313003527544017117 0ustar 00000000000000####################################################################### # Implements a topological sort algorithm. # # Copyright 2014 True Blade Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Notes: # Based on http://code.activestate.com/recipes/578272-topological-sort # with these major changes: # Added unittests. # Deleted doctests (maybe not the best idea in the world, but it cleans # up the docstring). # Moved functools import to the top of the file. # Changed assert to a ValueError. # Changed iter[items|keys] to [items|keys], for python 3 # compatibility. I don't think it matters for python 2 these are # now lists instead of iterables. # Copy the input so as to leave it unmodified. # Renamed function from toposort2 to toposort. # Handle empty input. # Switch tests to use set literals. # ######################################################################## from functools import reduce as _reduce __all__ = ['toposort', 'toposort_flatten', 'CircularDependencyError'] class CircularDependencyError(ValueError): def __init__(self, data): # Sort the data just to make the output consistent, for use in # error messages. That's convenient for doctests. s = 'Circular dependencies exist among these items: {{{}}}'.format(', '.join('{!r}:{!r}'.format(key, value) for key, value in sorted(data.items()))) super(CircularDependencyError, self).__init__(s) self.data = data def toposort(data): """Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items. Output is a list of sets in topological order. The first set consists of items with no dependences, each subsequent set consists of items that depend upon items in the preceeding sets. """ # Special case empty input. if len(data) == 0: return # Copy the input so as to leave it unmodified. data = data.copy() # Ignore self dependencies. for k, v in data.items(): v.discard(k) # Find all items that don't depend on anything. extra_items_in_deps = _reduce(set.union, data.values()) - set(data.keys()) # Add empty dependences where needed. data.update({item:set() for item in extra_items_in_deps}) while True: ordered = set(item for item, dep in data.items() if len(dep) == 0) if not ordered: break yield ordered data = {item: (dep - ordered) for item, dep in data.items() if item not in ordered} if len(data) != 0: raise CircularDependencyError(data) def toposort_flatten(data, sort=True): """Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic).""" result = [] for d in toposort(data): result.extend((sorted if sort else list)(d)) return result