├── README.md ├── .gitignore ├── tox.ini ├── docs ├── index.rst ├── Makefile └── conf.py ├── LICENSE ├── setup.py ├── test_classtools.py └── classtools.py /README.md: -------------------------------------------------------------------------------- 1 | # classtools 2 | 3 | Docs: http://classtools.readthedocs.org/en/latest/ 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | .*.sw* 4 | .coverage 5 | .tox 6 | /*.egg-info 7 | /docs/_build 8 | __pycache__ 9 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py34,pypy,pypy3 3 | 4 | [testenv] 5 | deps = 6 | pytest 7 | commands = 8 | py.test 9 | 10 | [testenv:docs] 11 | deps = sphinx 12 | commands = make -C docs html 13 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. classtools documentation master file, created by 2 | sphinx-quickstart2 on Thu Jan 8 19:09:17 2015. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | classtools 7 | ========== 8 | 9 | .. automodule:: classtools 10 | :members: 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright ©2017, Lexy "Eevee" Munroe 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 10 | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 11 | AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 12 | INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 13 | LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 14 | OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 15 | PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='classtools', 5 | version='0.1', 6 | description='A few class utilities the stdlib is missing.', 7 | url='https://github.com/eevee/classtools', 8 | author='Eevee', 9 | author_email='eevee.classtools@veekun.com', 10 | license='MIT', 11 | classifiers=[ 12 | 'Development Status :: 2 - Pre-Alpha', 13 | 'Intended Audience :: Developers', 14 | 'License :: OSI Approved :: ISC License (ISCL)', 15 | 'Programming Language :: Python :: 2', 16 | 'Programming Language :: Python :: 2.6', 17 | 'Programming Language :: Python :: 2.7', 18 | 'Programming Language :: Python :: 3', 19 | 'Programming Language :: Python :: 3.2', 20 | 'Programming Language :: Python :: 3.3', 21 | 'Programming Language :: Python :: 3.4', 22 | ], 23 | keywords='class development', 24 | py_modules=['classtools'], 25 | tests_require=['pytest'], 26 | ) 27 | -------------------------------------------------------------------------------- /test_classtools.py: -------------------------------------------------------------------------------- 1 | import gc 2 | 3 | import pytest 4 | 5 | from classtools import classproperty 6 | from classtools import frozenproperty 7 | from classtools import keyed_ordering 8 | from classtools import reify 9 | from classtools import weakattr 10 | 11 | 12 | def test_classproperty(): 13 | class Square(object): 14 | @classproperty 15 | def num_sides(cls): 16 | return 4 17 | 18 | assert Square.num_sides == 4 19 | assert Square().num_sides == 4 20 | 21 | # Should always get the class as an argument 22 | class Reflector(object): 23 | @classproperty 24 | def me(cls): 25 | return cls 26 | 27 | assert Reflector.me is Reflector 28 | assert Reflector().me is Reflector 29 | 30 | 31 | def test_reify(): 32 | class Lazy(object): 33 | @reify 34 | def attr(self): 35 | return [] 36 | 37 | assert isinstance(Lazy.attr, reify) 38 | 39 | lazy = Lazy() 40 | value = lazy.attr 41 | assert value == [] 42 | assert lazy.attr is value 43 | lazy.attr.append(3) 44 | assert lazy.attr == [3] 45 | del lazy.attr 46 | assert lazy.attr == [] 47 | assert value == [3] 48 | assert lazy.attr is not value 49 | 50 | 51 | def test_weakattr(): 52 | class Foo(object): 53 | bar = weakattr('bar') 54 | 55 | def __init__(self, bar): 56 | self.bar = bar 57 | 58 | class Dummy(object): 59 | pass 60 | 61 | assert isinstance(Foo.bar, weakattr) 62 | 63 | obj = Dummy() 64 | foo = Foo(obj) 65 | assert foo.bar is obj 66 | del foo.bar 67 | assert foo.bar is None 68 | 69 | foo = Foo(obj) 70 | assert foo.bar is obj 71 | del obj 72 | # PyPy reserves the right to delete objects whenever; encourage it 73 | gc.collect() 74 | assert foo.bar is None 75 | 76 | 77 | def test_frozenproperty(): 78 | class Cat(object): 79 | @frozenproperty 80 | def num_legs(self): 81 | return 2 + 2 82 | 83 | assert isinstance(Cat.num_legs, frozenproperty) 84 | 85 | cat = Cat() 86 | assert cat.num_legs == 4 87 | cat.num_legs = 5 88 | assert cat.num_legs == 5 89 | 90 | 91 | def test_keyed_ordering(): 92 | @keyed_ordering 93 | class NeedlesslyComplicatedPoint(object): 94 | def __init__(self, x, y): 95 | self.x = x 96 | self.y = y 97 | 98 | def __key__(self): 99 | return (self.x, self.y) 100 | 101 | p = NeedlesslyComplicatedPoint(1, 3) 102 | q = NeedlesslyComplicatedPoint(2, 0) 103 | 104 | assert p == p 105 | assert q == q 106 | assert p != q 107 | assert q != p 108 | 109 | assert p < q 110 | assert p <= q 111 | assert p <= p 112 | 113 | assert q > p 114 | assert q >= p 115 | assert q >= q 116 | 117 | assert p != (p.x, p.y) 118 | 119 | @keyed_ordering 120 | class PartiallyOrderedClass(object): 121 | def __init__(self, attr): 122 | self.attr = attr 123 | 124 | def __eq__(self, other): 125 | return True 126 | 127 | def __key__(self): 128 | return self.attr 129 | 130 | # TODO seems useful to have something to fill in __ne__ for you, without 131 | # needing __key__. maybe a @partial_ordering, that only fills in the 132 | # methods it can? (or, even better, does it perl-style?) 133 | # TODO also, no way to extend this to allow comparisons with other classes 134 | # atm 135 | a = PartiallyOrderedClass(1) 136 | b = PartiallyOrderedClass(2) 137 | 138 | assert a == b 139 | assert b == a 140 | assert a == 5 141 | assert a != b 142 | assert b != a 143 | assert a < b 144 | 145 | with pytest.raises(TypeError): 146 | @keyed_ordering 147 | class NoKeyMethod(object): 148 | pass 149 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build2 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build2 11 | ifeq ($(shell which $(SPHINXBUILD) >/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) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 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 " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/classtools.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/classtools.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/classtools" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/classtools" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # classtools documentation build configuration file, created by 4 | # sphinx-quickstart2 on Thu Jan 8 19:09:17 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 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | sys.path.insert(0, os.path.abspath('..')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | ] 34 | 35 | # Add any paths that contain templates here, relative to this directory. 36 | templates_path = ['_templates'] 37 | 38 | # The suffix of source filenames. 39 | source_suffix = '.rst' 40 | 41 | # The encoding of source files. 42 | #source_encoding = 'utf-8-sig' 43 | 44 | # The master toctree document. 45 | master_doc = 'index' 46 | 47 | # General information about the project. 48 | project = u'classtools' 49 | copyright = u'2015, Eevee' 50 | 51 | # The version info for the project you're documenting, acts as replacement for 52 | # |version| and |release|, also used in various other places throughout the 53 | # built documents. 54 | # 55 | # The short X.Y version. 56 | version = '0.1' 57 | # The full version, including alpha/beta/rc tags. 58 | release = '0.1' 59 | 60 | # The language for content autogenerated by Sphinx. Refer to documentation 61 | # for a list of supported languages. 62 | #language = None 63 | 64 | # There are two options for replacing |today|: either, you set today to some 65 | # non-false value, then it is used: 66 | #today = '' 67 | # Else, today_fmt is used as the format for a strftime call. 68 | #today_fmt = '%B %d, %Y' 69 | 70 | # List of patterns, relative to source directory, that match files and 71 | # directories to ignore when looking for source files. 72 | exclude_patterns = ['_build'] 73 | 74 | # The reST default role (used for this markup: `text`) to use for all 75 | # documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output ---------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # Add any extra paths that contain custom files (such as robots.txt or 135 | # .htaccess) here, relative to this directory. These files are copied 136 | # directly to the root of the documentation. 137 | #html_extra_path = [] 138 | 139 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 140 | # using the given strftime format. 141 | #html_last_updated_fmt = '%b %d, %Y' 142 | 143 | # If true, SmartyPants will be used to convert quotes and dashes to 144 | # typographically correct entities. 145 | #html_use_smartypants = True 146 | 147 | # Custom sidebar templates, maps document names to template names. 148 | #html_sidebars = {} 149 | 150 | # Additional templates that should be rendered to pages, maps page names to 151 | # template names. 152 | #html_additional_pages = {} 153 | 154 | # If false, no module index is generated. 155 | #html_domain_indices = True 156 | 157 | # If false, no index is generated. 158 | #html_use_index = True 159 | 160 | # If true, the index is split into individual pages for each letter. 161 | #html_split_index = False 162 | 163 | # If true, links to the reST sources are added to the pages. 164 | #html_show_sourcelink = True 165 | 166 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 167 | #html_show_sphinx = True 168 | 169 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 170 | #html_show_copyright = True 171 | 172 | # If true, an OpenSearch description file will be output, and all pages will 173 | # contain a tag referring to it. The value of this option must be the 174 | # base URL from which the finished HTML is served. 175 | #html_use_opensearch = '' 176 | 177 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 178 | #html_file_suffix = None 179 | 180 | # Output file base name for HTML help builder. 181 | htmlhelp_basename = 'classtoolsdoc' 182 | 183 | 184 | # -- Options for LaTeX output --------------------------------------------- 185 | 186 | latex_elements = { 187 | # The paper size ('letterpaper' or 'a4paper'). 188 | #'papersize': 'letterpaper', 189 | 190 | # The font size ('10pt', '11pt' or '12pt'). 191 | #'pointsize': '10pt', 192 | 193 | # Additional stuff for the LaTeX preamble. 194 | #'preamble': '', 195 | } 196 | 197 | # Grouping the document tree into LaTeX files. List of tuples 198 | # (source start file, target name, title, 199 | # author, documentclass [howto, manual, or own class]). 200 | latex_documents = [ 201 | ('index', 'classtools.tex', u'classtools Documentation', 202 | u'Eevee', 'manual'), 203 | ] 204 | 205 | # The name of an image file (relative to this directory) to place at the top of 206 | # the title page. 207 | #latex_logo = None 208 | 209 | # For "manual" documents, if this is true, then toplevel headings are parts, 210 | # not chapters. 211 | #latex_use_parts = False 212 | 213 | # If true, show page references after internal links. 214 | #latex_show_pagerefs = False 215 | 216 | # If true, show URL addresses after external links. 217 | #latex_show_urls = False 218 | 219 | # Documents to append as an appendix to all manuals. 220 | #latex_appendices = [] 221 | 222 | # If false, no module index is generated. 223 | #latex_domain_indices = True 224 | 225 | 226 | # -- Options for manual page output --------------------------------------- 227 | 228 | # One entry per manual page. List of tuples 229 | # (source start file, name, description, authors, manual section). 230 | man_pages = [ 231 | ('index', 'classtools', u'classtools Documentation', 232 | [u'Eevee'], 1) 233 | ] 234 | 235 | # If true, show URL addresses after external links. 236 | #man_show_urls = False 237 | 238 | 239 | # -- Options for Texinfo output ------------------------------------------- 240 | 241 | # Grouping the document tree into Texinfo files. List of tuples 242 | # (source start file, target name, title, author, 243 | # dir menu entry, description, category) 244 | texinfo_documents = [ 245 | ('index', 'classtools', u'classtools Documentation', 246 | u'Eevee', 'classtools', 'One line description of project.', 247 | 'Miscellaneous'), 248 | ] 249 | 250 | # Documents to append as an appendix to all manuals. 251 | #texinfo_appendices = [] 252 | 253 | # If false, no module index is generated. 254 | #texinfo_domain_indices = True 255 | 256 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 257 | #texinfo_show_urls = 'footnote' 258 | 259 | # If true, do not generate a @detailmenu in the "Top" node's menu. 260 | #texinfo_no_detailmenu = False 261 | -------------------------------------------------------------------------------- /classtools.py: -------------------------------------------------------------------------------- 1 | """Collection of small class-related utilities that will hopefully save you a 2 | tiny bit of grief, in the vein of itertools and functools. 3 | """ 4 | import operator 5 | import weakref 6 | 7 | 8 | class classproperty(object): 9 | """Method decorator similar to ``@property``, but called like a 10 | ``classmethod``. 11 | 12 | .. code-block:: python 13 | 14 | class Square(object): 15 | @classproperty 16 | def num_sides(cls): 17 | return 4 18 | 19 | Setting and deleting are not supported, due to the design of the descriptor 20 | protocol. If you need a class property you can set or delete, you need to 21 | create a metaclass and put a regular ``@property`` on it. 22 | 23 | This decorator is of questionable use for normal classes, but may be 24 | helpful for "declarative" classes such as enums. 25 | """ 26 | def __init__(desc, fget, fset=None, fdel=None): 27 | desc.fget = fget 28 | desc.fset = fset 29 | desc.fdel = fdel 30 | try: 31 | desc.__doc__ = fget.__doc__ 32 | except Exception: # pragma: no cover 33 | pass 34 | 35 | def __get__(desc, self, cls): 36 | return desc.fget(cls) 37 | 38 | 39 | class reify(object): 40 | """Method decorator similar to ``@property``, except that after the wrapped 41 | method is called, its return value is stored in the instance dict, 42 | effectively replacing this decorator. The name means "to make real", 43 | because some value becomes a "real" instance attribute as soon as it's 44 | computed. 45 | 46 | The wrapped method is thus only called once at most, making this decorator 47 | particularly useful for lazy/delayed creation of resources, or expensive 48 | computations that will always have the same result but may not be needed at 49 | all. For example: 50 | 51 | .. code-block:: python 52 | 53 | class Resource(object): 54 | @reify 55 | def result(self): 56 | print('fetching result') 57 | return "foo" 58 | 59 | >>> r = Resource() 60 | >>> r.result 61 | fetching result 62 | 'foo' 63 | >>> r.result 64 | 'foo' 65 | >>> # result not called the second time, because r.result is now populated 66 | 67 | Because this is a "non-data descriptor", it's possible to set or delete the 68 | attribute: 69 | 70 | >>> r.result = "bar" 71 | >>> r.result 72 | 'bar' 73 | >>> del r.result 74 | >>> r.result 75 | fetching result 76 | 'foo' 77 | 78 | Deleting the attribute causes the wrapped method to be called again on the 79 | next read. While it's possible to take advantage of this to create a cache 80 | with manual eviction, the author strongly advises you not to think of this 81 | decorator as merely a caching mechanism. Strictly speaking, cache eviction 82 | should only ever affect performance, but consider the following: 83 | 84 | .. code-block:: python 85 | 86 | class Database(object): 87 | @reify 88 | def connection(self): 89 | return dbapi.connect(...) 90 | 91 | Here, ``reify`` is used as lazy initialization, and its return value is a 92 | (mutable!) handle to some external resource. That handle is not cached in 93 | any meaningful sense: its permanence is guaranteed by the class. Having it 94 | transparently evicted and recreated would not only destroy the illusion 95 | that it's a regular attribute, but completely break the class's semantics. 96 | """ 97 | def __init__(self, wrapped): 98 | self.wrapped = wrapped 99 | try: 100 | self.__doc__ = wrapped.__doc__ 101 | except Exception: # pragma: no cover 102 | pass 103 | 104 | def __get__(self, inst, objtype=None): 105 | if inst is None: 106 | return self 107 | val = self.wrapped(inst) 108 | setattr(inst, self.wrapped.__name__, val) 109 | return val 110 | 111 | 112 | class weakattr(object): 113 | """Descriptor that transparently wraps its stored value in a weak 114 | reference. Reading this attribute will never raise `AttributeError`; if 115 | the reference is broken or missing, you'll just get `None`. 116 | 117 | To use, create a ``weakattr`` in the class body and assign to it as normal. 118 | You must provide an attribute name, which is used to store the actual 119 | weakref in the instance dict. 120 | 121 | .. code-block:: python 122 | 123 | class Foo(object): 124 | bar = weakattr('bar') 125 | 126 | def __init__(self, bar): 127 | self.bar = bar 128 | 129 | >>> class Dummy(object): pass 130 | >>> obj = Dummy() 131 | >>> foo = Foo(obj) 132 | >>> assert foo.bar is obj 133 | >>> print(foo.bar) 134 | 135 | >>> del obj 136 | >>> print(foo.bar) 137 | None 138 | 139 | Of course, if you try to assign a value that can't be weak referenced, 140 | you'll get a ``TypeError``. So don't do that. In particular, a lot of 141 | built-in types can't be weakref'd! 142 | 143 | Note that due to the ``__dict__`` twiddling, this descriptor will never 144 | trigger ``__getattr__``, ``__setattr__``, or ``__delattr__``. 145 | """ 146 | def __init__(self, name): 147 | self.name = name 148 | 149 | def __get__(desc, self, cls): 150 | if self is None: 151 | return desc 152 | 153 | try: 154 | ref = self.__dict__[desc.name] 155 | except KeyError: 156 | return None 157 | else: 158 | value = ref() 159 | if value is None: 160 | # No sense leaving a dangling weakref around 161 | del self.__dict__[desc.name] 162 | return value 163 | 164 | def __set__(desc, self, value): 165 | self.__dict__[desc.name] = weakref.ref(value) 166 | 167 | def __delete__(desc, self): 168 | del self.__dict__[desc.name] 169 | 170 | 171 | class frozenproperty(object): 172 | """Similar to the built-in ``@property`` decorator, but without support for 173 | setters or deleters. This makes it a "non-data" descriptor, which you can 174 | overwrite directly. Compare: 175 | 176 | .. code-block:: python 177 | 178 | class Cat(object): 179 | @property 180 | def num_legs(self): 181 | return 2 + 2 182 | 183 | >>> cat = Cat() 184 | >>> cat.num_legs 185 | 4 186 | >>> cat.num_legs = 5 187 | ... 188 | AttributeError: can't set attribute 189 | 190 | Versus: 191 | 192 | .. code-block:: python 193 | 194 | class Cat(object): 195 | @frozenproperty 196 | def num_legs(self): 197 | return 2 + 2 198 | 199 | >>> cat = Cat() 200 | >>> cat.num_legs 201 | 4 202 | >>> cat.num_legs = 5 203 | >>> cat.num_legs 204 | 5 205 | """ 206 | def __init__(self, fget): 207 | self.fget = fget 208 | 209 | def __get__(desc, self, cls): 210 | if self is None: 211 | return desc 212 | 213 | return desc.fget(self) 214 | 215 | 216 | def _keyed_ordering_impl(opname, basecls): 217 | op = getattr(operator, opname) 218 | 219 | def method(self, other): 220 | if not isinstance(other, basecls): 221 | return NotImplemented 222 | 223 | return op(self.__key__(), other.__key__()) 224 | 225 | method.__name__ = opname 226 | return method 227 | 228 | 229 | def keyed_ordering(cls): 230 | """Class decorator to generate all six rich comparison methods, based on a 231 | ``__key__`` method. 232 | 233 | Many simple classes are wrappers for very simple data, and want to defer 234 | comparisons to that data. Rich comparison is very flexible and powerful, 235 | but makes this simple case tedious to set up. There's the standard 236 | library's ``total_ordering`` decorator, but it still requires you to write 237 | essentially the same method twice, and doesn't correctly handle 238 | ``NotImplemented`` before 3.4. It also doesn't automatically generate 239 | ``__ne__`` from ``__eq__``, which is a common gotcha. 240 | 241 | With this decorator, comparisons will be done on the return value of 242 | ``__key__``, in much the same way as the ``key`` argument to ``sorted``. 243 | For example, if you have a class representing a span of time: 244 | 245 | .. code-block:: python 246 | 247 | @keyed_ordering 248 | class TimeSpan(object): 249 | def __init__(self, start, end): 250 | self.start = start 251 | self.end = end 252 | 253 | def __key__(self): 254 | return (self.start, self.end) 255 | 256 | This is equivalent to the following, assuming 3.4's ``total_ordering``: 257 | 258 | .. code-block:: python 259 | 260 | @total_ordering 261 | class TimeSpan(object): 262 | def __init__(self, start, end): 263 | self.start = start 264 | self.end = end 265 | 266 | def __eq__(self, other): 267 | if not isinstance(other, TimeSpan): 268 | return NotImplemented 269 | return (self.start, self.end) == (other.start, other.end) 270 | 271 | def __ne__(self, other): 272 | if not isinstance(other, TimeSpan): 273 | return NotImplemented 274 | return (self.start, self.end) != (other.start, other.end) 275 | 276 | def __lt__(self, other): 277 | if not isinstance(other, TimeSpan): 278 | return NotImplemented 279 | return (self.start, self.end) < (other.start, other.end) 280 | 281 | The ``NotImplemented`` check is based on the class being decorated, so 282 | subclassses can still be correctly compared. 283 | 284 | You may also implement some of the rich comparison methods in the decorated 285 | class, in which case they'll be left alone. 286 | """ 287 | if '__key__' not in cls.__dict__: 288 | raise TypeError("keyed_ordering requires a __key__ method") 289 | 290 | for name in ('__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__'): 291 | if name in cls.__dict__: 292 | continue 293 | method = _keyed_ordering_impl(name, cls) 294 | setattr(cls, name, method) 295 | 296 | return cls 297 | --------------------------------------------------------------------------------