pax_global_header00006660000000000000000000000064146104505440014515gustar00rootroot0000000000000052 comment=13de53c537a257402035139dd6862558eb19d362 ipython-traitlets-a3e321a/000077500000000000000000000000001461045054400156215ustar00rootroot00000000000000ipython-traitlets-a3e321a/.git-blame-ignore-revs000066400000000000000000000001071461045054400217170ustar00rootroot00000000000000# Initial pre-commit reformat 660aeaf51fdf4df1b696faed681819de246ad081 ipython-traitlets-a3e321a/.github/000077500000000000000000000000001461045054400171615ustar00rootroot00000000000000ipython-traitlets-a3e321a/.github/dependabot.yml000066400000000000000000000005071461045054400220130ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" groups: actions: patterns: - "*" - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" groups: actions: patterns: - "*" ipython-traitlets-a3e321a/.github/workflows/000077500000000000000000000000001461045054400212165ustar00rootroot00000000000000ipython-traitlets-a3e321a/.github/workflows/downstream.yml000066400000000000000000000045161461045054400241320ustar00rootroot00000000000000name: Test downstream projects on: push: branches: ["main"] pull_request: concurrency: group: downstream-${{ github.ref }} cancel-in-progress: true jobs: ipython: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/downstream-test@v1 with: package_name: ipython package_spec: pip install -e ".[test]" nbconvert: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/downstream-test@v1 with: package_name: nbconvert package_spec: pip install -e ".[test]" jupyter_server: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/downstream-test@v1 with: package_name: jupyter_server ipywidgets: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/downstream-test@v1 with: package_name: ipywidgets notebook: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/downstream-test@v1 with: package_name: notebook test_command: pytest -vv --ignore-glob=notebook/tests/selenium/* --ignore-glob=notebook/nbconvert/tests/* --ignore-glob=notebook/services/nbconvert/tests/* downstream_check: # This job does nothing and is only used for the branch protection if: always() needs: - notebook - ipywidgets - jupyter_server - nbconvert - ipython runs-on: ubuntu-latest steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} ipython-traitlets-a3e321a/.github/workflows/enforce-label.yml000066400000000000000000000005001461045054400244320ustar00rootroot00000000000000name: Enforce PR label on: pull_request: types: [labeled, unlabeled, opened, edited, synchronize] jobs: enforce-label: runs-on: ubuntu-latest permissions: pull-requests: write steps: - name: enforce-triage-label uses: jupyterlab/maintainer-tools/.github/actions/enforce-label@v1 ipython-traitlets-a3e321a/.github/workflows/prep-release.yml000066400000000000000000000032311461045054400243240ustar00rootroot00000000000000name: "Step 1: Prep Release" on: workflow_dispatch: inputs: version_spec: description: "New Version Specifier" default: "next" required: false branch: description: "The branch to target" required: false post_version_spec: description: "Post Version Specifier" required: false silent: description: "Set a placeholder in the changelog and don't publish the release." required: false type: boolean since: description: "Use PRs with activity since this date or git reference" required: false since_last_stable: description: "Use PRs with activity since the last stable git tag" required: false type: boolean jobs: prep_release: runs-on: ubuntu-latest permissions: contents: write steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Prep Release id: prep-release uses: jupyter-server/jupyter_releaser/.github/actions/prep-release@v2 with: token: ${{ secrets.GITHUB_TOKEN }} version_spec: ${{ github.event.inputs.version_spec }} silent: ${{ github.event.inputs.silent }} post_version_spec: ${{ github.event.inputs.post_version_spec }} target: ${{ github.event.inputs.target }} branch: ${{ github.event.inputs.branch }} since: ${{ github.event.inputs.since }} since_last_stable: ${{ github.event.inputs.since_last_stable }} - name: "** Next Step **" run: | echo "Optional): Review Draft Release: ${{ steps.prep-release.outputs.release_url }}" ipython-traitlets-a3e321a/.github/workflows/publish-changelog.yml000066400000000000000000000016401461045054400253350ustar00rootroot00000000000000name: "Publish Changelog" on: release: types: [published] workflow_dispatch: inputs: branch: description: "The branch to target" required: false jobs: publish_changelog: runs-on: ubuntu-latest environment: release steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: actions/create-github-app-token@v1 id: app-token with: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Publish changelog id: publish-changelog uses: jupyter-server/jupyter_releaser/.github/actions/publish-changelog@v2 with: token: ${{ steps.app-token.outputs.token }} branch: ${{ github.event.inputs.branch }} - name: "** Next Step **" run: | echo "Merge the changelog update PR: ${{ steps.publish-changelog.outputs.pr_url }}" ipython-traitlets-a3e321a/.github/workflows/publish-release.yml000066400000000000000000000034061461045054400250300ustar00rootroot00000000000000name: "Step 2: Publish Release" on: workflow_dispatch: inputs: branch: description: "The target branch" required: false release_url: description: "The URL of the draft GitHub release" required: false steps_to_skip: description: "Comma separated list of steps to skip" required: false jobs: publish_release: runs-on: ubuntu-latest environment: release permissions: id-token: write steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: actions/create-github-app-token@v1 id: app-token with: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Populate Release id: populate-release uses: jupyter-server/jupyter_releaser/.github/actions/populate-release@v2 with: token: ${{ steps.app-token.outputs.token }} branch: ${{ github.event.inputs.branch }} release_url: ${{ github.event.inputs.release_url }} steps_to_skip: ${{ github.event.inputs.steps_to_skip }} - name: Finalize Release id: finalize-release uses: jupyter-server/jupyter_releaser/.github/actions/finalize-release@v2 with: token: ${{ steps.app-token.outputs.token }} release_url: ${{ steps.populate-release.outputs.release_url }} - name: "** Next Step **" if: ${{ success() }} run: | echo "Verify the final release" echo ${{ steps.finalize-release.outputs.release_url }} - name: "** Failure Message **" if: ${{ failure() }} run: | echo "Failed to Publish the Draft Release Url:" echo ${{ steps.populate-release.outputs.release_url }} ipython-traitlets-a3e321a/.github/workflows/tests.yml000066400000000000000000000104271461045054400231070ustar00rootroot00000000000000name: Tests on: push: pull_request: schedule: - cron: "0 8 * * *" concurrency: group: >- ${{ github.workflow }}- ${{ github.ref_type }}- ${{ github.event.pull_request.number || github.sha }} cancel-in-progress: true defaults: run: shell: bash -eux {0} jobs: tests: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] python-version: ["3.8", "3.12"] include: - os: windows-latest python-version: "3.9" - os: ubuntu-latest python-version: "pypy-3.8" - os: ubuntu-latest python-version: "3.10" - os: macos-latest python-version: "3.11" steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Run Tests run: hatch run cov:test - uses: jupyterlab/maintainer-tools/.github/actions/upload-coverage@v1 coverage: runs-on: ubuntu-latest needs: - tests steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/report-coverage@v1 test_minimum_versions: name: Test Minimum Versions runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - name: Base Setup uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 with: dependency_type: minimum - name: Run the unit tests run: | hatch run test:nowarn || hatch -v run test:nowarn --lf test_lint: name: Test Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Run Linters run: | hatch run typing:test hatch run lint:build pipx run 'validate-pyproject[all]' pyproject.toml pipx run doc8 --max-line-length=200 test_docs: timeout-minutes: 10 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Build the docs run: hatch run docs:build test_prereleases: name: Test Prereleases timeout-minutes: 10 runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Base Setup uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 with: dependency_type: pre - name: Run the tests run: | hatch run test:nowarn || hatch run test:nowarn --lf make_sdist: name: Make SDist runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/make-sdist@v1 test_sdist: runs-on: ubuntu-latest needs: [make_sdist] name: Install from SDist and Test timeout-minutes: 20 steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/test-sdist@v1 check_links: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/check-links@v1 check_release: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Base Setup uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Install Dependencies run: | pip install -e . - name: Check Release uses: jupyter-server/jupyter_releaser/.github/actions/check-release@v2 with: token: ${{ secrets.GITHUB_TOKEN }} tests_check: # This job does nothing and is only used for the branch protection if: always() needs: - coverage - test_lint - test_docs - test_minimum_versions - test_prereleases - check_links - check_release - test_sdist runs-on: ubuntu-latest steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} ipython-traitlets-a3e321a/.gitignore000066400000000000000000000004021461045054400176050ustar00rootroot00000000000000MANIFEST build dist _build docs/man/*.gz docs/gh-pages IPython/html/notebook/static/mathjax IPython/html/static/style/*.map *.py[co] __pycache__ *.egg-info *~ *.bak .ipynb_checkpoints .tox .DS_Store \#*# .#* .coverage .cache htmlcov docs/source/CHANGELOG.md ipython-traitlets-a3e321a/.mailmap000066400000000000000000000250661461045054400172530ustar00rootroot00000000000000A. J. Holyoake ajholyoake Aaron Culich Aaron Culich Aron Ahmadia ahmadia Benjamin Ragan-Kelley Benjamin Ragan-Kelley Min RK Benjamin Ragan-Kelley MinRK Barry Wark Barry Wark Ben Edwards Ben Edwards Bradley M. Froehle Bradley M. Froehle Bradley M. Froehle Bradley Froehle Brandon Parsons Brandon Parsons Brian E. Granger Brian Granger Brian E. Granger Brian Granger <> Brian E. Granger bgranger <> Brian E. Granger bgranger Christoph Gohlke cgohlke Cyrille Rossant rossant Damián Avila damianavila Damián Avila damianavila Damon Allen damontallen Darren Dale darren.dale <> Darren Dale Darren Dale <> Dav Clark Dav Clark <> Dav Clark Dav Clark David Hirschfeld dhirschfeld David P. Sanders David P. Sanders David Warde-Farley David Warde-Farley <> Doug Blank Doug Blank Eugene Van den Bulke Eugene Van den Bulke Evan Patterson Evan Patterson Evan Patterson Evan Patterson Evan Patterson epatters Evan Patterson epatters Ernie French Ernie French Ernie French ernie french Ernie French ernop Fernando Perez Fernando Perez Fernando Perez Fernando Perez fperez <> Fernando Perez fptest <> Fernando Perez fptest1 <> Fernando Perez Fernando Perez Fernando Perez Fernando Perez <> Fernando Perez Fernando Perez Frank Murphy Frank Murphy Gabriel Becker gmbecker Gael Varoquaux gael.varoquaux <> Gael Varoquaux gvaroquaux Gael Varoquaux Gael Varoquaux <> Ingolf Becker watercrossing Jake Vanderplas Jake Vanderplas Jakob Gager jakobgager Jakob Gager jakobgager Jakob Gager jakobgager Jason Grout Jason Grout Jason Gors jason gors Jason Gors jgors Jens Hedegaard Nielsen Jens Hedegaard Nielsen Jens Hedegaard Nielsen Jens H Nielsen Jens Hedegaard Nielsen Jens H. Nielsen Jez Ng Jez Ng Jonathan Frederic Jonathan Frederic Jonathan Frederic Jonathan Frederic Jonathan Frederic Jonathan Frederic Jonathan Frederic jon Jonathan Frederic U-Jon-PC\Jon Jonathan March Jonathan March Jonathan March jdmarch Jörgen Stenarson Jörgen Stenarson Jörgen Stenarson Jorgen Stenarson Jörgen Stenarson Jorgen Stenarson <> Jörgen Stenarson jstenar Jörgen Stenarson jstenar <> Jörgen Stenarson Jörgen Stenarson Juergen Hasch juhasch Juergen Hasch juhasch Julia Evans Julia Evans Kester Tong KesterTong Kyle Kelley Kyle Kelley Kyle Kelley rgbkrk Laurent Dufréchou Laurent Dufréchou Laurent Dufréchou laurent dufrechou <> Laurent Dufréchou laurent.dufrechou <> Laurent Dufréchou Laurent Dufrechou <> Laurent Dufréchou laurent.dufrechou@gmail.com <> Laurent Dufréchou ldufrechou Lorena Pantano Lorena Luis Pedro Coelho Luis Pedro Coelho Marc Molla marcmolla Martín Gaitán Martín Gaitán Matthias Bussonnier Matthias BUSSONNIER Matthias Bussonnier Bussonnier Matthias Matthias Bussonnier Matthias BUSSONNIER Matthias Bussonnier Matthias Bussonnier Michael Droettboom Michael Droettboom Nicholas Bollweg Nicholas Bollweg (Nick) Nicolas Rougier Nikolay Koldunov Nikolay Koldunov Omar Andrés Zapata Mesa Omar Andres Zapata Mesa Omar Andrés Zapata Mesa Omar Andres Zapata Mesa Pankaj Pandey Pankaj Pandey Pascal Schetelat pascal-schetelat Paul Ivanov Paul Ivanov Pauli Virtanen Pauli Virtanen <> Pauli Virtanen Pauli Virtanen Pierre Gerold Pierre Gerold Pietro Berkes Pietro Berkes Piti Ongmongkolkul piti118 Prabhu Ramachandran Prabhu Ramachandran <> Puneeth Chaganti Puneeth Chaganti Robert Kern rkern <> Robert Kern Robert Kern Robert Kern Robert Kern Robert Kern Robert Kern <> Robert Marchman Robert Marchman Satrajit Ghosh Satrajit Ghosh Satrajit Ghosh Satrajit Ghosh Scott Sanderson Scott Sanderson smithj1 smithj1 smithj1 smithj1 Steven Johnson stevenJohnson Steven Silvester blink1073 S. Weber s8weber Stefan van der Walt Stefan van der Walt Silvia Vinyes Silvia Silvia Vinyes silviav12 Sylvain Corlay Sylvain Corlay sylvain.corlay Ted Drain TD22057 Théophile Studer Théophile Studer Thomas Kluyver Thomas Thomas Spura Thomas Spura Timo Paulssen timo vds vds2212 vds vds Ville M. Vainio Ville M. Vainio ville Ville M. Vainio ville Ville M. Vainio vivainio <> Ville M. Vainio Ville M. Vainio Ville M. Vainio Ville M. Vainio Walter Doerwald walter.doerwald <> Walter Doerwald Walter Doerwald <> W. Trevor King W. Trevor King Yoval P. y-p ipython-traitlets-a3e321a/.pre-commit-config.yaml000066400000000000000000000042361461045054400221070ustar00rootroot00000000000000ci: autoupdate_schedule: monthly autoupdate_commit_msg: "chore: update pre-commit hooks" repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-case-conflict - id: check-ast - id: check-docstring-first - id: check-executables-have-shebangs - id: check-added-large-files - id: check-case-conflict - id: check-merge-conflict - id: check-json - id: check-toml - id: check-yaml - id: debug-statements - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/python-jsonschema/check-jsonschema rev: 0.27.4 hooks: - id: check-github-workflows - repo: https://github.com/executablebooks/mdformat rev: 0.7.17 hooks: - id: mdformat additional_dependencies: [mdformat-gfm, mdformat-frontmatter, mdformat-footnote] - repo: https://github.com/pre-commit/mirrors-prettier rev: "v4.0.0-alpha.8" hooks: - id: prettier types_or: [yaml, html, json] - repo: https://github.com/adamchainz/blacken-docs rev: "1.16.0" hooks: - id: blacken-docs additional_dependencies: [black==23.7.0] - repo: https://github.com/codespell-project/codespell rev: "v2.2.6" hooks: - id: codespell args: ["-L", "sur,nd"] - repo: https://github.com/pre-commit/mirrors-mypy rev: "v1.8.0" hooks: - id: mypy files: "^traitlets" stages: [manual] args: ["--install-types", "--non-interactive"] additional_dependencies: ["argcomplete>=3.1"] - repo: https://github.com/pre-commit/pygrep-hooks rev: "v1.10.0" hooks: - id: rst-backticks - id: rst-directive-colons - id: rst-inline-touching-normal - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.2.0 hooks: - id: ruff types_or: [python, jupyter] args: ["--fix", "--show-fixes"] - id: ruff-format types_or: [python, jupyter] - repo: https://github.com/scientific-python/cookie rev: "2024.01.24" hooks: - id: sp-repo-review additional_dependencies: ["repo-review[cli]"] ipython-traitlets-a3e321a/.readthedocs.yml000066400000000000000000000004141461045054400207060ustar00rootroot00000000000000version: 2 sphinx: configuration: docs/source/conf.py formats: - epub - pdf python: install: # install itself with pip install . - method: pip path: . extra_requirements: - docs build: os: ubuntu-22.04 tools: python: "3.11" ipython-traitlets-a3e321a/CHANGELOG.md000066400000000000000000001242241461045054400174370ustar00rootroot00000000000000# Changes in Traitlets ## 5.14.3 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.14.2...5cf34f6c42b6e39aa1e53394443efca3d7329e3b)) ### Bugs fixed - Fix assigning string value to Set [#903](https://github.com/ipython/traitlets/pull/903) ([@azjps](https://github.com/azjps)) ### Maintenance and upkeep improvements - Bump the actions group with 1 update [#899](https://github.com/ipython/traitlets/pull/899) ([@dependabot](https://github.com/dependabot)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2024-03-12&to=2024-04-19&type=c)) [@azjps](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Aazjps+updated%3A2024-03-12..2024-04-19&type=Issues) | [@dependabot](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Adependabot+updated%3A2024-03-12..2024-04-19&type=Issues) ## 5.14.2 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.14.1...2d0fb91f39a71c5528860e23bf9c2138e441b319)) ### Maintenance and upkeep improvements - Update Release Scripts [#900](https://github.com/ipython/traitlets/pull/900) ([@blink1073](https://github.com/blink1073)) - chore: update pre-commit hooks [#897](https://github.com/ipython/traitlets/pull/897) ([@pre-commit-ci](https://github.com/pre-commit-ci)) - Bump the actions group with 1 update [#896](https://github.com/ipython/traitlets/pull/896) ([@dependabot](https://github.com/dependabot)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2024-01-02&to=2024-03-12&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2024-01-02..2024-03-12&type=Issues) | [@dependabot](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Adependabot+updated%3A2024-01-02..2024-03-12&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2024-01-02..2024-03-12&type=Issues) ## 5.14.1 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.14.0...a1108c92013f9da56a9dccb79f7a5453ffe8d1db)) ### Bugs fixed - FIX: map - to _ for environment variable prefix. [#895](https://github.com/ipython/traitlets/pull/895) ([@Carreau](https://github.com/Carreau)) ### Maintenance and upkeep improvements - chore: update pre-commit hooks [#894](https://github.com/ipython/traitlets/pull/894) ([@pre-commit-ci](https://github.com/pre-commit-ci)) - Update ruff config [#893](https://github.com/ipython/traitlets/pull/893) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-11-27&to=2024-01-02&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-11-27..2024-01-02&type=Issues) | [@Carreau](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3ACarreau+updated%3A2023-11-27..2024-01-02&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2023-11-27..2024-01-02&type=Issues) ## 5.14.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.13.0...4d7504601b9db9eb6f31dfc102b9c469c8517496)) ### Enhancements made - Add option to load traitlets values from environment. [#856](https://github.com/ipython/traitlets/pull/856) ([@Carreau](https://github.com/Carreau)) ### Maintenance and upkeep improvements - Update types for mypy 1.7 [#892](https://github.com/ipython/traitlets/pull/892) ([@blink1073](https://github.com/blink1073)) - chore: update pre-commit hooks [#890](https://github.com/ipython/traitlets/pull/890) ([@pre-commit-ci](https://github.com/pre-commit-ci)) - Clean up lint handling [#888](https://github.com/ipython/traitlets/pull/888) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-10-30&to=2023-11-27&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-10-30..2023-11-27&type=Issues) | [@Carreau](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3ACarreau+updated%3A2023-10-30..2023-11-27&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2023-10-30..2023-11-27&type=Issues) ## 5.13.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.12.0...dacbf9b03ebecbd09604ab2fa41e088e3f60b403)) ### Bugs fixed - Use passed-in `info` argument for `TraitType.error()` [#884](https://github.com/ipython/traitlets/pull/884) ([@kylebarron](https://github.com/kylebarron)) ### Maintenance and upkeep improvements - Improve generics handling [#886](https://github.com/ipython/traitlets/pull/886) ([@blink1073](https://github.com/blink1073)) - Finish Strict Typing [#885](https://github.com/ipython/traitlets/pull/885) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-10-25&to=2023-10-30&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-10-25..2023-10-30&type=Issues) | [@kylebarron](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Akylebarron+updated%3A2023-10-25..2023-10-30&type=Issues) ## 5.12.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.11.2...b018581f0acd75844bbd7584e233c3ab3126501b)) ### Enhancements made - Pass \*\*kwds in MetaHasDescriptors __new__ and __init__ [#881](https://github.com/ipython/traitlets/pull/881) ([@fleming79](https://github.com/fleming79)) ### Maintenance and upkeep improvements - Adopt sp-repo-review [#883](https://github.com/ipython/traitlets/pull/883) ([@blink1073](https://github.com/blink1073)) - Cleanup after remove Python 2 support [#882](https://github.com/ipython/traitlets/pull/882) ([@shadchin](https://github.com/shadchin)) - Add more project URLs, trove classifiers [#879](https://github.com/ipython/traitlets/pull/879) ([@bollwyvl](https://github.com/bollwyvl)) ### Documentation improvements - Fix docs version [#880](https://github.com/ipython/traitlets/pull/880) ([@bollwyvl](https://github.com/bollwyvl)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-10-03&to=2023-10-24&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-10-03..2023-10-24&type=Issues) | [@bollwyvl](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Abollwyvl+updated%3A2023-10-03..2023-10-24&type=Issues) | [@fleming79](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Afleming79+updated%3A2023-10-03..2023-10-24&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2023-10-03..2023-10-24&type=Issues) | [@shadchin](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ashadchin+updated%3A2023-10-03..2023-10-24&type=Issues) ## 5.11.2 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.11.1...e238765a0ba28fc68318cff75e852958d5c65c93)) ### Maintenance and upkeep improvements - More typing cleanup [#877](https://github.com/ipython/traitlets/pull/877) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-10-03&to=2023-10-03&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-10-03..2023-10-03&type=Issues) ## 5.11.1 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.11.0...292a699ad1a3a3ece760a8335cae73927cccd711)) ### Maintenance and upkeep improvements - Typing fixups [#875](https://github.com/ipython/traitlets/pull/875) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-10-03&to=2023-10-03&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-10-03..2023-10-03&type=Issues) ## 5.11.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.10.1...24a24508260d501abd6bc8b42b59163c6c07d8c4)) ### Maintenance and upkeep improvements - More Typing Adoption [#873](https://github.com/ipython/traitlets/pull/873) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-09-26&to=2023-10-03&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-09-26..2023-10-03&type=Issues) ## 5.10.1 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.10.0...c0a3afdb2dcb28bd7ade6dd730604df8f3fbfc78)) ### Maintenance and upkeep improvements - Typing upgrades [#868](https://github.com/ipython/traitlets/pull/868) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-09-14&to=2023-09-26&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-09-14..2023-09-26&type=Issues) ## 5.10.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.9.0...6588680dc69be75676ca3835b4061b1784232600)) ### Enhancements made - Added type hints to HasTraits.observe() and friends. (#834 [#834](https://github.com/ipython/traitlets/pull/834) ([@scholer](https://github.com/scholer)) - feat: trait typing [#818](https://github.com/ipython/traitlets/pull/818) ([@maartenbreddels](https://github.com/maartenbreddels)) ### Maintenance and upkeep improvements - Fix mypy deps and support Python 3.8-3.12 [#862](https://github.com/ipython/traitlets/pull/862) ([@blink1073](https://github.com/blink1073)) - Update pytest requirement from \<7.2,>=7.0 to >=7.0,\<7.5 [#861](https://github.com/ipython/traitlets/pull/861) ([@dependabot](https://github.com/dependabot)) - Bump actions/checkout from 3 to 4 [#860](https://github.com/ipython/traitlets/pull/860) ([@dependabot](https://github.com/dependabot)) - Fix typing [#848](https://github.com/ipython/traitlets/pull/848) ([@blink1073](https://github.com/blink1073)) - Update docs config [#843](https://github.com/ipython/traitlets/pull/843) ([@blink1073](https://github.com/blink1073)) - Use local coverage [#842](https://github.com/ipython/traitlets/pull/842) ([@blink1073](https://github.com/blink1073)) - Adjust argcomplete typings [#839](https://github.com/ipython/traitlets/pull/839) ([@blink1073](https://github.com/blink1073)) - Better warnings [#838](https://github.com/ipython/traitlets/pull/838) ([@NickCrews](https://github.com/NickCrews)) - Update typings (#836 [#836](https://github.com/ipython/traitlets/pull/836) ([@blink1073](https://github.com/blink1073)) ### Documentation improvements - rename `MyClass` to `School` [#858](https://github.com/ipython/traitlets/pull/858) ([@metaperl](https://github.com/metaperl)) - Even though returning a value from a validation method is ideal, by no means is `proposal['value']` the only thing that can be returned [#855](https://github.com/ipython/traitlets/pull/855) ([@metaperl](https://github.com/metaperl)) - Document help parameter of TraitType.__init__(). [#847](https://github.com/ipython/traitlets/pull/847) ([@metaperl](https://github.com/metaperl)) ### Other merged PRs - Clean up license (#832)Co-authored-by: pre-commit-ci\[bot\] \<66853113+pre-commit-ci\[bot\]@users.noreply.github.com> [#832](https://github.com/ipython/traitlets/pull/832) ([@dcsaba89](https://github.com/dcsaba89)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-01-30&to=2023-09-14&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-01-30..2023-09-14&type=Issues) | [@dcsaba89](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Adcsaba89+updated%3A2023-01-30..2023-09-14&type=Issues) | [@dependabot](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Adependabot+updated%3A2023-01-30..2023-09-14&type=Issues) | [@maartenbreddels](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Amaartenbreddels+updated%3A2023-01-30..2023-09-14&type=Issues) | [@metaperl](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ametaperl+updated%3A2023-01-30..2023-09-14&type=Issues) | [@NickCrews](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3ANickCrews+updated%3A2023-01-30..2023-09-14&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2023-01-30..2023-09-14&type=Issues) | [@rmorshea](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Armorshea+updated%3A2023-01-30..2023-09-14&type=Issues) | [@saulshanabrook](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Asaulshanabrook+updated%3A2023-01-30..2023-09-14&type=Issues) | [@scholer](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ascholer+updated%3A2023-01-30..2023-09-14&type=Issues) ## 5.9.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.8.1...c11a4d942b08df5c19be88b6cc81dfa8302fef9b)) ### Enhancements made - Polishing argcomplete support [#829](https://github.com/ipython/traitlets/pull/829) ([@azjps](https://github.com/azjps)) ### Maintenance and upkeep improvements - Test that name and description can be set via constructor. [#826](https://github.com/ipython/traitlets/pull/826) ([@Carreau](https://github.com/Carreau)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2023-01-09&to=2023-01-30&type=c)) [@azjps](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Aazjps+updated%3A2023-01-09..2023-01-30&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2023-01-09..2023-01-30&type=Issues) | [@Carreau](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3ACarreau+updated%3A2023-01-09..2023-01-30&type=Issues) ## 5.8.1 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.8.0...18814204c7e7987851cc1836a36863b4fab60165)) ### Bugs fixed - fix: mro_trait can be unbound when the class is not in mro [#824](https://github.com/ipython/traitlets/pull/824) ([@maartenbreddels](https://github.com/maartenbreddels)) ### Maintenance and upkeep improvements ### Documentation improvements - Add more api docs [#821](https://github.com/ipython/traitlets/pull/821) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2022-12-19&to=2023-01-09&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2022-12-19..2023-01-09&type=Issues) | [@maartenbreddels](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Amaartenbreddels+updated%3A2022-12-19..2023-01-09&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2022-12-19..2023-01-09&type=Issues) | [@rmorshea](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Armorshea+updated%3A2022-12-19..2023-01-09&type=Issues) ## 5.8.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.7.1...47e652f96aff54d1aa3b19337c9c8d80fe0fd4c4)) ### Enhancements made -Shell command-line tab-completion via `argcomplete` [#811](https://github.com/ipython/traitlets/pull/811) ([@azjps](https://github.com/azjps)) - Define `trait.__doc__` = `trait.help` for better API Docs [#816](https://github.com/ipython/traitlets/pull/816) ([@minrk](https://github.com/minrk)) ### Maintenance and upkeep improvements - Expose more attributes for typing [#817](https://github.com/ipython/traitlets/pull/817) ([@blink1073](https://github.com/blink1073)) - Fix lint [#814](https://github.com/ipython/traitlets/pull/814) ([@blink1073](https://github.com/blink1073)) ### Documentation improvements - Additional `Application` examples and docs [#811](https://github.com/ipython/traitlets/pull/811) ([@azjps](https://github.com/azjps)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2022-12-12&to=2022-12-19&type=c)) [@azjps](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Aazjps+updated%3A2022-12-12..2022-12-19&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2022-12-12..2022-12-19&type=Issues) | [@minrk](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Aminrk+updated%3A2022-12-12..2022-12-19&type=Issues) ## 5.7.1 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.7.0...aa0d38bf02d34a6df788477da30eac6e58ffbda5)) ### Bugs fixed - fix: some descriptors raise AttributeError [#812](https://github.com/ipython/traitlets/pull/812) ([@maartenbreddels](https://github.com/maartenbreddels)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2022-12-08&to=2022-12-12&type=c)) [@maartenbreddels](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Amaartenbreddels+updated%3A2022-12-08..2022-12-12&type=Issues) ## 5.7.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/v5.6.0...f07afea52cf6314bc20571c52409ff6cb115a709)) ### Enhancements made - Performance: decrease runtime overhead for constructing HasTraits (up to 20x faster) [#777](https://github.com/ipython/traitlets/pull/777) ([@maartenbreddels](https://github.com/maartenbreddels)) ### Maintenance and upkeep improvements - Minor fixes for Application.aliases [#810](https://github.com/ipython/traitlets/pull/810) ([@azjps](https://github.com/azjps)) - Adopt ruff and address lint [#809](https://github.com/ipython/traitlets/pull/809) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2022-11-29&to=2022-12-08&type=c)) [@azjps](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Aazjps+updated%3A2022-11-29..2022-12-08&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2022-11-29..2022-12-08&type=Issues) | [@maartenbreddels](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Amaartenbreddels+updated%3A2022-11-29..2022-12-08&type=Issues) | [@naterush](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Anaterush+updated%3A2022-11-29..2022-12-08&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2022-11-29..2022-12-08&type=Issues) ## 5.6.0 ([Full Changelog](https://github.com/ipython/traitlets/compare/5.5.0...2c5188a3562f03c0703315b21df41ca7ace23dd3)) ### Maintenance and upkeep improvements - Adopt jupyter releaser [#806](https://github.com/ipython/traitlets/pull/806) ([@blink1073](https://github.com/blink1073)) - Use base setup dependency type [#805](https://github.com/ipython/traitlets/pull/805) ([@blink1073](https://github.com/blink1073)) - More CI Cleanup [#803](https://github.com/ipython/traitlets/pull/803) ([@blink1073](https://github.com/blink1073)) - More maintenance cleanup [#802](https://github.com/ipython/traitlets/pull/802) ([@blink1073](https://github.com/blink1073)) - Add project description [#801](https://github.com/ipython/traitlets/pull/801) ([@blink1073](https://github.com/blink1073)) - Bump actions/setup-python from 2 to 4 [#798](https://github.com/ipython/traitlets/pull/798) ([@dependabot](https://github.com/dependabot)) - Bump actions/checkout from 2 to 3 [#797](https://github.com/ipython/traitlets/pull/797) ([@dependabot](https://github.com/dependabot)) - Bump pre-commit/action from 2.0.0 to 3.0.0 [#796](https://github.com/ipython/traitlets/pull/796) ([@dependabot](https://github.com/dependabot)) - Bump actions/upload-artifact from 2 to 3 [#795](https://github.com/ipython/traitlets/pull/795) ([@dependabot](https://github.com/dependabot)) - Add dependabot [#794](https://github.com/ipython/traitlets/pull/794) ([@blink1073](https://github.com/blink1073)) - Add more typings [#791](https://github.com/ipython/traitlets/pull/791) ([@blink1073](https://github.com/blink1073)) - Format changelog [#789](https://github.com/ipython/traitlets/pull/789) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/ipython/traitlets/graphs/contributors?from=2022-10-18&to=2022-11-29&type=c)) [@blink1073](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Ablink1073+updated%3A2022-10-18..2022-11-29&type=Issues) | [@dependabot](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Adependabot+updated%3A2022-10-18..2022-11-29&type=Issues) | [@maartenbreddels](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Amaartenbreddels+updated%3A2022-10-18..2022-11-29&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Apre-commit-ci+updated%3A2022-10-18..2022-11-29&type=Issues) | [@rmorshea](https://github.com/search?q=repo%3Aipython%2Ftraitlets+involves%3Armorshea+updated%3A2022-10-18..2022-11-29&type=Issues) ## 5.5.0 - Clean up application typing - Update tests and docs to use non-deprecated functions - Clean up version handling - Prep for jupyter releaser - Format the changelog ## 5.4.0 - Fix version_info - Make generated config files more lintable - Fix union trait from string - Add security.md, and tidelift badge ## 5.3.0 - Fix traitlet name in docstring - Re-support multiple-alias key for ArgParseConfigLoader ## 5.2.2 - Make `traitlets.__all__` explicit and validate in test. - Fix `KeyError` in `Application.get_default_logging_config`. ## 5.2.1 - logging: Don't attempt to close handlers unless they have been opened. Fixes `ValueError: Unable to configure formatter 'console'` traceback. ## 5.2.0 Traitlets 5.2 brings a couple of updates and changes to traitlets, and is recommended for all users. What follows is a non-exhaustive list of changes: - Application: add logging_config trait. - Disambiguate the use of the term value in the example. - Add mypy typing support. - DOC: Add log example. - Internal cleanup: linters, autoformatters, CI. ## 5.1.1 5.1.1 fixes compatibility issues with Python 3.10 (rc2). ## 5.1.0 Traitlets 5.1 brings a couple of updates and changes to traitlets, and is recommended for all users. What follow is a non-exhaustive list of changes: - Removal of the `ipython_genutils` dependency, this should remove any direct and indirect reliance on `nose` and prepare traitlets 5.1 for Python 3.10 and above compatibility, some test suite changes also accommodate Python 3.10 changes. If you package traitlets downstream, make sure to remove this dependency. - Removal of `ipython_genutils` may have change the default encoding detected for the command line argument parsing when not utf-8. We expect this to affect a small portion of older windows version. If you encounter issue let us know. - Stop recommendation of `CUnicode` in some circumstances as it's deprecated. - Our test suite is now using GitHub action instead of travis CI. If you are packaging downstream using the git repository, you may have to exclude the `.github` folder now, and can remove exclusion of - It fixes a parsing issue for list of one single element on the CLI. - We reserve the right to remove official support for Python 3.7 in subsequent minor revisions. ## 5.0.5 - Support deprecated literals for sets, tuples on the command-line: `nbconvert --TagRemovePreprocessor.remove_cell_tags='{"tag"}'` - Fix `from_string_list` for Tuples in general - Fix support for `List(default_value=None, allow_none=True)` and other Container traits - Fix help output for nested aliases and tuple traits ## 5.0.4 - Support deprecated use of byte-literals for bytes on the command-line: `ipython kernel --Session.key="b'abc'"`. The `b` prefix is no longer needed in traitlets 5.0, but is supported for backward-compatibility - Improve output of configuration errors, especially when help output would make it hard to find the helpful error message ## 5.0.3 - Fix regression in handling `--opt=None` on the CLI for configurable traits with `allow_none=True` ## 5.0.2 - Fix casting bytes to unicode ## 5.0.0 (This is an in-progress changelog, please let us know if something is missing/or could be phrased better) Traitlets 5.0 is a new version of traitlets that accumulate changes over a period of more close to four years; A number of internal refactoring made the internal code structure cleaner and simpler, and greatly improved the diagnostic error messages as well has help and documentation generation. We expect no code change needed for any consumer of the Python API (ipywidgets, and alike), though CLI argument parsing have seen a complete rewrite, so if you have an application that does use the parsing logic of traitlets you may see changes in behavior, and now have access to more features. There was also a cleanup of what was considered a part of the public API, certain previously exposed utility functions and types are no longer available. Please see an exhaustive list below. ::: seealso `commandline` docs for details about command-line parsing and the changes in 5.0. Please [let us know](https://github.com/ipython/traitlets/issues) if you find issues with the new command-line parsing changes. ::: We also want to thanks in particular a number of regular contributor through the years that have patiently waited for their often large contribution to be available, if **rough** order of number of contribution: - Ryan Morshead - @rmorshea - For serving as a maintainer of the 4.x branch and providing a number of bug fix through the years. - Kostis Anagnostopoulos - @ankostis - Who push a major refactor of the CLI paring, as well as many help-generating function. - Benjamin Ragan-Kelley -- @minrk -- for reviewing and help fixing edge case in most of the above - Matthias Bussonnier -- @carreau - Sylvain Corlay - Francisco de la Peña - Martin Renou - Yves Delley - Thomas Kluyver - hristian Clauss - maartenbreddels - Aliaksei Urbanski - Kevin Bates - David Brochart As well as many of the passer-by, and less frequent contributors: - Tim Paine - Jake VanderPlas - Frédéric Chapoton - Dan Allan - Adam Chainz - William Krinsman - Travis DePrato - Todd - Thomas Aarholt - Lumir Balhar - Leonardo Uieda - Leo Gallucci - Kyle Kelley - Jeroen Demeyer - Jason Grout - Hans Moritz Günther - FredInChina - Conner Cowling - Carol Willing - Albert Zeyer Major changes are: - Removal of Python 2 support, - Removal of Python 3.0-3.6 support - we now follow NEP 29, and are thus Python 3.7+ only. - remove `six` as a dependency - remove `funcsig` as a dependency. - no longer exposes the following functions / types: - ClassTypes - DefaultHandler - EventHandler - ForwardDeclaredMixin - ObserveHandler - SequenceTypes - ValidateHandler - add_article - class_of - getargspec - getmembers - is_trait - isidentifier - repr_type Here is a list of most Pull requests that went into 5.0 and a short description. - [#362](https://github.com/ipython/traitlets/pull/362) , [#361](https://github.com/ipython/traitlets/pull/361) introduces: - help for aliases , aliases dict values can now be a tuple with ('target', 'help string') - subcommands can now be arbitrary callable and do not need to be subclass of `Application` - [#306](https://github.com/ipython/traitlets/pull/306) Add compatibility with the `trait` package for Dictionaries and add the `key_trait` parameters allowing to restrict the type of the key of a mapping. The constructor parameters `trait` and `traits` are renamed to `value_trait` and `per_key_traits`. - [#319](https://github.com/ipython/traitlets/pull/319) adds ability to introduce both shot and long version of aliases, allowing for short and long options `-` and `--`. - [#322](https://github.com/ipython/traitlets/pull/322) rewrite command line argument parsing to use argparse, and allow more flexibility in assigning literals without quoting. - [#332](https://github.com/ipython/traitlets/pull/332) Make it easier to redefined default values of parents classes. - [#333](https://github.com/ipython/traitlets/pull/333) introduces a `Callable` trait. - [#340](https://github.com/ipython/traitlets/pull/340) Old way of passing containers in the command line is now deprecated, and will emit warning on the command line. - [#341](https://github.com/ipython/traitlets/pull/341) introduces `--Application.show_config=True` which will make by default any application show it configuration, all the files it loaded configuration from, and exit. - [#349](https://github.com/ipython/traitlets/pull/349) unify ability to declare default values across traitlets with a singular method `default` method, and [#525](https://github.com/ipython/traitlets/pull/525) adds a warning that `Undefined`is deprecated. - [#355](https://github.com/ipython/traitlets/pull/355) fix a random ordering issues in command lines flags. - [#356](https://github.com/ipython/traitlets/pull/356) allow both `self` and `cls` in `__new__` method for genericity. - [#360](https://github.com/ipython/traitlets/pull/360) Simplify overwriting and extending the command line argument parser. - [#371](https://github.com/ipython/traitlets/pull/371) introduces a `FuzzyEnum` trait that allow case insensitive and unique prefix matching. - [#384](https://github.com/ipython/traitlets/pull/384) Ass a `trait_values` method to extra a mapping of trait and their values. - [#393](https://github.com/ipython/traitlets/pull/393) `Link` now have a transform attribute (taking two functions inverse of each other), that affect how a value is mapped between a source and a target. - [#394](https://github.com/ipython/traitlets/pull/394) `Link` now have a `link` method to re-link object after `unlink` has been called. - [#402](https://github.com/ipython/traitlets/pull/402) rewrite handling of error messages for nested traits. - [#405](https://github.com/ipython/traitlets/pull/405) all function that use to print help now have an equivalent that yields the help lines. - [#413](https://github.com/ipython/traitlets/pull/413) traits now have a method `trait_has_value`, returning a boolean to know if a value has been assigned to a trait (excluding the default), in order to help avoiding circular validation at initialisation. - [#416](https://github.com/ipython/traitlets/pull/416) Explicitly export traitlets in `__all__` to avoid exposing implementation details. - [#438](https://github.com/ipython/traitlets/pull/438) introduces `.info_rst()` to let traitlets overwrite the automatically generated rst documentation. - [#458](https://github.com/ipython/traitlets/pull/458) Add a sphinx extension to automatically document options of `Application` instance in projects using traitlets. - [#509](https://github.com/ipython/traitlets/pull/509) remove all base `except:` meaning traitlets will not catch a number of `BaseException` s anymore. - [#515](https://github.com/ipython/traitlets/pull/515) Add a class decorator to enable tab completion of keyword arguments in signature. - [#516](https://github.com/ipython/traitlets/pull/516) a `Sentinel` Traitlets was made public by mistake and is now deprecated. - [#517](https://github.com/ipython/traitlets/pull/517) use parent Logger within logggin configurable when possible. - [#522](https://github.com/ipython/traitlets/pull/522) Make loading config files idempotent and expose the list of loaded config files for long running services. ### API changes This list is auto-generated by `frappuccino`, comparing with traitlets 4.3.3 API and edited for shortness: ``` The following items are new: + traitlets.Sentinel + traitlets.config.application.Application.emit_alias_help(self) + traitlets.config.application.Application.emit_description(self) + traitlets.config.application.Application.emit_examples(self) + traitlets.config.application.Application.emit_flag_help(self) + traitlets.config.application.Application.emit_help(self, classes=False) + traitlets.config.application.Application.emit_help_epilogue(self, classes) + traitlets.config.application.Application.emit_options_help(self) + traitlets.config.application.Application.emit_subcommands_help(self) + traitlets.config.application.Application.start_show_config(self) + traitlets.config.application.default_aliases + traitlets.config.application.default_flags + traitlets.config.default_aliases + traitlets.config.default_flags + traitlets.config.loader.DeferredConfig + traitlets.config.loader.DeferredConfig.get_value(self, trait) + traitlets.config.loader.DeferredConfigList + traitlets.config.loader.DeferredConfigList.get_value(self, trait) + traitlets.config.loader.DeferredConfigString + traitlets.config.loader.DeferredConfigString.get_value(self, trait) + traitlets.config.loader.LazyConfigValue.merge_into(self, other) + traitlets.config.loader.Undefined + traitlets.config.loader.class_trait_opt_pattern + traitlets.traitlets.BaseDescriptor.subclass_init(self, cls) + traitlets.traitlets.Bool.from_string(self, s) + traitlets.traitlets.Bytes.from_string(self, s) + traitlets.traitlets.Callable + traitlets.traitlets.Callable.validate(self, obj, value) + traitlets.traitlets.CaselessStrEnum.info(self) + traitlets.traitlets.CaselessStrEnum.info_rst(self) + traitlets.traitlets.Complex.from_string(self, s) + traitlets.traitlets.Container.from_string(self, s) + traitlets.traitlets.Container.from_string_list(self, s_list) + traitlets.traitlets.Container.item_from_string(self, s) + traitlets.traitlets.Dict.from_string(self, s) + traitlets.traitlets.Dict.from_string_list(self, s_list) + traitlets.traitlets.Dict.item_from_string(self, s) + traitlets.traitlets.Enum.from_string(self, s) + traitlets.traitlets.Enum.info_rst(self) + traitlets.traitlets.Float.from_string(self, s) + traitlets.traitlets.FuzzyEnum + traitlets.traitlets.FuzzyEnum.info(self) + traitlets.traitlets.FuzzyEnum.info_rst(self) + traitlets.traitlets.FuzzyEnum.validate(self, obj, value) + traitlets.traitlets.HasTraits.trait_defaults(self, *names, **metadata) + traitlets.traitlets.HasTraits.trait_has_value(self, name) + traitlets.traitlets.HasTraits.trait_values(self, **metadata) + traitlets.traitlets.Instance.from_string(self, s) + traitlets.traitlets.Int.from_string(self, s) + traitlets.traitlets.ObjectName.from_string(self, s) + traitlets.traitlets.TCPAddress.from_string(self, s) + traitlets.traitlets.TraitType.default(self, obj='None') + traitlets.traitlets.TraitType.from_string(self, s) + traitlets.traitlets.Unicode.from_string(self, s) + traitlets.traitlets.Union.default(self, obj='None') + traitlets.traitlets.UseEnum.info_rst(self) + traitlets.traitlets.directional_link.link(self) + traitlets.traitlets.link.link(self) + traitlets.utils.cast_unicode(s, encoding='None') + traitlets.utils.decorators + traitlets.utils.decorators.Undefined + traitlets.utils.decorators.signature_has_traits(cls) + traitlets.utils.descriptions + traitlets.utils.descriptions.add_article(name, definite=False, capital=False) + traitlets.utils.descriptions.class_of(value) + traitlets.utils.descriptions.describe(article, value, name='None', verbose=False, capital=False) + traitlets.utils.descriptions.repr_type(obj) The following items have been removed (or moved to superclass): - traitlets.ClassTypes - traitlets.SequenceTypes - traitlets.config.absolute_import - traitlets.config.application.print_function - traitlets.config.configurable.absolute_import - traitlets.config.configurable.print_function - traitlets.config.loader.KeyValueConfigLoader.clear - traitlets.config.loader.KeyValueConfigLoader.load_config - traitlets.config.loader.flag_pattern - traitlets.config.loader.kv_pattern - traitlets.config.print_function - traitlets.traitlets.ClassBasedTraitType.error - traitlets.traitlets.Container.element_error - traitlets.traitlets.List.validate - traitlets.traitlets.TraitType.instance_init - traitlets.traitlets.Union.make_dynamic_default - traitlets.traitlets.add_article - traitlets.traitlets.class_of - traitlets.traitlets.repr_type - traitlets.utils.getargspec.PY3 - traitlets.utils.importstring.string_types - traitlets.warn_explicit The following signatures differ between versions: - traitlets.config.application.Application.generate_config_file(self) + traitlets.config.application.Application.generate_config_file(self, classes='None') - traitlets.config.application.catch_config_error(method, app, *args, **kwargs) + traitlets.config.application.catch_config_error(method) - traitlets.config.configurable.Configurable.class_config_section() + traitlets.config.configurable.Configurable.class_config_section(classes='None') - traitlets.config.configurable.Configurable.class_get_trait_help(trait, inst='None') + traitlets.config.configurable.Configurable.class_get_trait_help(trait, inst='None', helptext='None') - traitlets.config.loader.ArgParseConfigLoader.load_config(self, argv='None', aliases='None', flags='None') + traitlets.config.loader.ArgParseConfigLoader.load_config(self, argv='None', aliases='None', flags='', classes='None') - traitlets.traitlets.Dict.element_error(self, obj, element, validator) + traitlets.traitlets.Dict.element_error(self, obj, element, validator, side='Values') - traitlets.traitlets.HasDescriptors.setup_instance(self, *args, **kwargs) + traitlets.traitlets.HasDescriptors.setup_instance(*args, **kwargs) - traitlets.traitlets.HasTraits.setup_instance(self, *args, **kwargs) + traitlets.traitlets.HasTraits.setup_instance(*args, **kwargs) - traitlets.traitlets.TraitType.error(self, obj, value) + traitlets.traitlets.TraitType.error(self, obj, value, error='None', info='None') ``` ## 4.3 ## 4.3.2 [4.3.2 on GitHub](https://github.com/ipython/traitlets/milestones/4.3.2) 4.3.2 is a tiny release, relaxing some of the deprecations introduced in 4.3.1: - using `_traitname_default()` without the `@default` decorator is no longer deprecated. - Passing `config=True` in traitlets constructors is no longer deprecated. ## 4.3.1 [4.3.1 on GitHub](https://github.com/ipython/traitlets/milestones/4.3.1) - Compatibility fix for Python 3.6a1 - Fix bug in Application.classes getting extra entries when multiple Applications are instantiated in the same process. ## 4.3.0 [4.3.0 on GitHub](https://github.com/ipython/traitlets/milestones/4.3) - Improve the generated config file output. - Allow TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR env to override `Application.raise_config_file_errors`, so that config file errors can result in exiting immediately. - Avoid using root logger. If no application logger is registered, the `'traitlets'` logger will be used instead of the root logger. - Change/Validation arguments are now Bunch objects, allowing attribute-access, in addition to dictionary access. - Reduce number of common deprecation messages in certain cases. - Ensure command-line options always have higher priority than config files. - Add bounds on numeric traits. - Improves various error messages. ## 4.2 ## 4.2.2 - 2016-07-01 [4.2.2 on GitHub](https://github.com/ipython/traitlets/milestones/4.2.2) Partially revert a change in 4.1 that prevented IPython's command-line options from taking priority over config files. ## 4.2.1 - 2016-03-14 [4.2.1 on GitHub](https://github.com/ipython/traitlets/milestones/4.2.1) Demotes warning about unused arguments in `HasTraits.__init__` introduced in 4.2.0 to DeprecationWarning. ## 4.2.0 - 2016-03-14 [4.2 on GitHub](https://github.com/ipython/traitlets/milestones/4.2) - `JSONFileConfigLoader` can be used as a context manager for updating configuration. - If a value in config does not map onto a configurable trait, a message is displayed that the value will have no effect. - Unused arguments are passed to `super()` in `HasTraits.__init__`, improving support for multiple inheritance. - Various bugfixes and improvements in the new API introduced in 4.1. - Application subclasses may specify `raise_config_file_errors = True` to exit on failure to load config files, instead of the default of logging the failures. ## 4.1 - 2016-01-15 [4.1 on GitHub](https://github.com/ipython/traitlets/milestones/4.1) Traitlets 4.1 introduces a totally new decorator-based API for configuring traitlets. Highlights: - Decorators are used, rather than magic method names, for registering trait-related methods. See `using_traitlets` and `migration` for more info. - Deprecate `Trait(config=True)` in favor of `Trait().tag(config=True)`. In general, metadata is added via `tag` instead of the constructor. Other changes: - Trait attributes initialized with `read_only=True` can only be set with the `set_trait` method. Attempts to directly modify a read-only trait attribute raises a `TraitError`. - The directional link now takes an optional `transform` attribute allowing the modification of the value. - Various fixes and improvements to config-file generation (fixed ordering, Undefined showing up, etc.) - Warn on unrecognized traits that aren't configurable, to avoid silently ignoring mistyped config. ## 4.0 - 2015-06-19 [4.0 on GitHub](https://github.com/ipython/traitlets/milestones/4.0) First release of traitlets as a standalone package. ipython-traitlets-a3e321a/CHANGES.txt000066400000000000000000000000621461045054400174300ustar00rootroot00000000000000The changes are at "./docs/source/changelog.rst". ipython-traitlets-a3e321a/CONTRIBUTING.md000066400000000000000000000001741461045054400200540ustar00rootroot00000000000000# Contributing We follow the [IPython Contributing Guide](https://github.com/ipython/ipython/blob/master/CONTRIBUTING.md). ipython-traitlets-a3e321a/LICENSE000066400000000000000000000030001461045054400166170ustar00rootroot00000000000000BSD 3-Clause License - Copyright (c) 2001-, IPython Development Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ipython-traitlets-a3e321a/README.md000066400000000000000000000164761461045054400171160ustar00rootroot00000000000000# Traitlets [![Tests](https://github.com/ipython/traitlets/actions/workflows/tests.yml/badge.svg)](https://github.com/ipython/traitlets/actions/workflows/tests.yml) [![Documentation Status](https://readthedocs.org/projects/traitlets/badge/?version=latest)](https://traitlets.readthedocs.io/en/latest/?badge=latest) [![Tidelift](https://tidelift.com/subscription/pkg/pypi-traitlets)](https://tidelift.com/badges/package/pypi/traitlets) | | | | ------------- | ------------------------------------ | | **home** | https://github.com/ipython/traitlets | | **pypi-repo** | https://pypi.org/project/traitlets/ | | **docs** | https://traitlets.readthedocs.io/ | | **license** | Modified BSD License | Traitlets is a pure Python library enabling: - the enforcement of strong typing for attributes of Python objects (typed attributes are called _"traits"_); - dynamically calculated default values; - automatic validation and coercion of trait attributes when attempting a change; - registering for receiving notifications when trait values change; - reading configuring values from files or from command line arguments - a distinct layer on top of traitlets, so you may use traitlets without the configuration machinery. Its implementation relies on the [descriptor](https://docs.python.org/howto/descriptor.html) pattern, and it is a lightweight pure-python alternative of the [_traits_ library](https://docs.enthought.com/traits/). Traitlets powers the configuration system of IPython and Jupyter and the declarative API of IPython interactive widgets. ## Installation For a local installation, make sure you have [pip installed](https://pip.pypa.io/en/stable/installing/) and run: ```bash pip install traitlets ``` For a **development installation**, clone this repository, change into the `traitlets` root directory, and run pip: ```bash git clone https://github.com/ipython/traitlets.git cd traitlets pip install -e . ``` ## Running the tests ```bash pip install "traitlets[test]" py.test traitlets ``` ## Code Styling `traitlets` has adopted automatic code formatting so you shouldn't need to worry too much about your code style. As long as your code is valid, the pre-commit hook should take care of how it should look. To install `pre-commit` locally, run the following:: ``` pip install pre-commit pre-commit install ``` You can invoke the pre-commit hook by hand at any time with:: ``` pre-commit run ``` which should run any autoformatting on your code and tell you about any errors it couldn't fix automatically. You may also install [black integration](https://github.com/psf/black#editor-integration) into your text editor to format code automatically. If you have already committed files before setting up the pre-commit hook with `pre-commit install`, you can fix everything up using `pre-commit run --all-files`. You need to make the fixing commit yourself after that. Some of the hooks only run on CI by default, but you can invoke them by running with the `--hook-stage manual` argument. ## Usage Any class with trait attributes must inherit from `HasTraits`. For the list of available trait types and their properties, see the [Trait Types](https://traitlets.readthedocs.io/en/latest/trait_types.html) section of the documentation. ### Dynamic default values To calculate a default value dynamically, decorate a method of your class with `@default({traitname})`. This method will be called on the instance, and should return the default value. In this example, the `_username_default` method is decorated with `@default('username')`: ```Python import getpass from traitlets import HasTraits, Unicode, default class Identity(HasTraits): username = Unicode() @default('username') def _username_default(self): return getpass.getuser() ``` ### Callbacks when a trait attribute changes When a trait changes, an application can follow this trait change with additional actions. To do something when a trait attribute is changed, decorate a method with [`traitlets.observe()`](https://traitlets.readthedocs.io/en/latest/api.html?highlight=observe#traitlets.observe). The method will be called with a single argument, a dictionary which contains an owner, new value, old value, name of the changed trait, and the event type. In this example, the `_num_changed` method is decorated with `` @observe(`num`) ``: ```Python from traitlets import HasTraits, Integer, observe class TraitletsExample(HasTraits): num = Integer(5, help="a number").tag(config=True) @observe('num') def _num_changed(self, change): print("{name} changed from {old} to {new}".format(**change)) ``` and is passed the following dictionary when called: ```Python { 'owner': object, # The HasTraits instance 'new': 6, # The new value 'old': 5, # The old value 'name': "foo", # The name of the changed trait 'type': 'change', # The event type of the notification, usually 'change' } ``` ### Validation and coercion Each trait type (`Int`, `Unicode`, `Dict` etc.) may have its own validation or coercion logic. In addition, we can register custom cross-validators that may depend on the state of other attributes. For example: ```Python from traitlets import HasTraits, TraitError, Int, Bool, validate class Parity(HasTraits): value = Int() parity = Int() @validate('value') def _valid_value(self, proposal): if proposal['value'] % 2 != self.parity: raise TraitError('value and parity should be consistent') return proposal['value'] @validate('parity') def _valid_parity(self, proposal): parity = proposal['value'] if parity not in [0, 1]: raise TraitError('parity should be 0 or 1') if self.value % 2 != parity: raise TraitError('value and parity should be consistent') return proposal['value'] parity_check = Parity(value=2) # Changing required parity and value together while holding cross validation with parity_check.hold_trait_notifications(): parity_check.value = 1 parity_check.parity = 1 ``` However, we **recommend** that custom cross-validators don't modify the state of the HasTraits instance. ## About the IPython Development Team The IPython Development Team is the set of all contributors to the IPython project. This includes all of the IPython subprojects. The core team that coordinates development on GitHub can be found here: https://github.com/jupyter/. ## Our Copyright Policy IPython uses a shared copyright model. Each contributor maintains copyright over their contributions to IPython. But, it is important to note that these contributions are typically only changes to the repositories. Thus, the IPython source code, in its entirety is not the copyright of any single person or institution. Instead, it is the collective copyright of the entire IPython Development Team. If individual contributors want to maintain a record of what changes/contributions they have specific copyright on, they should indicate their copyright in the commit message of the change, when they commit the change to one of the IPython repositories. With this in mind, the following banner should be used in any source code file to indicate the copyright and license terms: ``` # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. ``` ipython-traitlets-a3e321a/RELEASE.md000066400000000000000000000020311461045054400172170ustar00rootroot00000000000000# Making a Pytest-Jupyter Release ## Using `jupyter_releaser` The recommended way to make a release is to use [`jupyter_releaser`](https://jupyter-releaser.readthedocs.io/en/latest/get_started/making_release_from_repo.html). Note that we must use manual versions since Jupyter Releaser does not yet support "next" or "patch" when dev versions are used. ## Manual Release To create a manual release, perform the following steps: ### Set up ```bash pip install hatch twine build git pull origin $(git branch --show-current) git clean -dffx ``` ### Update the version and apply the tag ```bash echo "Enter new version" read new_version hatch version ${new_version} git tag -a ${new_version} -m "Release ${new_version}" ``` ### Build the artifacts ```bash rm -rf dist python -m build . ``` ### Update the version back to dev ```bash echo "Enter dev version" read dev_version hatch version ${dev_version} git push origin $(git branch --show-current) ``` ### Publish the artifacts to pypi ```bash twine check dist/* twine upload dist/* ``` ipython-traitlets-a3e321a/SECURITY.md000066400000000000000000000005441461045054400174150ustar00rootroot00000000000000# Security Policy ## Reporting a Vulnerability All IPython and Jupyter security are handled via security@ipython.org. You can find more information on the Jupyter website. https://jupyter.org/security ## Tidelift We are also lifting IPython via Tidelift, you can also report security concern via the [tidelift platform](https://tidelift.com/security). ipython-traitlets-a3e321a/docs/000077500000000000000000000000001461045054400165515ustar00rootroot00000000000000ipython-traitlets-a3e321a/docs/Makefile000066400000000000000000000164311461045054400202160ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext api default: html help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/traitlets.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/traitlets.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/traitlets" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/traitlets" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." ipython-traitlets-a3e321a/docs/make.bat000066400000000000000000000161331461045054400201620ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source set I18NSPHINXOPTS=%SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\traitlets.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\traitlets.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end ipython-traitlets-a3e321a/docs/readme-docs.md000066400000000000000000000025631461045054400212640ustar00rootroot00000000000000# Documenting traitlets [Documentation for `traitlets`](https://traitlets.readthedocs.io/en/latest/) is hosted on ReadTheDocs. ## Build documentation locally With [`hatch`](https://hatch.pypa.io/), one can build environments, docs, and serve it in one command: ``` pip install hatch hatch run docs:build ``` #### Build documentation manually Otherwise to build docs manually, ``` cd docs ``` Create virtual environment (and install relevant dependencies): ``` virtualenv traitlets_docs -p python3 pip install -r traitlets[docs] ``` The virtualenv should have been automatically activated. If not: ``` source activate ``` ##### Build documentation using: - Makefile for Linux and OS X: ``` make html ``` - make.bat for Windows: ``` make.bat html ``` ##### Display the documentation locally - Navigate to `build/html/index.html` in your browser. - Or alternatively you may run a local server to display the docs. In Python 3: ``` python -m http.server 8000 ``` In your browser, go to `http://localhost:8000`. ## Developing Documentation [Jupyter documentation guide](https://jupyter.readthedocs.io/en/latest/contrib_docs/index.html) ## Helpful files and directories - `source/conf.py` - Sphinx build configuration file - `source` directory - source for documentation - `source/index.rst` - Main landing page of the Sphinx documentation ipython-traitlets-a3e321a/docs/source/000077500000000000000000000000001461045054400200515ustar00rootroot00000000000000ipython-traitlets-a3e321a/docs/source/api.rst000066400000000000000000000066131461045054400213620ustar00rootroot00000000000000Traitlets API reference ======================= .. currentmodule:: traitlets Any class with trait attributes must inherit from :class:`HasTraits`. .. autoclass:: HasTraits .. automethod:: has_trait .. automethod:: trait_has_value .. automethod:: trait_names .. automethod:: class_trait_names .. automethod:: traits .. automethod:: class_traits .. automethod:: trait_metadata .. automethod:: add_traits You then declare the trait attributes on the class like this:: from traitlets import HasTraits, Int, Unicode class Requester(HasTraits): url = Unicode() timeout = Int(30) # 30 will be the default value For the available trait types and the arguments you can give them, see :doc:`trait_types`. Dynamic default values ---------------------- .. autofunction:: default To calculate a default value dynamically, decorate a method of your class with ``@default({traitname})``. This method will be called on the instance, and should return the default value. For example:: import getpass class Identity(HasTraits): username = Unicode() @default('username') def _username_default(self): return getpass.getuser() Callbacks when trait attributes change -------------------------------------- .. autofunction:: observe To do something when a trait attribute is changed, decorate a method with :func:`traitlets.observe`. The method will be called with a single argument, a dictionary of the form:: { 'owner': object, # The HasTraits instance 'new': 6, # The new value 'old': 5, # The old value 'name': "foo", # The name of the changed trait 'type': 'change', # The event type of the notification, usually 'change' } For example:: from traitlets import HasTraits, Integer, observe class TraitletsExample(HasTraits): num = Integer(5, help="a number").tag(config=True) @observe('num') def _num_changed(self, change): print("{name} changed from {old} to {new}".format(**change)) .. versionchanged:: 4.1 The ``_{trait}_changed`` magic method-name approach is deprecated. You can also add callbacks to a trait dynamically: .. automethod:: HasTraits.observe .. note:: If a trait attribute with a dynamic default value has another value set before it is used, the default will not be calculated. Any callbacks on that trait will will fire, and *old_value* will be ``None``. Validating proposed changes --------------------------- .. autofunction:: validate Validator methods can be used to enforce certain aspects of a property. These are called on proposed changes, and can raise a TraitError if the change should be rejected, or coerce the value if it should be accepted with some modification. This can be useful for things such as ensuring a path string is always absolute, or check if it points to an existing directory. For example:: from traitlets import HasTraits, Unicode, validate, TraitError class TraitletsExample(HasTraits): path = Unicode('', help="a path") @validate('path') def _check_prime(self, proposal): path = proposal['value'] if not path.endswith('/'): # ensure path always has trailing / path = path + '/' if not os.path.exists(path): raise TraitError("path %r does not exist" % path) return path ipython-traitlets-a3e321a/docs/source/conf.py000066400000000000000000000244271461045054400213610ustar00rootroot00000000000000# # traitlets documentation build configuration file, created by # sphinx-quickstart on Mon Apr 13 16:57:06 2015. # # NOTE: This file has been edited manually from the auto-generated one from # sphinx. Do NOT delete and re-generate. If any changes from sphinx are # needed, generate a scratch one and merge by hand any new fields needed. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. from __future__ import annotations import os.path as osp import shutil import sys HERE = osp.abspath(osp.dirname(__file__)) ROOT = osp.dirname(osp.dirname(HERE)) from traitlets import __version__, version_info # noqa: E402 # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. sys.path.insert(0, osp.abspath(osp.join(HERE, "sphinxext"))) extensions = [ "myst_parser", "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", ] github_project_url = "https://github.com/ipython/traitlets" # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # Add dev disclaimer. if version_info[-1] == "dev": rst_prolog = """ .. note:: This documentation is for a development version of Traitlets. There may be significant differences from the latest stable release. """ # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "traitlets" copyright = "2015, The IPython Development Team" author = "The IPython Development Team" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(map(str, version_info[:2])) # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = "en" # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. # html_style = 'default.css' # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "pydata_sphinx_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = {"navigation_with_keys": False} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = "traitletsdoc" # -- Options for LaTeX output --------------------------------------------- # latex_elements = {} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "traitlets.tex", "traitlets Documentation", "The IPython Development Team", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "traitlets", "traitlets Documentation", [author], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "traitlets", "traitlets Documentation", author, "traitlets", "One line description of project.", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} def setup(app): dest = osp.join(HERE, "changelog.md") shutil.copy(osp.join(HERE, "..", "..", "CHANGELOG.md"), dest) ipython-traitlets-a3e321a/docs/source/config-api.rst000066400000000000000000000010401461045054400226120ustar00rootroot00000000000000Traitlets config API reference ============================== .. currentmodule:: traitlets.config .. autoclass:: Configurable :members: .. autoclass:: SingletonConfigurable :members: .. autoclass:: LoggingConfigurable :members: .. autoclass:: JSONFileConfigLoader :members: .. autoclass:: Application :members: .. autoclass:: Config :members: .. autoclass:: traitlets.config.loader.LazyConfigValue :members: .. autoclass:: traitlets.config.loader.KVArgParseConfigLoader :members: __init__, load_config ipython-traitlets-a3e321a/docs/source/config.rst000066400000000000000000001075771461045054400220710ustar00rootroot00000000000000========================================== Configurable objects with traitlets.config ========================================== .. module:: traitlets.config This document describes :mod:`traitlets.config`, the traitlets-based configuration system used by IPython and Jupyter. The main concepts ================= There are a number of abstractions that the IPython configuration system uses. Each of these abstractions is represented by a Python class. Configuration object: :class:`~traitlets.config.Config` A configuration object is a simple dictionary-like class that holds configuration attributes and sub-configuration objects. These classes support dotted attribute style access (``cfg.Foo.bar``) in addition to the regular dictionary style access (``cfg['Foo']['bar']``). The Config object is a wrapper around a simple dictionary with some convenience methods, such as merging and automatic section creation. Application: :class:`~traitlets.config.Application` An application is a process that does a specific job. The most obvious application is the :command:`ipython` command line program. Each application may read configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates, usually either via the `config` or `parent` constructor arguments. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object. Applications always have a `log` attribute that is a configured Logger. This allows centralized logging configuration per-application. Configurable: :class:`~traitlets.config.Configurable` A configurable is a regular Python class that serves as a base class for all main classes in an application. The :class:`~traitlets.config.Configurable` base class is lightweight and only does one thing. This :class:`~traitlets.config.Configurable` is a subclass of :class:`~traitlets.HasTraits` that knows how to configure itself. Class level traits with the metadata ``config=True`` become values that can be configured from the command line and configuration files. Developers create :class:`~traitlets.config.Configurable` subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created. When constructing a :class:`~traitlets.config.Configurable`, the `config` or `parent` arguments can be passed to the constructor (respectively a :class:`~traitlets.config.Config` and a Configurable object with a ``.config``). Singletons: :class:`~traitlets.config.SingletonConfigurable` Any object for which there is a single canonical instance. These are just like Configurables, except they have a class method :meth:`~traitlets.config.SingletonConfigurable.instance`, that returns the current active instance (or creates one if it does not exist). :class:`~traitlets.config.Application` is a singleton. This lets objects easily connect to the current running Application without passing objects around everywhere. For instance, to get the current running Application instance, simply do: ``app = Application.instance()``. .. note:: Singletons are not strictly enforced - you can have many instances of a given singleton class, but the :meth:`instance` method will always return the same one. Having described these main concepts, we can now state the main idea in our configuration system: *"configuration" allows the default values of class attributes to be controlled on a class by class basis*. Thus all instances of a given class are configured in the same way. Furthermore, if two instances need to be configured differently, they need to be instances of two different classes. While this model may seem a bit restrictive, we have found that it expresses most things that need to be configured extremely well. However, it is possible to create two instances of the same class that have different trait values. This is done by overriding the configuration. Now, we show what our configuration objects and files look like. Configuration objects and files =============================== A configuration object is little more than a wrapper around a dictionary. A configuration *file* is simply a mechanism for producing that object. Configuration files currently can be a plain Python script or a JSON file. The former has the benefit that it can perform extensive logic to populate the config object, while the latter is just a direct JSON serialization of the config dictionary and can be easily processed by external software. When both Python and JSON configuration file are present, both will be loaded, with JSON configuration having higher priority. The configuration files can be loaded by calling :meth:`Application.load_config_file()`, which takes the relative path to the config file (with or without file extension) and the directories in which to search for the config file. All found configuration files will be loaded in reverse order, so that configs in earlier directories will have higher priority. Python configuration Files -------------------------- A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a :class:`~traitlets.config.Config` instance. It is available inside the config file as ``c``, and you simply set attributes on this. All you have to know is: * The name of the class to configure. * The name of the attribute. * The type of each attribute. The answers to these questions are provided by the various :class:`~traitlets.config.Configurable` subclasses that an application uses. Let's look at how this would work for a simple configurable subclass .. code-block:: python # Sample configurable: from traitlets.config.configurable import Configurable from traitlets import Int, Float, Unicode, Bool class School(Configurable): name = Unicode("defaultname", help="the name of the object").tag(config=True) ranking = Integer(0, help="the class's ranking").tag(config=True) value = Float(99.0) # The rest of the class implementation would go here.. # Construct from config via School(config=..) In this example, we see that :class:`School` has three attributes, two of which (``name``, ``ranking``) can be configured. All of the attributes are given types and default values. If a :class:`School` is instantiated, but not configured, these default values will be used. But let's see how to configure this class in a configuration file .. code-block:: python # Sample config file c.School.name = "coolname" c.School.ranking = 10 After this configuration file is loaded, the values set in it will override the class defaults anytime a :class:`School` is created. Furthermore, these attributes will be type checked and validated anytime they are set. This type checking is handled by the :mod:`traitlets` module, which provides the :class:`~traitlets.Unicode`, :class:`~traitlets.Integer` and :class:`~traitlets.Float` types; see :doc:`trait_types` for the full list. It should be very clear at this point what the naming convention is for configuration attributes:: c.ClassName.attribute_name = attribute_value Here, ``ClassName`` is the name of the class whose configuration attribute you want to set, ``attribute_name`` is the name of the attribute you want to set and ``attribute_value`` the value you want it to have. The ``ClassName`` attribute of ``c`` is not the actual class, but instead is another :class:`~traitlets.config.Config` instance. .. note:: The careful reader may wonder how the ``ClassName`` (``School`` in the above example) attribute of the configuration object ``c`` gets created. These attributes are created on the fly by the :class:`~traitlets.config.Config` instance, using a simple naming convention. Any attribute of a :class:`~traitlets.config.Config` instance whose name begins with an uppercase character is assumed to be a sub-configuration and a new empty :class:`~traitlets.config.Config` instance is dynamically created for that attribute. This allows deeply hierarchical information created easily (``c.Foo.Bar.value``) on the fly. JSON configuration Files ------------------------ A JSON configuration file is simply a file that contains a :class:`~traitlets.config.Config` dictionary serialized to JSON. A JSON configuration file has the same base name as a Python configuration file, but with a .json extension. Configuration described in previous section could be written as follows in a JSON configuration file: .. code-block:: json { "School": { "name": "coolname", "ranking": 10 } } JSON configuration files can be more easily generated or processed by programs or other languages. Configuration files inheritance =============================== .. note:: This section only applies to Python configuration files. Let's say you want to have different configuration files for various purposes. Our configuration system makes it easy for one configuration file to inherit the information in another configuration file. The :func:`load_subconfig` command can be used in a configuration file for this purpose. Here is a simple example that loads all of the values from the file :file:`base_config.py`: .. code-block:: python :caption: examples/docs/configs/base_config.py c = get_config() # noqa c.School.name = "Harvard" c.School.ranking = 100 into the configuration file :file:`main_config.py`: .. code-block:: python :caption: examples/docs/configs/main_config.py :emphasize-lines: 4 c = get_config() # noqa # Load everything from base_config.py load_subconfig("base_config.py") # noqa # Now override one of the values c.School.name = "bettername" In a situation like this the :func:`load_subconfig` makes sure that the search path for sub-configuration files is inherited from that of the parent. Thus, you can typically put the two in the same directory and everything will just work. An example app using these configuration files can be found at `examples/docs/load_config_app.py `__. Class based configuration inheritance ===================================== There is another aspect of configuration where inheritance comes into play. Sometimes, your classes will have an inheritance hierarchy that you want to be reflected in the configuration system. Here is a simple example: .. code-block:: python from traitlets.config import Application, Configurable from traitlets import Integer, Float, Unicode, Bool class Foo(Configurable): name = Unicode("fooname", config=True) value = Float(100.0, config=True) class Bar(Foo): name = Unicode("barname", config=True) othervalue = Int(0, config=True) # construct Bar(config=..) Now, we can create a configuration file to configure instances of :class:`Foo` and :class:`Bar`: .. code-block:: python # config file c = get_config() # noqa c.Foo.name = "bestname" c.Bar.othervalue = 10 This class hierarchy and configuration file accomplishes the following: * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be ``'bestname'``. Because :class:`Bar` is a :class:`Foo` subclass it also picks up the configuration information for :class:`Foo`. * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be ``100.0``, which is the value specified as the class default. * The default value for :attr:`Bar.othervalue` will be 10 as set in the configuration file. Because :class:`Foo` is the parent of :class:`Bar` it doesn't know anything about the :attr:`othervalue` attribute. .. _commandline: Command-line arguments ====================== All configurable options can also be supplied at the command line when launching the application. Internally, when :meth:`Application.initialize()` is called, a :class:`~traitlets.config.loader.KVArgParseConfigLoader` instance is constructed to load values into a :class:`~traitlets.config.Config` object. (For advanced users, this can be overridden in the helper method :meth:`Application._create_loader()`.) Most command-line scripts simply need to call :meth:`Application.launch_instance()`, which will create the Application singleton, parse the command-line arguments, and start the application: .. code-block:: python :emphasize-lines: 8 from traitlets.config import Application class MyApp(Application): def start(self): pass # app logic goes here if __name__ == "__main__": MyApp.launch_instance() By default, config values are assigned from command-line arguments in much the same way as in a config file: .. code-block:: bash $ ipython --InteractiveShell.autoindent=False --BaseIPythonApplication.profile='myprofile' is the same as adding: .. code-block:: python c.InteractiveShell.autoindent = False c.BaseIPythonApplication.profile = "myprofile" to your configuration file. Command-line arguments take precedence over values read from configuration files. (This is done in :meth:`Application.load_config_file()` by merging ``Application.cli_config`` over values read from configuration files.) Note that even though :class:`Application` is a :class:`SingletonConfigurable`, multiple applications could still be started and called from each other by constructing them as one would with any other :class:`Configurable`: .. code-block:: python :caption: examples/docs/multiple_apps.py :emphasize-lines: 11,12,13 from traitlets.config import Application class OtherApp(Application): def start(self): print("other") class MyApp(Application): classes = [OtherApp] def start(self): # similar to OtherApp.launch_instance(), but without singleton self.other_app = OtherApp(config=self.config) self.other_app.initialize(["--OtherApp.log_level", "INFO"]) self.other_app.start() if __name__ == "__main__": MyApp.launch_instance() .. versionchanged:: 5.0 Prior to 5.0, fully specified ``--Class.trait=value`` arguments required an equals sign and no space separating the key and value. But after 5.0, these arguments can be separated by space as with aliases. .. versionchanged:: 5.0 extra quotes around strings and literal prefixes are no longer required. .. seealso:: :ref:`cli_strings` .. versionchanged:: 5.0 If a scalar (:class:`~.Unicode`, :class:`~.Integer`, etc.) is specified multiple times on the command-line, this will now raise. Prior to 5.0, all instances of the option before the last would be ignored. .. versionchanged:: 5.0 In 5.0, positional extra arguments (typically a list of files) must be contiguous, for example:: mycommand file1 file2 --flag or:: mycommand --flag file1 file2 whereas prior to 5.0, these "extra arguments" be distributed among other arguments:: mycommand file1 --flag file2 .. note:: By default, an error in a configuration file will cause the configuration file to be ignored and a warning logged. Application subclasses may specify `raise_config_file_errors = True` to exit on failure to load config files instead. .. versionadded:: 4.3 The environment variable ``TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR`` to ``'1'`` or ``'true'`` to change the default value of ``raise_config_file_errors``. Common Arguments ---------------- Since the strictness and verbosity of the full ``--Class.trait=value`` form are not ideal for everyday use, common arguments can be specified as flags_ or aliases_. In general, flags and aliases are prefixed by ``--``, except for those that are single characters, in which case they can be specified with a single ``-``, e.g.: .. code-block:: bash $ ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg Flags and aliases are declared by specifying ``flags`` and ``aliases`` attributes as dictionaries on subclasses of :class:`~traitlets.config.Application`. A key in both those dictionaries might be a string or tuple of strings. One-character strings are converted into "short" options (like ``-v``); longer strings are "long" options (like ``--verbose``). Aliases ******* For convenience, applications have a mapping of commonly used traits, so you don't have to specify the whole class name: .. code-block:: bash $ ipython --profile myprofile # and $ ipython --profile='myprofile' # are equivalent to $ ipython --BaseIPythonApplication.profile='myprofile' When specifying ``alias`` dictionary in code, the values might be the strings like ``'Class.trait'`` or two-tuples like ``('Class.trait', "Some help message")``. For example: .. code-block:: python :caption: examples/docs/aliases.py :emphasize-lines: 11,12 from traitlets import Bool from traitlets.config import Application, Configurable class Foo(Configurable): enabled = Bool(False, help="whether enabled").tag(config=True) class App(Application): classes = [Foo] dry_run = Bool(False, help="dry run test").tag(config=True) aliases = { "dry-run": "App.dry_run", ("f", "foo-enabled"): ("Foo.enabled", "whether foo is enabled"), } if __name__ == "__main__": App.launch_instance() By default, the ``--log-level`` alias will be set up for ``Application.log_level``. Flags ***** Applications can also be passed **flags**. Flags are options that take no arguments. They are simply wrappers for setting one or more configurables with predefined values, often True/False. For instance: .. code-block:: bash $ ipcontroller --debug # is equivalent to $ ipcontroller --Application.log_level=DEBUG # and $ ipython --matplotlib # is equivalent to $ ipython --matplotlib auto # or $ ipython --no-banner # is equivalent to $ ipython --TerminalIPythonApp.display_banner=False And a runnable code example: .. code-block:: python :caption: examples/docs/flags.py :emphasize-lines: 11,12,13,14,15,16,17 from traitlets import Bool from traitlets.config import Application, Configurable class Foo(Configurable): enabled = Bool(False, help="whether enabled").tag(config=True) class App(Application): classes = [Foo] dry_run = Bool(False, help="dry run test").tag(config=True) flags = { "dry-run": ({"App": {"dry_run": True}}, dry_run.help), ("f", "enable-foo"): ( { "Foo": {"enabled": True}, }, "Enable foo", ), ("disable-foo"): ( { "Foo": {"enabled": False}, }, "Disable foo", ), } if __name__ == "__main__": App.launch_instance() Since flags are a bit more complicated to set up, there are a couple of common patterns implemented in helper methods. For example, :func:`traitlets.config.boolean_flag()` sets up the flags ``--x`` and ``--no-x``. By default, the following few flags are set up: ``--debug`` (setting ``log_level=DEBUG``), ``--show-config``, and ``--show-config-json`` (print config to stdout and exit). Subcommands ----------- Configurable applications can also have **subcommands**. Subcommands are modeled after :command:`git`, and are called with the form :command:`command subcommand [...args]`. For instance, the QtConsole is a subcommand of terminal IPython: .. code-block:: bash $ jupyter qtconsole --profile myprofile .. currentmodule:: traitlets.config Subcommands are specified as a dictionary assigned to a ``subcommands`` class member of :class:`~traitlets.config.Application` instances. This dictionary maps *subcommand names* to two-tuples containing these: 1. A subclass of :class:`Application` to handle the subcommand. This can be specified as: - simply as a class, where its :meth:`SingletonConfigurable.instance()` will be invoked (straight-forward, but loads subclasses on import time); - as a string which can be imported to produce the above class; - as a factory function accepting a single argument like that:: app_factory(parent_app: Application) -> Application .. note:: The return value of the factory above is an *instance*, not a class, so the :meth:`SingletonConfigurable.instance()` is not invoked in this case. In all cases, the instantiated app is stored in :attr:`Application.subapp` and its :meth:`Application.initialize()` is invoked. 2. A short description of the subcommand for use in help output. For example (refer to ``examples/subcommands_app.py`` for a more complete example): .. code-block:: python :caption: examples/docs/subcommands.py :emphasize-lines: 14,15 from traitlets.config import Application class SubApp1(Application): pass class SubApp2(Application): @classmethod def get_subapp_instance(cls, app: Application) -> Application: app.clear_instance() # since Application is singleton, need to clear main app return cls.instance(parent=app) class MainApp(Application): subcommands = { "subapp1": (SubApp1, "First subapp"), "subapp2": (SubApp2.get_subapp_instance, "Second subapp"), } if __name__ == "__main__": MainApp.launch_instance() To see a list of the available aliases, flags, and subcommands for a configurable application, simply pass ``-h`` or ``--help``. To see the full list of configurable options (*very* long), pass ``--help-all``. For more complete examples of setting up :class:`~traitlets.config.Application`, refer to the `application examples `__. Other ``Application`` members ----------------------------- The following are typically set as class variables of :class:`~traitlets.config.Application` subclasses, but can also be set as instance variables. * ``.classes``: A list of :class:`~traitlets.config.Configurable` classes. Similar to configs, any class name can be used in ``--Class.trait=value`` arguments, including classes that the :class:`~traitlets.config.Application` might not know about. However, the ``--help-all`` menu will only enumerate ``config`` traits of classes in ``Application.classes``. Similarly, ``.classes`` is used in other places where an application wants to list all configurable traits; examples include :meth:`Application.generate_config_file()` and the :ref:`argcomplete` handling. * ``.name``, ``.description``, ``.option_description``, ``.keyvalue_description``, ``.subcommand_description``, ``.examples``, ``.version``: Various strings used in the ``--help`` menu and other messages * ``.log_level``, ``.log_datefmt``, ``.log_format``, ``.logging_config``: Configurable options to control application logging, which is emitted via the logger ``Application.log``. For more information about these, refer to their respective traits' ``.help``. * ``.show_config``, ``.show_config_json``: Configurable boolean options, which if set to ``True``, will cause the application to print the config to stdout instead of calling :meth:`Application.start()` Additionally, the following are set by :class:`~traitlets.config.Application`: * ``.cli_config``: The :class:`~traitlets.config.Config` created from the command-line arguments. This is saved to override any config values loaded from configuration files called by :meth:`Application.load_config_file()`. * ``.extra_args``: This is a list holding any positional arguments remaining from the command-line arguments parsed during :meth:`Application.initialize()`. As noted earlier, these must be contiguous in the command-line. .. _cli_strings: Interpreting command-line strings --------------------------------- .. versionadded:: 5.0 :meth:`~.TraitType.from_string`, :meth:`~.List.from_string_list`, and :meth:`~.List.item_from_string`. Prior to 5.0, we only had good support for Unicode or similar string types on the command-line. Other types were supported via :py:func:`ast.literal_eval`, which meant that simple types such as integers were well supported, too. The downside of this implementation was that the :py:func:`literal_eval` happened before the type of the target trait was known, meaning that strings that could be interpreted as literals could end up with the wrong type, famously:: $ ipython -c 1 ... [TerminalIPythonApp] CRITICAL | Bad config encountered during initialization: [TerminalIPythonApp] CRITICAL | The 'code_to_run' trait of a TerminalIPythonApp instance must be a unicode string, but a value of 1 was specified. This resulted in requiring redundant "double-quoting" of strings in many cases. That gets confusing when the shell *also* interprets quotes, so one had to:: $ ipython -c "'1'" in order to set a string that looks like an integer. traitlets 5.0 defers parsing of interpreting command-line strings to :meth:`~.TraitType.from_string`, which is an arbitrary function that will be called with the string given on the command-line. This eliminates the need to 'guess' how to interpret strings before we know what they are configuring. Backward compatibility ********************** It is not feasible to be perfectly backward-compatible when fixing behavior as problematic as this. However, we are doing our best to ensure that folks who had workarounds for this funky behavior are disrupted as little as we can manage. That means that we have kept what look like literals working wherever we could, so if you were double-quoting strings to ensure the were interpreted as strings, that will continue to work with warnings for the foreseeable future. If you have an example command-line call that used to work with traitlets 4 but does not any more with traitlets 5, please `let us know `__. Custom traits ************* .. versionadded:: 5.0 Custom trait types can override :meth:`~.TraitType.from_string` to specify how strings should be interpreted. This could for example allow specifying hex-encoded bytes on the command-line: .. code-block:: python :caption: examples/docs/from_string.py :emphasize-lines: 6,7 from binascii import a2b_hex from traitlets.config import Application from traitlets import Bytes class HexBytes(Bytes): def from_string(self, s): return a2b_hex(s) class App(Application): aliases = {"key": "App.key"} key = HexBytes( help=""" Key to be used. Specify as hex on the command-line. """, config=True, ) def start(self): print(f"key={self.key}") if __name__ == "__main__": App.launch_instance() .. code-block:: bash $ examples/docs/from_string.py --key=a1b2 key=b'\xa2\xb2' Container traits ---------------- In traitlets 5.0, items for container traits can be specified by passing the key multiple times, e.g.:: myprogram -l a -l b to produce the list ``["a", "b"]`` or for dictionaries use ``key=value``:: myprogram -d a=5 -d b=10 to produce the dict ``{"a": 5, "b": 10}``. In traitlets prior to 5.0, container traits (List, Dict) could *technically* be configured on the command-line by specifying a repr of a Python list or dict, e.g:: ipython --ScriptMagics.script_paths='{"perl": "/usr/bin/perl"}' but that gets pretty tedious, especially with more than a couple of fields. This still works with a FutureWarning, but the new way allows container items to be specified by passing the argument multiple times:: ipython \ --ScriptMagics.script_paths perl=/usr/bin/perl \ --ScriptMagics.script_paths ruby=/usr/local/opt/bin/ruby This handling is good enough that we can recommend defining aliases for container traits for the first time! For example: .. code-block:: python :caption: examples/docs/container.py from traitlets.config import Application from traitlets import Dict, Integer, List, Unicode class App(Application): aliases = {"x": "App.x", "y": "App.y"} x = List(Unicode(), config=True) y = Dict(Integer(), config=True) def start(self): print(f"x={self.x}") print(f"y={self.y}") if __name__ == "__main__": App.launch_instance() produces: .. code-block:: bash $ examples/docs/container.py -x a -x b -y a=10 -y b=5 x=['a', 'b'] y={'a': 10, 'b': 5} .. note:: Specifying the value trait of Dict was necessary to cast the values in `y` to integers. Otherwise, they values of `y` would have been the strings ``'10'`` and ``'5'``. For container types, :meth:`.List.from_string_list` is called with the list of all values specified on the command-line and is responsible for turning the list of strings into the appropriate type. Each item is then passed to :meth:`.List.item_from_string` which is responsible for handling the item, such as casting to integer or parsing ``key=value`` in the case of a Dict. The deprecated :py:func:`ast.literal_eval` handling is preserved for backward-compatibility in the event of a single item that 'looks like' a list or dict literal. If you would prefer, you can also use custom container traits which define :meth`~.TraitType.from_string` to expand a single string into a list, for example: .. code-block:: python class PathList(List): def from_string(self, s): return s.split(os.pathsep) which would allow:: myprogram --path /bin:/usr/local/bin:/opt/bin to set a ``PathList`` trait with ``["/bin", "/usr/local/bin", "/opt/bin"]``. .. _argcomplete: Command-line tab completion with ``argcomplete`` ------------------------------------------------ .. versionadded:: 5.8 ``traitlets`` has limited support for command-line tab completion for scripts based on :class:`~traitlets.config.Application` using `argcomplete `__. To use this, follow the instructions for setting up argcomplete; you will likely want to `activate global completion `__ by doing something alone the lines of: .. code-block:: bash # pip install argcomplete mkdir -p ~/.bash_completion.d/ activate-global-python-argcomplete --dest=~/.bash_completion.d/argcomplete # source ~/.bash_completion.d/argcomplete from your ~/.bashrc (Follow relevant instructions for your shell.) For any script you want tab-completion to work on, include the line: .. code-block:: python # PYTHON_ARGCOMPLETE_OK in the first 1024 bytes of the script. The following options can be tab-completed: * Flags and aliases * The classes in ``Application.classes``, which can be initially completed as ``--Class.`` * Once a completion is narrows to a single class, the individual ``config`` traits of the class will be tab-completable, as ``--Class.trait``. * The available values for :class:`traitlets.Bool` and :class:`traitlets.Enum` will be completable, as well as any other custom :class:`traitlets.TraitType` which defines a ``argcompleter()`` method returning a list of available string completions. * Custom completer methods can be assigned to a trait by tagging an ``argcompleter`` metadata tag. Refer to `argcomplete's documentation `__ for examples of creating custom completer methods. Detailed examples of these can be found in the docstring of `examples/argcomplete_app.py `__. Caveats with ``argcomplete`` handling ************************************* The support for ``argcomplete`` is still relatively new and may not work with all ways in which an :class:`~traitlets.config.Application` is used. Some known caveats: * ``argcomplete`` is called when any ``Application`` first constructs and uses a :class:`~traitlets.config.KVArgParseConfigLoader` instance, which constructs a ``argparse.ArgumentParser`` instance. We assume that this is usually first done in scripts when parsing the command-line arguments, but technically a script can first call ``Application.initialize(["other", "args"])`` for some other reason. * ``traitlets`` does not actually add ``"--Class.trait"`` options to the ``ArgumentParser``, but instead directly parses them from ``argv``. In order to complete these, a custom :class:`~traitlets.config.argcomplete_config.CompletionFinder` is subclassed from ``argcomplete.CompletionFinder``, which dynamically inserts the ``"--Class.""`` and ``"--Class.trait"`` completions when it thinks suitable. However, this handling may be a bit fragile. * Because ``traitlets`` initializes configs from ``argv`` and not from ``ArgumentParser``, it may be more difficult to write custom completers which dynamically provide completions based on the state of other parsed arguments. * Subcommand handling is especially tricky. ``argcomplete`` libraries' strategy is to call the python script with no arguments e.g. ``len(sys.argv) == 1``, run until ``argcomplete`` is called on an ``ArgumentParser`` and determine what completions are available. On the other hand, the ``traitlet`` subcommand-handling strategy is to check ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically load the subcommand app and initialize it with ``sys.argv[1:]``. To reconcile these two different approaches, some hacking was done to get ``traitlets`` to recognize the current command-line as seen by ``argcomplete``, and to get ``argcomplete`` to start parsing command-line arguments after subcommands have been evaluated. * Currently, completing subcommands themselves is not yet supported. * Some applications like ``Jupyter`` have custom ways of constructing subcommands or parsing ``argv`` which complicates matters even further. More details about these caveats can be found in the `original pull request `__. Design requirements =================== Here are the main requirements we wanted our configuration system to have: * Support for hierarchical configuration information. * Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override. * Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another. Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a ``1`` in a config file is the integer '1', while a ``'1'`` is a string. * A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry. * Type checking and validation that doesn't require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don't always know everything that needs to be configured when a program starts. ipython-traitlets-a3e321a/docs/source/defining_traits.rst000066400000000000000000000017611461045054400237610ustar00rootroot00000000000000Defining new trait types ======================== .. py:currentmodule:: traitlets To define a new trait type, subclass from :class:`TraitType`. You can define the following things: .. class:: MyTrait .. attribute:: info_text A short string describing what this trait should hold. .. attribute:: default_value A default value, if one makes sense for this trait type. If there is no obvious default, don't provide this. .. method:: validate(obj, value) Check whether a given value is valid. If it is, it should return the value (coerced to the desired type, if necessary). If not, it should raise :exc:`TraitError`. :meth:`TraitType.error` is a convenient way to raise an descriptive error saying that the given value is not of the required type. ``obj`` is the object to which the trait belongs. For instance, here's the definition of the :class:`TCPAddress` trait: .. literalinclude:: /../../traitlets/traitlets.py :pyobject: TCPAddress ipython-traitlets-a3e321a/docs/source/index.rst000066400000000000000000000015041461045054400217120ustar00rootroot00000000000000Traitlets ========= :Release: |release| :Date: |today| :home: https://github.com/ipython/traitlets :pypi-repo: https://pypi.org/project/traitlets/ :docs: https://traitlets.readthedocs.io/ :license: Modified BSD License Traitlets is a framework that lets Python classes have attributes with type checking, dynamically calculated default values, and 'on change' callbacks. The package also includes a mechanism to use traitlets for configuration, loading values from files or from command line arguments. This is a distinct layer on top of traitlets, so you can use traitlets in your code without using the configuration machinery. .. toctree:: :maxdepth: 2 using_traitlets trait_types defining_traits api config config-api utils migration changelog ipython-traitlets-a3e321a/docs/source/migration.rst000066400000000000000000000205451461045054400226020ustar00rootroot00000000000000Migration from Traitlets 4.0 to Traitlets 4.1 ============================================= Traitlets 4.1 introduces a totally new decorator-based API for configuring traitlets and a couple of other changes. However, it is a backward-compatible release and the deprecated APIs will be supported for some time. Separation of metadata and keyword arguments in ``TraitType`` constructors -------------------------------------------------------------------------- In traitlets 4.0, trait types constructors used all unrecognized keyword arguments passed to the constructor (like ``sync`` or ``config``) to populate the ``metadata`` dictionary. In trailets 4.1, we deprecated this behavior. The preferred method to populate the metadata for a trait type instance is to use the new ``tag`` method. .. code:: python x = Int(allow_none=True, sync=True) # deprecated x = Int(allow_none=True).tag(sync=True) # ok We also deprecated the ``get_metadata`` method. The metadata of a trait type instance can directly be accessed via the ``metadata`` attribute. Deprecation of ``on_trait_change`` ---------------------------------- The most important change in this release is the deprecation of the ``on_trait_change`` method. Instead, we introduced two methods, ``observe`` and ``unobserve`` to register and unregister handlers (instead of passing ``remove=True`` to ``on_trait_change`` for the removal). - The ``observe`` method takes one positional argument (the handler), and two keyword arguments, ``names`` and ``type``, which are used to filter by notification type or by the names of the observed trait attribute. The special value ``All`` corresponds to listening to all the notification types or all notifications from the trait attributes. The ``names`` argument can be a list of string, a string, or ``All`` and ``type`` can be a string or ``All``. - The observe handler's signature is different from the signature of on\_trait\_change. It takes a single change dictionary argument, containing .. code:: python {"type": ""} In the case where ``type`` is the string ``'change'``, the following additional attributes are provided: .. code:: python { "owner": "", "old": "", "new": "", "name": "", } The ``type`` key in the change dictionary is meant to enable protocols for other notification types. By default, its value is equal to the ``'change'`` string which corresponds to the change of a trait value. **Example:** .. code:: python from traitlets import HasTraits, Int, Unicode class Foo(HasTraits): bar = Int() baz = Unicode() def handle_change(change): print("{name} changed from {old} to {new}".format(**change)) foo = Foo() foo.observe(handle_change, names="bar") The new ``@observe`` decorator ------------------------------ The use of the magic methods ``_{trait}_changed`` as change handlers is deprecated, in favor of a new ``@observe`` method decorator. The ``@observe`` method decorator takes the names of traits to be observed as positional arguments and has a ``type`` keyword-only argument (defaulting to ``'change'``) to filter by notification type. **Example:** .. code:: python class Foo(HasTraits): bar = Int() baz = EnventfulContainer() # hypothetical trait type emitting # other notifications types @observe("bar") # 'change' notifications for `bar` def handler_bar(self, change): pass @observe("baz ", type="element_change") # 'element_change' notifications for `baz` def handler_baz(self, change): pass @observe("bar", "baz", type=All) # all notifications for `bar` and `baz` def handler_all(self, change): pass dynamic defaults generation with decorators ------------------------------------------- The use of the magic methods ``_{trait}_default`` for dynamic default generation is not deprecated, but a new ``@default`` method decorator is added. **Example:** Default generators should only be called if they are registered in subclasses of ``trait.this_type``. .. code:: python from traitlets import HasTraits, Int, Float, default class A(HasTraits): bar = Int() @default("bar") def get_bar_default(self): return 11 class B(A): bar = Float() # This ignores the default generator # defined in the base class A class C(B): @default("bar") def some_other_default(self): # This should not be ignored since return 3.0 # it is defined in a class derived # from B.a.this_class. Deprecation of magic method for cross-validation ------------------------------------------------ ``traitlets`` enables custom cross validation between the different attributes of a ``HasTraits`` instance. For example, a slider value should remain bounded by the ``min`` and ``max`` attribute. This validation occurs before the trait notification fires. The use of the magic methods ``_{name}_validate`` for custom cross-validation is deprecated, in favor of a new ``@validate`` method decorator. The method decorated with the ``@validate`` decorator take a single ``proposal`` dictionary .. code:: python { "trait": "", "value": "", "owner": "", } Custom validators may raise ``TraitError`` exceptions in case of invalid proposal, and should return the value that will be eventually assigned. **Example:** .. code:: python from traitlets import HasTraits, TraitError, Int, Bool, validate class Parity(HasTraits): value = Int() parity = Int() @validate("value") def _valid_value(self, proposal): if proposal["value"] % 2 != self.parity: raise TraitError("value and parity should be consistent") return proposal["value"] @validate("parity") def _valid_parity(self, proposal): parity = proposal["value"] if parity not in [0, 1]: raise TraitError("parity should be 0 or 1") if self.value % 2 != parity: raise TraitError("value and parity should be consistent") return proposal["value"] parity_check = Parity(value=2) # Changing required parity and value together while holding cross validation with parity_check.hold_trait_notifications(): parity_check.value = 1 parity_check.parity = 1 The presence of the ``owner`` key in the proposal dictionary enable the use of other attributes of the object in the cross validation logic. However, we recommend that the custom cross validator don't modify the other attributes of the object but only coerce the proposed value. Backward-compatible upgrades ---------------------------- One challenge in adoption of a changing API is how to adopt the new API while maintaining backward compatibility for subclasses, as event listeners methods are *de facto* public APIs. Take for instance the following class: .. code:: python from traitlets import HasTraits, Unicode class Parent(HasTraits): prefix = Unicode() path = Unicode() def _path_changed(self, name, old, new): self.prefix = os.path.dirname(new) And you know another package has the subclass: .. code:: python from parent import Parent class Child(Parent): def _path_changed(self, name, old, new): super()._path_changed(name, old, new) if not os.path.exists(new): os.makedirs(new) If the parent package wants to upgrade without breaking Child, it needs to preserve the signature of ``_path_changed``. For this, we have provided an ``@observe_compat`` decorator, which automatically shims the deprecated signature into the new signature: .. code:: python from traitlets import HasTraits, Unicode, observe, observe_compat class Parent(HasTraits): prefix = Unicode() path = Unicode() @observe("path") @observe_compat # <- this allows super()._path_changed in subclasses to work with the old signature. def _path_changed(self, change): self.prefix = os.path.dirname(change["value"]) ipython-traitlets-a3e321a/docs/source/trait_types.rst000066400000000000000000000041511461045054400231530ustar00rootroot00000000000000Trait Types =========== .. module:: traitlets .. class:: TraitType The base class for all trait types. .. automethod:: __init__ .. automethod:: from_string Numbers ------- .. autoclass:: Integer An integer trait. On Python 2, this automatically uses the ``int`` or ``long`` types as necessary. .. class:: Int .. class:: Long On Python 2, these are traitlets for values where the ``int`` and ``long`` types are not interchangeable. On Python 3, they are both aliases for :class:`Integer`. In almost all situations, you should use :class:`Integer` instead of these. .. autoclass:: Float .. autoclass:: Complex .. class:: CInt CLong CFloat CComplex Casting variants of the above. When a value is assigned to the attribute, these will attempt to convert it by calling e.g. ``value = int(value)``. Strings ------- .. autoclass:: Unicode .. autoclass:: Bytes .. class:: CUnicode CBytes Casting variants. When a value is assigned to the attribute, these will attempt to convert it to their type. They will not automatically encode/decode between unicode and bytes, however. .. autoclass:: ObjectName .. autoclass:: DottedObjectName Containers ---------- .. autoclass:: List :members: __init__, from_string_list, item_from_string .. autoclass:: Set :members: __init__ .. autoclass:: Tuple :members: __init__ .. autoclass:: Dict :members: __init__, from_string_list, item_from_string Classes and instances --------------------- .. autoclass:: Instance :members: __init__ .. autoclass:: Type :members: __init__ .. autoclass:: This .. autoclass:: ForwardDeclaredInstance .. autoclass:: ForwardDeclaredType Miscellaneous ------------- .. autoclass:: Bool .. class:: CBool Casting variant. When a value is assigned to the attribute, this will attempt to convert it by calling ``value = bool(value)``. .. autoclass:: Enum .. autoclass:: CaselessStrEnum .. autoclass:: UseEnum .. autoclass:: TCPAddress .. autoclass:: CRegExp .. autoclass:: Union :members: __init__ .. autoclass:: Callable .. autoclass:: Any ipython-traitlets-a3e321a/docs/source/using_traitlets.rst000066400000000000000000000135621461045054400240320ustar00rootroot00000000000000Using Traitlets =============== In short, traitlets let the user define classes that have 1. Attributes (traits) with type checking and dynamically computed default values 2. Traits emit change events when attributes are modified 3. Traitlets perform some validation and allow coercion of new trait values on assignment. They also allow the user to define custom validation logic for attributes based on the value of other attributes. Default values, and checking type and value ------------------------------------------- At its most basic, traitlets provides type checking, and dynamic default value generation of attributes on :class:`traitlets.HasTraits` subclasses: .. code:: python from traitlets import HasTraits, Int, Unicode, default import getpass class Identity(HasTraits): username = Unicode() @default("username") def _default_username(self): return getpass.getuser() .. code:: python class Foo(HasTraits): bar = Int() foo = Foo(bar="3") # raises a TraitError :: TraitError: The 'bar' trait of a Foo instance must be an int, but a value of '3' was specified observe ------- Traitlets implement the observer pattern .. code:: python class Foo(HasTraits): bar = Int() baz = Unicode() foo = Foo() def func(change): print(change["old"]) print(change["new"]) # as of traitlets 4.3, one should be able to # write print(change.new) instead foo.observe(func, names=["bar"]) foo.bar = 1 # prints '0\n 1' foo.baz = "abc" # prints nothing When observers are methods of the class, a decorator syntax can be used. .. code:: python class Foo(HasTraits): bar = Int() baz = Unicode() @observe("bar") def _observe_bar(self, change): print(change["old"]) print(change["new"]) Validation and Coercion ----------------------- Custom Cross-Validation ^^^^^^^^^^^^^^^^^^^^^^^ Each trait type (``Int``, ``Unicode``, ``Dict`` etc.) may have its own validation or coercion logic. In addition, we can register custom cross-validators that may depend on the state of other attributes. Basic Example: Validating the Parity of a Trait ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python from traitlets import HasTraits, TraitError, Int, Bool, validate class Parity(HasTraits): data = Int() parity = Int() @validate("data") def _valid_data(self, proposal): if proposal["value"] % 2 != self.parity: raise TraitError("data and parity should be consistent") return proposal["value"] @validate("parity") def _valid_parity(self, proposal): parity = proposal["value"] if parity not in [0, 1]: raise TraitError("parity should be 0 or 1") if self.data % 2 != parity: raise TraitError("data and parity should be consistent") return proposal["value"] parity_check = Parity(data=2) # Changing required parity and value together while holding cross validation with parity_check.hold_trait_notifications(): parity_check.data = 1 parity_check.parity = 1 Notice how all of the examples above return ``proposal['value']``. Returning a value is necessary for validation to work properly, since the new value of the trait will be the return value of the function decorated by ``@validate``. If this function does not have any ``return`` statement, then the returned value will be ``None``, instead of what we wanted (which is ``proposal['value']``). However, we recommend that custom cross-validators don't modify the state of the HasTraits instance. Advanced Example: Validating the Schema ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``List`` and ``Dict`` trait types allow the validation of nested properties. .. code:: python from traitlets import HasTraits, Dict, Bool, Unicode class Nested(HasTraits): value = Dict( per_key_traits={"configuration": Dict(value_trait=Unicode()), "flag": Bool()} ) n = Nested() n.value = dict(flag=True, configuration={}) # OK n.value = dict(flag=True, configuration="") # raises a TraitError. However, for deeply nested properties it might be more appropriate to use an external validator: .. code:: python import jsonschema value_schema = { "type": "object", "properties": { "price": {"type": "number"}, "name": {"type": "string"}, }, } from traitlets import HasTraits, Dict, TraitError, validate, default class Schema(HasTraits): value = Dict() @default("value") def _default_value(self): return dict(name="", price=1) @validate("value") def _validate_value(self, proposal): try: jsonschema.validate(proposal["value"], value_schema) except jsonschema.ValidationError as e: raise TraitError(e) return proposal["value"] s = Schema() s.value = dict(name="", price="1") # raises a TraitError Holding Trait Cross-Validation and Notifications ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sometimes it may be impossible to transition between valid states for a ``HasTraits`` instance by changing attributes one by one. The ``hold_trait_notifications`` context manager can be used to hold the custom cross validation until the context manager is released. If a validation error occurs, changes are rolled back to the initial state. Custom Events ------------- Finally, trait types can emit other events types than trait changes. This capability was added so as to enable notifications on change of values in container classes. The items available in the dictionary passed to the observer registered with ``observe`` depends on the event type. ipython-traitlets-a3e321a/docs/source/utils.rst000066400000000000000000000017341461045054400217500ustar00rootroot00000000000000Utils ===== .. module:: traitlets :noindex: A simple utility to import something by its string name. .. autofunction:: import_item .. autofunction:: signature_has_traits This is a way to expand the signature of the ``HasTraits`` class constructor. This enables auto-completion of trait-names in IPython and xeus-python when having Jedi>=0.15 by adding trait names with their default values in the constructor signature. Example: .. code:: Python from inspect import signature from traitlets import HasTraits, Int, Unicode, signature_has_traits @signature_has_traits class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode('Hello') def __init__(self, arg1, **kwargs): self.arg1 = arg1 super(Foo, self).__init__(**kwargs) print(signature(Foo)) # Links ----- .. autoclass:: link .. autoclass:: directional_link ipython-traitlets-a3e321a/docs/sphinxext/000077500000000000000000000000001461045054400206035ustar00rootroot00000000000000ipython-traitlets-a3e321a/docs/sphinxext/github.py000066400000000000000000000131121461045054400224350ustar00rootroot00000000000000"""Define text roles for GitHub * ghissue - Issue * ghpull - Pull Request * ghuser - User Adapted from bitbucket example here: https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/bitbucket/sphinxcontrib/bitbucket.py Authors ------- * Doug Hellmann * Min RK """ # # Original Copyright (c) 2010 Doug Hellmann. All rights reserved. # from __future__ import annotations from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes from sphinx.util.logging import getLogger info = getLogger(__name__).info def make_link_node(rawtext, app, type, slug, options): """Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Link type (issues, changeset, etc.) :param slug: ID of the thing to link to :param options: Options dictionary passed to role func. """ try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith("/"): base += "/" except AttributeError as err: raise ValueError( "github_project_url configuration value is not set (%s)" % str(err) ) from err ref = base + type + "/" + slug + "/" set_classes(options) prefix = "#" if type == "pull": prefix = "PR " + prefix return nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref, **options) def ghissue_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Link to a GitHub issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ options = options or {} content = content or [] try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( "GitHub issue number must be a number greater than or equal to 1; " '"%s" is invalid.' % text, line=lineno, ) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] app = inliner.document.settings.env.app # info('issue %r' % text) if "pull" in name.lower(): category = "pull" elif "issue" in name.lower(): category = "issues" else: msg = inliner.reporter.error( 'GitHub roles include "ghpull" and "ghissue", "%s" is invalid.' % name, line=lineno ) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = make_link_node(rawtext, app, category, str(issue_num), options) return [node], [] def ghuser_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ options = options or {} content = content or [] # info('user link %r' % text) ref = "https://www.github.com/" + text node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], [] def ghcommit_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Link to a GitHub commit. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ options = options or {} content = content or [] app = inliner.document.settings.env.app # info('user link %r' % text) try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith("/"): base += "/" except AttributeError as err: raise ValueError( "github_project_url configuration value is not set (%s)" % str(err) ) from err ref = base + text node = nodes.reference(rawtext, text[:6], refuri=ref, **options) return [node], [] def setup(app): """Install the plugin. :param app: Sphinx application context. """ info("Initializing GitHub plugin") app.add_role("ghissue", ghissue_role) app.add_role("ghpull", ghissue_role) app.add_role("ghuser", ghuser_role) app.add_role("ghcommit", ghcommit_role) app.add_config_value("github_project_url", None, "env") return {"parallel_read_safe": True, "parallel_write_safe": True} ipython-traitlets-a3e321a/examples/000077500000000000000000000000001461045054400174375ustar00rootroot00000000000000ipython-traitlets-a3e321a/examples/argcomplete_app.py000077500000000000000000000123241461045054400231600ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example to test CLI completion with `traitlets.Application` Follow the installation instructions in https://github.com/kislyuk/argcomplete#installation to install argcomplete. For example for bash, you can set up global completion via something like:: $ activate-global-python-argcomplete --dest=~/.bash_completion.d and ``source ~/.bash_completion.d`` in your ``~/.bashrc``. To use the `global-python-argcomplete`, your `traitlets.Application`-based script should have the string ``PYTHON_ARGCOMPLETE_OK`` in the first few lines of the script. Afterwards, try tab completing options to this script:: # Option completion, show flags, aliases and --Class. $ examples/argcomplete_app.py --[TAB] --Application. --JsonPrinter. --env-vars --s --ArgcompleteApp. --e --help --skip-if-missing --EnvironPrinter. --env-var --json-indent --style $ examples/argcomplete_app.py --A[TAB] --Application. --ArgcompleteApp. # Complete class config traits $ examples/argcomplete_app.py --EnvironPrinter.[TAB] --EnvironPrinter.no_complete --EnvironPrinter.style --EnvironPrinter.skip_if_missing --EnvironPrinter.vars # Using argcomplete's provided EnvironCompleter $ examples/argcomplete_app.py --EnvironPrinter.vars=[TAB] APPDATA LS_COLORS COMP_LINE NAME COMP_POINT OLDPWD COMP_TYPE PATH ... $ examples/argcomplete_app.py --EnvironPrinter.vars USER [TAB] APPDATA LS_COLORS COMP_LINE NAME COMP_POINT OLDPWD COMP_TYPE PATH ... # Alias for --EnvironPrinter.vars $ examples/argcomplete_app.py --env-vars P[TAB] PATH PWD PYTHONPATH # Custom completer example $ examples/argcomplete_app.py --env-vars PWD --json-indent [TAB] 2 4 8 # Enum completer example $ examples/argcomplete_app.py --style [TAB] ndjson posix verbose # Bool completer example $ examples/argcomplete_app.py --Application.show_config_json [TAB] 0 1 false true If completions are not showing, you can set the environment variable ``_ARC_DEBUG=1`` to assist in debugging argcomplete. This was last checked with ``argcomplete==1.12.3``. """ from __future__ import annotations import json import os try: from argcomplete.completers import EnvironCompleter, SuppressCompleter except ImportError: EnvironCompleter = SuppressCompleter = None from traitlets import Bool, Enum, Int, List, Unicode from traitlets.config.application import Application from traitlets.config.configurable import Configurable def _indent_completions(**kwargs): """Example of a custom completer, which could be dynamic""" return ["2", "4", "8"] class JsonPrinter(Configurable): indent = Int(None, allow_none=True).tag(config=True, argcompleter=_indent_completions) def print(self, obj): print(json.dumps(obj, indent=self.indent)) class EnvironPrinter(Configurable): """A class that has configurable, typed attributes.""" vars = List(trait=Unicode(), help="Environment variable").tag( # NOTE: currently multiplicity is ignored by the traitlets CLI. # Refer to issue GH#690 for discussion config=True, multiplicity="+", argcompleter=EnvironCompleter, ) no_complete = Unicode().tag(config=True, argcompleter=SuppressCompleter) style = Enum(values=["posix", "ndjson", "verbose"], default_value="posix").tag(config=True) skip_if_missing = Bool(False, help="Skip variable if not set").tag(config=True) def print(self): for env_var in self.vars: if env_var not in os.environ: if self.skip_if_missing: continue raise KeyError(f"Environment variable not set: {env_var}") value = os.environ[env_var] if self.style == "posix": print(f"{env_var}={value}") elif self.style == "verbose": print(f">> key: {env_var} value:\n{value}\n") elif self.style == "ndjson": JsonPrinter(parent=self).print({"key": env_var, "value": value}) def bool_flag(trait, value=True): return ({trait.this_class.__name__: {trait.name: value}}, trait.help) class ArgcompleteApp(Application): name = Unicode("argcomplete-example-app") description = Unicode("prints requested environment variables") classes = [JsonPrinter, EnvironPrinter] config_file = Unicode("", help="Load this config file").tag(config=True) aliases = { ("e", "env-var", "env-vars"): "EnvironPrinter.vars", ("s", "style"): "EnvironPrinter.style", ("json-indent"): "JsonPrinter.indent", } flags = { "skip-if-missing": bool_flag(EnvironPrinter.skip_if_missing), } def initialize(self, argv=None): self.parse_command_line(argv) if self.config_file: self.load_config_file(self.config_file) def start(self): EnvironPrinter(parent=self).print() if __name__ == "__main__": ArgcompleteApp.launch_instance() ipython-traitlets-a3e321a/examples/docs/000077500000000000000000000000001461045054400203675ustar00rootroot00000000000000ipython-traitlets-a3e321a/examples/docs/aliases.py000077500000000000000000000011461461045054400223670ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of using Application aliases, for docs""" from __future__ import annotations from traitlets import Bool from traitlets.config import Application, Configurable class Foo(Configurable): enabled = Bool(False, help="whether enabled").tag(config=True) class App(Application): classes = [Foo] dry_run = Bool(False, help="dry run test").tag(config=True) aliases = { "dry-run": "App.dry_run", ("f", "foo-enabled"): ("Foo.enabled", "whether foo is enabled"), } if __name__ == "__main__": App.launch_instance() ipython-traitlets-a3e321a/examples/docs/configs/000077500000000000000000000000001461045054400220175ustar00rootroot00000000000000ipython-traitlets-a3e321a/examples/docs/configs/base_config.py000066400000000000000000000002421461045054400246260ustar00rootroot00000000000000# Example config used by load_config_app.py from __future__ import annotations c = get_config() # noqa: F821 c.MyClass.name = "Harvard" c.MyClass.ranking = 100 ipython-traitlets-a3e321a/examples/docs/configs/main_config.py000066400000000000000000000004011461045054400246350ustar00rootroot00000000000000# Example config used by load_config_app.py from __future__ import annotations c = get_config() # noqa: F821 # Load everything from base_config.py load_subconfig("base_config.py") # noqa: F821 # Now override one of the values c.School.name = "Caltech" ipython-traitlets-a3e321a/examples/docs/container.py000077500000000000000000000010211461045054400227200ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of using container traits in Application command-line""" from __future__ import annotations from traitlets import Dict, Integer, List, Unicode from traitlets.config import Application class App(Application): aliases = {"x": "App.x", "y": "App.y"} x = List(Unicode(), config=True) y = Dict(Integer(), config=True) def start(self): print(f"x={self.x}") print(f"y={self.y}") if __name__ == "__main__": App.launch_instance() ipython-traitlets-a3e321a/examples/docs/flags.py000077500000000000000000000015121461045054400220370ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of using Application flags, for docs""" from __future__ import annotations from traitlets import Bool from traitlets.config import Application, Configurable class Foo(Configurable): enabled = Bool(False, help="whether enabled").tag(config=True) class App(Application): classes = [Foo] dry_run = Bool(False, help="dry run test").tag(config=True) flags = { "dry-run": ({"App": {"dry_run": True}}, dry_run.help), ("f", "enable-foo"): ( { "Foo": {"enabled": True}, }, "Enable foo", ), ("disable-foo"): ( { "Foo": {"enabled": False}, }, "Disable foo", ), } if __name__ == "__main__": App.launch_instance() ipython-traitlets-a3e321a/examples/docs/from_string.py000077500000000000000000000012201461045054400232700ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of using TraitType.from_string, for docs""" from __future__ import annotations from binascii import a2b_hex from traitlets import Bytes from traitlets.config import Application class HexBytes(Bytes): def from_string(self, s): return a2b_hex(s) class App(Application): aliases = {"key": "App.key"} key = HexBytes( help=""" Key to be used. Specify as hex on the command-line. """, config=True, ) def start(self): print(f"key={self.key.decode('utf8')}") if __name__ == "__main__": App.launch_instance() ipython-traitlets-a3e321a/examples/docs/load_config_app.py000077500000000000000000000027271461045054400240600ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of loading configs and overriding Example: $ ./examples/docs/load_config_app.py The school Caltech has a rank of 1. $ ./examples/docs/load_config_app.py --name Duke The school Duke has a rank of 1. $ ./examples/docs/load_config_app.py --name Duke --MyApp.MyClass.ranking=12 The school Duke has a rank of 12. $ ./examples/docs/load_config_app.py -c "" The school MIT has a rank of 1. """ from __future__ import annotations from pathlib import Path from traitlets import Int, Unicode from traitlets.config import Application, Configurable class School(Configurable): name = Unicode(default_value="MIT").tag(config=True) ranking = Int(default_value=1).tag(config=True) def __str__(self): return f"The school {self.name} has a rank of {self.ranking}." class MyApp(Application): classes = [School] config_file = Unicode(default_value="main_config", help="base name of config file").tag( config=True ) aliases = { "name": "School.name", "ranking": "School.ranking", ("c", "config-file"): "MyApp.config_file", } def initialize(self, argv=None): super().initialize(argv=argv) if self.config_file: self.load_config_file(self.config_file, [Path(__file__).parent / "configs"]) def start(self): print(School(parent=self)) if __name__ == "__main__": MyApp.launch_instance() ipython-traitlets-a3e321a/examples/docs/multiple_apps.py000077500000000000000000000011441461045054400236220ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of one application calling another""" from __future__ import annotations from traitlets.config import Application class OtherApp(Application): def start(self): print("other") class MyApp(Application): classes = [OtherApp] def start(self): # similar to OtherApp.launch_instance(), but without singleton self.other_app = OtherApp(config=self.config) self.other_app.initialize(["--OtherApp.log_level", "INFO"]) self.other_app.start() if __name__ == "__main__": MyApp.launch_instance() ipython-traitlets-a3e321a/examples/docs/subcommands.py000077500000000000000000000013301461045054400232540ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of using Application subcommands, for docs""" from __future__ import annotations from traitlets.config import Application class SubApp1(Application): pass class SubApp2(Application): @classmethod def get_subapp_instance(cls, app: Application) -> Application: app.clear_instance() # since Application is singleton, need to clear main app return cls.instance(parent=app) # type: ignore[no-any-return] class MainApp(Application): subcommands = { "subapp1": (SubApp1, "First subapp"), "subapp2": (SubApp2.get_subapp_instance, "Second subapp"), } if __name__ == "__main__": MainApp.launch_instance() ipython-traitlets-a3e321a/examples/myapp.py000077500000000000000000000126421461045054400211470ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example of how to use traitlets.config.application.Application. This should serve as a simple example that shows how the traitlets config system works. The main classes are: * traitlets.config.Configurable * traitlets.config.SingletonConfigurable * traitlets.config.Config * traitlets.config.Application To see the command line option help, run this program from the command line:: $ python myapp.py -h To make one of your classes configurable (from the command line and config files) inherit from Configurable and declare class attributes as traits (see classes Foo and Bar below). To make the traits configurable, you will need to set the following options: * ``config``: set to ``True`` to make the attribute configurable. * ``shortname``: by default, configurable attributes are set using the syntax "Classname.attributename". At the command line, this is a bit verbose, so we allow "shortnames" to be declared. Setting a shortname is optional, but when you do this, you can set the option at the command line using the syntax: "shortname=value". * ``help``: set the help string to display a help message when the ``-h`` option is given at the command line. The help string should be valid ReST. When the config attribute of an Application is updated, it will fire all of the trait's events for all of the config=True attributes. """ from __future__ import annotations from traitlets import Bool, Dict, Enum, Int, List, Unicode from traitlets.config.application import Application from traitlets.config.configurable import Configurable class SubConfigurable(Configurable): subvalue = Int(0, help="The integer subvalue.").tag(config=True) def describe(self): print("I am SubConfigurable with:") print(" subvalue =", self.subvalue) class Foo(Configurable): """A class that has configurable, typed attributes.""" i = Int(0, help="The integer i.").tag(config=True) j = Int(1, help="The integer j.").tag(config=True) name = Unicode("Brian", help="First name.").tag(config=True, shortname="B") mode = Enum(values=["on", "off", "other"], default_value="on").tag(config=True) def __init__(self, **kwargs): super().__init__(**kwargs) # using parent=self allows configuration in the form c.Foo.SubConfigurable.subvalue=1 # while c.SubConfigurable.subvalue=1 will still work, this allow to # target specific instances of SubConfigurables self.subconf = SubConfigurable(parent=self) def describe(self): print("I am Foo with:") print(" i =", self.i) print(" j =", self.j) print(" name =", self.name) print(" mode =", self.mode) self.subconf.describe() class Bar(Configurable): enabled = Bool(True, help="Enable bar.").tag(config=True) mylist = List([1, 2, 3], help="Just a list.").tag(config=True) def describe(self): print("I am Bar with:") print(" enabled = ", self.enabled) print(" mylist = ", self.mylist) self.subconf.describe() def __init__(self, **kwargs): super().__init__(**kwargs) # here we do not use parent=self, so configuration in the form # c.Bar.SubConfigurable.subvalue=1 will not work. Only # c.SubConfigurable.subvalue=1 will work and affect all instances of # SubConfigurable self.subconf = SubConfigurable(config=self.config) class MyApp(Application): name = Unicode("myapp") running = Bool(False, help="Is the app running?").tag(config=True) classes = List([Bar, Foo]) # type:ignore[assignment] config_file = Unicode("", help="Load this config file").tag(config=True) aliases = Dict( # type:ignore[assignment] dict( # noqa: C408 i="Foo.i", j="Foo.j", name="Foo.name", mode="Foo.mode", running="MyApp.running", enabled="Bar.enabled", log_level="MyApp.log_level", ) ) flags = Dict( # type:ignore[assignment] dict( # noqa: C408 enable=({"Bar": {"enabled": True}}, "Enable Bar"), disable=({"Bar": {"enabled": False}}, "Disable Bar"), debug=({"MyApp": {"log_level": 10}}, "Set loglevel to DEBUG"), ) ) def init_foo(self): # You can pass self as parent to automatically propagate config. self.foo = Foo(parent=self) def init_bar(self): # Pass config to other classes for them to inherit the config. self.bar = Bar(config=self.config) def initialize(self, argv=None): self.parse_command_line(argv) if self.config_file: self.load_config_file(self.config_file) self.load_config_environ() self.init_foo() self.init_bar() def start(self): print("app.config:") print(self.config) self.describe() print("try running with --help-all to see all available flags") assert self.log is not None self.log.debug("Debug Message") self.log.info("Info Message") self.log.warning("Warning Message") self.log.critical("Critical Message") def describe(self): print("I am MyApp with", self.name, self.running, "and 2 sub configurables Foo and bar:") self.foo.describe() self.bar.describe() def main(): app = MyApp() app.initialize() app.start() if __name__ == "__main__": main() ipython-traitlets-a3e321a/examples/subcommands_app.py000077500000000000000000000043421461045054400231720ustar00rootroot00000000000000#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """A simple example to demonstrate subcommands with traitlets.Application Example: $ examples/subcommands_app.py foo --print-name alice foo hello alice $ examples/subcommands_app.py bar --print-name bob bar hello bob """ from __future__ import annotations from traitlets import Enum, Unicode from traitlets.config.application import Application from traitlets.config.configurable import Configurable class PrintHello(Configurable): greet_name = Unicode("world").tag(config=True) greeting = Enum(values=["hello", "hi", "bye"], default_value="hello").tag(config=True) def run(self): print(f"{self.greeting} {self.greet_name}") class FooApp(Application): name = Unicode("foo") classes = [PrintHello] aliases = { "print-name": "PrintHello.greet_name", } config_file = Unicode("", help="Load this config file").tag(config=True) def start(self): print(self.name) PrintHello(parent=self).run() class BarApp(Application): name = Unicode("bar") classes = [PrintHello] aliases = { "print-name": "PrintHello.greet_name", } config_file = Unicode("", help="Load this config file").tag(config=True) def start(self): print(self.name) PrintHello(parent=self).run() @classmethod def get_subapp(cls, main_app: Application) -> Application: main_app.clear_instance() return cls.instance(parent=main_app) # type: ignore[no-any-return] class MainApp(Application): name = Unicode("subcommand-example-app") description = Unicode("demonstrates app with subcommands") subcommands = { # Subcommands should be a dictionary mapping from the subcommand name # to one of the following: # 1. The Application class to be instantiated e.g. FooApp # 2. A string e.g. "traitlets.examples.subcommands_app.FooApp" # which will be lazily evaluated # 3. A callable which takes this Application and returns an instance # (not class) of the subcommmand Application "foo": (FooApp, "run foo"), "bar": (BarApp.get_subapp, "run bar"), } if __name__ == "__main__": MainApp.launch_instance() ipython-traitlets-a3e321a/pyproject.toml000066400000000000000000000171271461045054400205450ustar00rootroot00000000000000[build-system] requires = ["hatchling >=1.5"] build-backend = "hatchling.build" [project] name = "traitlets" authors = [{name = "IPython Development Team", email = "ipython-dev@python.org"}] description = "Traitlets Python configuration system" license = {file = "LICENSE"} readme = "README.md" keywords = ["Interactive", "Interpreter", "Shell", "Web"] classifiers = [ "Framework :: IPython", "Framework :: Jupyter", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3", "Programming Language :: Python", "Typing :: Typed", ] requires-python = ">=3.8" dynamic = ["version"] [project.urls] Homepage = "https://github.com/ipython/traitlets" Documentation = "https://traitlets.readthedocs.io" Source = "https://github.com/ipython/traitlets" Funding = "https://numfocus.org" Tracker = "https://github.com/ipython/traitlets/issues" [project.optional-dependencies] test = [ "argcomplete>=3.0.3", "mypy>=1.7.0", "pre-commit", "pytest-mock", "pytest-mypy-testing", "pytest>=7.0,<8.2", ] docs = [ "myst-parser", "pydata-sphinx-theme", "sphinx" ] [tool.hatch.version] path = "traitlets/_version.py" [tool.hatch.metadata] allow-direct-references = true [tool.hatch.envs.docs] features = ["docs"] [tool.hatch.envs.docs.scripts] build = "make -C docs html SPHINXOPTS='-W'" [tool.hatch.envs.test] features = ["test"] [tool.hatch.envs.test.scripts] test = "python -m pytest -vv {args}" nowarn = "test -W default {args}" [tool.hatch.envs.cov] features = ["test"] dependencies = ["coverage[toml]", "pytest-cov"] [tool.hatch.envs.cov.scripts] test = "python -m pytest -vv --cov traitlets --cov-branch --cov-report term-missing:skip-covered {args}" nowarn = "test -W default {args}" [tool.hatch.envs.typing] dependencies = ["pre-commit"] detached = true [tool.hatch.envs.typing.scripts] test = "pre-commit run --all-files --hook-stage manual mypy" [tool.hatch.envs.lint] dependencies = ["pre-commit"] detached = true [tool.hatch.envs.lint.scripts] build = [ "pre-commit run --all-files ruff", "pre-commit run --all-files ruff-format" ] [tool.mypy] files = "traitlets" python_version = "3.8" strict = true enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] pretty = true show_error_context = true warn_unreachable = true exclude = ["examples/docs/configs", "traitlets/tests/test_typing.py"] [tool.pytest.ini_options] minversion = "6.0" xfail_strict = true log_cli_level = "info" addopts = [ "-ra", "--durations=10", "--color=yes", "--doctest-modules", "--showlocals", "--strict-markers", "--strict-config", "--ignore=examples/docs/configs" ] testpaths = [ "tests", "examples", ] filterwarnings = [ "ignore", "ignore:Passing unrecognized arguments", "ignore:Keyword .* is deprecated", "ignore:Supporting extra quotes around", "ignore:DeprecatedApp._config_changed is deprecated in traitlets", "ignore:A parent of DeprecatedApp._config_changed has adopted", "ignore:KeyValueConfigLoader is deprecated since Traitlets", "ignore:Traits should be given as instances", "ignore:Explicit using of Undefined as", "ignore:on_trait_change is deprecated", "ignore:.*use @observe and @unobserve instead", "ignore:.*for no default is deprecated in traitlets", "ignore:.*use @validate decorator instead", "ignore:.*has adopted the new \\(traitlets 4.1\\) @observe\\(change\\) API", "ignore:.*will be removed in Jinja 3.1.:DeprecationWarning", "ignore: the imp module is deprecated in favour of importlib", "ignore:IPython.core.inputsplitter is deprecated since IPython 7 in favor of `IPython.core.inputtransformer2`:DeprecationWarning", "ignore:pyee.EventEmitter is deprecated and will be removed in a future major version", # you should instead use either pyee.AsyncIOEventEmitter, pyee.TwistedEventEmitter, pyee.ExecutorEventEmitter, pyee.TrioEventEmitter, or pyee.BaseEventEmitter.:DeprecationWarning "ignore:Your element with mimetype.*", ] markers = [ "network: marks tests which require network connection (nbconvert)", "integration_tests: notebook mark (notebook)", ] [tool.coverage.report] exclude_lines = [ "pragma: no cover", "def __repr__", "if self.debug:", "if settings.DEBUG", "raise AssertionError", "raise NotImplementedError", "if 0:", "if __name__ == .__main__.:", "class .*\bProtocol\\):", "@(abc\\.)?abstractmethod", ] [tool.coverage.run] relative_files = true source = ["traitlets"] [tool.ruff] line-length = 100 [tool.ruff.lint] extend-select = [ "B", # flake8-bugbear "I", # isort "ARG", # flake8-unused-arguments "C4", # flake8-comprehensions # "EM", # flake8-errmsg "ICN", # flake8-import-conventions "G", # flake8-logging-format "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # pylint # "PTH", # flake8-use-pathlib "PT", # flake8-pytest-style "RET", # flake8-return "RUF", # Ruff-specific "SIM", # flake8-simplify "T20", # flake8-print "UP", # pyupgrade "YTT", # flake8-2020 "EXE", # flake8-executable "PYI", # flake8-pyi "S", # flake8-bandit ] ignore = [ "PLR", # Design related pylint codes "B027", # Allow non-abstract empty methods in abstract base classes "S101", # Use of `assert` detected "E501", # Line too long "S105", "S106", # Possible hardcoded password "S110", # S110 `try`-`except`-`pass` detected "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` "UP006", # non-pep585-annotation "UP007", # non-pep604-annotation "ARG001", "ARG002", # Unused function argument "RET503", # Missing explicit `return` at the end of function "RET505", # Unnecessary `else` after `return` statement "SIM102", # Use a single `if` statement instead of nested `if` statements "SIM105", # Use `contextlib.suppress(ValueError)` "SIM108", # Use ternary operator "SIM114", # Combine `if` branches using logical `or` operator" "PLW2901", # `for` loop variable `path` overwritten by assignment target # https://github.com/astral-sh/ruff/issues/8796#issuecomment-1825907715 "PT001", "PT004", "PT005", "PT02", "PT009" ] unfixable = [ # Don't touch noqa lines "RUF100", ] isort.required-imports = ["from __future__ import annotations"] [tool.ruff.lint.per-file-ignores] # B011 Do not call assert False since python -O removes these calls # F841 local variable 'foo' is assigned to but never used # C408 Unnecessary `dict` call # E402 Module level import not at top of file # T201 `print` found # B007 Loop control variable `i` not used within the loop body. # N802 Function name `assertIn` should be lowercase # F841 Local variable `t` is assigned to but never used # B018 Found useless expression # S301 `pickle` and modules that wrap..." # PGH003 Use specific rule codes when ignoring type issues "tests/*" = ["B011", "F841", "C408", "E402", "T201", "B007", "N802", "F841", "B018", "S301", "ARG", "PGH003"] "traitlets/config/application.py" = ["T201"] # B003 Assigning to os.environ doesn't clear the environment "tests/config/*" = ["B003", "B018", "S301"] # F401 `_version.__version__` imported but unused # F403 `from .traitlets import *` used; unable to detect undefined names "traitlets/*__init__.py" = ["F401", "F403"] "examples/*" = ["T201"] [tool.ruff.lint.flake8-pytest-style] fixture-parentheses = false mark-parentheses = false parametrize-names-type = "csv" ipython-traitlets-a3e321a/tests/000077500000000000000000000000001461045054400167635ustar00rootroot00000000000000ipython-traitlets-a3e321a/tests/__init__.py000066400000000000000000000000001461045054400210620ustar00rootroot00000000000000ipython-traitlets-a3e321a/tests/_warnings.py000066400000000000000000000102031461045054400213200ustar00rootroot00000000000000# From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py # Licensed under modified BSD license from __future__ import annotations __all__ = ["all_warnings", "expected_warnings"] import inspect import os import re import sys import warnings from contextlib import contextmanager from unittest import mock @contextmanager def all_warnings(): """ Context for use in testing to ensure that all warnings are raised. Examples -------- >>> import warnings >>> def foo(): ... warnings.warn(RuntimeWarning("bar")) We raise the warning once, while the warning filter is set to "once". Hereafter, the warning is invisible, even with custom filters: >>> with warnings.catch_warnings(): ... warnings.simplefilter('once') ... foo() We can now run ``foo()`` without a warning being raised: >>> from numpy.testing import assert_warns # doctest: +SKIP >>> foo() # doctest: +SKIP To catch the warning, we call in the help of ``all_warnings``: >>> with all_warnings(): # doctest: +SKIP ... assert_warns(RuntimeWarning, foo) """ # Whenever a warning is triggered, Python adds a __warningregistry__ # member to the *calling* module. The exercise here is to find # and eradicate all those breadcrumbs that were left lying around. # # We proceed by first searching all parent calling frames and explicitly # clearing their warning registries (necessary for the doctests above to # pass). Then, we search for all submodules of skimage and clear theirs # as well (necessary for the skimage test suite to pass). frame = inspect.currentframe() if frame: for f in inspect.getouterframes(frame): f[0].f_locals["__warningregistry__"] = {} del frame for _, mod in list(sys.modules.items()): try: mod.__warningregistry__.clear() except AttributeError: pass with warnings.catch_warnings(record=True) as w, mock.patch.dict( os.environ, {"TRAITLETS_ALL_DEPRECATIONS": "1"} ): warnings.simplefilter("always") yield w @contextmanager def expected_warnings(matching): r"""Context for use in testing to catch known warnings matching regexes Parameters ---------- matching : list of strings or compiled regexes Regexes for the desired warning to catch Examples -------- >>> from skimage import data, img_as_ubyte, img_as_float # doctest: +SKIP >>> with expected_warnings(["precision loss"]): # doctest: +SKIP ... d = img_as_ubyte(img_as_float(data.coins())) # doctest: +SKIP Notes ----- Uses `all_warnings` to ensure all warnings are raised. Upon exiting, it checks the recorded warnings for the desired matching pattern(s). Raises a ValueError if any match was not found or an unexpected warning was raised. Allows for three types of behaviors: "and", "or", and "optional" matches. This is done to accommodate different build environments or loop conditions that may produce different warnings. The behaviors can be combined. If you pass multiple patterns, you get an orderless "and", where all of the warnings must be raised. If you use the "|" operator in a pattern, you can catch one of several warnings. Finally, you can use "|\A\Z" in a pattern to signify it as optional. """ with all_warnings() as w: # enter context yield w # exited user context, check the recorded warnings remaining = [m for m in matching if r"\A\Z" not in m.split("|")] for warn in w: found = False for match in matching: if re.search(match, str(warn.message)) is not None: found = True if match in remaining: remaining.remove(match) if not found: raise ValueError("Unexpected warning: %s" % str(warn.message)) if len(remaining) > 0: msg = "No warning raised matching:\n%s" % "\n".join(remaining) raise ValueError(msg) ipython-traitlets-a3e321a/tests/config/000077500000000000000000000000001461045054400202305ustar00rootroot00000000000000ipython-traitlets-a3e321a/tests/config/__init__.py000066400000000000000000000000001461045054400223270ustar00rootroot00000000000000ipython-traitlets-a3e321a/tests/config/test_application.py000066400000000000000000000741371461045054400241600ustar00rootroot00000000000000""" Tests for traitlets.config.application.Application """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import contextlib import io import json import logging import os import sys import typing as t from io import StringIO from tempfile import TemporaryDirectory from unittest import TestCase, mock import pytest from traitlets import Bool, Bytes, Dict, HasTraits, Integer, List, Set, Tuple, Unicode from traitlets.config.application import Application from traitlets.config.configurable import Configurable from traitlets.config.loader import Config, KVArgParseConfigLoader from traitlets.tests.utils import check_help_all_output, check_help_output, get_output_error_code pjoin = os.path.join class Foo(Configurable): i = Integer( 0, help=""" The integer i. Details about i. """, ).tag(config=True) j = Integer(1, help="The integer j.").tag(config=True) name = Unicode("Brian", help="First name.").tag(config=True) la = List([]).tag(config=True) li = List(Integer()).tag(config=True) fdict = Dict().tag(config=True, multiplicity="+") class Bar(Configurable): b = Integer(0, help="The integer b.").tag(config=True) enabled = Bool(True, help="Enable bar.").tag(config=True) tb = Tuple(()).tag(config=True, multiplicity="*") aset = Set().tag(config=True, multiplicity="+") bdict = Dict().tag(config=True) idict = Dict(value_trait=Integer()).tag(config=True) key_dict = Dict(per_key_traits={"i": Integer(), "b": Bytes()}).tag(config=True) class MyApp(Application): name = Unicode("myapp") running = Bool(False, help="Is the app running?").tag(config=True) classes = List([Bar, Foo]) # type:ignore config_file = Unicode("", help="Load this config file").tag(config=True) warn_tpyo = Unicode( "yes the name is wrong on purpose", config=True, help="Should print a warning if `MyApp.warn-typo=...` command is passed", ) aliases: t.Dict[t.Any, t.Any] = {} aliases.update(Application.aliases) aliases.update( { ("fooi", "i"): "Foo.i", ("j", "fooj"): ("Foo.j", "`j` terse help msg"), "name": "Foo.name", "la": "Foo.la", "li": "Foo.li", "tb": "Bar.tb", "D": "Bar.bdict", "enabled": "Bar.enabled", "enable": "Bar.enabled", "log-level": "Application.log_level", } ) flags: t.Dict[t.Any, t.Any] = {} flags.update(Application.flags) flags.update( { ("enable", "e"): ({"Bar": {"enabled": True}}, "Set Bar.enabled to True"), ("d", "disable"): ({"Bar": {"enabled": False}}, "Set Bar.enabled to False"), "crit": ({"Application": {"log_level": logging.CRITICAL}}, "set level=CRITICAL"), } ) def init_foo(self): self.foo = Foo(parent=self) def init_bar(self): self.bar = Bar(parent=self) def class_to_names(classes): return [klass.__name__ for klass in classes] class TestApplication(TestCase): def test_log(self): stream = StringIO() app = MyApp(log_level=logging.INFO) handler = logging.StreamHandler(stream) # trigger reconstruction of the log formatter app.log_format = "%(message)s" app.log_datefmt = "%Y-%m-%d %H:%M" app.log.handlers = [handler] app.log.info("hello") assert "hello" in stream.getvalue() def test_no_eval_cli_text(self): app = MyApp() app.initialize(["--Foo.name=1"]) app.init_foo() assert app.foo.name == "1" def test_basic(self): app = MyApp() self.assertEqual(app.name, "myapp") self.assertEqual(app.running, False) self.assertEqual(app.classes, [MyApp, Bar, Foo]) # type:ignore self.assertEqual(app.config_file, "") def test_app_name_set_via_constructor(self): app = MyApp(name="set_via_constructor") assert app.name == "set_via_constructor" def test_mro_discovery(self): app = MyApp() self.assertSequenceEqual( class_to_names(app._classes_with_config_traits()), ["Application", "MyApp", "Bar", "Foo"], ) self.assertSequenceEqual( class_to_names(app._classes_inc_parents()), [ "Configurable", "LoggingConfigurable", "SingletonConfigurable", "Application", "MyApp", "Bar", "Foo", ], ) self.assertSequenceEqual( class_to_names(app._classes_with_config_traits([Application])), ["Application"] ) self.assertSequenceEqual( class_to_names(app._classes_inc_parents([Application])), ["Configurable", "LoggingConfigurable", "SingletonConfigurable", "Application"], ) self.assertSequenceEqual(class_to_names(app._classes_with_config_traits([Foo])), ["Foo"]) self.assertSequenceEqual( class_to_names(app._classes_inc_parents([Bar])), ["Configurable", "Bar"] ) class MyApp2(Application): # no defined `classes` attr pass self.assertSequenceEqual(class_to_names(app._classes_with_config_traits([Foo])), ["Foo"]) self.assertSequenceEqual( class_to_names(app._classes_inc_parents([Bar])), ["Configurable", "Bar"] ) def test_config(self): app = MyApp() app.parse_command_line( [ "--i=10", "--Foo.j=10", "--enable=False", "--log-level=50", ] ) config = app.config print(config) self.assertEqual(config.Foo.i, 10) self.assertEqual(config.Foo.j, 10) self.assertEqual(config.Bar.enabled, False) self.assertEqual(config.MyApp.log_level, 50) def test_config_seq_args(self): app = MyApp() app.parse_command_line( "--li 1 --li 3 --la 1 --tb AB 2 --Foo.la=ab --Bar.aset S1 --Bar.aset S2 --Bar.aset S1".split() ) assert app.extra_args == ["2"] config = app.config assert config.Foo.li == [1, 3] assert config.Foo.la == ["1", "ab"] assert config.Bar.tb == ("AB",) self.assertEqual(config.Bar.aset, {"S1", "S2"}) app.init_foo() assert app.foo.li == [1, 3] assert app.foo.la == ["1", "ab"] app.init_bar() self.assertEqual(app.bar.aset, {"S1", "S2"}) assert app.bar.tb == ("AB",) def test_config_dict_args(self): app = MyApp() app.parse_command_line( "--Foo.fdict a=1 --Foo.fdict b=b --Foo.fdict c=3 " "--Bar.bdict k=1 -D=a=b -D 22=33 " "--Bar.idict k=1 --Bar.idict b=2 --Bar.idict c=3 ".split() ) fdict = {"a": "1", "b": "b", "c": "3"} bdict = {"k": "1", "a": "b", "22": "33"} idict = {"k": 1, "b": 2, "c": 3} config = app.config assert config.Bar.idict == idict self.assertDictEqual(config.Foo.fdict, fdict) self.assertDictEqual(config.Bar.bdict, bdict) app.init_foo() self.assertEqual(app.foo.fdict, fdict) app.init_bar() assert app.bar.idict == idict self.assertEqual(app.bar.bdict, bdict) def test_config_propagation(self): app = MyApp() app.parse_command_line(["--i=10", "--Foo.j=10", "--enable=False", "--log-level=50"]) app.init_foo() app.init_bar() self.assertEqual(app.foo.i, 10) self.assertEqual(app.foo.j, 10) self.assertEqual(app.bar.enabled, False) def test_cli_priority(self): """Test that loading config files does not override CLI options""" name = "config.py" class TestApp(Application): value = Unicode().tag(config=True) config_file_loaded = Bool().tag(config=True) aliases = {"v": "TestApp.value"} app = TestApp() with TemporaryDirectory() as td: config_file = pjoin(td, name) with open(config_file, "w") as f: f.writelines( ["c.TestApp.value = 'config file'\n", "c.TestApp.config_file_loaded = True\n"] ) app.parse_command_line(["--v=cli"]) assert "value" in app.config.TestApp assert app.config.TestApp.value == "cli" assert app.value == "cli" app.load_config_file(name, path=[td]) assert app.config_file_loaded assert app.config.TestApp.value == "cli" assert app.value == "cli" def test_ipython_cli_priority(self): # this test is almost entirely redundant with above, # but we can keep it around in case of subtle issues creeping into # the exact sequence IPython follows. name = "config.py" class TestApp(Application): value = Unicode().tag(config=True) config_file_loaded = Bool().tag(config=True) aliases = {"v": ("TestApp.value", "some help")} app = TestApp() with TemporaryDirectory() as td: config_file = pjoin(td, name) with open(config_file, "w") as f: f.writelines( ["c.TestApp.value = 'config file'\n", "c.TestApp.config_file_loaded = True\n"] ) # follow IPython's config-loading sequence to ensure CLI priority is preserved app.parse_command_line(["--v=cli"]) # this is where IPython makes a mistake: # it assumes app.config will not be modified, # and storing a reference is storing a copy cli_config = app.config assert "value" in app.config.TestApp assert app.config.TestApp.value == "cli" assert app.value == "cli" app.load_config_file(name, path=[td]) assert app.config_file_loaded # enforce cl-opts override config file opts: # this is where IPython makes a mistake: it assumes # that cl_config is a different object, but it isn't. app.update_config(cli_config) assert app.config.TestApp.value == "cli" assert app.value == "cli" def test_cli_allow_none(self): class App(Application): aliases = {"opt": "App.opt"} opt = Unicode(allow_none=True, config=True) app = App() app.parse_command_line(["--opt=None"]) assert app.opt is None def test_flags(self): app = MyApp() app.parse_command_line(["--disable"]) app.init_bar() self.assertEqual(app.bar.enabled, False) app = MyApp() app.parse_command_line(["-d"]) app.init_bar() self.assertEqual(app.bar.enabled, False) app = MyApp() app.parse_command_line(["--enable"]) app.init_bar() self.assertEqual(app.bar.enabled, True) app = MyApp() app.parse_command_line(["-e"]) app.init_bar() self.assertEqual(app.bar.enabled, True) def test_flags_help_msg(self): app = MyApp() stdout = io.StringIO() with contextlib.redirect_stdout(stdout): app.print_flag_help() hmsg = stdout.getvalue() self.assertRegex(hmsg, "(? 2 aliases for the same argument class TestMultiAliasApp(Application): foo = Integer(config=True) aliases = {("f", "bar", "qux"): "TestMultiAliasApp.foo"} app = TestMultiAliasApp() app.parse_command_line(["-f", "3"]) self.assertEqual(app.foo, 3) app = TestMultiAliasApp() app.parse_command_line(["--bar", "4"]) self.assertEqual(app.foo, 4) app = TestMultiAliasApp() app.parse_command_line(["--qux", "5"]) self.assertEqual(app.foo, 5) def test_aliases_help_msg(self): app = MyApp() stdout = io.StringIO() with contextlib.redirect_stdout(stdout): app.print_alias_help() hmsg = stdout.getvalue() self.assertRegex(hmsg, "(? 0 def test_logging_config(tmp_path, capsys): """We should be able to configure additional log handlers.""" log_file = tmp_path / "log_file" app = Application( logging_config={ "version": 1, "handlers": { "file": { "class": "logging.FileHandler", "level": "DEBUG", "filename": str(log_file), }, }, "loggers": { "Application": { "level": "DEBUG", "handlers": ["console", "file"], }, }, } ) # the default "console" handler + our new "file" handler assert len(app.log.handlers) == 2 # log a couple of messages app.log.info("info") app.log.warning("warn") # test that log messages get written to the file with open(log_file) as log_handle: assert log_handle.read() == "info\nwarn\n" # test that log messages get written to stderr (default console handler) assert capsys.readouterr().err == "[Application] WARNING | warn\n" def test_get_default_logging_config_pythonw(monkeypatch): """Ensure logging is correctly disabled for pythonw usage.""" monkeypatch.setattr("traitlets.config.application.IS_PYTHONW", True) config = Application().get_default_logging_config() assert "handlers" not in config assert "loggers" not in config monkeypatch.setattr("traitlets.config.application.IS_PYTHONW", False) config = Application().get_default_logging_config() assert "handlers" in config assert "loggers" in config @pytest.fixture() def caplogconfig(monkeypatch): """Capture logging config events for DictConfigurator objects. This suppresses the event (so the configuration doesn't happen). Returns a list of (args, kwargs). """ calls = [] def _configure(*args, **kwargs): nonlocal calls calls.append((args, kwargs)) monkeypatch.setattr( "logging.config.DictConfigurator.configure", _configure, ) return calls @pytest.mark.skipif(sys.implementation.name == "pypy", reason="Test does not work on pypy") def test_logging_teardown_on_error(capsys, caplogconfig): """Ensure we don't try to open logs in order to close them (See #722). If you try to configure logging handlers whilst Python is shutting down you may get traceback. """ # create and destroy an app (without configuring logging) # (ensure that the logs were not configured) app = Application() del app assert len(caplogconfig) == 0 # logging was not configured out, err = capsys.readouterr() assert "Traceback" not in err # ensure that the logs would have been configured otherwise # (to prevent this test from yielding false-negatives) app = Application() app._logging_configured = True # make it look like logging was configured del app assert len(caplogconfig) == 1 # logging was configured if __name__ == "__main__": # for test_help_output: MyApp.launch_instance() ipython-traitlets-a3e321a/tests/config/test_argcomplete.py000066400000000000000000000175121461045054400241510ustar00rootroot00000000000000""" Tests for argcomplete handling by traitlets.config.application.Application """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import io import os import typing as t import pytest argcomplete = pytest.importorskip("argcomplete") from traitlets import Unicode from traitlets.config.application import Application from traitlets.config.configurable import Configurable from traitlets.config.loader import KVArgParseConfigLoader class ArgcompleteApp(Application): """Override loader to pass through kwargs for argcomplete testing""" argcomplete_kwargs: t.Dict[str, t.Any] def __init__(self, *args, **kwargs): # For subcommands, inherit argcomplete_kwargs from parent app parent = kwargs.get("parent") super().__init__(*args, **kwargs) if parent: argcomplete_kwargs = getattr(parent, "argcomplete_kwargs", None) if argcomplete_kwargs: self.argcomplete_kwargs = argcomplete_kwargs def _create_loader(self, argv, aliases, flags, classes): loader = KVArgParseConfigLoader( argv, aliases, flags, classes=classes, log=self.log, subcommands=self.subcommands ) loader._argcomplete_kwargs = self.argcomplete_kwargs # type: ignore[attr-defined] return loader class SubApp1(ArgcompleteApp): pass class SubApp2(ArgcompleteApp): @classmethod def get_subapp_instance(cls, app: Application) -> Application: app.clear_instance() # since Application is singleton, need to clear main app return cls.instance(parent=app) # type: ignore[no-any-return] class MainApp(ArgcompleteApp): subcommands = { "subapp1": (SubApp1, "First subapp"), "subapp2": (SubApp2.get_subapp_instance, "Second subapp"), } class CustomError(Exception): """Helper for exit hook for testing argcomplete""" @classmethod def exit(cls, code): raise cls(str(code)) class TestArgcomplete: IFS = "\013" COMP_WORDBREAKS = " \t\n\"'><=;|&(:" @pytest.fixture() def argcomplete_on(self, mocker): """Mostly borrowed from argcomplete's unit test fixtures Set up environment variables to mimic those passed by argcomplete """ _old_environ = os.environ os.environ = os.environ.copy() # type: ignore[assignment] os.environ["_ARGCOMPLETE"] = "1" os.environ["_ARC_DEBUG"] = "yes" os.environ["IFS"] = self.IFS os.environ["_ARGCOMPLETE_COMP_WORDBREAKS"] = self.COMP_WORDBREAKS # argcomplete==2.0.0 always calls fdopen(9, "w") to open a debug stream, # however this could conflict with file descriptors used by pytest # and lead to obscure errors. Since we are not looking at debug stream # in these tests, just mock this fdopen call out. mocker.patch("os.fdopen") try: yield finally: os.environ = _old_environ def run_completer( self, app: ArgcompleteApp, command: str, point: t.Union[str, int, None] = None, **kwargs: t.Any, ) -> t.List[str]: """Mostly borrowed from argcomplete's unit tests Modified to take an application instead of an ArgumentParser Command is the current command being completed and point is the index into the command where the completion is triggered. """ if point is None: point = str(len(command)) # Flushing tempfile was leading to CI failures with Bad file descriptor, not sure why. # Fortunately we can just write to a StringIO instead. # print("Writing completions to temp file with mode=", write_mode) # from tempfile import TemporaryFile # with TemporaryFile(mode=write_mode) as t: strio = io.StringIO() os.environ["COMP_LINE"] = command os.environ["COMP_POINT"] = str(point) with pytest.raises(CustomError) as cm: # noqa: PT012 app.argcomplete_kwargs = dict( output_stream=strio, exit_method=CustomError.exit, **kwargs ) app.initialize() if str(cm.value) != "0": raise RuntimeError(f"Unexpected exit code {cm.value}") out = strio.getvalue() return out.split(self.IFS) def test_complete_simple_app(self, argcomplete_on): app = ArgcompleteApp() expected = [ "--help", "--debug", "--show-config", "--show-config-json", "--log-level", "--Application.", "--ArgcompleteApp.", ] assert set(self.run_completer(app, "app --")) == set(expected) # completing class traits assert set(self.run_completer(app, "app --App")) > { "--Application.show_config", "--Application.log_level", "--Application.log_format", } def test_complete_custom_completers(self, argcomplete_on): app = ArgcompleteApp() # test pre-defined completers for Bool/Enum assert set(self.run_completer(app, "app --Application.log_level=")) > {"DEBUG", "INFO"} assert set(self.run_completer(app, "app --ArgcompleteApp.show_config ")) == { "0", "1", "true", "false", } # test custom completer and mid-command completions class CustomCls(Configurable): val = Unicode().tag( config=True, argcompleter=argcomplete.completers.ChoicesCompleter(["foo", "bar"]) ) class CustomApp(ArgcompleteApp): classes = [CustomCls] aliases = {("v", "val"): "CustomCls.val"} app = CustomApp() assert self.run_completer(app, "app --val ") == ["foo", "bar"] assert self.run_completer(app, "app --val=") == ["foo", "bar"] assert self.run_completer(app, "app -v ") == ["foo", "bar"] assert self.run_completer(app, "app -v=") == ["foo", "bar"] assert self.run_completer(app, "app --CustomCls.val ") == ["foo", "bar"] assert self.run_completer(app, "app --CustomCls.val=") == ["foo", "bar"] completions = self.run_completer(app, "app --val= abc xyz", point=10) # fixed in argcomplete >= 2.0 to return latter below assert completions == ["--val=foo", "--val=bar"] or completions == ["foo", "bar"] assert self.run_completer(app, "app --val --log-level=", point=10) == ["foo", "bar"] def test_complete_subcommands(self, argcomplete_on): app = MainApp() assert set(self.run_completer(app, "app ")) >= {"subapp1", "subapp2"} assert set(self.run_completer(app, "app sub")) == {"subapp1", "subapp2"} assert set(self.run_completer(app, "app subapp1")) == {"subapp1"} def test_complete_subcommands_subapp1(self, argcomplete_on): # subcommand handling modifies _ARGCOMPLETE env var global state, so # only can test one completion per unit test app = MainApp() try: assert set(self.run_completer(app, "app subapp1 --Sub")) > { "--SubApp1.show_config", "--SubApp1.log_level", "--SubApp1.log_format", } finally: SubApp1.clear_instance() def test_complete_subcommands_subapp2(self, argcomplete_on): app = MainApp() try: assert set(self.run_completer(app, "app subapp2 --")) > { "--Application.", "--SubApp2.", } finally: SubApp2.clear_instance() def test_complete_subcommands_main(self, argcomplete_on): app = MainApp() completions = set(self.run_completer(app, "app --")) assert completions > {"--Application.", "--MainApp."} assert "--SubApp1." not in completions assert "--SubApp2." not in completions ipython-traitlets-a3e321a/tests/config/test_configurable.py000066400000000000000000000537741461045054400243210ustar00rootroot00000000000000"""Tests for traitlets.config.configurable""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import logging from unittest import TestCase import pytest from tests._warnings import expected_warnings from traitlets.config.application import Application from traitlets.config.configurable import Configurable, LoggingConfigurable, SingletonConfigurable from traitlets.config.loader import Config from traitlets.log import get_logger from traitlets.traitlets import ( CaselessStrEnum, Dict, Enum, Float, FuzzyEnum, Integer, List, Set, Unicode, validate, ) from traitlets.utils.warnings import _deprecations_shown class MyConfigurable(Configurable): a = Integer(1, help="The integer a.").tag(config=True) b = Float(1.0, help="The integer b.").tag(config=True) c = Unicode("no config") mc_help = """MyConfigurable(Configurable) options ------------------------------------ --MyConfigurable.a= The integer a. Default: 1 --MyConfigurable.b= The integer b. Default: 1.0""" mc_help_inst = """MyConfigurable(Configurable) options ------------------------------------ --MyConfigurable.a= The integer a. Current: 5 --MyConfigurable.b= The integer b. Current: 4.0""" # On Python 3, the Integer trait is a synonym for Int mc_help = mc_help.replace("", "") mc_help_inst = mc_help_inst.replace("", "") class Foo(Configurable): a = Integer(0, help="The integer a.").tag(config=True) b = Unicode("nope").tag(config=True) flist = List([]).tag(config=True) fdict = Dict().tag(config=True) class Bar(Foo): b = Unicode("gotit", help="The string b.").tag(config=False) c = Float(help="The string c.").tag(config=True) bset = Set([]).tag(config=True, multiplicity="+") bset_values = Set([2, 1, 5]).tag(config=True, multiplicity="+") bdict = Dict().tag(config=True, multiplicity="+") bdict_values = Dict({1: "a", "0": "b", 5: "c"}).tag(config=True, multiplicity="+") foo_help = """Foo(Configurable) options ------------------------- --Foo.a= The integer a. Default: 0 --Foo.b= Default: 'nope' --Foo.fdict==... Default: {} --Foo.flist=... Default: []""" bar_help = """Bar(Foo) options ---------------- --Bar.a= The integer a. Default: 0 --Bar.bdict =... Default: {} --Bar.bdict_values =... Default: {1: 'a', '0': 'b', 5: 'c'} --Bar.bset ... Default: set() --Bar.bset_values ... Default: {1, 2, 5} --Bar.c= The string c. Default: 0.0 --Bar.fdict==... Default: {} --Bar.flist=... Default: []""" class TestConfigurable(TestCase): def test_default(self): c1 = Configurable() c2 = Configurable(config=c1.config) c3 = Configurable(config=c2.config) self.assertEqual(c1.config, c2.config) self.assertEqual(c2.config, c3.config) def test_custom(self): config = Config() config.foo = "foo" config.bar = "bar" c1 = Configurable(config=config) c2 = Configurable(config=c1.config) c3 = Configurable(config=c2.config) self.assertEqual(c1.config, config) self.assertEqual(c2.config, config) self.assertEqual(c3.config, config) # Test that copies are not made self.assertTrue(c1.config is config) self.assertTrue(c2.config is config) self.assertTrue(c3.config is config) self.assertTrue(c1.config is c2.config) self.assertTrue(c2.config is c3.config) def test_inheritance(self): config = Config() config.MyConfigurable.a = 2 config.MyConfigurable.b = 2.0 c1 = MyConfigurable(config=config) c2 = MyConfigurable(config=c1.config) self.assertEqual(c1.a, config.MyConfigurable.a) self.assertEqual(c1.b, config.MyConfigurable.b) self.assertEqual(c2.a, config.MyConfigurable.a) self.assertEqual(c2.b, config.MyConfigurable.b) def test_parent(self): config = Config() config.Foo.a = 10 config.Foo.b = "wow" config.Bar.b = "later" config.Bar.c = 100.0 f = Foo(config=config) with expected_warnings(["`b` not recognized"]): b = Bar(config=f.config) self.assertEqual(f.a, 10) self.assertEqual(f.b, "wow") self.assertEqual(b.b, "gotit") self.assertEqual(b.c, 100.0) def test_override1(self): config = Config() config.MyConfigurable.a = 2 config.MyConfigurable.b = 2.0 c = MyConfigurable(a=3, config=config) self.assertEqual(c.a, 3) self.assertEqual(c.b, config.MyConfigurable.b) self.assertEqual(c.c, "no config") def test_override2(self): config = Config() config.Foo.a = 1 config.Bar.b = "or" # Up above b is config=False, so this won't do it. config.Bar.c = 10.0 with expected_warnings(["`b` not recognized"]): c = Bar(config=config) self.assertEqual(c.a, config.Foo.a) self.assertEqual(c.b, "gotit") self.assertEqual(c.c, config.Bar.c) with expected_warnings(["`b` not recognized"]): c = Bar(a=2, b="and", c=20.0, config=config) self.assertEqual(c.a, 2) self.assertEqual(c.b, "and") self.assertEqual(c.c, 20.0) def test_help(self): self.assertEqual(MyConfigurable.class_get_help(), mc_help) self.assertEqual(Foo.class_get_help(), foo_help) self.assertEqual(Bar.class_get_help(), bar_help) def test_help_inst(self): inst = MyConfigurable(a=5, b=4) self.assertEqual(MyConfigurable.class_get_help(inst), mc_help_inst) def test_generated_config_enum_comments(self): class MyConf(Configurable): an_enum = Enum("Choice1 choice2".split(), help="Many choices.").tag(config=True) help_str = "Many choices." enum_choices_str = "Choices: any of ['Choice1', 'choice2']" rst_choices_str = "MyConf.an_enum : any of ``'Choice1'``|``'choice2'``" or_none_str = "or None" cls_help = MyConf.class_get_help() self.assertIn(help_str, cls_help) self.assertIn(enum_choices_str, cls_help) self.assertNotIn(or_none_str, cls_help) cls_cfg = MyConf.class_config_section() self.assertIn(help_str, cls_cfg) self.assertIn(enum_choices_str, cls_cfg) self.assertNotIn(or_none_str, cls_help) # Check order of Help-msg <--> Choices sections self.assertGreater(cls_cfg.index(enum_choices_str), cls_cfg.index(help_str)) rst_help = MyConf.class_config_rst_doc() self.assertIn(help_str, rst_help) self.assertIn(rst_choices_str, rst_help) self.assertNotIn(or_none_str, rst_help) class MyConf2(Configurable): an_enum = Enum( "Choice1 choice2".split(), allow_none=True, default_value="choice2", help="Many choices.", ).tag(config=True) defaults_str = "Default: 'choice2'" cls2_msg = MyConf2.class_get_help() self.assertIn(help_str, cls2_msg) self.assertIn(enum_choices_str, cls2_msg) self.assertIn(or_none_str, cls2_msg) self.assertIn(defaults_str, cls2_msg) # Check order of Default <--> Choices sections self.assertGreater(cls2_msg.index(defaults_str), cls2_msg.index(enum_choices_str)) cls2_cfg = MyConf2.class_config_section() self.assertIn(help_str, cls2_cfg) self.assertIn(enum_choices_str, cls2_cfg) self.assertIn(or_none_str, cls2_cfg) self.assertIn(defaults_str, cls2_cfg) # Check order of Default <--> Choices sections self.assertGreater(cls2_cfg.index(defaults_str), cls2_cfg.index(enum_choices_str)) def test_generated_config_strenum_comments(self): help_str = "Many choices." defaults_str = "Default: 'choice2'" or_none_str = "or None" class MyConf3(Configurable): an_enum = CaselessStrEnum( "Choice1 choice2".split(), allow_none=True, default_value="choice2", help="Many choices.", ).tag(config=True) enum_choices_str = "Choices: any of ['Choice1', 'choice2'] (case-insensitive)" cls3_msg = MyConf3.class_get_help() self.assertIn(help_str, cls3_msg) self.assertIn(enum_choices_str, cls3_msg) self.assertIn(or_none_str, cls3_msg) self.assertIn(defaults_str, cls3_msg) # Check order of Default <--> Choices sections self.assertGreater(cls3_msg.index(defaults_str), cls3_msg.index(enum_choices_str)) cls3_cfg = MyConf3.class_config_section() self.assertIn(help_str, cls3_cfg) self.assertIn(enum_choices_str, cls3_cfg) self.assertIn(or_none_str, cls3_cfg) self.assertIn(defaults_str, cls3_cfg) # Check order of Default <--> Choices sections self.assertGreater(cls3_cfg.index(defaults_str), cls3_cfg.index(enum_choices_str)) class MyConf4(Configurable): an_enum = FuzzyEnum( "Choice1 choice2".split(), allow_none=True, default_value="choice2", help="Many choices.", ).tag(config=True) enum_choices_str = "Choices: any case-insensitive prefix of ['Choice1', 'choice2']" cls4_msg = MyConf4.class_get_help() self.assertIn(help_str, cls4_msg) self.assertIn(enum_choices_str, cls4_msg) self.assertIn(or_none_str, cls4_msg) self.assertIn(defaults_str, cls4_msg) # Check order of Default <--> Choices sections self.assertGreater(cls4_msg.index(defaults_str), cls4_msg.index(enum_choices_str)) cls4_cfg = MyConf4.class_config_section() self.assertIn(help_str, cls4_cfg) self.assertIn(enum_choices_str, cls4_cfg) self.assertIn(or_none_str, cls4_cfg) self.assertIn(defaults_str, cls4_cfg) # Check order of Default <--> Choices sections self.assertGreater(cls4_cfg.index(defaults_str), cls4_cfg.index(enum_choices_str)) class TestSingletonConfigurable(TestCase): def test_instance(self): class Foo(SingletonConfigurable): pass self.assertEqual(Foo.initialized(), False) foo = Foo.instance() self.assertEqual(Foo.initialized(), True) self.assertEqual(foo, Foo.instance()) self.assertEqual(SingletonConfigurable._instance, None) def test_inheritance(self): class Bar(SingletonConfigurable): pass class Bam(Bar): pass self.assertEqual(Bar.initialized(), False) self.assertEqual(Bam.initialized(), False) bam = Bam.instance() self.assertEqual(Bar.initialized(), True) self.assertEqual(Bam.initialized(), True) self.assertEqual(bam, Bam._instance) self.assertEqual(bam, Bar._instance) self.assertEqual(SingletonConfigurable._instance, None) class TestLoggingConfigurable(TestCase): def test_parent_logger(self): class Parent(LoggingConfigurable): pass class Child(LoggingConfigurable): pass log = get_logger().getChild("TestLoggingConfigurable") parent = Parent(log=log) child = Child(parent=parent) self.assertEqual(parent.log, log) self.assertEqual(child.log, log) parent = Parent() child = Child(parent=parent, log=log) self.assertEqual(parent.log, get_logger()) self.assertEqual(child.log, log) def test_parent_not_logging_configurable(self): class Parent(Configurable): pass class Child(LoggingConfigurable): pass parent = Parent() child = Child(parent=parent) self.assertEqual(child.log, get_logger()) class MyParent(Configurable): pass class MyParent2(MyParent): pass class TestParentConfigurable(TestCase): def test_parent_config(self): cfg = Config( { "MyParent": { "MyConfigurable": { "b": 2.0, } } } ) parent = MyParent(config=cfg) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent.MyConfigurable.b) def test_parent_inheritance(self): cfg = Config( { "MyParent": { "MyConfigurable": { "b": 2.0, } } } ) parent = MyParent2(config=cfg) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent.MyConfigurable.b) def test_multi_parent(self): cfg = Config( { "MyParent2": { "MyParent": { "MyConfigurable": { "b": 2.0, } }, # this one shouldn't count "MyConfigurable": { "b": 3.0, }, } } ) parent2 = MyParent2(config=cfg) parent = MyParent(parent=parent2) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent2.MyParent.MyConfigurable.b) def test_parent_priority(self): cfg = Config( { "MyConfigurable": { "b": 2.0, }, "MyParent": { "MyConfigurable": { "b": 3.0, } }, "MyParent2": { "MyConfigurable": { "b": 4.0, } }, } ) parent = MyParent2(config=cfg) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent2.MyConfigurable.b) def test_multi_parent_priority(self): cfg = Config( { "MyConfigurable": { "b": 2.0, }, "MyParent": { "MyConfigurable": { "b": 3.0, }, }, "MyParent2": { "MyConfigurable": { "b": 4.0, }, "MyParent": { "MyConfigurable": { "b": 5.0, }, }, }, } ) parent2 = MyParent2(config=cfg) parent = MyParent2(parent=parent2) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent2.MyParent.MyConfigurable.b) class Containers(Configurable): lis = List().tag(config=True) def _lis_default(self): return [-1] s = Set().tag(config=True) def _s_default(self): return {"a"} d = Dict().tag(config=True) def _d_default(self): return {"a": "b"} class TestConfigContainers(TestCase): def test_extend(self): c = Config() c.Containers.lis.extend(list(range(5))) obj = Containers(config=c) self.assertEqual(obj.lis, list(range(-1, 5))) def test_insert(self): c = Config() c.Containers.lis.insert(0, "a") c.Containers.lis.insert(1, "b") obj = Containers(config=c) self.assertEqual(obj.lis, ["a", "b", -1]) def test_prepend(self): c = Config() c.Containers.lis.prepend([1, 2]) c.Containers.lis.prepend([2, 3]) obj = Containers(config=c) self.assertEqual(obj.lis, [2, 3, 1, 2, -1]) def test_prepend_extend(self): c = Config() c.Containers.lis.prepend([1, 2]) c.Containers.lis.extend([2, 3]) obj = Containers(config=c) self.assertEqual(obj.lis, [1, 2, -1, 2, 3]) def test_append_extend(self): c = Config() c.Containers.lis.append([1, 2]) c.Containers.lis.extend([2, 3]) obj = Containers(config=c) self.assertEqual(obj.lis, [-1, [1, 2], 2, 3]) def test_extend_append(self): c = Config() c.Containers.lis.extend([2, 3]) c.Containers.lis.append([1, 2]) obj = Containers(config=c) self.assertEqual(obj.lis, [-1, 2, 3, [1, 2]]) def test_insert_extend(self): c = Config() c.Containers.lis.insert(0, 1) c.Containers.lis.extend([2, 3]) obj = Containers(config=c) self.assertEqual(obj.lis, [1, -1, 2, 3]) def test_set_update(self): c = Config() c.Containers.s.update({0, 1, 2}) c.Containers.s.update({3}) obj = Containers(config=c) self.assertEqual(obj.s, {"a", 0, 1, 2, 3}) def test_dict_update(self): c = Config() c.Containers.d.update({"c": "d"}) c.Containers.d.update({"e": "f"}) obj = Containers(config=c) self.assertEqual(obj.d, {"a": "b", "c": "d", "e": "f"}) def test_update_twice(self): c = Config() c.MyConfigurable.a = 5 m = MyConfigurable(config=c) self.assertEqual(m.a, 5) c2 = Config() c2.MyConfigurable.a = 10 m.update_config(c2) self.assertEqual(m.a, 10) c2.MyConfigurable.a = 15 m.update_config(c2) self.assertEqual(m.a, 15) def test_update_self(self): """update_config with same config object still triggers config_changed""" c = Config() c.MyConfigurable.a = 5 m = MyConfigurable(config=c) self.assertEqual(m.a, 5) c.MyConfigurable.a = 10 m.update_config(c) self.assertEqual(m.a, 10) def test_config_default(self): class SomeSingleton(SingletonConfigurable): pass class DefaultConfigurable(Configurable): a = Integer().tag(config=True) def _config_default(self): if SomeSingleton.initialized(): return SomeSingleton.instance().config return Config() c = Config() c.DefaultConfigurable.a = 5 d1 = DefaultConfigurable() self.assertEqual(d1.a, 0) single = SomeSingleton.instance(config=c) d2 = DefaultConfigurable() self.assertIs(d2.config, single.config) self.assertEqual(d2.a, 5) def test_config_default_deprecated(self): """Make sure configurables work even with the deprecations in traitlets""" class SomeSingleton(SingletonConfigurable): pass # reset deprecation limiter _deprecations_shown.clear() with expected_warnings([]): class DefaultConfigurable(Configurable): a = Integer(config=True) def _config_default(self): if SomeSingleton.initialized(): return SomeSingleton.instance().config return Config() c = Config() c.DefaultConfigurable.a = 5 d1 = DefaultConfigurable() self.assertEqual(d1.a, 0) single = SomeSingleton.instance(config=c) d2 = DefaultConfigurable() self.assertIs(d2.config, single.config) self.assertEqual(d2.a, 5) def test_kwarg_config_priority(self): # a, c set in kwargs # a, b set in config # verify that: # - kwargs are set before config # - kwargs have priority over config class A(Configurable): a = Unicode("default", config=True) b = Unicode("default", config=True) c = Unicode("default", config=True) c_during_config = Unicode("never") @validate("b") def _record_c(self, proposal): # setting b from config records c's value at the time self.c_during_config = self.c return proposal.value cfg = Config() cfg.A.a = "a-config" cfg.A.b = "b-config" obj = A(a="a-kwarg", c="c-kwarg", config=cfg) assert obj.a == "a-kwarg" assert obj.b == "b-config" assert obj.c == "c-kwarg" assert obj.c_during_config == "c-kwarg" class TestLogger(TestCase): class A(LoggingConfigurable): foo = Integer(config=True) bar = Integer(config=True) baz = Integer(config=True) @pytest.mark.skipif(not hasattr(TestCase, "assertLogs"), reason="requires TestCase.assertLogs") def test_warn_match(self): logger = logging.getLogger("test_warn_match") cfg = Config({"A": {"bat": 5}}) with self.assertLogs(logger, logging.WARNING) as captured: TestLogger.A(config=cfg, log=logger) output = "\n".join(captured.output) self.assertIn("Did you mean one of: `bar, baz`?", output) self.assertIn("Config option `bat` not recognized by `A`.", output) cfg = Config({"A": {"fool": 5}}) with self.assertLogs(logger, logging.WARNING) as captured: TestLogger.A(config=cfg, log=logger) output = "\n".join(captured.output) self.assertIn("Config option `fool` not recognized by `A`.", output) self.assertIn("Did you mean `foo`?", output) cfg = Config({"A": {"totally_wrong": 5}}) with self.assertLogs(logger, logging.WARNING) as captured: TestLogger.A(config=cfg, log=logger) output = "\n".join(captured.output) self.assertIn("Config option `totally_wrong` not recognized by `A`.", output) self.assertNotIn("Did you mean", output) def test_logger_adapter(caplog, capsys): logger = logging.getLogger("Application") adapter = logging.LoggerAdapter(logger, {"key": "adapted"}) app = Application(log=adapter, log_level=logging.INFO) app.log_format = "%(key)s %(message)s" app.log.info("test message") assert "adapted test message" in capsys.readouterr().err ipython-traitlets-a3e321a/tests/config/test_loader.py000066400000000000000000000543511461045054400231170ustar00rootroot00000000000000"""Tests for traitlets.config.loader""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import copy import os import pickle from itertools import chain from tempfile import mkstemp from unittest import TestCase import pytest from traitlets import Dict, Integer, List, Tuple, Unicode from traitlets.config import Configurable from traitlets.config.loader import ( ArgParseConfigLoader, Config, JSONFileConfigLoader, KeyValueConfigLoader, KVArgParseConfigLoader, LazyConfigValue, PyFileConfigLoader, ) pyfile = """ c = get_config() c.a=10 c.b=20 c.Foo.Bar.value=10 c.Foo.Bam.value=list(range(10)) c.D.C.value='hi there' """ json1file = """ { "version": 1, "a": 10, "b": 20, "Foo": { "Bam": { "value": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] }, "Bar": { "value": 10 } }, "D": { "C": { "value": "hi there" } } } """ # should not load json2file = """ { "version": 2 } """ import logging log = logging.getLogger("devnull") log.setLevel(0) class TestFileCL(TestCase): def _check_conf(self, config): self.assertEqual(config.a, 10) self.assertEqual(config.b, 20) self.assertEqual(config.Foo.Bar.value, 10) self.assertEqual(config.Foo.Bam.value, list(range(10))) self.assertEqual(config.D.C.value, "hi there") def test_python(self): fd, fname = mkstemp(".py", prefix="μnïcø∂e") f = os.fdopen(fd, "w") f.write(pyfile) f.close() # Unlink the file cl = PyFileConfigLoader(fname, log=log) config = cl.load_config() self._check_conf(config) def test_json(self): fd, fname = mkstemp(".json", prefix="μnïcø∂e") f = os.fdopen(fd, "w") f.write(json1file) f.close() # Unlink the file cl = JSONFileConfigLoader(fname, log=log) config = cl.load_config() self._check_conf(config) def test_context_manager(self): fd, fname = mkstemp(".json", prefix="μnïcø∂e") f = os.fdopen(fd, "w") f.write("{}") f.close() cl = JSONFileConfigLoader(fname, log=log) value = "context_manager" with cl as c: c.MyAttr.value = value self.assertEqual(cl.config.MyAttr.value, value) # check that another loader does see the change _ = JSONFileConfigLoader(fname, log=log) self.assertEqual(cl.config.MyAttr.value, value) def test_json_context_bad_write(self): fd, fname = mkstemp(".json", prefix="μnïcø∂e") f = os.fdopen(fd, "w") f.write("{}") f.close() with JSONFileConfigLoader(fname, log=log) as config: config.A.b = 1 with self.assertRaises(TypeError), JSONFileConfigLoader(fname, log=log) as config: config.A.cant_json = lambda x: x loader = JSONFileConfigLoader(fname, log=log) cfg = loader.load_config() assert cfg.A.b == 1 assert "cant_json" not in cfg.A def test_collision(self): a = Config() b = Config() self.assertEqual(a.collisions(b), {}) a.A.trait1 = 1 b.A.trait2 = 2 self.assertEqual(a.collisions(b), {}) b.A.trait1 = 1 self.assertEqual(a.collisions(b), {}) b.A.trait1 = 0 self.assertEqual( a.collisions(b), { "A": { "trait1": "1 ignored, using 0", } }, ) self.assertEqual( b.collisions(a), { "A": { "trait1": "0 ignored, using 1", } }, ) a.A.trait2 = 3 self.assertEqual( b.collisions(a), { "A": { "trait1": "0 ignored, using 1", "trait2": "2 ignored, using 3", } }, ) def test_v2raise(self): fd, fname = mkstemp(".json", prefix="μnïcø∂e") f = os.fdopen(fd, "w") f.write(json2file) f.close() # Unlink the file cl = JSONFileConfigLoader(fname, log=log) with self.assertRaises(ValueError): cl.load_config() def _parse_int_or_str(v): try: return int(v) except Exception: return str(v) class MyLoader1(ArgParseConfigLoader): def _add_arguments(self, aliases=None, flags=None, classes=None): p = self.parser p.add_argument("-f", "--foo", dest="Global.foo", type=str) p.add_argument("-b", dest="MyClass.bar", type=int) p.add_argument("-n", dest="n", action="store_true") p.add_argument("Global.bam", type=str) p.add_argument("--list1", action="append", type=_parse_int_or_str) p.add_argument("--list2", nargs="+", type=int) class MyLoader2(ArgParseConfigLoader): def _add_arguments(self, aliases=None, flags=None, classes=None): subparsers = self.parser.add_subparsers(dest="subparser_name") subparser1 = subparsers.add_parser("1") subparser1.add_argument("-x", dest="Global.x") subparser2 = subparsers.add_parser("2") subparser2.add_argument("y") class TestArgParseCL(TestCase): def test_basic(self): cl = MyLoader1() config = cl.load_config("-f hi -b 10 -n wow".split()) self.assertEqual(config.Global.foo, "hi") self.assertEqual(config.MyClass.bar, 10) self.assertEqual(config.n, True) self.assertEqual(config.Global.bam, "wow") config = cl.load_config(["wow"]) self.assertEqual(list(config.keys()), ["Global"]) self.assertEqual(list(config.Global.keys()), ["bam"]) self.assertEqual(config.Global.bam, "wow") def test_add_arguments(self): cl = MyLoader2() config = cl.load_config("2 frobble".split()) self.assertEqual(config.subparser_name, "2") self.assertEqual(config.y, "frobble") config = cl.load_config("1 -x frobble".split()) self.assertEqual(config.subparser_name, "1") self.assertEqual(config.Global.x, "frobble") def test_argv(self): cl = MyLoader1(argv="-f hi -b 10 -n wow".split()) config = cl.load_config() self.assertEqual(config.Global.foo, "hi") self.assertEqual(config.MyClass.bar, 10) self.assertEqual(config.n, True) self.assertEqual(config.Global.bam, "wow") def test_list_args(self): cl = MyLoader1() config = cl.load_config("--list1 1 wow --list2 1 2 3 --list1 B".split()) self.assertEqual(list(config.Global.keys()), ["bam"]) self.assertEqual(config.Global.bam, "wow") self.assertEqual(config.list1, [1, "B"]) self.assertEqual(config.list2, [1, 2, 3]) class C(Configurable): str_trait = Unicode(config=True) int_trait = Integer(config=True) list_trait = List(config=True) list_of_ints = List(Integer(), config=True) dict_trait = Dict(config=True) dict_of_ints = Dict( key_trait=Integer(), value_trait=Integer(), config=True, ) dict_multi = Dict( key_trait=Unicode(), per_key_traits={ "int": Integer(), "str": Unicode(), }, config=True, ) class TestKeyValueCL(TestCase): klass = KeyValueConfigLoader def test_eval(self): cl = self.klass(log=log) config = cl.load_config( '--C.str_trait=all --C.int_trait=5 --C.list_trait=["hello",5]'.split() ) c = C(config=config) assert c.str_trait == "all" assert c.int_trait == 5 assert c.list_trait == ["hello", 5] def test_basic(self): cl = self.klass(log=log) argv = ["--" + s[2:] for s in pyfile.split("\n") if s.startswith("c.")] config = cl.load_config(argv) assert config.a == "10" assert config.b == "20" assert config.Foo.Bar.value == "10" # non-literal expressions are not evaluated self.assertEqual(config.Foo.Bam.value, "list(range(10))") self.assertEqual(Unicode().from_string(config.D.C.value), "hi there") def test_expanduser(self): cl = self.klass(log=log) argv = ["--a=~/1/2/3", "--b=~", "--c=~/", '--d="~/"'] config = cl.load_config(argv) u = Unicode() self.assertEqual(u.from_string(config.a), os.path.expanduser("~/1/2/3")) self.assertEqual(u.from_string(config.b), os.path.expanduser("~")) self.assertEqual(u.from_string(config.c), os.path.expanduser("~/")) self.assertEqual(u.from_string(config.d), "~/") def test_extra_args(self): cl = self.klass(log=log) config = cl.load_config(["--a=5", "b", "d", "--c=10"]) self.assertEqual(cl.extra_args, ["b", "d"]) assert config.a == "5" assert config.c == "10" config = cl.load_config(["--", "--a=5", "--c=10"]) self.assertEqual(cl.extra_args, ["--a=5", "--c=10"]) cl = self.klass(log=log) config = cl.load_config(["extra", "--a=2", "--c=1", "--", "-"]) self.assertEqual(cl.extra_args, ["extra", "-"]) def test_unicode_args(self): cl = self.klass(log=log) argv = ["--a=épsîlön"] config = cl.load_config(argv) print(config, cl.extra_args) self.assertEqual(config.a, "épsîlön") def test_list_append(self): cl = self.klass(log=log) argv = ["--C.list_trait", "x", "--C.list_trait", "y"] config = cl.load_config(argv) assert config.C.list_trait == ["x", "y"] c = C(config=config) assert c.list_trait == ["x", "y"] def test_list_single_item(self): cl = self.klass(log=log) argv = ["--C.list_trait", "x"] config = cl.load_config(argv) c = C(config=config) assert c.list_trait == ["x"] def test_dict(self): cl = self.klass(log=log) argv = ["--C.dict_trait", "x=5", "--C.dict_trait", "y=10"] config = cl.load_config(argv) c = C(config=config) assert c.dict_trait == {"x": "5", "y": "10"} def test_dict_key_traits(self): cl = self.klass(log=log) argv = ["--C.dict_of_ints", "1=2", "--C.dict_of_ints", "3=4"] config = cl.load_config(argv) c = C(config=config) assert c.dict_of_ints == {1: 2, 3: 4} class CBase(Configurable): a = List().tag(config=True) b = List(Integer()).tag(config=True, multiplicity="*") c = List().tag(config=True, multiplicity="append") adict = Dict().tag(config=True) class CSub(CBase): d = Tuple().tag(config=True) e = Tuple().tag(config=True, multiplicity="+") bdict = Dict().tag(config=True, multiplicity="*") class TestArgParseKVCL(TestKeyValueCL): klass = KVArgParseConfigLoader # type:ignore def test_no_cast_literals(self): cl = self.klass(log=log) # type:ignore # test ipython -c 1 doesn't cast to int argv = ["-c", "1"] config = cl.load_config(argv, aliases=dict(c="IPython.command_to_run")) assert config.IPython.command_to_run == "1" def test_int_literals(self): cl = self.klass(log=log) # type:ignore # test ipython -c 1 doesn't cast to int argv = ["-c", "1"] config = cl.load_config(argv, aliases=dict(c="IPython.command_to_run")) assert config.IPython.command_to_run == "1" def test_unicode_alias(self): cl = self.klass(log=log) # type:ignore argv = ["--a=épsîlön"] config = cl.load_config(argv, aliases=dict(a="A.a")) print(dict(config)) print(cl.extra_args) print(cl.aliases) self.assertEqual(config.A.a, "épsîlön") def test_expanduser2(self): cl = self.klass(log=log) # type:ignore argv = ["-a", "~/1/2/3", "--b", "'~/1/2/3'"] config = cl.load_config(argv, aliases=dict(a="A.a", b="A.b")) class A(Configurable): a = Unicode(config=True) b = Unicode(config=True) a = A(config=config) self.assertEqual(a.a, os.path.expanduser("~/1/2/3")) self.assertEqual(a.b, "~/1/2/3") def test_eval(self): cl = self.klass(log=log) # type:ignore argv = ["-c", "a=5"] config = cl.load_config(argv, aliases=dict(c="A.c")) self.assertEqual(config.A.c, "a=5") def test_seq_traits(self): cl = self.klass(log=log, classes=(CBase, CSub)) # type:ignore aliases = {"a3": "CBase.c", "a5": "CSub.e"} argv = ( "--CBase.a A --CBase.a 2 --CBase.b 1 --CBase.b 3 --a3 AA --CBase.c BB " "--CSub.d 1 --CSub.d BBB --CSub.e 1 --CSub.e=bcd a b c " ).split() config = cl.load_config(argv, aliases=aliases) assert cl.extra_args == ["a", "b", "c"] assert config.CBase.a == ["A", "2"] assert config.CBase.b == [1, 3] self.assertEqual(config.CBase.c, ["AA", "BB"]) assert config.CSub.d == ("1", "BBB") assert config.CSub.e == ("1", "bcd") def test_seq_traits_single_empty_string(self): cl = self.klass(log=log, classes=(CBase,)) # type:ignore aliases = {"seqopt": "CBase.c"} argv = ["--seqopt", ""] config = cl.load_config(argv, aliases=aliases) self.assertEqual(config.CBase.c, [""]) def test_dict_traits(self): cl = self.klass(log=log, classes=(CBase, CSub)) # type:ignore aliases = {"D": "CBase.adict", "E": "CSub.bdict"} argv = ["-D", "k1=v1", "-D=k2=2", "-D", "k3=v 3", "-E", "k=v", "-E", "22=222"] config = cl.load_config(argv, aliases=aliases) c = CSub(config=config) assert c.adict == {"k1": "v1", "k2": "2", "k3": "v 3"} assert c.bdict == {"k": "v", "22": "222"} def test_mixed_seq_positional(self): aliases = {"c": "Class.trait"} cl = self.klass(log=log, aliases=aliases) # type:ignore assignments = [("-c", "1"), ("--Class.trait=2",), ("--c=3",), ("--Class.trait", "4")] positionals = ["a", "b", "c"] # test with positionals at any index for idx in range(len(assignments) + 1): argv_parts = assignments[:] argv_parts[idx:idx] = (positionals,) # type:ignore argv = list(chain(*argv_parts)) config = cl.load_config(argv) assert config.Class.trait == ["1", "2", "3", "4"] assert cl.extra_args == ["a", "b", "c"] def test_split_positional(self): """Splitting positionals across flags is no longer allowed in traitlets 5""" cl = self.klass(log=log) # type:ignore argv = ["a", "--Class.trait=5", "b"] with pytest.raises(SystemExit): cl.load_config(argv) class TestConfig(TestCase): def test_setget(self): c = Config() c.a = 10 self.assertEqual(c.a, 10) self.assertEqual("b" in c, False) def test_auto_section(self): c = Config() self.assertNotIn("A", c) assert not c._has_section("A") A = c.A A.foo = "hi there" self.assertIn("A", c) assert c._has_section("A") self.assertEqual(c.A.foo, "hi there") del c.A self.assertEqual(c.A, Config()) def test_merge_doesnt_exist(self): c1 = Config() c2 = Config() c2.bar = 10 c2.Foo.bar = 10 c1.merge(c2) self.assertEqual(c1.Foo.bar, 10) self.assertEqual(c1.bar, 10) c2.Bar.bar = 10 c1.merge(c2) self.assertEqual(c1.Bar.bar, 10) def test_merge_exists(self): c1 = Config() c2 = Config() c1.Foo.bar = 10 c1.Foo.bam = 30 c2.Foo.bar = 20 c2.Foo.wow = 40 c1.merge(c2) self.assertEqual(c1.Foo.bam, 30) self.assertEqual(c1.Foo.bar, 20) self.assertEqual(c1.Foo.wow, 40) c2.Foo.Bam.bam = 10 c1.merge(c2) self.assertEqual(c1.Foo.Bam.bam, 10) def test_deepcopy(self): c1 = Config() c1.Foo.bar = 10 c1.Foo.bam = 30 c1.a = "asdf" c1.b = range(10) c1.Test.logger = logging.Logger("test") c1.Test.get_logger = logging.getLogger("test") c2 = copy.deepcopy(c1) self.assertEqual(c1, c2) self.assertTrue(c1 is not c2) self.assertTrue(c1.Foo is not c2.Foo) self.assertTrue(c1.Test is not c2.Test) self.assertTrue(c1.Test.logger is c2.Test.logger) self.assertTrue(c1.Test.get_logger is c2.Test.get_logger) def test_builtin(self): c1 = Config() c1.format = "json" def test_fromdict(self): c1 = Config({"Foo": {"bar": 1}}) self.assertEqual(c1.Foo.__class__, Config) self.assertEqual(c1.Foo.bar, 1) def test_fromdictmerge(self): c1 = Config() c2 = Config({"Foo": {"bar": 1}}) c1.merge(c2) self.assertEqual(c1.Foo.__class__, Config) self.assertEqual(c1.Foo.bar, 1) def test_fromdictmerge2(self): c1 = Config({"Foo": {"baz": 2}}) c2 = Config({"Foo": {"bar": 1}}) c1.merge(c2) self.assertEqual(c1.Foo.__class__, Config) self.assertEqual(c1.Foo.bar, 1) self.assertEqual(c1.Foo.baz, 2) self.assertNotIn("baz", c2.Foo) def test_contains(self): c1 = Config({"Foo": {"baz": 2}}) c2 = Config({"Foo": {"bar": 1}}) self.assertIn("Foo", c1) self.assertIn("Foo.baz", c1) self.assertIn("Foo.bar", c2) self.assertNotIn("Foo.bar", c1) def test_pickle_config(self): cfg = Config() cfg.Foo.bar = 1 pcfg = pickle.dumps(cfg) cfg2 = pickle.loads(pcfg) self.assertEqual(cfg2, cfg) def test_getattr_section(self): cfg = Config() self.assertNotIn("Foo", cfg) Foo = cfg.Foo assert isinstance(Foo, Config) self.assertIn("Foo", cfg) def test_getitem_section(self): cfg = Config() self.assertNotIn("Foo", cfg) Foo = cfg["Foo"] assert isinstance(Foo, Config) self.assertIn("Foo", cfg) def test_getattr_not_section(self): cfg = Config() self.assertNotIn("foo", cfg) foo = cfg.foo assert isinstance(foo, LazyConfigValue) self.assertIn("foo", cfg) def test_getattr_private_missing(self): cfg = Config() self.assertNotIn("_repr_html_", cfg) with self.assertRaises(AttributeError): _ = cfg._repr_html_ self.assertNotIn("_repr_html_", cfg) self.assertEqual(len(cfg), 0) def test_lazy_config_repr(self): cfg = Config() cfg.Class.lazy.append(1) cfg_repr = repr(cfg) assert "" in cfg_repr assert "value=" not in cfg_repr cfg.Class.lazy.get_value([0]) repr2 = repr(cfg) assert repr([0, 1]) in repr2 assert "value=" in repr2 def test_getitem_not_section(self): cfg = Config() self.assertNotIn("foo", cfg) foo = cfg["foo"] assert isinstance(foo, LazyConfigValue) self.assertIn("foo", cfg) def test_merge_no_copies(self): c = Config() c2 = Config() c2.Foo.trait = [] c.merge(c2) c2.Foo.trait.append(1) self.assertIs(c.Foo, c2.Foo) self.assertEqual(c.Foo.trait, [1]) self.assertEqual(c2.Foo.trait, [1]) def test_merge_multi_lazy(self): """ With multiple config files (systemwide and users), we want compounding. If systemwide overwrite and user append, we want both in the right order. """ c1 = Config() c2 = Config() c1.Foo.trait = [1] c2.Foo.trait.append(2) c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait, [1, 2]) def test_merge_multi_lazyII(self): """ With multiple config files (systemwide and users), we want compounding. If both are lazy we still want a lazy config. """ c1 = Config() c2 = Config() c1.Foo.trait.append(1) c2.Foo.trait.append(2) c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait._extend, [1, 2]) def test_merge_multi_lazy_III(self): """ With multiple config files (systemwide and users), we want compounding. Prepend should prepend in the right order. """ c1 = Config() c2 = Config() c1.Foo.trait = [1] c2.Foo.trait.prepend([0]) c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait, [0, 1]) def test_merge_multi_lazy_IV(self): """ With multiple config files (systemwide and users), we want compounding. Both prepending should be lazy """ c1 = Config() c2 = Config() c1.Foo.trait.prepend([1]) c2.Foo.trait.prepend([0]) c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait._prepend, [0, 1]) def test_merge_multi_lazy_update_I(self): """ With multiple config files (systemwide and users), we want compounding. dict update should be in the right order. """ c1 = Config() c2 = Config() c1.Foo.trait = {"a": 1, "z": 26} c2.Foo.trait.update({"a": 0, "b": 1}) c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait, {"a": 0, "b": 1, "z": 26}) def test_merge_multi_lazy_update_II(self): """ With multiple config files (systemwide and users), we want compounding. Later dict overwrite laziness """ c1 = Config() c2 = Config() c1.Foo.trait.update({"a": 0, "b": 1}) c2.Foo.trait = {"a": 1, "z": 26} c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait, {"a": 1, "z": 26}) def test_merge_multi_lazy_update_III(self): """ With multiple config files (systemwide and users), we want compounding. Later dict overwrite laziness """ c1 = Config() c2 = Config() c1.Foo.trait.update({"a": 0, "b": 1}) c2.Foo.trait.update({"a": 1, "z": 26}) c = Config() c.merge(c1) c.merge(c2) self.assertEqual(c.Foo.trait._update, {"a": 1, "z": 26, "b": 1}) ipython-traitlets-a3e321a/tests/test_traitlets.py000066400000000000000000002354141461045054400224200ustar00rootroot00000000000000"""Tests for traitlets.traitlets.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. # # Adapted from enthought.traits, Copyright (c) Enthought, Inc., # also under the terms of the Modified BSD License. from __future__ import annotations import pickle import re import typing as t from unittest import TestCase import pytest from traitlets import ( All, Any, BaseDescriptor, Bool, Bytes, Callable, CBytes, CFloat, CInt, CLong, Complex, CRegExp, CUnicode, Dict, DottedObjectName, Enum, Float, ForwardDeclaredInstance, ForwardDeclaredType, HasDescriptors, HasTraits, Instance, Int, Integer, List, Long, MetaHasTraits, ObjectName, Set, TCPAddress, This, TraitError, TraitType, Tuple, Type, Undefined, Unicode, Union, default, directional_link, link, observe, observe_compat, traitlets, validate, ) from traitlets.utils import cast_unicode from ._warnings import expected_warnings def change_dict(*ordered_values): change_names = ("name", "old", "new", "owner", "type") return dict(zip(change_names, ordered_values)) # ----------------------------------------------------------------------------- # Helper classes for testing # ----------------------------------------------------------------------------- class HasTraitsStub(HasTraits): def notify_change(self, change): self._notify_name = change["name"] self._notify_old = change["old"] self._notify_new = change["new"] self._notify_type = change["type"] class CrossValidationStub(HasTraits): _cross_validation_lock = False # ----------------------------------------------------------------------------- # Test classes # ----------------------------------------------------------------------------- class TestTraitType(TestCase): def test_get_undefined(self): class A(HasTraits): a = TraitType a = A() assert a.a is Undefined # type:ignore def test_set(self): class A(HasTraitsStub): a = TraitType a = A() a.a = 10 # type:ignore self.assertEqual(a.a, 10) self.assertEqual(a._notify_name, "a") self.assertEqual(a._notify_old, Undefined) self.assertEqual(a._notify_new, 10) def test_validate(self): class MyTT(TraitType[int, int]): def validate(self, inst, value): return -1 class A(HasTraitsStub): tt = MyTT a = A() a.tt = 10 # type:ignore self.assertEqual(a.tt, -1) a = A(tt=11) self.assertEqual(a.tt, -1) def test_default_validate(self): class MyIntTT(TraitType[int, int]): def validate(self, obj, value): if isinstance(value, int): return value self.error(obj, value) class A(HasTraits): tt = MyIntTT(10) a = A() self.assertEqual(a.tt, 10) # Defaults are validated when the HasTraits is instantiated class B(HasTraits): tt = MyIntTT("bad default") self.assertRaises(TraitError, getattr, B(), "tt") def test_info(self): class A(HasTraits): tt = TraitType a = A() self.assertEqual(A.tt.info(), "any value") # type:ignore def test_error(self): class A(HasTraits): tt = TraitType[int, int]() a = A() self.assertRaises(TraitError, A.tt.error, a, 10) def test_deprecated_dynamic_initializer(self): class A(HasTraits): x = Int(10) def _x_default(self): return 11 class B(A): x = Int(20) class C(A): def _x_default(self): return 21 a = A() self.assertEqual(a._trait_values, {}) self.assertEqual(a.x, 11) self.assertEqual(a._trait_values, {"x": 11}) b = B() self.assertEqual(b.x, 20) self.assertEqual(b._trait_values, {"x": 20}) c = C() self.assertEqual(c._trait_values, {}) self.assertEqual(c.x, 21) self.assertEqual(c._trait_values, {"x": 21}) # Ensure that the base class remains unmolested when the _default # initializer gets overridden in a subclass. a = A() c = C() self.assertEqual(a._trait_values, {}) self.assertEqual(a.x, 11) self.assertEqual(a._trait_values, {"x": 11}) def test_deprecated_method_warnings(self): with expected_warnings([]): class ShouldntWarn(HasTraits): x = Integer() @default("x") def _x_default(self): return 10 @validate("x") def _x_validate(self, proposal): return proposal.value @observe("x") def _x_changed(self, change): pass obj = ShouldntWarn() obj.x = 5 assert obj.x == 5 with expected_warnings(["@validate", "@observe"]) as w: class ShouldWarn(HasTraits): x = Integer() def _x_default(self): return 10 def _x_validate(self, value, _): return value def _x_changed(self): pass obj = ShouldWarn() # type:ignore obj.x = 5 assert obj.x == 5 def test_dynamic_initializer(self): class A(HasTraits): x = Int(10) @default("x") def _default_x(self): return 11 class B(A): x = Int(20) class C(A): @default("x") def _default_x(self): return 21 a = A() self.assertEqual(a._trait_values, {}) self.assertEqual(a.x, 11) self.assertEqual(a._trait_values, {"x": 11}) b = B() self.assertEqual(b.x, 20) self.assertEqual(b._trait_values, {"x": 20}) c = C() self.assertEqual(c._trait_values, {}) self.assertEqual(c.x, 21) self.assertEqual(c._trait_values, {"x": 21}) # Ensure that the base class remains unmolested when the _default # initializer gets overridden in a subclass. a = A() c = C() self.assertEqual(a._trait_values, {}) self.assertEqual(a.x, 11) self.assertEqual(a._trait_values, {"x": 11}) def test_tag_metadata(self): class MyIntTT(TraitType[int, int]): metadata = {"a": 1, "b": 2} a = MyIntTT(10).tag(b=3, c=4) self.assertEqual(a.metadata, {"a": 1, "b": 3, "c": 4}) def test_metadata_localized_instance(self): class MyIntTT(TraitType[int, int]): metadata = {"a": 1, "b": 2} a = MyIntTT(10) b = MyIntTT(10) a.metadata["c"] = 3 # make sure that changing a's metadata didn't change b's metadata self.assertNotIn("c", b.metadata) def test_union_metadata(self): class Foo(HasTraits): bar = (Int().tag(ta=1) | Dict().tag(ta=2, ti="b")).tag(ti="a") foo = Foo() # At this point, no value has been set for bar, so value-specific # is not set. self.assertEqual(foo.trait_metadata("bar", "ta"), None) self.assertEqual(foo.trait_metadata("bar", "ti"), "a") foo.bar = {} self.assertEqual(foo.trait_metadata("bar", "ta"), 2) self.assertEqual(foo.trait_metadata("bar", "ti"), "b") foo.bar = 1 self.assertEqual(foo.trait_metadata("bar", "ta"), 1) self.assertEqual(foo.trait_metadata("bar", "ti"), "a") def test_union_default_value(self): class Foo(HasTraits): bar = Union([Dict(), Int()], default_value=1) foo = Foo() self.assertEqual(foo.bar, 1) def test_union_validation_priority(self): class Foo(HasTraits): bar = Union([CInt(), Unicode()]) foo = Foo() foo.bar = "1" # validation in order of the TraitTypes given self.assertEqual(foo.bar, 1) def test_union_trait_default_value(self): class Foo(HasTraits): bar = Union([Dict(), Int()]) self.assertEqual(Foo().bar, {}) def test_deprecated_metadata_access(self): class MyIntTT(TraitType[int, int]): metadata = {"a": 1, "b": 2} a = MyIntTT(10) with expected_warnings(["use the instance .metadata dictionary directly"] * 2): a.set_metadata("key", "value") v = a.get_metadata("key") self.assertEqual(v, "value") with expected_warnings(["use the instance .help string directly"] * 2): a.set_metadata("help", "some help") v = a.get_metadata("help") self.assertEqual(v, "some help") def test_trait_types_deprecated(self): with expected_warnings(["Traits should be given as instances"]): class C(HasTraits): t = Int def test_trait_types_list_deprecated(self): with expected_warnings(["Traits should be given as instances"]): class C(HasTraits): t = List(Int) def test_trait_types_tuple_deprecated(self): with expected_warnings(["Traits should be given as instances"]): class C(HasTraits): t = Tuple(Int) def test_trait_types_dict_deprecated(self): with expected_warnings(["Traits should be given as instances"]): class C(HasTraits): t = Dict(Int) class TestHasDescriptorsMeta(TestCase): def test_metaclass(self): self.assertEqual(type(HasTraits), MetaHasTraits) class A(HasTraits): a = Int() a = A() self.assertEqual(type(a.__class__), MetaHasTraits) self.assertEqual(a.a, 0) a.a = 10 self.assertEqual(a.a, 10) class B(HasTraits): b = Int() b = B() self.assertEqual(b.b, 0) b.b = 10 self.assertEqual(b.b, 10) class C(HasTraits): c = Int(30) c = C() self.assertEqual(c.c, 30) c.c = 10 self.assertEqual(c.c, 10) def test_this_class(self): class A(HasTraits): t = This["A"]() tt = This["A"]() class B(A): tt = This["A"]() ttt = This["A"]() self.assertEqual(A.t.this_class, A) self.assertEqual(B.t.this_class, A) self.assertEqual(B.tt.this_class, B) self.assertEqual(B.ttt.this_class, B) class TestHasDescriptors(TestCase): def test_setup_instance(self): class FooDescriptor(BaseDescriptor): def instance_init(self, inst): foo = inst.foo # instance should have the attr class HasFooDescriptors(HasDescriptors): fd = FooDescriptor() def setup_instance(self, *args, **kwargs): self.foo = kwargs.get("foo", None) super().setup_instance(*args, **kwargs) hfd = HasFooDescriptors(foo="bar") class TestHasTraitsNotify(TestCase): def setUp(self): self._notify1 = [] self._notify2 = [] def notify1(self, name, old, new): self._notify1.append((name, old, new)) def notify2(self, name, old, new): self._notify2.append((name, old, new)) def test_notify_all(self): class A(HasTraits): a = Int() b = Float() a = A() a.on_trait_change(self.notify1) a.a = 0 self.assertEqual(len(self._notify1), 0) a.b = 0.0 self.assertEqual(len(self._notify1), 0) a.a = 10 self.assertTrue(("a", 0, 10) in self._notify1) a.b = 10.0 self.assertTrue(("b", 0.0, 10.0) in self._notify1) self.assertRaises(TraitError, setattr, a, "a", "bad string") self.assertRaises(TraitError, setattr, a, "b", "bad string") self._notify1 = [] a.on_trait_change(self.notify1, remove=True) a.a = 20 a.b = 20.0 self.assertEqual(len(self._notify1), 0) def test_notify_one(self): class A(HasTraits): a = Int() b = Float() a = A() a.on_trait_change(self.notify1, "a") a.a = 0 self.assertEqual(len(self._notify1), 0) a.a = 10 self.assertTrue(("a", 0, 10) in self._notify1) self.assertRaises(TraitError, setattr, a, "a", "bad string") def test_subclass(self): class A(HasTraits): a = Int() class B(A): b = Float() b = B() self.assertEqual(b.a, 0) self.assertEqual(b.b, 0.0) b.a = 100 b.b = 100.0 self.assertEqual(b.a, 100) self.assertEqual(b.b, 100.0) def test_notify_subclass(self): class A(HasTraits): a = Int() class B(A): b = Float() b = B() b.on_trait_change(self.notify1, "a") b.on_trait_change(self.notify2, "b") b.a = 0 b.b = 0.0 self.assertEqual(len(self._notify1), 0) self.assertEqual(len(self._notify2), 0) b.a = 10 b.b = 10.0 self.assertTrue(("a", 0, 10) in self._notify1) self.assertTrue(("b", 0.0, 10.0) in self._notify2) def test_static_notify(self): class A(HasTraits): a = Int() _notify1 = [] def _a_changed(self, name, old, new): self._notify1.append((name, old, new)) a = A() a.a = 0 # This is broken!!! self.assertEqual(len(a._notify1), 0) a.a = 10 self.assertTrue(("a", 0, 10) in a._notify1) class B(A): b = Float() _notify2 = [] def _b_changed(self, name, old, new): self._notify2.append((name, old, new)) b = B() b.a = 10 b.b = 10.0 self.assertTrue(("a", 0, 10) in b._notify1) self.assertTrue(("b", 0.0, 10.0) in b._notify2) def test_notify_args(self): def callback0(): self.cb = () def callback1(name): self.cb = (name,) # type:ignore def callback2(name, new): self.cb = (name, new) # type:ignore def callback3(name, old, new): self.cb = (name, old, new) # type:ignore def callback4(name, old, new, obj): self.cb = (name, old, new, obj) # type:ignore class A(HasTraits): a = Int() a = A() a.on_trait_change(callback0, "a") a.a = 10 self.assertEqual(self.cb, ()) a.on_trait_change(callback0, "a", remove=True) a.on_trait_change(callback1, "a") a.a = 100 self.assertEqual(self.cb, ("a",)) a.on_trait_change(callback1, "a", remove=True) a.on_trait_change(callback2, "a") a.a = 1000 self.assertEqual(self.cb, ("a", 1000)) a.on_trait_change(callback2, "a", remove=True) a.on_trait_change(callback3, "a") a.a = 10000 self.assertEqual(self.cb, ("a", 1000, 10000)) a.on_trait_change(callback3, "a", remove=True) a.on_trait_change(callback4, "a") a.a = 100000 self.assertEqual(self.cb, ("a", 10000, 100000, a)) self.assertEqual(len(a._trait_notifiers["a"]["change"]), 1) a.on_trait_change(callback4, "a", remove=True) self.assertEqual(len(a._trait_notifiers["a"]["change"]), 0) def test_notify_only_once(self): class A(HasTraits): listen_to = ["a"] a = Int(0) b = 0 def __init__(self, **kwargs): super().__init__(**kwargs) self.on_trait_change(self.listener1, ["a"]) def listener1(self, name, old, new): self.b += 1 class B(A): c = 0 d = 0 def __init__(self, **kwargs): super().__init__(**kwargs) self.on_trait_change(self.listener2) def listener2(self, name, old, new): self.c += 1 def _a_changed(self, name, old, new): self.d += 1 b = B() b.a += 1 self.assertEqual(b.b, b.c) self.assertEqual(b.b, b.d) b.a += 1 self.assertEqual(b.b, b.c) self.assertEqual(b.b, b.d) class TestObserveDecorator(TestCase): def setUp(self): self._notify1 = [] self._notify2 = [] def notify1(self, change): self._notify1.append(change) def notify2(self, change): self._notify2.append(change) def test_notify_all(self): class A(HasTraits): a = Int() b = Float() a = A() a.observe(self.notify1) a.a = 0 self.assertEqual(len(self._notify1), 0) a.b = 0.0 self.assertEqual(len(self._notify1), 0) a.a = 10 change = change_dict("a", 0, 10, a, "change") self.assertTrue(change in self._notify1) a.b = 10.0 change = change_dict("b", 0.0, 10.0, a, "change") self.assertTrue(change in self._notify1) self.assertRaises(TraitError, setattr, a, "a", "bad string") self.assertRaises(TraitError, setattr, a, "b", "bad string") self._notify1 = [] a.unobserve(self.notify1) a.a = 20 a.b = 20.0 self.assertEqual(len(self._notify1), 0) def test_notify_one(self): class A(HasTraits): a = Int() b = Float() a = A() a.observe(self.notify1, "a") a.a = 0 self.assertEqual(len(self._notify1), 0) a.a = 10 change = change_dict("a", 0, 10, a, "change") self.assertTrue(change in self._notify1) self.assertRaises(TraitError, setattr, a, "a", "bad string") def test_subclass(self): class A(HasTraits): a = Int() class B(A): b = Float() b = B() self.assertEqual(b.a, 0) self.assertEqual(b.b, 0.0) b.a = 100 b.b = 100.0 self.assertEqual(b.a, 100) self.assertEqual(b.b, 100.0) def test_notify_subclass(self): class A(HasTraits): a = Int() class B(A): b = Float() b = B() b.observe(self.notify1, "a") b.observe(self.notify2, "b") b.a = 0 b.b = 0.0 self.assertEqual(len(self._notify1), 0) self.assertEqual(len(self._notify2), 0) b.a = 10 b.b = 10.0 change = change_dict("a", 0, 10, b, "change") self.assertTrue(change in self._notify1) change = change_dict("b", 0.0, 10.0, b, "change") self.assertTrue(change in self._notify2) def test_static_notify(self): class A(HasTraits): a = Int() b = Int() _notify1 = [] _notify_any = [] @observe("a") def _a_changed(self, change): self._notify1.append(change) @observe(All) def _any_changed(self, change): self._notify_any.append(change) a = A() a.a = 0 self.assertEqual(len(a._notify1), 0) a.a = 10 change = change_dict("a", 0, 10, a, "change") self.assertTrue(change in a._notify1) a.b = 1 self.assertEqual(len(a._notify_any), 2) change = change_dict("b", 0, 1, a, "change") self.assertTrue(change in a._notify_any) class B(A): b = Float() # type:ignore _notify2 = [] @observe("b") def _b_changed(self, change): self._notify2.append(change) b = B() b.a = 10 b.b = 10.0 # type:ignore change = change_dict("a", 0, 10, b, "change") self.assertTrue(change in b._notify1) change = change_dict("b", 0.0, 10.0, b, "change") self.assertTrue(change in b._notify2) def test_notify_args(self): def callback0(): self.cb = () def callback1(change): self.cb = change class A(HasTraits): a = Int() a = A() a.on_trait_change(callback0, "a") a.a = 10 self.assertEqual(self.cb, ()) a.unobserve(callback0, "a") a.observe(callback1, "a") a.a = 100 change = change_dict("a", 10, 100, a, "change") self.assertEqual(self.cb, change) self.assertEqual(len(a._trait_notifiers["a"]["change"]), 1) a.unobserve(callback1, "a") self.assertEqual(len(a._trait_notifiers["a"]["change"]), 0) def test_notify_only_once(self): class A(HasTraits): listen_to = ["a"] a = Int(0) b = 0 def __init__(self, **kwargs): super().__init__(**kwargs) self.observe(self.listener1, ["a"]) def listener1(self, change): self.b += 1 class B(A): c = 0 d = 0 def __init__(self, **kwargs): super().__init__(**kwargs) self.observe(self.listener2) def listener2(self, change): self.c += 1 @observe("a") def _a_changed(self, change): self.d += 1 b = B() b.a += 1 self.assertEqual(b.b, b.c) self.assertEqual(b.b, b.d) b.a += 1 self.assertEqual(b.b, b.c) self.assertEqual(b.b, b.d) class TestHasTraits(TestCase): def test_trait_names(self): class A(HasTraits): i = Int() f = Float() a = A() self.assertEqual(sorted(a.trait_names()), ["f", "i"]) self.assertEqual(sorted(A.class_trait_names()), ["f", "i"]) self.assertTrue(a.has_trait("f")) self.assertFalse(a.has_trait("g")) def test_trait_has_value(self): class A(HasTraits): i = Int() f = Float() a = A() self.assertFalse(a.trait_has_value("f")) self.assertFalse(a.trait_has_value("g")) a.i = 1 a.f self.assertTrue(a.trait_has_value("i")) self.assertTrue(a.trait_has_value("f")) def test_trait_metadata_deprecated(self): with expected_warnings([r"metadata should be set using the \.tag\(\) method"]): class A(HasTraits): i = Int(config_key="MY_VALUE") a = A() self.assertEqual(a.trait_metadata("i", "config_key"), "MY_VALUE") def test_trait_metadata(self): class A(HasTraits): i = Int().tag(config_key="MY_VALUE") a = A() self.assertEqual(a.trait_metadata("i", "config_key"), "MY_VALUE") def test_trait_metadata_default(self): class A(HasTraits): i = Int() a = A() self.assertEqual(a.trait_metadata("i", "config_key"), None) self.assertEqual(a.trait_metadata("i", "config_key", "default"), "default") def test_traits(self): class A(HasTraits): i = Int() f = Float() a = A() self.assertEqual(a.traits(), dict(i=A.i, f=A.f)) self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f)) def test_traits_metadata(self): class A(HasTraits): i = Int().tag(config_key="VALUE1", other_thing="VALUE2") f = Float().tag(config_key="VALUE3", other_thing="VALUE2") j = Int(0) a = A() self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j)) traits = a.traits(config_key="VALUE1", other_thing="VALUE2") self.assertEqual(traits, dict(i=A.i)) # This passes, but it shouldn't because I am replicating a bug in # traits. traits = a.traits(config_key=lambda v: True) self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j)) def test_traits_metadata_deprecated(self): with expected_warnings([r"metadata should be set using the \.tag\(\) method"] * 2): class A(HasTraits): i = Int(config_key="VALUE1", other_thing="VALUE2") f = Float(config_key="VALUE3", other_thing="VALUE2") j = Int(0) a = A() self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j)) traits = a.traits(config_key="VALUE1", other_thing="VALUE2") self.assertEqual(traits, dict(i=A.i)) # This passes, but it shouldn't because I am replicating a bug in # traits. traits = a.traits(config_key=lambda v: True) self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j)) def test_init(self): class A(HasTraits): i = Int() x = Float() a = A(i=1, x=10.0) self.assertEqual(a.i, 1) self.assertEqual(a.x, 10.0) def test_positional_args(self): class A(HasTraits): i = Int(0) def __init__(self, i): super().__init__() self.i = i a = A(5) self.assertEqual(a.i, 5) # should raise TypeError if no positional arg given self.assertRaises(TypeError, A) # ----------------------------------------------------------------------------- # Tests for specific trait types # ----------------------------------------------------------------------------- class TestType(TestCase): def test_default(self): class B: pass class A(HasTraits): klass = Type(allow_none=True) a = A() self.assertEqual(a.klass, object) a.klass = B self.assertEqual(a.klass, B) self.assertRaises(TraitError, setattr, a, "klass", 10) def test_default_options(self): class B: pass class C(B): pass class A(HasTraits): # Different possible combinations of options for default_value # and klass. default_value=None is only valid with allow_none=True. k1 = Type() k2 = Type(None, allow_none=True) k3 = Type(B) k4 = Type(klass=B) k5 = Type(default_value=None, klass=B, allow_none=True) k6 = Type(default_value=C, klass=B) self.assertIs(A.k1.default_value, object) self.assertIs(A.k1.klass, object) self.assertIs(A.k2.default_value, None) self.assertIs(A.k2.klass, object) self.assertIs(A.k3.default_value, B) self.assertIs(A.k3.klass, B) self.assertIs(A.k4.default_value, B) self.assertIs(A.k4.klass, B) self.assertIs(A.k5.default_value, None) self.assertIs(A.k5.klass, B) self.assertIs(A.k6.default_value, C) self.assertIs(A.k6.klass, B) a = A() self.assertIs(a.k1, object) self.assertIs(a.k2, None) self.assertIs(a.k3, B) self.assertIs(a.k4, B) self.assertIs(a.k5, None) self.assertIs(a.k6, C) def test_value(self): class B: pass class C: pass class A(HasTraits): klass = Type(B) a = A() self.assertEqual(a.klass, B) self.assertRaises(TraitError, setattr, a, "klass", C) self.assertRaises(TraitError, setattr, a, "klass", object) a.klass = B def test_allow_none(self): class B: pass class C(B): pass class A(HasTraits): klass = Type(B) a = A() self.assertEqual(a.klass, B) self.assertRaises(TraitError, setattr, a, "klass", None) a.klass = C self.assertEqual(a.klass, C) def test_validate_klass(self): class A(HasTraits): klass = Type("no strings allowed") self.assertRaises(ImportError, A) class A(HasTraits): # type:ignore klass = Type("rub.adub.Duck") self.assertRaises(ImportError, A) def test_validate_default(self): class B: pass class A(HasTraits): klass = Type("bad default", B) self.assertRaises(ImportError, A) class C(HasTraits): klass = Type(None, B) self.assertRaises(TraitError, getattr, C(), "klass") def test_str_klass(self): class A(HasTraits): klass = Type("traitlets.config.Config") from traitlets.config import Config a = A() a.klass = Config self.assertEqual(a.klass, Config) self.assertRaises(TraitError, setattr, a, "klass", 10) def test_set_str_klass(self): class A(HasTraits): klass = Type() a = A(klass="traitlets.config.Config") from traitlets.config import Config self.assertEqual(a.klass, Config) class TestInstance(TestCase): def test_basic(self): class Foo: pass class Bar(Foo): pass class Bah: pass class A(HasTraits): inst = Instance(Foo, allow_none=True) a = A() self.assertTrue(a.inst is None) a.inst = Foo() self.assertTrue(isinstance(a.inst, Foo)) a.inst = Bar() self.assertTrue(isinstance(a.inst, Foo)) self.assertRaises(TraitError, setattr, a, "inst", Foo) self.assertRaises(TraitError, setattr, a, "inst", Bar) self.assertRaises(TraitError, setattr, a, "inst", Bah()) def test_default_klass(self): class Foo: pass class Bar(Foo): pass class Bah: pass class FooInstance(Instance[Foo]): klass = Foo class A(HasTraits): inst = FooInstance(allow_none=True) a = A() self.assertTrue(a.inst is None) a.inst = Foo() self.assertTrue(isinstance(a.inst, Foo)) a.inst = Bar() self.assertTrue(isinstance(a.inst, Foo)) self.assertRaises(TraitError, setattr, a, "inst", Foo) self.assertRaises(TraitError, setattr, a, "inst", Bar) self.assertRaises(TraitError, setattr, a, "inst", Bah()) def test_unique_default_value(self): class Foo: pass class A(HasTraits): inst = Instance(Foo, (), {}) a = A() b = A() self.assertTrue(a.inst is not b.inst) def test_args_kw(self): class Foo: def __init__(self, c): self.c = c class Bar: pass class Bah: def __init__(self, c, d): self.c = c self.d = d class A(HasTraits): inst = Instance(Foo, (10,)) a = A() self.assertEqual(a.inst.c, 10) class B(HasTraits): inst = Instance(Bah, args=(10,), kw=dict(d=20)) b = B() self.assertEqual(b.inst.c, 10) self.assertEqual(b.inst.d, 20) class C(HasTraits): inst = Instance(Foo, allow_none=True) c = C() self.assertTrue(c.inst is None) def test_bad_default(self): class Foo: pass class A(HasTraits): inst = Instance(Foo) a = A() with self.assertRaises(TraitError): a.inst def test_instance(self): class Foo: pass def inner(): class A(HasTraits): inst = Instance(Foo()) # type:ignore self.assertRaises(TraitError, inner) class TestThis(TestCase): def test_this_class(self): class Foo(HasTraits): this = This["Foo"]() f = Foo() self.assertEqual(f.this, None) g = Foo() f.this = g self.assertEqual(f.this, g) self.assertRaises(TraitError, setattr, f, "this", 10) def test_this_inst(self): class Foo(HasTraits): this = This["Foo"]() f = Foo() f.this = Foo() self.assertTrue(isinstance(f.this, Foo)) def test_subclass(self): class Foo(HasTraits): t = This["Foo"]() class Bar(Foo): pass f = Foo() b = Bar() f.t = b b.t = f self.assertEqual(f.t, b) self.assertEqual(b.t, f) def test_subclass_override(self): class Foo(HasTraits): t = This["Foo"]() class Bar(Foo): t = This() f = Foo() b = Bar() f.t = b self.assertEqual(f.t, b) self.assertRaises(TraitError, setattr, b, "t", f) def test_this_in_container(self): class Tree(HasTraits): value = Unicode() leaves = List(This()) tree = Tree(value="foo", leaves=[Tree(value="bar"), Tree(value="buzz")]) with self.assertRaises(TraitError): tree.leaves = [1, 2] class TraitTestBase(TestCase): """A best testing class for basic trait types.""" def assign(self, value): self.obj.value = value # type:ignore def coerce(self, value): return value def test_good_values(self): if hasattr(self, "_good_values"): for value in self._good_values: self.assign(value) self.assertEqual(self.obj.value, self.coerce(value)) # type:ignore def test_bad_values(self): if hasattr(self, "_bad_values"): for value in self._bad_values: try: self.assertRaises(TraitError, self.assign, value) except AssertionError: assert False, value # noqa: PT015 def test_default_value(self): if hasattr(self, "_default_value"): self.assertEqual(self._default_value, self.obj.value) # type:ignore def test_allow_none(self): if ( hasattr(self, "_bad_values") and hasattr(self, "_good_values") and None in self._bad_values ): trait = self.obj.traits()["value"] # type:ignore try: trait.allow_none = True self._bad_values.remove(None) # skip coerce. Allow None casts None to None. self.assign(None) self.assertEqual(self.obj.value, None) # type:ignore self.test_good_values() self.test_bad_values() finally: # tear down trait.allow_none = False self._bad_values.append(None) def tearDown(self): # restore default value after tests, if set if hasattr(self, "_default_value"): self.obj.value = self._default_value # type:ignore class AnyTrait(HasTraits): value = Any() class AnyTraitTest(TraitTestBase): obj = AnyTrait() _default_value = None _good_values = [10.0, "ten", [10], {"ten": 10}, (10,), None, 1j] _bad_values: t.Any = [] class UnionTrait(HasTraits): value = Union([Type(), Bool()]) class UnionTraitTest(TraitTestBase): obj = UnionTrait(value="traitlets.config.Config") _good_values = [int, float, True] _bad_values = [[], (0,), 1j] class CallableTrait(HasTraits): value = Callable() class CallableTraitTest(TraitTestBase): obj = CallableTrait(value=lambda x: type(x)) _good_values = [int, sorted, lambda x: print(x)] _bad_values = [[], 1, ""] class OrTrait(HasTraits): value = Bool() | Unicode() class OrTraitTest(TraitTestBase): obj = OrTrait() _good_values = [True, False, "ten"] _bad_values = [[], (0,), 1j] class IntTrait(HasTraits): value = Int(99, min=-100) class TestInt(TraitTestBase): obj = IntTrait() _default_value = 99 _good_values = [10, -10] _bad_values = [ "ten", [10], {"ten": 10}, (10,), None, 1j, 10.1, -10.1, "10L", "-10L", "10.1", "-10.1", "10", "-10", -200, ] class CIntTrait(HasTraits): value = CInt("5") class TestCInt(TraitTestBase): obj = CIntTrait() _default_value = 5 _good_values = ["10", "-10", 10, 10.0, -10.0, 10.1] _bad_values = ["ten", [10], {"ten": 10}, (10,), None, 1j, "10.1"] def coerce(self, n): return int(n) class MinBoundCIntTrait(HasTraits): value = CInt("5", min=3) class TestMinBoundCInt(TestCInt): obj = MinBoundCIntTrait() # type:ignore _default_value = 5 _good_values = [3, 3.0, "3"] _bad_values = [2.6, 2, -3, -3.0] class LongTrait(HasTraits): value = Long(99) class TestLong(TraitTestBase): obj = LongTrait() _default_value = 99 _good_values = [10, -10] _bad_values = [ "ten", [10], {"ten": 10}, (10,), None, 1j, 10.1, -10.1, "10", "-10", "10L", "-10L", "10.1", "-10.1", ] class MinBoundLongTrait(HasTraits): value = Long(99, min=5) class TestMinBoundLong(TraitTestBase): obj = MinBoundLongTrait() _default_value = 99 _good_values = [5, 10] _bad_values = [4, -10] class MaxBoundLongTrait(HasTraits): value = Long(5, max=10) class TestMaxBoundLong(TraitTestBase): obj = MaxBoundLongTrait() _default_value = 5 _good_values = [10, -2] _bad_values = [11, 20] class CLongTrait(HasTraits): value = CLong("5") class TestCLong(TraitTestBase): obj = CLongTrait() _default_value = 5 _good_values = ["10", "-10", 10, 10.0, -10.0, 10.1] _bad_values = ["ten", [10], {"ten": 10}, (10,), None, 1j, "10.1"] def coerce(self, n): return int(n) class MaxBoundCLongTrait(HasTraits): value = CLong("5", max=10) class TestMaxBoundCLong(TestCLong): obj = MaxBoundCLongTrait() # type:ignore _default_value = 5 _good_values = [10, "10", 10.3] _bad_values = [11.0, "11"] class IntegerTrait(HasTraits): value = Integer(1) class TestInteger(TestLong): obj = IntegerTrait() # type:ignore _default_value = 1 def coerce(self, n): return int(n) class MinBoundIntegerTrait(HasTraits): value = Integer(5, min=3) class TestMinBoundInteger(TraitTestBase): obj = MinBoundIntegerTrait() _default_value = 5 _good_values = 3, 20 _bad_values = [2, -10] class MaxBoundIntegerTrait(HasTraits): value = Integer(1, max=3) class TestMaxBoundInteger(TraitTestBase): obj = MaxBoundIntegerTrait() _default_value = 1 _good_values = 3, -2 _bad_values = [4, 10] class FloatTrait(HasTraits): value = Float(99.0, max=200.0) class TestFloat(TraitTestBase): obj = FloatTrait() _default_value = 99.0 _good_values = [10, -10, 10.1, -10.1] _bad_values = [ "ten", [10], {"ten": 10}, (10,), None, 1j, "10", "-10", "10L", "-10L", "10.1", "-10.1", 201.0, ] class CFloatTrait(HasTraits): value = CFloat("99.0", max=200.0) class TestCFloat(TraitTestBase): obj = CFloatTrait() _default_value = 99.0 _good_values = [10, 10.0, 10.5, "10.0", "10", "-10"] _bad_values = ["ten", [10], {"ten": 10}, (10,), None, 1j, 200.1, "200.1"] def coerce(self, v): return float(v) class ComplexTrait(HasTraits): value = Complex(99.0 - 99.0j) class TestComplex(TraitTestBase): obj = ComplexTrait() _default_value = 99.0 - 99.0j _good_values = [ 10, -10, 10.1, -10.1, 10j, 10 + 10j, 10 - 10j, 10.1j, 10.1 + 10.1j, 10.1 - 10.1j, ] _bad_values = ["10L", "-10L", "ten", [10], {"ten": 10}, (10,), None] class BytesTrait(HasTraits): value = Bytes(b"string") class TestBytes(TraitTestBase): obj = BytesTrait() _default_value = b"string" _good_values = [b"10", b"-10", b"10L", b"-10L", b"10.1", b"-10.1", b"string"] _bad_values = [10, -10, 10.1, -10.1, 1j, [10], ["ten"], {"ten": 10}, (10,), None, "string"] class UnicodeTrait(HasTraits): value = Unicode("unicode") class TestUnicode(TraitTestBase): obj = UnicodeTrait() _default_value = "unicode" _good_values = ["10", "-10", "10L", "-10L", "10.1", "-10.1", "", "string", "€", b"bytestring"] _bad_values = [10, -10, 10.1, -10.1, 1j, [10], ["ten"], {"ten": 10}, (10,), None] def coerce(self, v): return cast_unicode(v) class ObjectNameTrait(HasTraits): value = ObjectName("abc") class TestObjectName(TraitTestBase): obj = ObjectNameTrait() _default_value = "abc" _good_values = ["a", "gh", "g9", "g_", "_G", "a345_"] _bad_values = [ 1, "", "€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]", None, object(), object, ] _good_values.append("þ") # þ=1 is valid in Python 3 (PEP 3131). class DottedObjectNameTrait(HasTraits): value = DottedObjectName("a.b") class TestDottedObjectName(TraitTestBase): obj = DottedObjectNameTrait() _default_value = "a.b" _good_values = ["A", "y.t", "y765.__repr__", "os.path.join"] _bad_values = [1, "abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None] _good_values.append("t.þ") class TCPAddressTrait(HasTraits): value = TCPAddress() class TestTCPAddress(TraitTestBase): obj = TCPAddressTrait() _default_value = ("127.0.0.1", 0) _good_values = [("localhost", 0), ("192.168.0.1", 1000), ("www.google.com", 80)] _bad_values = [(0, 0), ("localhost", 10.0), ("localhost", -1), None] class ListTrait(HasTraits): value = List(Int()) class TestList(TraitTestBase): obj = ListTrait() _default_value: t.List[t.Any] = [] _good_values = [[], [1], list(range(10)), (1, 2)] _bad_values = [10, [1, "a"], "a"] def coerce(self, value): if value is not None: value = list(value) return value class SetTrait(HasTraits): value = Set(Unicode()) class TestSet(TraitTestBase): obj = SetTrait() _default_value: t.Set[str] = set() _good_values = [{"a", "b"}, "ab"] _bad_values = [1] def coerce(self, value): if isinstance(value, str): # compatibility handling: convert string to set containing string value = {value} return value class Foo: pass class NoneInstanceListTrait(HasTraits): value = List(Instance(Foo)) class TestNoneInstanceList(TraitTestBase): obj = NoneInstanceListTrait() _default_value: t.List[t.Any] = [] _good_values = [[Foo(), Foo()], []] _bad_values = [[None], [Foo(), None]] class InstanceListTrait(HasTraits): value = List(Instance(__name__ + ".Foo")) class TestInstanceList(TraitTestBase): obj = InstanceListTrait() def test_klass(self): """Test that the instance klass is properly assigned.""" self.assertIs(self.obj.traits()["value"]._trait.klass, Foo) _default_value: t.List[t.Any] = [] _good_values = [[Foo(), Foo()], []] _bad_values = [ [ "1", 2, ], "1", [Foo], None, ] class UnionListTrait(HasTraits): value = List(Int() | Bool()) class TestUnionListTrait(TraitTestBase): obj = UnionListTrait() _default_value: t.List[t.Any] = [] _good_values = [[True, 1], [False, True]] _bad_values = [[1, "True"], False] class LenListTrait(HasTraits): value = List(Int(), [0], minlen=1, maxlen=2) class TestLenList(TraitTestBase): obj = LenListTrait() _default_value = [0] _good_values = [[1], [1, 2], (1, 2)] _bad_values = [10, [1, "a"], "a", [], list(range(3))] def coerce(self, value): if value is not None: value = list(value) return value class TupleTrait(HasTraits): value = Tuple(Int(allow_none=True), default_value=(1,)) class TestTupleTrait(TraitTestBase): obj = TupleTrait() _default_value = (1,) _good_values = [(1,), (0,), [1]] _bad_values = [10, (1, 2), ("a"), (), None] def coerce(self, value): if value is not None: value = tuple(value) return value def test_invalid_args(self): self.assertRaises(TypeError, Tuple, 5) self.assertRaises(TypeError, Tuple, default_value="hello") t = Tuple(Int(), CBytes(), default_value=(1, 5)) class LooseTupleTrait(HasTraits): value = Tuple((1, 2, 3)) class TestLooseTupleTrait(TraitTestBase): obj = LooseTupleTrait() _default_value = (1, 2, 3) _good_values = [(1,), [1], (0,), tuple(range(5)), tuple("hello"), ("a", 5), ()] _bad_values = [10, "hello", {}, None] def coerce(self, value): if value is not None: value = tuple(value) return value def test_invalid_args(self): self.assertRaises(TypeError, Tuple, 5) self.assertRaises(TypeError, Tuple, default_value="hello") t = Tuple(Int(), CBytes(), default_value=(1, 5)) class MultiTupleTrait(HasTraits): value = Tuple(Int(), Bytes(), default_value=[99, b"bottles"]) class TestMultiTuple(TraitTestBase): obj = MultiTupleTrait() _default_value = (99, b"bottles") _good_values = [(1, b"a"), (2, b"b")] _bad_values = ((), 10, b"a", (1, b"a", 3), (b"a", 1), (1, "a")) @pytest.mark.parametrize( "Trait", ( # noqa: PT007 List, Tuple, Set, Dict, Integer, Unicode, ), ) def test_allow_none_default_value(Trait): class C(HasTraits): t = Trait(default_value=None, allow_none=True) # test default value c = C() assert c.t is None # and in constructor c = C(t=None) assert c.t is None @pytest.mark.parametrize( "Trait, default_value", ((List, []), (Tuple, ()), (Set, set()), (Dict, {}), (Integer, 0), (Unicode, "")), # noqa: PT007 ) def test_default_value(Trait, default_value): class C(HasTraits): t = Trait() # test default value c = C() assert type(c.t) is type(default_value) assert c.t == default_value @pytest.mark.parametrize( "Trait, default_value", ((List, []), (Tuple, ()), (Set, set())), # noqa: PT007 ) def test_subclass_default_value(Trait, default_value): """Test deprecated default_value=None behavior for Container subclass traits""" class SubclassTrait(Trait): # type:ignore def __init__(self, default_value=None): super().__init__(default_value=default_value) class C(HasTraits): t = SubclassTrait() # test default value c = C() assert type(c.t) is type(default_value) assert c.t == default_value class CRegExpTrait(HasTraits): value = CRegExp(r"") class TestCRegExp(TraitTestBase): def coerce(self, value): return re.compile(value) obj = CRegExpTrait() _default_value = re.compile(r"") _good_values = [r"\d+", re.compile(r"\d+")] _bad_values = ["(", None, ()] class DictTrait(HasTraits): value = Dict() def test_dict_assignment(): d: t.Dict[str, int] = {} c = DictTrait() c.value = d d["a"] = 5 assert d == c.value assert c.value is d class UniformlyValueValidatedDictTrait(HasTraits): value = Dict(value_trait=Unicode(), default_value={"foo": "1"}) class TestInstanceUniformlyValueValidatedDict(TraitTestBase): obj = UniformlyValueValidatedDictTrait() _default_value = {"foo": "1"} _good_values = [{"foo": "0", "bar": "1"}] _bad_values = [{"foo": 0, "bar": "1"}] class NonuniformlyValueValidatedDictTrait(HasTraits): value = Dict(per_key_traits={"foo": Int()}, default_value={"foo": 1}) class TestInstanceNonuniformlyValueValidatedDict(TraitTestBase): obj = NonuniformlyValueValidatedDictTrait() _default_value = {"foo": 1} _good_values = [{"foo": 0, "bar": "1"}, {"foo": 0, "bar": 1}] _bad_values = [{"foo": "0", "bar": "1"}] class KeyValidatedDictTrait(HasTraits): value = Dict(key_trait=Unicode(), default_value={"foo": "1"}) class TestInstanceKeyValidatedDict(TraitTestBase): obj = KeyValidatedDictTrait() _default_value = {"foo": "1"} _good_values = [{"foo": "0", "bar": "1"}] _bad_values = [{"foo": "0", 0: "1"}] class FullyValidatedDictTrait(HasTraits): value = Dict( value_trait=Unicode(), key_trait=Unicode(), per_key_traits={"foo": Int()}, default_value={"foo": 1}, ) class TestInstanceFullyValidatedDict(TraitTestBase): obj = FullyValidatedDictTrait() _default_value = {"foo": 1} _good_values = [{"foo": 0, "bar": "1"}, {"foo": 1, "bar": "2"}] _bad_values = [{"foo": 0, "bar": 1}, {"foo": "0", "bar": "1"}, {"foo": 0, 0: "1"}] def test_dict_default_value(): """Check that the `{}` default value of the Dict traitlet constructor is actually copied.""" class Foo(HasTraits): d1 = Dict() d2 = Dict() foo = Foo() assert foo.d1 == {} assert foo.d2 == {} assert foo.d1 is not foo.d2 class TestValidationHook(TestCase): def test_parity_trait(self): """Verify that the early validation hook is effective""" class Parity(HasTraits): value = Int(0) parity = Enum(["odd", "even"], default_value="even") @validate("value") def _value_validate(self, proposal): value = proposal["value"] if self.parity == "even" and value % 2: raise TraitError("Expected an even number") if self.parity == "odd" and (value % 2 == 0): raise TraitError("Expected an odd number") return value u = Parity() u.parity = "odd" u.value = 1 # OK with self.assertRaises(TraitError): u.value = 2 # Trait Error u.parity = "even" u.value = 2 # OK def test_multiple_validate(self): """Verify that we can register the same validator to multiple names""" class OddEven(HasTraits): odd = Int(1) even = Int(0) @validate("odd", "even") def check_valid(self, proposal): if proposal["trait"].name == "odd" and not proposal["value"] % 2: raise TraitError("odd should be odd") if proposal["trait"].name == "even" and proposal["value"] % 2: raise TraitError("even should be even") u = OddEven() u.odd = 3 # OK with self.assertRaises(TraitError): u.odd = 2 # Trait Error u.even = 2 # OK with self.assertRaises(TraitError): u.even = 3 # Trait Error def test_validate_used(self): """Verify that the validate value is being used""" class FixedValue(HasTraits): value = Int(0) @validate("value") def _value_validate(self, proposal): return -1 u = FixedValue(value=2) assert u.value == -1 u = FixedValue() u.value = 3 assert u.value == -1 class TestLink(TestCase): def test_connect_same(self): """Verify two traitlets of the same type can be linked together using link.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) # Connect the two classes. c = link((a, "value"), (b, "value")) # Make sure the values are the same at the point of linking. self.assertEqual(a.value, b.value) # Change one of the values to make sure they stay in sync. a.value = 5 self.assertEqual(a.value, b.value) b.value = 6 self.assertEqual(a.value, b.value) def test_link_different(self): """Verify two traitlets of different types can be linked together using link.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() class B(HasTraits): count = Int() a = A(value=9) b = B(count=8) # Connect the two classes. c = link((a, "value"), (b, "count")) # Make sure the values are the same at the point of linking. self.assertEqual(a.value, b.count) # Change one of the values to make sure they stay in sync. a.value = 5 self.assertEqual(a.value, b.count) b.count = 4 self.assertEqual(a.value, b.count) def test_unlink_link(self): """Verify two linked traitlets can be unlinked and relinked.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) # Connect the two classes. c = link((a, "value"), (b, "value")) a.value = 4 c.unlink() # Change one of the values to make sure they don't stay in sync. a.value = 5 self.assertNotEqual(a.value, b.value) c.link() self.assertEqual(a.value, b.value) a.value += 1 self.assertEqual(a.value, b.value) def test_callbacks(self): """Verify two linked traitlets have their callbacks called once.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() class B(HasTraits): count = Int() a = A(value=9) b = B(count=8) # Register callbacks that count. callback_count = [] def a_callback(name, old, new): callback_count.append("a") a.on_trait_change(a_callback, "value") def b_callback(name, old, new): callback_count.append("b") b.on_trait_change(b_callback, "count") # Connect the two classes. c = link((a, "value"), (b, "count")) # Make sure b's count was set to a's value once. self.assertEqual("".join(callback_count), "b") del callback_count[:] # Make sure a's value was set to b's count once. b.count = 5 self.assertEqual("".join(callback_count), "ba") del callback_count[:] # Make sure b's count was set to a's value once. a.value = 4 self.assertEqual("".join(callback_count), "ab") del callback_count[:] def test_tranform(self): """Test transform link.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) # Connect the two classes. c = link((a, "value"), (b, "value"), transform=(lambda x: 2 * x, lambda x: int(x / 2.0))) # Make sure the values are correct at the point of linking. self.assertEqual(b.value, 2 * a.value) # Change one the value of the source and check that it modifies the target. a.value = 5 self.assertEqual(b.value, 10) # Change one the value of the target and check that it modifies the # source. b.value = 6 self.assertEqual(a.value, 3) def test_link_broken_at_source(self): class MyClass(HasTraits): i = Int() j = Int() @observe("j") def another_update(self, change): self.i = change.new * 2 mc = MyClass() l = link((mc, "i"), (mc, "j")) # noqa: E741 self.assertRaises(TraitError, setattr, mc, "i", 2) def test_link_broken_at_target(self): class MyClass(HasTraits): i = Int() j = Int() @observe("i") def another_update(self, change): self.j = change.new * 2 mc = MyClass() l = link((mc, "i"), (mc, "j")) # noqa: E741 self.assertRaises(TraitError, setattr, mc, "j", 2) class TestDirectionalLink(TestCase): def test_connect_same(self): """Verify two traitlets of the same type can be linked together using directional_link.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) # Connect the two classes. c = directional_link((a, "value"), (b, "value")) # Make sure the values are the same at the point of linking. self.assertEqual(a.value, b.value) # Change one the value of the source and check that it synchronizes the target. a.value = 5 self.assertEqual(b.value, 5) # Change one the value of the target and check that it has no impact on the source b.value = 6 self.assertEqual(a.value, 5) def test_tranform(self): """Test transform link.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) # Connect the two classes. c = directional_link((a, "value"), (b, "value"), lambda x: 2 * x) # Make sure the values are correct at the point of linking. self.assertEqual(b.value, 2 * a.value) # Change one the value of the source and check that it modifies the target. a.value = 5 self.assertEqual(b.value, 10) # Change one the value of the target and check that it has no impact on the source b.value = 6 self.assertEqual(a.value, 5) def test_link_different(self): """Verify two traitlets of different types can be linked together using link.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() class B(HasTraits): count = Int() a = A(value=9) b = B(count=8) # Connect the two classes. c = directional_link((a, "value"), (b, "count")) # Make sure the values are the same at the point of linking. self.assertEqual(a.value, b.count) # Change one the value of the source and check that it synchronizes the target. a.value = 5 self.assertEqual(b.count, 5) # Change one the value of the target and check that it has no impact on the source b.value = 6 # type:ignore self.assertEqual(a.value, 5) def test_unlink_link(self): """Verify two linked traitlets can be unlinked and relinked.""" # Create two simple classes with Int traitlets. class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) # Connect the two classes. c = directional_link((a, "value"), (b, "value")) a.value = 4 c.unlink() # Change one of the values to make sure they don't stay in sync. a.value = 5 self.assertNotEqual(a.value, b.value) c.link() self.assertEqual(a.value, b.value) a.value += 1 self.assertEqual(a.value, b.value) class Pickleable(HasTraits): i = Int() @observe("i") def _i_changed(self, change): pass @validate("i") def _i_validate(self, commit): return commit["value"] j = Int() def __init__(self): with self.hold_trait_notifications(): self.i = 1 self.on_trait_change(self._i_changed, "i") def test_pickle_hastraits(): c = Pickleable() for protocol in range(pickle.HIGHEST_PROTOCOL + 1): p = pickle.dumps(c, protocol) c2 = pickle.loads(p) assert c2.i == c.i assert c2.j == c.j c.i = 5 for protocol in range(pickle.HIGHEST_PROTOCOL + 1): p = pickle.dumps(c, protocol) c2 = pickle.loads(p) assert c2.i == c.i assert c2.j == c.j def test_hold_trait_notifications(): changes = [] class Test(HasTraits): a = Integer(0) b = Integer(0) def _a_changed(self, name, old, new): changes.append((old, new)) def _b_validate(self, value, trait): if value != 0: raise TraitError("Only 0 is a valid value") return value # Test context manager and nesting t = Test() with t.hold_trait_notifications(): with t.hold_trait_notifications(): t.a = 1 assert t.a == 1 assert changes == [] t.a = 2 assert t.a == 2 with t.hold_trait_notifications(): t.a = 3 assert t.a == 3 assert changes == [] t.a = 4 assert t.a == 4 assert changes == [] t.a = 4 assert t.a == 4 assert changes == [] assert changes == [(0, 4)] # Test roll-back try: with t.hold_trait_notifications(): t.b = 1 # raises a Trait error except Exception: pass assert t.b == 0 class RollBack(HasTraits): bar = Int() def _bar_validate(self, value, trait): if value: raise TraitError("foobar") return value class TestRollback(TestCase): def test_roll_back(self): def assign_rollback(): RollBack(bar=1) self.assertRaises(TraitError, assign_rollback) class CacheModification(HasTraits): foo = Int() bar = Int() def _bar_validate(self, value, trait): self.foo = value return value def _foo_validate(self, value, trait): self.bar = value return value def test_cache_modification(): CacheModification(foo=1) CacheModification(bar=1) class OrderTraits(HasTraits): notified = Dict() a = Unicode() b = Unicode() c = Unicode() d = Unicode() e = Unicode() f = Unicode() g = Unicode() h = Unicode() i = Unicode() j = Unicode() k = Unicode() l = Unicode() # noqa: E741 def _notify(self, name, old, new): """check the value of all traits when each trait change is triggered This verifies that the values are not sensitive to dict ordering when loaded from kwargs """ # check the value of the other traits # when a given trait change notification fires self.notified[name] = {c: getattr(self, c) for c in "abcdefghijkl"} def __init__(self, **kwargs): self.on_trait_change(self._notify) super().__init__(**kwargs) def test_notification_order(): d = {c: c for c in "abcdefghijkl"} obj = OrderTraits() assert obj.notified == {} obj = OrderTraits(**d) notifications = {c: d for c in "abcdefghijkl"} assert obj.notified == notifications ### # Traits for Forward Declaration Tests ### class ForwardDeclaredInstanceTrait(HasTraits): value = ForwardDeclaredInstance["ForwardDeclaredBar"]("ForwardDeclaredBar", allow_none=True) class ForwardDeclaredTypeTrait(HasTraits): value = ForwardDeclaredType[t.Any, t.Any]("ForwardDeclaredBar", allow_none=True) class ForwardDeclaredInstanceListTrait(HasTraits): value = List(ForwardDeclaredInstance("ForwardDeclaredBar")) class ForwardDeclaredTypeListTrait(HasTraits): value = List(ForwardDeclaredType("ForwardDeclaredBar")) ### # End Traits for Forward Declaration Tests ### ### # Classes for Forward Declaration Tests ### class ForwardDeclaredBar: pass class ForwardDeclaredBarSub(ForwardDeclaredBar): pass ### # End Classes for Forward Declaration Tests ### ### # Forward Declaration Tests ### class TestForwardDeclaredInstanceTrait(TraitTestBase): obj = ForwardDeclaredInstanceTrait() _default_value = None _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()] _bad_values = ["foo", 3, ForwardDeclaredBar, ForwardDeclaredBarSub] class TestForwardDeclaredTypeTrait(TraitTestBase): obj = ForwardDeclaredTypeTrait() _default_value = None _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub] _bad_values = ["foo", 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()] class TestForwardDeclaredInstanceList(TraitTestBase): obj = ForwardDeclaredInstanceListTrait() def test_klass(self): """Test that the instance klass is properly assigned.""" self.assertIs(self.obj.traits()["value"]._trait.klass, ForwardDeclaredBar) _default_value: t.List[t.Any] = [] _good_values = [ [ForwardDeclaredBar(), ForwardDeclaredBarSub()], [], ] _bad_values = [ ForwardDeclaredBar(), [ForwardDeclaredBar(), 3, None], "1", # Note that this is the type, not an instance. [ForwardDeclaredBar], [None], None, ] class TestForwardDeclaredTypeList(TraitTestBase): obj = ForwardDeclaredTypeListTrait() def test_klass(self): """Test that the instance klass is properly assigned.""" self.assertIs(self.obj.traits()["value"]._trait.klass, ForwardDeclaredBar) _default_value: t.List[t.Any] = [] _good_values = [ [ForwardDeclaredBar, ForwardDeclaredBarSub], [], ] _bad_values = [ ForwardDeclaredBar, [ForwardDeclaredBar, 3], "1", # Note that this is an instance, not the type. [ForwardDeclaredBar()], [None], None, ] ### # End Forward Declaration Tests ### class TestDynamicTraits(TestCase): def setUp(self): self._notify1 = [] def notify1(self, name, old, new): self._notify1.append((name, old, new)) @t.no_type_check def test_notify_all(self): class A(HasTraits): pass a = A() self.assertTrue(not hasattr(a, "x")) self.assertTrue(not hasattr(a, "y")) # Dynamically add trait x. a.add_traits(x=Int()) self.assertTrue(hasattr(a, "x")) self.assertTrue(isinstance(a, (A,))) # Dynamically add trait y. a.add_traits(y=Float()) self.assertTrue(hasattr(a, "y")) self.assertTrue(isinstance(a, (A,))) self.assertEqual(a.__class__.__name__, A.__name__) # Create a new instance and verify that x and y # aren't defined. b = A() self.assertTrue(not hasattr(b, "x")) self.assertTrue(not hasattr(b, "y")) # Verify that notification works like normal. a.on_trait_change(self.notify1) a.x = 0 self.assertEqual(len(self._notify1), 0) a.y = 0.0 self.assertEqual(len(self._notify1), 0) a.x = 10 self.assertTrue(("x", 0, 10) in self._notify1) a.y = 10.0 self.assertTrue(("y", 0.0, 10.0) in self._notify1) self.assertRaises(TraitError, setattr, a, "x", "bad string") self.assertRaises(TraitError, setattr, a, "y", "bad string") self._notify1 = [] a.on_trait_change(self.notify1, remove=True) a.x = 20 a.y = 20.0 self.assertEqual(len(self._notify1), 0) def test_enum_no_default(): class C(HasTraits): t = Enum(["a", "b"]) c = C() c.t = "a" assert c.t == "a" c = C() with pytest.raises(TraitError): t = c.t c = C(t="b") assert c.t == "b" def test_default_value_repr(): class C(HasTraits): t = Type("traitlets.HasTraits") t2 = Type(HasTraits) n = Integer(0) lis = List() d = Dict() assert C.t.default_value_repr() == "'traitlets.HasTraits'" assert C.t2.default_value_repr() == "'traitlets.traitlets.HasTraits'" assert C.n.default_value_repr() == "0" assert C.lis.default_value_repr() == "[]" assert C.d.default_value_repr() == "{}" class TransitionalClass(HasTraits): d = Any() @default("d") def _d_default(self): return TransitionalClass parent_super = False calls_super = Integer(0) @default("calls_super") def _calls_super_default(self): return -1 @observe("calls_super") @observe_compat def _calls_super_changed(self, change): self.parent_super = change parent_override = False overrides = Integer(0) @observe("overrides") @observe_compat def _overrides_changed(self, change): self.parent_override = change class SubClass(TransitionalClass): def _d_default(self): return SubClass subclass_super = False def _calls_super_changed(self, name, old, new): self.subclass_super = True super()._calls_super_changed(name, old, new) subclass_override = False def _overrides_changed(self, name, old, new): self.subclass_override = True def test_subclass_compat(): obj = SubClass() obj.calls_super = 5 assert obj.parent_super assert obj.subclass_super obj.overrides = 5 assert obj.subclass_override assert not obj.parent_override assert obj.d is SubClass class DefinesHandler(HasTraits): parent_called = False trait = Integer() @observe("trait") def handler(self, change): self.parent_called = True class OverridesHandler(DefinesHandler): child_called = False @observe("trait") def handler(self, change): self.child_called = True def test_subclass_override_observer(): obj = OverridesHandler() obj.trait = 5 assert obj.child_called assert not obj.parent_called class DoesntRegisterHandler(DefinesHandler): child_called = False def handler(self, change): self.child_called = True def test_subclass_override_not_registered(): """Subclass that overrides observer and doesn't re-register unregisters both""" obj = DoesntRegisterHandler() obj.trait = 5 assert not obj.child_called assert not obj.parent_called class AddsHandler(DefinesHandler): child_called = False @observe("trait") def child_handler(self, change): self.child_called = True def test_subclass_add_observer(): obj = AddsHandler() obj.trait = 5 assert obj.child_called assert obj.parent_called def test_observe_iterables(): class C(HasTraits): i = Integer() s = Unicode() c = C() recorded = {} def record(change): recorded["change"] = change # observe with names=set c.observe(record, names={"i", "s"}) c.i = 5 assert recorded["change"].name == "i" assert recorded["change"].new == 5 c.s = "hi" assert recorded["change"].name == "s" assert recorded["change"].new == "hi" # observe with names=custom container with iter, contains class MyContainer: def __init__(self, container): self.container = container def __iter__(self): return iter(self.container) def __contains__(self, key): return key in self.container c.observe(record, names=MyContainer({"i", "s"})) c.i = 10 assert recorded["change"].name == "i" assert recorded["change"].new == 10 c.s = "ok" assert recorded["change"].name == "s" assert recorded["change"].new == "ok" def test_super_args(): class SuperRecorder: def __init__(self, *args, **kwargs): self.super_args = args self.super_kwargs = kwargs class SuperHasTraits(HasTraits, SuperRecorder): i = Integer() obj = SuperHasTraits("a1", "a2", b=10, i=5, c="x") assert obj.i == 5 assert not hasattr(obj, "b") assert not hasattr(obj, "c") assert obj.super_args == ("a1", "a2") assert obj.super_kwargs == {"b": 10, "c": "x"} def test_super_bad_args(): class SuperHasTraits(HasTraits): a = Integer() w = ["Passing unrecognized arguments"] with expected_warnings(w): obj = SuperHasTraits(a=1, b=2) assert obj.a == 1 assert not hasattr(obj, "b") def test_default_mro(): """Verify that default values follow mro""" class Base(HasTraits): trait = Unicode("base") attr = "base" class A(Base): pass class B(Base): trait = Unicode("B") attr = "B" class AB(A, B): pass class BA(B, A): pass assert A().trait == "base" assert A().attr == "base" assert BA().trait == "B" assert BA().attr == "B" assert AB().trait == "B" assert AB().attr == "B" def test_cls_self_argument(): class X(HasTraits): def __init__(__self, cls, self): pass x = X(cls=None, self=None) def test_override_default(): class C(HasTraits): a = Unicode("hard default") def _a_default(self): return "default method" C._a_default = lambda self: "overridden" # type:ignore c = C() assert c.a == "overridden" def test_override_default_decorator(): class C(HasTraits): a = Unicode("hard default") @default("a") def _a_default(self): return "default method" C._a_default = lambda self: "overridden" # type:ignore c = C() assert c.a == "overridden" def test_override_default_instance(): class C(HasTraits): a = Unicode("hard default") @default("a") def _a_default(self): return "default method" c = C() c._a_default = lambda self: "overridden" assert c.a == "overridden" def test_copy_HasTraits(): from copy import copy class C(HasTraits): a = Int() c = C(a=1) assert c.a == 1 cc = copy(c) cc.a = 2 assert cc.a == 2 assert c.a == 1 def _from_string_test(traittype, s, expected): """Run a test of trait.from_string""" if isinstance(traittype, TraitType): trait = traittype else: trait = traittype(allow_none=True) if isinstance(s, list): cast = trait.from_string_list # type:ignore else: cast = trait.from_string if type(expected) is type and issubclass(expected, Exception): with pytest.raises(expected): # noqa: PT012 value = cast(s) trait.validate(CrossValidationStub(), value) # type:ignore else: value = cast(s) assert value == expected @pytest.mark.parametrize( "s, expected", [("xyz", "xyz"), ("1", "1"), ('"xx"', "xx"), ("'abc'", "abc"), ("None", None)], ) def test_unicode_from_string(s, expected): _from_string_test(Unicode, s, expected) @pytest.mark.parametrize( "s, expected", [("xyz", "xyz"), ("1", "1"), ('"xx"', "xx"), ("'abc'", "abc"), ("None", None)], ) def test_cunicode_from_string(s, expected): _from_string_test(CUnicode, s, expected) @pytest.mark.parametrize( "s, expected", [("xyz", b"xyz"), ("1", b"1"), ('b"xx"', b"xx"), ("b'abc'", b"abc"), ("None", None)], ) def test_bytes_from_string(s, expected): _from_string_test(Bytes, s, expected) @pytest.mark.parametrize( "s, expected", [("xyz", b"xyz"), ("1", b"1"), ('b"xx"', b"xx"), ("b'abc'", b"abc"), ("None", None)], ) def test_cbytes_from_string(s, expected): _from_string_test(CBytes, s, expected) @pytest.mark.parametrize( "s, expected", [("x", ValueError), ("1", 1), ("123", 123), ("2.0", ValueError), ("None", None)], ) def test_int_from_string(s, expected): _from_string_test(Integer, s, expected) @pytest.mark.parametrize( "s, expected", [("x", ValueError), ("1", 1.0), ("123.5", 123.5), ("2.5", 2.5), ("None", None)], ) def test_float_from_string(s, expected): _from_string_test(Float, s, expected) @pytest.mark.parametrize( "s, expected", [ ("x", ValueError), ("1", 1.0), ("123.5", 123.5), ("2.5", 2.5), ("1+2j", 1 + 2j), ("None", None), ], ) def test_complex_from_string(s, expected): _from_string_test(Complex, s, expected) @pytest.mark.parametrize( "s, expected", [ ("true", True), ("TRUE", True), ("1", True), ("0", False), ("False", False), ("false", False), ("1.0", ValueError), ("None", None), ], ) def test_bool_from_string(s, expected): _from_string_test(Bool, s, expected) @pytest.mark.parametrize( "s, expected", [ ("{}", {}), ("1", TraitError), ("{1: 2}", {1: 2}), ('{"key": "value"}', {"key": "value"}), ("x", TraitError), ("None", None), ], ) def test_dict_from_string(s, expected): _from_string_test(Dict, s, expected) @pytest.mark.parametrize( "s, expected", [ ("[]", []), ('[1, 2, "x"]', [1, 2, "x"]), (["1", "x"], ["1", "x"]), (["None"], None), ], ) def test_list_from_string(s, expected): _from_string_test(List, s, expected) @pytest.mark.parametrize( "s, expected, value_trait", [ (["1", "2", "3"], [1, 2, 3], Integer()), (["x"], ValueError, Integer()), (["1", "x"], ["1", "x"], Unicode()), (["None"], [None], Unicode(allow_none=True)), (["None"], ["None"], Unicode(allow_none=False)), ], ) def test_list_items_from_string(s, expected, value_trait): _from_string_test(List(value_trait), s, expected) @pytest.mark.parametrize( "s, expected", [ ("[]", set()), ('[1, 2, "x"]', {1, 2, "x"}), ('{1, 2, "x"}', {1, 2, "x"}), (["1", "x"], {"1", "x"}), (["None"], None), ], ) def test_set_from_string(s, expected): _from_string_test(Set, s, expected) @pytest.mark.parametrize( "s, expected, value_trait", [ (["1", "2", "3"], {1, 2, 3}, Integer()), (["x"], ValueError, Integer()), (["1", "x"], {"1", "x"}, Unicode()), (["None"], {None}, Unicode(allow_none=True)), ], ) def test_set_items_from_string(s, expected, value_trait): _from_string_test(Set(value_trait), s, expected) @pytest.mark.parametrize( "s, expected", [ ("[]", ()), ("()", ()), ('[1, 2, "x"]', (1, 2, "x")), ('(1, 2, "x")', (1, 2, "x")), (["1", "x"], ("1", "x")), (["None"], None), ], ) def test_tuple_from_string(s, expected): _from_string_test(Tuple, s, expected) @pytest.mark.parametrize( "s, expected, value_traits", [ (["1", "2", "3"], (1, 2, 3), [Integer(), Integer(), Integer()]), (["x"], ValueError, [Integer()]), (["1", "x"], ("1", "x"), [Unicode()]), (["None"], ("None",), [Unicode(allow_none=False)]), (["None"], (None,), [Unicode(allow_none=True)]), ], ) def test_tuple_items_from_string(s, expected, value_traits): _from_string_test(Tuple(*value_traits), s, expected) @pytest.mark.parametrize( "s, expected", [ ("x", "x"), ("mod.submod", "mod.submod"), ("not an identifier", TraitError), ("1", "1"), ("None", None), ], ) def test_object_from_string(s, expected): _from_string_test(DottedObjectName, s, expected) @pytest.mark.parametrize( "s, expected", [ ("127.0.0.1:8000", ("127.0.0.1", 8000)), ("host.tld:80", ("host.tld", 80)), ("host:notaport", ValueError), ("127.0.0.1", ValueError), ("None", None), ], ) def test_tcp_from_string(s, expected): _from_string_test(TCPAddress, s, expected) @pytest.mark.parametrize( "s, expected", [("[]", []), ("{}", "{}")], ) def test_union_of_list_and_unicode_from_string(s, expected): _from_string_test(Union([List(), Unicode()]), s, expected) @pytest.mark.parametrize( "s, expected", [("1", 1), ("1.5", 1.5)], ) def test_union_of_int_and_float_from_string(s, expected): _from_string_test(Union([Int(), Float()]), s, expected) @pytest.mark.parametrize( "s, expected, allow_none", [("[]", [], False), ("{}", {}, False), ("None", TraitError, False), ("None", None, True)], ) def test_union_of_list_and_dict_from_string(s, expected, allow_none): _from_string_test(Union([List(), Dict()], allow_none=allow_none), s, expected) def test_all_attribute(): """Verify all trait types are added to `traitlets.__all__`""" names = dir(traitlets) for name in names: value = getattr(traitlets, name) if not name.startswith("_") and isinstance(value, type) and issubclass(value, TraitType): if name not in traitlets.__all__: raise ValueError(f"{name} not in __all__") for name in traitlets.__all__: if name not in names: raise ValueError(f"{name} should be removed from __all__") ipython-traitlets-a3e321a/tests/test_traitlets_docstring.py000066400000000000000000000046641461045054400244750ustar00rootroot00000000000000"""Tests for traitlets.traitlets.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. # from __future__ import annotations from traitlets import Dict, Instance, Integer, Unicode, Union from traitlets.config import Configurable def test_handle_docstring(): class SampleConfigurable(Configurable): pass class TraitTypesSampleConfigurable(Configurable): """TraitTypesSampleConfigurable docstring""" trait_integer = Integer( help="""trait_integer help text""", config=True, ) trait_integer_nohelp = Integer( config=True, ) trait_integer_noconfig = Integer( help="""trait_integer_noconfig help text""", ) trait_unicode = Unicode( help="""trait_unicode help text""", config=True, ) trait_unicode_nohelp = Unicode( config=True, ) trait_unicode_noconfig = Unicode( help="""trait_unicode_noconfig help text""", ) trait_dict = Dict( help="""trait_dict help text""", config=True, ) trait_dict_nohelp = Dict( config=True, ) trait_dict_noconfig = Dict( help="""trait_dict_noconfig help text""", ) trait_instance = Instance( klass=SampleConfigurable, help="""trait_instance help text""", config=True, ) trait_instance_nohelp = Instance( klass=SampleConfigurable, config=True, ) trait_instance_noconfig = Instance( klass=SampleConfigurable, help="""trait_instance_noconfig help text""", ) trait_union = Union( [Integer(), Unicode()], help="""trait_union help text""", config=True, ) trait_union_nohelp = Union( [Integer(), Unicode()], config=True, ) trait_union_noconfig = Union( [Integer(), Unicode()], help="""trait_union_noconfig help text""", ) base_names = SampleConfigurable().trait_names() for name in TraitTypesSampleConfigurable().trait_names(): if name in base_names: continue doc = getattr(TraitTypesSampleConfigurable, name).__doc__ if "nohelp" not in name: assert doc == f"{name} help text" ipython-traitlets-a3e321a/tests/test_traitlets_enum.py000066400000000000000000000324001461045054400234320ustar00rootroot00000000000000# pylint: disable=missing-docstring, too-few-public-methods """ Test the trait-type ``UseEnum``. """ from __future__ import annotations import enum import unittest from traitlets import CaselessStrEnum, Enum, FuzzyEnum, HasTraits, TraitError, UseEnum # ----------------------------------------------------------------------------- # TEST SUPPORT: # ----------------------------------------------------------------------------- class Color(enum.Enum): red = 1 green = 2 blue = 3 yellow = 4 class OtherColor(enum.Enum): red = 0 green = 1 class CSColor(enum.Enum): red = 1 Green = 2 BLUE = 3 YeLLoW = 4 color_choices = "red Green BLUE YeLLoW".split() # ----------------------------------------------------------------------------- # TESTSUITE: # ----------------------------------------------------------------------------- class TestUseEnum(unittest.TestCase): # pylint: disable=invalid-name class Example(HasTraits): color = UseEnum(Color, help="Color enum") def test_assign_enum_value(self): example = self.Example() example.color = Color.green self.assertEqual(example.color, Color.green) def test_assign_all_enum_values(self): # pylint: disable=no-member enum_values = list(Color.__members__.values()) for value in enum_values: self.assertIsInstance(value, Color) example = self.Example() example.color = value self.assertEqual(example.color, value) self.assertIsInstance(value, Color) def test_assign_enum_value__with_other_enum_raises_error(self): example = self.Example() with self.assertRaises(TraitError): example.color = OtherColor.green def test_assign_enum_name_1(self): # -- CONVERT: string => Enum value (item) example = self.Example() example.color = "red" self.assertEqual(example.color, Color.red) def test_assign_enum_value_name(self): # -- CONVERT: string => Enum value (item) # pylint: disable=no-member enum_names = [enum_val.name for enum_val in Color.__members__.values()] for value in enum_names: self.assertIsInstance(value, str) example = self.Example() enum_value = Color.__members__.get(value) example.color = value self.assertIs(example.color, enum_value) self.assertEqual(example.color.name, value) # type:ignore def test_assign_scoped_enum_value_name(self): # -- CONVERT: string => Enum value (item) scoped_names = ["Color.red", "Color.green", "Color.blue", "Color.yellow"] for value in scoped_names: example = self.Example() example.color = value self.assertIsInstance(example.color, Color) self.assertEqual(str(example.color), value) def test_assign_bad_enum_value_name__raises_error(self): # -- CONVERT: string => Enum value (item) bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"] for value in bad_enum_names: example = self.Example() with self.assertRaises(TraitError): example.color = value def test_assign_enum_value_number_1(self): # -- CONVERT: number => Enum value (item) example = self.Example() example.color = 1 # == Color.red.value example.color = Color.red.value self.assertEqual(example.color, Color.red) def test_assign_enum_value_number(self): # -- CONVERT: number => Enum value (item) # pylint: disable=no-member enum_numbers = [enum_val.value for enum_val in Color.__members__.values()] for value in enum_numbers: self.assertIsInstance(value, int) example = self.Example() example.color = value self.assertIsInstance(example.color, Color) self.assertEqual(example.color.value, value) # type:ignore def test_assign_bad_enum_value_number__raises_error(self): # -- CONVERT: number => Enum value (item) bad_numbers = [-1, 0, 5] for value in bad_numbers: self.assertIsInstance(value, int) assert UseEnum(Color).select_by_number(value, None) is None example = self.Example() with self.assertRaises(TraitError): example.color = value def test_ctor_without_default_value(self): # -- IMPLICIT: default_value = Color.red (first enum-value) class Example2(HasTraits): color = UseEnum(Color) example = Example2() self.assertEqual(example.color, Color.red) def test_ctor_with_default_value_as_enum_value(self): # -- CONVERT: number => Enum value (item) class Example2(HasTraits): color = UseEnum(Color, default_value=Color.green) example = Example2() self.assertEqual(example.color, Color.green) def test_ctor_with_default_value_none_and_not_allow_none(self): # -- IMPLICIT: default_value = Color.red (first enum-value) class Example2(HasTraits): color1 = UseEnum(Color, default_value=None, allow_none=False) color2 = UseEnum(Color, default_value=None) example = Example2() self.assertEqual(example.color1, Color.red) self.assertEqual(example.color2, Color.red) def test_ctor_with_default_value_none_and_allow_none(self): class Example2(HasTraits): color1 = UseEnum(Color, default_value=None, allow_none=True) color2 = UseEnum(Color, allow_none=True) example = Example2() self.assertIs(example.color1, None) self.assertIs(example.color2, None) def test_assign_none_without_allow_none_resets_to_default_value(self): class Example2(HasTraits): color1 = UseEnum(Color, allow_none=False) color2 = UseEnum(Color) example = Example2() example.color1 = None example.color2 = None self.assertIs(example.color1, Color.red) self.assertIs(example.color2, Color.red) def test_assign_none_to_enum_or_none(self): class Example2(HasTraits): color = UseEnum(Color, allow_none=True) example = Example2() example.color = None self.assertIs(example.color, None) def test_assign_bad_value_with_to_enum_or_none(self): class Example2(HasTraits): color = UseEnum(Color, allow_none=True) example = Example2() with self.assertRaises(TraitError): example.color = "BAD_VALUE" def test_info(self): choices = color_choices class Example(HasTraits): enum1 = Enum(choices, allow_none=False) enum2 = CaselessStrEnum(choices, allow_none=False) enum3 = FuzzyEnum(choices, allow_none=False) enum4 = UseEnum(CSColor, allow_none=False) for i in range(1, 5): attr = "enum%s" % i enum = getattr(Example, attr) enum.allow_none = True info = enum.info() self.assertEqual(len(info.split(", ")), len(choices), info.split(", ")) self.assertIn("or None", info) info = enum.info_rst() self.assertEqual(len(info.split("|")), len(choices), info.split("|")) self.assertIn("or `None`", info) # Check no single `\` exists. self.assertNotRegex(info, r"\b\\\b") enum.allow_none = False info = enum.info() self.assertEqual(len(info.split(", ")), len(choices), info.split(", ")) self.assertNotIn("None", info) info = enum.info_rst() self.assertEqual(len(info.split("|")), len(choices), info.split("|")) self.assertNotIn("None", info) # Check no single `\` exists. self.assertNotRegex(info, r"\b\\\b") # ----------------------------------------------------------------------------- # TESTSUITE: # ----------------------------------------------------------------------------- class TestFuzzyEnum(unittest.TestCase): # Check mostly `validate()`, Ctor must be checked on generic `Enum` # or `CaselessStrEnum`. def test_search_all_prefixes__overwrite(self): class FuzzyExample(HasTraits): color = FuzzyEnum(color_choices, help="Color enum") example = FuzzyExample() for color in color_choices: for wlen in range(1, len(color)): value = color[:wlen] example.color = value self.assertEqual(example.color, color) example.color = value.upper() self.assertEqual(example.color, color) example.color = value.lower() self.assertEqual(example.color, color) def test_search_all_prefixes__ctor(self): class FuzzyExample(HasTraits): color = FuzzyEnum(color_choices, help="Color enum") for color in color_choices: for wlen in range(1, len(color)): value = color[:wlen] example = FuzzyExample() example.color = value self.assertEqual(example.color, color) example = FuzzyExample() example.color = value.upper() self.assertEqual(example.color, color) example = FuzzyExample() example.color = value.lower() self.assertEqual(example.color, color) def test_search_substrings__overwrite(self): class FuzzyExample(HasTraits): color = FuzzyEnum(color_choices, help="Color enum", substring_matching=True) example = FuzzyExample() for color in color_choices: for wlen in range(2): value = color[wlen:] example.color = value self.assertEqual(example.color, color) example.color = value.upper() self.assertEqual(example.color, color) example.color = value.lower() self.assertEqual(example.color, color) def test_search_substrings__ctor(self): class FuzzyExample(HasTraits): color = FuzzyEnum(color_choices, help="Color enum", substring_matching=True) color = color_choices[-1] # 'YeLLoW' for end in (-1, len(color)): for start in range(1, len(color) - 2): value = color[start:end] example = FuzzyExample() example.color = value self.assertEqual(example.color, color) example = FuzzyExample() example.color = value.upper() self.assertEqual(example.color, color) def test_assign_other_raises(self): def new_trait_class(case_sensitive, substring_matching): class Example(HasTraits): color = FuzzyEnum( color_choices, case_sensitive=case_sensitive, substring_matching=substring_matching, ) return Example example = new_trait_class(case_sensitive=False, substring_matching=False)() with self.assertRaises(TraitError): example.color = "" with self.assertRaises(TraitError): example.color = "BAD COLOR" with self.assertRaises(TraitError): example.color = "ed" example = new_trait_class(case_sensitive=True, substring_matching=False)() with self.assertRaises(TraitError): example.color = "" with self.assertRaises(TraitError): example.color = "Red" # not 'red' example = new_trait_class(case_sensitive=True, substring_matching=True)() with self.assertRaises(TraitError): example.color = "" with self.assertRaises(TraitError): example.color = "BAD COLOR" with self.assertRaises(TraitError): example.color = "green" # not 'Green' with self.assertRaises(TraitError): example.color = "lue" # not (b)'LUE' with self.assertRaises(TraitError): example.color = "lUE" # not (b)'LUE' example = new_trait_class(case_sensitive=False, substring_matching=True)() with self.assertRaises(TraitError): example.color = "" with self.assertRaises(TraitError): example.color = "BAD COLOR" def test_ctor_with_default_value(self): def new_trait_class(default_value, case_sensitive, substring_matching): class Example(HasTraits): color = FuzzyEnum( color_choices, default_value=default_value, case_sensitive=case_sensitive, substring_matching=substring_matching, ) return Example for color in color_choices: example = new_trait_class(color, False, False)() self.assertEqual(example.color, color) example = new_trait_class(color.upper(), False, False)() self.assertEqual(example.color, color) color = color_choices[-1] # 'YeLLoW' example = new_trait_class(color, True, False)() self.assertEqual(example.color, color) # FIXME: default value not validated! # with self.assertRaises(TraitError): # example = new_trait_class(color.lower(), True, False) ipython-traitlets-a3e321a/tests/test_typing.py000066400000000000000000000374071461045054400217210ustar00rootroot00000000000000from __future__ import annotations import logging import typing as t from abc import ABC import pytest from traitlets import ( Any, Bool, CInt, Dict, Enum, HasTraits, Instance, Int, List, Set, TCPAddress, Type, Unicode, Union, default, observe, validate, ) from traitlets.config import Config if not t.TYPE_CHECKING: def reveal_type(*args: t.Any, **kwargs: t.Any) -> None: pass # mypy: disallow-untyped-calls class Foo: def __init__(self, c: t.Any) -> None: self.c = c @pytest.mark.mypy_testing def mypy_decorator_typing() -> None: class T(HasTraits): foo = Unicode("").tag(config=True) @default("foo") def _default_foo(self) -> str: return "hi" @observe("foo") def _foo_observer(self, change: t.Any) -> bool: return True @validate("foo") def _foo_validate(self, commit: t.Any) -> bool: return True t = T() reveal_type(t.foo) # R: builtins.str reveal_type(t._foo_observer) # R: Any reveal_type(t._foo_validate) # R: Any @pytest.mark.mypy_testing def mypy_config_typing() -> None: c = Config( { "ExtractOutputPreprocessor": {"enabled": True}, } ) reveal_type(c) # R: traitlets.config.loader.Config @pytest.mark.mypy_testing def mypy_union_typing() -> None: class T(HasTraits): style = Union( [Unicode("default"), Type(klass=object)], help="Name of the pygments style to use", default_value="hi", ).tag(config=True) t = T() reveal_type(Union("foo")) # R: traitlets.traitlets.Union reveal_type(Union("").tag(sync=True)) # R: traitlets.traitlets.Union reveal_type(Union(None, allow_none=True)) # R: traitlets.traitlets.Union reveal_type(Union(None, allow_none=True).tag(sync=True)) # R: traitlets.traitlets.Union reveal_type(T.style) # R: traitlets.traitlets.Union reveal_type(t.style) # R: Any @pytest.mark.mypy_testing def mypy_list_typing() -> None: class T(HasTraits): latex_command = List( ["xelatex", "{filename}", "-quiet"], help="Shell command used to compile latex." ).tag(config=True) t = T() reveal_type(List(["foo"])) # R: traitlets.traitlets.List[builtins.str] reveal_type(List([""]).tag(sync=True)) # R: traitlets.traitlets.List[builtins.str] reveal_type(List(None, allow_none=True)) # R: traitlets.traitlets.List[Never] reveal_type( List(None, allow_none=True).tag(sync=True) # R: traitlets.traitlets.List[Never] ) reveal_type(T.latex_command) # R: traitlets.traitlets.List[builtins.str] reveal_type(t.latex_command) # R: builtins.list[builtins.str] @pytest.mark.mypy_testing def mypy_dict_typing() -> None: class T(HasTraits): foo = Dict({}, help="Shell command used to compile latex.").tag(config=True) t = T() reveal_type(Dict(None, allow_none=True)) # R: traitlets.traitlets.Dict[builtins.str, Any] reveal_type( Dict(None, allow_none=True).tag(sync=True) # R: traitlets.traitlets.Dict[builtins.str, Any] ) reveal_type(T.foo) # R: traitlets.traitlets.Dict[builtins.str, Any] reveal_type(t.foo) # R: builtins.dict[builtins.str, Any] @pytest.mark.mypy_testing def mypy_type_typing() -> None: class KernelSpec: item = Unicode("foo") class KernelSpecSubclass(KernelSpec): other = Unicode("bar") class GatewayTokenRenewerBase(ABC): item = Unicode("foo") class KernelSpecManager(HasTraits): """A manager for kernel specs.""" kernel_spec_class = Type( KernelSpec, config=True, help="""The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior. """, ) other_class = Type("foo.bar.baz") other_kernel_spec_class = Type( default_value=KernelSpecSubclass, klass=KernelSpec, config=True, ) gateway_token_renewer_class = Type( klass=GatewayTokenRenewerBase, config=True, help="""The class to use for Gateway token renewal. (JUPYTER_GATEWAY_TOKEN_RENEWER_CLASS env var)""", ) t = KernelSpecManager() reveal_type(t.kernel_spec_class) # R: def () -> tests.test_typing.KernelSpec@129 reveal_type(t.kernel_spec_class()) # R: tests.test_typing.KernelSpec@129 reveal_type(t.kernel_spec_class().item) # R: builtins.str reveal_type(t.other_class) # R: builtins.type reveal_type(t.other_class()) # R: Any reveal_type(t.other_kernel_spec_class) # R: def () -> tests.test_typing.KernelSpec@129 reveal_type(t.other_kernel_spec_class()) # R: tests.test_typing.KernelSpec@129 reveal_type( t.gateway_token_renewer_class # R: def () -> tests.test_typing.GatewayTokenRenewerBase@135 ) reveal_type(t.gateway_token_renewer_class()) # R: tests.test_typing.GatewayTokenRenewerBase@135 @pytest.mark.mypy_testing def mypy_unicode_typing() -> None: class T(HasTraits): export_format = Unicode( allow_none=False, help="""The export format to be used, either one of the built-in formats or a dotted object name that represents the import path for an ``Exporter`` class""", ).tag(config=True) t = T() reveal_type( Unicode( # R: traitlets.traitlets.Unicode[builtins.str, Union[builtins.str, builtins.bytes]] "foo" ) ) reveal_type( Unicode( # R: traitlets.traitlets.Unicode[builtins.str, Union[builtins.str, builtins.bytes]] "" ).tag(sync=True) ) reveal_type( Unicode( # R: traitlets.traitlets.Unicode[Union[builtins.str, None], Union[builtins.str, builtins.bytes, None]] None, allow_none=True ) ) reveal_type( Unicode( # R: traitlets.traitlets.Unicode[Union[builtins.str, None], Union[builtins.str, builtins.bytes, None]] None, allow_none=True ).tag(sync=True) ) reveal_type( T.export_format # R: traitlets.traitlets.Unicode[builtins.str, Union[builtins.str, builtins.bytes]] ) reveal_type(t.export_format) # R: builtins.str @pytest.mark.mypy_testing def mypy_enum_typing() -> None: class T(HasTraits): log_level = Enum( (0, 10, 20, 30, 40, 50), default_value=logging.WARN, help="Set the log level by value or name.", ).tag(config=True) t = T() reveal_type( Enum( # R: traitlets.traitlets.Enum[builtins.str] ("foo",) ) ) reveal_type( Enum( # R: traitlets.traitlets.Enum[builtins.str] [""] ).tag(sync=True) ) reveal_type( Enum( # R: traitlets.traitlets.Enum[None] None, allow_none=True ) ) reveal_type( Enum( # R: traitlets.traitlets.Enum[None] None, allow_none=True ).tag(sync=True) ) reveal_type( T.log_level # R: traitlets.traitlets.Enum[builtins.int] ) reveal_type(t.log_level) # R: builtins.int @pytest.mark.mypy_testing def mypy_set_typing() -> None: class T(HasTraits): remove_cell_tags = Set( Unicode(), default_value=[], help=( "Tags indicating which cells are to be removed," "matches tags in ``cell.metadata.tags``." ), ).tag(config=True) safe_output_keys = Set( config=True, default_value={ "metadata", # Not a mimetype per-se, but expected and safe. "text/plain", "text/latex", "application/json", "image/png", "image/jpeg", }, help="Cell output mimetypes to render without modification", ) t = T() reveal_type(Set("foo")) # R: traitlets.traitlets.Set reveal_type(Set("").tag(sync=True)) # R: traitlets.traitlets.Set reveal_type(Set(None, allow_none=True)) # R: traitlets.traitlets.Set reveal_type(Set(None, allow_none=True).tag(sync=True)) # R: traitlets.traitlets.Set reveal_type(T.remove_cell_tags) # R: traitlets.traitlets.Set reveal_type(t.remove_cell_tags) # R: builtins.set[Any] reveal_type(T.safe_output_keys) # R: traitlets.traitlets.Set reveal_type(t.safe_output_keys) # R: builtins.set[Any] @pytest.mark.mypy_testing def mypy_any_typing() -> None: class T(HasTraits): attributes = Any( config=True, default_value={ "a": ["href", "title"], "abbr": ["title"], "acronym": ["title"], }, help="Allowed HTML tag attributes", ) t = T() reveal_type(Any("foo")) # R: traitlets.traitlets.Any reveal_type(Any("").tag(sync=True)) # R: traitlets.traitlets.Any reveal_type(Any(None, allow_none=True)) # R: traitlets.traitlets.Any reveal_type(Any(None, allow_none=True).tag(sync=True)) # R: traitlets.traitlets.Any reveal_type(T.attributes) # R: traitlets.traitlets.Any reveal_type(t.attributes) # R: Any @pytest.mark.mypy_testing def mypy_bool_typing() -> None: class T(HasTraits): b = Bool(True).tag(sync=True) ob = Bool(None, allow_none=True).tag(sync=True) t = T() reveal_type( Bool(True) # R: traitlets.traitlets.Bool[builtins.bool, Union[builtins.bool, builtins.int]] ) reveal_type( Bool( # R: traitlets.traitlets.Bool[builtins.bool, Union[builtins.bool, builtins.int]] True ).tag(sync=True) ) reveal_type( Bool( # R: traitlets.traitlets.Bool[Union[builtins.bool, None], Union[builtins.bool, builtins.int, None]] None, allow_none=True ) ) reveal_type( Bool( # R: traitlets.traitlets.Bool[Union[builtins.bool, None], Union[builtins.bool, builtins.int, None]] None, allow_none=True ).tag(sync=True) ) reveal_type( T.b # R: traitlets.traitlets.Bool[builtins.bool, Union[builtins.bool, builtins.int]] ) reveal_type(t.b) # R: builtins.bool reveal_type(t.ob) # R: Union[builtins.bool, None] reveal_type( T.b # R: traitlets.traitlets.Bool[builtins.bool, Union[builtins.bool, builtins.int]] ) reveal_type( T.ob # R: traitlets.traitlets.Bool[Union[builtins.bool, None], Union[builtins.bool, builtins.int, None]] ) # we would expect this to be Optional[Union[bool, int]], but... t.b = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "Union[bool, int]") [assignment] t.b = None # E: Incompatible types in assignment (expression has type "None", variable has type "Union[bool, int]") [assignment] @pytest.mark.mypy_testing def mypy_int_typing() -> None: class T(HasTraits): i: Int[int, int] = Int(42).tag(sync=True) oi: Int[int | None, int | None] = Int(42, allow_none=True).tag(sync=True) t = T() reveal_type(Int(True)) # R: traitlets.traitlets.Int[builtins.int, builtins.int] reveal_type(Int(True).tag(sync=True)) # R: traitlets.traitlets.Int[builtins.int, builtins.int] reveal_type( Int( # R: traitlets.traitlets.Int[Union[builtins.int, None], Union[builtins.int, None]] None, allow_none=True ) ) reveal_type( Int( # R: traitlets.traitlets.Int[Union[builtins.int, None], Union[builtins.int, None]] None, allow_none=True ).tag(sync=True) ) reveal_type(T.i) # R: traitlets.traitlets.Int[builtins.int, builtins.int] reveal_type(t.i) # R: builtins.int reveal_type(t.oi) # R: Union[builtins.int, None] reveal_type(T.i) # R: traitlets.traitlets.Int[builtins.int, builtins.int] reveal_type( T.oi # R: traitlets.traitlets.Int[Union[builtins.int, None], Union[builtins.int, None]] ) t.i = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment] t.i = None # E: Incompatible types in assignment (expression has type "None", variable has type "int") [assignment] t.i = 1.2 # E: Incompatible types in assignment (expression has type "float", variable has type "int") [assignment] @pytest.mark.mypy_testing def mypy_cint_typing() -> None: class T(HasTraits): i = CInt(42).tag(sync=True) oi = CInt(42, allow_none=True).tag(sync=True) t = T() reveal_type(CInt(42)) # R: traitlets.traitlets.CInt[builtins.int, Any] reveal_type(CInt(42).tag(sync=True)) # R: traitlets.traitlets.CInt[builtins.int, Any] reveal_type( CInt(None, allow_none=True) # R: traitlets.traitlets.CInt[Union[builtins.int, None], Any] ) reveal_type( CInt( # R: traitlets.traitlets.CInt[Union[builtins.int, None], Any] None, allow_none=True ).tag(sync=True) ) reveal_type(T.i) # R: traitlets.traitlets.CInt[builtins.int, Any] reveal_type(t.i) # R: builtins.int reveal_type(t.oi) # R: Union[builtins.int, None] reveal_type(T.i) # R: traitlets.traitlets.CInt[builtins.int, Any] reveal_type(T.oi) # R: traitlets.traitlets.CInt[Union[builtins.int, None], Any] @pytest.mark.mypy_testing def mypy_tcp_typing() -> None: class T(HasTraits): tcp = TCPAddress() otcp = TCPAddress(None, allow_none=True) t = T() reveal_type(t.tcp) # R: Tuple[builtins.str, builtins.int] reveal_type( T.tcp # R: traitlets.traitlets.TCPAddress[Tuple[builtins.str, builtins.int], Tuple[builtins.str, builtins.int]] ) reveal_type( T.tcp.tag( # R:traitlets.traitlets.TCPAddress[Tuple[builtins.str, builtins.int], Tuple[builtins.str, builtins.int]] sync=True ) ) reveal_type(t.otcp) # R: Union[Tuple[builtins.str, builtins.int], None] reveal_type( T.otcp # R: traitlets.traitlets.TCPAddress[Union[Tuple[builtins.str, builtins.int], None], Union[Tuple[builtins.str, builtins.int], None]] ) reveal_type( T.otcp.tag( # R: traitlets.traitlets.TCPAddress[Union[Tuple[builtins.str, builtins.int], None], Union[Tuple[builtins.str, builtins.int], None]] sync=True ) ) t.tcp = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "Tuple[str, int]") [assignment] t.otcp = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "Optional[Tuple[str, int]]") [assignment] t.tcp = None # E: Incompatible types in assignment (expression has type "None", variable has type "Tuple[str, int]") [assignment] @pytest.mark.mypy_testing def mypy_instance_typing() -> None: class T(HasTraits): inst = Instance(Foo) oinst = Instance(Foo, allow_none=True) oinst_string = Instance("Foo", allow_none=True) t = T() reveal_type(t.inst) # R: tests.test_typing.Foo reveal_type(T.inst) # R: traitlets.traitlets.Instance[tests.test_typing.Foo] reveal_type(T.inst.tag(sync=True)) # R: traitlets.traitlets.Instance[tests.test_typing.Foo] reveal_type(t.oinst) # R: Union[tests.test_typing.Foo, None] reveal_type(t.oinst_string) # R: Union[Any, None] reveal_type(T.oinst) # R: traitlets.traitlets.Instance[Union[tests.test_typing.Foo, None]] reveal_type( T.oinst.tag( # R: traitlets.traitlets.Instance[Union[tests.test_typing.Foo, None]] sync=True ) ) t.inst = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "Foo") [assignment] t.oinst = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "Optional[Foo]") [assignment] t.inst = None # E: Incompatible types in assignment (expression has type "None", variable has type "Foo") [assignment] ipython-traitlets-a3e321a/tests/utils/000077500000000000000000000000001461045054400201235ustar00rootroot00000000000000ipython-traitlets-a3e321a/tests/utils/__init__.py000066400000000000000000000000001461045054400222220ustar00rootroot00000000000000ipython-traitlets-a3e321a/tests/utils/test_bunch.py000066400000000000000000000005041461045054400226320ustar00rootroot00000000000000from __future__ import annotations from traitlets.utils.bunch import Bunch def test_bunch(): b = Bunch(x=5, y=10) assert "y" in b assert "x" in b assert b.x == 5 b["a"] = "hi" assert b.a == "hi" def test_bunch_dir(): b = Bunch(x=5, y=10) assert "x" in dir(b) assert "keys" in dir(b) ipython-traitlets-a3e321a/tests/utils/test_decorators.py000066400000000000000000000112731461045054400237050ustar00rootroot00000000000000from __future__ import annotations from inspect import Parameter, signature from unittest import TestCase from traitlets import HasTraits, Int, Unicode from traitlets.utils.decorators import signature_has_traits class TestExpandSignature(TestCase): def test_no_init(self): @signature_has_traits class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode("Hello") parameters = signature(Foo).parameters parameter_names = list(parameters) self.assertIs(parameters["args"].kind, Parameter.VAR_POSITIONAL) self.assertEqual("args", parameter_names[0]) self.assertIs(parameters["number1"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["number2"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["value"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["kwargs"].kind, Parameter.VAR_KEYWORD) self.assertEqual("kwargs", parameter_names[-1]) f = Foo(number1=32, value="World") self.assertEqual(f.number1, 32) self.assertEqual(f.number2, 0) self.assertEqual(f.value, "World") def test_partial_init(self): @signature_has_traits class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode("Hello") def __init__(self, arg1, **kwargs): self.arg1 = arg1 super().__init__(**kwargs) parameters = signature(Foo).parameters parameter_names = list(parameters) self.assertIs(parameters["arg1"].kind, Parameter.POSITIONAL_OR_KEYWORD) self.assertEqual("arg1", parameter_names[0]) self.assertIs(parameters["number1"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["number2"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["value"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["kwargs"].kind, Parameter.VAR_KEYWORD) self.assertEqual("kwargs", parameter_names[-1]) f = Foo(1, number1=32, value="World") self.assertEqual(f.arg1, 1) self.assertEqual(f.number1, 32) self.assertEqual(f.number2, 0) self.assertEqual(f.value, "World") def test_duplicate_init(self): @signature_has_traits class Foo(HasTraits): number1 = Int() number2 = Int() def __init__(self, number1, **kwargs): self.test = number1 super().__init__(number1=number1, **kwargs) parameters = signature(Foo).parameters parameter_names = list(parameters) self.assertListEqual(parameter_names, ["number1", "number2", "kwargs"]) f = Foo(number1=32, number2=36) self.assertEqual(f.test, 32) self.assertEqual(f.number1, 32) self.assertEqual(f.number2, 36) def test_full_init(self): @signature_has_traits class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode("Hello") def __init__(self, arg1, arg2=None, *pos_args, **kw_args): self.arg1 = arg1 self.arg2 = arg2 self.pos_args = pos_args self.kw_args = kw_args super().__init__(*pos_args, **kw_args) parameters = signature(Foo).parameters parameter_names = list(parameters) self.assertIs(parameters["arg1"].kind, Parameter.POSITIONAL_OR_KEYWORD) self.assertEqual("arg1", parameter_names[0]) self.assertIs(parameters["arg2"].kind, Parameter.POSITIONAL_OR_KEYWORD) self.assertEqual("arg2", parameter_names[1]) self.assertIs(parameters["pos_args"].kind, Parameter.VAR_POSITIONAL) self.assertEqual("pos_args", parameter_names[2]) self.assertIs(parameters["number1"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["number2"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["value"].kind, Parameter.KEYWORD_ONLY) self.assertIs(parameters["kw_args"].kind, Parameter.VAR_KEYWORD) self.assertEqual("kw_args", parameter_names[-1]) f = Foo(1, 3, 45, "hey", number1=32, value="World") self.assertEqual(f.arg1, 1) self.assertEqual(f.arg2, 3) self.assertTupleEqual(f.pos_args, (45, "hey")) self.assertEqual(f.number1, 32) self.assertEqual(f.number2, 0) self.assertEqual(f.value, "World") def test_no_kwargs(self): with self.assertRaises(RuntimeError): @signature_has_traits class Foo(HasTraits): number1 = Int() number2 = Int() def __init__(self, arg1, arg2=None): pass ipython-traitlets-a3e321a/tests/utils/test_importstring.py000066400000000000000000000015701461045054400243000ustar00rootroot00000000000000# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. # # Adapted from enthought.traits, Copyright (c) Enthought, Inc., # also under the terms of the Modified BSD License. """Tests for traitlets.utils.importstring.""" from __future__ import annotations import os from unittest import TestCase from traitlets.utils.importstring import import_item class TestImportItem(TestCase): def test_import_unicode(self): self.assertIs(os, import_item("os")) self.assertIs(os.path, import_item("os.path")) self.assertIs(os.path.join, import_item("os.path.join")) def test_bad_input(self): class NotAString: pass msg = "import_item accepts strings, not '%s'." % NotAString with self.assertRaisesRegex(TypeError, msg): import_item(NotAString()) # type:ignore[arg-type] ipython-traitlets-a3e321a/traitlets/000077500000000000000000000000001461045054400176345ustar00rootroot00000000000000ipython-traitlets-a3e321a/traitlets/__init__.py000066400000000000000000000016521461045054400217510ustar00rootroot00000000000000"""Traitlets Python configuration system""" from __future__ import annotations import typing as _t from . import traitlets from ._version import __version__, version_info from .traitlets import * from .utils.bunch import Bunch from .utils.decorators import signature_has_traits from .utils.importstring import import_item from .utils.warnings import warn __all__ = [ "traitlets", "__version__", "version_info", "Bunch", "signature_has_traits", "import_item", "Sentinel", ] class Sentinel(traitlets.Sentinel): # type:ignore[name-defined, misc] def __init__(self, *args: _t.Any, **kwargs: _t.Any) -> None: super().__init__(*args, **kwargs) warn( """ Sentinel is not a public part of the traitlets API. It was published by mistake, and may be removed in the future. """, DeprecationWarning, stacklevel=2, ) ipython-traitlets-a3e321a/traitlets/_version.py000066400000000000000000000010551461045054400220330ustar00rootroot00000000000000""" handle the current version info of traitlets. """ from __future__ import annotations import re from typing import List # Version string must appear intact for hatch versioning __version__ = "5.14.3" # Build up version_info tuple for backwards compatibility pattern = r"(?P\d+).(?P\d+).(?P\d+)(?P.*)" match = re.match(pattern, __version__) assert match is not None parts: List[object] = [int(match[part]) for part in ["major", "minor", "patch"]] if match["rest"]: parts.append(match["rest"]) version_info = tuple(parts) ipython-traitlets-a3e321a/traitlets/config/000077500000000000000000000000001461045054400211015ustar00rootroot00000000000000ipython-traitlets-a3e321a/traitlets/config/__init__.py000066400000000000000000000007351461045054400232170ustar00rootroot00000000000000# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations from .application import * from .configurable import * from .loader import Config __all__ = [ # noqa: F405 "Config", "Application", "ApplicationError", "LevelFormatter", "configurable", "Configurable", "ConfigurableError", "MultipleInstanceError", "LoggingConfigurable", "SingletonConfigurable", ] ipython-traitlets-a3e321a/traitlets/config/application.py000066400000000000000000001234111461045054400237600ustar00rootroot00000000000000"""A base class for a configurable application.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import functools import json import logging import os import pprint import re import sys import typing as t from collections import OrderedDict, defaultdict from contextlib import suppress from copy import deepcopy from logging.config import dictConfig from textwrap import dedent from traitlets.config.configurable import Configurable, SingletonConfigurable from traitlets.config.loader import ( ArgumentError, Config, ConfigFileNotFound, DeferredConfigString, JSONFileConfigLoader, KVArgParseConfigLoader, PyFileConfigLoader, ) from traitlets.traitlets import ( Bool, Dict, Enum, Instance, List, TraitError, Unicode, default, observe, observe_compat, ) from traitlets.utils.bunch import Bunch from traitlets.utils.nested_update import nested_update from traitlets.utils.text import indent, wrap_paragraphs from ..utils import cast_unicode from ..utils.importstring import import_item # ----------------------------------------------------------------------------- # Descriptions for the various sections # ----------------------------------------------------------------------------- # merge flags&aliases into options option_description = """ The options below are convenience aliases to configurable class-options, as listed in the "Equivalent to" description-line of the aliases. To see all configurable class-options for some , use: --help-all """.strip() # trim newlines of front and back keyvalue_description = """ The command-line option below sets the respective configurable class-parameter: --Class.parameter=value This line is evaluated in Python, so simple expressions are allowed. For instance, to set `C.a=[0,1,2]`, you may type this: --C.a='range(3)' """.strip() # trim newlines of front and back # sys.argv can be missing, for example when python is embedded. See the docs # for details: http://docs.python.org/2/c-api/intro.html#embedding-python if not hasattr(sys, "argv"): sys.argv = [""] subcommand_description = """ Subcommands are launched as `{app} cmd [args]`. For information on using subcommand 'cmd', do: `{app} cmd -h`. """ # get running program name # ----------------------------------------------------------------------------- # Application class # ----------------------------------------------------------------------------- _envvar = os.environ.get("TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR", "") if _envvar.lower() in {"1", "true"}: TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = True elif _envvar.lower() in {"0", "false", ""}: TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = False else: raise ValueError( "Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}." % _envvar ) IS_PYTHONW = sys.executable and sys.executable.endswith("pythonw.exe") T = t.TypeVar("T", bound=t.Callable[..., t.Any]) AnyLogger = t.Union[logging.Logger, "logging.LoggerAdapter[t.Any]"] StrDict = t.Dict[str, t.Any] ArgvType = t.Optional[t.List[str]] ClassesType = t.List[t.Type[Configurable]] def catch_config_error(method: T) -> T: """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. """ @functools.wraps(method) def inner(app: Application, *args: t.Any, **kwargs: t.Any) -> t.Any: try: return method(app, *args, **kwargs) except (TraitError, ArgumentError) as e: app.log.fatal("Bad config encountered during initialization: %s", e) app.log.debug("Config at the time: %s", app.config) app.exit(1) return t.cast(T, inner) class ApplicationError(Exception): pass class LevelFormatter(logging.Formatter): """Formatter with additional `highlevel` record This field is empty if log level is less than highlevel_limit, otherwise it is formatted with self.highlevel_format. Useful for adding 'WARNING' to warning messages, without adding 'INFO' to info, etc. """ highlevel_limit = logging.WARN highlevel_format = " %(levelname)s |" def format(self, record: logging.LogRecord) -> str: if record.levelno >= self.highlevel_limit: record.highlevel = self.highlevel_format % record.__dict__ else: record.highlevel = "" return super().format(record) class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name: str | Unicode[str, str | bytes] = Unicode("application") # The description of the application that is printed at the beginning # of the help. description: str | Unicode[str, str | bytes] = Unicode("This is an application.") # default section descriptions option_description: str | Unicode[str, str | bytes] = Unicode(option_description) keyvalue_description: str | Unicode[str, str | bytes] = Unicode(keyvalue_description) subcommand_description: str | Unicode[str, str | bytes] = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples: str | Unicode[str, str | bytes] = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes: ClassesType = [] def _classes_inc_parents( self, classes: ClassesType | None = None ) -> t.Generator[type[Configurable], None, None]: """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent # The version string of this application. version: str | Unicode[str, str | bytes] = Unicode("0.0") # the argv used to initialize the application argv: list[str] | List[str] = List() # Whether failing to load config files should prevent startup raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR) # The log level for the application log_level = Enum( (0, 10, 20, 30, 40, 50, "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"), default_value=logging.WARN, help="Set the log level by value or name.", ).tag(config=True) _log_formatter_cls = LevelFormatter log_datefmt = Unicode( "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s" ).tag(config=True) log_format = Unicode( "[%(name)s]%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) def get_default_logging_config(self) -> StrDict: """Return the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging. """ config: StrDict = { "version": 1, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "console", "level": logging.getLevelName(self.log_level), # type:ignore[arg-type] "stream": "ext://sys.stderr", }, }, "formatters": { "console": { "class": ( f"{self._log_formatter_cls.__module__}" f".{self._log_formatter_cls.__name__}" ), "format": self.log_format, "datefmt": self.log_datefmt, }, }, "loggers": { self.__class__.__name__: { "level": "DEBUG", "handlers": ["console"], } }, "disable_existing_loggers": False, } if IS_PYTHONW: # disable logging # (this should really go to a file, but file-logging is only # hooked up in parallel applications) del config["handlers"] del config["loggers"] return config @observe("log_datefmt", "log_format", "log_level", "logging_config") def _observe_logging_change(self, change: Bunch) -> None: # convert log level strings to ints log_level = self.log_level if isinstance(log_level, str): self.log_level = t.cast(int, getattr(logging, log_level)) self._configure_logging() @observe("log", type="default") def _observe_logging_default(self, change: Bunch) -> None: self._configure_logging() def _configure_logging(self) -> None: config = self.get_default_logging_config() nested_update(config, self.logging_config or {}) dictConfig(config) # make a note that we have configured logging self._logging_configured = True @default("log") def _log_default(self) -> AnyLogger: """Start logging for this application.""" log = logging.getLogger(self.__class__.__name__) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log is not None: if _log.handlers: return log if not _log.propagate: break _log = _log.parent # type:ignore[assignment] return log logging_config = Dict( help=""" Configure additional log handlers. The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings. This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers. If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema This dictionary is merged with the base logging configuration which defines the following: * A logging formatter intended for interactive use called ``console``. * A logging handler that writes to stderr called ``console`` which uses the formatter ``console``. * A logger with the name of this application set to ``DEBUG`` level. This example adds a new handler that writes to a file: .. code-block:: python c.Application.logging_config = { "handlers": { "file": { "class": "logging.FileHandler", "level": "DEBUG", "filename": "", } }, "loggers": { "": { "level": "DEBUG", # NOTE: if you don't list the default "console" # handler here then it will be disabled "handlers": ["console", "file"], }, }, } """, ).tag(config=True) #: the alias map for configurables #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`. #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text), # or just the "Class.trait" string, in which case the help text is inferred from the # corresponding trait aliases: StrDict = {"log-level": "Application.log_level"} # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags: StrDict = { "debug": ( { "Application": { "log_level": logging.DEBUG, }, }, "Set log-level to debug, for the most verbose logging.", ), "show-config": ( { "Application": { "show_config": True, }, }, "Show the application's configuration (human-readable format)", ), "show-config-json": ( { "Application": { "show_config_json": True, }, }, "Show the application's configuration (json format)", ), } # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands: dict[str, t.Any] | Dict[str, t.Any] = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance("traitlets.config.application.Application", allow_none=True) # extra command-line arguments that don't set config values extra_args = List(Unicode()) cli_config = Instance( Config, (), {}, help="""The subset of our configuration that came from the command-line We re-load this configuration after loading config files, to ensure that it maintains highest priority. """, ) _loaded_config_files: List[str] = List() show_config = Bool( help="Instead of starting the Application, dump configuration to stdout" ).tag(config=True) show_config_json = Bool( help="Instead of starting the Application, dump configuration to stdout (as JSON)" ).tag(config=True) @observe("show_config_json") def _show_config_json_changed(self, change: Bunch) -> None: self.show_config = change.new @observe("show_config") def _show_config_changed(self, change: Bunch) -> None: if change.new: self._save_start = self.start self.start = self.start_show_config # type:ignore[method-assign] def __init__(self, **kwargs: t.Any) -> None: SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls, *self.classes] else: self.classes.insert(0, self.__class__) @observe("config") @observe_compat def _config_changed(self, change: Bunch) -> None: super()._config_changed(change) self.log.debug("Config changed: %r", change.new) @catch_config_error def initialize(self, argv: ArgvType = None) -> None: """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self) -> None: """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: assert isinstance(self.subapp, Application) return self.subapp.start() def start_show_config(self) -> None: """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop("show_config", None) cls_config.pop("show_config_json", None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write("\n") return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(" " + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs: StrDict = dict(indent=4, compact=True) # noqa: C408 for traitname in sorted(class_config): value = class_config[traitname] print(f" .{traitname} = {pprint.pformat(value, **pformat_kwargs)}") def print_alias_help(self) -> None: """Print the alias parts of the help.""" print("\n".join(self.emit_alias_help())) def emit_alias_help(self) -> t.Generator[str, None, None]: """Yield the lines for alias part of the help.""" if not self.aliases: return classdict: dict[str, type[Configurable]] = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = t.cast(t.Type[Configurable], c) fhelp: str | None for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split(".")[-2:] longname = classname + "." + traitname cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp_lines = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): # type:ignore[unreachable] alias = (alias,) # type:ignore[assignment] alias = sorted(alias, key=len) # type:ignore[assignment] alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias) # reformat first line fhelp_lines[0] = fhelp_lines[0].replace("--" + longname, alias) yield from fhelp_lines yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error("Failed collecting help-message for alias %r, due to: %s", alias, ex) raise def print_flag_help(self) -> None: """Print the flag part of the help.""" print("\n".join(self.emit_flag_help())) def emit_flag_help(self) -> t.Generator[str, None, None]: """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): # type:ignore[unreachable] flags = (flags,) # type:ignore[assignment] flags = sorted(flags, key=len) # type:ignore[assignment] flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = " ".join( f"--{clname}.{prop}={val}" for clname, props_dict in cfg.items() for prop, val in props_dict.items() ) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error("Failed collecting help-message for flag %r, due to: %s", flags, ex) raise def print_options(self) -> None: """Print the options part of the help.""" print("\n".join(self.emit_options_help())) def emit_options_help(self) -> t.Generator[str, None, None]: """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = "Options" yield header yield "=" * len(header) for p in wrap_paragraphs(self.option_description): yield p yield "" yield from self.emit_flag_help() yield from self.emit_alias_help() yield "" def print_subcommands(self) -> None: """Print the subcommand part of the help.""" print("\n".join(self.emit_subcommands_help())) def emit_subcommands_help(self) -> t.Generator[str, None, None]: """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield "=" * len(header) for p in wrap_paragraphs(self.subcommand_description.format(app=self.name)): yield p yield "" for subc, (_, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield "" def emit_help_epilogue(self, classes: bool) -> t.Generator[str, None, None]: """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield "" def print_help(self, classes: bool = False) -> None: """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print("\n".join(self.emit_help(classes=classes))) def emit_help(self, classes: bool = False) -> t.Generator[str, None, None]: """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ yield from self.emit_description() yield from self.emit_subcommands_help() yield from self.emit_options_help() if classes: help_classes = self._classes_with_config_traits() if help_classes is not None: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield "" for cls in help_classes: yield cls.class_get_help() yield "" yield from self.emit_examples() yield from self.emit_help_epilogue(classes) def document_config_options(self) -> str: """Generate rST format documentation for the config options this application Returns a multiline string. """ return "\n".join(c.class_config_rst_doc() for c in self._classes_inc_parents()) def print_description(self) -> None: """Print the application description.""" print("\n".join(self.emit_description())) def emit_description(self) -> t.Generator[str, None, None]: """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__ or ""): yield p yield "" def print_examples(self) -> None: """Print usage and examples (see `emit_examples()`).""" print("\n".join(self.emit_examples())) def emit_examples(self) -> t.Generator[str, None, None]: """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield "" yield indent(dedent(self.examples.strip())) yield "" def print_version(self) -> None: """Print the version string.""" print(self.version) @catch_config_error def initialize_subcommand(self, subc: str, argv: ArgvType = None) -> None: """Initialize a subcommand with argv.""" val = self.subcommands.get(subc) assert val is not None subapp, _ = val if isinstance(subapp, str): subapp = import_item(subapp) # Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430) if isinstance(subapp, type) and issubclass(subapp, Application): # Clear existing instances before... self.__class__.clear_instance() # instantiating subapp... self.subapp = subapp.instance(parent=self) elif callable(subapp): # or ask factory to create it... self.subapp = subapp(self) else: raise AssertionError("Invalid mappings for subcommand '%s'!" % subc) # ... and finally initialize subapp. self.subapp.initialize(argv) def flatten_flags(self) -> tuple[dict[str, t.Any], dict[str, t.Any]]: """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases: dict[str, str] = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split(".", 1) children = mro_tree[cls] # type:ignore[index] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] # type:ignore[assignment] if not isinstance(aliases, tuple): # type:ignore[unreachable] alias = (alias,) # type:ignore[assignment] for al in alias: aliases[al] = ".".join([cls, trait]) # type:ignore[list-item] # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag: dict[t.Any, t.Any] = {} for cls, subdict in flagdict.items(): children = mro_tree[cls] # type:ignore[index] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] # type:ignore[assignment] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): # type:ignore[unreachable] key = (key,) # type:ignore[assignment] for k in key: flags[k] = (newflag, help) return flags, aliases def _create_loader( self, argv: list[str] | None, aliases: StrDict, flags: StrDict, classes: ClassesType | None, ) -> KVArgParseConfigLoader: return KVArgParseConfigLoader( argv, aliases, flags, classes=classes, log=self.log, subcommands=self.subcommands ) @classmethod def _get_sys_argv(cls, check_argcomplete: bool = False) -> list[str]: """Get `sys.argv` or equivalent from `argcomplete` `argcomplete`'s strategy is to call the python script with no arguments, so ``len(sys.argv) == 1``, and run until the `ArgumentParser` is constructed and determine what completions are available. On the other hand, `traitlet`'s subcommand-handling strategy is to check ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically load the subcommand app and initialize it with ``sys.argv[1:]``. This helper method helps to take the current tokens for `argcomplete` and pass them through as `argv`. """ if check_argcomplete and "_ARGCOMPLETE" in os.environ: try: from traitlets.config.argcomplete_config import get_argcomplete_cwords cwords = get_argcomplete_cwords() assert cwords is not None return cwords except (ImportError, ModuleNotFoundError): pass return sys.argv @classmethod def _handle_argcomplete_for_subcommand(cls) -> None: """Helper for `argcomplete` to recognize `traitlets` subcommands `argcomplete` does not know that `traitlets` has already consumed subcommands, as it only "sees" the final `argparse.ArgumentParser` that is constructed. (Indeed `KVArgParseConfigLoader` does not get passed subcommands at all currently.) We explicitly manipulate the environment variables used internally by `argcomplete` to get it to skip over the subcommand tokens. """ if "_ARGCOMPLETE" not in os.environ: return try: from traitlets.config.argcomplete_config import increment_argcomplete_index increment_argcomplete_index() except (ImportError, ModuleNotFoundError): pass @catch_config_error def parse_command_line(self, argv: ArgvType = None) -> None: """Parse the command line arguments.""" assert not isinstance(argv, str) if argv is None: argv = self._get_sys_argv(check_argcomplete=bool(self.subcommands))[1:] self.argv = [cast_unicode(arg) for arg in argv] if argv and argv[0] == "help": # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ["-h"] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r"^\w(\-?\w)*$", subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter self._handle_argcomplete_for_subcommand() return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[: argv.index("--")] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ("-h", "--help-all", "--help")): self.print_help("--help-all" in interpreted_argv) self.exit(0) if "--version" in interpreted_argv or "-V" in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags, aliases = self.flatten_flags() classes = list(self._classes_with_config_traits()) loader = self._create_loader(argv, aliases, flags, classes=classes) try: self.cli_config = deepcopy(loader.load_config()) except SystemExit: # traitlets 5: no longer print help output on error # help output is huge, and comes after the error raise self.update_config(self.cli_config) # store unparsed args in extra_args self.extra_args = loader.extra_args @classmethod def _load_config_files( cls, basefilename: str, path: str | t.Sequence[str | None] | None, log: AnyLogger | None = None, raise_config_file_errors: bool = False, ) -> t.Generator[t.Any, None, None]: """Load config files (py,json) by filename and path. yield each config object in turn. """ if isinstance(path, str) or path is None: path = [path] for current in reversed(path): # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename + ".py", path=current, log=log) if log: log.debug("Looking for %s in %s", basefilename, current or os.getcwd()) jsonloader = cls.json_config_loader_class(basefilename + ".json", path=current, log=log) loaded: list[t.Any] = [] filenames: list[str] = [] for loader in [pyloader, jsonloader]: config = None try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if raise_config_file_errors: raise if log: log.error("Exception while loading config file %s", filename, exc_info=True) # noqa: G201 else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: for filename, earlier_config in zip(filenames, loaded): collisions = earlier_config.collisions(config) if collisions and log: log.warning( "Collisions detected in {0} and {1} config files." # noqa: G001 " {1} has higher priority: {2}".format( filename, loader.full_filename, json.dumps(collisions, indent=2), ) ) yield (config, loader.full_filename) loaded.append(config) filenames.append(loader.full_filename) @property def loaded_config_files(self) -> list[str]: """Currently loaded configuration files""" return self._loaded_config_files[:] @catch_config_error def load_config_file( self, filename: str, path: str | t.Sequence[str | None] | None = None ) -> None: """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) new_config = Config() for config, fname in self._load_config_files( filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors, ): new_config.merge(config) if ( fname not in self._loaded_config_files ): # only add to list of loaded files if not previously loaded self._loaded_config_files.append(fname) # add self.cli_config to preserve CLI config priority new_config.merge(self.cli_config) self.update_config(new_config) @catch_config_error def load_config_environ(self) -> None: """Load config files by environment.""" PREFIX = self.name.upper().replace("-", "_") new_config = Config() self.log.debug('Looping through config variables with prefix "%s"', PREFIX) for k, v in os.environ.items(): if k.startswith(PREFIX): self.log.debug('Seeing environ "%s"="%s"', k, v) # use __ instead of . as separator in env variable. # Warning, case sensitive ! _, *path, key = k.split("__") section = new_config for p in path: section = section[p] setattr(section, key, DeferredConfigString(v)) new_config.merge(self.cli_config) self.update_config(new_config) def _classes_with_config_traits( self, classes: ClassesType | None = None ) -> t.Generator[type[Configurable], None, None]: """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes) ) def is_any_parent_included(cls: t.Any) -> bool: return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) # Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items() ) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl def generate_config_file(self, classes: ClassesType | None = None) -> str: """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append("") lines.append("c = get_config() #" + "noqa") lines.append("") classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return "\n".join(lines) def close_handlers(self) -> None: if getattr(self, "_logging_configured", False): # don't attempt to close handlers unless they have been opened # (note accessing self.log.handlers will create handlers if they # have not yet been initialised) for handler in self.log.handlers: with suppress(Exception): handler.close() self._logging_configured = False def exit(self, exit_status: int | str | None = 0) -> None: self.log.debug("Exiting application: %s", self.name) self.close_handlers() sys.exit(exit_status) def __del__(self) -> None: self.close_handlers() @classmethod def launch_instance(cls, argv: ArgvType = None, **kwargs: t.Any) -> None: """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start() # ----------------------------------------------------------------------------- # utility functions, for convenience # ----------------------------------------------------------------------------- default_aliases = Application.aliases default_flags = Application.flags def boolean_flag(name: str, configurable: str, set_help: str = "", unset_help: str = "") -> StrDict: """Helper for building basic --trait, --no-trait flags. Parameters ---------- name : str The name of the flag. configurable : str The 'Class.trait' string of the trait to be set/unset with the flag set_help : unicode help string for --name flag unset_help : unicode help string for --no-name flag Returns ------- cfg : dict A dict with two keys: 'name', and 'no-name', for setting and unsetting the trait, respectively. """ # default helpstrings set_help = set_help or "set %s=True" % configurable unset_help = unset_help or "set %s=False" % configurable cls, trait = configurable.split(".") setter = {cls: {trait: True}} unsetter = {cls: {trait: False}} return {name: (setter, set_help), "no-" + name: (unsetter, unset_help)} def get_config() -> Config: """Get the config object for the global Application instance, if there is one otherwise return an empty config object """ if Application.initialized(): return Application.instance().config else: return Config() if __name__ == "__main__": Application.launch_instance() ipython-traitlets-a3e321a/traitlets/config/argcomplete_config.py000066400000000000000000000241411461045054400253040ustar00rootroot00000000000000"""Helper utilities for integrating argcomplete with traitlets""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import argparse import os import typing as t try: import argcomplete from argcomplete import CompletionFinder # type:ignore[attr-defined] except ImportError: # This module and its utility methods are written to not crash even # if argcomplete is not installed. class StubModule: def __getattr__(self, attr: str) -> t.Any: if not attr.startswith("__"): raise ModuleNotFoundError("No module named 'argcomplete'") raise AttributeError(f"argcomplete stub module has no attribute '{attr}'") argcomplete = StubModule() # type:ignore[assignment] CompletionFinder = object # type:ignore[assignment, misc] def get_argcomplete_cwords() -> t.Optional[t.List[str]]: """Get current words prior to completion point This is normally done in the `argcomplete.CompletionFinder` constructor, but is exposed here to allow `traitlets` to follow dynamic code-paths such as determining whether to evaluate a subcommand. """ if "_ARGCOMPLETE" not in os.environ: return None comp_line = os.environ["COMP_LINE"] comp_point = int(os.environ["COMP_POINT"]) # argcomplete.debug("splitting COMP_LINE for:", comp_line, comp_point) comp_words: t.List[str] try: ( cword_prequote, cword_prefix, cword_suffix, comp_words, last_wordbreak_pos, ) = argcomplete.split_line(comp_line, comp_point) # type:ignore[attr-defined,no-untyped-call] except ModuleNotFoundError: return None # _ARGCOMPLETE is set by the shell script to tell us where comp_words # should start, based on what we're completing. # 1: