padme-1.1.1/0000755000175000017500000000000012475560703012557 5ustar zygazyga00000000000000padme-1.1.1/PKG-INFO0000644000175000017500000000637312475560703013665 0ustar zygazyga00000000000000Metadata-Version: 1.1 Name: padme Version: 1.1.1 Summary: Padme is a mostly transparent proxy class for Python Home-page: https://github.com/zyga/padme Author: Zygmunt Krynicki Author-email: me@zygoon.pl License: LGPLv3 Description: =================================================== Padme - a mostly transparent proxy class for Python =================================================== .. image:: https://badge.fury.io/py/padme.png :target: http://badge.fury.io/py/padme .. image:: https://travis-ci.org/zyga/padme.png?branch=master :target: https://travis-ci.org/zyga/padme .. image:: https://pypip.in/d/padme/badge.png :target: https://pypi.python.org/pypi/padme Features ======== * Free software: LGPLv3 license * Support for Python 2.7 and Python 3.2+ * Documentation: https://padme.readthedocs.org. * Create proxy classes for any object with :class:`padme.proxy`. * Redirect particular methods in subclasses using :class:`padme.unproxied`. History ======= 1.1.1 (2015-03-04) ------------------ * Add general support for **Python 2.7**. * All numeric methods are now supported with some methods exclusive to Python 2.x (``__div__()``, ``__coerce__()``, ``__oct__()``, ``__hex__()``). * Add support for the new matrix multiplication operator ``@``. * Make ``__nonzero__()`` and ``__unicode__()`` exlusive to Python 2.x. * Make ``__bool__()`` and ``__bytes__()`` exclusive to Python 3.x. * Make ``__length_hint()`` exclusive to Python 3.4. * Add support for the ``__cmp__()`` method, exclusive to Python 2.x. * Add support for accessing the proxied object with the new :meth:`~padme.proxy.original()` function. * Add support for accessing proxy state with the new :meth:`~padme.proxy.state()` function. * De-couple proxy classes from proxied objects, much more lightweight proxy design is possible this way (less objects, lower cost to create each new proxy). 1.0 (2014-02-11) ---------------- * First release on PyPI. * Add a short introduction. * Enable travis-ci.org integration. * Remove numbering of generated meta-classes 2015 ---- * Released on PyPI as a part of plainbox as ``plainbox.impl.proxy`` Keywords: padme proxy Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy padme-1.1.1/AUTHORS.rst0000664000175000017500000000025412466710270014435 0ustar zygazyga00000000000000======= Credits ======= Development Lead ---------------- * Zygmunt Krynicki Contributors ------------ None yet. Why not be the first? padme-1.1.1/setup.py0000755000175000017500000000430512475560601014273 0ustar zygazyga00000000000000#!/usr/bin/env python # Copyright 2015 Canonical Ltd. # Written by: # Zygmunt Krynicki # # This file is part of Padme. # # Padme is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3, # as published by the Free Software Foundation. # # Padme is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Padme. If not, see . import sys try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='padme', version='1.1.1', description='Padme is a mostly transparent proxy class for Python', long_description=readme + '\n\n' + history, author='Zygmunt Krynicki', author_email='me@zygoon.pl', url='https://github.com/zyga/padme', packages=['padme'], package_dir={'padme': 'padme'}, include_package_data=True, license="LGPLv3", zip_safe=True, keywords='padme proxy', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', ('License :: OSI Approved :: GNU Lesser General Public License v3' ' (LGPLv3)'), 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], tests_require=([ 'unittest2' if sys.version_info[0] == 2 else 'unittest2py3k', 'mock'] if sys.version_info[:2] <= (3, 3) else None), test_suite='padme.tests', ) padme-1.1.1/docs/0000755000175000017500000000000012475560703013507 5ustar zygazyga00000000000000padme-1.1.1/docs/Makefile0000664000175000017500000001517112463652605015156 0ustar zygazyga00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(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/) endif # 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 clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 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 " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @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)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." 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." 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/complexity.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 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)." 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." 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." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 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)." 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." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." 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." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."padme-1.1.1/docs/index.rst0000664000175000017500000000076012466721717015361 0ustar zygazyga00000000000000.. complexity documentation master file, created by sphinx-quickstart on Tue Jul 9 22:26:36 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Padme's documentation! ================================= Contents: .. toctree:: :maxdepth: 2 readme installation usage contributing authors history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` padme-1.1.1/docs/contributing.rst0000644000175000017500000000004012463652605016742 0ustar zygazyga00000000000000.. include:: ../CONTRIBUTING.rstpadme-1.1.1/docs/readme.rst0000664000175000017500000000003212463652605015473 0ustar zygazyga00000000000000.. include:: ../README.rstpadme-1.1.1/docs/make.bat0000664000175000017500000001450212463652605015120 0ustar zygazyga00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "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. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over 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 goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :endpadme-1.1.1/docs/installation.rst0000644000175000017500000000027112466712122016734 0ustar zygazyga00000000000000============ Installation ============ At the command line:: $ easy_install padme Or, if you have virtualenvwrapper installed:: $ mkvirtualenv padme $ pip install padme padme-1.1.1/docs/authors.rst0000664000175000017500000000003312463652605015724 0ustar zygazyga00000000000000.. include:: ../AUTHORS.rstpadme-1.1.1/docs/usage.rst0000644000175000017500000000070212474637056015351 0ustar zygazyga00000000000000===== Usage ===== .. automodule:: padme Reference ========= .. autoclass:: padme.proxy :members: :inherited-members: Internals ========= .. autoclass:: padme.proxy_meta :special-members: :undoc-members: .. autofunction:: padme.make_typed_proxy_meta .. autoclass:: padme.proxy_base :members: :special-members: :undoc-members: .. autoclass:: padme.proxy_state :members: :special-members: :undoc-members: padme-1.1.1/docs/conf.py0000664000175000017500000002027212466710432015007 0ustar zygazyga00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # 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. import sys import os # 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. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import padme # -- 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 of source filenames. 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'padme' copyright = u'2014, Zygmunt Krynicki' # 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 = padme.__version__ # The full version, including alpha/beta/rc tags. release = padme.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #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. exclude_patterns = ['_build'] # 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 # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # 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. If None, it defaults to # " v documentation". #html_title = None # 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 (within the static path) to use as 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 = [] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # 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 # Output file base name for HTML help builder. htmlhelp_basename = 'padmedoc' # -- 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': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'padme.tex', u'Padme Documentation', u'Zygmunt Krynicki', '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 = [ ('index', 'padme', u'Padme Documentation', [u'Zygmunt Krynicki'], 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 = [ ('index', 'padme', u'Padme Documentation', u'Zygmunt Krynicki', 'padme', 'A mostly transparent proxy for Python', '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 padme-1.1.1/docs/history.rst0000664000175000017500000000003312463652605015740 0ustar zygazyga00000000000000.. include:: ../HISTORY.rstpadme-1.1.1/padme/0000755000175000017500000000000012475560703013645 5ustar zygazyga00000000000000padme-1.1.1/padme/tests.py0000644000175000017500000011421412475557056015373 0ustar zygazyga00000000000000# Copyright 2015 Canonical Ltd. # Written by: # Zygmunt Krynicki # # This file is part of Padme. # # Padme is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3, # as published by the Free Software Foundation. # # Padme is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Padme. If not, see . """ :mod:`padme.tests` -- tests for padme. ====================================== This package contains unit tests for padme. You don't want to use it directly and it can get changed at any time without notice. """ from __future__ import print_function, absolute_import, unicode_literals import doctest import operator import sys from padme import _logger from padme import proxy from padme import unproxied if sys.version_info[0:2] >= (3, 4): import unittest from unittest import mock else: import unittest2 as unittest import mock # https://code.google.com/p/mock/issues/detail?id=247 # or http://bugs.python.org/issue23569 if sys.version_info[0] == 3 and '__div__' in mock._all_magics: mock._magics.remove('__div__') mock._magics.remove('__rdiv__') mock._magics.remove('__idiv__') mock._all_magics.remove('__div__') mock._all_magics.remove('__rdiv__') mock._all_magics.remove('__idiv__') if sys.version_info[0] == 3 and '__truediv__' not in mock._all_magics: mock._magics.add('__truediv__') mock._magics.add('__rtruediv__') mock._magics.add('__itruediv__') mock._all_magics.add('__truediv__') mock._all_magics.add('__rtruediv__') mock._all_magics.add('__itruediv__') # http://bugs.python.org/issue23568 if '__rdivmod__' not in mock._magics: mock._magics.add('__rdivmod__') mock._all_magics.add('__rdivmod__') # http://bugs.python.org/issue23581 if 'matmul' not in mock.numerics: mock._magics.add('__matmul__') mock._magics.add('__rmatmul__') mock._magics.add('__imatmul__') mock._all_magics.add('__matmul__') mock._all_magics.add('__rmatmul__') mock._all_magics.add('__imatmul__') # XXX: Set to True for revelation reality_is_broken = False def load_tests(loader, tests, ignore): """ Load doctests for padme (part of unittest test discovery protocol). """ import padme tests.addTests( doctest.DocTestSuite(padme, optionflags=doctest.REPORT_NDIFF)) return tests def setUpModule(): """ Module-level setup function (part of unittest protocol). """ if reality_is_broken: import logging logging.basicConfig(level=logging.DEBUG) class proxy_as_function(unittest.TestCase): """ Tests for uses of proxy() as factory for proxy objects. """ def setUp(self): """ Per-test-case setup function. """ if reality_is_broken: print() _logger.debug("STARTING") _logger.debug("[%s]", self._testMethodName) self.obj = mock.MagicMock(name='obj') self.proxy = proxy(self.obj) def tearDown(self): """ Per-test-case teardown function. """ if reality_is_broken: _logger.debug("DONE") # NOTE: order of test methods matches implementation def test_repr(self): """ Verify that repr/__repr__ is redirected to the proxiee. """ self.assertEqual(repr(self.proxy), repr(self.obj)) self.assertEqual(self.proxy.__repr__(), repr(self.obj)) def test_str(self): """ Verify that str/__str__ is redirected to the proxiee. """ self.assertEqual(str(self.proxy), str(self.obj)) self.assertEqual(self.proxy.__str__(), str(self.obj)) @unittest.skipUnless(sys.version_info[0] == 3, "requires python 3") def test_bytes(self): """ Verify that bytes/__bytes__ is redirected to the proxiee. """ # NOTE: bytes() is unlike str() or repr() in that it is not a function # that converts an arbitrary object into a bytes object. We cannot # just call it on a random object. What we must do is implement # __bytes__() on a new class and use instances of that class. class C(object): def __bytes__(self): return b'good' self.obj = C() self.proxy = proxy(self.obj) self.assertEqual(bytes(self.proxy), bytes(self.obj)) self.assertEqual(self.proxy.__bytes__(), bytes(self.obj)) def test_format(self): """ Verify that format/__format__ is redirected to the proxiee. """ self.assertEqual(format(self.proxy), format(self.obj)) self.assertEqual(self.proxy.__format__(""), format(self.obj)) def test_lt(self): """ Verify that < /__lt__ is redirected to the proxiee. """ # NOTE: MagicMock is not ordered so let's just use an integer self.obj = 0 self.proxy = proxy(self.obj) self.assertLess(self.proxy, 1) self.assertLess(self.obj, 1) def test_le(self): """ Verify that <=/ __le__ is redirected to the proxiee. """ # NOTE: MagicMock is not ordered so let's just use an integer self.obj = 0 self.proxy = proxy(self.obj) self.assertLessEqual(self.proxy, 0) self.assertLessEqual(self.proxy, 1) self.assertLessEqual(self.obj, 0) self.assertLessEqual(self.obj, 1) def test_eq(self): """ Verify that == /__eq__ is redirected to the proxiee. """ self.assertEqual(self.proxy, self.obj) self.obj.__eq__.assert_called_once_with(self.obj) self.assertEqual(self.obj, self.obj) def test_ne(self): """ Verify that != /__ne__ is redirected to the proxiee. """ other = object() self.assertNotEqual(self.proxy, other) self.obj.__ne__.assert_called_once_with(other) self.assertNotEqual(self.obj, object()) def test_gt(self): """ Verify that > /__gt__ is redirected to the proxiee. """ # NOTE: MagicMock is not ordered so let's just use an integer self.obj = 0 self.proxy = proxy(self.obj) self.assertGreater(self.proxy, -1) self.assertGreater(self.obj, -1) def test_ge(self): """ Verify that >= /__ge__ is redirected to the proxiee. """ # NOTE: MagicMock is not ordered so let's just use an integer self.obj = 0 self.proxy = proxy(self.obj) self.assertGreaterEqual(self.proxy, 0) self.assertGreaterEqual(self.proxy, -1) self.assertGreaterEqual(self.obj, 0) self.assertGreaterEqual(self.obj, -1) @unittest.skipUnless(sys.version_info[0] == 2, "requires python 2") def test_cmp(self): """ Verify that cmp /__cmp__ is redirected to the proxiee. """ class C(object): def __cmp__(self, other): return -1 self.obj = C() self.proxy = proxy(self.obj) other = object() self.assertEqual(cmp(self.proxy, other), cmp(self.obj, other)) self.assertEqual(self.proxy.__cmp__(other), cmp(self.obj, other)) def test_hash(self): """ Verify that hash /__hash__ is redirected to the proxiee. """ self.assertEqual(hash(self.proxy), hash(self.obj)) self.assertEqual(self.proxy.__hash__(), hash(self.obj)) @unittest.skipUnless(sys.version_info[0] == 3, "requires python 3") def test_bool(self): """ Verify that bool /__bool__ is redirected to the proxiee. """ self.assertEqual(bool(self.proxy), bool(self.obj)) self.assertEqual(self.proxy.__bool__(), bool(self.obj)) @unittest.skipUnless(sys.version_info[0] == 2, "requires python 2") def test_nonzero(self): """ Verify that bool /__nonzero__ is redirected to the proxiee. """ self.assertEqual(bool(self.proxy), bool(self.obj)) self.assertEqual(self.proxy.__nonzero__(), bool(self.obj)) @unittest.skipUnless(sys.version_info[0] == 2, "requires python 2") def test_unicode(self): """ Verify that unicode /__unicode__ is redirected to the proxiee. """ self.assertEqual(unicode(self.proxy), unicode(self.obj)) self.assertEqual(self.proxy.__unicode__(), unicode(self.obj)) def test_attr_get(self): """ Verify that attribute reads are redirected to the proxiee. """ self.assertIs(self.proxy.attr, self.obj.attr) def test_attr_set(self): """ Verify that attribute writes are redirected to the proxiee. """ value = mock.Mock(name='value') self.proxy.attr = value self.assertIs(self.obj.attr, value) def test_attr_del(self): """ Verify that attribute deletes are redirected to the proxiee. """ del self.proxy.attr with self.assertRaises(AttributeError): self.obj.attr def test_dir(self): """ Verify that dir / __dir__ is redirected to the proxiee. """ self.assertEqual(dir(self.proxy), dir(self.obj)) self.assertEqual(self.proxy.__dir__(), dir(self.obj)) def test_descriptor_methods(self): """ Verify that __{get,set,delete}__ are redirected to the proxiee. """ property_proxy = proxy(property) class C(object): _ok = "default" @property_proxy def ok(self): return self._ok @ok.setter def ok(self, value): self._ok = value @ok.deleter def ok(self): del self._ok obj = C() self.assertEqual(obj._ok, "default") # __set__ assigns the new value obj.ok = True self.assertTrue(obj._ok) # __get__ returns the current value self.assertTrue(obj.ok) # __delete__ removes the current value del obj.ok self.assertEqual(obj._ok, "default") def test_call(self): """ Verify that __call__ is redirected to the proxiee. """ self.assertEqual(self.proxy(), self.obj()) self.assertEqual(self.proxy.__call__(), self.obj()) def test_len(self): """ Verify that len / __len__ is redirected to the proxiee. """ self.assertEqual(len(self.proxy), len(self.obj)) self.assertEqual(self.proxy.__len__(), len(self.obj)) @unittest.skipUnless(sys.version_info[0:2] >= (3, 4), "requires python 3.4") def test_length_hint(self): """ Verify that __length_hint__ is redirected to the proxiee. """ # NOTE: apparently MagicMock doesn't support this method class C(object): def __length_hint__(self): return 42 self.obj = C() self.proxy = proxy(self.obj) self.assertEqual( operator.length_hint(self.proxy), operator.length_hint(self.obj)) self.assertEqual( self.proxy.__length_hint__(), operator.length_hint(self.obj)) def test_getitem(self): """ Verify that [] / __getitem__ is redirected to the proxiee. """ self.assertEqual(self.proxy['item'], self.obj['item']) self.assertEqual(self.proxy.__getitem__('item'), self.obj['item']) def test_setitem_v1(self): """ Verify that []= is redirected to the proxiee. """ # NOTE: MagicMock doesn't store item assignment self.obj = ["old"] self.proxy = proxy(self.obj) self.proxy[0] = "new" self.assertEqual(self.obj[0], "new") def test_setitem_v2(self): """ Verify that __setitem__ is redirected to the proxiee. """ # NOTE: MagicMock doesn't store item assignment self.obj = ["old"] self.proxy = proxy(self.obj) self.proxy.__setitem__(0, "value") self.assertEqual(self.obj[0], "value") def test_delitem(self): """ Verify that del[] / __delitem__ is redirected to the proxiee. """ obj = {'k': 'v'} del proxy(obj)['k'] self.assertEqual(obj, {}) obj = {'k': 'v'} proxy(obj).__delitem__('k') self.assertEqual(obj, {}) def test_iter(self): """ Verify that iter / __iter__ is redirected to the proxiee. """ # NOTE: MagicMock.__iter__ needs to return a deterministic iterator as # by default a new iterator is returned each time. self.obj.__iter__.return_value = iter([]) self.assertEqual(iter(self.proxy), iter(self.obj)) self.assertEqual(self.proxy.__iter__(), iter(self.obj)) def test_reversed(self): """ Verify that __reversed__ is redirected to the proxiee. """ # NOTE: apparently MagicMock.doesn't support __reversed__ so we fall # back to the approach with a custom class. The same comment, as above, # for __iter__() applies though. with self.assertRaises(AttributeError): self.obj.__reversed__.return_value = reversed([]) class C(object): reversed_retval = iter([]) def __reversed__(self): return self.reversed_retval self.obj = C() self.proxy = proxy(self.obj) self.assertEqual(reversed(self.proxy), reversed(self.obj)) self.assertEqual(self.proxy.__reversed__(), reversed(self.obj)) def test_contains(self): """ Verify that __contains__ is redirected to the proxiee. """ item = object() self.assertEqual(item in self.proxy, item in self.obj) self.assertEqual(self.proxy.__contains__(item), item in self.obj) self.assertEqual(self.proxy.__contains__(item), False) self.obj.__contains__.return_value = True self.assertEqual(item in self.proxy, item in self.obj) self.assertEqual(self.proxy.__contains__(item), item in self.obj) self.assertEqual(self.proxy.__contains__(item), True) def test_add(self): other = mock.MagicMock() self.assertEqual(self.proxy + other, self.obj + other) self.assertEqual(self.proxy.__add__(other), self.obj + other) self.assertEqual(proxy(4.5) + 2, 6.5) self.assertEqual(proxy(5) + 2, 7) with self.assertRaises(TypeError): proxy("foo") + 2 self.assertEqual(proxy("foo") + "bar", "foobar") def test_sub(self): other = mock.MagicMock() self.assertEqual(self.proxy - other, self.obj - other) self.assertEqual(self.proxy.__sub__(other), self.obj - other) self.assertEqual(proxy(4.5) - 2, 2.5) self.assertEqual(proxy(5) - 2, 3) with self.assertRaises(TypeError): proxy("foo") - 2 def test_mul(self): other = mock.MagicMock() self.assertEqual(self.proxy * other, self.obj * other) self.assertEqual(self.proxy.__mul__(other), self.obj * other) self.assertEqual(proxy(4.5) * 2, 9.0) self.assertEqual(proxy(5) * 2, 10) self.assertEqual(proxy("foo") * 2, "foofoo") @unittest.skipUnless( sys.version_info[0:2] >= (3, 5), "requires python 3.5") def test_matmul(self): other = mock.MagicMock() self.assertEqual(operator.matmul(self.proxy, other), operator.matmul(self.obj, other)) self.assertEqual(self.proxy.__matmul__(other), operator.matmul(self.obj, other)) @unittest.skipUnless(sys.version_info[0] == 2, "requires python 2") def test_div(self): other = mock.MagicMock() self.assertEqual(operator.div(self.proxy, other), operator.div(self.obj, other)) self.assertEqual(self.proxy.__div__(other), operator.div(self.obj, other)) self.assertEqual(operator.div(proxy(4.5), 2), 2.25) self.assertEqual(operator.div(proxy(5), 2), 2) def test_truediv(self): other = mock.MagicMock() self.assertEqual(operator.truediv(self.proxy, other), operator.truediv(self.obj, other)) self.assertEqual(self.proxy.__truediv__(other), operator.truediv(self.obj, other)) self.assertEqual(operator.truediv(proxy(4.5), 2), 2.25) self.assertEqual(operator.truediv(proxy(5), 2), 2.5) def test_floordiv(self): other = mock.MagicMock() self.assertEqual(self.proxy // other, self.obj // other) self.assertEqual(self.proxy.__floordiv__(other), self.obj // other) self.assertEqual(proxy(4.5) // 2, 2) self.assertEqual(proxy(5) // 2, 2) def test_mod(self): other = mock.MagicMock() self.assertEqual(self.proxy % other, self.obj % other) self.assertEqual(self.proxy.__mod__(other), self.obj % other) self.assertEqual(proxy(4.5) % 2, 0.5) self.assertEqual(proxy(5) % 2, 1) def test_divmod(self): other = mock.MagicMock() self.assertEqual(divmod(self.proxy, other), divmod(self.obj, other)) self.assertEqual(self.proxy.__divmod__(other), divmod(self.obj, other)) self.assertEqual(divmod(proxy(4.5), 2), (2, 0.5)) self.assertEqual(divmod(proxy(5), 2), (2, 1)) def test_pow(self): other = mock.MagicMock() self.assertEqual(self.proxy ** other, self.obj ** other) self.assertEqual(self.proxy.__pow__(other), self.obj ** other) self.assertEqual(pow(self.proxy, other), self.obj ** other) self.assertEqual(pow(proxy(2), 3), 8) def test_lshift(self): other = mock.MagicMock() self.assertEqual(self.proxy << other, self.obj << other) self.assertEqual(self.proxy.__lshift__(other), self.obj << other) self.assertEqual(proxy(1) << 3, 8) def test_rshift(self): other = mock.MagicMock() self.assertEqual(self.proxy >> other, self.obj >> other) self.assertEqual(self.proxy.__rshift__(other), self.obj >> other) self.assertEqual(proxy(8) >> 3, 1) def test_and(self): other = mock.MagicMock() self.assertEqual(self.proxy & other, self.obj & other) self.assertEqual(self.proxy.__and__(other), self.obj & other) self.assertEqual(proxy(7) & 4, 4) def test_xor(self): other = mock.MagicMock() self.assertEqual(self.proxy ^ other, self.obj ^ other) self.assertEqual(self.proxy.__xor__(other), self.obj ^ other) self.assertEqual(proxy(1) ^ 1, 0) self.assertEqual(proxy(1) ^ 0, 1) self.assertEqual(proxy(0) ^ 0, 0) self.assertEqual(proxy(0) ^ 1, 1) def test_or(self): other = mock.MagicMock() self.assertEqual(self.proxy | other, self.obj | other) self.assertEqual(self.proxy.__or__(other), self.obj | other) self.assertEqual(proxy(1) | 2, 3) def test_radd(self): """ Verify that __radd__ is redirected to the proxiee. """ # NOTE: ``other`` is anything other than MagicMock to let # the reverse methods do their work. The same rule applies # to all the other test_r* methods so it won't be repeated # there. other = mock.Mock() self.assertEqual(other + self.proxy, other + self.obj) self.assertEqual(self.proxy.__radd__(other), other + self.obj) self.assertEqual(4.5 + proxy(2), 6.5) self.assertEqual(5 + proxy(2), 7) with self.assertRaises(TypeError): 2 + proxy("foo") self.assertEqual("foo" + proxy("bar"), "foobar") self.assertEqual([1, 2, 3] + proxy([4, 5]), [1, 2, 3, 4, 5]) def test_rsub(self): """ Verify that __rsub__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other - self.proxy, other - self.obj) self.assertEqual(self.proxy.__rsub__(other), other - self.obj) self.assertEqual(4.5 - proxy(2), 2.5) self.assertEqual(5 - proxy(2), 3) with self.assertRaises(TypeError): "foo" - proxy(2) def test_rmul(self): """ Verify that __rmul__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other * self.proxy, other * self.obj) self.assertEqual(self.proxy.__rmul__(other), other * self.obj) self.assertEqual(4.5 * proxy(2), 9.0) self.assertEqual(5 * proxy(2), 10) self.assertEqual("foo" * proxy(2), "foofoo") @unittest.skipUnless( sys.version_info[0:2] >= (3, 5), "requires python 3.5") def test_rmatmul(self): """ Verify that __rmul__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(operator.matmul(other, self.proxy), operator.matmul(other, self.obj)) self.assertEqual(self.proxy.__rmatmul__(other), operator.matmul(other, self.obj)) @unittest.skipUnless(sys.version_info[0] == 2, "requires python 2") def test_rdiv(self): """ Verify that __rdiv__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(operator.div(other, self.proxy), operator.div(other, self.obj)) self.assertEqual(self.proxy.__rdiv__(other), operator.div(other, self.obj)) self.assertEqual(operator.div(4.5, proxy(2)), 2.25) self.assertEqual(operator.div(5, proxy(2)), 2) def test_rtruediv(self): """ Verify that __rtruediv__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(operator.truediv(other, self.proxy), operator.truediv(other, self.obj)) self.assertEqual(self.proxy.__rtruediv__(other), operator.truediv(other, self.obj)) self.assertEqual(operator.truediv(4.5, proxy(2)), 2.25) self.assertEqual(operator.truediv(5, proxy(2)), 2.5) def test_rfloordiv(self): """ Verify that __rfloordiv__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other // self.proxy, other // self.obj) self.assertEqual(self.proxy.__rfloordiv__(other), other // self.obj) self.assertEqual(4.5 // proxy(2), 2) self.assertEqual(5 // proxy(2), 2) def test_rmod(self): """ Verify that __rmod__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other % self.proxy, other % self.obj) self.assertEqual(self.proxy.__rmod__(other), other % self.obj) self.assertEqual(4.5 % proxy(2), 0.5) self.assertEqual(5 % proxy(2), 1) def test_rdivmod(self): """ Verify that __rdivmod__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(divmod(other, self.proxy), divmod(other, self.obj)) self.assertEqual( self.proxy.__rdivmod__(other), divmod(other, self.obj)) self.assertEqual(divmod(4.5, proxy(2)), (2, 0.5)) self.assertEqual(divmod(5, proxy(2)), (2, 1)) def test_rpow(self): """ Verify that __rpow__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other ** self.proxy, other ** self.obj) self.assertEqual(self.proxy.__rpow__(other), other ** self.obj) self.assertEqual(pow(other, self.proxy), other ** self.obj) self.assertEqual(pow(2, proxy(3)), 8) with self.assertRaises(TypeError): # __rpow__ is not called for the three-argument version of pow() self.assertEqual(pow(2, proxy(10), 1000), 24) def test_rlshift(self): """ Verify that __rlshift__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other << self.proxy, other << self.obj) self.assertEqual(self.proxy.__rlshift__(other), other << self.obj) self.assertEqual(1 << proxy(3), 8) def test_rrshift(self): """ Verify that __rrshift__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other >> self.proxy, other >> self.obj) self.assertEqual(self.proxy.__rrshift__(other), other >> self.obj) self.assertEqual(8 >> proxy(3), 1) def test_rand(self): """ Verify that __rand__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other & self.proxy, other & self.obj) self.assertEqual(self.proxy.__rand__(other), other & self.obj) self.assertEqual(7 & proxy(4), 4) def test_rxor(self): """ Verify that __rxor__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other ^ self.proxy, other ^ self.obj) self.assertEqual(self.proxy.__rxor__(other), other ^ self.obj) self.assertEqual(1 ^ proxy(1), 0) self.assertEqual(1 ^ proxy(0), 1) self.assertEqual(0 ^ proxy(0), 0) self.assertEqual(0 ^ proxy(1), 1) def test_ror(self): """ Verify that __ror__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(other | self.proxy, other | self.obj) self.assertEqual(self.proxy.__ror__(other), other | self.obj) self.assertEqual(1 | proxy(2), 3) def test_iadd__via_operator__mutable(self): """ Verify that += is redirected to the proxiee (mutable case). """ # Mock__iadd__ that returns the object itself self.obj.__iadd__.return_value = self.obj other = mock.MagicMock() proxy_old = self.proxy self.proxy += other # __iadd__ was called and mutated the state of obj self.obj.__iadd__.assert_called_with(other) # += returned the same proxy object self.assertIs(self.proxy, proxy_old) self.assertTrue(issubclass(type(self.proxy), proxy)) # the proxy object tracks the original object self.assertIs(proxy.original(self.proxy), self.obj) def test_iadd__via_operator__immutable(self): """ Verify that += is redirected to the proxiee (immutable case). """ # Mock the absence of __iadd__ del self.obj.__iadd__ other = mock.MagicMock() proxy_old = self.proxy self.proxy += other # __add__ was called and returned new obj self.obj.__add__.assert_called_with(other) # += returned a new proxy object self.assertTrue(issubclass(type(self.proxy), proxy)) self.assertIsNot(self.proxy, proxy_old) # the new proxy object tracks new object self.assertIsNot(proxy.original(self.proxy), self.obj) def test_iadd__via_dunder__mutable(self): """ Verify that __iadd__ is redirected to the proxiee. """ # Mock __iadd__ that returns the object itself self.obj.__iadd__.return_value = self.obj other = mock.MagicMock() proxy_old = self.proxy self.proxy = self.proxy.__iadd__(other) # __iadd__ was called and mutated the state of obj self.obj.__iadd__.assert_called_with(other) # += returned the same proxy object self.assertIs(self.proxy, proxy_old) self.assertTrue(issubclass(type(self.proxy), proxy)) # the proxy object tracks the original object self.assertIs(proxy.original(self.proxy), self.obj) def test_iadd__via_dunder__immutable(self): """ Verify that __iadd__ doesn't show up if not originally present. """ # Mock the absence of __iadd__ del self.obj.__iadd__ other = mock.MagicMock() with self.assertRaises(AttributeError): self.proxy.__iadd__(other) def test_iadd__on_int__via_operator(self): """ Verify that += works on proxy[int]. """ # int is immutable so += actually works using the + operator a = b = proxy(2) # b is modified, a is unchanged b += 2 self.assertEqual(a, 2) self.assertEqual(b, b) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_iadd__on_str__via_operator(self): """ Verify that += works on proxy[str]. """ # str is immutable so += actually works using the + operator a = b = proxy("hello") b += " world" self.assertEqual(a, "hello") self.assertEqual(b, "hello world") self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_iadd__on_list__via_operator(self): """ Verify that += works on proxy[list]. """ # list is mutable so += is implemented directly a = b = proxy(['first']) b += ['second'] self.assertEqual(a, ['first', 'second']) self.assertEqual(b, ['first', 'second']) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_iadd__on_int__via_dunder(self): """ Verify that __iadd__ doesn't exist on proxy[int]. """ a = 2 with self.assertRaises(AttributeError): a.__iadd__(2) b = proxy(2) with self.assertRaises(AttributeError): b.__iadd__(2) def test_iadd__on_str__via_dunder(self): """ Verify that __iadd__ doesn't exist on proxy[str]. """ a = "hello" with self.assertRaises(AttributeError): a.__iadd__(" world") b = proxy("hello") with self.assertRaises(AttributeError): b.__iadd__(" world") def test_iadd__on_list__via_dunder(self): """ Verify that __iadd__ works on proxy[list]. """ a = proxy(['first']) b = a.__iadd__(['second']) self.assertEqual(a, ['first', 'second']) self.assertEqual(b, ['first', 'second']) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) self.assertIs(a, b) def test_isub__on_int(self): """ Verify that -= works on proxy[int]. """ a = b = proxy(4) b -= 3 self.assertEqual(a, 4) self.assertEqual(b, 1) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_imul__on_int(self): """ Verify that *= works on proxy[int]. """ a = b = proxy(4) b *= 2 self.assertEqual(a, 4) self.assertEqual(b, 8) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) # NOTE: there's no type in stdlib that supports matmul so there's no smoke # test for that. @unittest.skipUnless(sys.version_info[0] == 2, "requires python 2") def test_idiv__on_int(self): """ Verify that (old) /= works on proxy[int]. """ a = b = proxy(7) b = operator.idiv(b, 2) self.assertEqual(a, 7) self.assertEqual(b, 3) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_itruediv__on_int(self): """ Verify that (true) /= works on proxy[int]. """ a = b = proxy(7) b = operator.itruediv(b, 2) self.assertEqual(a, 7) self.assertEqual(b, 3.5) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_ifloordiv__on_int(self): """ Verify that //= works on proxy[int]. """ a = b = proxy(7) b //= 2 self.assertEqual(a, 7) self.assertEqual(b, 3) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_imod__on_int(self): """ Verify that %= works on proxy[int]. """ a = b = proxy(7) b %= 2 self.assertEqual(a, 7) self.assertEqual(b, 1) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_ipow__on_int(self): """ Verify that **= works on proxy[int]. """ a = b = proxy(7) b **= 2 self.assertEqual(a, 7) self.assertEqual(b, 49) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_ilshift__on_int(self): """ Verify that <<= works on proxy[int]. """ a = b = proxy(1) b <<= 10 self.assertEqual(a, 1) self.assertEqual(b, 1024) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_irshift__on_int(self): """ Verify that >>= works on proxy[int]. """ a = b = proxy(1024) b >>= 10 self.assertEqual(a, 1024) self.assertEqual(b, 1) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_iand__on_int(self): """ Verify that &= works on proxy[int]. """ a = b = proxy(7) b &= 4 self.assertEqual(a, 7) self.assertEqual(b, 4) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_ixor__on_int(self): """ Verify that ^= works on proxy[int]. """ a = b = proxy(7) b ^= 5 self.assertEqual(a, 7) self.assertEqual(b, 2) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_ior__on_int(self): """ Verify that |= works on proxy[int]. """ a = b = proxy(7) b |= 8 self.assertEqual(a, 7) self.assertEqual(b, 15) self.assertTrue(issubclass(type(a), proxy)) self.assertTrue(issubclass(type(b), proxy)) def test_context_manager_methods_v1(self): """ Verify that __enter__ and __exit__ are redirected. """ with self.proxy: pass self.obj.__enter__.assert_called_once_with() self.obj.__exit__.assert_called_once_with(None, None, None) def test_context_manager_methods_v2(self): """ Verify that redirecting __exit__ passes right arguments. """ exc = Exception("boom") with self.assertRaisesRegex(Exception, "boom"): with self.proxy: try: raise exc except: traceback = sys.exc_info()[2] raise self.obj.__enter__.assert_called_once_with() # XXX: it's called with (Exception, exc, traceback) but I don't know # how to reach the traceback here self.obj.__exit__.assert_called_once_with(Exception, exc, traceback) def test_hasattr_parity(self): """ verify that hasattr() behaves the same for original and proxy. """ class C(object): pass special_methods = str(''' __del__ __repr__ __str__ __bytes__ __format__ __lt__ __le__ __eq__ __ne__ __gt__ __ge__ __cmp__ __hash__ __bool__ __nonzero__ __unicode__ __getattr__ __getattribute__ __setattr__ __delattr__ __dir__ __get__ __set__ __delete__ __call__ __len__ __length_hint__ __getitem__ __setitem__ __delitem__ __iter__ __reversed__ __contains__ __add__ __sub__ __mul__ __floordiv__ __mod__ __divmod__ __pow__ __lshift__ __rshift__ __and__ __xor__ __or__ __div__ __truediv__ __radd__ __rsub__ __rmul__ __rdiv__ __rtruediv__ __rfloordiv__ __rmod__ __rdivmod__ __rpow__ __rlshift__ __rrshift__ __rand__ __rxor__ __ror__ __iadd__ __isub__ __imul__ __idiv__ __itruediv__ __ifloordiv__ __imod__ __ipow__ __ilshift__ __irshift__ __iand__ __ixor__ __ior__ __neg__ __pos__ __abs__ __invert__ __complex__ __int__ __long__ __float__ __oct__ __hex__ __index__ __coerce__ __enter__ __exit__ ''').split() for obj in [C(), 42, property(lambda x: x), int, None]: self.obj = obj self.proxy = proxy(self.obj) for attr in special_methods: self.assertEqual( hasattr(self.obj, attr), hasattr(self.proxy, attr), "attribute presence mismatch on attr %r and object %r" % ( attr, self.obj)) def test_isinstance(self): """ Verify that isinstance() checks work. """ # NOTE: this method tests the metaclass self.assertIsInstance(self.obj, type(self.obj)) self.assertIsInstance(self.proxy, type(self.obj)) def test_issubclass(self): """ Verify that issubclass() checks work. """ # NOTE: this method tests the metaclass # NOTE: mock doesn't support subclasscheck # NOTE: str ... below is just for python 2.7 # (__future__.unicode_literals is in effect) obj = str("something other than mock") self.assertTrue(issubclass(str, type(obj))) self.assertTrue(issubclass(str, type(proxy(obj)))) def test_class(self): """ Verify that proxy_obj.__class__ is redirected to the proxiee. """ self.assertEqual(self.proxy.__class__, self.obj.__class__) # NOTE: The proxy cannot hide the fact, that it is a proxy self.assertNotEqual(type(self.proxy), type(self.obj)) class proxy_as_class(unittest.TestCase): """ Tests for uses of proxy() as a base class for specialized proxies. """ def setUp(self): """ Per-test-case setup function. """ if reality_is_broken: print() _logger.debug("STARTING") _logger.debug("[%s]", self._testMethodName) def tearDown(self): """ Per-test-case teardown function. """ if reality_is_broken: _logger.debug("DONE") def test_proxy_subclass(self): """ Verify that basic @unproxied use case works. """ # NOTE: bring your comb, because this is the extra-hairy land class censored(proxy): @unproxied def __str__(self): return "*" * len(super(censored, self).__str__()) self.assertTrue(issubclass(censored, proxy)) self.assertEqual(str(censored("freedom")), "*******") self.assertEqual(censored("freedom").__str__(), "*******") padme-1.1.1/padme/__init__.py0000644000175000017500000011375112475560616015771 0ustar zygazyga00000000000000# Copyright 2015 Canonical Ltd. # Written by: # Zygmunt Krynicki # # This file is part of Padme. # # Padme is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3, # as published by the Free Software Foundation. # # Padme is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Padme. If not, see . """ :mod:`padme` -- a mostly transparent proxy class for Python. ============================================================ Padme, named after the Star Wars (tm) character, is a library for creating proxy objects out of any other python object. The resulting object is as close to mimicking the original as possible. Some things are impossible to fake in CPython so those are highlighted below. All other operations are silently forwarded to the original. Terminology ----------- .. glossary: proxy: An intermediate object that is used in place of some original object. proxiee: The original object hidden behind one or more proxies. Basic features -------------- Let's consider a simple example: >>> pets = [str('cat'), str('dog'), str('fish')] >>> pets_proxy = proxy(pets) >>> pets_proxy ['cat', 'dog', 'fish'] >>> isinstance(pets_proxy, list) True >>> pets_proxy.append(str('rooster')) >>> pets ['cat', 'dog', 'fish', 'rooster'] By default, a proxy object is not that interesting. What is more interesting is the ability to create subclasses that change a subset of the behavior. For implementation simplicity such methods need to be decorated with ``@proxy.direct``. Let's consider a crazy proxy that overrides the ``__repr__()`` method to censor the word 'cat'. This is how it can be implemented: >>> class censor_cat(proxy): ... @proxy.direct ... def __repr__(self): ... return repr(proxy.original(self)).replace( ... str('cat'), str('***')) Now let's create a proxy for our pets collection and see how it looks like: >>> pets_proxy = censor_cat(pets) >>> pets_proxy ['***', 'dog', 'fish', 'rooster'] As before, all other aspects of the proxy behave the same way. All of the methods work and are forwarded to the original object. The type of the proxy object is correct, event the meta-class of the object is correct (this matters for ``issubclass()``, for instance). Accessing the original object ----------------------------- At any time one can access the original object hidden behind any proxy by using the :meth:`proxy.original()` function. For example: >>> obj = 'hello world' >>> proxy.original(proxy(obj)) is obj True Accessing proxy state --------------------- At any time the state of any proxy object can be accessed using the :meth:`proxy.state()` function. The state object behaves as a regular object with attributes. It can be used to add custom state to an object that cannot hold it, for example: >>> obj = 42 >>> obj.foo = 42 Traceback (most recent call last): ... AttributeError: 'int' object has no attribute 'foo' >>> obj = proxy(obj) >>> obj.foo = 42 Traceback (most recent call last): ... AttributeError: 'int' object has no attribute 'foo' >>> proxy.state(obj).foo = 42 >>> proxy.state(obj).foo 42 Using the @proxy.direct decorator --------------------------------- The ``@proxy.direct`` decorator can be used to disable the automatic pass-through behavior that is exhibited by any proxy object. In practice we can use it to either intercept and substitute an existing functionality or to add a new functionality that doesn't exist in the original object. First, let's write a custom proxy class for the ``bool`` class (which cannot be used as a base class anymore) and change the core functionality. >>> class nay(proxy): ... ... @proxy.direct ... def __nonzero__(self): ... return not bool(proxiee(self)) ... ... @proxy.direct ... def __bool__(self): ... return not bool(proxiee(self)) >>> bool(nay(True)) False >>> bool(nay(False)) True >>> if nay([]): ... print("It works!") It works! Now, let's write a different proxy class that will add some new functionality Here, the self_aware_proxy class gives any object a new property, ``is_proxy`` which always returns ``True``. >>> class self_aware_proxy(proxy): ... @proxy.direct ... def is_proxy(self): ... return True >>> self_aware_proxy('hello').is_proxy() True Limitations ----------- There are only two things that that give our proxy away. The ``type()`` function: >>> type(pets_proxy) # doctest: +ELLIPSIS And the ``id`` function (and anything that checks object identity): >>> pets_proxy is pets False >>> id(pets) == id(pets_proxy) False That's it, enjoy. You can read the unit tests for additional interesting details of how the proxy class works. Those are not covered in this short introduction. .. note:: There are a number of classes and meta-classes but the only public interface is the :class:`proxy` class and the :meth:`proxy.direct` decorator. See below for examples. Deprecated 1.0 APIs ------------------- If you've used Padme before you may have seen ``@unproxied()`` and ``proxiee()``. They are still here but ``@unproxied`` is now spelled ``@proxy.direct`` and ``proxiee()`` is now ``proxy.original()``. This was done to allow all of Padme to be used from the one :class:`proxy` class. """ from __future__ import print_function, absolute_import, unicode_literals import logging import operator import sys __author__ = 'Zygmunt Krynicki' __email__ = 'zygmunt.krynicki@canonical.com' __version__ = '1.1.1' __all__ = (str('proxy'), ) _logger = logging.getLogger("padme") class proxy_meta(type): """ Meta-class for all proxy types. This meta-class is responsible for gathering the __unproxied__ attributes on each created class. The attribute is a frozenset of names that will not be forwarded to the ``proxiee`` but instead will be looked up on the proxy itself. """ def __new__(mcls, name, bases, ns, *args, **kwargs): _logger.debug( "%s.__new__ with name: %r, bases: %r (args: %r, kwargs %r)", mcls.__name__, name, bases, args, kwargs) unproxied_set = set() for base in bases: if hasattr(base, '__unproxied__'): unproxied_set.update(base.__unproxied__) for ns_attr, ns_value in ns.items(): if getattr(ns_value, 'unproxied', False): unproxied_set.add(ns_attr) if unproxied_set: _logger.debug( "proxy type %r will pass-thru %r", name, unproxied_set) ns['__unproxied__'] = frozenset(unproxied_set) # _logger.debug("injecting fresh _c_registry into %s", name) ns['_c_registry'] = {} cls = super(proxy_meta, mcls).__new__(mcls, name, bases, ns) cls._untyped_base = cls return cls def __getitem__(proxy_cls, proxiee_cls): proxy_cls = proxy_cls._untyped_base if not isinstance(proxiee_cls, type): raise ValueError("proxiee_cls must be a type") if proxiee_cls not in proxy_cls._m_registry: typed_proxy_meta = make_typed_proxy_meta(proxiee_cls) proxy_cls._m_registry[proxiee_cls] = typed_proxy_meta else: typed_proxy_meta = proxy_cls._m_registry[proxiee_cls] if proxiee_cls not in proxy_cls._c_registry: typed_proxy_cls = metaclass(typed_proxy_meta)( proxy_cls, str('{}[{}]').format( proxy_cls.__name__, proxiee_cls.__name__)) proxy_cls._c_registry[proxiee_cls] = typed_proxy_cls else: typed_proxy_cls = proxy_cls._c_registry[proxiee_cls] typed_proxy_cls._untyped_base = proxy_cls return typed_proxy_cls def make_typed_proxy_meta(proxiee_cls): """ Make a new proxy meta-class for the specified class of proxiee objects. .. note:: Had python had an easier way of doing this, it would have been spelled as ``proxy_meta[cls]`` but I didn't want to drag pretty things into something nobody would ever see. :param proxiee_cls: The type of the that will be proxied :returns: A new meta-class that lexically wraps ``proxiee`` and ``proxiee_cls`` and subclasses :class:`proxy_meta`. """ def __instancecheck__(mcls, instance): # NOTE: this is never called in practice since # proxy(obj).__class__ is really obj.__class__. _logger.debug("__instancecheck__ %r on %r", instance, proxiee_cls) return isinstance(instance, proxiee_cls) def __subclasscheck__(mcls, subclass): # This is still called though since type(proxy(obj)) is # something else _logger.debug("__subclasscheck__ %r on %r", subclass, proxiee_cls) return issubclass(proxiee_cls, subclass) name = str('proxy_meta[{}]').format(proxiee_cls.__name__) bases = (proxy_meta,) ns = { '__doc__': """ Meta-class for all proxies type-bound to type {}. This class implements two methods that participate in instance and class checks: ``__instancecheck__`` and ``__subclasscheck__``. """.format(proxiee_cls.__name__), '__instancecheck__': __instancecheck__, '__subclasscheck__': __subclasscheck__ } return proxy_meta(name, bases, ns) def _get_proxiee(proxy_obj): return object.__getattribute__(proxy_obj, '_original') def _set_proxiee(proxy_obj, proxiee): return object.__setattr__(proxy_obj, '_original', proxiee) def _get_unproxied(proxy): return type(proxy).__unproxied__ # All augmented assignment methods. We need to know those to let use intercept # __getattribute__ access to them. Normally it is safe to directly call methods # on the original object but augmented assignment a (op)= b actually changes a # and we need to make sure that a proxy object is returned there. _imethods = set([ '__iadd__', '__isub__', '__imul__', '__itruediv__', '__ifloordiv__', '__imod__', '__ipow__', '__ilshift__', '__irshift__', '__iand__', '__ixor__', '__ior__', ]) if sys.version_info[0] == 2: _imethods.add('__idiv__') _imethods = frozenset(_imethods) def _imethod(self, other, name, op): """ Shared implementation of __iFUNC__ method. :param self: A proxy_base instance :param other: Any right-hand-side value :param name: Name of the __iFUNC__ :param op: Appropriate operator.__iFUNC__ operator :returns: self """ proxiee_old = proxiee_new = _get_proxiee(self) _logger.debug("%s on proxiee (%r)", name, proxiee_old) # NOTE: This _may_ or _may not be_ calling __iFUNC__ # as the proxiee may not support it in the first place proxiee_new = op(proxiee_old, other) if proxiee_new is not proxiee_old: # NOTE: all of the augmented assignment methods handle the case where # the __iFUNC__ method returns something other than self. To maintain # the illusion that the proxy is not there the internal proxiee # reference is changed to the new proxiee. _logger.debug("%s creates new %s (%r)", name, type(self).__name__, proxiee_new) return type(self)(proxiee_new) return self class proxy_base(object): """ Base class for all proxies. This class implements the bulk of the proxy work by having a lot of dunder methods that delegate their work to a ``proxiee`` object. The ``proxiee`` object must be available as the ``__proxiee__`` attribute on a class deriving from ``base_proxy``. Apart from ``__proxiee__`, the ``__unproxied__`` attribute, which should be a frozenset, must also be present in all derived classes. In practice, the two special attributes are injected via ``boundproxy_meta`` created by :func:`make_boundproxy_meta()`. This class is also used as a base class for the tricky :class:`proxy` below. NOTE: Look at ``pydoc3 SPECIALMETHODS`` section titled ``Special method lookup`` for a rationale of why we have all those dunder methods while still having __getattribute__() """ # NOTE: the order of methods below matches that of ``pydoc3 # SPECIALMETHODS``. The "N/A to instances" text means that it makes no # sense to add proxy support to the specified method because that method # makes no sense on instances. Proxy is designed to intercept access to # *objects*, not construction of such objects in the first place. # N/A to instances: __new__ # N/A to instances: __init__ def __del__(self): """ No-op object delete method. .. note:: This method is handled specially since it must be called after an object becomes unreachable. As long as the proxy object itself exits, it holds a strong reference to the original object. """ def __repr__(self): proxiee = _get_proxiee(self) _logger.debug("__repr__ on proxiee (%r)", proxiee) return repr(proxiee) def __str__(self): proxiee = _get_proxiee(self) _logger.debug("__str__ on proxiee (%r)", proxiee) return str(proxiee) def __bytes__(self): proxiee = _get_proxiee(self) _logger.debug("__bytes__ on proxiee (%r)", proxiee) return bytes(proxiee) def __format__(self, format_spec): proxiee = _get_proxiee(self) _logger.debug("__format__ on proxiee (%r)", proxiee) return format(proxiee, format_spec) def __lt__(self, other): proxiee = _get_proxiee(self) _logger.debug("__lt__ on proxiee (%r)", proxiee) return proxiee < other def __le__(self, other): proxiee = _get_proxiee(self) _logger.debug("__le__ on proxiee (%r)", proxiee) return proxiee <= other def __eq__(self, other): proxiee = _get_proxiee(self) _logger.debug("__eq__ on proxiee (%r)", proxiee) return proxiee == other def __ne__(self, other): proxiee = _get_proxiee(self) _logger.debug("__ne__ on proxiee (%r)", proxiee) return proxiee != other def __gt__(self, other): proxiee = _get_proxiee(self) _logger.debug("__gt__ on proxiee (%r)", proxiee) return proxiee > other def __ge__(self, other): proxiee = _get_proxiee(self) _logger.debug("__ge__ on proxiee (%r)", proxiee) return proxiee >= other if sys.version_info[0] == 2: # NOTE: having it in python3 is harmless but it's handled by # __getattribute__ already def __cmp__(self, other): proxiee = _get_proxiee(self) _logger.debug("__cmp__ on proxiee (%r)", proxiee) return cmp(proxiee, other) def __hash__(self): proxiee = _get_proxiee(self) _logger.debug("__hash__ on proxiee (%r)", proxiee) return hash(proxiee) # NOTE: __bool__ is spelled as __nonzero__ in pre-3K world # See PEP:`3100` for details. if sys.version_info[0] == 3: def __bool__(self): proxiee = _get_proxiee(self) _logger.debug("__bool__ on proxiee (%r)", proxiee) return bool(proxiee) else: def __nonzero__(self): proxiee = _get_proxiee(self) _logger.debug("__nonzero__ on proxiee (%r)", proxiee) return bool(proxiee) if sys.version_info[0] == 2: def __unicode__(self): proxiee = _get_proxiee(self) _logger.debug("__unicode__ on proxiee (%r)", proxiee) return unicode(proxiee) def __getattr__(self, name): proxiee = _get_proxiee(self) _logger.debug("__getattr__ %r on proxiee (%r)", name, proxiee) return getattr(proxiee, name) def __getattribute__(self, name): is_unproxied = name in _get_unproxied(self) is_imethod = name in _imethods if is_unproxied: _logger.debug("%s.__getattribute__ %r on proxy itself (direct)", type(self).__name__, name) return object.__getattribute__(self, name) elif is_imethod: _logger.debug( "%s.__getattribute__ %r on proxy itself (augmented" " assignment)", type(self).__name__, name) proxiee = _get_proxiee(self) object.__getattribute__(proxiee, name) return object.__getattribute__(self, name) else: proxiee = _get_proxiee(self) _logger.debug("%s.__getattribute__ %r on proxiee (%r)", type(self).__name__, name, proxiee) return getattr(proxiee, name) def __setattr__(self, name, value): if name not in _get_unproxied(self): proxiee = _get_proxiee(self) _logger.debug("__setattr__ %r on proxiee (%r)", name, proxiee) setattr(proxiee, name, value) else: _logger.debug("__setattr__ %r on proxy itself (direct)", name) object.__setattr__(self, name, value) def __delattr__(self, name): if name not in _get_unproxied(self): proxiee = _get_proxiee(self) _logger.debug("__delattr__ %r on proxiee (%r)", name, proxiee) delattr(proxiee, name) else: _logger.debug("__delattr__ %r on proxy itself (direct)", name) object.__delattr__(self, name) def __dir__(self): proxiee = _get_proxiee(self) _logger.debug("__dir__ on proxiee (%r)", proxiee) return dir(proxiee) def __get__(self, instance, owner): proxiee = _get_proxiee(self) _logger.debug("__get__ on proxiee (%r)", proxiee) return proxiee.__get__(instance, owner) def __set__(self, instance, value): proxiee = _get_proxiee(self) _logger.debug("__set__ on proxiee (%r)", proxiee) proxiee.__set__(instance, value) def __delete__(self, instance): proxiee = _get_proxiee(self) _logger.debug("__delete__ on proxiee (%r)", proxiee) proxiee.__delete__(instance) def __call__(self, *args, **kwargs): proxiee = _get_proxiee(self) _logger.debug("__call__ on proxiee (%r)", proxiee) return proxiee(*args, **kwargs) def __len__(self): proxiee = _get_proxiee(self) _logger.debug("__len__ on proxiee (%r)", proxiee) return len(proxiee) if sys.version_info[0:2] >= (3, 4): def __length_hint__(self): proxiee = _get_proxiee(self) _logger.debug("__length_hint__ on proxiee (%r)", proxiee) return proxiee.__length_hint__() def __getitem__(self, item): proxiee = _get_proxiee(self) _logger.debug("__getitem__ on proxiee (%r)", proxiee) return proxiee[item] def __setitem__(self, item, value): proxiee = _get_proxiee(self) _logger.debug("__setitem__ on proxiee (%r)", proxiee) proxiee[item] = value def __delitem__(self, item): proxiee = _get_proxiee(self) _logger.debug("__delitem__ on proxiee (%r)", proxiee) del proxiee[item] def __iter__(self): proxiee = _get_proxiee(self) _logger.debug("__iter__ on proxiee (%r)", proxiee) return iter(proxiee) def __reversed__(self): proxiee = _get_proxiee(self) _logger.debug("__reversed__ on proxiee (%r)", proxiee) return reversed(proxiee) def __contains__(self, item): proxiee = _get_proxiee(self) _logger.debug("__contains__ on proxiee (%r)", proxiee) return item in proxiee # NOTE: __{get,set,del}slice__() methods are not implemented as they are # not used anymore by anything, AFAIK # all basic numeric methods def __add__(self, other): proxiee = _get_proxiee(self) _logger.debug("__add__ on proxiee (%r)", proxiee) return proxiee + other def __sub__(self, other): proxiee = _get_proxiee(self) _logger.debug("__sub__ on proxiee (%r)", proxiee) return proxiee - other def __mul__(self, other): proxiee = _get_proxiee(self) _logger.debug("__mul__ on proxiee (%r)", proxiee) return proxiee * other if sys.version_info[0:2] >= (3, 5): def __matmul__(self, other): proxiee = _get_proxiee(self) _logger.debug("__matmul__ on proxiee (%r)", proxiee) # NOTE: this is equivalent to ``proxiee @ other`` but we cannot use # this syntax as long as 3.4 and earlier have to be supported. return operator.matmul(proxiee, other) if sys.version_info[0] == 2: def __div__(self, other): proxiee = _get_proxiee(self) _logger.debug("__div__ on proxiee (%r)", proxiee) return operator.div(proxiee, other) def __truediv__(self, other): proxiee = _get_proxiee(self) _logger.debug("__truediv__ on proxiee (%r)", proxiee) return operator.truediv(proxiee, other) def __floordiv__(self, other): proxiee = _get_proxiee(self) _logger.debug("__floordiv__ on proxiee (%r)", proxiee) return proxiee // other def __mod__(self, other): proxiee = _get_proxiee(self) _logger.debug("__mod__ on proxiee (%r)", proxiee) return proxiee % other def __divmod__(self, other): proxiee = _get_proxiee(self) _logger.debug("__divmod__ on proxiee (%r)", proxiee) return divmod(proxiee, other) def __pow__(self, other, modulo=None): proxiee = _get_proxiee(self) _logger.debug("__pow__ on proxiee (%r)", proxiee) return pow(proxiee, other, modulo) def __lshift__(self, other): proxiee = _get_proxiee(self) _logger.debug("__lshift__ on proxiee (%r)", proxiee) return proxiee << other def __rshift__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rshift__ on proxiee (%r)", proxiee) return proxiee >> other def __and__(self, other): proxiee = _get_proxiee(self) _logger.debug("__and__ on proxiee (%r)", proxiee) return proxiee & other def __xor__(self, other): proxiee = _get_proxiee(self) _logger.debug("__xor__ on proxiee (%r)", proxiee) return proxiee ^ other def __or__(self, other): proxiee = _get_proxiee(self) _logger.debug("__or__ on proxiee (%r)", proxiee) return proxiee | other # all reversed numeric methods def __radd__(self, other): proxiee = _get_proxiee(self) _logger.debug("__radd__ on proxiee (%r)", proxiee) return other + proxiee def __rsub__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rsub__ on proxiee (%r)", proxiee) return other - proxiee def __rmul__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rmul__ on proxiee (%r)", proxiee) return other * proxiee if sys.version_info[0:2] >= (3, 5): def __rmatmul__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rmatmul__ on proxiee (%r)", proxiee) # NOTE: this is equivalent to ``proxiee @ other`` but we cannot use # this syntax as long as 3.4 and earlier have to be supported. return operator.matmul(other, proxiee) if sys.version_info[0] == 2: def __rdiv__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rdiv__ on proxiee (%r)", proxiee) return operator.__div__(other, proxiee) def __rtruediv__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rtruediv__ on proxiee (%r)", proxiee) return operator.__truediv__(other, proxiee) def __rfloordiv__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rfloordiv__ on proxiee (%r)", proxiee) return other // proxiee def __rmod__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rmod__ on proxiee (%r)", proxiee) return other % proxiee def __rdivmod__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rdivmod__ on proxiee (%r)", proxiee) return divmod(other, proxiee) def __rpow__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rpow__ on proxiee (%r)", proxiee) return pow(other, proxiee) def __rlshift__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rlshift__ on proxiee (%r)", proxiee) return other << proxiee def __rrshift__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rrshift__ on proxiee (%r)", proxiee) return other >> proxiee def __rand__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rand__ on proxiee (%r)", proxiee) return other & proxiee def __rxor__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rxor__ on proxiee (%r)", proxiee) return other ^ proxiee def __ror__(self, other): proxiee = _get_proxiee(self) _logger.debug("__rrshift__ on proxiee (%r)", proxiee) return other | proxiee # all augmented assignment numeric methods def __iadd__(self, other): return _imethod(self, other, '__iadd__', operator.iadd) def __isub__(self, other): return _imethod(self, other, '__isub__', operator.isub) def __imul__(self, other): return _imethod(self, other, '__imul__', operator.imul) if sys.version_info[0:2] >= (3, 5): def __imatmul__(self, other): return _imethod(self, other, '__imatmul__', operator.imatmul) if sys.version_info[0] == 2: def __idiv__(self, other): return _imethod(self, other, '__idiv__', operator.idiv) def __itruediv__(self, other): return _imethod(self, other, '__itruediv__', operator.itruediv) def __ifloordiv__(self, other): return _imethod(self, other, '__ifloordiv__', operator.ifloordiv) def __imod__(self, other): return _imethod(self, other, '__imod__', operator.imod) def __ipow__(self, other, modulo=None): assert modulo is None return _imethod(self, other, '__ipow__', operator.ipow) def __ilshift__(self, other): return _imethod(self, other, '__ilshift__', operator.ilshift) def __irshift__(self, other): return _imethod(self, other, '__irshift__', operator.irshift) def __iand__(self, other): return _imethod(self, other, '__iand__', operator.iand) def __ixor__(self, other): return _imethod(self, other, '__ixor__', operator.ixor) def __ior__(self, other): return _imethod(self, other, '__ior__', operator.ior) # all miscellaneous numeric methods def __neg__(self): proxiee = _get_proxiee(self) _logger.debug("__neg__ on proxiee (%r)", proxiee) return - proxiee def __pos__(self): proxiee = _get_proxiee(self) _logger.debug("__pos__ on proxiee (%r)", proxiee) return + proxiee def __abs__(self): proxiee = _get_proxiee(self) _logger.debug("__abs__ on proxiee (%r)", proxiee) return abs(proxiee) def __invert__(self): proxiee = _get_proxiee(self) _logger.debug("__invert__ on proxiee (%r)", proxiee) return ~ proxiee # Helpers for built-ins: complex(), int(), float() and round() def __complex__(self): proxiee = _get_proxiee(self) _logger.debug("__complex__ on proxiee (%r)", proxiee) return complex(proxiee) def __int__(self): proxiee = _get_proxiee(self) _logger.debug("__int__ on proxiee (%r)", proxiee) return int(proxiee) if sys.version_info[0] == 2: def __long__(self): proxiee = _get_proxiee(self) _logger.debug("__long__ on proxiee (%r)", proxiee) return long(proxiee) def __float__(self): proxiee = _get_proxiee(self) _logger.debug("__float__ on proxiee (%r)", proxiee) return float(proxiee) if sys.version_info[0] == 3: def __round__(self, n): proxiee = _get_proxiee(self) _logger.debug("__float__ on proxiee (%r)", proxiee) return round(proxiee, n) if sys.version_info[0] == 2: def __oct__(self): proxiee = _get_proxiee(self) _logger.debug("__oct__ on proxiee (%r)", proxiee) return oct(proxiee) def __hex__(self): proxiee = _get_proxiee(self) _logger.debug("__hex__ on proxiee (%r)", proxiee) return hex(proxiee) def __index__(self): proxiee = _get_proxiee(self) _logger.debug("__index__ on proxiee (%r)", proxiee) return operator.index(proxiee) if sys.version_info[0] == 2: def __coerce__(self, other): proxiee = _get_proxiee(self) _logger.debug("__coerce__ on proxiee (%r)", proxiee) return coerce(proxiee, other) def __enter__(self): proxiee = _get_proxiee(self) _logger.debug("__enter__ on proxiee (%r)", proxiee) return proxiee.__enter__() def __exit__(self, exc_type, exc_value, traceback): proxiee = _get_proxiee(self) _logger.debug("__exit__ on proxiee (%r)", proxiee) return proxiee.__exit__(exc_type, exc_value, traceback) class proxy_state(object): """ Support class for working with proxy state. This class implements simple attribute-based access methods. It is normally instantiated internally for each proxy object. You don't want to fuss with it manually, instead just use :meth:`proxy.state()` function to access it. """ def __init__(self, proxy_obj): proxy_dict = object.__getattribute__(proxy_obj, '__dict__') object.__setattr__(self, '__dict__', proxy_dict) def __repr__(self): return "<{}.{} object at {:#x} with state {!r}>".format( __name__, self.__class__.__name__, id(self), self.__dict__) class metaclass(object): """ Support decorator for Python-agnostic meta-class injection. The following snippet illustrates how to use this decorator: >>> class my_meta(type): ... METACLASS_WORKS = True >>> @metaclass(my_meta) ... class my_cls(object): ... pass >>> assert my_cls.METACLASS_WORKS """ def __init__(self, mcls): self.mcls = mcls def __call__(self, cls, name=None): # NOTE: the name is not changed so that sphinx doesn't think this is an # alias of some other object. This is pretty weird but important. if name is None: name = cls.__name__ bases = (cls,) ns = { # Patch-in __doc__ so that various help systems work better '__doc__': cls.__doc__, } _logger.debug("metaclass(%s)(%s, name=%r)", self.mcls.__name__, cls.__name__, name) return self.mcls(name, bases, ns) @metaclass(proxy_meta) class proxy(proxy_base): """ A mostly transparent proxy type. The proxy class can be used in two different ways. First, as a callable ``proxy(obj)``. This simply returns a proxy for a single object. >>> truth = [str('trust no one')] >>> lie = proxy(truth) This will return an instance of a new ``proxy`` sub-class which for all intents and purposes, to the extent possible in CPython, forwards all requests to the original object. One can still examine the proxy with some ways:: >>> lie is truth False >>> type(lie) is type(truth) False Having said that, the vast majority of stuff will make the proxy behave identically to the original object. >>> lie[0] 'trust no one' >>> lie[0] = str('trust the government') >>> truth[0] 'trust the government' The second way of using the ``proxy`` class is as a base class. In this way, one can actually override certain methods. To ensure that all the dunder methods work correctly please use the ``@proxy.direct`` decorator on them. >>> import codecs >>> class crypto(proxy): ... ... @proxy.direct ... def __repr__(self): ... return codecs.encode( ... super(crypto, self).__repr__(), "rot_13") With this weird class, we can change the repr() of any object we want to be ROT-13 encoded. Let's see: >>> orig = [str('ala ma kota'), str('a kot ma ale')] >>> prox = crypto(orig) We can sill access all of the data through the proxy: >>> prox[0] 'ala ma kota' But the whole repr() is now a bit different than usual: >>> prox ['nyn zn xbgn', 'n xbg zn nyr'] """ # Registry of known typed_proxy_meta objects _m_registry = {} # There is a corresponding _c_registry but it is reset for each proxy # subclass by proxy_meta. def __new__(proxy_cls, proxiee, *args, **kwargs): """ Create a new instance of ``proxy()`` wrapping ``proxiee``. :param proxiee: The object to proxy :returns: An instance of new subclass of ``proxy`` with injected meta-class proxy_meta[cls] where cls is the type of proxiee. """ _logger.debug( "%s.__new__ with proxiee: %r (args: %r, kwargs %r)", proxy_cls.__name__, proxiee, args, kwargs) proxiee_cls = type(proxiee) typed_proxy_cls = proxy_cls[proxiee_cls] proxy_obj = object.__new__(typed_proxy_cls) state = proxy_state(proxy_obj) # _logger.debug("%s.__new__ inserted _original into instance", # proxy_cls.__name__) state._original = proxiee # _logger.debug("%s.__new__ is about to return", proxy_cls.__name__) return proxy_obj def __init__(proxy_obj, proxiee): """ Initialize a fresh proxy instance specific to ``proxiee``. :param proxiee: The object to proxy """ _logger.debug( "%s.__init__ with proxiee: %r", type(proxy_obj).__name__, proxiee) @staticmethod def direct(fn): """ Mark a method as not-to-be-proxied. This decorator can be used inside :class:`proxy` sub-classes. Please consult the documentation of ``proxy`` for details. In practical terms there are two reasons one can use ``proxy.direct``. - First, as a way to change the behaviour of a proxy. In this mode a method that already exists on the proxied object is intercepted and custom code is executed. The custom code can still call the original, if desired, by using the :meth:`proxy.original()` function to access the original object - Second, as a way to introduce new functionality to an object. In that sense the resulting proxy will be less transparent as all ``proxy.direct`` methods are explicitly visible and available to access but this may be exactly what is desired in some situations. For additional details on how to use this decorator, see the documentation of the :mod:`padme` module. """ fn.unproxied = True _logger.debug("function %r marked as unproxied/direct", fn) return fn @staticmethod def original(proxy_obj): """ Return the :term:`proxiee` hidden behind the given proxy. :param proxy: An instance of :class:`proxy` or its subclass. :returns: The original object that the proxy is hiding. This function can be used to access the object hidden behind a proxy. This is useful when access to original object is necessary, for example, to implement an method decorated with ``@proxy.direct``. In the following example, we cannot use ``super()`` to get access to the append method because the proxy does not really subclass the list object. To override the ``append`` method in a way that allows us to still call the original we must use the :meth:`proxy.original()` function:: >>> class verbose_list(proxy): ... @proxy.direct ... def append(self, item): ... print("Appending:", item) ... proxy.original(self).append(item) Now that we have a ``verbose_list`` class, we can use it to see that it works as expected: >>> l = verbose_list([]) >>> l.append(42) Appending: 42 >>> l [42] """ state = proxy_state(proxy_obj) return state._original @staticmethod def state(proxy_obj): """ Support function for accessing the state of a proxy object. The main reason for this function to exist is to facilitate creating stateful proxy objects. This allows you to put state on objects that cannot otherwise hold it (typically built-in classes or classes using ``__slots__``) and to keep the state invisible to the original object so that it cannot interfere with any future APIs. To use it, just call it on any proxy object and use the return value as a normal object you can get/set attributes on. For example: >>> life = proxy(42) We cannot set attributes on integer instances: >>> life.foo = True Traceback (most recent call last): ... AttributeError: 'int' object has no attribute 'foo' But we can do that with a proxy around the integer object. >>> proxy.state(life).foo = True >>> proxy.state(life).foo True """ return proxy_state(proxy_obj) # 1.0 backwards-compatibility aliases unproxied = proxy.direct proxiee = proxy.original padme-1.1.1/README.rst0000664000175000017500000000134412470352063014243 0ustar zygazyga00000000000000=================================================== Padme - a mostly transparent proxy class for Python =================================================== .. image:: https://badge.fury.io/py/padme.png :target: http://badge.fury.io/py/padme .. image:: https://travis-ci.org/zyga/padme.png?branch=master :target: https://travis-ci.org/zyga/padme .. image:: https://pypip.in/d/padme/badge.png :target: https://pypi.python.org/pypi/padme Features ======== * Free software: LGPLv3 license * Support for Python 2.7 and Python 3.2+ * Documentation: https://padme.readthedocs.org. * Create proxy classes for any object with :class:`padme.proxy`. * Redirect particular methods in subclasses using :class:`padme.unproxied`. padme-1.1.1/COPYING0000664000175000017500000010451212463652605013617 0ustar zygazyga00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .padme-1.1.1/CONTRIBUTING.rst0000664000175000017500000000605612466710314015224 0ustar zygazyga00000000000000============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/zyga/padme/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ padme could always use more documentation, whether as part of the official padme docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/zyga/padme/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `padme` for local development. 1. Fork the `padme` repo on GitHub. 2. Clone your fork locally:: $ git clone git@github.com:your_name_here/padme.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv padme $ cd padme/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 padme $ python setup.py test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.7, 3.2, 3.3, and 3.4, and for PyPy. Check https://travis-ci.org/zyga/padme/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ python -m unittest padme.tests padme-1.1.1/MANIFEST.in0000664000175000017500000000036012463652605014316 0ustar zygazyga00000000000000include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include COPYING include COPYING.LESSER include README.rst recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-include docs *.rst conf.py Makefile make.batpadme-1.1.1/HISTORY.rst0000644000175000017500000000225312475560631014454 0ustar zygazyga00000000000000.. :changelog: History ======= 1.1.1 (2015-03-04) ------------------ * Add general support for **Python 2.7**. * All numeric methods are now supported with some methods exclusive to Python 2.x (``__div__()``, ``__coerce__()``, ``__oct__()``, ``__hex__()``). * Add support for the new matrix multiplication operator ``@``. * Make ``__nonzero__()`` and ``__unicode__()`` exlusive to Python 2.x. * Make ``__bool__()`` and ``__bytes__()`` exclusive to Python 3.x. * Make ``__length_hint()`` exclusive to Python 3.4. * Add support for the ``__cmp__()`` method, exclusive to Python 2.x. * Add support for accessing the proxied object with the new :meth:`~padme.proxy.original()` function. * Add support for accessing proxy state with the new :meth:`~padme.proxy.state()` function. * De-couple proxy classes from proxied objects, much more lightweight proxy design is possible this way (less objects, lower cost to create each new proxy). 1.0 (2014-02-11) ---------------- * First release on PyPI. * Add a short introduction. * Enable travis-ci.org integration. * Remove numbering of generated meta-classes 2015 ---- * Released on PyPI as a part of plainbox as ``plainbox.impl.proxy`` padme-1.1.1/COPYING.LESSER0000664000175000017500000001674212463652605014622 0ustar zygazyga00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.padme-1.1.1/padme.egg-info/0000755000175000017500000000000012475560703015337 5ustar zygazyga00000000000000padme-1.1.1/padme.egg-info/PKG-INFO0000644000175000017500000000637312475560703016445 0ustar zygazyga00000000000000Metadata-Version: 1.1 Name: padme Version: 1.1.1 Summary: Padme is a mostly transparent proxy class for Python Home-page: https://github.com/zyga/padme Author: Zygmunt Krynicki Author-email: me@zygoon.pl License: LGPLv3 Description: =================================================== Padme - a mostly transparent proxy class for Python =================================================== .. image:: https://badge.fury.io/py/padme.png :target: http://badge.fury.io/py/padme .. image:: https://travis-ci.org/zyga/padme.png?branch=master :target: https://travis-ci.org/zyga/padme .. image:: https://pypip.in/d/padme/badge.png :target: https://pypi.python.org/pypi/padme Features ======== * Free software: LGPLv3 license * Support for Python 2.7 and Python 3.2+ * Documentation: https://padme.readthedocs.org. * Create proxy classes for any object with :class:`padme.proxy`. * Redirect particular methods in subclasses using :class:`padme.unproxied`. History ======= 1.1.1 (2015-03-04) ------------------ * Add general support for **Python 2.7**. * All numeric methods are now supported with some methods exclusive to Python 2.x (``__div__()``, ``__coerce__()``, ``__oct__()``, ``__hex__()``). * Add support for the new matrix multiplication operator ``@``. * Make ``__nonzero__()`` and ``__unicode__()`` exlusive to Python 2.x. * Make ``__bool__()`` and ``__bytes__()`` exclusive to Python 3.x. * Make ``__length_hint()`` exclusive to Python 3.4. * Add support for the ``__cmp__()`` method, exclusive to Python 2.x. * Add support for accessing the proxied object with the new :meth:`~padme.proxy.original()` function. * Add support for accessing proxy state with the new :meth:`~padme.proxy.state()` function. * De-couple proxy classes from proxied objects, much more lightweight proxy design is possible this way (less objects, lower cost to create each new proxy). 1.0 (2014-02-11) ---------------- * First release on PyPI. * Add a short introduction. * Enable travis-ci.org integration. * Remove numbering of generated meta-classes 2015 ---- * Released on PyPI as a part of plainbox as ``plainbox.impl.proxy`` Keywords: padme proxy Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy padme-1.1.1/padme.egg-info/zip-safe0000664000175000017500000000000112466712126016767 0ustar zygazyga00000000000000 padme-1.1.1/padme.egg-info/SOURCES.txt0000664000175000017500000000067312475560703017233 0ustar zygazyga00000000000000AUTHORS.rst CONTRIBUTING.rst COPYING COPYING.LESSER HISTORY.rst MANIFEST.in README.rst setup.cfg setup.py docs/Makefile docs/authors.rst docs/conf.py docs/contributing.rst docs/history.rst docs/index.rst docs/installation.rst docs/make.bat docs/readme.rst docs/usage.rst padme/__init__.py padme/tests.py padme.egg-info/PKG-INFO padme.egg-info/SOURCES.txt padme.egg-info/dependency_links.txt padme.egg-info/top_level.txt padme.egg-info/zip-safepadme-1.1.1/padme.egg-info/dependency_links.txt0000664000175000017500000000000112475560703021407 0ustar zygazyga00000000000000 padme-1.1.1/padme.egg-info/top_level.txt0000664000175000017500000000000612475560703020067 0ustar zygazyga00000000000000padme padme-1.1.1/setup.cfg0000644000175000017500000000015012475560703014374 0ustar zygazyga00000000000000[upload] sign = True [wheel] universal = 1 [egg_info] tag_date = 0 tag_build = tag_svn_revision = 0