././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1761131124.443291 traittypes-0.2.3/0000755000175000017500000000000015076135164013342 5ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/LICENSE0000644000175000017500000000272115075634623014354 0ustar00martinmartinCopyright (c) IPython Development Team. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of traittypes nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/MANIFEST.in0000644000175000017500000000056315075634623015107 0ustar00martinmartininclude CONTRIBUTING.md include README.md include LICENSE # Documentation graft docs exclude docs/\#* # Examples graft examples # docs subdirs we want to skip prune docs/build prune docs/gh-pages prune docs/dist # Patterns to exclude from any directory global-exclude *~ global-exclude *.pyc global-exclude *.pyo global-exclude .git global-exclude .ipynb_checkpoints ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1761131124.4432788 traittypes-0.2.3/PKG-INFO0000644000175000017500000000233415076135164014441 0ustar00martinmartinMetadata-Version: 2.4 Name: traittypes Version: 0.2.3 Summary: Scipy trait types Home-page: http://ipython.org Author: IPython Development Team Author-email: ipython-dev@scipy.org License: BSD Keywords: Interactive,Interpreter,Shell,Web Platform: Linux Platform: Mac OS X Platform: Windows Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 License-File: LICENSE Requires-Dist: traitlets>=4.2.2 Provides-Extra: test Requires-Dist: numpy; extra == "test" Requires-Dist: pandas; extra == "test" Requires-Dist: xarray; extra == "test" Requires-Dist: pytest; extra == "test" Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: home-page Dynamic: keywords Dynamic: license Dynamic: license-file Dynamic: platform Dynamic: provides-extra Dynamic: requires-dist Dynamic: summary Custom trait types for scientific computing. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761120882.0 traittypes-0.2.3/README.md0000644000175000017500000000463115076111162014615 0ustar00martinmartin# Scipy Trait Types [![Build Status](https://travis-ci.org/jupyter-widgets/traittypes.svg?branch=master)](https://travis-ci.org/jupyter-widgets/traittypes) [![Documentation Status](https://readthedocs.org/projects/traittypes/badge/?version=latest)](http://traittypes.readthedocs.org/en/latest/?badge=latest) Trait types for NumPy, SciPy and friends ## Goals Provide a reference implementation of trait types for common data structures used in the scipy stack such as - [numpy](https://github.com/numpy/numpy) arrays - [pandas](https://github.com/pydata/pandas) and [xarray](https://github.com/pydata/xarray) data structures which are out of the scope of the main [traitlets](https://github.com/ipython/traitlets) project but are a common requirement to build applications with traitlets in combination with the scipy stack. Another goal is to create adequate serialization and deserialization routines for these trait types to be used with the [ipywidgets](https://github.com/ipython/ipywidgets) project (`to_json` and `from_json`). These could also return a list of binary buffers as allowed by the current messaging protocol. ## Installation Using `pip`: Make sure you have [pip installed](https://pip.readthedocs.org/en/stable/installing/) and run: ``` pip install traittypes ``` Using `conda`: ``` conda install -c conda-forge traittypes ``` ## Usage `traittypes` extends the `traitlets` library with an implementation of trait types for numpy arrays, pandas dataframes, pandas series, xarray datasets and xarray dataarrays. - `traittypes` works around some limitations with numpy array comparison to only trigger change events when necessary. - `traittypes` also extends the traitlets API for adding custom validators to constrain proposed values for the attribute. For a general introduction to `traitlets`, check out the [traitlets documentation](https://traitlets.readthedocs.io/en/stable/). ### Example usage with a custom validator ```python from traitlets import HasTraits, TraitError from traittypes import Array def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() foo.bar = [1, 2] # Should raise a TraitError ``` ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1761131124.4420917 traittypes-0.2.3/docs/0000755000175000017500000000000015076135164014272 5ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/Makefile0000644000175000017500000001643515075634623015746 0ustar00martinmartin# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext api default: html help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" 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/traittypes.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/traittypes.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/traittypes" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/traittypes" @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." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.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." ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/make.bat0000644000175000017500000001613515075634623015710 0ustar00martinmartin@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source set I18NSPHINXOPTS=%SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\traittypes.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\traittypes.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/requirements.txt0000644000175000017500000000000515075634623017554 0ustar00martinmartin-e . ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1761131124.4422774 traittypes-0.2.3/docs/source/0000755000175000017500000000000015076135164015572 5ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/source/api_documentation.rst0000644000175000017500000000141515075634623022032 0ustar00martinmartinAPI Reference Documentation --------------------------- The ``SciType`` trait type is the base trait type for all Scipy trait types. It complements the ``traitlets.TraitType`` with a special API to register custom validators. .. autoclass:: traittypes.traittypes.SciType :members: The ``Array`` trait type holds a numpy Array. .. autoclass:: traittypes.traittypes.Array The ``DataFrame`` trait type holds a pandas DataFrame. .. autoclass:: traittypes.traittypes.DataFrame The ``Series`` trait type holds a pandas Series. .. autoclass:: traittypes.traittypes.Series The ``Dataset`` trait type holds an xarray Dataset. .. autoclass:: traittypes.traittypes.Dataset The ``DataArray`` trait type holds an xarray DataArray. .. autoclass:: traittypes.traittypes.DataArray ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/source/conf.py0000644000175000017500000002007315075634623017076 0ustar00martinmartin# -*- coding: utf-8 -*- # # traittypes documentation build configuration file. # # NOTE: This file has been edited manually from the auto-generated one from # sphinx. Do NOT delete and re-generate. If any changes from sphinx are # needed, generate a scratch one and merge by hand any new fields needed. # import sys import os # We load the traittypes release info into a dict by explicit execution import traittypes release = traittypes.__version__ # -- 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.intersphinx', 'sphinx.ext.autosummary', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'sphinx.ext.mathjax', ] autosummary_generate = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. source_suffix = '.rst' # Add dev disclaimer. if 'dev' in release: rst_prolog = """ .. note:: This documentation is for a development version of traittypes. There may be significant differences from the latest stable release. """ # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'traittypes' author = u'The IPython Contributors' # 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 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 = [] # 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 = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. 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 = 'traittypesdoc' # -- 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', 'traittypes.tex', u'traittypes Documentation', u'IPython contributors', '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', 'traittypes', u'traittypes Documentation', [u'IPython contributors'], 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', 'traittypes', u'traittypes Documentation', u'IPython contributors', 'traittypes', '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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/source/index.rst0000644000175000017500000000030715075634623017436 0ustar00martinmartin============================================= traittypes: Trait Types for Scientific Python ============================================= .. toctree:: introduction usage api_documentation ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/source/introduction.rst0000644000175000017500000000154315075634623021053 0ustar00martinmartin.. _introduction: Introduction ============ The `traittypes` module provides a robust reference implementation of trait types for common data structures used in the scipy stack such as - `numpy `_ arrays - `pandas `_ and `xarray `_ data structures which are out of the scope of the main `traitlets `_ project but are a common requirement to build applications with traitlets in combination with the scipy stack. Another goal is to create adequate serialization and deserialization routines for these trait types to be used with the `ipywidgets `_ project (``to_json`` and ``from_json``). These could also return a list of binary buffers as allowed by the current messaging protocol. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/docs/source/usage.rst0000644000175000017500000000150615075634623017435 0ustar00martinmartinUsage ===== Example: Validating the Shape of a Numpy Array ---------------------------------------------- We pass a validation function to the ``valid`` method of the ``Array`` trait type. In this example, the validation function is returned by the ``shape`` closure which stores the tuple in its closure. .. code:: from traitlets import HasTraits, TraitError from traittypes import Array def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() foo.bar = [1, 2] # Should raise a TraitError ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1761131124.4434962 traittypes-0.2.3/setup.cfg0000644000175000017500000000014615076135164015164 0ustar00martinmartin[bdist_wheel] universal = 1 [metadata] license_file = LICENSE [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761037566.0 traittypes-0.2.3/setup.py0000644000175000017500000000543715075646376015100 0ustar00martinmartin#!/usr/bin/env python # coding: utf-8 # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function # the name of the project name = 'traittypes' #----------------------------------------------------------------------------- # Minimal Python version sanity check #----------------------------------------------------------------------------- import sys v = sys.version_info if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3, 5)): error = "ERROR: %s requires Python version 2.7 or 3.5 or above." % name print(error, file=sys.stderr) sys.exit(1) PY3 = (sys.version_info[0] >= 3) #----------------------------------------------------------------------------- # get on with it #----------------------------------------------------------------------------- import os from glob import glob from distutils.core import setup pjoin = os.path.join here = os.path.abspath(os.path.dirname(__file__)) pkg_root = pjoin(here, name) packages = [] for d, _, _ in os.walk(pjoin(here, name)): if os.path.exists(pjoin(d, '__init__.py')): packages.append(d[len(here)+1:].replace(os.path.sep, '.')) version_ns = {} with open(pjoin(here, name, '_version.py')) as f: exec(f.read(), {}, version_ns) setup_args = dict( name = name, version = version_ns['__version__'], scripts = glob(pjoin('scripts', '*')), packages = packages, description = "Scipy trait types", long_description= "Custom trait types for scientific computing.", author = 'IPython Development Team', author_email = 'ipython-dev@scipy.org', url = 'http://ipython.org', license = 'BSD', platforms = "Linux, Mac OS X, Windows", keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'], classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], ) if 'develop' in sys.argv or any(a.startswith('bdist') for a in sys.argv): import setuptools setuptools_args = {} install_requires = setuptools_args['install_requires'] = [ 'traitlets>=4.2.2', ] extras_require = setuptools_args['extras_require'] = { 'test': [ 'numpy', 'pandas', 'xarray', 'pytest', # traitlets[test] require this ] } if 'setuptools' in sys.modules: setup_args.update(setuptools_args) if __name__ == '__main__': setup(**setup_args) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1761131124.4424758 traittypes-0.2.3/traittypes/0000755000175000017500000000000015076135164015552 5ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/traittypes/__init__.py0000644000175000017500000000011215075634623017660 0ustar00martinmartinfrom .traittypes import * from ._version import version_info, __version__ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131103.0 traittypes-0.2.3/traittypes/_version.py0000644000175000017500000000011015076135137017740 0ustar00martinmartinversion_info = (0, 2, 3) __version__ = '.'.join(map(str, version_info)) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1761131124.442827 traittypes-0.2.3/traittypes/tests/0000755000175000017500000000000015076135164016714 5ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/traittypes/tests/__init__.py0000644000175000017500000000000015075634623021016 0ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/traittypes/tests/test_import_errors.py0000644000175000017500000000032415075634623023235 0ustar00martinmartin import pytest from ..traittypes import _DelayedImportError def test_delayed_access_raises(): dummy = _DelayedImportError('mypackage') with pytest.raises(RuntimeError): dummy.asarray([1, 2, 3]) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761120919.0 traittypes-0.2.3/traittypes/tests/test_traittypes.py0000644000175000017500000001651215076111227022534 0ustar00martinmartin# encoding: utf-8 """Tests for traittypes.traittypes.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from unittest import TestCase from traitlets import HasTraits, TraitError, observe, Undefined from traitlets.tests.test_traitlets import TraitTestBase from traittypes import Array, DataFrame, Series, Dataset, DataArray import numpy as np import pandas as pd import xarray as xr # Good / Bad value trait test cases class IntArrayTrait(HasTraits): value = Array().tag(dtype=np.int32) class TestIntArray(TraitTestBase): """ Test dtype validation with a ``dtype=np.int32`` """ obj = IntArrayTrait() _good_values = [1, [1, 2, 3], [[1, 2, 3], [4, 5, 6]], np.array([1])] def assertEqual(self, v1, v2): return np.testing.assert_array_equal(v1, v2) # Other test cases class TestArray(TestCase): def test_array_equal(self): notifications = [] class Foo(HasTraits): bar = Array([1, 2]) @observe('bar') def _(self, change): notifications.append(change) foo = Foo() foo.bar = [1, 2] self.assertFalse(len(notifications)) foo.bar = [1, 1] self.assertTrue(len(notifications)) def test_initial_values(self): class Foo(HasTraits): a = Array() b = Array(dtype='int') c = Array(None, allow_none=True) d = Array([]) e = Array(Undefined) foo = Foo() self.assertTrue(np.array_equal(foo.a, np.array(0))) self.assertTrue(np.array_equal(foo.b, np.array(0))) self.assertTrue(foo.c is None) self.assertTrue(np.array_equal(foo.d, [])) self.assertTrue(foo.e is Undefined) def test_allow_none(self): class Foo(HasTraits): bar = Array() baz = Array(allow_none=True) foo = Foo() with self.assertRaises(TraitError): foo.bar = None foo.baz = None def test_custom_validators(self): # Test with a squeeze coercion def squeeze(trait, value): if 1 in value.shape: value = np.squeeze(value) return value class Foo(HasTraits): bar = Array().valid(squeeze) foo = Foo(bar=[[1], [2]]) self.assertTrue(np.array_equal(foo.bar, [1, 2])) foo.bar = [[1], [2], [3]] self.assertTrue(np.array_equal(foo.bar, [1, 2, 3])) # Test with a shape constraint def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() with self.assertRaises(TraitError): foo.bar = [1] new_value = [[0, 1], [1, 0]] foo.bar = new_value self.assertTrue(np.array_equal(foo.bar, new_value)) class TestDataFrame(TestCase): def test_df_equal(self): notifications = [] class Foo(HasTraits): bar = DataFrame([1, 2]) @observe('bar') def _(self, change): notifications.append(change) foo = Foo() foo.bar = [1, 2] self.assertEqual(notifications, []) foo.bar = [1, 1] self.assertEqual(len(notifications), 1) def test_initial_values(self): class Foo(HasTraits): a = DataFrame() b = DataFrame(None, allow_none=True) c = DataFrame([]) d = DataFrame(Undefined) foo = Foo() self.assertTrue(foo.a.equals(pd.DataFrame())) self.assertTrue(foo.b is None) self.assertTrue(foo.c.equals(pd.DataFrame([]))) self.assertTrue(foo.d is Undefined) def test_allow_none(self): class Foo(HasTraits): bar = DataFrame() baz = DataFrame(allow_none=True) foo = Foo() with self.assertRaises(TraitError): foo.bar = None foo.baz = None class TestSeries(TestCase): def test_series_equal(self): notifications = [] class Foo(HasTraits): bar = Series([1, 2], dtype=np.int64) @observe('bar') def _(self, change): notifications.append(change) foo = Foo() foo.bar = [1, 2] self.assertEqual(notifications, []) foo.bar = [1, 1] self.assertEqual(len(notifications), 1) def test_initial_values(self): class Foo(HasTraits): a = Series() b = Series(None, allow_none=True) c = Series([]) d = Series(Undefined) foo = Foo() self.assertTrue(foo.a.equals(pd.Series())) self.assertTrue(foo.b is None) self.assertTrue(foo.c.equals(pd.Series([]))) self.assertTrue(foo.d is Undefined) def test_allow_none(self): class Foo(HasTraits): bar = Series() baz = Series(allow_none=True) foo = Foo() with self.assertRaises(TraitError): foo.bar = None foo.baz = None class TestDataset(TestCase): def test_ds_equal(self): notifications = [] class Foo(HasTraits): bar = Dataset({'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.14}) @observe('bar') def _(self, change): notifications.append(change) foo = Foo() foo.bar = {'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.14} self.assertEqual(notifications, []) foo.bar = {'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.15} self.assertEqual(len(notifications), 1) def test_initial_values(self): class Foo(HasTraits): a = Dataset() b = Dataset(None, allow_none=True) d = Dataset(Undefined) foo = Foo() self.assertTrue(foo.a.equals(xr.Dataset())) self.assertTrue(foo.b is None) self.assertTrue(foo.d is Undefined) def test_allow_none(self): class Foo(HasTraits): bar = Dataset() baz = Dataset(allow_none=True) foo = Foo() with self.assertRaises(TraitError): foo.bar = None foo.baz = None class TestDataArray(TestCase): def test_ds_equal(self): notifications = [] class Foo(HasTraits): bar = DataArray([[0, 1], [2, 3]]) @observe('bar') def _(self, change): notifications.append(change) foo = Foo() foo.bar = [[0, 1], [2, 3]] self.assertEqual(notifications, []) foo.bar = [[0, 1], [2, 4]] self.assertEqual(len(notifications), 1) def test_initial_values(self): class Foo(HasTraits): b = DataArray(None, allow_none=True) c = DataArray([]) d = DataArray(Undefined) foo = Foo() self.assertTrue(foo.b is None) self.assertTrue(foo.c.equals(xr.DataArray([]))) self.assertTrue(foo.d is Undefined) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/traittypes/tests/test_validators.py0000644000175000017500000000236315075634623022504 0ustar00martinmartin#!/usr/bin/env python # coding: utf-8 # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import pytest from traitlets import HasTraits, TraitError from ..traittypes import SciType def test_coercion_validator(): # Test with a squeeze coercion def truncate(trait, value): return value[:10] class Foo(HasTraits): bar = SciType().valid(truncate) foo = Foo(bar=list(range(20))) assert foo.bar == list(range(10)) foo.bar = list(range(10, 40)) assert foo.bar == list(range(10, 20)) def test_validaton_error(): # Test with a squeeze coercion def maxlen(trait, value): if len(value) > 10: raise ValueError('Too long sequence!') return value class Foo(HasTraits): bar = SciType().valid(maxlen) # Check that it works as expected: foo = Foo(bar=list(range(5))) assert foo.bar == list(range(5)) # Check that it fails as expected: with pytest.raises(TraitError): # Should convert ValueError to TraitError foo.bar = list(range(10, 40)) assert foo.bar == list(range(5)) # Check that it can again be set correctly foo = Foo(bar=list(range(5, 10))) assert foo.bar == list(range(5, 10)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131097.0 traittypes-0.2.3/traittypes/traittypes.py0000644000175000017500000002375315076135131020340 0ustar00martinmartinimport inspect import warnings from traitlets import TraitType, TraitError, Undefined from .utils import Sentinel class _DelayedImportError(object): def __init__(self, package_name): self.package_name = package_name def __getattribute__(self, name): package_name = super(_DelayedImportError, self).__getattribute__('package_name') raise RuntimeError('Missing dependency: %s' % package_name) try: import numpy as np except ImportError: np = _DelayedImportError('numpy') Empty = Sentinel('Empty', 'traittypes', """ Used in traittypes to specify that the default value should be an empty dataset """) class SciType(TraitType): """A base trait type for numpy arrays, pandas dataframes, pandas series, xarray datasets and xarray dataarrays.""" def __init__(self, **kwargs): super(SciType, self).__init__(**kwargs) self.validators = [] def valid(self, *validators): """ Register new trait validators Validators are functions that take two arguments. - The trait instance - The proposed value Validators return the (potentially modified) value, which is either assigned to the HasTraits attribute or input into the next validator. They are evaluated in the order in which they are provided to the `valid` function. Example ------- .. code:: python # Test with a shape constraint def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() foo.bar = [1, 2] # Should raise a TraitError """ self.validators.extend(validators) return self def validate(self, obj, value): """Validate the value against registered validators.""" try: for validator in self.validators: value = validator(self, value) return value except (ValueError, TypeError) as e: raise TraitError(e) class Array(SciType): """A numpy array trait type.""" info_text = 'a numpy array' dtype = None def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(Array, self).validate(obj, value) try: r = np.asarray(value, dtype=self.dtype) if isinstance(value, np.ndarray) and r is not value: warnings.warn( 'Given trait value dtype "%s" does not match required type "%s". ' 'A coerced copy has been created.' % ( np.dtype(value.dtype).name, np.dtype(self.dtype).name)) value = r except (ValueError, TypeError) as e: raise TraitError(e) return super(Array, self).validate(obj, value) def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if not np.array_equal(old_value, new_value): obj._notify_trait(self.name, old_value, new_value) def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): self.dtype = dtype if default_value is Empty: default_value = np.array(0, dtype=self.dtype) elif default_value is not None and default_value is not Undefined: default_value = np.asarray(default_value, dtype=self.dtype) super(Array, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return np.copy(self.default_value) class PandasType(SciType): """A pandas dataframe or series trait type.""" info_text = 'a pandas dataframe or series' klass = None def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(PandasType, self).validate(obj, value) try: value = self.klass(value) except (ValueError, TypeError) as e: raise TraitError(e) return super(PandasType, self).validate(obj, value) def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if ((old_value is None and new_value is not None) or (old_value is Undefined and new_value is not Undefined) or not old_value.equals(new_value)): obj._notify_trait(self.name, old_value, new_value) def __init__(self, default_value=Empty, allow_none=False, klass=None, klass_kwargs=None, **kwargs): if klass is None: klass = self.klass if klass_kwargs is None: klass_kwargs = {} if (klass is not None) and inspect.isclass(klass): self.klass = klass else: raise TraitError('The klass attribute must be a class' ' not: %r' % klass) if default_value is Empty: default_value = klass(**klass_kwargs) elif default_value is not None and default_value is not Undefined: default_value = klass(default_value, **klass_kwargs) super(PandasType, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return self.default_value.copy() class DataFrame(PandasType): """A pandas dataframe trait type.""" info_text = 'a pandas dataframe' def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): if 'klass' not in kwargs and self.klass is None: import pandas as pd kwargs['klass'] = pd.DataFrame super(DataFrame, self).__init__( default_value=default_value, allow_none=allow_none, **kwargs) self.tag(dtype=dtype) class Series(PandasType): """A pandas series trait type.""" info_text = 'a pandas series' dtype = None def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): if 'klass' not in kwargs and self.klass is None: import pandas as pd kwargs['klass'] = pd.Series if dtype is None: dtype = np.float64 super(Series, self).__init__( default_value=default_value, allow_none=allow_none, klass_kwargs={"dtype": dtype}, **kwargs) self.tag(dtype=dtype) self.dtype = dtype class XarrayType(SciType): """An xarray dataset or dataarray trait type.""" info_text = 'an xarray dataset or dataarray' klass = None def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(XarrayType, self).validate(obj, value) try: value = self.klass(value) except (ValueError, TypeError) as e: raise TraitError(e) return super(XarrayType, self).validate(obj, value) def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if ((old_value is None and new_value is not None) or (old_value is Undefined and new_value is not Undefined) or not old_value.equals(new_value)): obj._notify_trait(self.name, old_value, new_value) def __init__(self, default_value=Empty, allow_none=False, klass=None, **kwargs): if klass is None: klass = self.klass if (klass is not None) and inspect.isclass(klass): self.klass = klass else: raise TraitError('The klass attribute must be a class' ' not: %r' % klass) if default_value is Empty: default_value = klass() elif default_value is not None and default_value is not Undefined: default_value = klass(default_value) super(XarrayType, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return self.default_value.copy() class Dataset(XarrayType): """An xarray dataset trait type.""" info_text = 'an xarray dataset' def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): if 'klass' not in kwargs and self.klass is None: import xarray as xr kwargs['klass'] = xr.Dataset super(Dataset, self).__init__( default_value=default_value, allow_none=allow_none, **kwargs) self.tag(dtype=dtype) class DataArray(XarrayType): """An xarray dataarray trait type.""" info_text = 'an xarray dataarray' dtype = None def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): if 'klass' not in kwargs and self.klass is None: import xarray as xr kwargs['klass'] = xr.DataArray super(DataArray, self).__init__( default_value=default_value, allow_none=allow_none, **kwargs) self.tag(dtype=dtype) self.dtype = dtype ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761032595.0 traittypes-0.2.3/traittypes/utils.py0000644000175000017500000000101415075634623017263 0ustar00martinmartin"""Sentinel class for constants with useful reprs""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. class Sentinel(object): def __init__(self, name, module, docstring=None): self.name = name self.module = module if docstring: self.__doc__ = docstring def __repr__(self): return str(self.module) + '.' + self.name def __copy__(self): return self def __deepcopy__(self, memo): return self ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1761131124.4428644 traittypes-0.2.3/traittypes.egg-info/0000755000175000017500000000000015076135164017244 5ustar00martinmartin././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131124.0 traittypes-0.2.3/traittypes.egg-info/PKG-INFO0000644000175000017500000000233415076135164020343 0ustar00martinmartinMetadata-Version: 2.4 Name: traittypes Version: 0.2.3 Summary: Scipy trait types Home-page: http://ipython.org Author: IPython Development Team Author-email: ipython-dev@scipy.org License: BSD Keywords: Interactive,Interpreter,Shell,Web Platform: Linux Platform: Mac OS X Platform: Windows Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 License-File: LICENSE Requires-Dist: traitlets>=4.2.2 Provides-Extra: test Requires-Dist: numpy; extra == "test" Requires-Dist: pandas; extra == "test" Requires-Dist: xarray; extra == "test" Requires-Dist: pytest; extra == "test" Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: home-page Dynamic: keywords Dynamic: license Dynamic: license-file Dynamic: platform Dynamic: provides-extra Dynamic: requires-dist Dynamic: summary Custom trait types for scientific computing. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131124.0 traittypes-0.2.3/traittypes.egg-info/SOURCES.txt0000644000175000017500000000116115076135164021127 0ustar00martinmartinLICENSE MANIFEST.in README.md setup.cfg setup.py docs/Makefile docs/make.bat docs/requirements.txt docs/source/api_documentation.rst docs/source/conf.py docs/source/index.rst docs/source/introduction.rst docs/source/usage.rst traittypes/__init__.py traittypes/_version.py traittypes/traittypes.py traittypes/utils.py traittypes.egg-info/PKG-INFO traittypes.egg-info/SOURCES.txt traittypes.egg-info/dependency_links.txt traittypes.egg-info/requires.txt traittypes.egg-info/top_level.txt traittypes/tests/__init__.py traittypes/tests/test_import_errors.py traittypes/tests/test_traittypes.py traittypes/tests/test_validators.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131124.0 traittypes-0.2.3/traittypes.egg-info/dependency_links.txt0000644000175000017500000000000115076135164023312 0ustar00martinmartin ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131124.0 traittypes-0.2.3/traittypes.egg-info/requires.txt0000644000175000017500000000006415076135164021644 0ustar00martinmartintraitlets>=4.2.2 [test] numpy pandas xarray pytest ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1761131124.0 traittypes-0.2.3/traittypes.egg-info/top_level.txt0000644000175000017500000000001315076135164021770 0ustar00martinmartintraittypes