├── .clang-format ├── .coveragerc ├── .gitattributes ├── .github ├── dependabot.yml ├── pull_request_template.md └── workflows │ ├── release-to-pypi.yml │ ├── run-core-traits-tests.yml │ ├── run-style-checks.yml │ ├── run-traits-tests.yml │ ├── test-documentation-build.yml │ └── test-from-pypi.yml ├── .gitignore ├── .readthedocs.yaml ├── CHANGES.rst ├── LICENSE-CC-BY-3.0.txt ├── LICENSE.txt ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── make.bat └── source │ ├── _static │ ├── default.css │ ├── e-logo-rev.png │ └── et.ico │ ├── _templates │ ├── layout.html │ └── search.html │ ├── changelog.rst │ ├── conf.py │ ├── index.rst │ ├── traits_api_reference │ ├── base_trait_handler.rst │ ├── constants.rst │ ├── ctrait.rst │ ├── ctraits.rst │ ├── editor_factories.rst │ ├── has_traits.rst │ ├── index.rst │ ├── interface_checker.rst │ ├── trait_base.rst │ ├── trait_converters.rst │ ├── trait_dict_object.rst │ ├── trait_errors.rst │ ├── trait_factory.rst │ ├── trait_handler.rst │ ├── trait_handlers.rst │ ├── trait_list_object.rst │ ├── trait_notifiers.rst │ ├── trait_numeric.rst │ ├── trait_set_object.rst │ ├── trait_type.rst │ ├── trait_types.rst │ ├── traits.adaptation.rst │ ├── traits.etsconfig.rst │ ├── traits.observation.rst │ ├── traits.rst │ ├── traits.testing.rst │ ├── traits.util.rst │ ├── traits_listener.rst │ └── version.rst │ ├── traits_tutorial │ ├── index.rst │ └── introduction.rst │ └── traits_user_manual │ ├── advanced.rst │ ├── appendix.rst │ ├── custom.rst │ ├── debugging.rst │ ├── deferring.rst │ ├── defining.rst │ ├── images │ └── adaptation.png │ ├── index.rst │ ├── installation.rst │ ├── internals.rst │ ├── intro.rst │ ├── listening.rst │ ├── notification.rst │ └── testing.rst ├── edm.yaml ├── etstool.py ├── examples ├── README.rst └── tutorials │ ├── default.css │ ├── doc_examples │ ├── __init__.py │ ├── default.css │ ├── doc_examples.rst │ ├── examples │ │ ├── __init__.py │ │ ├── adapt_metadata.py │ │ ├── add_class_trait.py │ │ ├── all_traits_features.py │ │ ├── all_wildcard.py │ │ ├── bad_self_ref.py │ │ ├── cached_prop.py │ │ ├── circular_definition.py │ │ ├── compound.py │ │ ├── configure_traits.py │ │ ├── custom_traithandler.py │ │ ├── deferring_notification.py │ │ ├── delegate.py │ │ ├── disallow.py │ │ ├── dynamic_notification.py │ │ ├── event.py │ │ ├── instance_trait_defaults.py │ │ ├── interface_definition.py │ │ ├── interface_implementation.py │ │ ├── keywords.py │ │ ├── lesson.desc │ │ ├── list_notifier.py │ │ ├── mapped.py │ │ ├── metadata.py │ │ ├── minimal.py │ │ ├── object_trait_attrs.py │ │ ├── observe_decorator.py │ │ ├── observe_different_events.py │ │ ├── observe_method.py │ │ ├── observe_optional.py │ │ ├── observe_post_init.py │ │ ├── override_default.py │ │ ├── post_init_notification.py │ │ ├── prototype_prefix.py │ │ ├── simple_adapter.py │ │ ├── static_notification.py │ │ ├── temp_wildcard.py │ │ ├── this.py │ │ ├── trait_reuse.py │ │ ├── trait_subclass.py │ │ ├── transient_metadata.py │ │ ├── use_custom_th.py │ │ ├── widget.py │ │ ├── wildcard.py │ │ ├── wildcard_all.py │ │ ├── wildcard_name.py │ │ ├── wildcard_rules.py │ │ └── wizard.py │ └── lesson.desc │ ├── introduction │ ├── traits_4.0 │ ├── decorators │ │ ├── cached_property.py │ │ ├── on_trait_change.py │ │ └── tutorial.desc │ ├── default.css │ ├── delegation │ │ ├── delegation.py │ │ └── tutorial.desc │ ├── extended_trait_change │ │ ├── extended_trait_change.py │ │ ├── properties.py │ │ └── tutorial.desc │ ├── getstate_setstate │ │ ├── getstate.py │ │ └── tutorial.desc │ ├── interfaces │ │ ├── interfaces.py │ │ └── tutorial.desc │ ├── trait_types │ │ ├── core_traits.py │ │ ├── new_types.py │ │ ├── trait_types.py │ │ └── tutorial.desc │ └── tutorial.desc │ └── tutor.py ├── image_LICENSE.txt ├── pyproject.toml ├── setup.cfg ├── setup.py └── traits ├── __init__.py ├── __init__.pyi ├── adaptation ├── __init__.py ├── adaptation_error.py ├── adaptation_manager.py ├── adaptation_offer.py ├── adapter.py ├── api.py └── tests │ ├── __init__.py │ ├── abc_examples.py │ ├── benchmark.py │ ├── interface_examples.py │ ├── lazy_examples.py │ ├── test_adaptation_manager.py │ ├── test_adaptation_offer.py │ ├── test_adapter.py │ └── test_global_adaptation_manager.py ├── api.py ├── api.pyi ├── base_trait_handler.py ├── base_trait_handler.pyi ├── constants.py ├── constants.pyi ├── ctrait.py ├── ctrait.pyi ├── ctraits.c ├── ctraits.pyi ├── editor_factories.py ├── editor_factories.pyi ├── etsconfig ├── __init__.py ├── api.py ├── etsconfig.py └── tests │ ├── __init__.py │ └── test_etsconfig.py ├── examples ├── __init__.py ├── _etsdemo_info.py ├── introduction │ ├── 0_introduction.py │ ├── 1_validation.py │ ├── 2_initialization.py │ ├── 3_observation.py │ ├── 4_properties.py │ ├── 5_documentation.py │ ├── 6_visualization.py │ ├── default.css │ ├── images │ │ ├── LICENSE.txt │ │ ├── sample_0001.png │ │ └── sample_0002.png │ └── index.rst └── tests │ ├── __init__.py │ └── test_etsdemo_info.py ├── has_traits.py ├── has_traits.pyi ├── interface_checker.py ├── observation ├── __init__.py ├── _anytrait_filter.py ├── _dict_change_event.py ├── _dict_item_observer.py ├── _dsl_grammar.lark ├── _filtered_trait_observer.py ├── _generated_parser.py ├── _has_traits_helpers.py ├── _i_notifier.py ├── _i_observer.py ├── _list_change_event.py ├── _list_item_observer.py ├── _metadata_filter.py ├── _named_trait_observer.py ├── _observe.py ├── _observer_change_notifier.py ├── _observer_graph.py ├── _set_change_event.py ├── _set_item_observer.py ├── _testing.py ├── _trait_added_observer.py ├── _trait_change_event.py ├── _trait_event_notifier.py ├── api.py ├── events.py ├── exception_handling.py ├── exceptions.py ├── expression.py ├── i_observable.py ├── observe.py ├── parsing.py └── tests │ ├── __init__.py │ ├── test_dict_change_event.py │ ├── test_dict_item_observer.py │ ├── test_exception_handling.py │ ├── test_expression.py │ ├── test_filtered_trait_observer.py │ ├── test_generated_parser.py │ ├── test_has_traits_helpers.py │ ├── test_list_change_event.py │ ├── test_list_item_observer.py │ ├── test_metadata_filter.py │ ├── test_named_trait_observer.py │ ├── test_observe.py │ ├── test_observer_change_notifier.py │ ├── test_observer_graph.py │ ├── test_parsing.py │ ├── test_set_change_event.py │ ├── test_set_item_observer.py │ ├── test_trait_added_observer.py │ ├── test_trait_change_event.py │ └── test_trait_event_notifier.py ├── py.typed ├── stubs_tests ├── __init__.py ├── examples │ ├── Any.py │ ├── BaseClass.py │ ├── Bool.py │ ├── CInt.py │ ├── Callable.py │ ├── Complex.py │ ├── Date.py │ ├── Datetime.py │ ├── Dict.py │ ├── Enum.py │ ├── File.py │ ├── Float.py │ ├── HasStrictTraits.py │ ├── HasTraits.py │ ├── Instance.py │ ├── Int.py │ ├── Interface.py │ ├── List.py │ ├── Map.py │ ├── PrefixList.py │ ├── PrefixMap.py │ ├── Property.py │ ├── Range.py │ ├── Set.py │ ├── Str.py │ ├── String.py │ ├── Time.py │ ├── Tuple.py │ ├── UUID.py │ ├── WeakRef.py │ └── completeness.py ├── numpy_examples │ └── Array.py ├── test_all.py └── util.py ├── testing ├── __init__.py ├── api.py ├── doctest_tools.py ├── optional_dependencies.py ├── tests │ ├── __init__.py │ ├── test_optional_dependencies.py │ └── test_unittest_tools.py └── unittest_tools.py ├── tests ├── __init__.py ├── check_observe_timing.py ├── check_timing.py ├── test-data │ └── historical-pickles │ │ ├── README │ │ ├── generate_pickles.py │ │ ├── hipt-t5.2.0-p0-float-ctrait.pkl │ │ ├── hipt-t5.2.0-p1-float-ctrait.pkl │ │ ├── hipt-t5.2.0-p2-float-ctrait.pkl │ │ ├── hipt-t5.2.0-p3-float-ctrait.pkl │ │ ├── hipt-t5.2.0-p4-float-ctrait.pkl │ │ └── hipt-t5.2.0-p5-float-ctrait.pkl ├── test_abc.py ├── test_any.py ├── test_anytrait_static_notifiers.py ├── test_array.py ├── test_array_or_none.py ├── test_automatic_adaptation.py ├── test_bool.py ├── test_callable.py ├── test_class_traits.py ├── test_clone.py ├── test_comparison_mode.py ├── test_complex.py ├── test_configure_traits.py ├── test_constant.py ├── test_constants.py ├── test_container_events.py ├── test_copy_traits.py ├── test_copyable_trait_names.py ├── test_ctraits.py ├── test_date.py ├── test_datetime.py ├── test_delegate.py ├── test_dict.py ├── test_directory.py ├── test_dynamic_notifiers.py ├── test_dynamic_trait_definition.py ├── test_editor_factories.py ├── test_enum.py ├── test_event_order.py ├── test_expression.py ├── test_extended_notifiers.py ├── test_extended_trait_change.py ├── test_file.py ├── test_float.py ├── test_float_range.py ├── test_get_traits.py ├── test_has_required_traits.py ├── test_has_traits.py ├── test_historical_unpickling.py ├── test_instance.py ├── test_int_range_long.py ├── test_integer.py ├── test_integer_range.py ├── test_interface_checker.py ├── test_interfaces.py ├── test_keyword_args.py ├── test_list.py ├── test_list_events.py ├── test_listeners.py ├── test_map.py ├── test_new_notifiers.py ├── test_none.py ├── test_observe.py ├── test_pickle_validated_dict.py ├── test_prefix_list.py ├── test_prefix_map.py ├── test_property_delete.py ├── test_property_notifications.py ├── test_python_properties.py ├── test_range.py ├── test_readonly.py ├── test_regression.py ├── test_special_event_handlers.py ├── test_static_notifiers.py ├── test_str_handler.py ├── test_string.py ├── test_sync_traits.py ├── test_target.py ├── test_time.py ├── test_trait_base.py ├── test_trait_change_event_tracer.py ├── test_trait_converters.py ├── test_trait_cycle.py ├── test_trait_default_initializer.py ├── test_trait_dict_list_set_event.py ├── test_trait_dict_object.py ├── test_trait_exceptions.py ├── test_trait_get_set.py ├── test_trait_list_dict.py ├── test_trait_list_object.py ├── test_trait_notifiers.py ├── test_trait_set_object.py ├── test_trait_types.py ├── test_traits.py ├── test_traits_listener.py ├── test_tuple.py ├── test_type.py ├── test_ui_notifiers.py ├── test_undefined.py ├── test_unicode_traits.py ├── test_union.py ├── test_uuid.py ├── test_validated_tuple.py ├── test_version.py ├── test_view_elements.py ├── test_weak_ref.py └── tuple_test_mixin.py ├── trait_base.py ├── trait_converters.py ├── trait_dict_object.py ├── trait_errors.py ├── trait_factory.py ├── trait_handler.py ├── trait_handler.pyi ├── trait_handlers.py ├── trait_handlers.pyi ├── trait_list_object.py ├── trait_notifiers.py ├── trait_numeric.py ├── trait_numeric.pyi ├── trait_set_object.py ├── trait_type.py ├── trait_type.pyi ├── trait_types.py ├── trait_types.pyi ├── traits.py ├── traits.pyi ├── traits_listener.py ├── traits_notifiers.pyi └── util ├── __init__.py ├── api.py ├── async_trait_wait.py ├── camel_case.py ├── clean_strings.py ├── deprecated.py ├── event_tracer.py ├── home_directory.py ├── import_symbol.py ├── resource.py ├── tests ├── __init__.py ├── test_async_trait_wait.py ├── test_camel_case.py ├── test_deprecated.py ├── test_import_symbol.py ├── test_message_records.py ├── test_record_containers.py ├── test_record_events.py ├── test_trait_documenter.py └── test_weakidddict.py ├── toposort.py ├── trait_documenter.py └── weakiddict.py /.clang-format: -------------------------------------------------------------------------------- 1 | # A style for the clang-format tool that roughly matches Python's PEP 7. 2 | # Used with Clang 9.0 to update ctraits.c, via: 3 | # 4 | # $ clang-format --style=file -i traits/ctraits.c 5 | 6 | BasedOnStyle: Google 7 | AlignAfterOpenBracket: AlwaysBreak 8 | AlwaysBreakAfterReturnType: All 9 | AllowShortIfStatementsOnASingleLine: Never 10 | BreakBeforeBraces: Stroustrup 11 | ColumnLimit: 79 12 | IndentWidth: 4 13 | BreakBeforeBinaryOperators: NonAssignment 14 | StatementMacros: ['PyObject_HEAD'] 15 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = traits 4 | omit = */tests/* 5 | 6 | [paths] 7 | source = 8 | ./traits 9 | */traits 10 | 11 | [report] 12 | # Regexes for lines to exclude from consideration 13 | exclude_lines = 14 | # Have to re-enable the standard pragma 15 | pragma: no cover 16 | 17 | # Don't complain about missing debug-only code: 18 | def __repr__ 19 | 20 | # Don't complain if tests don't hit defensive assertion code: 21 | raise AssertionError 22 | raise NotImplementedError 23 | 24 | if __name__ == .__main__.: 25 | 26 | ignore_errors = True 27 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # For archives, substitute the commit hash in the setup.py file. 2 | /setup.py export-subst 3 | 4 | # Make sure that pickle files are treated as binary, else Git 5 | # may try to modify line-endings when cloning on Windows. 6 | *.pkl binary 7 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | **Checklist** 2 | - [ ] Tests 3 | - [ ] Update API reference (`docs/source/traits_api_reference`) 4 | - [ ] Update User manual (`docs/source/traits_user_manual`) 5 | - [ ] Update type annotation hints in stub files 6 | -------------------------------------------------------------------------------- /.github/workflows/release-to-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Release to PyPI 2 | 3 | on: 4 | workflow_dispatch: 5 | release: 6 | types: [published] 7 | 8 | jobs: 9 | build-wheels: 10 | strategy: 11 | matrix: 12 | os: [windows-latest, macos-13, macos-14, ubuntu-latest] 13 | 14 | runs-on: ${{ matrix.os }} 15 | 16 | steps: 17 | 18 | - name: Check out the release commit 19 | uses: actions/checkout@v4 20 | 21 | - name: Set up Python 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: '3.10' 25 | 26 | - name: Install Python packages needed for wheel build and upload 27 | run: python -m pip install twine 28 | 29 | - name: Build wheels 30 | uses: pypa/cibuildwheel@v2.23.3 31 | 32 | - name: Check and upload wheels 33 | env: 34 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 35 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 36 | run: | 37 | python -m twine check --strict wheelhouse/*.whl 38 | python -m twine upload wheelhouse/*.whl 39 | 40 | build-sdist: 41 | runs-on: ubuntu-latest 42 | 43 | steps: 44 | 45 | - name: Check out the release commit 46 | uses: actions/checkout@v4 47 | 48 | - name: Set up Python 49 | uses: actions/setup-python@v5 50 | with: 51 | python-version: '3.10' 52 | 53 | - name: Install Python packages needed for sdist build and upload 54 | run: python -m pip install build twine 55 | 56 | - name: Build sdist 57 | run: python -m build --sdist 58 | 59 | - name: Publish sdist to PyPI 60 | env: 61 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 62 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 63 | run: | 64 | python -m twine check --strict dist/* 65 | python -m twine upload dist/* 66 | -------------------------------------------------------------------------------- /.github/workflows/run-core-traits-tests.yml: -------------------------------------------------------------------------------- 1 | # Test run with no optional dependencies installed, to help 2 | # detect any accidental dependencies. 3 | 4 | name: Core tests 5 | 6 | on: 7 | pull_request 8 | 9 | jobs: 10 | core: 11 | strategy: 12 | matrix: 13 | os: [ubuntu-latest, windows-latest] 14 | python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13'] 15 | 16 | runs-on: ${{ matrix.os }} 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v5 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | allow-prereleases: true 25 | - name: Install local package 26 | run: | 27 | # Uninstall setuptools so that the tests will catch any accidental 28 | # dependence of the Traits source on setuptools. Note that in future 29 | # setuptools may not exist in a newly-created venv 30 | # https://github.com/python/cpython/issues/95299 31 | python -m pip uninstall -y setuptools 32 | python -m pip install -v . 33 | python -m pip list 34 | - name: Test Traits package 35 | run: | 36 | mkdir testdir 37 | cd testdir 38 | python -m unittest discover -v traits 39 | -------------------------------------------------------------------------------- /.github/workflows/run-style-checks.yml: -------------------------------------------------------------------------------- 1 | name: Style check 2 | 3 | on: 4 | pull_request 5 | 6 | jobs: 7 | style: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Python 3.10 13 | uses: actions/setup-python@v5 14 | with: 15 | python-version: '3.10' 16 | - name: Install dependencies and local packages 17 | run: | 18 | python -m pip install flake8 19 | python -m pip install flake8-ets 20 | - name: Run style checks 21 | run: | 22 | python -m flake8 23 | -------------------------------------------------------------------------------- /.github/workflows/run-traits-tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | - pull_request 5 | - workflow_dispatch 6 | 7 | jobs: 8 | tests: 9 | strategy: 10 | matrix: 11 | os: [ubuntu-latest, windows-latest, macos-latest] 12 | python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13'] 13 | 14 | runs-on: ${{ matrix.os }} 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v5 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | allow-prereleases: true 23 | - name: Install test dependencies and local package 24 | run: | 25 | python -m pip install -v .[test] 26 | - name: Create clean test directory 27 | run: | 28 | mkdir testdir 29 | - name: Test Traits package 30 | run: python -m unittest discover -v traits 31 | working-directory: testdir 32 | -------------------------------------------------------------------------------- /.github/workflows/test-documentation-build.yml: -------------------------------------------------------------------------------- 1 | name: Doc build 2 | 3 | on: 4 | pull_request 5 | 6 | jobs: 7 | docs: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Python 3.10 13 | uses: actions/setup-python@v5 14 | with: 15 | python-version: '3.10' 16 | - name: Install dependencies and local packages 17 | run: python -m pip install .[docs] 18 | - name: Build HTML documentation with Sphinx 19 | run: | 20 | cd docs 21 | python -m sphinx -b html -W source build 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Python bytecode 2 | *.pyc 3 | 4 | # Compiled C extensions 5 | *.pyd 6 | *.so 7 | 8 | # Build directories 9 | *.egg-info/ 10 | /build/ 11 | /dist/ 12 | /docs/build/ 13 | 14 | # Coverage artifacts 15 | /.coverage 16 | 17 | # Version file (auto-generated by setup.py) 18 | /traits/version.py 19 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # Read the Docs configuration file 2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 3 | 4 | version: 2 5 | 6 | python: 7 | version: 3.8 8 | install: 9 | - method: pip 10 | path: . 11 | extra_requirements: 12 | - docs 13 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | This software is OSI Certified Open Source Software. 2 | OSI Certified is a certification mark of the Open Source Initiative. 3 | 4 | (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 5 | All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without 8 | modification, are permitted provided that the following conditions are met: 9 | 10 | * Redistributions of source code must retain the above copyright notice, this 11 | list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | * Neither the name of Enthought, Inc. nor the names of its contributors may 16 | be used to endorse or promote products derived from this software without 17 | specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 23 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 26 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CHANGES.rst 2 | include LICENSE.txt 3 | include LICENSE-CC-BY-3.0.txt 4 | include MANIFEST.in 5 | include README.rst 6 | include image_LICENSE.txt 7 | graft docs 8 | prune docs/build 9 | recursive-exclude docs *.pyc 10 | graft examples 11 | recursive-exclude examples *.pyc 12 | include traits/ctraits.c 13 | include traits/py.typed 14 | recursive-include traits *.py 15 | include traits/observation/_dsl_grammar.lark 16 | -------------------------------------------------------------------------------- /docs/source/_static/e-logo-rev.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/docs/source/_static/e-logo-rev.png -------------------------------------------------------------------------------- /docs/source/_static/et.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/docs/source/_static/et.ico -------------------------------------------------------------------------------- /docs/source/_templates/layout.html: -------------------------------------------------------------------------------- 1 | {# Filename: .templates/layout.html #} 2 | {% extends '!layout.html' %} 3 | 4 | 5 | {% block relbaritems %} 6 | {% if current_page_name != 'index' %} 7 |
  • {{ title }}
  • 8 | {% endif %} 9 | {% endblock %} 10 | -------------------------------------------------------------------------------- /docs/source/_templates/search.html: -------------------------------------------------------------------------------- 1 | {% extends "!search.html" %} 2 | {% block body %} 3 |

    Search

    4 |

    5 | Enter your search words into the box below and click 6 | search. Note that the search function automatically 7 | searches for all of the words. Pages containing some but not all 8 | of them won't appear in the result list. 9 |

    10 |
    11 | 12 | 13 |
    14 | {% if search_performed %} 15 |

    Search Results

    16 | {% if not search_results %} 17 |

    Your search did not match any results.

    18 | {% endif %} 19 | {% endif %} 20 |
    21 | {% if search_results %} 22 | 29 | {% endif %} 30 |
    31 | {% endblock %} 32 | -------------------------------------------------------------------------------- /docs/source/changelog.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../CHANGES.rst 2 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Traits |version| Documentation 2 | ============================== 3 | 4 | Tutorial 5 | -------- 6 | .. toctree:: 7 | :maxdepth: 3 8 | 9 | traits_tutorial/index 10 | 11 | User Reference 12 | -------------- 13 | .. toctree:: 14 | :maxdepth: 3 15 | 16 | traits_user_manual/index 17 | 18 | 19 | Developer Reference 20 | ------------------- 21 | 22 | .. toctree:: 23 | :maxdepth: 3 24 | 25 | traits_api_reference/index 26 | 27 | Miscellaneous 28 | ------------- 29 | 30 | .. toctree:: 31 | :maxdepth: 2 32 | 33 | changelog 34 | 35 | * :ref:`search` 36 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/base_trait_handler.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.base_trait_handler` Module 2 | ======================================= 3 | 4 | .. automodule:: traits.base_trait_handler 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: BaseTraitHandler 11 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/constants.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.constants` Module 2 | ============================== 3 | 4 | .. automodule:: traits.constants 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autodata:: TraitKind 11 | 12 | .. autodata:: ValidateTrait 13 | 14 | .. autodata:: DefaultValue 15 | 16 | .. autodata:: ComparisonMode 17 | 18 | .. autodata:: NO_COMPARE 19 | 20 | .. autodata:: OBJECT_IDENTITY_COMPARE 21 | 22 | .. autodata:: RICH_COMPARE 23 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/ctrait.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.ctrait` Module 2 | =========================== 3 | 4 | .. automodule:: traits.ctrait 5 | :no-members: 6 | 7 | .. currentmodule:: traits.ctrait 8 | 9 | Classes 10 | ------- 11 | 12 | .. autoclass:: CTrait 13 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/ctraits.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.ctraits` Module 2 | ============================ 3 | 4 | .. automodule:: traits.ctraits 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: CHasTraits 11 | 12 | .. automethod:: _class_traits 13 | 14 | .. automethod:: _instance_traits 15 | 16 | .. autoclass:: cTrait 17 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/editor_factories.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.editor_factories` Module 2 | ===================================== 3 | 4 | .. automodule:: traits.editor_factories 5 | :no-members: 6 | 7 | .. currentmodule:: traits.editor_factories 8 | 9 | Functions 10 | --------- 11 | 12 | .. autofunction:: bytes_editor 13 | 14 | .. autofunction:: code_editor 15 | 16 | .. autofunction:: date_editor 17 | 18 | .. autofunction:: datetime_editor 19 | 20 | .. autofunction:: html_editor 21 | 22 | .. autofunction:: list_editor 23 | 24 | .. autofunction:: multi_line_text_editor 25 | 26 | .. autofunction:: password_editor 27 | 28 | .. autofunction:: shell_editor 29 | 30 | .. autofunction:: time_editor 31 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/has_traits.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.has_traits` Module 2 | =============================== 3 | 4 | .. automodule:: traits.has_traits 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: MetaHasTraits 11 | 12 | .. autoclass:: MetaInterface 13 | 14 | .. automethod:: __init__ 15 | 16 | .. automethod:: __call__ 17 | 18 | .. autoclass:: HasTraits 19 | :exclude-members: wrappers 20 | 21 | .. attribute:: wrappers 22 | :annotation: = 23 | 24 | | {'same': TraitChangeNotifyWrapper, 25 | | 'extended': ExtendedTraitChangeNotifyWrapper, 26 | | 'new': NewTraitChangeNotifyWrapper, 27 | | 'fast_ui': FastUITraitChangeNotifyWrapper, 28 | | 'ui': FastUITraitChangeNotifyWrapper} 29 | 30 | Mapping from dispatch type to notification wrapper class type 31 | 32 | .. autoclass:: HasStrictTraits 33 | 34 | .. autoclass:: HasRequiredTraits 35 | 36 | .. autoclass:: HasPrivateTraits 37 | 38 | .. autoclass:: Vetoable 39 | 40 | .. autoclass:: Interface 41 | 42 | .. autoclass:: ISerializable 43 | 44 | ABC classes 45 | ----------- 46 | 47 | .. note:: These classes are only available when the abc module is present. 48 | 49 | .. autoclass:: ABCMetaHasTraits 50 | 51 | .. autoclass:: ABCHasTraits 52 | 53 | .. autoclass:: ABCHasStrictTraits 54 | 55 | Functions 56 | --------- 57 | 58 | .. autofunction:: cached_property 59 | 60 | .. autofunction:: get_delegate_pattern 61 | 62 | .. autofunction:: observe 63 | 64 | .. autofunction:: on_trait_change 65 | 66 | .. autofunction:: property_depends_on 67 | 68 | .. autofunction:: provides 69 | 70 | .. autofunction:: weak_arg 71 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/index.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | Traits core 5 | ----------- 6 | 7 | .. toctree:: 8 | :maxdepth: 1 9 | 10 | traits 11 | has_traits 12 | 13 | base_trait_handler 14 | constants 15 | ctrait 16 | ctraits 17 | editor_factories 18 | interface_checker 19 | trait_base 20 | trait_converters 21 | trait_dict_object 22 | trait_errors 23 | trait_factory 24 | trait_handler 25 | trait_handlers 26 | trait_list_object 27 | trait_numeric 28 | trait_type 29 | trait_types 30 | trait_notifiers 31 | trait_set_object 32 | traits_listener 33 | version 34 | 35 | Subpackages 36 | ----------- 37 | 38 | .. toctree:: 39 | :maxdepth: 1 40 | 41 | traits.adaptation 42 | traits.etsconfig 43 | traits.observation 44 | traits.testing 45 | traits.util 46 | 47 | Indices and tables 48 | ================== 49 | 50 | * :ref:`genindex` 51 | * :ref:`search` 52 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/interface_checker.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.interface_checker` Module 2 | ====================================== 3 | 4 | .. automodule:: traits.interface_checker 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: InterfaceError 11 | 12 | .. autoclass:: InterfaceChecker 13 | 14 | Function 15 | -------- 16 | 17 | .. autofunction:: check_implements 18 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_base.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_base` Module 2 | =============================== 3 | 4 | .. automodule:: traits.trait_base 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autodata:: Uninitialized 11 | 12 | .. autodata:: Undefined 13 | 14 | .. autodata:: Missing 15 | 16 | .. autodata:: Self 17 | 18 | .. autoclass:: HandleWeakRef 19 | 20 | Functions 21 | --------- 22 | 23 | .. autofunction:: strx 24 | 25 | .. autofunction:: class_of 26 | 27 | .. autofunction:: add_article 28 | 29 | .. autofunction:: user_name_for 30 | 31 | .. autofunction:: traits_home 32 | 33 | .. autofunction:: verify_path 34 | 35 | .. autofunction:: get_module_name 36 | 37 | .. autofunction:: get_resource_path 38 | 39 | .. autofunction:: xgetattr 40 | 41 | .. autofunction:: xsetattr 42 | 43 | .. autofunction:: is_none 44 | 45 | .. autofunction:: not_none 46 | 47 | .. autofunction:: not_false 48 | 49 | .. autofunction:: not_event 50 | 51 | .. autofunction:: is_str 52 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_converters.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_converters` Module 2 | ===================================== 3 | 4 | .. automodule:: traits.trait_converters 5 | :no-members: 6 | 7 | .. currentmodule:: traits.trait_converters 8 | 9 | 10 | Functions 11 | --------- 12 | 13 | .. autofunction:: as_ctrait 14 | 15 | .. autofunction:: check_trait 16 | 17 | .. autofunction:: trait_cast 18 | 19 | .. autofunction:: trait_from 20 | 21 | .. autofunction:: trait_for 22 | 23 | .. autofunction:: mapped_trait_for 24 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_dict_object.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_dict_object` Module 2 | ====================================== 3 | 4 | .. automodule:: traits.trait_dict_object 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: TraitDictEvent 11 | 12 | .. autoclass:: TraitDict 13 | 14 | .. autoclass:: TraitDictObject 15 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_errors.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_errors` Module 2 | ================================= 3 | 4 | .. automodule:: traits.trait_errors 5 | :no-members: 6 | 7 | Functions 8 | --------- 9 | 10 | .. autofunction:: repr_type 11 | 12 | Classes 13 | ------- 14 | 15 | .. autoclass:: TraitError 16 | 17 | .. autoclass:: TraitNotificationError 18 | 19 | .. autoclass:: DelegationError 20 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_factory.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_factory` Module 2 | ================================== 3 | 4 | .. automodule:: traits.trait_factory 5 | :no-members: 6 | 7 | .. currentmodule:: traits.trait_factory 8 | 9 | Classes 10 | ------- 11 | 12 | .. autoclass:: TraitFactory 13 | 14 | .. autoclass:: TraitImportError 15 | 16 | 17 | Functions 18 | --------- 19 | 20 | .. autofunction:: trait_factory 21 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_handler.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_handler` Module 2 | ================================== 3 | 4 | .. automodule:: traits.trait_handler 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: TraitHandler 11 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_handlers.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_handlers` Module 2 | =================================== 3 | 4 | .. automodule:: traits.trait_handlers 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: TraitCoerceType 11 | 12 | .. autoclass:: TraitCastType 13 | 14 | .. autoclass:: TraitInstance 15 | 16 | .. autoclass:: TraitFunction 17 | 18 | .. autoclass:: TraitEnum 19 | 20 | .. autoclass:: TraitCompound 21 | 22 | .. autoclass:: TraitMap 23 | 24 | 25 | Private Functions 26 | ----------------- 27 | 28 | .. autofunction:: traits.trait_handlers._undefined_get 29 | 30 | .. autofunction:: traits.trait_handlers._undefined_set 31 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_list_object.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_list_object` Module 2 | ====================================== 3 | 4 | .. automodule:: traits.trait_list_object 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: TraitListEvent 11 | 12 | .. autoclass:: TraitList 13 | 14 | .. autoclass:: TraitListObject 15 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_notifiers.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_notifiers` Module 2 | ==================================== 3 | 4 | .. automodule:: traits.trait_notifiers 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: NotificationExceptionHandlerState 11 | 12 | .. autoclass:: NotificationExceptionHandler 13 | :members: _push_handler, _pop_handler, _handle_exception, _get_handlers, 14 | _check_lock, _log_exception 15 | 16 | .. autoclass:: StaticAnytraitChangeNotifyWrapper 17 | 18 | .. autoclass:: StaticTraitChangeNotifyWrapper 19 | 20 | .. autoclass:: TraitChangeNotifyWrapper 21 | 22 | .. autoclass:: ExtendedTraitChangeNotifyWrapper 23 | 24 | .. autoclass:: FastUITraitChangeNotifyWrapper 25 | 26 | .. autoclass:: NewTraitChangeNotifyWrapper 27 | 28 | Functions 29 | --------- 30 | 31 | .. autofunction:: set_ui_handler 32 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_numeric.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_numeric` Module 2 | ================================== 3 | 4 | .. automodule:: traits.trait_numeric 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: AbstractArray 11 | :show-inheritance: 12 | 13 | .. autoclass:: Array 14 | :show-inheritance: 15 | 16 | .. autoclass:: ArrayOrNone 17 | :show-inheritance: 18 | 19 | .. autoclass:: CArray 20 | :show-inheritance: 21 | 22 | Function 23 | -------- 24 | 25 | .. autofunction:: dtype2trait 26 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_set_object.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_set_object` Module 2 | ===================================== 3 | 4 | .. automodule:: traits.trait_set_object 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autoclass:: TraitSetEvent 11 | 12 | .. autoclass:: TraitSet 13 | 14 | .. autoclass:: TraitSetObject 15 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/trait_type.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.trait_type` Module 2 | =============================== 3 | 4 | .. automodule:: traits.trait_type 5 | :no-members: 6 | 7 | Classes 8 | ------- 9 | 10 | .. autodata:: NoDefaultSpecified 11 | 12 | .. autoclass:: TraitType 13 | 14 | Private Functions 15 | ----------------- 16 | .. autofunction:: traits.trait_type._infer_default_value_type 17 | 18 | .. autofunction:: traits.trait_type._write_only 19 | 20 | .. autofunction:: traits.trait_type._read_only 21 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/traits.adaptation.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.adaptation` Package 2 | ================================ 3 | 4 | .. automodule:: traits.adaptation 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | :mod:`traits.adaptation.adaptation_error` Module 10 | ------------------------------------------------ 11 | 12 | .. automodule:: traits.adaptation.adaptation_error 13 | :members: 14 | :undoc-members: 15 | :show-inheritance: 16 | 17 | :mod:`traits.adaptation.adaptation_manager` Module 18 | -------------------------------------------------- 19 | 20 | .. automodule:: traits.adaptation.adaptation_manager 21 | :members: 22 | :undoc-members: 23 | :show-inheritance: 24 | 25 | 26 | :mod:`traits.adaptation.adaptation_offer` Module 27 | ------------------------------------------------ 28 | 29 | .. automodule:: traits.adaptation.adaptation_offer 30 | :members: 31 | :undoc-members: 32 | :show-inheritance: 33 | 34 | :mod:`traits.adaptation.adapter` Module 35 | --------------------------------------- 36 | 37 | .. automodule:: traits.adaptation.adapter 38 | :members: 39 | :undoc-members: 40 | :show-inheritance: 41 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/traits.etsconfig.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.etsconfig` Package 2 | =============================== 3 | 4 | .. automodule:: traits.etsconfig 5 | :no-members: 6 | 7 | :mod:`traits.etsconfig.etsconfig` Module 8 | ---------------------------------------- 9 | 10 | .. automodule:: traits.etsconfig.etsconfig 11 | :no-members: 12 | 13 | .. autoclass:: ETSConfigType 14 | 15 | .. autodata:: ETSConfig 16 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/traits.observation.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.observation` Package 2 | ================================= 3 | 4 | .. automodule:: traits.observation 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | :mod:`traits.observation.exception_handling` Module 10 | --------------------------------------------------- 11 | 12 | .. automodule:: traits.observation.exception_handling 13 | :members: 14 | :undoc-members: 15 | :show-inheritance: 16 | 17 | 18 | :mod:`traits.observation.exceptions` Module 19 | --------------------------------------------- 20 | 21 | .. automodule:: traits.observation.exceptions 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | 26 | 27 | :mod:`traits.observation.api` Module 28 | ------------------------------------ 29 | 30 | .. automodule:: traits.observation.api 31 | :members: 32 | :undoc-members: 33 | :show-inheritance: 34 | 35 | 36 | :mod:`traits.observation.expression` Module 37 | ------------------------------------------- 38 | 39 | .. automodule:: traits.observation.expression 40 | :members: 41 | :undoc-members: 42 | :show-inheritance: 43 | :special-members: __eq__, __or__ 44 | 45 | 46 | :mod:`traits.observation.events` Module 47 | --------------------------------------- 48 | 49 | .. automodule:: traits.observation.events 50 | :members: 51 | :undoc-members: 52 | :show-inheritance: 53 | 54 | .. autoclass:: DictChangeEvent 55 | :members: 56 | :inherited-members: 57 | 58 | .. autoclass:: ListChangeEvent 59 | :members: 60 | :inherited-members: 61 | 62 | .. autoclass:: SetChangeEvent 63 | :members: 64 | :inherited-members: 65 | 66 | .. autoclass:: TraitChangeEvent 67 | :members: 68 | :inherited-members: 69 | 70 | 71 | :mod:`traits.observation.parsing` Module 72 | ---------------------------------------- 73 | 74 | .. automodule:: traits.observation.parsing 75 | :members: 76 | :undoc-members: 77 | :show-inheritance: 78 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/traits.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.traits` Module 2 | =========================== 3 | 4 | .. automodule:: traits.traits 5 | :no-members: 6 | 7 | .. currentmodule:: traits.traits 8 | 9 | Classes 10 | ------- 11 | 12 | .. autoclass:: Default 13 | 14 | .. autoclass:: ForwardProperty 15 | 16 | 17 | Functions 18 | --------- 19 | 20 | .. autofunction:: Trait 21 | 22 | .. autofunction:: Property 23 | 24 | 25 | Private Classes 26 | --------------- 27 | 28 | .. autoclass:: traits.traits._InstanceArgs 29 | 30 | .. autoclass:: traits.traits._TraitMaker 31 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/traits.testing.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.testing` Package 2 | ============================= 3 | 4 | .. automodule:: traits.testing 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | :mod:`traits.testing.doctest_tools` Module 10 | ------------------------------------------ 11 | 12 | .. automodule:: traits.testing.doctest_tools 13 | :members: 14 | :undoc-members: 15 | :show-inheritance: 16 | 17 | :mod:`traits.testing.optional_dependencies` Module 18 | -------------------------------------------------- 19 | 20 | .. automodule:: traits.testing.optional_dependencies 21 | :members: 22 | :undoc-members: 23 | :show-inheritance: 24 | 25 | :mod:`traits.testing.unittest_tools` Module 26 | ------------------------------------------- 27 | 28 | .. automodule:: traits.testing.unittest_tools 29 | :members: 30 | :undoc-members: 31 | :show-inheritance: 32 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/traits_listener.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.traits_listener` Module 2 | ==================================== 3 | 4 | .. automodule:: traits.traits_listener 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/traits_api_reference/version.rst: -------------------------------------------------------------------------------- 1 | :mod:`traits.version` Module 2 | ============================ 3 | 4 | .. automodule:: traits.version 5 | :no-members: 6 | 7 | Attributes 8 | ---------- 9 | 10 | .. autodata:: version 11 | 12 | .. autodata:: git_revision 13 | -------------------------------------------------------------------------------- /docs/source/traits_tutorial/index.rst: -------------------------------------------------------------------------------- 1 | Traits |version| Tutorial 2 | ========================= 3 | 4 | Tutorial 5 | -------- 6 | .. toctree:: 7 | :maxdepth: 3 8 | 9 | introduction 10 | -------------------------------------------------------------------------------- /docs/source/traits_user_manual/appendix.rst: -------------------------------------------------------------------------------- 1 | 2 | ======== 3 | Appendix 4 | ======== 5 | 6 | .. toctree:: 7 | :hidden: 8 | 9 | listening.rst 10 | 11 | 12 | Trait Notification with **on_trait_change** 13 | -------------------------------------------- 14 | 15 | See :ref:`on-trait-change-notification` for details on how to set up change 16 | notifications using an older API. 17 | 18 | 19 | Property **depends_on** 20 | ----------------------- 21 | 22 | The **depends_on** attribute on a **Property** trait allows change 23 | notifications to be fired for the property when one of its dependents has 24 | changed. This makes use of **on_trait_change** internally and therefore this 25 | is an older API. See :ref:`caching-a-property-value` for the current API. 26 | 27 | .. index:: depends_on metadata 28 | 29 | For example:: 30 | 31 | from traits.api import HasStrictTraits, List, Int, Property 32 | 33 | class TestScores(HasStrictTraits): 34 | 35 | scores = List(Int) 36 | average = Property(depends_on='scores') 37 | 38 | def _get_average(self): 39 | s = self.scores 40 | return (float(reduce(lambda n1, n2: n1 + n2, s, 0)) / len(s)) 41 | 42 | The **depends_on** metadata attribute accepts extended trait references, using 43 | the same syntax as the on_trait_change() method's name parameter, described in 44 | :ref:`the-name-parameter`. As a result, it can take values that specify 45 | attributes on referenced objects, multiple attributes, or attributes that are 46 | selected based on their metadata attributes. 47 | -------------------------------------------------------------------------------- /docs/source/traits_user_manual/images/adaptation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/docs/source/traits_user_manual/images/adaptation.png -------------------------------------------------------------------------------- /docs/source/traits_user_manual/installation.rst: -------------------------------------------------------------------------------- 1 | .. index:: installation 2 | 3 | .. _installation: 4 | 5 | ============ 6 | Installation 7 | ============ 8 | 9 | The latest release of Traits is available from the Python Package Index (PyPI), 10 | and the normal way to install Traits into your Python environment is using 11 | pip:: 12 | 13 | python -m pip install traits 14 | 15 | Traits includes a C extension module. Binary wheels are provided on PyPI for 16 | common platforms, but some platforms may need to compile Traits from source. On 17 | those platforms, a suitable C compiler will be needed. 18 | 19 | 20 | Installation from source on macOS 21 | --------------------------------- 22 | 23 | The system Python 3.8 on macOS Catalina has trouble installing Traits from 24 | source, due to an apparent mismatch in architecture settings. This issue can 25 | be worked around by specifying the "ARCHFLAGS" environment variable for 26 | the install:: 27 | 28 | ARCHFLAGS="-arch x86_64" python -m pip install traits 29 | 30 | See https://github.com/enthought/traits/issues/1337 for more details. 31 | -------------------------------------------------------------------------------- /edm.yaml: -------------------------------------------------------------------------------- 1 | # Change this if you are using on-premise brood 2 | store_url: "https://packages.enthought.com" 3 | 4 | repositories: 5 | - enthought/free 6 | - enthought/lgpl 7 | - enthought/gpl 8 | -------------------------------------------------------------------------------- /examples/README.rst: -------------------------------------------------------------------------------- 1 | This folder contains examples for demonstration and documentation purposes. 2 | 3 | To aid discovery, symbolic links are created for files hosted in the package 4 | in order to be included as package data. 5 | -------------------------------------------------------------------------------- /examples/tutorials/default.css: -------------------------------------------------------------------------------- 1 | pre { border: 1px solid black; background-color: #E8E8E8; padding: 4px } 2 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Traits examples 13 | 14 | Please see doc_examples.rst for more information. 15 | """ 16 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/default.css: -------------------------------------------------------------------------------- 1 | body { background-color: #FFFFFF; } 2 | 3 | h1 { font-family: Arial; 4 | font-size: 14pt; 5 | color: #303030; 6 | background-color: #FCD062; 7 | padding-top: 3px; 8 | padding-left:8px; 9 | padding-bottom: 3px; 10 | padding-right: 8px; } 11 | 12 | h2 { font-family: Arial; 13 | font-size: 12pt; 14 | color: #303030; 15 | background-color: #FCD062; 16 | padding-top: 3px; 17 | padding-left:8px; 18 | padding-bottom: 3px; 19 | padding-right: 8px; } 20 | 21 | pre { border: 1px solid #A0A0A0; 22 | background-color: #FDF7E7; 23 | padding: 4px; } 24 | 25 | dl { border: 1px solid #A0A0A0; 26 | background-color: #FDF7E7; 27 | padding-top: 4px; 28 | padding-bottom: 6px; 29 | padding-left: 8px; 30 | padding-right: 8px; } 31 | 32 | dl dl { border: 0px solid #A0A0A0; } 33 | 34 | dt { font-family: Arial; 35 | font-weight: bold; 36 | 37 | dd { padding-bottom: 10px; } 38 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This directory contains a collection of the various examples taken from the 13 | Traits documentation. 14 | """ 15 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/adapt_metadata.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # adapt_metadata.py - Example of using 'adapt' metadata 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Instance 15 | from interface_definition import IName 16 | 17 | 18 | # --[Code]--------------------------------------------------------------------- 19 | class Apartment(HasTraits): 20 | renter = Instance(IName, adapt="no") 21 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/add_class_trait.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # add_class_trait.py --- Example of mutually-referring classes 12 | # using add_class_trait() 13 | 14 | 15 | # --[Imports]------------------------------------------------------------------ 16 | from traits.api import HasTraits, Instance 17 | 18 | 19 | # --[Code]--------------------------------------------------------------------- 20 | # Defining mutually-referring classes using add_class_trait() 21 | class Chicken(HasTraits): 22 | pass 23 | 24 | 25 | class Egg(HasTraits): 26 | created_by = Instance(Chicken) 27 | 28 | 29 | # Now that 'Egg' is defined, we can add the 'hatched_from' trait to 30 | # solve the mutual-reference problem... 31 | 32 | Chicken.add_class_trait("hatched_from", Instance(Egg)) 33 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/all_wildcard.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # all_wildcard.py --- Example of trait attribute wildcard rules 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import Any, Str, Int, HasTraits, TraitError 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Person(HasTraits): 19 | 20 | # Normal, explicitly defined trait: 21 | name = Str 22 | 23 | # By default, let all traits have any value: 24 | _ = Any 25 | 26 | # Except for this one, which must be an Int: 27 | age = Int 28 | 29 | 30 | # --[Example*]----------------------------------------------------------------- 31 | # Create a sample Person: 32 | bill = Person() 33 | 34 | # These assignments should all work: 35 | bill.name = "William" 36 | bill.address = "121 Drury Lane" 37 | bill.zip_code = 55212 38 | bill.age = 49 39 | 40 | # This should generate an error (must be an Int): 41 | print("Attempting to assign a string to an Int trait object...\n") 42 | try: 43 | bill.age = "middle age" 44 | except TraitError as c: 45 | print("TraitError: ", c, "\n") 46 | 47 | # Display the final results: 48 | bill.print_traits() 49 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/bad_self_ref.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # bad_self_ref.py -- Non-working example with self-referencing class definition 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Instance 15 | 16 | # --[Code]--------------------------------------------------------------------- 17 | # Shows the incorrect way of defining a self-referencing class. 18 | try: 19 | 20 | class Employee(HasTraits): 21 | 22 | # This won't work. 23 | # 'Employee' is not defined until the class definition is complete: 24 | manager = Instance(Employee) 25 | 26 | 27 | except NameError as excp: 28 | print(excp) 29 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/cached_prop.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This example demonstrates the use of Property, with caching and notification 13 | support. 14 | 15 | """ 16 | 17 | from traits.api import ( 18 | cached_property, HasStrictTraits, Str, observe, Property, 19 | ) 20 | 21 | 22 | class Person(HasStrictTraits): 23 | 24 | full_name = Str() 25 | last_name = Property(observe="full_name") 26 | 27 | @cached_property 28 | def _get_last_name(self): 29 | return self.full_name.split(" ")[-1] 30 | 31 | @observe("last_name") 32 | def _last_name_updated(self, event): 33 | print("last_name is changed.") 34 | 35 | 36 | obj = Person() 37 | obj.full_name = "John Doe" # print: last_name is changed. 38 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/circular_definition.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # --[Imports]------------------------------------------------------------------ 12 | from traits.api import HasTraits, Instance 13 | 14 | 15 | # --[Code]--------------------------------------------------------------------- 16 | # Shows the incorrect way of defining mutually-referring classes. 17 | try: 18 | 19 | class Chicken(HasTraits): 20 | 21 | # Won't work: 'Egg' not defined yet: 22 | hatched_from = Instance(Egg) 23 | 24 | class Egg(HasTraits): 25 | 26 | # If we move this class to the top, then this line won't work, because 27 | # 'Chicken' won't be defined yet: 28 | created_by = Instance(Chicken) 29 | 30 | 31 | except NameError as excp: 32 | print(excp) 33 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/compound.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # compound.py -- Example of multiple criteria in a trait definition 12 | 13 | 14 | # --[Imports]------------------------------------------------------------------ 15 | from traits.api import HasTraits, Range, Trait, TraitError 16 | 17 | 18 | # --[Code]--------------------------------------------------------------------- 19 | # Shows the definition of a compound trait. 20 | 21 | 22 | class Die(HasTraits): 23 | 24 | # Define a compound trait definition: 25 | value = Trait(1, Range(1, 6), "one", "two", "three", "four", "five", "six") 26 | 27 | 28 | # --[Example*]----------------------------------------------------------------- 29 | # Create a sample Die: 30 | die = Die() 31 | 32 | # Try out some sample valid values: 33 | die.value = 3 34 | die.value = "three" 35 | die.value = 5 36 | die.value = "five" 37 | 38 | # Now try out some invalid values: 39 | try: 40 | die.value = 0 41 | except TraitError as excp: 42 | print(excp) 43 | 44 | try: 45 | die.value = "zero" 46 | except TraitError as excp: 47 | print(excp) 48 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/configure_traits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # configure_traits.py -- Sample code to demonstrate configure_traits() 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Str, Int 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class SimpleEmployee(HasTraits): 19 | first_name = Str 20 | last_name = Str 21 | department = Str 22 | 23 | employee_number = Str 24 | salary = Int 25 | 26 | 27 | sam = SimpleEmployee() 28 | sam.configure_traits() 29 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/custom_traithandler.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # custom_traithandler.py --- Example of a custom TraitHandler 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import TraitHandler 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class TraitOddInteger(TraitHandler): 19 | def validate(self, object, name, value): 20 | if isinstance(value, int) and (value > 0) and ((value % 2) == 1): 21 | return value 22 | self.error(object, name, value) 23 | 24 | def info(self): 25 | return "a positive odd integer" 26 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/disallow.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # disallow.py --- Example of using Disallow with wildcards 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import Disallow, Float, HasTraits, Int, Str 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Person(HasTraits): 19 | name = Str 20 | age = Int 21 | weight = Float 22 | _ = Disallow 23 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/dynamic_notification.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # dynamic_notification.py --- Example of dynamic notification 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import Float, HasTraits, Instance 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Part(HasTraits): 19 | cost = Float(0.0) 20 | 21 | 22 | class Widget(HasTraits): 23 | part1 = Instance(Part) 24 | part2 = Instance(Part) 25 | cost = Float(0.0) 26 | 27 | def __init__(self): 28 | self.part1 = Part() 29 | self.part2 = Part() 30 | self.part1.on_trait_change(self.update_cost, "cost") 31 | self.part2.on_trait_change(self.update_cost, "cost") 32 | 33 | def update_cost(self): 34 | self.cost = self.part1.cost + self.part2.cost 35 | 36 | 37 | # --[Example*]----------------------------------------------------------------- 38 | w = Widget() 39 | w.part1.cost = 2.25 40 | w.part2.cost = 5.31 41 | print(w.cost) 42 | # Result: 7.56 43 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/event.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # event.py --- Example of a trait event 12 | 13 | # -------------------------------------------------------------------- 14 | from traits.api import Event, HasTraits, List, Tuple 15 | from traitsui.api import RGBColor 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | 19 | point_2d = Tuple(0, 0) 20 | 21 | 22 | class Line2D(HasTraits): 23 | points = List(point_2d) 24 | line_color = RGBColor("black") 25 | updated = Event 26 | 27 | def redraw(self): 28 | pass # Not implemented for this example 29 | 30 | def _points_changed(self): 31 | self.updated = True 32 | 33 | def _updated_fired(self): 34 | self.redraw() 35 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/instance_trait_defaults.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # instance_trait_defaults.py --- Example of Instance trait default values 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Instance 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Parent(HasTraits): 19 | pass 20 | 21 | 22 | class Child(HasTraits): 23 | # default value is None 24 | father = Instance(Parent) 25 | # default value is still None, but None can not be assigned 26 | grandfather = Instance(Parent, allow_none=False) 27 | # default value is Parent() 28 | mother = Instance(Parent, args=()) 29 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/interface_definition.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # interface_definition.py - Example of defining an interface 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import Interface 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class IName(Interface): 19 | def get_name(self): 20 | """ Returns a string which is the name of an object. """ 21 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/interface_implementation.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # interface_implementation.py - Example of implementing an interface 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Instance, provides, Str 15 | from interface_definition import IName 16 | 17 | 18 | # --[Code]--------------------------------------------------------------------- 19 | @provides(IName) 20 | class Person(HasTraits): 21 | first_name = Str("John") 22 | last_name = Str("Doe") 23 | 24 | # Implementation of the 'IName' interface: 25 | def get_name(self): 26 | """ Returns the name of an object. """ 27 | return "%s %s" % (self.first_name, self.last_name) 28 | 29 | 30 | # --[Example*]----------------------------------------------------------------- 31 | class Apartment(HasTraits): 32 | renter = Instance(IName) 33 | 34 | 35 | william = Person(first_name="William", last_name="Adams") 36 | apt1 = Apartment(renter=william) 37 | print("Renter is: ", apt1.renter.get_name()) 38 | # Result: Renter is: William Adams 39 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/keywords.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # keywords.py --- Example of trait keywords 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Str 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Person(HasTraits): 19 | # 'label' is used for Traits UI field labels; 20 | # 'desc' can be used for tooltips. 21 | first_name = Str("", desc="first or personal name", label="First Name") 22 | last_name = Str("", desc="last or family name", label="Last Name") 23 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/lesson.desc: -------------------------------------------------------------------------------- 1 | Examples from the Traits User Guide 2 | 3 | all_traits_features 4 | all_wildcard 5 | bad_self_ref 6 | circular_definition 7 | add_class_trait 8 | cast_simple 9 | compound 10 | 11 | custom_traithandler 12 | default_trait_ui 13 | delegate 14 | delegate_prefix 15 | disallow 16 | dynamic_notification 17 | enum_simple 18 | event 19 | explicit 20 | false 21 | graphic_example 22 | imageenumeditor 23 | include_extra 24 | instanceeditor 25 | instance_example 26 | keywords 27 | mapped 28 | map_simple 29 | minimal 30 | multiple_criteria 31 | object_trait_attrs 32 | override_default 33 | override_editor 34 | person_bmi 35 | range 36 | reuse_editor 37 | static_notification 38 | temp_wildcard 39 | this 40 | traitcasttype 41 | traitdict 42 | traitenum 43 | traitinstance 44 | traitlist 45 | traitmap 46 | traitrange 47 | traitstring 48 | traittuple 49 | traitype 50 | trait_reuse 51 | type_simple 52 | user_custom_th 53 | use_custom_th 54 | validator 55 | view_attributes 56 | view_multi_object 57 | view_standalone 58 | widget 59 | wildcard 60 | wildcard_all 61 | wildcard_name 62 | wildcard_rules 63 | wizard 64 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/list_notifier.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # list_notifier.py -- Example of zero-parameter handlers for an object 12 | # containing a list 13 | 14 | # --[Imports]------------------------------------------------------------------ 15 | from traits.api import HasTraits, List 16 | 17 | 18 | # --[Code]--------------------------------------------------------------------- 19 | class Employee: 20 | pass 21 | 22 | 23 | class Department(HasTraits): 24 | employees = List(Employee) 25 | 26 | 27 | # --[Example*]----------------------------------------------------------------- 28 | def a_handler(): 29 | print("A handler") 30 | 31 | 32 | def b_handler(): 33 | print("B handler") 34 | 35 | 36 | def c_handler(): 37 | print("C handler") 38 | 39 | 40 | fred = Employee() 41 | mary = Employee() 42 | donna = Employee() 43 | 44 | dept = Department(employees=[fred, mary]) 45 | 46 | # "Old style" name syntax 47 | # a_handler is called only if the list is replaced: 48 | dept.on_trait_change(a_handler, "employees") 49 | # b_handler is called if the membership of the list changes: 50 | dept.on_trait_change(b_handler, "employees_items") 51 | 52 | # "New style" name syntax 53 | # c_handler is called if 'employees' or its membership change: 54 | dept.on_trait_change(c_handler, "[employees]") 55 | 56 | print("Changing list items") 57 | dept.employees[1] = donna # Calls B and C 58 | print("Replacing list") 59 | dept.employees = [donna] # Calls A and C 60 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/minimal.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # minimal.py --- Minimal example of using traits. 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Float, TraitError 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Person(HasTraits): 19 | weight = Float(150.0) 20 | 21 | 22 | # --[Example*]----------------------------------------------------------------- 23 | # instantiate the class 24 | joe = Person() 25 | 26 | # Show the default value 27 | print(joe.weight) 28 | 29 | # Assign new values 30 | joe.weight = 161.9 # OK to assign a float 31 | print(joe.weight) 32 | 33 | joe.weight = 162 # OK to assign an int 34 | print(joe.weight) 35 | 36 | # The following line causes a traceback: 37 | try: 38 | joe.weight = "average" # Error to assign a string 39 | print("You should not see this message.") 40 | except TraitError: 41 | print("You can't assign a string to the 'weight' trait.") 42 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/object_trait_attrs.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # object_trait_attrs.py --- Example of per-object trait attributes 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Range 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class GUISlider(HasTraits): 19 | def __init__( 20 | self, 21 | eval=None, 22 | label="Value", 23 | trait=None, 24 | min=0.0, 25 | max=1.0, 26 | initial=None, 27 | **traits 28 | ): 29 | HasTraits.__init__(self, **traits) 30 | if trait is None: 31 | if min > max: 32 | min, max = max, min 33 | if initial is None: 34 | initial = min 35 | elif not (min <= initial <= max): 36 | initial = [min, max][abs(initial - min) > abs(initial - max)] 37 | trait = Range(min, max, value=initial) 38 | self.add_trait(label, trait) 39 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/observe_decorator.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This example shows how to set up notifications for changes on a single trait, 13 | for all instances of this class. 14 | 15 | Note that a change notification is also fired when the instance is created. 16 | This is because the value provided in the instance constructor is different 17 | from the default value. 18 | """ 19 | 20 | from traits.api import HasTraits, Int, observe 21 | 22 | 23 | class Person(HasTraits): 24 | age = Int(0) 25 | 26 | @observe("age") 27 | def notify_age_change(self, event): 28 | print("age changed from {} to {}".format(event.old, event.new)) 29 | 30 | 31 | person = Person(age=1) # print 'age changed from 0 to 1' 32 | person.age = 2 # print 'age changed from 1 to 2' 33 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/observe_different_events.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This example shows how to set up notifications for changes on an object that 13 | is an item in a list. 14 | 15 | Note that when a new list is assigned, the change event is of a different type 16 | compared to when a list is mutated. 17 | """ 18 | 19 | from traits.api import HasTraits, Int, List, observe 20 | from traits.observation.api import trait 21 | 22 | 23 | class Person(HasTraits): 24 | 25 | scores = List(Int) 26 | 27 | @observe("scores") 28 | def notify_scores_change(self, event): 29 | print( 30 | "{event.name} changed from {event.old} to {event.new}. " 31 | "(Event type: {event.__class__.__name__})".format(event=event) 32 | ) 33 | 34 | @observe(trait("scores", notify=False).list_items()) 35 | def notify_scores_content_change(self, event): 36 | print( 37 | "scores added: {event.added}. scores removed: {event.removed} " 38 | "(Event type: {event.__class__.__name__})".format(event=event) 39 | ) 40 | 41 | 42 | person = Person(scores=[1, 2]) 43 | # print: scores changed from [] to [1, 2]. (Event type: TraitChangeEvent) 44 | person.scores.append(3) 45 | # print: scores added: [3]. scores removed: [] (Event type: ListChangeEvent) 46 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/observe_method.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This example shows how to set up notifications for changes on a single trait, 13 | for a specific instance of HasTraits. 14 | 15 | The change handler can be removed using the 'remove' argument on ``observe``. 16 | """ 17 | 18 | from traits.api import HasTraits, Int 19 | 20 | 21 | class Person(HasTraits): 22 | age = Int(0) 23 | 24 | 25 | def print_change(event): 26 | print("{} changed: {} -> {}".format(event.name, event.old, event.new)) 27 | 28 | 29 | person = Person(age=1) 30 | person.observe(print_change, "age") 31 | person.age = 2 # print 'age changed: 1 -> 2' 32 | 33 | person.observe(print_change, "age", remove=True) 34 | person.age = 3 # nothing is printed. 35 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/observe_optional.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This example shows how to set up notifications for a trait that is defined 13 | after the instance is created. 14 | 15 | The optional flag suppresses the error that would otherwise occur because the 16 | trait is not found at the time ``observe`` is called. When the observed trait 17 | is defined, the change handler will be aded to the new trait. 18 | """ 19 | 20 | from traits.api import HasTraits, Int, observe 21 | from traits.observation.api import trait 22 | 23 | 24 | class Person(HasTraits): 25 | 26 | @observe(trait("age", optional=True)) 27 | def notify_age_change(self, event): 28 | print("age changed") 29 | 30 | 31 | person = Person() 32 | person.add_trait("age", Int()) 33 | person.age = 2 # print 'age changed' 34 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/observe_post_init.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | This example shows how to set up notifications for changes on a single trait, 13 | for all instances of this class, but only after the object state is set during 14 | instantiation. 15 | 16 | The 'post_init' argument suppresses change notifications during instantiation, 17 | but allows subsequent changes to trigger notifications. 18 | """ 19 | 20 | from traits.api import HasTraits, Int, observe 21 | 22 | 23 | class Person(HasTraits): 24 | age = Int(0) 25 | 26 | @observe("age", post_init=True) 27 | def notify_age_change(self, event): 28 | print("age changed from {} to {}".format(event.old, event.new)) 29 | 30 | 31 | person = Person(age=1) # no output 32 | person.age = 2 # print 'age changed from 1 to 2' 33 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/override_default.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # override_default.py -- Example of overriding a default value for 12 | # a trait attribute in a subclass 13 | 14 | from traits.api import HasTraits, Range, Str 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | # Example of overriding a default value for a trait in a subclass: 19 | 20 | 21 | # Define the base class: 22 | class Employee(HasTraits): 23 | 24 | name = Str 25 | salary_grade = Range(value=1, low=1, high=10) 26 | 27 | 28 | # Define a subclass: 29 | class Manager(Employee): 30 | 31 | # Override the default value for the inherited 'salary_grade' trait: 32 | salary_grade = 5 33 | 34 | 35 | # --[Example*]----------------------------------------------------------------- 36 | # Create an employee and display its initial contents: 37 | joe = Employee(name="Joe") 38 | joe.print_traits() 39 | 40 | # Now do the same thing for a manager object: 41 | mike = Manager(name="Mike") 42 | mike.print_traits() 43 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/post_init_notification.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # post_init_notification.py --- Example of static notification 12 | from traits.api import Float, HasTraits, on_trait_change, Str 13 | 14 | 15 | class Part(HasTraits): 16 | cost = Float(0.0) 17 | 18 | name = Str("Part") 19 | 20 | @on_trait_change("cost") 21 | def cost_updated(self, object, name, old, new): 22 | print("{} is changed from {} to {}".format(name, old, new)) 23 | 24 | @on_trait_change("name", post_init=True) 25 | def name_updated(self, object, name, old, new): 26 | print("{} is changed from {} to {}".format(name, old, new)) 27 | 28 | 29 | part = Part(cost=2.0, name="Nail") 30 | # Result: cost is changed from 0.0 to 2.0 31 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/prototype_prefix.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # prototype_prefix.py --- Examples of PrototypedFrom() prefix parameter 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import PrototypedFrom, Float, HasTraits, Instance, Str 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Parent(HasTraits): 19 | first_name = Str 20 | family_name = "" 21 | favorite_first_name = Str 22 | child_allowance = Float(1.00) 23 | 24 | 25 | class Child(HasTraits): 26 | __prefix__ = "child_" 27 | first_name = PrototypedFrom("mother", "favorite_*") 28 | last_name = PrototypedFrom("father", "family_name") 29 | allowance = PrototypedFrom("father", "*") 30 | father = Instance(Parent) 31 | mother = Instance(Parent) 32 | 33 | 34 | # --[Example*]----------------------------------------------------------------- 35 | fred = Parent( 36 | first_name="Fred", 37 | family_name="Lopez", 38 | favorite_first_name="Diego", 39 | child_allowance=5.0, 40 | ) 41 | 42 | maria = Parent( 43 | first_name="Maria", 44 | family_name="Gonzalez", 45 | favorite_first_name="Tomas", 46 | child_allowance=10.0, 47 | ) 48 | 49 | nino = Child(father=fred, mother=maria) 50 | 51 | print( 52 | "%s %s gets $%.2f for allowance" 53 | % (nino.first_name, nino.last_name, nino.allowance) 54 | ) 55 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/simple_adapter.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # simple_adapter.py - Example of adaptation using Adapter 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import Adapter, Instance, provides 15 | 16 | from interface_definition import IName 17 | from interface_implementation import Person 18 | 19 | 20 | # --[Code]--------------------------------------------------------------------- 21 | @provides(IName) 22 | class PersonINameAdapter(Adapter): 23 | 24 | # Declare the type of client it supports: 25 | adaptee = Instance(Person) 26 | 27 | # Implement the 'IName' interface on behalf of its client: 28 | def get_name(self): 29 | return "%s %s" % (self.adaptee.first_name, self.adaptee.last_name) 30 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/static_notification.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # static_notification.py --- Example of static attribute notification 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Float 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Person(HasTraits): 19 | weight_kg = Float(0.0) 20 | height_m = Float(1.0) 21 | bmi = Float(0.0) 22 | 23 | def _weight_kg_changed(self, old, new): 24 | print("weight_kg changed from %s to %s " % (old, new)) 25 | if self.height_m != 0.0: 26 | self.bmi = self.weight_kg / (self.height_m ** 2) 27 | 28 | def _anytrait_changed(self, name, old, new): 29 | print("The %s trait changed from %s to %s " % (name, old, new)) 30 | 31 | 32 | # --[Example*]----------------------------------------------------------------- 33 | bob = Person() 34 | bob.height_m = 1.75 35 | # Output: The height_m trait changed from 1.0 to 1.75 36 | bob.weight_kg = 100.0 37 | # Output: 38 | # The weight_kg trait changed from 0.0 to 100.0 39 | # weight_kg changed from 0.0 to 100.0 40 | # The bmi trait changed from 0.0 to 32.6530612245 41 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/temp_wildcard.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # temp_wildcard.py --- Example of using a wildcard with a trait 12 | # attribute name 13 | 14 | # --[Imports]------------------------------------------------------------------ 15 | from traits.api import Any, HasTraits 16 | 17 | 18 | # --[Code]--------------------------------------------------------------------- 19 | class Person(HasTraits): 20 | temp_ = Any 21 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/this.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # this.py --- Example of This predefined trait 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, This 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Employee(HasTraits): 19 | manager = This 20 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/trait_reuse.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # trait_reuse.py --- Example of reusing trait definitions 12 | 13 | from traits.api import HasTraits, Range 14 | 15 | # --[Code]--------------------------------------------------------------------- 16 | coefficient = Range(-1.0, 1.0, 0.0) 17 | 18 | 19 | class quadratic(HasTraits): 20 | c2 = coefficient 21 | c1 = coefficient 22 | c0 = coefficient 23 | x = Range(-100.0, 100.0, 0.0) 24 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/trait_subclass.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # trait_subclass.py -- Example of subclassing a trait class 12 | 13 | from traits.api import BaseInt 14 | 15 | 16 | # --[Code]--------------------------------------------------------------------- 17 | class OddInt(BaseInt): 18 | 19 | # Define the default value 20 | default_value = 1 21 | 22 | # Describe the trait type 23 | info_text = "an odd integer" 24 | 25 | def validate(self, object, name, value): 26 | value = super().validate(object, name, value) 27 | if (value % 2) == 1: 28 | return value 29 | 30 | self.error(object, name, value) 31 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/transient_metadata.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # transient_metadata.py - Example of using 'transient' metadata 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, File, Any 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class DataBase(HasTraits): 19 | 20 | # The name of the data base file: 21 | file_name = File 22 | 23 | # The open file handle used to access the data base: 24 | file = Any(transient=True) 25 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/use_custom_th.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # use_custom_th.py --- Example of using a custom TraitHandler 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import HasTraits, Range, Trait 15 | from custom_traithandler import TraitOddInteger 16 | 17 | 18 | # --[Code]--------------------------------------------------------------------- 19 | class AnOddClass(HasTraits): 20 | oddball = Trait(1, TraitOddInteger()) 21 | very_odd = Trait(-1, TraitOddInteger(), Range(-10, -1)) 22 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/widget.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Float, HasTraits, Trait 12 | 13 | 14 | class Part(HasTraits): 15 | cost = Trait(0.0) 16 | 17 | 18 | class Widget(HasTraits): 19 | part1 = Trait(Part) 20 | part2 = Trait(Part) 21 | cost = Float(0.0) 22 | 23 | def __init__(self): 24 | self.part1 = Part() 25 | self.part2 = Part() 26 | self.part1.on_trait_change(self.update_cost, "cost") 27 | self.part2.on_trait_change(self.update_cost, "cost") 28 | 29 | def update_cost(self): 30 | self.cost = self.part1.cost + self.part2.cost 31 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/wildcard.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # wildcard.py --- Example of using a wildcard with a trait 12 | # attribute name 13 | from traits.api import Any, HasTraits 14 | 15 | 16 | class Person(HasTraits): 17 | temp_ = Any 18 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/wildcard_all.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # wildcard_all.py --- Example of using a wildcard with all trait 12 | # attribute names 13 | from traits.api import HasTraits, Any 14 | 15 | 16 | class Person(HasTraits): 17 | _ = Any 18 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/wildcard_name.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # temp_wildcard.py --- Example of using a wildcard 12 | # with a trait attribute name 13 | from traits.api import Any, HasTraits 14 | 15 | 16 | class Person(HasTraits): 17 | temp_ = Any 18 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/wildcard_rules.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # wildcard_rules.py --- Example of trait attribute wildcard rules 12 | 13 | # --[Imports]------------------------------------------------------------------ 14 | from traits.api import Any, HasTraits, Int, Python 15 | 16 | 17 | # --[Code]--------------------------------------------------------------------- 18 | class Person(HasTraits): 19 | temp_count = Int(-1) 20 | temp_ = Any 21 | _ = Python 22 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/examples/wizard.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # wizard.py ---Example of a traits-based wizard UI 12 | from traits.api import HasTraits, Int, Str 13 | 14 | 15 | class Person(HasTraits): 16 | name = Str 17 | age = Int 18 | street = Str 19 | city = Str 20 | state = Str 21 | pcode = Str 22 | 23 | 24 | bill = Person() 25 | bill.configure_traits(kind="modal") 26 | -------------------------------------------------------------------------------- /examples/tutorials/doc_examples/lesson.desc: -------------------------------------------------------------------------------- 1 | The Traits Documentation Examples Tutorial 2 | 3 | examples 4 | -------------------------------------------------------------------------------- /examples/tutorials/introduction: -------------------------------------------------------------------------------- 1 | ../../traits/examples/introduction -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/decorators/tutorial.desc: -------------------------------------------------------------------------------- 1 | New Method Decorators 2 | 3 | on_trait_change: on_trait_change Decorator 4 | cached_property: cached_property Decorator 5 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/default.css: -------------------------------------------------------------------------------- 1 | body { background-color: #FFFFFF; } 2 | 3 | h1 { font-family: Arial; 4 | font-size: 14pt; 5 | color: #303030; 6 | background-color: #FCD062; 7 | padding-top: 3px; 8 | padding-left:8px; 9 | padding-bottom: 3px; 10 | padding-right: 8px; } 11 | 12 | h2 { font-family: Arial; 13 | font-size: 12pt; 14 | color: #303030; 15 | background-color: #FCD062; 16 | padding-top: 3px; 17 | padding-left:8px; 18 | padding-bottom: 3px; 19 | padding-right: 8px; } 20 | 21 | pre { border: 1px solid #A0A0A0; 22 | background-color: #FDF7E7; 23 | padding: 4px; } 24 | 25 | dl { border: 1px solid #A0A0A0; 26 | background-color: #FDF7E7; 27 | padding-top: 4px; 28 | padding-bottom: 6px; 29 | padding-left: 8px; 30 | padding-right: 8px; } 31 | 32 | dl dl { border: 0px solid #A0A0A0; } 33 | 34 | dt { font-family: Arial; 35 | font-weight: bold; 36 | 37 | dd { padding-bottom: 10px; } 38 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/delegation/tutorial.desc: -------------------------------------------------------------------------------- 1 | Delegation Fixes and Improvements 2 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/extended_trait_change/tutorial.desc: -------------------------------------------------------------------------------- 1 | Extended Trait Change Notification Syntax 2 | 3 | extended_trait_change: on_trait_change Method Enhancements 4 | properties: Extended Property depends_on References 5 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/getstate_setstate/tutorial.desc: -------------------------------------------------------------------------------- 1 | __getstate__/__setstate__ Changes 2 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/interfaces/tutorial.desc: -------------------------------------------------------------------------------- 1 | Interfaces and Adaptation 2 | 3 | interfaces: Interfaces 4 | adaptation: Adaptation 5 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/trait_types/core_traits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # --(Rewritten Core Traits)---------------------------------------------------- 12 | """ 13 | Rewritten Core Traits 14 | ===================== 15 | 16 | For several reasons, including the ability to subclass types, many of the 17 | previous core Traits package types have been entirely rewritten as subclasses 18 | of **TraitType**, the new base class for subclassable trait types. 19 | 20 | The core trait types which have been rewritten as subclasses of **TraitType** 21 | are: 22 | 23 | - Any 24 | - Bool 25 | - CBool 26 | - CComplex 27 | - CInt 28 | - CFloat 29 | - Code 30 | - Complex 31 | - CStr 32 | - Dict 33 | - Directory 34 | - Enum 35 | - Expression 36 | - File 37 | - Float 38 | - HTML 39 | - Instance 40 | - Int 41 | - List 42 | - Password 43 | - PythonValue 44 | - Range 45 | - Regex 46 | - Str 47 | - String 48 | - Tuple 49 | - WeakRef 50 | 51 | This may be useful information if you find yourself in need of creating a new 52 | trait type with behavior similar to any of these core trait types. 53 | """ 54 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/trait_types/tutorial.desc: -------------------------------------------------------------------------------- 1 | Trait Types 2 | 3 | trait_types: New Trait Definition Style 4 | core_traits: Rewritten Core Traits 5 | new_types: Creating New Trait Types 6 | -------------------------------------------------------------------------------- /examples/tutorials/traits_4.0/tutorial.desc: -------------------------------------------------------------------------------- 1 | Changes starting with Traits 3.0 2 | 3 | interfaces 4 | trait_types 5 | extended_trait_change 6 | decorators 7 | delegation 8 | getstate_setstate 9 | -------------------------------------------------------------------------------- /examples/tutorials/tutor.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # fixme: 12 | # - Get custom tree view images. 13 | # - Write a program to create a directory structure from a lesson plan file. 14 | 15 | """ Script to run the tutorial. 16 | """ 17 | 18 | 19 | import os 20 | import sys 21 | 22 | from traitsui.extras.demo import demo 23 | 24 | # Correct program usage information: 25 | usage = """ 26 | Correct usage is: tutor.py [root_dir] 27 | where: 28 | root_dir = Path to root of the tutorial tree 29 | 30 | If omitted, 'root_dir' defaults to the current directory.""" 31 | 32 | 33 | def main(root_dir): 34 | # Create a tutor and display the tutorial: 35 | path, name = os.path.splitext(root_dir) 36 | demo(dir_name=root_dir, title='Traits Demos') 37 | 38 | 39 | if __name__ == "__main__": 40 | 41 | # Validate the command line arguments: 42 | if len(sys.argv) > 2: 43 | print(usage) 44 | sys.exit(1) 45 | 46 | # Determine the root path to use for the tutorial files: 47 | if len(sys.argv) == 2: 48 | root_dir = sys.argv[1] 49 | else: 50 | root_dir = os.getcwd() 51 | 52 | main(root_dir) 53 | -------------------------------------------------------------------------------- /image_LICENSE.txt: -------------------------------------------------------------------------------- 1 | The icons are mostly derived work from other icons. As such they are 2 | licensed accordingly to the original license: 3 | 4 | Project License File, URL 5 | --------------------------------------------------------------------- 6 | Enthought BSD 3-Clause LICENSE.txt 7 | http://www.enthought.com/licenses/BSD.txt 8 | 9 | Hannes Grobe/AWI CC BY 3.0 LICENSE-CC-BY-3.0.txt 10 | https://creativecommons.org/licenses/by/3.0 11 | 12 | Unless stated in this file, icons and images are the work of Enthought, and 13 | are released under a 3 clause BSD license. 14 | 15 | Files and original authors: 16 | ---------------------------------------------------------------------------- 17 | docs/source/_static: 18 | e-logo-rev.png | Enthought 19 | 20 | docs/source/traits_user_manual/images: 21 | adaptation.png | Enthought 22 | 23 | traits/examples/introduction/images 24 | sample_0001.png | Hannes Grobe/AWI 25 | sample_0002.png | Hannes Grobe/AWI 26 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ['setuptools', 'wheel'] 3 | build-backend = 'setuptools.build_meta' 4 | 5 | [tool.black] 6 | line-length = 79 7 | target-version = ['py36'] 8 | 9 | [tool.isort] 10 | profile = 'black' 11 | line_length = 79 12 | order_by_type = 'False' 13 | 14 | [tool.cibuildwheel] 15 | skip = 'pp*' 16 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = traits/observation/_generated_parser.py,build 3 | ignore = E266,W503,E722,E731,E741 4 | per-file-ignores = 5 | */api.py:F401 6 | # Suppress flake8 complaints about black's formatting of .pyi files 7 | *.pyi:E302,E305,E701,E704 8 | -------------------------------------------------------------------------------- /traits/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | try: 12 | from traits.version import version as __version__ 13 | except ImportError: 14 | # If we get here, we're using a source tree that hasn't been created via 15 | # the setup script. That likely also means that the ctraits extension 16 | # hasn't been built, so this isn't a viable Traits installation. OTOH, it 17 | # can be useful if a simple "import traits" doesn't actually fail. 18 | __version__ = "unknown" 19 | -------------------------------------------------------------------------------- /traits/__init__.pyi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/__init__.pyi -------------------------------------------------------------------------------- /traits/adaptation/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Adaptation package. 13 | 14 | """ 15 | -------------------------------------------------------------------------------- /traits/adaptation/adaptation_error.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Exception raised when a requested adaptation is not possible. """ 12 | 13 | 14 | class AdaptationError(TypeError): 15 | """ Exception raised when a requested adaptation is not possible. """ 16 | 17 | pass 18 | -------------------------------------------------------------------------------- /traits/adaptation/adapter.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Base classes for adapters. 12 | 13 | Adapters do not have to inherit from these classes, as long as their 14 | constructor takes the object to be adapted as the first and only 15 | *positional* argument. 16 | 17 | """ 18 | 19 | 20 | from traits.has_traits import HasTraits 21 | from traits.trait_types import Any 22 | 23 | 24 | class PurePythonAdapter(object): 25 | """ Base class for pure Python adapters. """ 26 | 27 | def __init__(self, adaptee): 28 | self.adaptee = adaptee 29 | 30 | 31 | class Adapter(HasTraits): 32 | """ Base class for adapters with traits. """ 33 | 34 | def __init__(self, adaptee, **traits): 35 | traits["adaptee"] = adaptee 36 | super().__init__(**traits) 37 | 38 | adaptee = Any 39 | -------------------------------------------------------------------------------- /traits/adaptation/api.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from .adapter import Adapter, PurePythonAdapter 12 | 13 | from .adaptation_error import AdaptationError 14 | 15 | from .adaptation_manager import ( 16 | adapt, 17 | AdaptationManager, 18 | get_global_adaptation_manager, 19 | provides_protocol, 20 | register_factory, 21 | register_offer, 22 | register_provides, 23 | reset_global_adaptation_manager, 24 | set_global_adaptation_manager, 25 | supports_protocol, 26 | ) 27 | 28 | from .adaptation_offer import AdaptationOffer 29 | -------------------------------------------------------------------------------- /traits/adaptation/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/adaptation/tests/__init__.py -------------------------------------------------------------------------------- /traits/adaptation/tests/lazy_examples.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Examples for lazy adapter factories. 12 | 13 | This module should be only imported when the adaptation takes place. 14 | """ 15 | 16 | 17 | class IBar(object): 18 | pass 19 | 20 | 21 | class IBarToIFoo(object): 22 | pass 23 | 24 | 25 | class IFoo(object): 26 | pass 27 | -------------------------------------------------------------------------------- /traits/adaptation/tests/test_adapter.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Test the Adapter class. """ 12 | 13 | 14 | import unittest 15 | 16 | from traits.api import on_trait_change 17 | from traits.adaptation.api import Adapter 18 | 19 | 20 | class TestAdapter(unittest.TestCase): 21 | """ Test the Adapter class. """ 22 | 23 | #### Tests ################################################################ 24 | 25 | def test_initializing_adaptee(self): 26 | # Regression test: The `adaptee` trait used to be initialized after 27 | # all other traits, which caused "post_init" listeners to be 28 | # incorrectly triggered. 29 | 30 | class FooAdapter(Adapter): 31 | # True if a trait change notification for `adaptee` is fired. 32 | adaptee_notifier_called = False 33 | # True if a post-init trait change notification for `adaptee` 34 | # is fired. 35 | post_init_notifier_called = False 36 | 37 | @on_trait_change("adaptee", post_init=True) 38 | def check_that_adaptee_start_can_be_accessed(self): 39 | self.post_init_notifier_called = True 40 | 41 | @on_trait_change("adaptee") 42 | def check_that_adaptee_change_is_notified(self): 43 | self.adaptee_notifier_called = True 44 | 45 | foo_adapter = FooAdapter(adaptee="1234") 46 | self.assertEqual(foo_adapter.adaptee_notifier_called, True) 47 | self.assertEqual(foo_adapter.post_init_notifier_called, False) 48 | -------------------------------------------------------------------------------- /traits/base_trait_handler.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | class BaseTraitHandler: 12 | ... 13 | -------------------------------------------------------------------------------- /traits/ctrait.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from . import ctraits as ctraits 12 | from .constants import ComparisonMode as ComparisonMode, DefaultValue as DefaultValue, default_value_map as default_value_map 13 | from .trait_base import SequenceTypes as SequenceTypes, Undefined as Undefined 14 | from .trait_dict_object import TraitDictObject as TraitDictObject 15 | from .trait_list_object import TraitListObject as TraitListObject 16 | from .trait_set_object import TraitSetObject as TraitSetObject 17 | from typing import Any 18 | 19 | def __newobj__(cls, *args: Any): ... 20 | 21 | class CTrait(ctraits.cTrait): 22 | def __call__(self, *args: Any, **metadata: Any): ... 23 | @property 24 | def default(self): ... 25 | @property 26 | def default_kind(self): ... 27 | @property 28 | def trait_type(self): ... 29 | @property 30 | def inner_traits(self): ... 31 | @property 32 | def comparison_mode(self): ... 33 | @comparison_mode.setter 34 | def comparison_mode(self, value: Any) -> None: ... 35 | def is_trait_type(self, trait_type: Any): ... 36 | editor: Any = ... 37 | def get_editor(self): ... 38 | def get_help(self, full: bool = ...): ... 39 | def full_info(self, object: Any, name: Any, value: Any): ... 40 | def info(self): ... 41 | def as_ctrait(self): ... 42 | def __reduce_ex__(self, protocol: Any): ... 43 | -------------------------------------------------------------------------------- /traits/ctraits.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from typing import Any 12 | 13 | # Constants used in DefaultValue enumeration. 14 | _CALLABLE_AND_ARGS_DEFAULT_VALUE: int 15 | _CALLABLE_DEFAULT_VALUE: int 16 | _CONSTANT_DEFAULT_VALUE: int 17 | _DICT_COPY_DEFAULT_VALUE: int 18 | _DISALLOW_DEFAULT_VALUE: int 19 | _LIST_COPY_DEFAULT_VALUE: int 20 | _MAXIMUM_DEFAULT_VALUE_TYPE: int 21 | _MISSING_DEFAULT_VALUE: int 22 | _OBJECT_DEFAULT_VALUE: int 23 | _TRAIT_DICT_OBJECT_DEFAULT_VALUE: int 24 | _TRAIT_LIST_OBJECT_DEFAULT_VALUE: int 25 | _TRAIT_SET_OBJECT_DEFAULT_VALUE: int 26 | 27 | def _validate_complex_number(value: Any) -> complex: ... 28 | def _validate_float(value: Any) -> float: ... 29 | 30 | class CHasTraits: 31 | def __init__(self, **traits: Any): ... 32 | 33 | class cTrait: ... 34 | -------------------------------------------------------------------------------- /traits/editor_factories.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from typing import Any, Optional 12 | 13 | PasswordEditors: Any 14 | MultilineTextEditors: Any 15 | BytesEditors: Any 16 | SourceCodeEditor: Any 17 | HTMLTextEditor: Any 18 | PythonShellEditor: Any 19 | DateEditor: Any 20 | TimeEditor: Any 21 | logger: Any 22 | 23 | def password_editor(auto_set: bool = ..., enter_set: bool = ...): ... 24 | def multi_line_text_editor(auto_set: bool = ..., enter_set: bool = ...): ... 25 | def bytes_editor(auto_set: bool = ..., enter_set: bool = ..., encoding: Optional[Any] = ...): ... 26 | def code_editor(): ... 27 | def html_editor(): ... 28 | def shell_editor(): ... 29 | def time_editor(): ... 30 | def date_editor(): ... 31 | def datetime_editor(): ... 32 | def list_editor(trait: Any, handler: Any): ... 33 | -------------------------------------------------------------------------------- /traits/etsconfig/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Supports sharing settings across projects or programs on the same system. 12 | Part of the EnthoughtBase project. 13 | """ 14 | -------------------------------------------------------------------------------- /traits/etsconfig/api.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from .etsconfig import ETSConfig, ETSToolkitError 12 | -------------------------------------------------------------------------------- /traits/etsconfig/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/etsconfig/tests/__init__.py -------------------------------------------------------------------------------- /traits/examples/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | -------------------------------------------------------------------------------- /traits/examples/_etsdemo_info.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ This module provides functions to be advertised in the distribution 12 | entry points. 13 | """ 14 | 15 | 16 | def introduction(request): 17 | """ Return a configuration for contributing examples to the 18 | Demo application. 19 | 20 | Parameters 21 | ---------- 22 | request : dict 23 | Information provided by the demo application. 24 | Currently this is a placeholder. 25 | 26 | Returns 27 | ------- 28 | response : dict 29 | """ 30 | import pkg_resources 31 | 32 | return dict( 33 | version=1, 34 | name="Traits Introduction", 35 | root=( 36 | pkg_resources.resource_filename("traits", "examples/introduction") 37 | ), 38 | ) 39 | -------------------------------------------------------------------------------- /traits/examples/introduction/default.css: -------------------------------------------------------------------------------- 1 | body { background-color: #FFFFFF; } 2 | 3 | h1 { font-family: Arial; 4 | font-size: 18pt; 5 | color: #272a32; 6 | background-color: #8fbfde; 7 | padding-top: 3px; 8 | padding-left:8px; 9 | padding-bottom: 3px; 10 | padding-right: 8px; } 11 | 12 | h2 { font-family: Arial; 13 | font-size: 14pt; 14 | color: #272a32; 15 | background-color: #8fbfde; 16 | padding-top: 3px; 17 | padding-left:8px; 18 | padding-bottom: 3px; 19 | padding-right: 8px; } 20 | 21 | pre { border: 1px solid #4488c7; 22 | background-color: #eaeaea; 23 | padding: 4px; } 24 | 25 | dl { border: 1px solid #272a32; 26 | background-color: #eaeaea; 27 | padding-top: 4px; 28 | padding-bottom: 6px; 29 | padding-left: 8px; 30 | padding-right: 8px; } 31 | 32 | dl dl { border: 0px solid #A0A0A0; } 33 | 34 | dt { font-family: Arial; 35 | font-weight: bold; 36 | 37 | dd { padding-bottom: 10px; } 38 | -------------------------------------------------------------------------------- /traits/examples/introduction/images/LICENSE.txt: -------------------------------------------------------------------------------- 1 | All images are the original work of Hannes Grobe/AWI. 2 | 3 | The images in this directory are licensed according to the Creative Commons 4 | CC BY 3.0 license: https://creativecommons.org/licenses/by/3.0/ 5 | 6 | sample_0001.png 7 | https://commons.wikimedia.org/wiki/Category:Scanning_electron_microscopic_images_of_minerals#/media/File:Arnager-kalk-bornholm_01_hg.jpg 8 | 9 | sample_0002.png 10 | https://commons.wikimedia.org/wiki/Category:Scanning_electron_microscopic_images_of_minerals#/media/File:Arnager-kalk-bornholm_03_hg.jpg -------------------------------------------------------------------------------- /traits/examples/introduction/images/sample_0001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/examples/introduction/images/sample_0001.png -------------------------------------------------------------------------------- /traits/examples/introduction/images/sample_0002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/examples/introduction/images/sample_0002.png -------------------------------------------------------------------------------- /traits/examples/introduction/index.rst: -------------------------------------------------------------------------------- 1 | Introduction to Traits 2 | ====================== 3 | 4 | This is an interactive tutorial to introduce you to the basics of 5 | Traits and to give you an idea of what capabilities the Traits 6 | libraries provide. This tutorial assumes that you are comfortable 7 | with the Python programming language, object-oriented programming, 8 | and the core tools of the Python scientific ecosystem, such as 9 | NumPy. 10 | 11 | The tutorial starts with an **Introduction** which gives a realistic 12 | example of scientific code; then talks about how traits can be used 13 | for **Validation**, **Initialization**, **Documentation**, 14 | **Observation** and **Visualization**. This tutorial is designed 15 | to introduce the basics of Traits, but also to explain *why* you 16 | might want to use Traits in your own code. 17 | -------------------------------------------------------------------------------- /traits/examples/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/examples/tests/__init__.py -------------------------------------------------------------------------------- /traits/examples/tests/test_etsdemo_info.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | import os 11 | import unittest 12 | 13 | from traits.examples._etsdemo_info import introduction 14 | from traits.testing.optional_dependencies import requires_pkg_resources 15 | 16 | 17 | class TestETSDemoInfo(unittest.TestCase): 18 | @requires_pkg_resources 19 | def test_introduction(self): 20 | # input to introduction is currently just a placeholder 21 | response = introduction({}) 22 | self.assertTrue(os.path.exists(response['root'])) 23 | -------------------------------------------------------------------------------- /traits/observation/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/observation/__init__.py -------------------------------------------------------------------------------- /traits/observation/_anytrait_filter.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ A filter to be used with FilteredTraitObserver for observing all 12 | traits. """ 13 | 14 | 15 | def anytrait_filter(name, ctrait): 16 | """ Match filter that matches all traits. 17 | 18 | Parameters 19 | ---------- 20 | name : str 21 | Name of the trait. 22 | ctrait : CTrait 23 | The actual trait. 24 | """ 25 | return True 26 | -------------------------------------------------------------------------------- /traits/observation/_dsl_grammar.lark: -------------------------------------------------------------------------------- 1 | // Grammar for Traits Mini Language used in observe 2 | // After updating the grammar, rebuild the standalone parser with: 3 | // $ python etstool.py generate-parser 4 | // 5 | 6 | // Simple name as trait name, e.g. "a" 7 | trait: NAME 8 | 9 | // Keyword for handing items (in list, or dict, or set, 10 | // or a trait named "items") 11 | items: "items" 12 | 13 | // Syntax to indicate name is being used for matching an existing 14 | // metadata name rather than a trait name. 15 | metadata: "+" NAME 16 | 17 | // Used to match any trait name. 18 | anytrait: "*" 19 | 20 | // Series connector used when left item should notify 21 | notify: "." 22 | 23 | // Series connector used when left item should not notify 24 | quiet: ":" 25 | 26 | // Atomic expression 27 | ?element: trait | items | metadata | "[" parallel "]" 28 | 29 | // Rule for joining elements in series, e.g. "a.b.c" 30 | ?series: (series (notify | quiet))? element 31 | 32 | // Rule for joining elements in parallel, e.g. "a,b,c" 33 | ?parallel: (parallel ",")? series 34 | 35 | // We only allow "*" if it appears in a "terminal" position, in the sense that 36 | // it's not directly or indirectly followed by a "." or ":" connector. For 37 | // example, "b.*" and "[a:*,b]" are valid, but "*.b" and "[*,a].b" are not. 38 | // Here are variants of the series and parallel rules used for expressions 39 | // appearing in a terminal position. 40 | 41 | ?series_terminal : (series (notify | quiet))? (element | anytrait) 42 | 43 | ?parallel_terminal : (parallel_terminal ",")? series_terminal 44 | 45 | // Start point for the parser 46 | ?start: parallel_terminal 47 | 48 | // Matching Python variable name rule 49 | NAME: /[a-zA-Z_]\w*/ 50 | 51 | %import common.WS 52 | %ignore WS 53 | -------------------------------------------------------------------------------- /traits/observation/_i_notifier.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import abc 12 | 13 | 14 | class INotifier(abc.ABC): 15 | """ Interface for all notifiers. 16 | 17 | An instance of notifier must be a callable, i.e. ``__call__`` must be 18 | implemented and cannot be None. The signature of that callable should be 19 | compatible with the observables the notifier will be given to. This 20 | interface does not define what that signature should be. 21 | """ 22 | 23 | def __call__(self, *args, **kwargs): 24 | """ Called by an observable. 25 | The signature is not restricted by the interface. 26 | """ 27 | raise NotImplementedError("__call__ must be implemented.") 28 | 29 | def add_to(self, observable): 30 | """ Add this notifier to the observable. 31 | 32 | Parameters 33 | ---------- 34 | observable : IObservable 35 | """ 36 | raise NotImplementedError("add_to must be implemented.") 37 | 38 | def remove_from(self, observable): 39 | """ Remove this notifier or a notifier equivalent to this one 40 | from the observable. 41 | 42 | Parameters 43 | ---------- 44 | observable : IObservable 45 | 46 | Raises 47 | ------ 48 | NotifierNotFound 49 | If the notifier cannot be found. 50 | """ 51 | raise NotImplementedError("remove_from must be implemented.") 52 | -------------------------------------------------------------------------------- /traits/observation/_metadata_filter.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ A filter to be used with FilteredTraitObserver for observing traits 12 | with a given metadata. The filter is defined here so that two 13 | observers created using the same parameters compare equally. 14 | """ 15 | 16 | 17 | class MetadataFilter: 18 | """ Callable to be used with FilteredTraitObserver for filtering traits 19 | with the given metadata name. 20 | 21 | This filter returns true if the metadata value is not None, false 22 | if the metadata is not defined or the value is None. 23 | 24 | Attributes 25 | ---------- 26 | metadata_name : str 27 | Name of the metadata to filter traits with. 28 | """ 29 | 30 | __slots__ = ("metadata_name",) 31 | 32 | def __init__(self, metadata_name): 33 | self.metadata_name = metadata_name 34 | 35 | def __call__(self, name, trait): 36 | # If the metadata is not defined, CTrait still returns None. 37 | return getattr(trait, self.metadata_name) is not None 38 | 39 | def __eq__(self, other): 40 | return ( 41 | type(self) is type(other) 42 | and self.metadata_name == other.metadata_name 43 | ) 44 | 45 | def __hash__(self): 46 | return hash((type(self).__name__, self.metadata_name)) 47 | 48 | def __repr__(self): 49 | return ( 50 | "{self.__class__.__name__}" 51 | "(metadata_name={self.metadata_name!r})".format(self=self) 52 | ) 53 | -------------------------------------------------------------------------------- /traits/observation/_set_change_event.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | 12 | # SetChangeEvent is in the public API. 13 | 14 | 15 | class SetChangeEvent: 16 | """ Event object to represent mutations on a set. 17 | 18 | The interface of this object is provisional as of version 6.1. 19 | 20 | Attributes 21 | ---------- 22 | object : traits.trait_set_object.TraitSet 23 | The set being mutated. 24 | removed : set 25 | Values removed from the set. 26 | added : set 27 | Values added to the set. 28 | """ 29 | 30 | def __init__(self, *, object, removed, added): 31 | self.object = object 32 | self.removed = removed 33 | self.added = added 34 | 35 | def __repr__(self): 36 | return ( 37 | f"{self.__class__.__name__}(" 38 | f"object={self.object!r}, " 39 | f"removed={self.removed!r}, " 40 | f"added={self.added!r})" 41 | ) 42 | 43 | 44 | def set_event_factory(trait_set, removed, added): 45 | """ Adapt the call signature of TraitSet.notify to create an event. 46 | 47 | Parameters 48 | ---------- 49 | trait_set : traits.trait_set_object.TraitSet 50 | The set being mutated. 51 | removed : set 52 | Values removed from the set. 53 | added : set 54 | Values added to the set. 55 | 56 | Returns 57 | ------- 58 | SetChangeEvent 59 | """ 60 | return SetChangeEvent( 61 | object=trait_set, added=added, removed=removed, 62 | ) 63 | -------------------------------------------------------------------------------- /traits/observation/api.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.observation.events import ( 12 | DictChangeEvent, 13 | ListChangeEvent, 14 | SetChangeEvent, 15 | TraitChangeEvent, 16 | ) 17 | 18 | from traits.observation.exception_handling import ( 19 | pop_exception_handler, 20 | push_exception_handler, 21 | ) 22 | 23 | from traits.observation.exceptions import NotifierNotFound 24 | 25 | from traits.observation.expression import ( 26 | anytrait, 27 | compile_expr, 28 | dict_items, 29 | list_items, 30 | match, 31 | metadata, 32 | set_items, 33 | trait, 34 | ) 35 | 36 | from traits.observation.observe import ( 37 | apply_observers, 38 | dispatch_same, 39 | observe, 40 | ) 41 | 42 | from traits.observation.parsing import ( 43 | compile_str, 44 | parse, 45 | ) 46 | -------------------------------------------------------------------------------- /traits/observation/events.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Event objects received by change handlers added using observe. 12 | """ 13 | 14 | from traits.observation._dict_change_event import ( # noqa: F401 15 | DictChangeEvent, 16 | ) 17 | 18 | from traits.observation._list_change_event import ( # noqa: F401 19 | ListChangeEvent, 20 | ) 21 | 22 | from traits.observation._set_change_event import ( # noqa: F401 23 | SetChangeEvent, 24 | ) 25 | 26 | from traits.observation._trait_change_event import ( # noqa: F401 27 | TraitChangeEvent, 28 | ) 29 | -------------------------------------------------------------------------------- /traits/observation/exceptions.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | 12 | class NotifierNotFound(Exception): 13 | """ Raised when a notifier cannot be found.""" 14 | pass 15 | -------------------------------------------------------------------------------- /traits/observation/i_observable.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import abc 12 | 13 | 14 | class IObservable(abc.ABC): 15 | """ Interface for objects that can emit notifications for the observer 16 | system. 17 | """ 18 | 19 | def _notifiers(self, force_create): 20 | """ Return a list of callables where each callable is a notifier. 21 | The list is expected to be mutated for contributing or removing 22 | notifiers from the object. 23 | 24 | Parameters 25 | ---------- 26 | force_create: boolean 27 | It is added for compatibility with CTrait. 28 | It should not be used otherwise. 29 | """ 30 | raise NotImplementedError( 31 | "Observable object must implement _notifiers") 32 | -------------------------------------------------------------------------------- /traits/observation/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/observation/tests/__init__.py -------------------------------------------------------------------------------- /traits/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/py.typed -------------------------------------------------------------------------------- /traits/stubs_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/stubs_tests/__init__.py -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Any.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Any, Instance, Int 12 | 13 | 14 | class Test(HasTraits): 15 | i = Any() 16 | 17 | 18 | obj = Test() 19 | obj.i = "5" 20 | obj.i = 5 21 | obj.i = 5.5 22 | obj.i = {"a": 5, "b": 6} 23 | obj.i = {"a": 5.5, "b": 6} 24 | obj.i = {"a": 5, "b": None, "c": ""} 25 | obj.i = [] 26 | obj.i = [1, 2, 3] 27 | obj.i = [1.1] 28 | obj.i = [1.1, 2, 3.3] 29 | obj.i = '' 30 | obj.i = "5" 31 | obj.i = 5 32 | obj.i = False 33 | obj.i = 5.5 34 | obj.i = 5 + 4j 35 | obj.i = True 36 | obj.i = [1, 2, "3"] 37 | obj.i = None 38 | obj.i = ['1'] 39 | 40 | 41 | class Test2(HasTraits): 42 | i = Any(default_value="234") 43 | 44 | 45 | class Test3(HasTraits): 46 | i = Any(default_value=234) 47 | 48 | 49 | class Foo: 50 | pass 51 | 52 | 53 | class Superclass(HasTraits): 54 | x = Any() 55 | 56 | 57 | class Subclass(Superclass): 58 | x = Instance(Foo) # E: assignment 59 | y = Int() 60 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/BaseClass.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, BaseInstance 12 | 13 | 14 | class Animal: 15 | pass 16 | 17 | 18 | class Goldfish(Animal): 19 | pass 20 | 21 | 22 | class Leprechaun: 23 | pass 24 | 25 | 26 | class Test(HasTraits): 27 | animal = BaseInstance("Animal") 28 | animal2 = BaseInstance(Animal) 29 | 30 | 31 | t = Test() 32 | t.animal = Goldfish() 33 | t.animal = Leprechaun() 34 | t.animal = None 35 | t.animal = Goldfish 36 | t.animal = "sdf" 37 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Bool.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Bool, HasTraits 12 | 13 | 14 | class Test(HasTraits): 15 | var = Bool() 16 | 17 | 18 | obj = Test() 19 | obj.var = "5" # E: assignment 20 | obj.var = 5 # E: assignment 21 | 22 | obj.var = False 23 | obj.var = 5.5 # E: assignment 24 | 25 | obj.var = 5 + 4j # E: assignment 26 | obj.var = True 27 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/CInt.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, BaseCInt 12 | 13 | 14 | class TestClass1(HasTraits): 15 | i = BaseCInt() 16 | 17 | 18 | o = TestClass1() 19 | o.i = "5" 20 | o.i = 5 21 | o.i = 5.5 22 | 23 | 24 | class Test(HasTraits): 25 | i = BaseCInt(default_value="234") # E: arg-type 26 | 27 | 28 | class Test2(HasTraits): 29 | i = BaseCInt(default_value=234) 30 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Callable.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from math import pow 12 | from traits.api import HasTraits, Callable 13 | 14 | 15 | class Test(HasTraits): 16 | var = Callable() 17 | 18 | 19 | obj = Test() 20 | obj.var = pow 21 | obj.var = None 22 | 23 | obj.var = "someuuid" # E: assignment 24 | 25 | obj.var = 5 # E: assignment 26 | 27 | obj.var = False # E: assignment 28 | obj.var = 5.5 # E: assignment 29 | 30 | obj.var = 5 + 4j # E: assignment 31 | obj.var = True # E: assignment 32 | 33 | obj.var = (True,) # E: assignment 34 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Complex.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Complex, HasTraits 12 | 13 | 14 | class Test(HasTraits): 15 | var = Complex() 16 | 17 | 18 | obj = Test() 19 | obj.var = "5" # E: assignment 20 | obj.var = 5 21 | obj.var = 5.5 22 | obj.var = 5 + 4j 23 | 24 | 25 | class Test2(HasTraits): 26 | var = Complex(default_value="sdf") # E: arg-type 27 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Date.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import datetime 12 | from traits.api import HasTraits, Date, Int 13 | 14 | 15 | class TestClass(HasTraits): 16 | t = Date() 17 | x = Int() 18 | 19 | 20 | obj = TestClass() 21 | obj.t = datetime.datetime.now().date() 22 | obj.t = datetime.datetime.now() 23 | obj.t = None 24 | 25 | obj.t = datetime.datetime.now().time() # E: assignment 26 | obj.t = "sometime-string" # E: assignment 27 | obj.t = 9 # E: assignment 28 | obj.t = [] # E: assignment 29 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Datetime.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import datetime 12 | 13 | from traits.api import Datetime, HasTraits 14 | 15 | 16 | class TestClass(HasTraits): 17 | t = Datetime() 18 | 19 | 20 | obj = TestClass() 21 | obj.t = "sometime-string" # E: assignment 22 | obj.t = datetime.datetime.now() 23 | 24 | obj.t = 9 # E: assignment 25 | obj.t = [] # E: assignment 26 | obj.t = datetime.datetime.now().date() # E: assignment 27 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Dict.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Dict, HasTraits, Str, Any 12 | 13 | 14 | class Test(HasTraits): 15 | var = Dict(Str(), Any()) 16 | 17 | 18 | obj = Test() 19 | obj.var = {"a": 5, "b": None, "c": ""} 20 | obj.var = [] # E: assignment 21 | obj.var = [1, 2, 3] # E: assignment 22 | obj.var = [1.1] # E: assignment 23 | obj.var = [1.1, 2, 3.3] # E: assignment 24 | obj.var = '' # E: assignment 25 | obj.var = "5" # E: assignment 26 | obj.var = 5 # E: assignment 27 | obj.var = False # E: assignment 28 | obj.var = 5.5 # E: assignment 29 | obj.var = 5 + 4j # E: assignment 30 | obj.var = True # E: assignment 31 | obj.var = [1, 2, "3"] # E: assignment 32 | obj.var = None # E: assignment 33 | obj.var = ['1'] # E: assignment 34 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Enum.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Enum, HasTraits 12 | 13 | 14 | class TestClass(HasTraits): 15 | en = Enum("foo", "bar", "baz") 16 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/File.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from pathlib import Path, PosixPath 12 | from traits.api import HasTraits, BaseFile, File 13 | 14 | 15 | class Test(HasTraits): 16 | var = BaseFile() 17 | var2 = File() 18 | 19 | 20 | obj = Test() 21 | obj.var = Path('/tmp') 22 | obj.var = PosixPath('/tmp') 23 | obj.var = "someuuid" 24 | 25 | obj.var2 = Path('/tmp') 26 | obj.var2 = PosixPath('/tmp') 27 | obj.var2 = "someuuid" 28 | 29 | obj.var = 5 # E: assignment 30 | 31 | obj.var = False # E: assignment 32 | obj.var = 5.5 # E: assignment 33 | 34 | obj.var = 5 + 4j # E: assignment 35 | obj.var = True # E: assignment 36 | 37 | obj.var = (True,) # E: assignment 38 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Float.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Float, HasTraits 12 | 13 | 14 | class HasIndex: 15 | """Class with __index__ method; instances should be assignable to Float.""" 16 | def __index__(self): 17 | return 1729 18 | 19 | 20 | class HasFloat: 21 | """Class with __float__ method; instances should be assignable to Float.""" 22 | def __float__(self): 23 | return 1729.0 24 | 25 | 26 | class Test(HasTraits): 27 | i = Float() 28 | 29 | 30 | o = Test() 31 | o.i = "5" # E: assignment 32 | o.i = 5 33 | o.i = 5.5 34 | o.i = HasIndex() 35 | o.i = HasFloat() 36 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/HasStrictTraits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Event, HasStrictTraits, observe 12 | 13 | 14 | class Person(HasStrictTraits): 15 | conductor = Event() 16 | 17 | @observe("conductor") 18 | def talk(self, event): 19 | pass 20 | 21 | 22 | def sing(event): 23 | pass 24 | 25 | 26 | person = Person() 27 | person.observe(sing, "conductor") 28 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/HasTraits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Event, HasTraits, observe 12 | 13 | 14 | class Person(HasTraits): 15 | conductor = Event() 16 | 17 | @observe("conductor") 18 | def talk(self, event): 19 | pass 20 | 21 | 22 | def sing(event): 23 | pass 24 | 25 | 26 | person = Person() 27 | person.observe(sing, "conductor") 28 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Instance.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Instance, Str 12 | 13 | 14 | class Fruit: 15 | info = Str("good for you") 16 | 17 | def __init__(self, info="good for you", **traits): 18 | super().__init__(info=info, **traits) 19 | 20 | 21 | class Orange(Fruit): 22 | pass 23 | 24 | 25 | class Pizza: 26 | pass 27 | 28 | 29 | def fruit_factory(info, other_stuff): 30 | return Fruit(info=info) 31 | 32 | 33 | class TestClass(HasTraits): 34 | itm = Instance(Fruit) 35 | 36 | itm_args_kw = Instance(Fruit, ('different info',), {'another_trait': 3}) 37 | itm_args = Instance(Fruit, ('different info',)) 38 | itm_kw = Instance(Fruit, {'info': 'different info'}) 39 | itm_factory = Instance(Fruit, fruit_factory) 40 | itm_factory_args = Instance(Fruit, fruit_factory, ('different info',)) 41 | itm_factory_args_kw = Instance( 42 | Fruit, 43 | fruit_factory, 44 | ('different info',), 45 | {'other_stuff': 3}, 46 | ) 47 | itm_factory_kw = Instance( 48 | Fruit, 49 | fruit_factory, 50 | {'other_stuff': 3}, 51 | ) 52 | 53 | 54 | obj = TestClass() 55 | obj.itm = Orange() 56 | obj.itm = Pizza() 57 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Int.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Int 12 | 13 | 14 | class HasIndex: 15 | """Class with __index__ method; instances should be assignable to Int.""" 16 | def __index__(self): 17 | return 1729 18 | 19 | 20 | class Test(HasTraits): 21 | i = Int() 22 | j = Int(default_value="234") # E: arg-type 23 | k = Int(default_value=234, something="else") 24 | 25 | 26 | o = Test() 27 | o.i = 5 28 | o.i = HasIndex() 29 | 30 | o.i = "5" # E: assignment 31 | o.i = 5.5 # E: assignment 32 | o.i = 5.5 + 5 # E: assignment 33 | o.i = str(5) # E: assignment 34 | o.i = None # E: assignment 35 | 36 | 37 | # Test subclassing Int 38 | class Digit(Int): 39 | def validate(self, object, name, value): 40 | if isinstance(value, int) and 0 <= value <= 9: 41 | return value 42 | 43 | self.error(object, name, value) 44 | 45 | 46 | class TestClass2(HasTraits): 47 | i = Digit() 48 | 49 | 50 | obj = TestClass2() 51 | obj.i = 5 52 | obj.i = "5" # E: assignment 53 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Interface.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import Float, HasTraits, Interface, provides, Str, Tuple 12 | 13 | 14 | class IHasName(Interface): 15 | name = Str() 16 | 17 | 18 | @provides(IHasName) 19 | class NamedColor(HasTraits): 20 | name = Str() 21 | 22 | rgb = Tuple(Float, Float, Float) 23 | 24 | 25 | named_color = NamedColor(name="green", rgb=(0.0, 1.0, 0.0)) 26 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/List.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Int, List, Any 12 | 13 | 14 | class Test(HasTraits): 15 | var = List(Int()) 16 | 17 | 18 | obj = Test() 19 | obj.var = "5" # E: assignment 20 | obj.var = 5 # E: assignment 21 | obj.var = False # E: assignment 22 | obj.var = 5.5 # E: assignment 23 | obj.var = 5 + 4j # E: assignment 24 | obj.var = True # E: assignment 25 | obj.var = [1.1, 2, 3.3] # E: list-item 26 | obj.var = [1, 2, "3"] # E: list-item 27 | obj.var = None # E: assignment 28 | 29 | obj.var = [1, 2, 3] 30 | 31 | 32 | class TestAnyList(HasTraits): 33 | var = List(Any()) 34 | 35 | 36 | obj2 = TestAnyList() 37 | obj2.var = "5" 38 | obj2.var = 5 # E: assignment 39 | obj2.var = False # E: assignment 40 | obj2.var = 5.5 # E: assignment 41 | obj2.var = 5 + 4j # E: assignment 42 | obj2.var = True # E: assignment 43 | obj2.var = [1.1, 2, 3.3] 44 | obj2.var = [1, 2, "3"] 45 | obj2.var = None # E: assignment 46 | 47 | obj2.var = [1, 2, 3] 48 | 49 | 50 | class TestPlainList(HasTraits): 51 | var = List() # E: var-annotated 52 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Map.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Map 12 | 13 | 14 | class Person(HasTraits): 15 | married = Map({'yes': 1, 'no': 0}, default_value="yes") 16 | married_2 = Map([], default_value="yes") # E: arg-type 17 | 18 | 19 | p = Person() 20 | 21 | p.married = "yes" 22 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/PrefixList.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, PrefixList 12 | 13 | 14 | class Person(HasTraits): 15 | atr1 = PrefixList(('yes', 'no')) 16 | atr2 = PrefixList(['yes', 'no']) 17 | 18 | 19 | p = Person() 20 | p.atr1 = 5 # E: assignment 21 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/PrefixMap.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, PrefixMap 12 | 13 | 14 | class Person(HasTraits): 15 | married = PrefixMap({'yes': 1, 'no': 0}, default_value="yes") 16 | married_2 = PrefixMap([], default_value="yes") # E: arg-type 17 | 18 | 19 | p = Person() 20 | 21 | p.married = "y" 22 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Property.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Property, Float, Int 12 | 13 | 14 | class TestClass(HasTraits): 15 | i = Int() 16 | prop1 = Property(Float) 17 | prop2 = Property(i) 18 | prop3 = Property(3) # E: arg-type 19 | prop4 = Property(depends_on='i') 20 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Range.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Range 12 | 13 | 14 | class Test(HasTraits): 15 | var = Range(low=[]) # E: arg-type 16 | var2 = Range(low="3") 17 | var3 = Range(low=3) 18 | 19 | 20 | obj = Test() 21 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Set.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Set, Int 12 | 13 | 14 | class Test(HasTraits): 15 | var = Set(trait=Int()) 16 | 17 | 18 | obj = Test() 19 | obj.var = "5" # E: assignment 20 | obj.var = 5 # E: assignment 21 | 22 | obj.var = False # E: assignment 23 | obj.var = 5.5 # E: assignment 24 | 25 | obj.var = 5 + 4j # E: assignment 26 | obj.var = True # E: assignment 27 | 28 | obj.var = [1, 2, 3] # E: assignment 29 | obj.var = [1, 2, "3"] # E: assignment 30 | 31 | obj.var = {1, 2, 3} 32 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Str.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Str 12 | 13 | 14 | class Test(HasTraits): 15 | i = Str() 16 | 17 | 18 | o = Test() 19 | o.i = "5" 20 | o.i = 5 # E: assignment 21 | o.i = 5.5 # E: assignment 22 | 23 | 24 | class Test2(HasTraits): 25 | var = Str(default_value=None) # E: arg-type 26 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/String.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, String 12 | 13 | 14 | class Test(HasTraits): 15 | var = String() 16 | 17 | 18 | obj = Test() 19 | obj.var = "5" 20 | obj.var = 5 # E: assignment 21 | 22 | obj.var = False # E: assignment 23 | obj.var = 5.5 # E: assignment 24 | 25 | obj.var = 5 + 4j # E: assignment 26 | obj.var = True # E: assignment 27 | 28 | 29 | class Test2(HasTraits): 30 | var = String(minlen=5, something="else", regex=r"5") 31 | 32 | 33 | class Test3(HasTraits): 34 | var = String(minlen="5") # E: arg-type 35 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Time.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import datetime 12 | 13 | from traits.api import HasTraits, Time 14 | 15 | 16 | class TestClass(HasTraits): 17 | t = Time() 18 | 19 | 20 | obj = TestClass() 21 | obj.t = datetime.time(11, 12, 13) 22 | obj.t = "sometime-string" # E: assignment 23 | obj.t = datetime.datetime(2020, 1, 1) # E: assignment 24 | obj.t = 9 # E: assignment 25 | obj.t = [] # E: assignment 26 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/Tuple.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import HasTraits, Tuple 12 | 13 | 14 | class Test(HasTraits): 15 | var = Tuple(1, 2, 3) 16 | 17 | 18 | obj = Test() 19 | obj.var = "5" # E: assignment 20 | obj.var = 5 # E: assignment 21 | 22 | obj.var = False # E: assignment 23 | obj.var = 5.5 # E: assignment 24 | 25 | obj.var = 5 + 4j # E: assignment 26 | obj.var = True # E: assignment 27 | 28 | obj.var = (True,) 29 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/UUID.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import uuid 12 | from traits.api import HasTraits, UUID 13 | 14 | 15 | class Test(HasTraits): 16 | var = UUID() 17 | 18 | 19 | obj = Test() 20 | obj.var = uuid.UUID() 21 | 22 | obj.var = "someuuid" 23 | 24 | obj.var = 5 # E: assignment 25 | 26 | obj.var = False # E: assignment 27 | obj.var = 5.5 # E: assignment 28 | 29 | obj.var = 5 + 4j # E: assignment 30 | obj.var = True # E: assignment 31 | 32 | obj.var = (True,) # E: assignment 33 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/WeakRef.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from traits.api import WeakRef, HasTraits 12 | 13 | 14 | class Fruit: 15 | pass 16 | 17 | 18 | class TestClass(HasTraits): 19 | atr = WeakRef(Fruit) 20 | atr2 = WeakRef(Fruit()) 21 | atr3 = WeakRef("Fruit") 22 | -------------------------------------------------------------------------------- /traits/stubs_tests/examples/completeness.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | A selection of code snippets used to test completeness of the stubs. 13 | """ 14 | 15 | from traits.api import HasStrictTraits, Str, TraitError 16 | 17 | 18 | class HasName(HasStrictTraits): 19 | name = Str() 20 | 21 | 22 | def try_assigning_name(x: HasName, new_name: str): 23 | try: 24 | x.name = new_name 25 | except TraitError: 26 | raise ValueError(f"Bad name: {new_name}") 27 | -------------------------------------------------------------------------------- /traits/stubs_tests/numpy_examples/Array.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import numpy as np 12 | 13 | from traits.api import Array, ArrayOrNone, CArray, HasTraits 14 | 15 | 16 | class HasArrayTraits(HasTraits): 17 | spectrum = Array(shape=(None,), dtype=np.float64) 18 | complex_shape = Array(shape=((512, None), (512, None), (3, 4))) 19 | list_shape = Array(shape=[(512, None), (512, None), (3, 4)]) 20 | str_dtype = Array(dtype="f4") 21 | dtype_dtype = Array(dtype=np.dtype("float")) 22 | with_default_value = Array(value=np.zeros(5)) 23 | with_list_default = Array(value=[1, 2, 3, 4, 5]) 24 | with_tuple_default = Array(value=(1, 2, 3, 4, 5)) 25 | with_casting = Array(casting="same_kind") 26 | 27 | maybe_image = ArrayOrNone(shape=(None, None, 3), dtype=np.float64) 28 | cspectrum = CArray(shape=(None,), dtype=np.float64) 29 | 30 | # Bad trait declarations 31 | bad_dtype = Array(dtype=62) # E: arg-type 32 | bad_default = Array(value=123) # E: arg-type 33 | bad_shape = Array(shape=3) # E: arg-type 34 | bad_shape_element = Array(shape=(3, (None, None))) # E: arg-type 35 | 36 | 37 | obj = HasArrayTraits() 38 | obj.spectrum = np.array([2, 3, 4], dtype=np.float64) 39 | obj.spectrum = "not an array" # E: assignment 40 | obj.spectrum = None # E: assignment 41 | 42 | obj.maybe_image = None 43 | obj.maybe_image = np.zeros((5, 5, 3)) 44 | obj.maybe_image = 2.3 # E: assignment 45 | -------------------------------------------------------------------------------- /traits/testing/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Scripts and assert tools related to running unit tests. 12 | 13 | These scripts also allow running test suites in separate processes and 14 | aggregating the results. 15 | """ 16 | -------------------------------------------------------------------------------- /traits/testing/api.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from .doctest_tools import doctest_for_module 12 | from .unittest_tools import UnittestTools 13 | -------------------------------------------------------------------------------- /traits/testing/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/testing/tests/__init__.py -------------------------------------------------------------------------------- /traits/testing/tests/test_optional_dependencies.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.testing.optional_dependencies import optional_import 14 | 15 | 16 | class TestImportHandler(unittest.TestCase): 17 | def test_import_succeeds(self): 18 | 19 | module = optional_import("itertools") 20 | self.assertEqual(module.__name__, "itertools") 21 | 22 | def test_import_fails(self): 23 | 24 | module = optional_import("unavailable_module") 25 | self.assertIsNone(module) 26 | -------------------------------------------------------------------------------- /traits/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | # required by simple_test_case.py so it can do an import 12 | -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/README: -------------------------------------------------------------------------------- 1 | This directory contains binary files *.pkl whose contents are pickled traits 2 | and trait-related objects of various kinds, used for testing backward 3 | compatibility Traits unpickling. 4 | 5 | The pickle filenames are of the form: 6 | 7 | hitp-t5.2.0-p0-.pkl 8 | 9 | where the "t5.2.0" portion gives the version of Traits that was used to create 10 | the pickle, and the "p0" portion describes the pickle protocol. 11 | 12 | The "generate_pickles" script can be used to generate pickle files for 13 | a new version of Traits. 14 | -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/generate_pickles.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Script to generate the historical pickle test data. 13 | """ 14 | 15 | import os 16 | import pickle 17 | 18 | from traits.api import Float 19 | from traits import __version__ 20 | 21 | # Filename template. 22 | PKL_FILENAME = "hipt-t{traits_version}-p{pickle_protocol}-{description}.pkl" 23 | 24 | # Dictionary mapping description to object to be pickled. 25 | PICKLEES = { 26 | "float-ctrait": Float(5.3).as_ctrait(), 27 | } 28 | 29 | # Supported pickle protocols on this Python version. 30 | SUPPORTED_PICKLE_PROTOCOLS = range(pickle.HIGHEST_PROTOCOL + 1) 31 | 32 | 33 | def write_pickle_file(description, picklee, protocol, output_dir): 34 | filename = PKL_FILENAME.format( 35 | traits_version=__version__, 36 | pickle_protocol=protocol, 37 | description=description, 38 | ) 39 | output_path = os.path.join(output_dir, filename) 40 | with open(output_path, "wb") as pickle_file: 41 | pickle.dump(picklee, pickle_file, protocol=protocol) 42 | 43 | 44 | def generate_pickles(): 45 | # Write to the current directory. Could make the output directory 46 | # an option. 47 | pickle_directory = os.path.abspath(".") 48 | 49 | for protocol in SUPPORTED_PICKLE_PROTOCOLS: 50 | for description, picklee in PICKLEES.items(): 51 | write_pickle_file(description, picklee, protocol, pickle_directory) 52 | 53 | 54 | if __name__ == "__main__": 55 | generate_pickles() 56 | -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/hipt-t5.2.0-p0-float-ctrait.pkl: -------------------------------------------------------------------------------- 1 | ctraits.traits 2 | __newobj__ 3 | p0 4 | (ctraits.traits 5 | CTrait 6 | p1 7 | I0 8 | tp2 9 | Rp3 10 | (I0 11 | I0 12 | I5 13 | NI21 14 | (I21 15 | tp4 16 | I0 17 | F5.3 18 | I0 19 | NNI4 20 | Nccopy_reg 21 | _reconstructor 22 | p5 23 | (ctraits.trait_types 24 | Float 25 | p6 26 | c__builtin__ 27 | object 28 | p7 29 | Ntp8 30 | Rp9 31 | (dp10 32 | Vdefault_value 33 | p11 34 | F5.3 35 | sV_metadata 36 | p12 37 | (dp13 38 | Vtype 39 | p14 40 | Vtrait 41 | p15 42 | ssVdefault_value_type 43 | p16 44 | I0 45 | sb(dp17 46 | g14 47 | g15 48 | stp18 49 | b. -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/hipt-t5.2.0-p1-float-ctrait.pkl: -------------------------------------------------------------------------------- 1 | ctraits.traits 2 | __newobj__ 3 | q(ctraits.traits 4 | CTrait 5 | qKtqRq(KKKNK(KtqKG@333333KNNKNccopy_reg 6 | _reconstructor 7 | q(ctraits.trait_types 8 | Float 9 | qc__builtin__ 10 | object 11 | qNtqRq }q 12 | (X default_valueq G@333333X _metadataq }q XtypeqXtraitqsXdefault_value_typeqKub}qhhstqb. -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/hipt-t5.2.0-p2-float-ctrait.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/tests/test-data/historical-pickles/hipt-t5.2.0-p2-float-ctrait.pkl -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/hipt-t5.2.0-p3-float-ctrait.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/tests/test-data/historical-pickles/hipt-t5.2.0-p3-float-ctrait.pkl -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/hipt-t5.2.0-p4-float-ctrait.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/tests/test-data/historical-pickles/hipt-t5.2.0-p4-float-ctrait.pkl -------------------------------------------------------------------------------- /traits/tests/test-data/historical-pickles/hipt-t5.2.0-p5-float-ctrait.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/tests/test-data/historical-pickles/hipt-t5.2.0-p5-float-ctrait.pkl -------------------------------------------------------------------------------- /traits/tests/test_class_traits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Unit tests for the `HasTraits.class_traits` class function. 13 | 14 | """ 15 | 16 | import unittest 17 | 18 | from traits.api import HasTraits, Int, List, Str 19 | 20 | 21 | class A(HasTraits): 22 | 23 | x = Int 24 | 25 | name = Str(marked=True) 26 | 27 | 28 | class B(A): 29 | 30 | pass 31 | 32 | 33 | class C(B): 34 | 35 | lst = List(marked=False) 36 | 37 | y = Int(marked=True) 38 | 39 | 40 | class TestClassTraits(unittest.TestCase): 41 | def test_all_class_traits(self): 42 | expected = ["x", "name", "trait_added", "trait_modified"] 43 | self.assertCountEqual(A.class_traits(), expected) 44 | 45 | # Check that derived classes report the correct traits. 46 | self.assertCountEqual(B.class_traits(), expected) 47 | 48 | expected.extend(("lst", "y")) 49 | self.assertCountEqual(C.class_traits(), expected) 50 | 51 | def test_class_traits_with_metadata(self): 52 | 53 | # Retrieve all traits that have the `marked` metadata 54 | # attribute set to True. 55 | traits = C.class_traits(marked=True) 56 | self.assertCountEqual(list(traits.keys()), ("y", "name")) 57 | 58 | # Retrieve all traits that have a `marked` metadata attribute, 59 | # regardless of its value. 60 | marked_traits = C.class_traits(marked=lambda attr: attr is not None) 61 | self.assertCountEqual(marked_traits, ("y", "name", "lst")) 62 | -------------------------------------------------------------------------------- /traits/tests/test_constants.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | 12 | import unittest 13 | 14 | from traits.api import ComparisonMode 15 | 16 | 17 | class TestConstants(unittest.TestCase): 18 | def test_deprecated_comparison_constants(self): 19 | # Check availability of comparison constants. 20 | from traits.api import ( 21 | NO_COMPARE, OBJECT_IDENTITY_COMPARE, RICH_COMPARE) 22 | self.assertIs(NO_COMPARE, ComparisonMode.none) 23 | self.assertIs( 24 | OBJECT_IDENTITY_COMPARE, ComparisonMode.identity) 25 | self.assertIs( 26 | RICH_COMPARE, ComparisonMode.equality) 27 | -------------------------------------------------------------------------------- /traits/tests/test_dynamic_trait_definition.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import Float, HasTraits, Int, List 14 | 15 | 16 | class Foo(HasTraits): 17 | x = Float 18 | 19 | y_changes = List 20 | 21 | def _y_changed(self, new): 22 | self.y_changes.append(new) 23 | 24 | 25 | class TestDynamicTraitDefinition(unittest.TestCase): 26 | """ Test demonstrating special change events using the 'event' metadata. 27 | """ 28 | 29 | def test_add_trait(self): 30 | foo = Foo(x=3) 31 | foo.add_trait("y", Int) 32 | 33 | self.assertTrue(hasattr(foo, "y")) 34 | self.assertEqual(type(foo.y), int) 35 | 36 | foo.y = 4 37 | self.assertEqual(foo.y_changes, [4]) 38 | 39 | def test_remove_trait(self): 40 | foo = Foo(x=3) 41 | 42 | # We can't remove a "statically" added trait (i.e., a trait defined 43 | # in the Foo class). 44 | result = foo.remove_trait("x") 45 | self.assertFalse(result) 46 | 47 | # We can remove dynamically added traits. 48 | foo.add_trait("y", Int) 49 | foo.y = 70 50 | 51 | result = foo.remove_trait("y") 52 | self.assertTrue(result) 53 | 54 | self.assertFalse(hasattr(foo, "y")) 55 | foo.y = 10 56 | self.assertEqual(foo.y_changes, [70]) 57 | -------------------------------------------------------------------------------- /traits/tests/test_has_required_traits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | from traits.api import Int, Float, String, HasRequiredTraits, TraitError 13 | 14 | 15 | class TestHasRequiredTraits(unittest.TestCase): 16 | def test_trait_value_assignment(self): 17 | test_instance = RequiredTest(i_trait=4, f_trait=2.2, s_trait="test") 18 | self.assertEqual(test_instance.i_trait, 4) 19 | self.assertEqual(test_instance.f_trait, 2.2) 20 | self.assertEqual(test_instance.s_trait, "test") 21 | self.assertEqual(test_instance.non_req_trait, 4.4) 22 | self.assertEqual(test_instance.normal_trait, 42.0) 23 | 24 | def test_missing_required_trait(self): 25 | with self.assertRaises(TraitError) as exc: 26 | RequiredTest(i_trait=3) 27 | self.assertEqual( 28 | exc.exception.args[0], 29 | "The following required traits were not " 30 | "provided: f_trait, s_trait.", 31 | ) 32 | 33 | 34 | class RequiredTest(HasRequiredTraits): 35 | i_trait = Int(required=True) 36 | f_trait = Float(required=True) 37 | s_trait = String(required=True) 38 | non_req_trait = Float(4.4, required=False) 39 | normal_trait = Float(42.0) 40 | -------------------------------------------------------------------------------- /traits/tests/test_int_range_long.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import HasTraits, Int, Range, TraitError 14 | 15 | 16 | class A(HasTraits): 17 | i = Int 18 | r = Range(2, 9223372036854775807) 19 | 20 | 21 | class TraitIntRange(unittest.TestCase): 22 | def test_int(self): 23 | "Test it is legal to set an Int trait to any integer value" 24 | a = A() 25 | a.i = 1 26 | a.i = 10**20 27 | 28 | def test_range(self): 29 | "Test a range trait with large integers being set to an int value" 30 | a = A() 31 | a.r = 256 32 | a.r = 20 33 | self.assertRaises(TraitError, a.trait_set, r=1) 34 | self.assertRaises( 35 | TraitError, a.trait_set, r=9223372036854775808 36 | ) 37 | -------------------------------------------------------------------------------- /traits/tests/test_keyword_args.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import HasTraits, Instance, Int 14 | 15 | 16 | class Bar(HasTraits): 17 | b = Int(3) 18 | 19 | 20 | class Foo(HasTraits): 21 | bar = Instance(Bar) 22 | 23 | 24 | class KeyWordArgsTest(unittest.TestCase): 25 | def test_using_kw(self): 26 | bar = Bar(b=5) 27 | foo = Foo(bar=bar) 28 | self.assertEqual(foo.bar.b, 5) 29 | 30 | def test_not_using_kw(self): 31 | foo = Foo() 32 | self.assertEqual(foo.bar, None) 33 | -------------------------------------------------------------------------------- /traits/tests/test_none.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import HasTraits, TraitError 14 | from traits.trait_types import _NoneTrait 15 | 16 | 17 | class A(HasTraits): 18 | none_atr = _NoneTrait(default_value=None) 19 | 20 | 21 | class TestCaseNoneTrait(unittest.TestCase): 22 | def test_none(self): 23 | obj = A() 24 | self.assertIsNone(obj.none_atr) 25 | 26 | def test_assign_non_none(self): 27 | with self.assertRaises(TraitError): 28 | A(none_atr=5) 29 | 30 | def test_default_value_not_none(self): 31 | with self.assertRaises(ValueError): 32 | class TestClass(HasTraits): 33 | none_trait = _NoneTrait(default_value=[]) 34 | -------------------------------------------------------------------------------- /traits/tests/test_pickle_validated_dict.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import pickle 12 | import unittest 13 | 14 | from traits.api import Dict, HasTraits, Int, List 15 | 16 | 17 | class C(HasTraits): 18 | # A dict trait containing a list trait 19 | a = Dict(Int, List(Int)) 20 | 21 | # And we must initialize it to something non-trivial 22 | def __init__(self): 23 | super().__init__() 24 | self.a = {1: [2, 3]} 25 | 26 | 27 | class PickleValidatedDictTestCase(unittest.TestCase): 28 | def test_pickle_validated_dict(self): 29 | 30 | # And we must unpickle one 31 | x = pickle.dumps(C()) 32 | try: 33 | pickle.loads(x) 34 | except AttributeError as e: 35 | self.fail("Unpickling raised an AttributeError: %s" % e) 36 | -------------------------------------------------------------------------------- /traits/tests/test_property_delete.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Unit tests to ensure that we can call reset_traits/delete on a 13 | property trait (regression tests for Github issue #67). 14 | 15 | """ 16 | 17 | import unittest 18 | 19 | from traits.api import Any, HasTraits, Int, Property, TraitError 20 | 21 | 22 | class E(HasTraits): 23 | 24 | a = Property(Any) 25 | 26 | b = Property(Int) 27 | 28 | 29 | class TestPropertyDelete(unittest.TestCase): 30 | def test_property_delete(self): 31 | e = E() 32 | with self.assertRaises(TraitError): 33 | del e.a 34 | with self.assertRaises(TraitError): 35 | del e.b 36 | 37 | def test_property_reset_traits(self): 38 | e = E() 39 | unresetable = e.reset_traits() 40 | self.assertCountEqual(unresetable, ["a", "b"]) 41 | -------------------------------------------------------------------------------- /traits/tests/test_python_properties.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Tests for regular Python properties in a HasTraits subclass. """ 12 | 13 | import unittest 14 | 15 | from traits.api import HasTraits 16 | 17 | 18 | class Model(HasTraits): 19 | def __init__(self): 20 | super().__init__() 21 | self._value = 0 22 | 23 | @property 24 | def read_only(self): 25 | return 1729 26 | 27 | @property 28 | def value(self): 29 | return self._value 30 | 31 | @value.setter 32 | def value(self, new): 33 | self._value = new 34 | 35 | 36 | class TestPythonProperty(unittest.TestCase): 37 | def test_read_only_property(self): 38 | model = Model() 39 | self.assertEqual(model.read_only, 1729) 40 | 41 | with self.assertRaises(AttributeError): 42 | model.read_only = 2034 43 | 44 | with self.assertRaises(AttributeError): 45 | del model.read_only 46 | 47 | def test_read_write_property(self): 48 | model = Model() 49 | self.assertEqual(model.value, 0) 50 | model.value = 23 51 | self.assertEqual(model.value, 23) 52 | model.value = 77 53 | self.assertEqual(model.value, 77) 54 | 55 | with self.assertRaises(AttributeError): 56 | del model.value 57 | -------------------------------------------------------------------------------- /traits/tests/test_readonly.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Tests for the ReadOnly trait type. 13 | 14 | """ 15 | import unittest 16 | 17 | from traits.api import ( 18 | HasTraits, 19 | ReadOnly, 20 | TraitError, 21 | ) 22 | 23 | 24 | class ObjectWithReadOnlyText(HasTraits): 25 | """ A dummy object that set the readonly trait in __init__ 26 | 27 | There exists such usage in TraitsUI. 28 | """ 29 | 30 | text = ReadOnly() 31 | 32 | def __init__(self, text, **traits): 33 | self.text = text 34 | super(ObjectWithReadOnlyText, self).__init__(**traits) 35 | 36 | 37 | class TestReadOnlyTrait(unittest.TestCase): 38 | """ Test ReadOnly TraitType. """ 39 | 40 | def test_set_readonly_trait_in_init(self): 41 | 42 | obj = ObjectWithReadOnlyText(text="ABC") 43 | self.assertEqual(obj.text, "ABC") 44 | 45 | with self.assertRaises(TraitError): 46 | obj.text = "XYZ" 47 | 48 | self.assertEqual(obj.text, "ABC") 49 | -------------------------------------------------------------------------------- /traits/tests/test_special_event_handlers.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import Any, HasStrictTraits, Str 14 | 15 | 16 | class TestSpecialEvent(unittest.TestCase): 17 | """ Test demonstrating special change events using the 'event' metadata. 18 | """ 19 | 20 | def setUp(self): 21 | self.change_events = [] 22 | self.foo = Foo(test=self) 23 | 24 | def test_events(self): 25 | self.foo.val = "CHANGE" 26 | 27 | values = ["CHANGE"] 28 | self.assertEqual(self.change_events, values) 29 | 30 | def test_instance_events(self): 31 | foo = self.foo 32 | foo.add_trait("val2", Str(event="the_trait")) 33 | foo.val2 = "CHANGE2" 34 | 35 | values = ["CHANGE2"] 36 | self.assertEqual(self.change_events, values) 37 | 38 | 39 | class Foo(HasStrictTraits): 40 | val = Str(event="the_trait") 41 | test = Any(None) 42 | 43 | def _the_trait_changed(self, new): 44 | if self.test is not None: 45 | self.test.change_events.append(new) 46 | -------------------------------------------------------------------------------- /traits/tests/test_string.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Tests for the String trait type. 13 | 14 | """ 15 | import unittest 16 | 17 | from traits.api import HasTraits, String 18 | from traits.testing.optional_dependencies import numpy, requires_numpy 19 | 20 | 21 | class A(HasTraits): 22 | string = String 23 | 24 | 25 | class TestString(unittest.TestCase): 26 | @requires_numpy 27 | def test_accepts_numpy_string(self): 28 | numpy_string = numpy.str_("this is a numpy string!") 29 | a = A() 30 | a.string = numpy_string 31 | self.assertEqual(a.string, numpy_string) 32 | self.assertIs(type(a.string), str) 33 | -------------------------------------------------------------------------------- /traits/tests/test_trait_default_initializer.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.trait_types import Int 14 | from traits.has_traits import HasTraits 15 | 16 | 17 | class Foo(HasTraits): 18 | 19 | bar = Int 20 | 21 | def _bar_default(self): 22 | return 4 23 | 24 | 25 | class TestTraitDefaultInitializer(unittest.TestCase): 26 | """ Test basic usage of the default method. 27 | 28 | """ 29 | 30 | def test_default_value(self): 31 | foo = Foo() 32 | self.assertEqual(foo.bar, 4) 33 | 34 | def test_default_value_override(self): 35 | foo = Foo(bar=3) 36 | self.assertEqual(foo.bar, 3) 37 | 38 | def test_reset_to_default(self): 39 | foo = Foo(bar=3) 40 | foo.reset_traits(traits=["bar"]) 41 | self.assertEqual(foo.bar, 4) 42 | 43 | def test_error_propagation_in_default_methods(self): 44 | class FooException(Foo): 45 | def _bar_default(self): 46 | 1 / 0 47 | 48 | foo = FooException() 49 | self.assertRaises(ZeroDivisionError, lambda: foo.bar) 50 | 51 | class FooKeyError(Foo): 52 | def _bar_default(self): 53 | raise KeyError() 54 | 55 | # Check that KeyError is propagated (issue #70). 56 | foo = FooKeyError() 57 | self.assertRaises(KeyError, lambda: foo.bar) 58 | -------------------------------------------------------------------------------- /traits/tests/test_trait_exceptions.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import HasTraits, Int 14 | 15 | 16 | class A(HasTraits): 17 | x = Int(5) 18 | 19 | 20 | class TestGetAttr(unittest.TestCase): 21 | def setUp(self): 22 | self.a = A() 23 | 24 | def test_bad__getattribute__(self): 25 | # Argument to __getattribute__ must be a string 26 | self.assertEqual(self.a.__getattribute__("x"), 5) 27 | 28 | with self.assertRaises(TypeError) as e: 29 | self.a.__getattribute__(2) 30 | 31 | # Error message contains value and type of bad attribute name 32 | exception_msg = str(e.exception) 33 | self.assertIn("2", exception_msg) 34 | self.assertIn("int", exception_msg) 35 | -------------------------------------------------------------------------------- /traits/tests/test_trait_notifiers.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import HasTraits, Int 14 | 15 | 16 | class TestTraitNotifiers(unittest.TestCase): 17 | def test_ui_dispatch(self): 18 | # Given 19 | class DispatchTest(HasTraits): 20 | test_param = Int() 21 | 22 | t = DispatchTest() 23 | 24 | event_list = [] 25 | 26 | # create handler 27 | def test_handler(event): 28 | event_list.append(event) 29 | 30 | # When 31 | t.observe(test_handler, "test_param", dispatch="ui") 32 | t.test_param = 1 33 | 34 | # Then 35 | # check the observer is called once 36 | self.assertEqual(len(event_list), 1) 37 | # check the name of the parameter change 38 | self.assertEqual(event_list[0].name, "test_param") 39 | # check whether the value starts at 0 40 | self.assertEqual(event_list[0].old, 0) 41 | # check whether the value has been set to 1 42 | self.assertEqual(event_list[0].new, 1) 43 | -------------------------------------------------------------------------------- /traits/tests/test_unicode_traits.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import ( 14 | BaseCStr, 15 | BaseCUnicode, 16 | BaseStr, 17 | BaseUnicode, 18 | CStr, 19 | CUnicode, 20 | Str, 21 | Unicode, 22 | ) 23 | 24 | 25 | class TestUnicodeTraits(unittest.TestCase): 26 | def test_aliases(self): 27 | self.assertIs(Unicode, Str) 28 | self.assertIs(CUnicode, CStr) 29 | self.assertIs(BaseUnicode, BaseStr) 30 | self.assertIs(BaseCUnicode, BaseCStr) 31 | -------------------------------------------------------------------------------- /traits/tests/test_uuid.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Test cases for UUID traits. """ 12 | 13 | import unittest 14 | 15 | import uuid 16 | 17 | from traits.api import HasTraits, TraitError, UUID 18 | 19 | 20 | class A(HasTraits): 21 | id = UUID 22 | 23 | 24 | class B(HasTraits): 25 | id = UUID(can_init=True) 26 | 27 | 28 | class TestUUID(unittest.TestCase): 29 | 30 | def test_bad_assignment(self): 31 | with self.assertRaises(TraitError): 32 | a = A() 33 | a.id = uuid.uuid4() 34 | 35 | def test_bad_init(self): 36 | with self.assertRaises(TraitError): 37 | A(id=uuid.uuid4()) 38 | 39 | def test_good_init(self): 40 | B(id=uuid.uuid4()) 41 | B(id=str(uuid.uuid4())) 42 | -------------------------------------------------------------------------------- /traits/tests/test_validated_tuple.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import unittest 12 | 13 | from traits.api import HasStrictTraits, Int, TraitError 14 | from traits.tests.tuple_test_mixin import TupleTestMixin 15 | from traits.trait_types import ValidatedTuple 16 | 17 | 18 | class Simple(HasStrictTraits): 19 | 20 | scalar_range = ValidatedTuple( 21 | Int(0), Int(1), fvalidate=lambda x: x[0] < x[1] 22 | ) 23 | 24 | 25 | class ValidatedTupleTestCase(TupleTestMixin, unittest.TestCase): 26 | def setUp(self): 27 | self.trait = ValidatedTuple 28 | 29 | def test_initialization(self): 30 | simple = Simple() 31 | self.assertEqual(simple.scalar_range, (0, 1)) 32 | 33 | def test_custom_validation(self): 34 | simple = Simple() 35 | 36 | simple.scalar_range = (2, 5) 37 | self.assertEqual(simple.scalar_range, (2, 5)) 38 | 39 | with self.assertRaises(TraitError): 40 | simple.scalar_range = (5, 2) 41 | 42 | def test_error_during_custom_validation(self): 43 | def fvalidate(x): 44 | if x == (5, 2): 45 | raise RuntimeError() 46 | return True 47 | 48 | class Simple(HasStrictTraits): 49 | 50 | scalar_range = ValidatedTuple(Int(0), Int(1), fvalidate=fvalidate) 51 | 52 | simple = Simple() 53 | 54 | with self.assertRaises(RuntimeError): 55 | simple.scalar_range = (5, 2) 56 | -------------------------------------------------------------------------------- /traits/trait_handler.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from .base_trait_handler import BaseTraitHandler 12 | 13 | 14 | class TraitHandler(BaseTraitHandler): 15 | ... 16 | -------------------------------------------------------------------------------- /traits/trait_handlers.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from typing import ( 12 | Any as _Any, 13 | Callable as _CallableType, 14 | Dict as _Dict, 15 | Type as _Type, 16 | Union as _Union, 17 | ) 18 | from .trait_handler import TraitHandler 19 | 20 | 21 | class TraitCoerceType(TraitHandler): 22 | def __init__(self, 23 | atype: _Union[_Type, str] = ..., 24 | ) -> None: 25 | ... 26 | 27 | 28 | class TraitCastType(TraitCoerceType): 29 | ... 30 | 31 | 32 | class TraitInstance(TraitHandler): 33 | def __init__(self, 34 | aclass: _Union[_Type, str] = ..., 35 | allow_none: bool = ..., 36 | module: str = ..., 37 | ) -> None: 38 | ... 39 | 40 | 41 | class TraitFunction(TraitHandler): 42 | def __init__(self, 43 | afunc: _CallableType = ...) -> None: 44 | ... 45 | 46 | 47 | class TraitEnum(TraitHandler): 48 | def __init__(self, 49 | afunc: _CallableType = ...) -> None: 50 | ... 51 | 52 | 53 | class TraitMap(TraitHandler): 54 | def __init__(self, 55 | map: _Dict = ...) -> None: 56 | ... 57 | 58 | 59 | class TraitCompound(TraitHandler): 60 | def __init__(self, 61 | *handlers: _Any) -> None: 62 | ... 63 | -------------------------------------------------------------------------------- /traits/traits.pyi: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2020-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from typing import ( 12 | Any as _Any, 13 | Optional, 14 | Callable as _CallableType, 15 | Dict as _DictType, 16 | ) 17 | 18 | NoneType: _Any 19 | ConstantTypes: _Any 20 | PythonTypes: _Any 21 | CallableTypes: _Any 22 | TraitTypes: _Any 23 | DefaultValues: _Any 24 | 25 | 26 | class _InstanceArgs: 27 | def __init__(self, factory: _Any, args: _Any, kw: _Any) -> None: ... 28 | 29 | 30 | class Default: 31 | default_value: _Any = ... 32 | 33 | def __init__(self, func: Optional[_Any] = ..., args: _Any = ..., 34 | kw: Optional[_Any] = ...) -> None: ... 35 | 36 | 37 | def Trait(*value_type: _Any, 38 | **metadata: _DictType[str, _Any]): ... 39 | 40 | 41 | def Property(fget: Optional[_CallableType] = ..., 42 | fset: Optional[_CallableType] = ..., 43 | fvalidate: Optional[_CallableType] = ..., 44 | force: bool = ..., 45 | handler: Optional[_CallableType] = ..., 46 | trait: Optional[_Any] = ..., 47 | **metadata: _Any) -> _Any: 48 | ... 49 | 50 | 51 | class ForwardProperty: 52 | metadata: _Any = ... 53 | validate: _Any = ... 54 | handler: _Any = ... 55 | 56 | def __init__(self, metadata: _Any, 57 | validate: Optional[_Any] = ..., 58 | handler: Optional[_Any] = ...) -> None: ... 59 | 60 | 61 | generic_trait: _Any 62 | -------------------------------------------------------------------------------- /traits/traits_notifiers.pyi: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | _UI_Handler = Callable[..., None] | None 4 | 5 | 6 | def get_ui_handler() -> _UI_Handler: ... 7 | 8 | def set_ui_handler(handler: _UI_Handler) -> None: ... 9 | -------------------------------------------------------------------------------- /traits/util/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ 12 | Utility functions, part of the Traits project. 13 | 14 | """ 15 | -------------------------------------------------------------------------------- /traits/util/api.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | from .deprecated import deprecated 12 | from .event_tracer import record_events 13 | from .import_symbol import import_symbol 14 | -------------------------------------------------------------------------------- /traits/util/clean_strings.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Provides functions that mange strings to avoid characters that would be 12 | problematic in certain situations. 13 | """ 14 | 15 | # Standard library imports. 16 | import keyword 17 | 18 | 19 | def python_name(name): 20 | """ Attempt to make a valid Python identifier out of a name. 21 | """ 22 | 23 | if len(name) > 0: 24 | # Replace spaces with underscores. 25 | name = name.replace(" ", "_").lower() 26 | 27 | # If the name is a Python keyword then prefix it with an 28 | # underscore. 29 | if keyword.iskeyword(name): 30 | name = "_" + name 31 | 32 | # If the name starts with a digit then prefix it with an 33 | # underscore. 34 | if name[0].isdigit(): 35 | name = "_" + name 36 | 37 | return name 38 | -------------------------------------------------------------------------------- /traits/util/deprecated.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ A decorator for marking methods/functions as deprecated. """ 12 | 13 | # Standard library imports. 14 | import functools 15 | import warnings 16 | 17 | 18 | def deprecated(message): 19 | """ A factory for decorators for marking methods/functions as deprecated. 20 | 21 | """ 22 | 23 | def decorator(fn): 24 | """ A decorator for marking methods/functions as deprecated. """ 25 | 26 | @functools.wraps(fn) 27 | def wrapper(*args, **kw): 28 | """ The method/function wrapper. """ 29 | 30 | warnings.warn(message, DeprecationWarning, stacklevel=2) 31 | return fn(*args, **kw) 32 | 33 | return wrapper 34 | 35 | return decorator 36 | -------------------------------------------------------------------------------- /traits/util/home_directory.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | import os 12 | 13 | 14 | def get_home_directory(): 15 | """ Determine the user's home directory.""" 16 | 17 | # 'HOME' should work on most Unixes, and 'USERPROFILE' works on at 18 | # least Windows XP ;^) 19 | # 20 | # FIXME: Is this really better than the following?? 21 | # path = os.path.expanduser('~') 22 | # The above seems to work on both Windows and Unixes though the docs 23 | # indicate it might not work as well on Macs. 24 | for name in ["HOME", "USERPROFILE"]: 25 | if name in os.environ: 26 | # Make sure that the path ends with a path separator. 27 | path = os.environ[name] 28 | if path[-1] != os.path.sep: 29 | path += os.path.sep 30 | 31 | break 32 | 33 | # If all else fails, the current directory will do. 34 | else: 35 | path = "" 36 | 37 | return path 38 | -------------------------------------------------------------------------------- /traits/util/import_symbol.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ A function to import symbols. """ 12 | 13 | from importlib import import_module 14 | 15 | from traits.trait_base import xgetattr 16 | 17 | 18 | def import_symbol(symbol_path): 19 | """ Import the symbol defined by the specified symbol path. 20 | 21 | Examples 22 | -------- 23 | 24 | import_symbol('tarfile:TarFile') -> TarFile 25 | import_symbol('tarfile:TarFile.open') -> TarFile.open 26 | 27 | To allow compatibility with old-school traits symbol names we also allow 28 | all-dotted paths, but in this case you can only import top-level names 29 | from the module. 30 | 31 | import_symbol('tarfile.TarFile') -> TarFile 32 | 33 | """ 34 | 35 | if ":" in symbol_path: 36 | module_name, symbol_name = symbol_path.split(":") 37 | 38 | module = import_module(module_name) 39 | symbol = xgetattr(module, symbol_name) 40 | 41 | else: 42 | components = symbol_path.split(".") 43 | module_name = ".".join(components[:-1]) 44 | symbol_name = components[-1] 45 | 46 | module = import_module(module_name) 47 | symbol = getattr(module, symbol_name) 48 | 49 | return symbol 50 | -------------------------------------------------------------------------------- /traits/util/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enthought/traits/4a519d8801f2a1584e19c66eedeff0fc022360ed/traits/util/tests/__init__.py -------------------------------------------------------------------------------- /traits/util/tests/test_import_symbol.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ Tests for the import manager. """ 12 | 13 | import unittest 14 | 15 | from traits.util.api import import_symbol 16 | 17 | 18 | class TestImportSymbol(unittest.TestCase): 19 | """ Tests for the import manager. """ 20 | 21 | def test_import_dotted_symbol(self): 22 | """ import dotted symbol """ 23 | 24 | import tarfile 25 | 26 | symbol = import_symbol("tarfile.TarFile") 27 | self.assertEqual(symbol, tarfile.TarFile) 28 | 29 | def test_import_nested_symbol(self): 30 | """ import nested symbol """ 31 | 32 | import tarfile 33 | 34 | symbol = import_symbol("tarfile:TarFile.open") 35 | self.assertEqual(symbol, tarfile.TarFile.open) 36 | 37 | def test_import_dotted_module(self): 38 | """ import dotted module """ 39 | 40 | symbol = import_symbol("traits.util.import_symbol:import_symbol") 41 | 42 | self.assertEqual(symbol, import_symbol) 43 | -------------------------------------------------------------------------------- /traits/util/toposort.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2005-2025 Enthought, Inc., Austin, TX 2 | # All rights reserved. 3 | # 4 | # This software is provided without warranty under the terms of the BSD 5 | # license included in LICENSE.txt and may be redistributed only under 6 | # the conditions described in the aforementioned license. The license 7 | # is also available online at http://www.enthought.com/licenses/BSD.txt 8 | # 9 | # Thanks for using Enthought open source! 10 | 11 | """ A simple topological sort on a dictionary graph. 12 | """ 13 | 14 | 15 | class CyclicGraph(Exception): 16 | """ 17 | Exception for cyclic graphs. 18 | """ 19 | 20 | def __init__(self): 21 | Exception.__init__(self, "Graph is cyclic") 22 | 23 | 24 | def topological_sort(graph): 25 | """ 26 | Returns the nodes in the graph in topological order. 27 | """ 28 | discovered = {} 29 | explored = {} 30 | order = [] 31 | 32 | def explore(node): 33 | children = graph.get(node, []) 34 | for child in children: 35 | if child in explored: 36 | pass 37 | elif child in discovered: 38 | raise CyclicGraph() 39 | else: 40 | discovered[child] = 1 41 | explore(child) 42 | explored[node] = 1 43 | order.append(node) 44 | 45 | for node in graph.keys(): 46 | if node not in explored: 47 | explore(node) 48 | order.reverse() 49 | return order 50 | --------------------------------------------------------------------------------