././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.2855234
echo-0.5/ 0000755 0000770 0000024 00000000000 00000000000 012213 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1484773131.0
echo-0.5/.coveragerc 0000644 0000770 0000024 00000000100 00000000000 014323 0 ustar 00tom staff 0000000 0000000 [report]
omit = echo/tests/*, echo/conftest.py, echo/qt/tests/*
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/.gitignore 0000644 0000770 0000024 00000000530 00000000000 014201 0 ustar 00tom staff 0000000 0000000 *.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
__pycache__
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
_build
htmlcov
doc/api
.eggs
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/.readthedocs.yml 0000644 0000770 0000024 00000000251 00000000000 015277 0 ustar 00tom staff 0000000 0000000 version: 2
build:
image: latest
python:
version: 3.7
install:
- method: pip
path: .
extra_requirements:
- docs
- qt
formats: []
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571973.0
echo-0.5/CHANGES.rst 0000644 0000770 0000024 00000001373 00000000000 014021 0 ustar 00tom staff 0000000 0000000 Full changelog
==============
0.5 (2020-11-08)
----------------
* Add the ability to specify for ``SelectionCallbackProperty`` whether to
compare choices using equality or identity. [#26]
* Fixed an issue that could lead to ``CallbackContainer`` returning dead
weak references during iteration. [#27]
0.4 (2020-05-04)
----------------
* Added the ability to add arbitrary callbacks to ``CallbackDict`` and
``CallbackList`` via the ``.callbacks`` attribute. [#25]
0.3 (2020-05-04)
----------------
* Fix setting of defaults in callback list and dict properties. [#24]
0.2 (2020-04-11)
----------------
* Python 3.6 or later is now required. [#20]
* Significant refactoring of the package. [#20]
0.1 (2014-03-13)
----------------
* Initial version
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1451486606.0
echo-0.5/LICENSE 0000644 0000770 0000024 00000002062 00000000000 013220 0 ustar 00tom staff 0000000 0000000 The MIT License (MIT)
Copyright (c) 2014 glue-viz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1451486606.0
echo-0.5/MANIFEST.in 0000644 0000770 0000024 00000000062 00000000000 013747 0 ustar 00tom staff 0000000 0000000 include LICENSE
include README.md
include echo.py
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1599572028.286548
echo-0.5/PKG-INFO 0000644 0000770 0000024 00000004663 00000000000 013321 0 ustar 00tom staff 0000000 0000000 Metadata-Version: 2.1
Name: echo
Version: 0.5
Summary: Callback Properties in Python
Home-page: https://github.com/glue-viz/echo
Author: Chris Beaumont and Thomas Robitaille
Author-email: thomas.robitaille@gmail.com
Maintainer: Chris Beaumont and Thomas Robitaille
Maintainer-email: thomas.robitaille@gmail.com
License: MIT
Description: |Azure Status| |Coverage status|
echo: Callback Properties in Python
===================================
Echo is a small library for attaching callback functions to property
state changes. For example:
::
class Switch(object):
state = CallbackProperty('off')
def report_change(state):
print 'the switch is %s' % state
s = Switch()
add_callback(s, 'state', report_change)
s.state = 'on' # prints 'the switch is on'
CalllbackProperties can also be built using decorators
::
class Switch(object):
@callback_property
def state(self):
return self._state
@state.setter
def state(self, value):
if value not in ['on', 'off']:
raise ValueError("invalid setting")
self._state = value
Full documentation is avilable `here `__
.. |Azure Status| image:: https://dev.azure.com/glue-viz/echo/_apis/build/status/glue-viz.echo?branchName=master
:target: https://dev.azure.com/glue-viz/echo/_build/latest?definitionId=4&branchName=master
.. |Coverage Status| image:: https://codecov.io/gh/glue-viz/echo/branch/master/graph/badge.svg
:target: https://codecov.io/gh/glue-viz/echo
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Operating System :: OS Independent
Classifier: Topic :: Utilities
Requires-Python: >=3.6
Provides-Extra: test
Provides-Extra: docs
Provides-Extra: qt
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/README.rst 0000644 0000770 0000024 00000002342 00000000000 013703 0 ustar 00tom staff 0000000 0000000 |Azure Status| |Coverage status|
echo: Callback Properties in Python
===================================
Echo is a small library for attaching callback functions to property
state changes. For example:
::
class Switch(object):
state = CallbackProperty('off')
def report_change(state):
print 'the switch is %s' % state
s = Switch()
add_callback(s, 'state', report_change)
s.state = 'on' # prints 'the switch is on'
CalllbackProperties can also be built using decorators
::
class Switch(object):
@callback_property
def state(self):
return self._state
@state.setter
def state(self, value):
if value not in ['on', 'off']:
raise ValueError("invalid setting")
self._state = value
Full documentation is avilable `here `__
.. |Azure Status| image:: https://dev.azure.com/glue-viz/echo/_apis/build/status/glue-viz.echo?branchName=master
:target: https://dev.azure.com/glue-viz/echo/_build/latest?definitionId=4&branchName=master
.. |Coverage Status| image:: https://codecov.io/gh/glue-viz/echo/branch/master/graph/badge.svg
:target: https://codecov.io/gh/glue-viz/echo
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/azure-pipelines.yml 0000644 0000770 0000024 00000002061 00000000000 016051 0 ustar 00tom staff 0000000 0000000 resources:
repositories:
- repository: OpenAstronomy
type: github
endpoint: glue-viz
name: OpenAstronomy/azure-pipelines-templates
ref: master
jobs:
- template: run-tox-env.yml@OpenAstronomy
parameters:
xvfb: true
coverage: codecov
libraries:
apt:
- libxkbcommon-x11-0
envs:
- linux: codestyle
libraries: {}
coverage: 'false'
- linux: py36-test-pyqt59
- linux: py37-test-pyqt510
- linux: py37-test-pyqt511
- linux: py37-test-pyqt512
- linux: py37-test-pyqt513
- linux: py38-test-pyqt514
- linux: py36-test-pyside512
- linux: py37-test-pyside513
- linux: py38-test-pyside514
- macos: py36-test-pyqt59
- windows: py37-test-pyqt510
- macos: py37-test-pyqt511
- windows: py37-test-pyqt512
- macos: py37-test-pyqt513
- windows: py38-test-pyqt514
- macos: py36-test-pyside512
- windows: py37-test-pyside513
- macos: py38-test-pyside514
- linux: py36-docs-pyqt513
- macos: py37-docs-pyqt513
- windows: py38-docs-pyqt513
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.0151293
echo-0.5/doc/ 0000755 0000770 0000024 00000000000 00000000000 012760 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1484773606.0
echo-0.5/doc/Makefile 0000644 0000770 0000024 00000015145 00000000000 014426 0 ustar 00tom staff 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS = -W
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/Echo.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Echo.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/Echo"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Echo"
@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."
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1484773606.0
echo-0.5/doc/api.rst 0000644 0000770 0000024 00000000450 00000000000 014262 0 ustar 00tom staff 0000000 0000000 .. _api:
Detailed API documentation
--------------------------
Core functionality
^^^^^^^^^^^^^^^^^^
.. automodapi:: echo
:no-heading:
:no-inheritance-diagram:
:inherited-members:
.. _qtapi:
Qt helpers
^^^^^^^^^^
.. automodapi:: echo.qt
:no-heading:
:no-inheritance-diagram:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/doc/conf.py 0000644 0000770 0000024 00000021263 00000000000 014263 0 ustar 00tom staff 0000000 0000000 # -*- coding: utf-8 -*-
#
# echo documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 13 11:29:52 2014.
#
# 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('.'))
# -- 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.coverage',
'sphinx.ext.viewcode',
'sphinx.ext.intersphinx',
'sphinx_automodapi.automodapi',
'sphinx_automodapi.smart_resolver',
'numpydoc',
]
# 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'echo'
copyright = u'2014-2020, Chris Beaumont and Thomas Robitaille'
# 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.
from echo import __version__
version = __version__
# The full version, including alpha/beta/rc tags.
release = __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 = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', 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 = 'echodoc'
# -- 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, or own class]).
latex_documents = [
('index.rst', 'echo.tex', u'echo Documentation',
u'Chris Beaumont and Thomas Robitaille', '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.rst', 'echo', u'echo Documentation',
[u'Chris Beaumont and Thomas Robitaille'], 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.rst', 'echo', u'echo Documentation',
u'Chris Beaumont and Thomas Robitaille', 'echo', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Enable nitpicky mode - which ensures that all references in the docs
nitpicky = True
# This is needed to avoid sphinx-automodapi warnings
numpydoc_class_members_toctree = False
# Intersphinx options
intersphinx_cache_limit = 10 # days to keep the cached inventories
intersphinx_mapping = {
'sphinx': ('http://www.sphinx-doc.org/en/latest/', None),
'python': ('https://docs.python.org/3.6', None),
}
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1484773131.0
echo-0.5/doc/core.rst 0000644 0000770 0000024 00000004507 00000000000 014450 0 ustar 00tom staff 0000000 0000000 .. currentmodule:: echo
Quick Start
-----------
There are two syntaxes for creating callback properties. The first option is to
create a CallbackProperty instance at the class level::
class Foo(object):
bar = CallbackProperty(5) # initial value is 5
baz = CallbackProperty() # intial value is None
These behave like normal instance attributes. Altnernatively, you can use the
decorator syntax (all lowercase and with an underscore) to implement custom
getting and setting logic::
class Foo(object):
@callback_property
def bar(self):
... getter function ....
@bar.setter
def bar(self, value):
... setter function ...
To attach a function to a callback property, use the :func:`add_callback`
function::
def callback(new_value):
print('new value is %g' % new_value)
f = Foo()
add_callback(f, 'bar', callback)
# The following will print 'new value is 10'
f.bar = 10
.. note:: When calling :func:`add_callback`, the callback property is
referred to by name, as a string.
You can also write callbacks that receive both the old and new value of the
property, by setting ``echo_old=True`` in :func:`add_callback`::
def callback(old, new):
print('changed from %s to %s' % (old, new))
f = Foo()
add_callback(f, 'bar', callback, echo_old=True)
# The following will print 'changed from 5 to 10'
f.bar = 10
Delaying, ignoring, and removing callbacks
------------------------------------------
Callback functions can be removed with :func:`remove_callback`::
remove_callback(f, 'bar', callback)
The :func:`ignore_callback` and :func:`delay_callback` context managers
temporarily disable callbacks from being called::
with delay_callback(f, 'bar'):
f.bar = 10
f.bar = 20
f.bar = 30
Inside the context manager, none of the callbacks for ``f.bar`` will be called
-- this is useful in situations where you might be making temporary,
incremental changes to a callback property. The difference between
:func:`delay_callback` and :func:`ignore_callback` is whether any
callbacks will be invoked at the end of the context block. Callbacks are
never triggered inside :func:`ignore_callback`, where as they are triggered
a single time inside :func:`delay_callback` if the final state has changed.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/doc/gui.rst 0000644 0000770 0000024 00000004634 00000000000 014305 0 ustar 00tom staff 0000000 0000000 .. currentmodule:: echo.qt
Interfacing with Qt widgets
---------------------------
When designing GUIs, it can be useful to have class properties link directly
to widgets. Echo currently includes functions to connect to Qt widgets, which
are described below. Contributions for other GUI frameworks are welcome!
We recommend using Qt libraries via the `QtPy
`_ package, which provides a uniform API to
PyQt4, PyQt5, and PySide, and we use this in the following examples.
Let's assume we have a simple Qt window with a single checkbox::
from qtpy import QtWidgets
class MySimpleWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MySimpleWindow, self).__init__(parent=parent)
self.checkbox = QtWidgets.QCheckBox()
We can now add a callback property to the class and connect the property to the
Qt checkbox::
from qtpy import QtWidgets
from echo import CallbackProperty
from echo.qt import connect_checkable_button
class MySimpleWindow(QtWidgets.QMainWindow):
active = CallbackProperty(True)
def __init__(self, parent=None):
super(MySimpleWindow, self).__init__(parent=parent)
self.checkbox = QtWidgets.QCheckBox()
self.setCentralWidget(self.checkbox)
self._connection = connect_checkable_button(self, 'active', self.checkbox)
Note that the connection object needs to be stored in a variable, as one there
are no references left to the connection object, the connection is removed.
Let's now write a small script that uses this Qt window and adds a callback
when ``active`` is changed::
from echo import add_callback
def toggled(new):
print("Checkbox toggled: %s" % new)
app = QtWidgets.QApplication([''])
window = MySimpleWindow()
window.show()
add_callback(window, 'active', toggled)
app.exec_()
If you run this script, and click on the checkbox multiple times, the output
in the terminal will be::
Checkbox toggled: False
Checkbox toggled: True
Checkbox toggled: False
In addition, if you need to access the value of the checkbox in the code, you
can now simply access ``window.active`` rather than
``window.checkbox.isChecked``.
A number of other functions are available to connect to other types of widgets,
including combo boxes and text fields - see the API documentation for the
:ref:`qtapi` for more details.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1484773131.0
echo-0.5/doc/index.rst 0000644 0000770 0000024 00000001762 00000000000 014627 0 ustar 00tom staff 0000000 0000000 Echo: Callback Properties in Python
===================================
Overview
--------
Echo is a small Python module to create properties that you can attach callback
functions to::
>>> from echo import CallbackProperty, add_callback
>>> class Switch(object):
... state = CallbackProperty('off')
>>> def alert(value):
... print("The switch is %s" % value)
>>> s = Switch()
>>> add_callback(s, 'state', alert)
>>> s.state
'off'
>>> s.state = 'on'
The switch is on
>>> s.state
'on'
>>> s.state = 'off'
The switch is off
The main features of Echo are:
* A simple, property-like interface to monitor state changes
* Decorator syntax to create callback property getter/setter methods, similar to
``@property``
* Context managers to delay or ignore callback events
* Helper functions to connect callback properties to GUI elements (at the moment
only Qt is supported)
User guide
----------
.. toctree::
:maxdepth: 1
installation
core
gui
api
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1484773131.0
echo-0.5/doc/installation.rst 0000644 0000770 0000024 00000000133 00000000000 016210 0 ustar 00tom staff 0000000 0000000
Installation
------------
You can install echo from PyPI via pip::
pip install echo
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.0829973
echo-0.5/echo/ 0000755 0000770 0000024 00000000000 00000000000 013131 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/__init__.py 0000644 0000770 0000024 00000000176 00000000000 015246 0 ustar 00tom staff 0000000 0000000 from .core import * # noqa
from .containers import * # noqa
from .selection import * # noqa
from .version import * # noqa
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/callback_container.py 0000644 0000770 0000024 00000007127 00000000000 017310 0 ustar 00tom staff 0000000 0000000 import weakref
from functools import partial
__all__ = ['CallbackContainer']
class CallbackContainer(object):
"""
A list-like container for callback functions. We need to be careful with
storing references to methods, because if a callback method is on a class
which contains both the callback and a callback property, a circular
reference is created which results in a memory leak. Instead, we need to use
a weak reference which results in the callback being removed if the instance
is destroyed. This container class takes care of this automatically.
"""
def __init__(self):
self.callbacks = []
def clear(self):
self.callbacks[:] = []
def _wrap(self, value, priority=0):
"""
Given a function/method, this will automatically wrap a method using
weakref to avoid circular references.
"""
if not callable(value):
raise TypeError("Only callable values can be stored in CallbackContainer")
elif self.is_bound_method(value):
# We are dealing with a bound method. Method references aren't
# persistent, so instead we store a reference to the function
# and instance.
value = (weakref.ref(value.__func__),
weakref.ref(value.__self__, self._auto_remove),
priority)
else:
value = (value, priority)
return value
def _auto_remove(self, method_instance):
# Called when weakref detects that the instance on which a method was
# defined has been garbage collected.
for value in self.callbacks[:]:
if isinstance(value, tuple) and value[1] is method_instance:
self.callbacks.remove(value)
def __contains__(self, value):
if self.is_bound_method(value):
for callback in self.callbacks[:]:
if len(callback) == 3 and value.__func__ is callback[0]() and value.__self__ is callback[1]():
return True
else:
return False
else:
for callback in self.callbacks[:]:
if len(callback) == 2 and value is callback[0]:
return True
else:
return False
def __iter__(self):
for callback in sorted(self.callbacks, key=lambda x: x[-1], reverse=True):
if len(callback) == 3:
func = callback[0]()
inst = callback[1]()
# In some cases it can happen that the instance has been
# garbage collected but _auto_remove hasn't been called, so we
# just check here that the weakrefs were resolved
if func is None or inst is None:
continue
yield partial(func, inst)
else:
yield callback[0]
def __len__(self):
return len(self.callbacks)
@staticmethod
def is_bound_method(func):
return hasattr(func, '__func__') and getattr(func, '__self__', None) is not None
def append(self, value, priority=0):
self.callbacks.append(self._wrap(value, priority=priority))
def remove(self, value):
if self.is_bound_method(value):
for callback in self.callbacks[:]:
if len(callback) == 3 and value.__func__ is callback[0]() and value.__self__ is callback[1]():
self.callbacks.remove(callback)
else:
for callback in self.callbacks[:]:
if len(callback) == 2 and value is callback[0]:
self.callbacks.remove(callback)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/conftest.py 0000644 0000770 0000024 00000001150 00000000000 015325 0 ustar 00tom staff 0000000 0000000 from __future__ import absolute_import, division, print_function
try:
import qtpy # noqa
except Exception:
QT_INSTALLED = False
else:
QT_INSTALLED = True
qapp = None
def get_qapp():
global qapp
from qtpy import QtWidgets
qapp = QtWidgets.QApplication.instance()
if qapp is None:
qapp = QtWidgets.QApplication([''])
return qapp
def pytest_configure(config):
if QT_INSTALLED:
from qtpy import QtWidgets # noqa
app = get_qapp() # noqa
def pytest_unconfigure(config):
if QT_INSTALLED:
global qapp
qapp.exit()
qapp = None
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/containers.py 0000644 0000770 0000024 00000015212 00000000000 015651 0 ustar 00tom staff 0000000 0000000 from . import CallbackProperty, HasCallbackProperties
from .callback_container import CallbackContainer
__all__ = ['CallbackList', 'CallbackDict',
'ListCallbackProperty', 'DictCallbackProperty']
class ContainerMixin:
def _prepare_add(self, value):
if isinstance(value, list):
value = CallbackList(self.notify_all, value)
elif isinstance(value, dict):
value = CallbackDict(self.notify_all, value)
if isinstance(value, HasCallbackProperties):
value.add_global_callback(self.notify_all)
elif isinstance(value, (CallbackList, CallbackDict)):
value.callback = self.notify_all
return value
def _cleanup_remove(self, value):
if isinstance(value, HasCallbackProperties):
value.remove_global_callback(self.notify_all)
elif isinstance(value, (CallbackList, CallbackDict)):
value.callbacks.remove(self.notify_all)
class CallbackList(list, ContainerMixin):
"""
A list that calls a callback function when it is modified.
The first argument should be the callback function (which takes no
arguments), and subsequent arguments are as for `list`.
"""
def __init__(self, callback, *args, **kwargs):
super(CallbackList, self).__init__(*args, **kwargs)
self.callbacks = CallbackContainer()
self.callbacks.append(callback)
for index, value in enumerate(self):
super().__setitem__(index, self._prepare_add(value))
def notify_all(self, *args, **kwargs):
for callback in self.callbacks:
callback(*args, **kwargs)
def __repr__(self):
return "".format(len(self))
def append(self, value):
super(CallbackList, self).append(self._prepare_add(value))
self.notify_all()
def extend(self, iterable):
iterable = [self._prepare_add(value) for value in iterable]
super(CallbackList, self).extend(iterable)
self.notify_all()
def insert(self, index, value):
super(CallbackList, self).insert(index, self._prepare_add(value))
self.notify_all()
def pop(self, index=-1):
result = super(CallbackList, self).pop(index)
self._cleanup_remove(result)
self.notify_all()
return result
def remove(self, value):
super(CallbackList, self).remove(value)
self._cleanup_remove(value)
self.notify_all()
def reverse(self):
super(CallbackList, self).reverse()
self.notify_all()
def sort(self, key=None, reverse=False):
super(CallbackList, self).sort(key=key, reverse=reverse)
self.notify_all()
def __setitem__(self, slc, new_value):
old_values = self[slc]
if not isinstance(slc, slice):
old_values = [old_values]
for old_value in old_values:
self._cleanup_remove(old_value)
if isinstance(slc, slice):
new_value = [self._prepare_add(value) for value in new_value]
else:
new_value = self._prepare_add(new_value)
super(CallbackList, self).__setitem__(slc, new_value)
self.notify_all()
def clear(self):
for item in self:
self._cleanup_remove(item)
super(CallbackList, self).clear()
self.notify_all()
class CallbackDict(dict, ContainerMixin):
"""
A dictionary that calls a callback function when it is modified.
The first argument should be the callback function (which takes no
arguments), and subsequent arguments are passed to `dict`.
"""
def __init__(self, callback, *args, **kwargs):
super(CallbackDict, self).__init__(*args, **kwargs)
self.callbacks = CallbackContainer()
self.callbacks.append(callback)
for key, value in self.items():
super().__setitem__(key, self._prepare_add(value))
def notify_all(self, *args, **kwargs):
for callback in self.callbacks:
callback(*args, **kwargs)
def clear(self):
for value in self.values():
self._cleanup_remove(value)
super().clear()
self.notify_all()
def popitem(self):
result = super().popitem()
self._cleanup_remove(result)
self.notify_all()
return result
def update(self, *args, **kwargs):
values = {}
values.update(*args, **kwargs)
for key, value in values.items():
values[key] = self._prepare_add(value)
super().update(values)
self.notify_all()
def pop(self, *args, **kwargs):
result = super().pop(*args, **kwargs)
self._cleanup_remove(result)
self.notify_all()
return result
def __setitem__(self, key, value):
if key in self:
self._cleanup_remove(self[key])
super().__setitem__(key, self._prepare_add(value))
self.notify_all()
def __repr__(self):
return f""
class dynamic_callback:
function = None
def __call__(self, *args, **kwargs):
self.function(*args, **kwargs)
class ListCallbackProperty(CallbackProperty):
"""
A list property that calls callbacks when its contents are modified
"""
def _default_getter(self, instance, owner=None):
if instance not in self._values:
self._default_setter(instance, self._default or [])
return super(ListCallbackProperty, self)._default_getter(instance, owner)
def _default_setter(self, instance, value):
if not isinstance(value, list):
raise TypeError('callback property should be a list')
dcb = dynamic_callback()
wrapped_list = CallbackList(dcb, value)
def callback(*args, **kwargs):
self.notify(instance, wrapped_list, wrapped_list)
dcb.function = callback
super(ListCallbackProperty, self)._default_setter(instance, wrapped_list)
class DictCallbackProperty(CallbackProperty):
"""
A dictionary property that calls callbacks when its contents are modified
"""
def _default_getter(self, instance, owner=None):
if instance not in self._values:
self._default_setter(instance, self._default or {})
return super()._default_getter(instance, owner)
def _default_setter(self, instance, value):
if not isinstance(value, dict):
raise TypeError("Callback property should be a dictionary.")
dcb = dynamic_callback()
wrapped_dict = CallbackDict(dcb, value)
def callback(*args, **kwargs):
self.notify(instance, wrapped_dict, wrapped_dict)
dcb.function = callback
super()._default_setter(instance, wrapped_dict)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/core.py 0000644 0000770 0000024 00000050506 00000000000 014441 0 ustar 00tom staff 0000000 0000000 import weakref
from weakref import WeakKeyDictionary
from contextlib import contextmanager
from .callback_container import CallbackContainer
__all__ = ['CallbackProperty', 'callback_property',
'add_callback', 'remove_callback',
'delay_callback', 'ignore_callback',
'HasCallbackProperties', 'keep_in_sync']
class CallbackProperty(object):
"""
A property that callback functions can be added to.
When a callback property changes value, each callback function
is called with information about the state change. Otherwise,
callback properties behave just like normal instance variables.
CallbackProperties must be defined at the class level. Use
the helper function :func:`~echo.add_callback` to attach a callback to
a specific instance of a class with CallbackProperties
Parameters
----------
default
The initial value for the property
docstring : str
The docstring for the property
getter, setter : func
Custom getter and setter functions (advanced)
"""
def __init__(self, default=None, docstring=None, getter=None, setter=None):
"""
:param default: The initial value for the property
"""
self._default = default
self._callbacks = WeakKeyDictionary()
self._2arg_callbacks = WeakKeyDictionary()
self._disabled = WeakKeyDictionary()
self._values = WeakKeyDictionary()
if getter is None:
getter = self._default_getter
if setter is None:
setter = self._default_setter
self._getter = getter
self._setter = setter
if docstring is not None:
self.__doc__ = docstring
def _default_getter(self, instance, owner=None):
return self._values.get(instance, self._default)
def _default_setter(self, instance, value):
self._values.__setitem__(instance, value)
def __get__(self, instance, owner=None):
if instance is None:
return self
return self._getter(instance)
def __set__(self, instance, value):
try:
old = self.__get__(instance)
except AttributeError: # pragma: no cover
old = None
self._setter(instance, value)
new = self.__get__(instance)
if old != new:
self.notify(instance, old, new)
def setter(self, func):
"""
Method to use as a decorator, to mimic @property.setter
"""
self._setter = func
return self
def _get_full_info(self, instance):
# Some callback subclasses may contain additional info in addition
# to the main value, and we need to use this full information when
# comparing old and new 'values', so this method is used in that
# case. The result should be a tuple where the first item is the
# actual primary value of the property and the second item is any
# additional data to use in the comparison.
# Note that we need to make sure we convert any list here to a tuple
# to make sure the value is immutable, otherwise comparisons of
# old != new will not show any difference (since the list can still)
# be modified in-place
value = self.__get__(instance)
if isinstance(value, list):
value = tuple(value)
return value, None
def notify(self, instance, old, new):
"""
Call all callback functions with the current value
Each callback will either be called using
callback(new) or callback(old, new) depending
on whether ``echo_old`` was set to `True` when calling
:func:`~echo.add_callback`
Parameters
----------
instance
The instance to consider
old
The old value of the property
new
The new value of the property
"""
if not self.enabled(instance):
return
for cback in self._callbacks.get(instance, []):
cback(new)
for cback in self._2arg_callbacks.get(instance, []):
cback(old, new)
def disable(self, instance):
"""
Disable callbacks for a specific instance
"""
self._disabled[instance] = True
def enable(self, instance):
"""
Enable previously-disabled callbacks for a specific instance
"""
self._disabled[instance] = False
def enabled(self, instance):
return not self._disabled.get(instance, False)
def add_callback(self, instance, func, echo_old=False, priority=0):
"""
Add a callback to a specific instance that manages this property
Parameters
----------
instance
The instance to add the callback to
func : func
The callback function to add
echo_old : bool, optional
If `True`, the callback function will be invoked with both the old
and new values of the property, as ``func(old, new)``. If `False`
(the default), will be invoked as ``func(new)``
priority : int, optional
This can optionally be used to force a certain order of execution of
callbacks (larger values indicate a higher priority).
"""
if echo_old:
self._2arg_callbacks.setdefault(instance, CallbackContainer()).append(func, priority=priority)
else:
self._callbacks.setdefault(instance, CallbackContainer()).append(func, priority=priority)
def remove_callback(self, instance, func):
"""
Remove a previously-added callback
Parameters
----------
instance
The instance to detach the callback from
func : func
The callback function to remove
"""
for cb in [self._callbacks, self._2arg_callbacks]:
if instance not in cb:
continue
if func in cb[instance]:
cb[instance].remove(func)
return
else:
raise ValueError("Callback function not found: %s" % func)
def clear_callbacks(self, instance):
"""
Remove all callbacks on this property.
"""
for cb in [self._callbacks, self._2arg_callbacks]:
if instance in cb:
cb[instance].clear()
if instance in self._disabled:
self._disabled.pop(instance)
class HasCallbackProperties(object):
"""
A class that adds functionality to subclasses that use callback properties.
"""
def __init__(self):
from .containers import ListCallbackProperty, DictCallbackProperty
self._global_callbacks = CallbackContainer()
self._ignored_properties = set()
self._delayed_properties = {}
self._delay_global_calls = {}
self._callback_wrappers = {}
for prop_name, prop in self.iter_callback_properties():
if isinstance(prop, (ListCallbackProperty, DictCallbackProperty)):
prop.add_callback(self, self._notify_global_listordict)
def _ignore_global_callbacks(self, properties):
# This is to allow ignore_callbacks to work for global callbacks
self._ignored_properties.update(properties)
def _unignore_global_callbacks(self, properties):
# Once this is called, we simply remove properties from _ignored_properties
# and don't call the callbacks. This is used by ignore_callback
self._ignored_properties -= set(properties)
def _delay_global_callbacks(self, properties):
# This is to allow delay_callback to still have an effect in delaying
# global callbacks. We set _delayed_properties to a dictionary of the
# values at the point at which the callbacks are delayed.
self._delayed_properties.update(properties)
def _process_delayed_global_callbacks(self, properties):
# Once this is called, the global callbacks are called once each with
# a dictionary of the current values of properties that have been
# resumed.
kwargs = {}
for prop, new_value in properties.items():
old_value = self._delayed_properties.pop(prop)
if old_value != new_value:
kwargs[prop] = new_value[0]
self._notify_global(**kwargs)
def _notify_global_listordict(self, *args):
from .containers import ListCallbackProperty, DictCallbackProperty
properties = {}
for prop_name, prop in self.iter_callback_properties():
if isinstance(prop, (ListCallbackProperty, DictCallbackProperty)):
callback_listordict = getattr(self, prop_name)
if callback_listordict is args[0]:
properties[prop_name] = callback_listordict
break
self._notify_global(**properties)
def _notify_global(self, **kwargs):
for prop in set(self._delayed_properties) | set(self._ignored_properties):
if prop in kwargs:
kwargs.pop(prop)
if len(kwargs) > 0:
for callback in self._global_callbacks:
callback(**kwargs)
def __setattr__(self, attribute, value):
super(HasCallbackProperties, self).__setattr__(attribute, value)
if self.is_callback_property(attribute):
self._notify_global(**{attribute: value})
def add_callback(self, name, callback, echo_old=False, priority=0):
"""
Add a callback that gets triggered when a callback property of the
class changes.
Parameters
----------
name : str
The instance to add the callback to.
callback : func
The callback function to add
echo_old : bool, optional
If `True`, the callback function will be invoked with both the old
and new values of the property, as ``callback(old, new)``. If `False`
(the default), will be invoked as ``callback(new)``
priority : int, optional
This can optionally be used to force a certain order of execution of
callbacks (larger values indicate a higher priority).
"""
if self.is_callback_property(name):
prop = getattr(type(self), name)
prop.add_callback(self, callback, echo_old=echo_old, priority=priority)
else:
raise TypeError("attribute '{0}' is not a callback property".format(name))
def remove_callback(self, name, callback):
"""
Remove a previously-added callback
Parameters
----------
name : str
The instance to remove the callback from.
func : func
The callback function to remove
"""
if self.is_callback_property(name):
prop = getattr(type(self), name)
try:
prop.remove_callback(self, callback)
except ValueError: # pragma: nocover
pass # Be forgiving if callback was already removed before
else:
raise TypeError("attribute '{0}' is not a callback property".format(name))
def add_global_callback(self, callback):
"""
Add a global callback function, which is a callback that gets triggered
when any callback properties on the class change.
Parameters
----------
callback : func
The callback function to add
"""
self._global_callbacks.append(callback)
def remove_global_callback(self, callback):
"""
Remove a global callback function.
Parameters
----------
callback : func
The callback function to remove
"""
self._global_callbacks.remove(callback)
def is_callback_property(self, name):
"""
Whether a property (identified by name) is a callback property.
Parameters
----------
name : str
The name of the property to check
"""
return isinstance(getattr(type(self), name, None), CallbackProperty)
def iter_callback_properties(self):
"""
Iterator to loop over all callback properties.
"""
for name in dir(self):
if self.is_callback_property(name):
yield name, getattr(type(self), name)
def callback_properties(self):
return [name for name in dir(self) if self.is_callback_property(name)]
def clear_callbacks(self):
"""
Remove all global and property-specific callbacks.
"""
self._global_callbacks.clear()
for name, prop in self.iter_callback_properties():
prop.clear_callbacks(self)
def add_callback(instance, prop, callback, echo_old=False, priority=0):
"""
Attach a callback function to a property in an instance
Parameters
----------
instance
The instance to add the callback to
prop : str
Name of callback property in `instance`
callback : func
The callback function to add
echo_old : bool, optional
If `True`, the callback function will be invoked with both the old
and new values of the property, as ``func(old, new)``. If `False`
(the default), will be invoked as ``func(new)``
priority : int, optional
This can optionally be used to force a certain order of execution of
callbacks (larger values indicate a higher priority).
Examples
--------
::
class Foo:
bar = CallbackProperty(0)
def callback(value):
pass
f = Foo()
add_callback(f, 'bar', callback)
"""
p = getattr(type(instance), prop)
if not isinstance(p, CallbackProperty):
raise TypeError("%s is not a CallbackProperty" % prop)
p.add_callback(instance, callback, echo_old=echo_old, priority=priority)
def remove_callback(instance, prop, callback):
"""
Remove a callback function from a property in an instance
Parameters
----------
instance
The instance to detach the callback from
prop : str
Name of callback property in `instance`
callback : func
The callback function to remove
"""
p = getattr(type(instance), prop)
if not isinstance(p, CallbackProperty):
raise TypeError("%s is not a CallbackProperty" % prop)
p.remove_callback(instance, callback)
def callback_property(getter):
"""
A decorator to build a CallbackProperty.
This is used by wrapping a getter method, similar to the use of @property::
class Foo(object):
@callback_property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
In simple cases with no getter or setter logic, it's easier to create a
:class:`~echo.CallbackProperty` directly::
class Foo(object);
x = CallbackProperty(initial_value)
"""
cb = CallbackProperty(getter=getter)
cb.__doc__ = getter.__doc__
return cb
class delay_callback(object):
"""
Delay any callback functions from one or more callback properties
This is a context manager. Within the context block, no callbacks
will be issued. Each callback will be called once on exit
Parameters
----------
instance
An instance object with callback properties
*props : str
One or more properties within instance to delay
Examples
--------
::
with delay_callback(foo, 'bar', 'baz'):
f.bar = 20
f.baz = 30
f.bar = 10
print('done') # callbacks triggered at this point, if needed
"""
# Class-level registry of properties and how many times the callbacks have
# been delayed. The idea is that when nesting calls to delay_callback, the
# delay count is increased, and every time __exit__ is called, the count is
# decreased, and once the count reaches zero, the callback is triggered.
delay_count = {}
old_values = {}
def __init__(self, instance, *props):
self.instance = instance
self.props = props
def __enter__(self):
delay_props = {}
for prop in self.props:
p = getattr(type(self.instance), prop)
if not isinstance(p, CallbackProperty):
raise TypeError("%s is not a CallbackProperty" % prop)
if (self.instance, prop) not in self.delay_count:
self.delay_count[self.instance, prop] = 1
self.old_values[self.instance, prop] = p._get_full_info(self.instance)
delay_props[prop] = p._get_full_info(self.instance)
else:
self.delay_count[self.instance, prop] += 1
p.disable(self.instance)
if isinstance(self.instance, HasCallbackProperties):
self.instance._delay_global_callbacks(delay_props)
def __exit__(self, *args):
resume_props = {}
notifications = []
for prop in self.props:
p = getattr(type(self.instance), prop)
if not isinstance(p, CallbackProperty): # pragma: no cover
raise TypeError("%s is not a CallbackProperty" % prop)
if self.delay_count[self.instance, prop] > 1:
self.delay_count[self.instance, prop] -= 1
else:
self.delay_count.pop((self.instance, prop))
old = self.old_values.pop((self.instance, prop))
p.enable(self.instance)
new = p._get_full_info(self.instance)
if old != new:
notifications.append((p, (self.instance, old[0], new[0])))
resume_props[prop] = new
if isinstance(self.instance, HasCallbackProperties):
self.instance._process_delayed_global_callbacks(resume_props)
for p, args in notifications:
p.notify(*args)
@contextmanager
def ignore_callback(instance, *props):
"""
Temporarily ignore any callbacks from one or more callback properties
This is a context manager. Within the context block, no callbacks will be
issued. In contrast with `delay_callback`, no callbacks will be
called on exiting the context manager
Parameters
----------
instance
An instance object with callback properties
*props : str
One or more properties within instance to ignore
Examples
--------
::
with ignore_callback(foo, 'bar', 'baz'):
f.bar = 20
f.baz = 30
f.bar = 10
print('done') # no callbacks called
"""
for prop in props:
p = getattr(type(instance), prop)
if not isinstance(p, CallbackProperty):
raise TypeError("%s is not a CallbackProperty" % prop)
p.disable(instance)
if isinstance(instance, HasCallbackProperties):
instance._ignore_global_callbacks(props)
yield
for prop in props:
p = getattr(type(instance), prop)
assert isinstance(p, CallbackProperty)
p.enable(instance)
if isinstance(instance, HasCallbackProperties):
instance._unignore_global_callbacks(props)
class keep_in_sync(object):
def __init__(self, instance1, prop1, instance2, prop2):
self.instance1 = weakref.ref(instance1, self.disable_syncing)
self.prop1 = prop1
self.instance2 = weakref.ref(instance2, self.disable_syncing)
self.prop2 = prop2
self._syncing = False
self.enabled = False
self.enable_syncing()
def prop1_from_prop2(self, value):
if not self._syncing:
self._syncing = True
setattr(self.instance1(), self.prop1, getattr(self.instance2(), self.prop2))
self._syncing = False
def prop2_from_prop1(self, value):
if not self._syncing:
self._syncing = True
setattr(self.instance2(), self.prop2, getattr(self.instance1(), self.prop1))
self._syncing = False
def enable_syncing(self, *args):
if self.enabled:
return
add_callback(self.instance1(), self.prop1, self.prop2_from_prop1)
add_callback(self.instance2(), self.prop2, self.prop1_from_prop2)
self.enabled = True
def disable_syncing(self, *args):
if not self.enabled:
return
if self.instance1() is not None:
remove_callback(self.instance1(), self.prop1, self.prop2_from_prop1)
if self.instance2() is not None:
remove_callback(self.instance2(), self.prop2, self.prop1_from_prop2)
self.enabled = False
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 011451 x ustar 00 0000000 0000000 27 mtime=1599572028.246612
echo-0.5/echo/qt/ 0000755 0000770 0000024 00000000000 00000000000 013555 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/qt/__init__.py 0000644 0000770 0000024 00000000103 00000000000 015660 0 ustar 00tom staff 0000000 0000000 from .connect import * # noqa
from .autoconnect import * # noqa
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/qt/autoconnect.py 0000644 0000770 0000024 00000012344 00000000000 016455 0 ustar 00tom staff 0000000 0000000 from .connect import (connect_checkable_button,
connect_value,
connect_combo_data,
connect_combo_text,
connect_float_text,
connect_text,
connect_button,
connect_combo_selection,
connect_list_selection)
__all__ = ['autoconnect_callbacks_to_qt']
HANDLERS = {}
HANDLERS['value'] = connect_value
HANDLERS['valuetext'] = connect_float_text
HANDLERS['bool'] = connect_checkable_button
HANDLERS['text'] = connect_text
HANDLERS['combodata'] = connect_combo_data
HANDLERS['combotext'] = connect_combo_text
HANDLERS['button'] = connect_button
HANDLERS['combosel'] = connect_combo_selection
HANDLERS['listsel'] = connect_list_selection
def autoconnect_callbacks_to_qt(instance, widget, connect_kwargs={}):
"""
Given a class instance with callback properties and a Qt widget/window,
connect callback properties to Qt widgets automatically.
The matching is done based on the objectName of the Qt widgets. Qt widgets
that need to be connected should be named using the syntax ``type_name``
where ``type`` describes the kind of matching to be done, and ``name``
matches the name of a callback property. By default, the types can be:
* ``value``: the callback property is linked to a Qt widget that has
``value`` and ``setValue`` methods. Note that for this type, two
additional keyword arguments can be specified using ``connect_kwargs``
(see below): these are ``value_range``, which is used for cases where
the Qt widget is e.g. a slider which has a range of values, and you want
to map this range of values onto a different range for the callback
property, and the second is ``log``, which can be set to `True` if this
mapping should be done in log space.
* ``valuetext``: the callback property is linked to a Qt widget that has
``text`` and ``setText`` methods, and the text is set to a string
representation of the value. Note that for this type, an additional
argument ``fmt`` can be provided, which gives either the format to use
using the ``{}`` syntax, or should be a function that takes a value
and returns a string. Optionally, if the Qt widget supports
the ``editingFinished`` signal, this signal is connected to the callback
property too.
* ``bool``: the callback property is linked to a Qt widget that has
``isChecked`` and ``setChecked`` methods, such as a checkable button.
* ``text``: the callback property is linked to a Qt widget that has
``text`` and ``setText`` methods. Optionally, if the Qt widget supports
the ``editingFinished`` signal, this signal is connected to the callback
property too.
* ``combodata``: the callback property is linked to a QComboBox based on
the ``userData`` of the entries in the combo box.
* ``combotext``: the callback property is linked to a QComboBox based on
the label of the entries in the combo box.
Applications can also define additional mappings between type and
auto-linking. To do this, simply add a new entry to the ``HANDLERS`` object::
>>> echo.qt.autoconnect import HANDLERS
>>> HANDLERS['color'] = connect_color
The handler function (``connect_color`` in the example above) should take
the following arguments: the instance the callback property is attached to,
the name of the callback property, the Qt widget, and optionally some
keyword arguments.
When calling ``autoconnect_callbacks_to_qt``, you can specify
``connect_kwargs``, where each key should be a valid callback property name,
and which gives any additional keyword arguments that can be taken by the
connect functions, as described above. These include for example
``value_range``, ``log``, and ``fmt``.
This function is especially useful when defining ui files, since widget
objectNames can be easily set during the editing process.
"""
# We need a dictionary to store the returned connection handlers in cases
# where these are defined.
returned_handlers = {}
for original_name in dir(widget):
if original_name.startswith('_') or '_' not in original_name:
continue
# FIXME: this is a temorary workaround to allow multiple widgets to be
# connected to a state attribute.
if original_name.endswith('_'):
full_name = original_name[:-1]
else:
full_name = original_name
if '_' in full_name:
wtype, wname = full_name.split('_', 1)
if full_name in connect_kwargs:
kwargs = connect_kwargs[full_name]
elif wname in connect_kwargs:
kwargs = connect_kwargs[wname]
else:
kwargs = {}
if hasattr(instance, wname):
if wtype in HANDLERS:
child = getattr(widget, original_name)
# NOTE: we need to use original_name here since we need a
# unique key, and some wname values might be duplicate.
returned_handlers[original_name] = HANDLERS[wtype](instance, wname, child, **kwargs)
return returned_handlers
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/qt/connect.py 0000644 0000770 0000024 00000046200 00000000000 015562 0 ustar 00tom staff 0000000 0000000 # The functions in this module are used to connect callback properties to Qt
# widgets.
import math
from qtpy import QtGui, QtWidgets
from qtpy.QtCore import Qt
import numpy as np
from ..core import add_callback, remove_callback
from ..selection import SelectionCallbackProperty, ChoiceSeparator
__all__ = ['connect_checkable_button', 'connect_text', 'connect_combo_data',
'connect_combo_text', 'connect_float_text', 'connect_value',
'connect_combo_selection', 'connect_list_selection',
'BaseConnection']
class UserDataWrapper(object):
def __init__(self, data):
self.data = data
class BaseConnection(object):
def __init__(self, instance, prop, widget):
self._instance = instance
self._prop = prop
self._widget = widget
class connect_checkable_button(BaseConnection):
"""
Connect a boolean callback property with a Qt button widget.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should implement the ``setChecked``
method and the ``toggled`` signal.
"""
def __init__(self, instance, prop, widget):
super(connect_checkable_button, self).__init__(instance, prop, widget)
self.connect()
def update_widget(self, value):
self._widget.setChecked(value)
def update_prop(self, value):
setattr(self._instance, self._prop, value)
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
self._widget.toggled.connect(self.update_prop)
self._widget.setChecked(getattr(self._instance, self._prop) or False)
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
self._widget.toggled.disconnect(self.update_prop)
class connect_text(BaseConnection):
"""
Connect a string callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should implement the ``setText`` and
``text`` methods as well optionally the ``editingFinished`` signal.
"""
def __init__(self, instance, prop, widget):
super(connect_text, self).__init__(instance, prop, widget)
self.connect()
def update_prop(self):
value = self._widget.text()
setattr(self._instance, self._prop, value)
def update_widget(self, value):
if hasattr(self._widget, 'editingFinished'):
self._widget.blockSignals(True)
self._widget.setText(value)
self._widget.blockSignals(False)
self._widget.editingFinished.emit()
else:
self._widget.setText(value)
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
try:
self._widget.editingFinished.connect(self.update_prop)
except AttributeError:
pass
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
try:
self._widget.editingFinished.disconnect(self.update_prop)
except AttributeError:
pass
class connect_combo_data(BaseConnection):
"""
Connect a callback property with a QComboBox widget based on the userData.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QComboBox
The combo box to connect.
See Also
--------
connect_combo_text: connect a callback property with a QComboBox widget based on the text.
"""
def __init__(self, instance, prop, widget):
super(connect_combo_data, self).__init__(instance, prop, widget)
self.connect()
def update_widget(self, value):
try:
idx = _find_combo_data(self._widget, value)
except ValueError:
if value is None:
idx = -1
else:
raise
self._widget.setCurrentIndex(idx)
def update_prop(self, idx):
if idx == -1:
setattr(self._instance, self._prop, None)
else:
data_wrapper = self._widget.itemData(idx)
if data_wrapper is None:
setattr(self._instance, self._prop, None)
else:
setattr(self._instance, self._prop, data_wrapper.data)
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
self._widget.currentIndexChanged.connect(self.update_prop)
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
self._widget.currentIndexChanged.disconnect(self.update_prop)
class connect_combo_text(BaseConnection):
"""
Connect a callback property with a QComboBox widget based on the text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QComboBox
The combo box to connect.
See Also
--------
connect_combo_data: connect a callback property with a QComboBox widget based on the userData.
"""
def __init__(self, instance, prop, widget):
super(connect_combo_text, self).__init__(instance, prop, widget)
self.connect()
def update_widget(self, value):
try:
idx = _find_combo_text(self._widget, value)
except ValueError:
if value is None:
idx = -1
else:
raise
self._widget.setCurrentIndex(idx)
def update_prop(self, idx):
if idx == -1:
setattr(self._instance, self._prop, None)
else:
setattr(self._instance, self._prop, self._widget.itemText(idx))
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
self._widget.currentIndexChanged.connect(self.update_prop)
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
self._widget.currentIndexChanged.disconnect(self.update_prop)
class connect_float_text(BaseConnection):
"""
Connect a numerical callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should implement the ``setText`` and
``text`` methods as well optionally the ``editingFinished`` signal.
fmt : str or func
This should be either a format string (in the ``{}`` notation), or a
function that takes a number and returns a string.
"""
def __init__(self, instance, prop, widget, fmt="{:g}"):
super(connect_float_text, self).__init__(instance, prop, widget)
if callable(fmt):
format_func = fmt
else:
def format_func(x):
try:
return fmt.format(x)
except ValueError:
return str(x)
self._format_func = format_func
self.connect()
def update_prop(self):
value = self._widget.text()
try:
value = float(value)
except ValueError:
try:
value = np.datetime64(value)
except Exception:
value = 0
setattr(self._instance, self._prop, value)
def update_widget(self, value):
if value is None:
value = 0.
self._widget.setText(self._format_func(value))
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
try:
self._widget.editingFinished.connect(self.update_prop)
except AttributeError:
pass
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
try:
self._widget.editingFinished.disconnect(self.update_prop)
except AttributeError:
pass
class connect_value(BaseConnection):
"""
Connect a numerical callback property with a Qt widget representing a value.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should implement the ``setText`` and
``text`` methods as well optionally the ``editingFinished`` signal.
value_range : iterable, optional
A pair of two values representing the true range of values (since
Qt widgets such as sliders can only have values in certain ranges).
log : bool, optional
Whether the Qt widget value should be mapped to the log of the callback
property.
"""
def __init__(self, instance, prop, widget, value_range=None, log=False):
super(connect_value, self).__init__(instance, prop, widget)
if log:
if value_range is None:
raise ValueError("log option can only be set if value_range is given")
else:
self._value_range = math.log10(value_range[0]), math.log10(value_range[1])
else:
self._value_range = value_range
self._log = log
self.connect()
def update_prop(self):
value = self._widget.value()
if self._value_range is not None:
imin, imax = self._widget.minimum(), self._widget.maximum()
value = ((value - imin) / (imax - imin)
* (self._value_range[1] - self._value_range[0]) + self._value_range[0])
if self._log:
value = 10 ** value
setattr(self._instance, self._prop, value)
def update_widget(self, value):
if value is None:
self._widget.setValue(0)
return
if self._log:
value = math.log10(value)
if self._value_range is not None:
imin, imax = self._widget.minimum(), self._widget.maximum()
value = ((value - self._value_range[0])
/ (self._value_range[1] - self._value_range[0]) * (imax - imin) + imin)
if isinstance(self._widget, QtWidgets.QSlider):
self._widget.setValue(int(value))
else:
self._widget.setValue(value)
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
self._widget.valueChanged.connect(self.update_prop)
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
self._widget.valueChanged.disconnect(self.update_prop)
class connect_button(BaseConnection):
"""
Connect a button with a callback method
Parameters
----------
instance : object
The class instance that the callback method is attached to
prop : str
The name of the callback method
widget : QtWidget
The Qt widget to connect. This should implement the ``clicked`` method
"""
def __init__(self, instance, prop, widget):
super(connect_button, self).__init__(instance, prop, widget)
self.connect()
def connect(self):
self._widget.clicked.connect(getattr(self._instance, self._prop))
def disconnect(self):
self._widget.clicked.disconnect(self.update_prop)
def _find_combo_data(widget, value):
"""
Returns the index in a combo box where itemData == value
Raises a ValueError if data is not found
"""
# Here we check that the result is True, because some classes may overload
# == and return other kinds of objects whether true or false.
for idx in range(widget.count()):
if widget.itemData(idx) is not None:
if isinstance(widget.itemData(idx), UserDataWrapper):
if widget.itemData(idx).data is value or (widget.itemData(idx).data == value) is True:
return idx
else:
if widget.itemData(idx) is value or (widget.itemData(idx) == value) is True:
return idx
else:
raise ValueError("%s not found in combo box" % (value,))
def _find_combo_text(widget, value):
"""
Returns the index in a combo box where text == value
Raises a ValueError if data is not found
"""
i = widget.findText(value)
if i == -1:
raise ValueError("%s not found in combo box" % value)
else:
return i
class connect_combo_selection(BaseConnection):
def __init__(self, instance, prop, widget):
if not isinstance(getattr(type(instance), prop), SelectionCallbackProperty):
raise TypeError('connect_combo_selection requires a SelectionCallbackProperty')
super(connect_combo_selection, self).__init__(instance, prop, widget)
self.connect()
def update_widget(self, value):
# Update choices in the combo box
combo_data = [self._widget.itemData(idx) for idx in range(self._widget.count())]
combo_text = [self._widget.itemText(idx) for idx in range(self._widget.count())]
choices = getattr(type(self._instance), self._prop).get_choices(self._instance)
choice_labels = getattr(type(self._instance), self._prop).get_choice_labels(self._instance)
if combo_data == choices and combo_text == choice_labels:
choices_updated = False
else:
self._widget.blockSignals(True)
self._widget.clear()
if len(choices) == 0:
return
combo_model = self._widget.model()
for index, (label, choice) in enumerate(zip(choice_labels, choices)):
self._widget.addItem(label, userData=UserDataWrapper(choice))
# We interpret None data as being disabled rows (used for headers)
if isinstance(choice, ChoiceSeparator):
item = combo_model.item(index)
palette = self._widget.palette()
item.setFlags(Qt.ItemFlags(int(item.flags()) & int(~(Qt.ItemIsSelectable | Qt.ItemIsEnabled))))
item.setData(palette.color(QtGui.QPalette.Disabled, QtGui.QPalette.Text))
choices_updated = True
# Update current selection
try:
idx = _find_combo_data(self._widget, value)
except ValueError:
if value is None:
idx = -1
else:
raise
if idx == self._widget.currentIndex() and not choices_updated:
return
self._widget.setCurrentIndex(idx)
self._widget.blockSignals(False)
self._widget.currentIndexChanged.emit(idx)
def update_prop(self, idx):
if idx == -1:
setattr(self._instance, self._prop, None)
else:
data_wrapper = self._widget.itemData(idx)
if data_wrapper is None:
setattr(self._instance, self._prop, None)
else:
setattr(self._instance, self._prop, data_wrapper.data)
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
self._widget.currentIndexChanged.connect(self.update_prop)
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
self._widget.currentIndexChanged.disconnect(self.update_prop)
class connect_list_selection(BaseConnection):
def __init__(self, instance, prop, widget):
"""
Connect a SelectionCallbackProperty with a QListWidget that supports
single-item selection.
"""
if not isinstance(getattr(type(instance), prop), SelectionCallbackProperty):
raise TypeError('connect_list_selection requires a SelectionCallbackProperty')
super(connect_list_selection, self).__init__(instance, prop, widget)
self.connect()
def update_widget(self, value, force=False):
items = [self._widget.item(idx) for idx in range(self._widget.count())]
list_text = [item.text() for item in items]
list_data = [item.data(Qt.UserRole) for item in items]
list_data = [d.data if d is not None else d for d in list_data]
choices = getattr(type(self._instance), self._prop).get_choices(self._instance)
choice_labels = getattr(type(self._instance), self._prop).get_choice_labels(self._instance)
for idx in range(len(choices)):
if choices[idx] is value:
break
else:
idx = -1
self._widget.blockSignals(True)
choices_match = list_data == choices and list_text == choice_labels
if force or not choices_match:
self._widget.clear()
if len(choices) == 0:
self._widget.blockSignals(False)
return
for index, (label, choice) in enumerate(zip(choice_labels, choices)):
item = QtWidgets.QListWidgetItem(label)
item.setData(Qt.UserRole, UserDataWrapper(choice))
self._widget.addItem(item)
# We interpret None data as being disabled rows (used for headers)
if isinstance(choice, ChoiceSeparator):
item.setFlags(Qt.ItemFlags(int(item.flags()) & int(~(Qt.ItemIsSelectable | Qt.ItemIsEnabled))))
if len(self._widget.selectedItems()) == 0:
current_index = -1
else:
selected_item = self._widget.selectedItems()[0]
for current_index, item in enumerate(items):
if item is selected_item:
break
else:
current_index = -1
if idx == current_index and choices_match:
self._widget.blockSignals(False)
return
self._widget.setCurrentItem(self._widget.item(idx))
self._widget.blockSignals(False)
self._widget.itemSelectionChanged.emit()
def update_prop(self):
if len(self._widget.selectedItems()) == 0:
setattr(self._instance, self._prop, None)
else:
data_wrapper = self._widget.selectedItems()[0].data(Qt.UserRole)
if data_wrapper is None:
setattr(self._instance, self._prop, None)
else:
setattr(self._instance, self._prop, data_wrapper.data)
def connect(self):
add_callback(self._instance, self._prop, self.update_widget)
self._widget.itemSelectionChanged.connect(self.update_prop)
self.update_widget(getattr(self._instance, self._prop))
def disconnect(self):
remove_callback(self._instance, self._prop, self.update_widget)
self._widget.itemSelectionChanged.disconnect(self.update_prop)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.2687316
echo-0.5/echo/qt/tests/ 0000755 0000770 0000024 00000000000 00000000000 014717 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1475795433.0
echo-0.5/echo/qt/tests/__init__.py 0000644 0000770 0000024 00000000000 00000000000 017016 0 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/qt/tests/test_autoconnect.py 0000644 0000770 0000024 00000007267 00000000000 020666 0 ustar 00tom staff 0000000 0000000 from qtpy import QtWidgets, QtGui
from echo.qt.autoconnect import autoconnect_callbacks_to_qt
from echo import CallbackProperty
from echo.qt.connect import UserDataWrapper
def test_autoconnect_callbacks_to_qt():
class Data(object):
pass
data1 = Data()
data2 = Data()
class CustomWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(CustomWidget, self).__init__(parent=parent)
self.layout = QtWidgets.QVBoxLayout()
self.setLayout(self.layout)
self.combotext_planet = QtWidgets.QComboBox(objectName='combotext_planet')
self.layout.addWidget(self.combotext_planet)
self.combotext_planet.addItem('earth')
self.combotext_planet.addItem('mars')
self.combotext_planet.addItem('jupiter')
self.combodata_dataset = QtWidgets.QComboBox(objectName='combodata_dataset')
self.layout.addWidget(self.combodata_dataset)
self.combodata_dataset.addItem('data1', UserDataWrapper(data1))
self.combodata_dataset.addItem('data2', UserDataWrapper(data2))
self.text_name = QtWidgets.QLineEdit(objectName='text_name')
self.layout.addWidget(self.text_name)
self.valuetext_age = QtWidgets.QLineEdit(objectName='valuetext_age')
self.layout.addWidget(self.valuetext_age)
self.value_height = QtWidgets.QSlider(objectName='value_height')
self.value_height.setMinimum(0)
self.value_height.setMaximum(10)
self.layout.addWidget(self.value_height)
self.bool_log = QtWidgets.QToolButton(objectName='bool_log')
self.bool_log.setCheckable(True)
self.layout.addWidget(self.bool_log)
class Person(object):
planet = CallbackProperty()
dataset = CallbackProperty()
name = CallbackProperty()
age = CallbackProperty()
height = CallbackProperty()
log = CallbackProperty()
widget = CustomWidget()
person = Person()
connect_kwargs = {'height': {'value_range': (0, 100)},
'age': {'fmt': '{:.2f}'}}
c1 = autoconnect_callbacks_to_qt(person, widget, connect_kwargs=connect_kwargs) # noqa
# Check that modifying things in the Qt widget updates the callback properties
widget.combotext_planet.setCurrentIndex(2)
assert person.planet == 'jupiter'
widget.combodata_dataset.setCurrentIndex(1)
assert person.dataset is data2
widget.text_name.setText('Lovelace')
widget.text_name.editingFinished.emit()
assert person.name == 'Lovelace'
widget.valuetext_age.setText('76')
widget.valuetext_age.editingFinished.emit()
assert person.age == 76
widget.value_height.setValue(7)
assert person.height == 70
widget.bool_log.setChecked(True)
assert person.log
# Check that modifying the callback properties updates the Qt widget
person.planet = 'mars'
assert widget.combotext_planet.currentIndex() == 1
person.dataset = data1
assert widget.combodata_dataset.currentIndex() == 0
person.name = 'Curie'
assert widget.text_name.text() == 'Curie'
person.age = 66.3
assert widget.valuetext_age.text() == '66.30'
person.height = 54
assert widget.value_height.value() == 5
person.log = False
assert not widget.bool_log.isChecked()
def test_autoconnect_with_empty_qt_item():
# The following test just makes sure that if a widget without children
# is ever passed to autoconnect_callbacks_to_qt, things don't crash
widget = QtGui.QPalette()
class Person(object):
name = CallbackProperty()
person = Person()
autoconnect_callbacks_to_qt(person, widget)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/qt/tests/test_connect.py 0000644 0000770 0000024 00000011014 00000000000 017756 0 ustar 00tom staff 0000000 0000000 import pytest
from unittest.mock import MagicMock
from qtpy import QtWidgets
from echo import CallbackProperty
from echo.qt.connect import (connect_checkable_button, connect_text,
connect_combo_data, connect_combo_text,
connect_float_text, connect_value, connect_button,
UserDataWrapper)
def test_connect_checkable_button():
class Test(object):
a = CallbackProperty()
b = CallbackProperty(True)
t = Test()
box1 = QtWidgets.QCheckBox()
c1 = connect_checkable_button(t, 'a', box1) # noqa
box1.setChecked(True)
assert t.a
box1.setChecked(False)
assert not t.a
t.a = True
assert box1.isChecked()
t.a = False
assert not box1.isChecked()
# Make sure that the default value of the callback property is recognized
box2 = QtWidgets.QCheckBox()
connect_checkable_button(t, 'b', box2)
assert box2.isChecked()
def test_connect_text():
class Test(object):
a = CallbackProperty()
b = CallbackProperty()
t = Test()
box = QtWidgets.QLineEdit()
c1 = connect_text(t, 'a', box) # noqa
label = QtWidgets.QLabel()
c2 = connect_text(t, 'b', label) # noqa
box.setText('test1')
box.editingFinished.emit()
assert t.a == 'test1'
t.a = 'test3'
assert box.text() == 'test3'
t.b = 'test4'
assert label.text() == 'test4'
def test_connect_combo():
class Test(object):
a = CallbackProperty()
b = CallbackProperty()
t = Test()
combo = QtWidgets.QComboBox()
combo.addItem('label1', UserDataWrapper(4))
combo.addItem('label2', UserDataWrapper(3.5))
c1 = connect_combo_text(t, 'a', combo) # noqa
c2 = connect_combo_data(t, 'b', combo) # noqa
combo.setCurrentIndex(1)
assert t.a == 'label2'
assert t.b == 3.5
combo.setCurrentIndex(0)
assert t.a == 'label1'
assert t.b == 4
combo.setCurrentIndex(-1)
assert t.a is None
assert t.b is None
t.a = 'label2'
assert combo.currentIndex() == 1
t.a = 'label1'
assert combo.currentIndex() == 0
with pytest.raises(ValueError) as exc:
t.a = 'label3'
assert exc.value.args[0] == 'label3 not found in combo box'
t.a = None
assert combo.currentIndex() == -1
t.b = 3.5
assert combo.currentIndex() == 1
t.b = 4
assert combo.currentIndex() == 0
with pytest.raises(ValueError) as exc:
t.b = 2
assert exc.value.args[0] == '2 not found in combo box'
t.b = None
assert combo.currentIndex() == -1
def test_connect_float_text():
class Test(object):
a = CallbackProperty()
b = CallbackProperty()
c = CallbackProperty()
t = Test()
line1 = QtWidgets.QLineEdit()
line2 = QtWidgets.QLineEdit()
line3 = QtWidgets.QLabel()
def fmt_func(x):
return str(int(round(x)))
c1 = connect_float_text(t, 'a', line1) # noqa
c2 = connect_float_text(t, 'b', line2, fmt="{:5.2f}") # noqa
c3 = connect_float_text(t, 'c', line3, fmt=fmt_func) # noqa
for line in (line1, line2):
line1.setText('1.0')
line1.editingFinished.emit()
assert t.a == 1.0
line1.setText('banana')
line1.editingFinished.emit()
assert t.a == 0.0
t.a = 3.
assert line1.text() == '3'
t.b = 5.211
assert line2.text() == ' 5.21'
t.c = -2.222
assert line3.text() == '-2'
def test_connect_value():
class Test(object):
a = CallbackProperty()
b = CallbackProperty()
c = CallbackProperty()
t = Test()
slider = QtWidgets.QSlider()
slider.setMinimum(0)
slider.setMaximum(100)
c1 = connect_value(t, 'a', slider) # noqa
c2 = connect_value(t, 'b', slider, value_range=(0, 10)) # noqa
with pytest.raises(Exception) as exc:
connect_value(t, 'c', slider, log=True)
assert exc.value.args[0] == "log option can only be set if value_range is given"
c3 = connect_value(t, 'c', slider, value_range=(0.01, 100), log=True) # noqa
slider.setValue(25)
assert t.a == 25
assert t.b == 2.5
assert t.c == 0.1
t.a = 30
assert slider.value() == 30
t.b = 8.5
assert slider.value() == 85
t.c = 10
assert slider.value() == 75
def test_connect_button():
class Example(object):
a = MagicMock()
e = Example()
button = QtWidgets.QPushButton('OK')
connect_button(e, 'a', button)
assert e.a.call_count == 0
button.clicked.emit()
assert e.a.call_count == 1
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/qt/tests/test_connect_combo_selection.py 0000644 0000770 0000024 00000006540 00000000000 023212 0 ustar 00tom staff 0000000 0000000 import pytest
import numpy as np
from qtpy import QtWidgets
from echo.core import CallbackProperty
from echo.selection import SelectionCallbackProperty, ChoiceSeparator
from echo.qt.connect import connect_combo_selection
class Example(object):
a = SelectionCallbackProperty(default_index=1)
b = CallbackProperty()
def test_connect_combo_selection():
t = Example()
a_prop = getattr(type(t), 'a')
a_prop.set_choices(t, [4, 3.5])
a_prop.set_display_func(t, lambda x: 'value: {0}'.format(x))
combo = QtWidgets.QComboBox()
c1 = connect_combo_selection(t, 'a', combo) # noqa
assert combo.itemText(0) == 'value: 4'
assert combo.itemText(1) == 'value: 3.5'
assert combo.itemData(0).data == 4
assert combo.itemData(1).data == 3.5
combo.setCurrentIndex(1)
assert t.a == 3.5
combo.setCurrentIndex(0)
assert t.a == 4
combo.setCurrentIndex(-1)
assert t.a is None
t.a = 3.5
assert combo.currentIndex() == 1
t.a = 4
assert combo.currentIndex() == 0
with pytest.raises(ValueError) as exc:
t.a = 2
assert exc.value.args[0] == 'value 2 is not in valid choices: [4, 3.5]'
t.a = None
assert combo.currentIndex() == -1
# Changing choices should change Qt combo box. Let's first try with a case
# in which there is a matching data value in the new combo box
t.a = 3.5
assert combo.currentIndex() == 1
a_prop.set_choices(t, (4, 5, 3.5))
assert combo.count() == 3
assert t.a == 3.5
assert combo.currentIndex() == 2
assert combo.itemText(0) == 'value: 4'
assert combo.itemText(1) == 'value: 5'
assert combo.itemText(2) == 'value: 3.5'
assert combo.itemData(0).data == 4
assert combo.itemData(1).data == 5
assert combo.itemData(2).data == 3.5
# Now we change the choices so that there is no matching data - in this case
# the index should change to that given by default_index
a_prop.set_choices(t, (4, 5, 6))
assert t.a == 5
assert combo.currentIndex() == 1
assert combo.count() == 3
assert combo.itemText(0) == 'value: 4'
assert combo.itemText(1) == 'value: 5'
assert combo.itemText(2) == 'value: 6'
assert combo.itemData(0).data == 4
assert combo.itemData(1).data == 5
assert combo.itemData(2).data == 6
# Finally, if there are too few choices for the default_index to be valid,
# pick the last item in the combo
a_prop.set_choices(t, (9,))
assert t.a == 9
assert combo.currentIndex() == 0
assert combo.count() == 1
assert combo.itemText(0) == 'value: 9'
assert combo.itemData(0).data == 9
# Now just make sure that ChoiceSeparator works
separator = ChoiceSeparator('header')
a_prop.set_choices(t, (separator, 1, 2))
assert combo.count() == 3
assert combo.itemText(0) == 'header'
assert combo.itemData(0).data is separator
# And setting choices to an empty iterable shouldn't cause issues
a_prop.set_choices(t, ())
assert combo.count() == 0
# Try including an array in the choices
a_prop.set_choices(t, (4, 5, np.array([1, 2, 3])))
def test_connect_combo_selection_invalid():
t = Example()
combo = QtWidgets.QComboBox()
with pytest.raises(TypeError) as exc:
connect_combo_selection(t, 'b', combo)
assert exc.value.args[0] == 'connect_combo_selection requires a SelectionCallbackProperty'
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/selection.py 0000644 0000770 0000024 00000010637 00000000000 015477 0 ustar 00tom staff 0000000 0000000 import random
from weakref import WeakKeyDictionary
import numpy as np
from .core import CallbackProperty
__all__ = ['ChoiceSeparator', 'SelectionCallbackProperty']
class ChoiceSeparator(str):
pass
class SelectionCallbackProperty(CallbackProperty):
def __init__(self, default_index=0, choices=None, display_func=None, comparison_type=None, **kwargs):
if choices is not None and 'default' not in kwargs:
kwargs['default'] = choices[default_index]
super(SelectionCallbackProperty, self).__init__(**kwargs)
self.default_index = default_index
self.default_choices = choices or []
self.comparison_type = comparison_type
self._default_display_func = display_func
self._choices = WeakKeyDictionary()
self._display = WeakKeyDictionary()
self._force_next_sync = WeakKeyDictionary()
def __set__(self, instance, value):
if value is not None:
choices = self.get_choices(instance)
# For built-in scalar types we use ==, and for other types we use
# is, otherwise e.g. ComponentID returns something that evaluates
# to true when using ==.
if self.comparison_type == 'equality' or (self.comparison_type is None and np.isscalar(value)):
if not any(value == x for x in choices):
raise ValueError('value {0} is not in valid choices: {1}'.format(value, choices))
if self.comparison_type == 'identity' or (self.comparison_type is None and not np.isscalar(value)):
if not any(value is x for x in choices):
raise ValueError('value {0} is not in valid choices: {1}'.format(value, choices))
super(SelectionCallbackProperty, self).__set__(instance, value)
def force_next_sync(self, instance):
self._force_next_sync[instance] = True
def _get_full_info(self, instance):
if self._force_next_sync.get(instance, False):
try:
return self.__get__(instance), random.random()
finally:
self._force_next_sync[instance] = False
else:
return self.__get__(instance), self.get_choices(instance), self.get_choice_labels(instance)
def get_display_func(self, instance):
return self._display.get(instance, self._default_display_func)
def set_display_func(self, instance, display):
self._display[instance] = display
# selection = self.__get__(instance)
# self.notify(instance, selection, selection)
def get_choices(self, instance):
return self._choices.get(instance, self.default_choices)
def get_choice_labels(self, instance):
display = self._display.get(instance, str)
labels = []
for choice in self.get_choices(instance):
if isinstance(choice, ChoiceSeparator):
labels.append(str(choice))
else:
labels.append(display(choice))
return labels
def set_choices(self, instance, choices):
self._choices[instance] = choices
self._choices_updated(instance, choices)
selection = self.__get__(instance)
self.notify(instance, selection, selection)
def _choices_updated(self, instance, choices):
if not choices:
self.__set__(instance, None)
return
selection = self.__get__(instance)
# We do the following because 'selection in choice' actually compares
# equality not identity (and we really just care about identity here)
# However, for simple Python types, we also need to check ==.
for choice in choices:
if selection is choice or (np.isscalar(choice) and
(np.isreal(choice) or isinstance(choice, str)) and
selection == choice):
return
choices_without_separators = [choice for choice in choices
if not isinstance(choice, ChoiceSeparator)]
if choices_without_separators:
try:
selection = choices_without_separators[self.default_index]
except IndexError:
if self.default_index > 0:
selection = choices_without_separators[-1]
else:
selection = choices_without_separators[0]
else:
selection = None
self.__set__(instance, selection)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.2847497
echo-0.5/echo/tests/ 0000755 0000770 0000024 00000000000 00000000000 014273 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599381529.0
echo-0.5/echo/tests/__init__.py 0000644 0000770 0000024 00000000000 00000000000 016372 0 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/tests/test_containers.py 0000644 0000770 0000024 00000034030 00000000000 020051 0 ustar 00tom staff 0000000 0000000 import pytest
from unittest.mock import MagicMock
from echo import (CallbackProperty,
ListCallbackProperty,
DictCallbackProperty,
HasCallbackProperties)
class StubList(HasCallbackProperties):
prop1 = ListCallbackProperty()
prop2 = ListCallbackProperty()
class StubDict(HasCallbackProperties):
prop1 = DictCallbackProperty()
prop2 = DictCallbackProperty()
class Simple(HasCallbackProperties):
a = CallbackProperty()
def test_list_normal_callback():
stub = StubList()
test1 = MagicMock()
stub.add_callback('prop1', test1)
stub.prop1 = [3]
assert test1.call_count == 1
stub.prop2 = [4]
assert test1.call_count == 1
def test_list_invalid():
stub = StubList()
with pytest.raises(TypeError) as exc:
stub.prop1 = 'banana'
assert exc.value.args[0] == "callback property should be a list"
def test_list_default_empty():
stub = StubList()
stub.prop1.append(1)
def test_list_explicit_default():
class TestList(HasCallbackProperties):
prop = ListCallbackProperty(default=[1, 2, 3])
test1 = TestList()
assert test1.prop == [1, 2, 3]
test2 = TestList()
assert test2.prop == [1, 2, 3]
test1.prop.append(4)
assert test1.prop == [1, 2, 3, 4]
assert test2.prop == [1, 2, 3]
def test_list_change_callback():
stub = StubList()
test1 = MagicMock()
stub.add_callback('prop1', test1)
assert test1.call_count == 0
stub.prop1.append(3)
assert test1.call_count == 1
assert stub.prop1 == [3]
stub.prop1.clear()
assert test1.call_count == 2
assert stub.prop1 == []
stub.prop1.extend([1, 2, 3])
assert test1.call_count == 3
assert stub.prop1 == [1, 2, 3]
stub.prop1.insert(0, -1)
assert test1.call_count == 4
assert stub.prop1 == [-1, 1, 2, 3]
p = stub.prop1.pop()
assert test1.call_count == 5
assert p == 3
assert stub.prop1 == [-1, 1, 2]
stub.prop1.remove(1)
assert test1.call_count == 6
assert stub.prop1 == [-1, 2]
stub.prop1.reverse()
assert test1.call_count == 7
assert stub.prop1 == [2, -1]
stub.prop1.sort()
assert test1.call_count == 8
assert stub.prop1 == [-1, 2]
stub.prop1[0] = 3
assert test1.call_count == 9
assert stub.prop1 == [3, 2]
stub.prop1[:] = []
assert test1.call_count == 10
assert stub.prop1 == []
def test_state_in_a_list():
stub = StubList()
state1 = Simple()
state2 = Simple()
state3 = Simple()
state4 = Simple()
state5 = Simple()
# Add three of the state objects to the list in different ways
stub.prop1.append(state1)
stub.prop1.extend([state2, 3.4])
stub.prop1.insert(1, state3)
stub.prop1[3] = state4
# Check that all states except state 5 have a callback added
assert len(state1._global_callbacks) == 1
assert len(state2._global_callbacks) == 1
assert len(state3._global_callbacks) == 1
assert len(state4._global_callbacks) == 1
assert len(state5._global_callbacks) == 0
# Add a callback to the main list
callback = MagicMock()
stub.add_callback('prop1', callback)
# Check that modifying attributes of the state objects triggers the list
# callback.
assert callback.call_count == 0
state1.a = 1
assert callback.call_count == 1
state2.a = 1
assert callback.call_count == 2
state3.a = 1
assert callback.call_count == 3
state4.a = 1
assert callback.call_count == 4
state5.a = 1
assert callback.call_count == 4
# Remove one of the state objects and try again
stub.prop1.pop(0)
assert callback.call_count == 5
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 1
assert len(state3._global_callbacks) == 1
assert len(state4._global_callbacks) == 1
assert len(state5._global_callbacks) == 0
# Now modifying state1 sholdn't affect the call cont
state1.a = 2
assert callback.call_count == 5
state2.a = 2
assert callback.call_count == 6
state3.a = 2
assert callback.call_count == 7
state4.a = 2
assert callback.call_count == 8
state5.a = 2
assert callback.call_count == 8
# Remove again this time using remove
stub.prop1.remove(state2)
assert callback.call_count == 9
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 0
assert len(state3._global_callbacks) == 1
assert len(state4._global_callbacks) == 1
assert len(state5._global_callbacks) == 0
# Now modifying state2 sholdn't affect the call cont
state1.a = 3
assert callback.call_count == 9
state2.a = 3
assert callback.call_count == 9
state3.a = 3
assert callback.call_count == 10
state4.a = 3
assert callback.call_count == 11
state5.a = 3
assert callback.call_count == 11
# Remove using item access
stub.prop1[1] = 3.3
assert callback.call_count == 12
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 0
assert len(state3._global_callbacks) == 1
assert len(state4._global_callbacks) == 0
assert len(state5._global_callbacks) == 0
# Now modifying state4 sholdn't affect the call cont
state1.a = 4
assert callback.call_count == 12
state2.a = 4
assert callback.call_count == 12
state3.a = 4
assert callback.call_count == 13
state4.a = 4
assert callback.call_count == 13
state5.a = 4
assert callback.call_count == 13
# Now use slice access to remove state3 and add state5 in one go
stub.prop1[0:2] = [2.2, state5]
assert callback.call_count == 14
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 0
assert len(state3._global_callbacks) == 0
assert len(state4._global_callbacks) == 0
assert len(state5._global_callbacks) == 1
# Now only modifying state5 should have an effect
state1.a = 5
assert callback.call_count == 14
state2.a = 5
assert callback.call_count == 14
state3.a = 5
assert callback.call_count == 14
state4.a = 5
assert callback.call_count == 14
state5.a = 5
assert callback.call_count == 15
# On Python 3, check that clear does the right thing
stub.prop1.clear()
assert callback.call_count == 16
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 0
assert len(state3._global_callbacks) == 0
assert len(state4._global_callbacks) == 0
assert len(state5._global_callbacks) == 0
# Now the callback should never be called
state1.a = 6
assert callback.call_count == 16
state2.a = 6
assert callback.call_count == 16
state3.a = 6
assert callback.call_count == 16
state4.a = 6
assert callback.call_count == 16
state5.a = 6
assert callback.call_count == 16
def test_list_nested_callbacks():
stub1 = StubList()
stub2 = StubList()
simple = Simple()
stub1.prop1.append(stub2)
stub1.prop1.append(simple)
test1 = MagicMock()
stub1.add_callback('prop1', test1)
stub2.prop1.append(2)
assert test1.call_count == 1
simple.a = 'banana!'
assert test1.call_count == 2
def test_dict_normal_callback():
stub = StubDict()
test1 = MagicMock()
stub.add_callback('prop1', test1)
stub.prop1 = {'a': 1}
assert test1.call_count == 1
stub.prop2 = {'b': 2}
assert test1.call_count == 1
def test_dict_invalid():
stub = StubDict()
with pytest.raises(TypeError) as exc:
stub.prop1 = 'banana'
assert exc.value.args[0] == "Callback property should be a dictionary."
def test_dict_default_empty():
stub = StubDict()
stub.prop1['a'] = 1
def test_dict_explicit_default():
class TestDict(HasCallbackProperties):
prop = DictCallbackProperty(default={'a': 1, 'b': 2})
test1 = TestDict()
assert test1.prop == {'a': 1, 'b': 2}
test2 = TestDict()
assert test2.prop == {'a': 1, 'b': 2}
test1.prop['c'] = 3
assert test1.prop == {'a': 1, 'b': 2, 'c': 3}
assert test2.prop == {'a': 1, 'b': 2}
def test_dict_change_callback():
stub = StubDict()
test1 = MagicMock()
stub.add_callback('prop1', test1)
assert test1.call_count == 0
stub.prop1['a'] = 1
assert test1.call_count == 1
assert stub.prop1 == {'a': 1}
stub.prop1.clear()
assert test1.call_count == 2
assert stub.prop1 == {}
stub.prop1.update({'b': 2, 'c': 3, 'd': 4})
assert test1.call_count == 3
assert stub.prop1 == {'b': 2, 'c': 3, 'd': 4}
p = stub.prop1.pop('b')
assert test1.call_count == 4
assert p == 2
assert stub.prop1 == {'c': 3, 'd': 4}
k, v = stub.prop1.popitem()
assert test1.call_count == 5
assert stub.prop1 == {'c': 3} if k == 'd' else {'d': 4}
remaining_key = 'c' if k == 'd' else 'd'
stub.prop1[remaining_key] = 6
assert test1.call_count == 6
assert stub.prop1 == {remaining_key: 6}
stub.prop1.clear()
assert test1.call_count == 7
assert stub.prop1 == {}
def test_state_in_a_dict():
stub = StubDict()
state1 = Simple()
state2 = Simple()
state3 = Simple()
# Add three of the state objects to the dict in different ways
stub.prop1['a'] = state1
stub.prop1.update({'b': state2})
# Check that all states except state 3 have a callback added
assert len(state1._global_callbacks) == 1
assert len(state2._global_callbacks) == 1
assert len(state3._global_callbacks) == 0
# Add a callback to the main dict
callback = MagicMock()
stub.add_callback('prop1', callback)
# Check that modifying attributes of the state objects triggers the list
# callback.
assert callback.call_count == 0
state1.a = 1
assert callback.call_count == 1
state2.a = 1
assert callback.call_count == 2
state3.a = 1
assert callback.call_count == 2
# Remove one of the state objects and try again
stub.prop1.pop('a')
assert callback.call_count == 3
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 1
assert len(state3._global_callbacks) == 0
# Now modifying state1 sholdn't affect the call count
state1.a = 2
assert callback.call_count == 3
state2.a = 2
assert callback.call_count == 4
state3.a = 2
assert callback.call_count == 4
# Remove using item access and add state3
stub.prop1['b'] = 3.3
stub.prop1['c'] = state3
assert callback.call_count == 6
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 0
assert len(state3._global_callbacks) == 1
# Now modifying state2 sholdn't affect the call cont
state1.a = 4
assert callback.call_count == 6
state2.a = 4
assert callback.call_count == 6
state3.a = 4
assert callback.call_count == 7
# Check that clear does the right thing
stub.prop1.clear()
assert callback.call_count == 8
assert len(state1._global_callbacks) == 0
assert len(state2._global_callbacks) == 0
assert len(state3._global_callbacks) == 0
# Now the callback should never be called
state1.a = 6
assert callback.call_count == 8
state2.a = 6
assert callback.call_count == 8
state3.a = 6
assert callback.call_count == 8
def test_dict_nested_callbacks():
stub1 = StubDict()
stub2 = StubDict()
simple = Simple()
stub1.prop1['a'] = stub2
stub1.prop1['b'] = simple
test1 = MagicMock()
stub1.add_callback('prop1', test1)
stub2.prop1['c'] = 2
assert test1.call_count == 1
simple.a = 'banana!'
assert test1.call_count == 2
def test_multiple_nested_list_and_dict():
stubd = StubDict()
test1 = MagicMock()
stubd.add_callback('prop1', test1)
stubd.prop1 = {'a': {'b': {'c': 1}}}
assert test1.call_count == 1
stubd.prop1['a']['b']['c'] = 2
assert test1.call_count == 2
stubd.prop1['a']['b']['c'] = {'d': 3}
assert test1.call_count == 3
stubd.prop1['a']['b']['c']['d'] = 4
assert test1.call_count == 4
stubd.prop1['a']['b'] = [1, 2, 3]
assert test1.call_count == 5
stubd.prop1['a']['b'][1] = {'e': 6}
assert test1.call_count == 6
stubd.prop1['a']['b'][1]['e'] = 7
assert test1.call_count == 7
stubd.prop1['a'] = 2
assert test1.call_count == 8
stubl = StubList()
test2 = MagicMock()
stubl.add_callback('prop1', test2)
stubl.prop1 = [1, 2, {'a': 3, 'b': [4, 5, {'c': 6}]}]
assert test2.call_count == 1
stubl.prop1[2]['b'][2]['c'] = 5
assert test2.call_count == 2
stubl.prop1[2]['b'][2] = {'d': 7}
assert test2.call_count == 3
stubl.prop1[2]['b'][2]['d'] = 2
assert test2.call_count == 4
stubl.prop1[2]['b'][2] = [1, 2]
assert test2.call_count == 5
stubl.prop1[2]['b'][2][0] = 3
assert test2.call_count == 6
stubl.prop1[2] = [1, 2]
assert test2.call_count == 7
stubl.prop1[2][1] = 3
assert test2.call_count == 8
def test_list_additional_callbacks():
stub = StubList()
test1 = MagicMock()
test2 = MagicMock()
stub.add_callback('prop1', test1)
stub.prop1 = [3]
stub.prop2 = [4]
assert test1.call_count == 1
assert test2.call_count == 0
stub.prop1.callbacks.append(test2)
stub.prop2.append(5)
assert test1.call_count == 1
assert test2.call_count == 0
stub.prop1.append(2)
assert test1.call_count == 2
assert test2.call_count == 1
stub.prop1.callbacks.remove(test2)
stub.prop1.append(4)
assert test1.call_count == 3
assert test2.call_count == 1
def test_dict_additional_callbacks():
stub = StubDict()
test1 = MagicMock()
test2 = MagicMock()
stub.add_callback('prop1', test1)
stub.prop1 = {'a': 1}
stub.prop2 = {'b': 2}
assert test1.call_count == 1
assert test2.call_count == 0
stub.prop1.callbacks.append(test2)
stub.prop2['c'] = 3
assert test1.call_count == 1
assert test2.call_count == 0
stub.prop1['d'] = 4
assert test1.call_count == 2
assert test2.call_count == 1
stub.prop1.callbacks.remove(test2)
stub.prop1['e'] = 5
assert test1.call_count == 3
assert test2.call_count == 1
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/tests/test_core.py 0000644 0000770 0000024 00000034557 00000000000 016652 0 ustar 00tom staff 0000000 0000000 import pytest
from unittest.mock import MagicMock
from echo import (CallbackProperty, add_callback,
remove_callback, delay_callback,
ignore_callback, callback_property,
HasCallbackProperties, keep_in_sync)
class Stub(object):
prop1 = CallbackProperty()
prop2 = CallbackProperty(5)
prop3 = 5
class DecoratorStub(object):
def __init__(self):
self._val = 1
@callback_property
def prop(self):
return self._val * 2
@prop.setter
def prop(self, value):
self._val = value
def test_attribute_like_access():
stub = Stub()
assert stub.prop1 is None
assert stub.prop2 == 5
def test_attribute_like_set():
stub = Stub()
stub.prop1 = 10
assert stub.prop1 == 10
def test_class_access():
stub = Stub()
assert isinstance(type(stub).prop1, CallbackProperty)
def test_callback_fire_on_change():
stub = Stub()
test = MagicMock()
add_callback(stub, 'prop1', test)
stub.prop1 = 5
test.assert_called_once_with(5)
def test_callbacks_only_called_on_value_change():
stub = Stub()
test = MagicMock()
add_callback(stub, 'prop1', test)
stub.prop1 = 5
test.assert_called_once_with(5)
stub.prop1 = 5
assert test.call_count == 1
def test_callbacks_are_instance_specific():
s1, s2 = Stub(), Stub()
test = MagicMock()
add_callback(s2, 'prop1', test)
s1.prop1 = 100
assert test.call_count == 0
def test_remove_callback():
stub = Stub()
test = MagicMock()
add_callback(stub, 'prop1', test)
remove_callback(stub, 'prop1', test)
stub.prop1 = 5
assert test.call_count == 0
def test_add_callback_attribute_error_on_bad_name():
stub = Stub()
with pytest.raises(AttributeError):
add_callback(stub, 'bad_property', None)
def test_add_callback_type_error_if_not_calllback():
stub = Stub()
with pytest.raises(TypeError) as exc:
add_callback(stub, 'prop3', None)
assert exc.value.args[0] == "prop3 is not a CallbackProperty"
def test_remove_callback_attribute_error_on_bad_name():
stub = Stub()
with pytest.raises(AttributeError):
remove_callback(stub, 'bad_property', None)
def test_remove_callback_wrong_function():
stub = Stub()
test = MagicMock()
test2 = MagicMock()
add_callback(stub, 'prop1', test)
with pytest.raises(ValueError) as exc:
remove_callback(stub, 'prop1', test2)
assert exc.value.args[0].startswith('Callback function not found')
def test_remove_non_callback_property():
stub = Stub()
with pytest.raises(TypeError) as exc:
remove_callback(stub, 'prop3', None)
assert exc.value.args[0] == 'prop3 is not a CallbackProperty'
def test_remove_callback_not_found():
stub = Stub()
with pytest.raises(ValueError) as exc:
remove_callback(stub, 'prop1', None)
assert exc.value.args[0] == "Callback function not found: None"
def test_disable_callback():
stub = Stub()
test = MagicMock()
add_callback(stub, 'prop1', test)
Stub.prop1.disable(stub)
stub.prop1 = 100
assert test.call_count == 0
Stub.prop1.enable(stub)
stub.prop1 = 100
assert test.call_count == 0 # not changed
stub.prop1 = 200
assert test.call_count == 1
def test_delay_callback():
test = MagicMock()
stub = Stub()
add_callback(stub, 'prop1', test)
with delay_callback(stub, 'prop1'):
stub.prop1 = 100
stub.prop1 = 200
stub.prop1 = 300
assert test.call_count == 0
test.assert_called_once_with(300)
def test_delay_callback_nested():
test = MagicMock()
stub = Stub()
add_callback(stub, 'prop1', test)
with delay_callback(stub, 'prop1'):
with delay_callback(stub, 'prop1'):
stub.prop1 = 100
stub.prop1 = 200
stub.prop1 = 300
assert test.call_count == 0
assert test.call_count == 0
test.assert_called_once_with(300)
def test_delay_callback_not_called_if_unmodified():
test = MagicMock()
stub = Stub()
add_callback(stub, 'prop1', test)
with delay_callback(stub, 'prop1'):
pass
assert test.call_count == 0
def test_callback_with_two_arguments():
stub = Stub()
stub.prop1 = 5
on_change = MagicMock()
add_callback(stub, 'prop1', on_change, echo_old=True)
stub.prop1 = 10
on_change.assert_called_once_with(5, 10)
@pytest.mark.parametrize('context_func', (delay_callback, ignore_callback))
def test_context_on_non_callback(context_func):
stub = Stub()
with pytest.raises(TypeError) as exc:
with context_func(stub, 'prop3'):
pass
assert exc.value.args[0] == "prop3 is not a CallbackProperty"
def test_delay_multiple():
stub = Stub()
test = MagicMock()
test2 = MagicMock()
add_callback(stub, 'prop1', test)
add_callback(stub, 'prop2', test2)
with delay_callback(stub, 'prop1', 'prop2'):
stub.prop1 = 50
stub.prop1 = 100
stub.prop2 = 200
assert test.call_count == 0
assert test2.call_count == 0
test.assert_called_once_with(100)
test2.assert_called_once_with(200)
def test_ignore_multiple():
stub = Stub()
test = MagicMock()
test2 = MagicMock()
add_callback(stub, 'prop1', test)
add_callback(stub, 'prop2', test2)
with ignore_callback(stub, 'prop1', 'prop2'):
stub.prop1 = 100
stub.prop2 = 200
assert test.call_count == 0
assert test2.call_count == 0
assert test.call_count == 0
assert test2.call_count == 0
def test_delay_only_calls_if_changed():
stub = Stub()
test = MagicMock()
add_callback(stub, 'prop1', test)
with delay_callback(stub, 'prop1'):
pass
assert test.call_count == 0
val = stub.prop1
with delay_callback(stub, 'prop1'):
stub.prop1 = val
assert test.call_count == 0
def test_decorator_form():
stub = DecoratorStub()
test = MagicMock()
add_callback(stub, 'prop', test)
assert stub.prop == 2
stub.prop = 5
test.assert_called_once_with(10)
assert stub.prop == 10
def test_docstring():
class Simple(object):
a = CallbackProperty(docstring='important')
s = Simple()
assert type(s).a.__doc__ == 'important'
class State(HasCallbackProperties):
a = CallbackProperty()
b = CallbackProperty()
c = CallbackProperty()
d = 1
def test_class_add_remove_callback():
state = State()
class mockclass(object):
def __init__(self):
self.call_count = 0
self.args = ()
self.kwargs = {}
def __call__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.call_count += 1
test1 = mockclass()
state.add_callback('a', test1)
# Deliberaty adding to c twice to make sure it works fine with two callbacks
test2 = mockclass()
state.add_callback('c', test2)
test3 = mockclass()
state.add_callback('c', test3, echo_old=True)
test4 = mockclass()
state.add_global_callback(test4)
state.a = 1
assert test1.call_count == 1
assert test1.args == (1,)
assert test2.call_count == 0
assert test3.call_count == 0
assert test4.call_count == 1
assert test4.kwargs == dict(a=1)
state.b = 1
assert test1.call_count == 1
assert test2.call_count == 0
assert test3.call_count == 0
assert test4.call_count == 2
assert test4.kwargs == dict(b=1)
state.c = 1
assert test1.call_count == 1
assert test2.call_count == 1
assert test4.kwargs == dict(c=1)
assert test3.call_count == 1
assert test3.args == (None, 1)
assert test4.call_count == 3
assert test4.kwargs == dict(c=1)
state.remove_callback('a', test1)
state.a = 2
state.b = 2
state.c = 2
assert test1.call_count == 1
assert test2.call_count == 2
assert test3.call_count == 2
assert test4.call_count == 6
state.remove_callback('c', test2)
state.a = 3
state.b = 3
state.c = 3
assert test1.call_count == 1
assert test2.call_count == 2
assert test3.call_count == 3
assert test4.call_count == 9
state.remove_callback('c', test3)
state.a = 4
state.b = 4
state.c = 4
assert test1.call_count == 1
assert test2.call_count == 2
assert test3.call_count == 3
assert test4.call_count == 12
state.remove_global_callback(test4)
state.a = 6
state.b = 6
state.c = 6
assert test1.call_count == 1
assert test2.call_count == 2
assert test3.call_count == 3
assert test4.call_count == 12
def test_class_is_callback_property():
state = State()
assert state.is_callback_property('a')
assert state.is_callback_property('b')
assert state.is_callback_property('c')
assert not state.is_callback_property('d')
def test_class_add_remove_callback_invalid():
def callback():
pass
state = State()
state.z = 'banana'
with pytest.raises(TypeError) as exc:
state.add_callback('banana', callback)
assert exc.value.args[0] == "attribute 'banana' is not a callback property"
with pytest.raises(TypeError) as exc:
state.remove_callback('banana', callback)
assert exc.value.args[0] == "attribute 'banana' is not a callback property"
def test_keep_in_sync():
class State1(object):
a = CallbackProperty()
b = CallbackProperty()
class State2(object):
c = CallbackProperty()
state1 = State1()
state2 = State2()
state1_control = State1()
state2_control = State2()
s1 = keep_in_sync(state1, 'a', state1, 'b')
s2 = keep_in_sync(state1, 'a', state2, 'c')
state1.a = 1
assert state1.b == 1
assert state1_control.b is None
assert state2.c == 1
assert state2_control.c is None
state1.b = 3
assert state1.a == 3
assert state1_control.a is None
assert state2.c == 3
assert state2_control.c is None
state2.c = 5
assert state1.a == 5
assert state1_control.a is None
assert state1.b == 5
assert state1_control.b is None
s1.disable_syncing()
state1.a = 7
assert state1.b == 5
assert state1_control.b is None
assert state2.c == 7
assert state2_control.c is None
s2.disable_syncing()
def test_cleanup_when_objects_destroyed():
state = State()
class BasicClass():
def __init__(self, s):
self.s = s
self.s.add_callback('a', self.callback)
self.raise_error = False
def callback(self, arg):
if self.raise_error:
raise ValueError('Should never get here')
def isolated(state):
c = BasicClass(state)
state.a = 1
c.raise_error = True
isolated(state)
state.a = 2
def test_cleanup_when_objects_destroyed_kwargs():
state = State()
class BasicClass():
def __init__(self, s):
self.s = s
self.s.add_global_callback(self.callback)
self.raise_error = False
def callback(self, **kwargs):
if self.raise_error:
raise ValueError('Should never get here')
def isolated(state):
c = BasicClass(state)
state.a = 1
c.raise_error = True
isolated(state)
state.a = 2
def test_delay_global_callback():
# Regression test to make sure that delay_callback works for global
# callbacks too.
state = State()
test1 = MagicMock()
state.add_callback('a', test1)
test2 = MagicMock()
state.add_global_callback(test2)
with delay_callback(state, 'a'):
state.a = 100
assert test1.call_count == 0
assert test2.call_count == 0
test1.assert_called_once_with(100)
test2.assert_called_once_with(a=100)
test2.reset_mock()
with delay_callback(state, 'a'):
state.b = 200
assert test2.call_count == 1
test2.assert_called_once_with(b=200)
test2.reset_mock()
with delay_callback(state, 'a', 'b'):
state.a = 300
state.b = 400
assert test2.call_count == 0
test2.assert_called_once_with(a=300, b=400)
def test_delay_global_callback_stub():
# Make sure that adding the global callback delay functionality doesn't
# break things when we are dealing with a plain class without HasCallbackProperties
stub = Stub()
test1 = MagicMock()
add_callback(stub, 'prop1', test1)
with delay_callback(stub, 'prop1'):
stub.prop1 = 100
assert test1.call_count == 0
test1.assert_called_once_with(100)
def test_ignore_global_callback():
# Regression test to make sure that ignore_callback works for global
# callbacks too.
state = State()
test1 = MagicMock()
state.add_callback('a', test1)
test2 = MagicMock()
state.add_global_callback(test2)
with ignore_callback(state, 'a'):
state.a = 100
assert test1.call_count == 0
assert test2.call_count == 0
assert test1.call_count == 0
assert test2.call_count == 0
test2.reset_mock()
with ignore_callback(state, 'a'):
state.b = 200
assert test2.call_count == 1
test2.assert_called_once_with(b=200)
test2.reset_mock()
with ignore_callback(state, 'a', 'b'):
state.a = 300
state.b = 400
assert test2.call_count == 0
assert test2.call_count == 0
def test_ignore_global_callback_stub():
# Make sure that adding the global callback ignore functionality doesn't
# break things when we are dealing with a plain class without HasCallbackProperties
stub = Stub()
test1 = MagicMock()
add_callback(stub, 'prop1', test1)
with ignore_callback(stub, 'prop1'):
stub.prop1 = 100
assert test1.call_count == 0
assert test1.call_count == 0
def test_delay_in_delayed_callback():
# Regression test for a bug that occurred if a delayed callback included
# a delay itself.
state = State()
def callback(*args, **kwargs):
with delay_callback(state, 'a'):
state.a = 2
state.add_callback('a', callback)
with delay_callback(state, 'a', 'b'):
state.a = 100
def test_ignore_in_ignored_callback():
# Regression test for a bug that occurred if a delayed callback included
# a delay itself.
state = State()
def callback(*args, **kwargs):
with ignore_callback(state, 'a'):
state.a = 2
state.add_callback('a', callback)
with ignore_callback(state, 'a', 'b'):
state.a = 100
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/tests/test_selection.py 0000644 0000770 0000024 00000010503 00000000000 017670 0 ustar 00tom staff 0000000 0000000 import pytest
from unittest.mock import MagicMock
from ..core import HasCallbackProperties, delay_callback
from ..selection import SelectionCallbackProperty, ChoiceSeparator
class Example(HasCallbackProperties):
a = SelectionCallbackProperty()
b = SelectionCallbackProperty(default_index=1)
c = SelectionCallbackProperty(default_index=-1)
class TestSelectionCallbackProperty():
def setup_method(self, method):
self.state = Example()
self.a = Example.a
self.b = Example.b
self.c = Example.c
def test_set_choices(self):
# make sure that default_index is respected
self.a.set_choices(self.state, [1, 2])
self.b.set_choices(self.state, [1, 2])
self.c.set_choices(self.state, [1, 2, 3])
assert self.state.a == 1
assert self.state.b == 2
assert self.state.c == 3
self.a.set_choices(self.state, None)
assert self.state.a is None
def test_set_value(self):
# Since there are no choices set yet, the properties cannot be set to
# any values yet.
with pytest.raises(ValueError) as exc:
self.state.a = 1
assert exc.value.args[0] == "value 1 is not in valid choices: []"
self.a.set_choices(self.state, [1, 2])
# The following should work since it is a valid choice
self.state.a = 2
# Again if we try and set to an invalid value, things break
with pytest.raises(ValueError) as exc:
self.state.a = 3
assert exc.value.args[0] == "value 3 is not in valid choices: [1, 2]"
def test_value_constant(self):
# Make sure that the value is preserved if possible
self.a.set_choices(self.state, [1, 2])
self.state.a = 2
self.a.set_choices(self.state, [2, 5, 3])
assert self.state.a == 2
self.a.set_choices(self.state, [1, 4, 5])
assert self.state.a == 1
self.a.set_choices(self.state, [4, 2, 1])
assert self.state.a == 1
def test_get_choices(self):
self.a.set_choices(self.state, [1, 2])
self.a.get_choices == [1, 2]
self.a.set_choices(self.state, [2, 5, 3])
self.a.get_choices == [2, 5, 3]
def test_display_func(self):
separator = ChoiceSeparator('header')
self.a.set_choices(self.state, [separator, 1, 2])
self.a.get_choice_labels(self.state) == ['header', '1', '2']
assert self.a.get_display_func(self.state) is None
assert self.b.get_display_func(self.state) is None
def val(x):
return 'val{0}'.format(x)
self.a.set_display_func(self.state, val)
self.a.get_choice_labels(self.state) == ['header', 'val1', 'val2']
assert self.a.get_display_func(self.state) is val
assert self.b.get_display_func(self.state) is None
def test_callbacks(self):
# Make sure that callbacks are called when either choices or selection
# are changed
func = MagicMock()
self.state.add_callback('a', func)
self.a.set_choices(self.state, [1, 2, 3])
assert func.called_once_with(1)
self.state.a = 2
assert func.called_once_with(2)
self.a.set_choices(self.state, [4, 5, 6])
assert func.called_once_with(4)
def test_choice_separator(self):
separator = ChoiceSeparator('header')
self.a.set_choices(self.state, [separator, 1, 2])
assert self.state.a == 1
separator = ChoiceSeparator('header')
self.a.set_choices(self.state, [separator])
assert self.state.a is None
def test_delay(self):
func = MagicMock()
self.state.add_callback('a', func)
# Here we set the choices and as a result the selection changes from
# None to a value, so the callback is called after the delay block
with delay_callback(self.state, 'a'):
self.a.set_choices(self.state, [4, 5, 6])
assert func.call_count == 0
assert func.called_once_with(4)
func.reset_mock()
# Check that the callback gets called even if only the choices
# but not the selection are changed in a delay block
with delay_callback(self.state, 'a'):
self.a.set_choices(self.state, [1, 2, 4])
assert func.call_count == 0
assert func.called_once_with(4)
func.reset_mock()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/echo/version.py 0000644 0000770 0000024 00000000320 00000000000 015163 0 ustar 00tom staff 0000000 0000000 from pkg_resources import get_distribution, DistributionNotFound
__all__ = ['__version__']
try:
__version__ = get_distribution('echo').version
except DistributionNotFound:
__version__ = 'undefined'
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.2198637
echo-0.5/echo.egg-info/ 0000755 0000770 0000024 00000000000 00000000000 014623 5 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599572027.0
echo-0.5/echo.egg-info/PKG-INFO 0000644 0000770 0000024 00000004663 00000000000 015731 0 ustar 00tom staff 0000000 0000000 Metadata-Version: 2.1
Name: echo
Version: 0.5
Summary: Callback Properties in Python
Home-page: https://github.com/glue-viz/echo
Author: Chris Beaumont and Thomas Robitaille
Author-email: thomas.robitaille@gmail.com
Maintainer: Chris Beaumont and Thomas Robitaille
Maintainer-email: thomas.robitaille@gmail.com
License: MIT
Description: |Azure Status| |Coverage status|
echo: Callback Properties in Python
===================================
Echo is a small library for attaching callback functions to property
state changes. For example:
::
class Switch(object):
state = CallbackProperty('off')
def report_change(state):
print 'the switch is %s' % state
s = Switch()
add_callback(s, 'state', report_change)
s.state = 'on' # prints 'the switch is on'
CalllbackProperties can also be built using decorators
::
class Switch(object):
@callback_property
def state(self):
return self._state
@state.setter
def state(self, value):
if value not in ['on', 'off']:
raise ValueError("invalid setting")
self._state = value
Full documentation is avilable `here `__
.. |Azure Status| image:: https://dev.azure.com/glue-viz/echo/_apis/build/status/glue-viz.echo?branchName=master
:target: https://dev.azure.com/glue-viz/echo/_build/latest?definitionId=4&branchName=master
.. |Coverage Status| image:: https://codecov.io/gh/glue-viz/echo/branch/master/graph/badge.svg
:target: https://codecov.io/gh/glue-viz/echo
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Operating System :: OS Independent
Classifier: Topic :: Utilities
Requires-Python: >=3.6
Provides-Extra: test
Provides-Extra: docs
Provides-Extra: qt
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599572027.0
echo-0.5/echo.egg-info/SOURCES.txt 0000644 0000770 0000024 00000001504 00000000000 016507 0 ustar 00tom staff 0000000 0000000 .coveragerc
.gitignore
.readthedocs.yml
CHANGES.rst
LICENSE
MANIFEST.in
README.rst
azure-pipelines.yml
requirements.txt
setup.cfg
setup.py
tox.ini
doc/Makefile
doc/api.rst
doc/conf.py
doc/core.rst
doc/gui.rst
doc/index.rst
doc/installation.rst
echo/__init__.py
echo/callback_container.py
echo/conftest.py
echo/containers.py
echo/core.py
echo/selection.py
echo/version.py
echo.egg-info/PKG-INFO
echo.egg-info/SOURCES.txt
echo.egg-info/dependency_links.txt
echo.egg-info/requires.txt
echo.egg-info/top_level.txt
echo.egg-info/zip-safe
echo/qt/__init__.py
echo/qt/autoconnect.py
echo/qt/connect.py
echo/qt/tests/__init__.py
echo/qt/tests/test_autoconnect.py
echo/qt/tests/test_connect.py
echo/qt/tests/test_connect_combo_selection.py
echo/tests/__init__.py
echo/tests/test_containers.py
echo/tests/test_core.py
echo/tests/test_selection.py ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599572027.0
echo-0.5/echo.egg-info/dependency_links.txt 0000644 0000770 0000024 00000000001 00000000000 020671 0 ustar 00tom staff 0000000 0000000
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599572027.0
echo-0.5/echo.egg-info/requires.txt 0000644 0000770 0000024 00000000161 00000000000 017221 0 ustar 00tom staff 0000000 0000000 numpy
qtpy
[docs]
sphinx
sphinx-automodapi
numpydoc
sphinx-rtd-theme
[qt]
PyQt5>=5.9
[test]
pytest
pytest-cov
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599572027.0
echo-0.5/echo.egg-info/top_level.txt 0000644 0000770 0000024 00000000005 00000000000 017350 0 ustar 00tom staff 0000000 0000000 echo
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599572027.0
echo-0.5/echo.egg-info/zip-safe 0000644 0000770 0000024 00000000001 00000000000 016253 0 ustar 00tom staff 0000000 0000000
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1451486606.0
echo-0.5/requirements.txt 0000644 0000770 0000024 00000000000 00000000000 015465 0 ustar 00tom staff 0000000 0000000 ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 011452 x ustar 00 0000000 0000000 28 mtime=1599572028.2899723
echo-0.5/setup.cfg 0000644 0000770 0000024 00000001743 00000000000 014041 0 ustar 00tom staff 0000000 0000000 [metadata]
name = echo
url = https://github.com/glue-viz/echo
author = Chris Beaumont and Thomas Robitaille
author_email = thomas.robitaille@gmail.com
maintainer = Chris Beaumont and Thomas Robitaille
maintainer_email = thomas.robitaille@gmail.com
classifiers =
Development Status :: 4 - Beta
Environment :: Console
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Natural Language :: English
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Operating System :: OS Independent
Topic :: Utilities
license = MIT
description = Callback Properties in Python
long_description = file: README.rst
[options]
zip_safe = True
packages = find:
python_requires = >=3.6
setup_requires = setuptools_scm
install_requires =
numpy
qtpy
[options.extras_require]
test =
pytest
pytest-cov
docs =
sphinx
sphinx-automodapi
numpydoc
sphinx-rtd-theme
qt =
PyQt5>=5.9
[egg_info]
tag_build =
tag_date = 0
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/setup.py 0000644 0000770 0000024 00000000550 00000000000 013725 0 ustar 00tom staff 0000000 0000000 #!/usr/bin/env python
import sys
from distutils.version import LooseVersion
try:
import setuptools
assert LooseVersion(setuptools.__version__) >= LooseVersion('30.3')
except (ImportError, AssertionError):
sys.stderr.write("ERROR: setuptools 30.3 or later is required\n")
sys.exit(1)
from setuptools import setup
setup(use_scm_version=True)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 011453 x ustar 00 0000000 0000000 22 mtime=1599571818.0
echo-0.5/tox.ini 0000644 0000770 0000024 00000001631 00000000000 013527 0 ustar 00tom staff 0000000 0000000 [tox]
envlist =
py{36,37,38}-{codestyle,test,docs}-{pyqt57,pyqt58,pyqt59,pyqt510,pyqt511,pyqt512,pyqt513,pyside511,pyside512,pyside513}
requires = pip >= 18.0
setuptools >= 30.3.0
[testenv]
passenv =
DISPLAY
HOME
changedir =
test: .tmp/{envname}
docs: doc
deps =
pyqt59: PyQt5==5.9.*
pyqt510: PyQt5==5.10.*
pyqt511: PyQt5==5.11.*
pyqt512: PyQt5==5.12.*
pyqt513: PyQt5==5.13.*
pyqt514: PyQt5==5.14.*
pyside511: PySide2==5.11.*
pyside512: PySide2==5.12.*
pyside513: PySide2==5.13.*
pyside514: PySide2==5.14.*
extras =
test
docs: docs
commands =
test: pip freeze
test: pytest --pyargs echo --cov echo --cov-config={toxinidir}/setup.cfg {posargs}
docs: sphinx-build -n -b html -d _build/doctrees . _build/html
[testenv:codestyle]
deps = flake8
skipsdist = true
skip_install = true
commands =
flake8 --max-line-length=120 echo